From 9d601ea570eab7319bf0de2fb1f77c6f89ef315a Mon Sep 17 00:00:00 2001 From: RobinFiredrake Date: Mon, 9 Nov 2026 08:06:56 -0600 Subject: [PATCH] Split TableSettingsDialog and ResultTray into smaller files TableSettingsDialog keeps the common fields; its static editing rules move to TableSettingsRules and the kind-specific fields to SettingsKindFields. ResultTray keeps the layout and render loop; chip builders move to TrayChips, captions and effect lines to TrayText, and the Earlier tab to EarlierRolls. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- tests/test_logic_ui.gd | 2 +- tests/test_options.gd | 8 +- tests/test_plain_display.gd | 8 +- tests/test_router.gd | 2 +- tests/test_shell.gd | 10 +- ui/earlier_rolls.gd | 65 ++++ ui/earlier_rolls.gd.uid | 1 + ui/result_tray.gd | 364 +------------------ ui/settings_kind_fields.gd | 327 +++++++++++++++++ ui/settings_kind_fields.gd.uid | 1 + ui/table_settings_dialog.gd | 641 ++------------------------------- ui/table_settings_rules.gd | 307 ++++++++++++++++ ui/table_settings_rules.gd.uid | 1 + ui/tray_chips.gd | 166 +++++++++ ui/tray_chips.gd.uid | 1 + ui/tray_text.gd | 134 +++++++ ui/tray_text.gd.uid | 1 + 17 files changed, 1057 insertions(+), 982 deletions(-) create mode 100644 ui/earlier_rolls.gd create mode 100644 ui/earlier_rolls.gd.uid create mode 100644 ui/settings_kind_fields.gd create mode 100644 ui/settings_kind_fields.gd.uid create mode 100644 ui/table_settings_rules.gd create mode 100644 ui/table_settings_rules.gd.uid create mode 100644 ui/tray_chips.gd create mode 100644 ui/tray_chips.gd.uid create mode 100644 ui/tray_text.gd create mode 100644 ui/tray_text.gd.uid diff --git a/tests/test_logic_ui.gd b/tests/test_logic_ui.gd index 6838b5b..12b8c73 100644 --- a/tests/test_logic_ui.gd +++ b/tests/test_logic_ui.gd @@ -426,7 +426,7 @@ func _test_long_chain() -> void: _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") - var line := ResultTray.earlier_line({"root_name": "x", "steps": all}) + var line := EarlierRolls.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 diff --git a/tests/test_options.gd b/tests/test_options.gd index 37a3ab3..ff157ca 100644 --- a/tests/test_options.gd +++ b/tests/test_options.gd @@ -515,7 +515,7 @@ func _test_settings() -> void: var bad := s.duplicate(true) bad["options_from"] = "skill" bad["show_if"] = {"keep": "@x >"} - var probs := TableSettingsDialog.kind_problems(t, bad) + var probs := TableSettingsRules.kind_problems(t, bad) _check(probs.size() == 2, "a bad pattern and a bad show_if are refused (%s)" % [probs]) bad = s.duplicate(true) bad["options_from"] = "" @@ -571,10 +571,10 @@ func _test_card() -> void: main.add_child(d) await process_frame _check(_has_ci(d, "Options from (@prefix_* or a @list)") and _has_ci(d, "Show only if") and _has_ci(d, "From variables (+ fixed extras)"), "the settings dialog has the options fields") - _check(d._options_box.visible and d._opt_from.text == "@skill_*", "From variables is selected with its pattern") - d._opt_where.text = "option_value >=" + _check(d._kind._options_box.visible and d._kind._opt_from.text == "@skill_*", "From variables is selected with its pattern") + d._kind._opt_where.text = "option_value >=" d._refresh() - _check(d._kind_problem.visible, "a bad filter is flagged live") + _check(d._kind.problem.visible, "a bad filter is flagged live") d.queue_free() main.set_mode(Main.Mode.PLAY) main.queue_free() diff --git a/tests/test_plain_display.gd b/tests/test_plain_display.gd index ba23036..c380664 100644 --- a/tests/test_plain_display.gd +++ b/tests/test_plain_display.gd @@ -221,8 +221,8 @@ func _test_rules_view_helpers() -> void: _eq(RulesView.dice("2d6 + dm(@str)", b, true), "2D + Strength modifier", "expression dice") _eq(Describe.condition("@luck != \"\"", b), "Luck is not empty", "empty text reads as empty") _eq(RulesView.check_outlets(b.get_table("gate")), ["8+", "≤7"] as Array[String], "check outlets") - _eq(ResultTray.effect_fact_line({"type": "effect", "var": "@luck", "op": "-=", "before": 2, "after": 1}, b), "Luck 2 → 1", "tray effect line") - _eq(ResultTray.effect_fact_line({"type": "effect", "var": "@skill_*", "op": "reset", "count": 3}, b), "Cleared all Skills (3)", "tray prefix reset line") + _eq(TrayText.effect_fact_line({"type": "effect", "var": "@luck", "op": "-=", "before": 2, "after": 1}, b), "Luck 2 → 1", "tray effect line") + _eq(TrayText.effect_fact_line({"type": "effect", "var": "@skill_*", "op": "reset", "count": 3}, b), "Cleared all Skills (3)", "tray prefix reset line") # ---------------------------------------------------------------- cards @@ -360,7 +360,7 @@ func _test_roll_why() -> void: _check(not steps.is_empty() and str(steps[0].get("kind", "")) == RollTable.KIND_CHECK, "the check rolled") if steps.is_empty(): return - var cap := ResultTray.caption_for(steps[0], main.data, true) + var cap := TrayText.caption_for(steps[0], main.data, true) _check(cap.begins_with("Force the gate · rolled ") and cap.contains("→"), "the check's caption reads rolled N, ±M → total: " + cap) _check(main.tray.why_buttons.has(0), "a real check step has a Why button") var lines := WhyPopover.why_lines(steps, 0, main.data, true) @@ -371,7 +371,7 @@ func _test_roll_why() -> void: _check(not main.details().step_for("gate", lit).is_empty(), "a lit row finds its step for the hover reasons") for s: Dictionary in steps: if str(s.get("table_id", "")) == "loot": - _check(ResultTray.caption_for(s, main.data, true).contains("Tier "), "an inputs step's caption names its input") + _check(TrayText.caption_for(s, main.data, true).contains("Tier "), "an inputs step's caption names its input") func _test_build_rows() -> void: diff --git a/tests/test_router.gd b/tests/test_router.gd index 3c2eb29..53fe3af 100644 --- a/tests/test_router.gd +++ b/tests/test_router.gd @@ -408,7 +408,7 @@ func _test_ui_helpers() -> void: _check(not bad["ok"] and str(bad["error"]).begins_with("Case 1"), "settings refuse a bad case: %s" % str(bad)) var ok := TableSettingsDialog.apply_settings(r, {"name": "R", "cases": ["@a = 1", ""], "card_mode": true, "ranged": true}) _check(ok["ok"] and r.entries[0].when == "@a = 1" and not r.card_mode and not r.is_ranged(), "settings set case conditions; no card mode or ranges: %s" % str(ok)) - _check(TableSettingsDialog.router_hint(["", "@a"]) != "" and TableSettingsDialog.router_hint(["@a", ""]) == "", "router order hint") + _check(TableSettingsRules.router_hint(["", "@a"]) != "" and TableSettingsRules.router_hint(["@a", ""]) == "", "router order hint") _eq(TablePreview.kind_line(r), "Router · if / else if / otherwise", "preview kind line") diff --git a/tests/test_shell.gd b/tests/test_shell.gd index b9fa667..3301e26 100644 --- a/tests/test_shell.gd +++ b/tests/test_shell.gd @@ -61,13 +61,13 @@ func _test_ranges() -> void: t.entries[0].weight = 1 t.entries[1].weight = 3 t.dice = "1d100" - TableSettingsDialog.assign_ranges(t) + TableSettingsRules.assign_ranges(t) _check(t.entries[0].range_lo == 1 and t.entries[0].range_hi == 25, "weight 1 of 4 gets 1-25") _check(t.entries[1].range_lo == 26 and t.entries[1].range_hi == 100, "weight 3 of 4 gets 26-100") # More entries than values: everything stays valid and in span. var many := _plain_table(8) many.dice = "1d6" - TableSettingsDialog.assign_ranges(many) + TableSettingsRules.assign_ranges(many) var lit := 0 for e in many.entries: if e.has_range: @@ -78,15 +78,15 @@ func _test_ranges() -> void: var z := _plain_table(3) z.entries[1].weight = 0 z.entries[0].pipes = ["a", "b"] as Array[String] - TableSettingsDialog.assign_ranges(z) + TableSettingsRules.assign_ranges(z) _check(not z.entries[1].has_range and z.entries[0].pipes.size() == 1, "weight 0 skipped, extra pipe dropped") _check(z.entries[2].range_hi == 100, "last live entry reaches the top") func _test_wrap() -> void: - var r := TableSettingsDialog.wrap_text("hello world", Vector2i(0, 5), "[b]", "[/b]") + var r := TableSettingsRules.wrap_text("hello world", Vector2i(0, 5), "[b]", "[/b]") _check(r["text"] == "[b]hello[/b] world" and r["caret"] == 12, "bold wraps selection") - var r2 := TableSettingsDialog.wrap_text("ab", Vector2i(1, 1), "[i]", "[/i]") + var r2 := TableSettingsRules.wrap_text("ab", Vector2i(1, 1), "[i]", "[/i]") _check(r2["text"] == "a[i][/i]b" and r2["caret"] == 4, "empty selection inserts a pair") diff --git a/ui/earlier_rolls.gd b/ui/earlier_rolls.gd new file mode 100644 index 0000000..9e2214d --- /dev/null +++ b/ui/earlier_rolls.gd @@ -0,0 +1,65 @@ +class_name EarlierRolls +extends VBoxContainer +## ResultTray's Earlier tab: one row per past roll, newest first, as +## "12:04 Root: a → b → c". + +var main: Main +var _rows: VBoxContainer +var _empty: Label + + +func setup(p_main: Main) -> void: + main = p_main + add_theme_constant_override("separation", 6) + _rows = VBoxContainer.new() + _rows.add_theme_constant_override("separation", 6) + add_child(_rows) + _empty = Style.make_label("Older rolls show here.", Style.body(), 15, Style.ON_FELT_MUTED) + add_child(_empty) + + +func render() -> void: + for c in _rows.get_children(): + _rows.remove_child(c) + c.queue_free() + _empty.visible = main.history.is_empty() + for rec in main.history: + var row := HBoxContainer.new() + row.add_theme_constant_override("separation", 8) + var time := Style.make_label(clock(rec["time"]), Style.body(), 14, Style.ON_FELT_MUTED) + time.custom_minimum_size = Vector2(44, 0) + time.size_flags_vertical = SIZE_SHRINK_BEGIN + row.add_child(time) + var line := RichText.label(earlier_line(rec), 14, Style.ON_FELT, false) + line.size_flags_horizontal = SIZE_EXPAND_FILL + RichText.hook_hover(line, main) + row.add_child(line) + _rows.add_child(row) + + +## One Earlier row: "Root: a → b → c", with only the last few steps of a long +## chain. +static func earlier_line(rec: Dictionary) -> String: + var texts := PackedStringArray() + var all: Array = rec.get("steps", []) + var shown := 0 + var skipped := 0 + for k in range(all.size() - 1, -1, -1): + var s: Dictionary = all[k] + if s.get("inline", false): + continue + if shown >= 6: + skipped += 1 + continue + texts.insert(0, RichText.decorate(TrayText.one_line(str(s["text"])), true)) + shown += 1 + var lead := "[color=#%s]%s:[/color] " % [Style.ON_FELT_MUTED.to_html(false), RichText.plain(Formatter.strip_tags(str(rec.get("root_name", ""))))] + if skipped > 0: + lead += "[color=#%s]… %d earlier →[/color] " % [Style.ON_FELT_MUTED.to_html(false), skipped] + return lead + " → ".join(texts) + + +static func clock(unix: float) -> String: + var bias: int = Time.get_time_zone_from_system().get("bias", 0) + var d := Time.get_datetime_dict_from_unix_time(int(unix) + bias * 60) + return "%02d:%02d" % [d["hour"], d["minute"]] diff --git a/ui/earlier_rolls.gd.uid b/ui/earlier_rolls.gd.uid new file mode 100644 index 0000000..f5e8798 --- /dev/null +++ b/ui/earlier_rolls.gd.uid @@ -0,0 +1 @@ +uid://do4j32ods46nd diff --git a/ui/result_tray.gd b/ui/result_tray.gd index 45b3971..62fee1d 100644 --- a/ui/result_tray.gd +++ b/ui/result_tray.gd @@ -11,6 +11,9 @@ extends PanelContainer ## the chip shows the same reasons. Screenshot flag: --why[=] ## opens the pop-over for that step (default: the last one with reasons) ## after a roll. +## +## Pieces: TrayChips builds the chips and links, TrayText words them, and +## EarlierRolls is the Earlier tab. enum Side { EARLIER, VARIABLES } @@ -25,9 +28,7 @@ var _again: Button var _copy: MenuButton var _flow: HFlowContainer var _empty: Label -var _earlier_box: VBoxContainer -var _earlier: VBoxContainer -var _earlier_empty: Label +var _earlier: EarlierRolls var _vars: VariablesPanel var _tab_earlier: Button var _tab_vars: Button @@ -56,8 +57,6 @@ const TAIL := 12 const MAX_EXPANDED := 300 ## The chips area scrolls past this height instead of pushing the board up. const MAX_FLOW_HEIGHT := 200.0 -## Most effect lines listed under one chip. -const EFFECT_LINES := 3 func setup(p_main: Main) -> void: @@ -159,14 +158,9 @@ func setup(p_main: Main) -> void: _tab_vars.pressed.connect(func() -> void: set_side(Side.VARIABLES)) tabs.add_child(_tab_vars) - _earlier_box = VBoxContainer.new() - _earlier_box.add_theme_constant_override("separation", 6) - right.add_child(_earlier_box) - _earlier = VBoxContainer.new() - _earlier.add_theme_constant_override("separation", 6) - _earlier_box.add_child(_earlier) - _earlier_empty = Style.make_label("Older rolls show here.", Style.body(), 15, Style.ON_FELT_MUTED) - _earlier_box.add_child(_earlier_empty) + _earlier = EarlierRolls.new() + _earlier.setup(main) + right.add_child(_earlier) _vars = VariablesPanel.new() _vars.setup(main) right.add_child(_vars) @@ -200,7 +194,7 @@ func set_side(s: int) -> void: side = s _tab_earlier.set_pressed_no_signal(s == Side.EARLIER) _tab_vars.set_pressed_no_signal(s == Side.VARIABLES) - _earlier_box.visible = s == Side.EARLIER + _earlier.visible = s == Side.EARLIER _vars.visible = s == Side.VARIABLES if s == Side.VARIABLES: _vars.render() @@ -261,12 +255,12 @@ func render() -> void: _copy.visible = done var first := visible_from(steps.size(), expanded) if first > 0 or expanded and steps.size() > TAIL: - _flow.add_child(_earlier_toggle(first, steps.size())) + _flow.add_child(TrayChips.earlier_toggle(self, first, steps.size())) for i in range(first, steps.size()): var step: Dictionary = steps[i] if i > first: - _flow.add_child(_link(step.get("inline", false))) - var chip := _chip(step, done and i == steps.size() - 1, steps, i) + _flow.add_child(TrayChips.link(step.get("inline", false))) + var chip := TrayChips.chip(self, step, done and i == steps.size() - 1, steps, i) _flow.add_child(chip) if i >= fresh_from and not current.get("fast", false): chip.modulate.a = 0.3 @@ -274,25 +268,10 @@ func render() -> void: var asking := str(current.get("asking", "")) if asking != "" and not done: if steps.size() > first: - _flow.add_child(_link(false)) - _flow.add_child(_asking_chip(asking)) + _flow.add_child(TrayChips.link(false)) + _flow.add_child(TrayChips.asking_chip(asking)) - for c in _earlier.get_children(): - _earlier.remove_child(c) - c.queue_free() - _earlier_empty.visible = main.history.is_empty() - for rec in main.history: - var row := HBoxContainer.new() - row.add_theme_constant_override("separation", 8) - var time := Style.make_label(clock(rec["time"]), Style.body(), 14, Style.ON_FELT_MUTED) - time.custom_minimum_size = Vector2(44, 0) - time.size_flags_vertical = SIZE_SHRINK_BEGIN - row.add_child(time) - var line := RichText.label(earlier_line(rec), 14, Style.ON_FELT, false) - line.size_flags_horizontal = SIZE_EXPAND_FILL - RichText.hook_hover(line, main) - row.add_child(line) - _earlier.add_child(row) + _earlier.render() var n := main.variable_names().size() _tab_vars.text = "VARIABLES · %d" % n if n > 0 else "VARIABLES" @@ -356,36 +335,6 @@ static func visible_from(count: int, is_expanded: bool) -> int: return count - TAIL -## One Earlier row: "Root: a → b → c", with only the last few steps of a long -## chain. -static func earlier_line(rec: Dictionary) -> String: - var texts := PackedStringArray() - var all: Array = rec.get("steps", []) - var shown := 0 - var skipped := 0 - for k in range(all.size() - 1, -1, -1): - var s: Dictionary = all[k] - if s.get("inline", false): - continue - if shown >= 6: - skipped += 1 - continue - texts.insert(0, RichText.decorate(_one_line(str(s["text"])), true)) - shown += 1 - var lead := "[color=#%s]%s:[/color] " % [Style.ON_FELT_MUTED.to_html(false), RichText.plain(Formatter.strip_tags(str(rec.get("root_name", ""))))] - if skipped > 0: - lead += "[color=#%s]… %d earlier →[/color] " % [Style.ON_FELT_MUTED.to_html(false), skipped] - return lead + " → ".join(texts) - - -## The first line of a (sheet's) multi-line text, with "…" when there's more. -static func _one_line(text: String) -> String: - var nl := text.find("\n") - if nl < 0: - return text - return Formatter.close_open_tags(text.substr(0, nl)) + " …" - - ## The "Cancelled" / "Stopped after 10,000 actions" pill, and the sheet headline. func _render_status(current: Dictionary, steps: Array) -> void: var halted := str(current.get("halted", "")) @@ -400,7 +349,7 @@ func _render_status(current: Dictionary, steps: Array) -> void: _halt_label.text = ("✕ " if halted == Roller.CANCELLED else "⚠ ") + halted _halt.tooltip_text = "The roll was cancelled at a question; what came before is kept." if halted == Roller.CANCELLED \ else "This roll took too many steps, so it stopped; everything up to that point is kept." - var sheet := sheet_step(steps) if current.get("done", false) else {} + var sheet := TrayText.sheet_step(steps) if current.get("done", false) else {} _headline.visible = not sheet.is_empty() if not sheet.is_empty(): _headline_cap.text = Formatter.strip_tags(str(sheet.get("table", ""))).to_upper() @@ -408,15 +357,6 @@ func _render_status(current: Dictionary, steps: Array) -> void: _fit_headline() -## The last sheet step of a chain (the headline), or {}. -static func sheet_step(steps: Array) -> Dictionary: - for k in range(steps.size() - 1, -1, -1): - var s: Dictionary = steps[k] - if str(s.get("kind", "")) == RollTable.KIND_SHEET and not s.get("stop", false): - return s - return {} - - func _fit_scroll() -> void: if _scroll == null or _flow == null: return @@ -431,280 +371,6 @@ func _fit_scroll() -> void: _scroll.scroll_vertical = int(_scroll.get_v_scroll_bar().max_value) -## "+N earlier steps" (or "Hide earlier steps") at the start of a long chain. -func _earlier_toggle(first: int, total: int) -> Control: - var b := Button.new() - if expanded: - b.text = "Hide earlier steps" if first == 0 else "Hide earlier steps (%s not shown)" % _thousands(first) - else: - b.text = "+%s earlier steps" % _thousands(first) - b.tooltip_text = "This chain has %s steps" % _thousands(total) - b.size_flags_vertical = SIZE_SHRINK_CENTER - var n := Style.bordered(Style.box(Color(1, 1, 1, 0.04), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16)) - var h := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 8, [12, 6, 12, 6]), 1, Color(Style.BRASS, 0.5)) - Style.skin_button(b, n, h, h, Style.ON_FELT_MUTED, Style.ON_FELT) - b.add_theme_font_size_override("font_size", 14) - b.pressed.connect(func() -> void: - expanded = not expanded - render() - ) - var wrap := HBoxContainer.new() - wrap.add_theme_constant_override("separation", 0) - wrap.add_child(b) - var gap := Control.new() - gap.custom_minimum_size = Vector2(10, 0) - wrap.add_child(gap) - return wrap - - -static func _thousands(n: int) -> String: - var s := str(n) - var out := "" - while s.length() > 3: - out = "," + s.substr(s.length() - 3) + out - s = s.substr(0, s.length() - 3) - return s + out - - -## A dashed placeholder chip for the question that is open right now. -func _asking_chip(title: String) -> Control: - var p := PanelContainer.new() - var sb := Style.box(Color(1, 1, 1, 0.05), 9, [12, 7, 12, 8]) - Style.bordered(sb, 1, Color(Style.BRASS, 0.6)) - p.add_theme_stylebox_override("panel", sb) - p.size_flags_vertical = SIZE_SHRINK_CENTER - var v := VBoxContainer.new() - v.add_theme_constant_override("separation", 1) - p.add_child(v) - v.add_child(Style.make_label(title, Style.body(), 12, Style.ON_FELT_MUTED)) - v.add_child(Style.make_label("Waiting for your answer…", Style.display(), 20, Style.BRASS)) - return p - - -## The muted line above a chip's text: table name and how it got its result. -## With `plain`, rules read in plain words ("Loot · Tier 1 · rolled 4 on 1D + -## Tier", "Force the gate · rolled 7, +1 → 8"), labelled from `board`. -static func caption_for(step: Dictionary, board: TowerBoard = null, plain: bool = false) -> String: - var caption := Formatter.strip_tags(str(step["table"])) - var num: String = str(step.get("num", "")) - var ins: Variant = step.get("inputs") - if ins is Dictionary: - for nm: Variant in ins: - if plain: - caption += " · %s %s" % [Describe.label(str(nm), board), Expr.format_value(ins[nm])] - else: - caption += " · %s=%s" % [nm, Expr.format_value(ins[nm])] - match str(step.get("kind", "")): - RollTable.KIND_CHECK: - var c: Variant = step.get("check") - if c is Dictionary: - var mod := int(c.get("mod", 0)) - var ms := "" - if mod != 0: - ms = ("+%d" % mod) if mod > 0 else (Describe.MINUS + str(-mod)) - if plain: - caption += " · rolled %s%s → %s" % [Expr.format_value(c.get("nat")), (", " + ms) if ms != "" else "", Expr.format_value(c.get("total"))] - else: - caption += " · %s%s = %s vs %s" % [Expr.format_value(c.get("nat")), ms.replace(Describe.MINUS, "-"), Expr.format_value(c.get("total")), Expr.format_value(c.get("target"))] - RollTable.KIND_CHOICE: - if step.get("cancelled", false): - pass - elif step.has("answer"): - caption += " · answered" - elif step.get("picked", false): - caption += " · picked" - elif step.get("random", false): - caption += " · random" - if num != "": - caption += ", rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))] - RollTable.KIND_LOOP: - if step.has("pass"): - caption += " · pass %s" % str(step["pass"]) - elif step.get("after", false): - caption += " · afterwards" - RollTable.KIND_SHEET: - caption += " · sheet" - RollTable.KIND_ROUTER: - if step.has("case"): - var said := false - if plain and board != null: - var rt := board.get_table(str(step.get("table_id", ""))) - var k := int(step["case"]) - if rt != null and k >= 0 and k < rt.entries.size(): - caption += " · " + RulesView.cut(RulesView.case_label(rt.entries[k], board, true), 44) - said = true - if not said: - caption += " · case %d" % (int(step["case"]) + 1) - _: - if num != "": - var dl := str(step.get("dice", "d%d" % int(step.get("die", 0)))) - if plain and dl.contains(" "): - dl = RulesView.cut(Describe.dice(dl, board), 30) - caption += " · rolled %s on %s" % [num, dl] - if step.get("reshuffled", false): - caption += " · deck reshuffled" - if str(step.get("save_as", "")) != "": - if plain: - caption += " · saved as %s" % Describe.label(str(step["save_as"]), board) - else: - caption += " · saved as {%s}" % step["save_as"] - return caption - - -func _chip(step: Dictionary, last: bool, steps: Array = [], index: int = -1) -> Control: - var inline: bool = step.get("inline", false) - var p := PanelContainer.new() - var sb := Style.box(Style.LIT if last else Style.CARD, 9, [10, 5, 10, 6] if inline else [12, 7, 12, 8]) - sb.shadow_color = Color(0, 0, 0, 0.25) - sb.shadow_size = 1 - sb.shadow_offset = Vector2(0, 3) - if last: - Style.bordered(sb, 2, Style.BRASS) - sb.set_expand_margin_all(2) - if inline: - sb.bg_color = sb.bg_color.darkened(0.04) - p.add_theme_stylebox_override("panel", sb) - p.size_flags_vertical = SIZE_SHRINK_CENTER - p.mouse_filter = MOUSE_FILTER_PASS - var v := VBoxContainer.new() - v.add_theme_constant_override("separation", 1) - p.add_child(v) - var plain := RulesView.plain(main) - var caption := caption_for(step, main.data, plain) - var has_why := index >= 0 and WhyPopover.has_why(steps, index) - var has_details := main.details().step_has_details(step) - if has_details: - caption += " " + RichText.INFO_MARK - var cap := Style.make_label(caption, Style.body(), 11 if inline else 12, Style.MUTED) - cap.mouse_filter = MOUSE_FILTER_IGNORE - v.add_child(cap) - var raw := str(step["text"]) - if str(step.get("kind", "")) == RollTable.KIND_SHEET: - raw = _one_line(raw) - if step.has("answer") and Formatter.strip_tags(raw).strip_edges() == "": - raw = "[i]no answer[/i]" - var shown := RichText.decorate(raw) - var body := RichText.display_label(shown, 16 if inline else 20, Style.DANGER_INK if step.get("stop", false) else Style.INK) - if Formatter.strip_tags(shown).length() > 56: - body.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART - body.custom_minimum_size = Vector2(420, 0) - RichText.hook_hover(body, main) - v.add_child(body) - var fx: Array = step.get("effects", []) - if not fx.is_empty(): - v.add_child(_effect_lines(effect_lines_for(step, main.data, plain))) - if has_why: - var wb := _why_button() - wb.pressed.connect(func() -> void: open_why(index, wb)) - why_buttons[index] = wb - v.add_child(wb) - if has_details or has_why: - p.mouse_entered.connect(func() -> void: - if not _why.visible: - main.details().show_step(p, step, steps, index)) - return p - - -## The small "Why this?" pill under a chip. -func _why_button() -> Button: - var b := Button.new() - b.text = "Why this?" - b.tooltip_text = "What decided this step" - b.size_flags_horizontal = SIZE_SHRINK_BEGIN - b.focus_mode = Control.FOCUS_NONE - var n := Style.bordered(Style.box(Color.WHITE, 10, [9, 1, 9, 2]), 1, Style.RULE) - var h := Style.bordered(Style.box(Style.LIT, 10, [9, 1, 9, 2]), 1, Style.BRASS_DARK) - Style.skin_button(b, n, h, h, Style.COPPER_DARK, Style.INK) - b.add_theme_font_override("font", Style.body_bold()) - b.add_theme_font_size_override("font_size", 12) - return b - - -## A step's effect lines for its chip: in plain words, one per value that -## changed ("Luck 2 → 1", "Town = Millbrook", "Cleared all Skills (3)") from -## its why facts, then any errors from its log; else the log as it is. -static func effect_lines_for(step: Dictionary, board: TowerBoard, plain: bool) -> Array: - var fx: Array = step.get("effects", []) - if not plain or not (step.get("why") is Array): - return fx - var out: Array = [] - for f: Variant in step["why"]: - if f is Dictionary and str(f.get("type", "")) == "effect": - out.append({"text": effect_fact_line(f, board)}) - if out.is_empty(): - return fx - for l: Variant in fx: - if l is Dictionary and (l as Dictionary).get("error", false): - out.append(l) - return out - - -## "Luck 2 → 1", "Town = Millbrook", "Loot cleared", "Cleared all Skills (3)". -static func effect_fact_line(f: Dictionary, board: TowerBoard) -> String: - var lab := Describe.label(str(f.get("var", "")), board) - if f.has("count"): - return "Cleared all %s (%s)" % [lab, Expr.format_value(f["count"])] - var before: Variant = f.get("before") - var after: Variant = f.get("after") - if after == null: - return "%s cleared" % lab - var a := Expr.format_value(after) - if before == null or Expr.format_value(before) == "": - return "%s = %s" % [lab, a if a != "" else "(none)"] - return "%s %s → %s" % [lab, Expr.format_value(before), a if a != "" else "(none)"] - - -## The effect log under a chip: a few compact lines, errors in red. -func _effect_lines(fx: Array) -> Control: - var box := VBoxContainer.new() - box.add_theme_constant_override("separation", 0) - box.mouse_filter = MOUSE_FILTER_IGNORE - var shown := 0 - var errors := 0 - for l: Variant in fx: - var d: Dictionary = l if l is Dictionary else {"text": str(l)} - var bad: bool = d.get("error", false) - if bad: - errors += 1 - # Errors are always listed; ordinary lines up to EFFECT_LINES. - if shown >= EFFECT_LINES and not bad: - continue - var lab := Style.make_label(("⚠ " if bad else "") + str(d.get("text", "")), Style.body_bold() if bad else Style.body(), 12, - Style.DANGER_INK if bad else Style.COPPER_DARK) - lab.mouse_filter = MOUSE_FILTER_IGNORE - lab.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS - lab.custom_minimum_size.x = 0 - box.add_child(lab) - shown += 1 - var more := fx.size() - shown - if more > 0: - box.add_child(Style.make_label("+%d more" % more, Style.body(), 11, Style.MUTED)) - var tip := Effects.log_text(fx) - box.tooltip_text = "\n".join(tip) - return box - - -func _link(inline: bool = false) -> Control: - var link := Panel.new() - var sb := Style.box(Style.BRASS) - sb.border_width_top = 2 - sb.border_width_bottom = 2 - sb.border_color = Style.BRASS_DARK - if inline: - sb = Style.box(Color(Style.BRASS, 0.55)) - link.add_theme_stylebox_override("panel", sb) - link.custom_minimum_size = Vector2(16, 4) if inline else Vector2(22, 8) - link.size_flags_vertical = SIZE_SHRINK_CENTER - link.mouse_filter = MOUSE_FILTER_IGNORE - return link - - -static func clock(unix: float) -> String: - var bias: int = Time.get_time_zone_from_system().get("bias", 0) - var d := Time.get_datetime_dict_from_unix_time(int(unix) + bias * 60) - return "%02d:%02d" % [d["hour"], d["minute"]] - - ## Sizes the sheet headline's scroll area to its text, up to HEADLINE_MAX_H. func _fit_headline() -> void: await get_tree().process_frame diff --git a/ui/settings_kind_fields.gd b/ui/settings_kind_fields.gd new file mode 100644 index 0000000..652be89 --- /dev/null +++ b/ui/settings_kind_fields.gd @@ -0,0 +1,327 @@ +class_name SettingsKindFields +extends RefCounted +## The kind-specific part of a TableSettingsDialog (docs/LOGIC.md): the +## fields shown for a choice, loop, variable, sheet or router card, their +## part of the settings Dictionary, and their live checks. + +var d: TableSettingsDialog +var table: RollTable +## The kind's problems, shown under its fields (null for roll tables). +var problem: Label + +var _choice := "pick" +var _choice_note: Label +var _prompt: LineEdit +var _save_as: LineEdit +var _min: LineEdit +var _max: LineEdit +var _minmax_row: Control +## Pick choices: "fixed" or "vars" (options from variables, plus fixed extras). +var _options_mode := "fixed" +var _options_box: Control +var _opt_mode_box: Control +var _opt_from: LineEdit +var _opt_where: LineEdit +var _opt_note: Label +var _show_if_box: Control +## entry id -> its Show only if field. +var _show_if: Dictionary = {} +var _loop_mode := "times" +var _loop_expr: LineEdit +var _loop_note: Label +var _var_name: LineEdit +var _var_type := "number" +var _initial: LineEdit +var _template: TextEdit +var _template_preview: RichTextLabel +## Router cards: one condition field per case, in order. +var _cases: Array[LineEdit] = [] +var _case_note: Label + + +func _init(dialog: TableSettingsDialog) -> void: + d = dialog + table = dialog.table + _choice = table.choice + _options_mode = "vars" if table.options_from.strip_edges() != "" else "fixed" + _loop_mode = table.loop_mode + _var_type = table.var_type + + +## Adds the kind's settings to `s`. +func add_settings(s: Dictionary) -> void: + match table.kind: + RollTable.KIND_CHOICE: + s["choice"] = _choice + s["prompt"] = _prompt.text + s["save_as"] = _save_as.text.strip_edges() + s["min"] = _min.text.strip_edges() + s["max"] = _max.text.strip_edges() + s["options_mode"] = _options_mode + s["options_from"] = _opt_from.text.strip_edges() + s["options_where"] = _opt_where.text.strip_edges() + var si := {} + for eid: String in _show_if: + si[eid] = (_show_if[eid] as LineEdit).text.strip_edges() + s["show_if"] = si + RollTable.KIND_LOOP: + s["loop_mode"] = _loop_mode + s["loop_expr"] = _loop_expr.text.strip_edges() + RollTable.KIND_VARIABLE: + s["var_name"] = _var_name.text.strip_edges().trim_prefix("@") + s["var_type"] = _var_type + s["initial"] = _initial.text.strip_edges() + RollTable.KIND_SHEET: + s["template"] = _template.text + RollTable.KIND_ROUTER: + var cases: Array = [] + for le in _cases: + cases.append(le.text.strip_edges()) + s["cases"] = cases + + +func build() -> void: + var box := VBoxContainer.new() + box.add_theme_constant_override("separation", 10) + match table.kind: + RollTable.KIND_CHOICE: + box.add_child(ModalCard.section("Question type")) + box.add_child(ModalCard.segmented(TableSettingsDialog.CHOICE_LABELS, RollTable.CHOICES.find(_choice), func(i: int) -> void: + _choice = RollTable.CHOICES[i] + d._refresh() + )) + _choice_note = ModalCard.note("") + box.add_child(_choice_note) + _prompt = LineEdit.new() + _prompt.text = table.prompt + _prompt.placeholder_text = "Which way out? You have {@gold} gold." + ModalCard.style_line_edit(_prompt) + _prompt.text_changed.connect(func(_t: String) -> void: d._refresh()) + box.add_child(ModalCard.field("Question (BBCode, {@var} works)", _prompt)) + _save_as = LineEdit.new() + _save_as.text = table.save_as + _save_as.placeholder_text = "@name to keep, or a name for this roll" + ModalCard.style_line_edit(_save_as) + _save_as.text_changed.connect(func(_t: String) -> void: d._refresh()) + box.add_child(ModalCard.field("Save the answer as (optional)", _save_as)) + var mm := HBoxContainer.new() + mm.add_theme_constant_override("separation", 12) + _min = LineEdit.new() + _min.text = table.min_expr + ModalCard.style_line_edit(_min) + _min.text_changed.connect(func(_t: String) -> void: d._refresh()) + _max = LineEdit.new() + _max.text = table.max_expr + ModalCard.style_line_edit(_max) + _max.text_changed.connect(func(_t: String) -> void: d._refresh()) + mm.add_child(ModalCard.field("Lowest", _min)) + mm.add_child(ModalCard.field("Highest", _max)) + for c in mm.get_children(): + (c as Control).size_flags_horizontal = Control.SIZE_EXPAND_FILL + _minmax_row = mm + box.add_child(mm) + _build_options(box) + RollTable.KIND_LOOP: + box.add_child(ModalCard.section("Repeat")) + box.add_child(ModalCard.segmented(TableSettingsDialog.LOOP_LABELS, RollTable.LOOPS.find(_loop_mode), func(i: int) -> void: + _loop_mode = RollTable.LOOPS[i] + d._refresh() + )) + _loop_expr = LineEdit.new() + _loop_expr.text = table.loop_expr + ModalCard.style_line_edit(_loop_expr) + _loop_expr.text_changed.connect(func(_t: String) -> void: d._refresh()) + box.add_child(ModalCard.field("How many times / condition", _loop_expr)) + _loop_note = ModalCard.note("") + box.add_child(_loop_note) + RollTable.KIND_VARIABLE: + _var_name = LineEdit.new() + _var_name.text = table.var_name + _var_name.placeholder_text = "hp" + ModalCard.style_line_edit(_var_name) + _var_name.text_changed.connect(func(_t: String) -> void: d._refresh()) + box.add_child(ModalCard.field("Variable name (used as @name)", _var_name)) + box.add_child(ModalCard.section("Type")) + box.add_child(ModalCard.segmented(["Number", "Text", "List", "Collection"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void: + _var_type = RollTable.VAR_TYPES[i] + d._refresh() + )) + _initial = LineEdit.new() + _initial.text = table.initial + _initial.placeholder_text = "10, 2d6, or a word" + ModalCard.style_line_edit(_initial) + _initial.text_changed.connect(func(_t: String) -> void: d._refresh()) + box.add_child(ModalCard.field("Starting value", _initial)) + box.add_child(ModalCard.note("reset @name, and Reset in the Variables tab, put it back to this.")) + RollTable.KIND_SHEET: + _template = TextEdit.new() + _template.text = table.entries[0].text if not table.entries.is_empty() else "" + _template.placeholder_text = "[b]{@name}[/b]\nHP {@hp} · Gold {@gold}\nSkills: {@skill_*}" + _template.custom_minimum_size.y = 120 + _template.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY + ModalCard.style_text_edit(_template) + _template.text_changed.connect(d._refresh) + box.add_child(ModalCard.field("Template (BBCode with {@var}, {@prefix_*} and {= expr})", _template)) + _template_preview = RichTextLabel.new() + _template_preview.bbcode_enabled = true + _template_preview.fit_content = true + _template_preview.scroll_active = false + var pbox := PanelContainer.new() + pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7])) + pbox.add_child(_template_preview) + box.add_child(pbox) + RollTable.KIND_ROUTER: + box.add_child(ModalCard.section("Cases (if / else if / otherwise)")) + box.add_child(ModalCard.note("Checked top to bottom when the chain arrives; the first true case is chosen, and its effects, text and pipes run like a rolled result. An empty condition is Otherwise: it always matches, so keep it last. Add, remove and reorder cases on the card.")) + for i in table.entries.size(): + var e := table.entries[i] + var le := LineEdit.new() + le.text = e.when + le.placeholder_text = "Otherwise (always)" + ModalCard.style_line_edit(le) + le.text_changed.connect(func(_t: String) -> void: d._refresh()) + _cases.append(le) + var label := Formatter.strip_tags(e.text).strip_edges() + box.add_child(ModalCard.field("Case %d%s" % [i + 1, (" · " + label) if label != "" else ""], le)) + if table.entries.is_empty(): + box.add_child(ModalCard.note("This router has no cases yet: add some on the card.")) + _case_note = ModalCard.note("", Style.WARN_INK) + box.add_child(_case_note) + _: + box.free() # roll tables have no kind fields + return + problem = ModalCard.note("", Style.DANGER_INK) + box.add_child(problem) + d.body.add_child(box) + + +## Pick choices: where the options come from, and a Show only if field per +## option. +func _build_options(box: VBoxContainer) -> void: + var mb := VBoxContainer.new() + mb.add_theme_constant_override("separation", 6) + mb.add_child(ModalCard.section("Options")) + mb.add_child(ModalCard.segmented(TableSettingsDialog.OPTION_LABELS, 1 if _options_mode == "vars" else 0, func(i: int) -> void: + _options_mode = "vars" if i == 1 else "fixed" + d._refresh() + )) + box.add_child(mb) + _opt_mode_box = mb + var ob := VBoxContainer.new() + ob.add_theme_constant_override("separation", 8) + _opt_from = LineEdit.new() + _opt_from.text = table.options_from + _opt_from.placeholder_text = "@skill_* or @contacts" + ModalCard.style_line_edit(_opt_from) + _opt_from.text_changed.connect(func(_t: String) -> void: d._refresh()) + ob.add_child(ModalCard.field("Options from (@prefix_* or a @list)", _opt_from)) + _opt_where = LineEdit.new() + _opt_where.text = table.options_where + _opt_where.placeholder_text = "option_value >= 1 (optional)" + ModalCard.style_line_edit(_opt_where) + _opt_where.text_changed.connect(func(_t: String) -> void: d._refresh()) + ob.add_child(ModalCard.field("Only where (optional)", _opt_where)) + _opt_note = ModalCard.note("") + ob.add_child(_opt_note) + box.add_child(ob) + _options_box = ob + var sb := VBoxContainer.new() + sb.add_theme_constant_override("separation", 6) + sb.add_child(ModalCard.section("Show only if")) + sb.add_child(ModalCard.note("Checked when the card is reached. An option whose condition is false isn't offered, not even to Random. Empty means always.")) + for i in table.entries.size(): + var e := table.entries[i] + var le := LineEdit.new() + le.text = e.show_if + le.placeholder_text = "always" + ModalCard.style_line_edit(le) + le.text_changed.connect(func(_t: String) -> void: d._refresh()) + _show_if[e.id] = le + var label := Formatter.strip_tags(e.text).strip_edges() + var cap := "Chosen (every option from variables)" if (i == 0 and table.is_dynamic()) else "Option %d%s" % [i + (0 if table.is_dynamic() else 1), (" · " + label) if label != "" else ""] + sb.add_child(ModalCard.field(cap, le)) + box.add_child(sb) + _show_if_box = sb + + +func refresh() -> void: + var s := d.settings() + var problems := TableSettingsRules.kind_problems(table, s) + if problem: + problem.text = "\n".join(problems) + problem.visible = not problems.is_empty() + match table.kind: + RollTable.KIND_CHOICE: + _minmax_row.visible = _choice == "number" + var msg := "" + if _choice != table.choice and table.choice == "pick": + msg = "Only the first option is kept, as the Answer row (its effects and pipes stay)." + elif _choice != table.choice and _choice == "pick": + msg = "The Answer row becomes the first option; two more are added." + elif _choice == "pick" and _options_mode == "vars" and table.is_dynamic(): + msg = "The player picks one of the options from variables or a fixed extra, or Random." + elif _choice == "pick" and _options_mode == "fixed" and table.is_dynamic(): + msg = "Back to a fixed list: the Chosen row becomes an ordinary option (or goes, if it does nothing)." + elif _choice == "pick": + msg = "The player picks one of the card's options, or Random." + else: + msg = "The answer goes in {answer}; the Answer row's effects and pipes run after it." + _choice_note.text = msg + _mark(_save_as, s["save_as"] == "" or TableSettingsRules._re(TableSettingsRules.SAVE_PATTERN).search(TemplateKit.probe(s["save_as"])) != null) + var pick := _choice == "pick" + _opt_mode_box.visible = pick + _options_box.visible = pick and _options_mode == "vars" + _show_if_box.visible = pick and not _show_if.is_empty() + if pick and _options_mode == "vars": + _mark(_opt_from, TableSettingsRules.options_from_error(s["options_from"]) == "") + _mark(_opt_where, TableSettingsRules.when_error(s["options_where"]) == "") + var desc := RollTable.new() + desc.options_from = s["options_from"] + desc.options_where = s["options_where"] + var how := "One option for %s, labelled with its name and value, after any fixed options. The Chosen row runs for whichever is picked; option, option_label and option_value hold it, e.g. @[option] += 1." % desc.options_description() \ + if TableSettingsRules.options_from_error(s["options_from"]) == "" else "Write @skill_* for each set variable with that prefix, or @contacts for each item of a list." + if not table.is_dynamic(): + how += " A Chosen row is added first; the options already on the card stay as fixed extras." + _opt_note.text = how + elif pick and table.is_dynamic(): + _opt_note.text = "" + for eid: String in _show_if: + _mark(_show_if[eid] as LineEdit, TableSettingsRules.when_error((_show_if[eid] as LineEdit).text) == "") + _mark(_min, Expr.check(TemplateKit.probe(s["min"])) == "" and s["min"] != "") + _mark(_max, Expr.check(TemplateKit.probe(s["max"])) == "" and s["max"] != "") + RollTable.KIND_LOOP: + _loop_note.text = TableSettingsDialog.LOOP_NOTES.get(_loop_mode, "") + _mark(_loop_expr, s["loop_expr"] != "" and Expr.check(TemplateKit.probe(s["loop_expr"])) == "") + RollTable.KIND_VARIABLE: + _mark(_var_name, TableSettingsRules._re(TableSettingsRules.VAR_PATTERN).search(TemplateKit.probe(s["var_name"])) != null) + _mark(_initial, TableSettingsRules._initial_error(s["initial"], _var_type) == "") + RollTable.KIND_SHEET: + var ctx := Roller.live_context(table_board(), _live_vars()) + _template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \ + else "[color=#69726b]Preview appears here.[/color]" + RollTable.KIND_ROUTER: + var cases: Array = s["cases"] + for i in _cases.size(): + _mark(_cases[i], TableSettingsRules.when_error(str(cases[i])) == "") + var hint := TableSettingsRules.router_hint(cases) + _case_note.text = hint + _case_note.visible = hint != "" + # The ranged/card-mode sections only apply to roll tables and pick choices. + var rolls := table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and _choice == "pick") + d._type_box.visible = rolls + d._card_box.visible = rolls + + +func _mark(le: LineEdit, ok: bool) -> void: + le.add_theme_color_override("font_color", Style.INK if ok else Style.DANGER_INK) + + +## The board and variables for the sheet preview, when the dialog sits in Main. +func table_board() -> TowerBoard: + var m := d.get_parent() as Main + return m.data if m else TowerBoard.new() + + +func _live_vars() -> Dictionary: + var m := d.get_parent() as Main + return m.persistent_vars if m else {} diff --git a/ui/settings_kind_fields.gd.uid b/ui/settings_kind_fields.gd.uid new file mode 100644 index 0000000..0d24adc --- /dev/null +++ b/ui/settings_kind_fields.gd.uid @@ -0,0 +1 @@ +uid://dheq5ky4bl0ic diff --git a/ui/table_settings_dialog.gd b/ui/table_settings_dialog.gd index a46b1fd..c1a3b5f 100644 --- a/ui/table_settings_dialog.gd +++ b/ui/table_settings_dialog.gd @@ -1,8 +1,8 @@ class_name TableSettingsDialog extends ModalCard ## Build-mode editor for one table's name, details, tags, type and card mode. -## The editing rules live in static functions (apply_settings and friends) so -## they can be tested without a window. +## The editing rules live in TableSettingsRules (static, tested without a +## window); the kind-specific fields in SettingsKindFields. signal applied(settings: Dictionary) ## The footer's "Save as template…" (the dialog closes first; Main opens the save dialog). @@ -30,39 +30,9 @@ var _deck_block: Control var _ranged := false var _card_mode := false var _deck_empty := "reshuffle" - -# Logic-card fields (docs/LOGIC.md), shown for the matching kind. var _type_box: Control var _card_box: Control -var _kind_problem: Label -var _choice := "pick" -var _choice_note: Label -var _prompt: LineEdit -var _save_as: LineEdit -var _min: LineEdit -var _max: LineEdit -var _minmax_row: Control -## Pick choices: "fixed" or "vars" (options from variables, plus fixed extras). -var _options_mode := "fixed" -var _options_box: Control -var _opt_mode_box: Control -var _opt_from: LineEdit -var _opt_where: LineEdit -var _opt_note: Label -var _show_if_box: Control -## entry id -> its Show only if field. -var _show_if: Dictionary = {} -var _loop_mode := "times" -var _loop_expr: LineEdit -var _loop_note: Label -var _var_name: LineEdit -var _var_type := "number" -var _initial: LineEdit -var _template: TextEdit -var _template_preview: RichTextLabel -## Router cards: one condition field per case, in order. -var _cases: Array[LineEdit] = [] -var _case_note: Label +var _kind: SettingsKindFields const TITLES := { RollTable.KIND_ROLL: "Table settings", @@ -80,8 +50,6 @@ const LOOP_NOTES := { "while": "Checks the condition before each pass and stops when it's false. e.g. @hp > 0", "until": "Runs a pass, then stops once the condition is true (at least one pass). e.g. @gold >= 100", } -const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$" -const VAR_PATTERN := "^[a-z0-9_]+$" func _init(p_table: RollTable = null) -> void: @@ -90,10 +58,7 @@ func _init(p_table: RollTable = null) -> void: _ranged = table.is_ranged() _card_mode = table.card_mode _deck_empty = table.deck_empty - _choice = table.choice - _options_mode = "vars" if table.options_from.strip_edges() != "" else "fixed" - _loop_mode = table.loop_mode - _var_type = table.var_type + _kind = SettingsKindFields.new(self) _build() @@ -104,7 +69,7 @@ func _build() -> void: style_line_edit(_name) _name.text_changed.connect(func(_t: String) -> void: _refresh()) body.add_child(field("Name", _name)) - _build_kind() + _kind.build() _details = TextEdit.new() _details.text = table.details @@ -238,7 +203,7 @@ func _color_menu(anchor: Control) -> void: ## Wraps the selected text in the tags, or inserts an empty pair at the caret. func _wrap_selection(open: String, close_tag: String) -> void: - var r := wrap_text(_details.text, _selection_range(), open, close_tag) + var r := TableSettingsRules.wrap_text(_details.text, _selection_range(), open, close_tag) _details.text = r["text"] _set_caret_at_offset(int(r["caret"])) _details.grab_focus() @@ -275,286 +240,10 @@ func settings() -> Dictionary: "ranged": _ranged, "dice": _dice.text.strip_edges(), "card_mode": _card_mode, "deck_empty": _deck_empty, } - match table.kind: - RollTable.KIND_CHOICE: - s["choice"] = _choice - s["prompt"] = _prompt.text - s["save_as"] = _save_as.text.strip_edges() - s["min"] = _min.text.strip_edges() - s["max"] = _max.text.strip_edges() - s["options_mode"] = _options_mode - s["options_from"] = _opt_from.text.strip_edges() - s["options_where"] = _opt_where.text.strip_edges() - var si := {} - for eid: String in _show_if: - si[eid] = (_show_if[eid] as LineEdit).text.strip_edges() - s["show_if"] = si - RollTable.KIND_LOOP: - s["loop_mode"] = _loop_mode - s["loop_expr"] = _loop_expr.text.strip_edges() - RollTable.KIND_VARIABLE: - s["var_name"] = _var_name.text.strip_edges().trim_prefix("@") - s["var_type"] = _var_type - s["initial"] = _initial.text.strip_edges() - RollTable.KIND_SHEET: - s["template"] = _template.text - RollTable.KIND_ROUTER: - var cases: Array = [] - for le in _cases: - cases.append(le.text.strip_edges()) - s["cases"] = cases + _kind.add_settings(s) return s -# ---------- Kind-specific fields ---------- - -func _build_kind() -> void: - var box := VBoxContainer.new() - box.add_theme_constant_override("separation", 10) - match table.kind: - RollTable.KIND_CHOICE: - box.add_child(section("Question type")) - box.add_child(segmented(CHOICE_LABELS, RollTable.CHOICES.find(_choice), func(i: int) -> void: - _choice = RollTable.CHOICES[i] - _refresh() - )) - _choice_note = note("") - box.add_child(_choice_note) - _prompt = LineEdit.new() - _prompt.text = table.prompt - _prompt.placeholder_text = "Which way out? You have {@gold} gold." - style_line_edit(_prompt) - _prompt.text_changed.connect(func(_t: String) -> void: _refresh()) - box.add_child(field("Question (BBCode, {@var} works)", _prompt)) - _save_as = LineEdit.new() - _save_as.text = table.save_as - _save_as.placeholder_text = "@name to keep, or a name for this roll" - style_line_edit(_save_as) - _save_as.text_changed.connect(func(_t: String) -> void: _refresh()) - box.add_child(field("Save the answer as (optional)", _save_as)) - var mm := HBoxContainer.new() - mm.add_theme_constant_override("separation", 12) - _min = LineEdit.new() - _min.text = table.min_expr - style_line_edit(_min) - _min.text_changed.connect(func(_t: String) -> void: _refresh()) - _max = LineEdit.new() - _max.text = table.max_expr - style_line_edit(_max) - _max.text_changed.connect(func(_t: String) -> void: _refresh()) - mm.add_child(field("Lowest", _min)) - mm.add_child(field("Highest", _max)) - for c in mm.get_children(): - (c as Control).size_flags_horizontal = SIZE_EXPAND_FILL - _minmax_row = mm - box.add_child(mm) - _build_options(box) - RollTable.KIND_LOOP: - box.add_child(section("Repeat")) - box.add_child(segmented(LOOP_LABELS, RollTable.LOOPS.find(_loop_mode), func(i: int) -> void: - _loop_mode = RollTable.LOOPS[i] - _refresh() - )) - _loop_expr = LineEdit.new() - _loop_expr.text = table.loop_expr - style_line_edit(_loop_expr) - _loop_expr.text_changed.connect(func(_t: String) -> void: _refresh()) - box.add_child(field("How many times / condition", _loop_expr)) - _loop_note = note("") - box.add_child(_loop_note) - RollTable.KIND_VARIABLE: - _var_name = LineEdit.new() - _var_name.text = table.var_name - _var_name.placeholder_text = "hp" - style_line_edit(_var_name) - _var_name.text_changed.connect(func(_t: String) -> void: _refresh()) - box.add_child(field("Variable name (used as @name)", _var_name)) - box.add_child(section("Type")) - box.add_child(segmented(["Number", "Text", "List", "Collection"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void: - _var_type = RollTable.VAR_TYPES[i] - _refresh() - )) - _initial = LineEdit.new() - _initial.text = table.initial - _initial.placeholder_text = "10, 2d6, or a word" - style_line_edit(_initial) - _initial.text_changed.connect(func(_t: String) -> void: _refresh()) - box.add_child(field("Starting value", _initial)) - box.add_child(note("reset @name, and Reset in the Variables tab, put it back to this.")) - RollTable.KIND_SHEET: - _template = TextEdit.new() - _template.text = table.entries[0].text if not table.entries.is_empty() else "" - _template.placeholder_text = "[b]{@name}[/b]\nHP {@hp} · Gold {@gold}\nSkills: {@skill_*}" - _template.custom_minimum_size.y = 120 - _template.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY - style_text_edit(_template) - _template.text_changed.connect(_refresh) - box.add_child(field("Template (BBCode with {@var}, {@prefix_*} and {= expr})", _template)) - _template_preview = RichTextLabel.new() - _template_preview.bbcode_enabled = true - _template_preview.fit_content = true - _template_preview.scroll_active = false - var pbox := PanelContainer.new() - pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7])) - pbox.add_child(_template_preview) - box.add_child(pbox) - RollTable.KIND_ROUTER: - box.add_child(section("Cases (if / else if / otherwise)")) - box.add_child(note("Checked top to bottom when the chain arrives; the first true case is chosen, and its effects, text and pipes run like a rolled result. An empty condition is Otherwise: it always matches, so keep it last. Add, remove and reorder cases on the card.")) - for i in table.entries.size(): - var e := table.entries[i] - var le := LineEdit.new() - le.text = e.when - le.placeholder_text = "Otherwise (always)" - style_line_edit(le) - le.text_changed.connect(func(_t: String) -> void: _refresh()) - _cases.append(le) - var label := Formatter.strip_tags(e.text).strip_edges() - box.add_child(field("Case %d%s" % [i + 1, (" · " + label) if label != "" else ""], le)) - if table.entries.is_empty(): - box.add_child(note("This router has no cases yet: add some on the card.")) - _case_note = note("", Style.WARN_INK) - box.add_child(_case_note) - _: - box.free() # roll tables have no kind fields - return - _kind_problem = note("", Style.DANGER_INK) - box.add_child(_kind_problem) - body.add_child(box) - - -## Pick choices: where the options come from, and a Show only if field per -## option. -func _build_options(box: VBoxContainer) -> void: - var mb := VBoxContainer.new() - mb.add_theme_constant_override("separation", 6) - mb.add_child(section("Options")) - mb.add_child(segmented(OPTION_LABELS, 1 if _options_mode == "vars" else 0, func(i: int) -> void: - _options_mode = "vars" if i == 1 else "fixed" - _refresh() - )) - box.add_child(mb) - _opt_mode_box = mb - var ob := VBoxContainer.new() - ob.add_theme_constant_override("separation", 8) - _opt_from = LineEdit.new() - _opt_from.text = table.options_from - _opt_from.placeholder_text = "@skill_* or @contacts" - style_line_edit(_opt_from) - _opt_from.text_changed.connect(func(_t: String) -> void: _refresh()) - ob.add_child(field("Options from (@prefix_* or a @list)", _opt_from)) - _opt_where = LineEdit.new() - _opt_where.text = table.options_where - _opt_where.placeholder_text = "option_value >= 1 (optional)" - style_line_edit(_opt_where) - _opt_where.text_changed.connect(func(_t: String) -> void: _refresh()) - ob.add_child(field("Only where (optional)", _opt_where)) - _opt_note = note("") - ob.add_child(_opt_note) - box.add_child(ob) - _options_box = ob - var sb := VBoxContainer.new() - sb.add_theme_constant_override("separation", 6) - sb.add_child(section("Show only if")) - sb.add_child(note("Checked when the card is reached. An option whose condition is false isn't offered, not even to Random. Empty means always.")) - for i in table.entries.size(): - var e := table.entries[i] - var le := LineEdit.new() - le.text = e.show_if - le.placeholder_text = "always" - style_line_edit(le) - le.text_changed.connect(func(_t: String) -> void: _refresh()) - _show_if[e.id] = le - var label := Formatter.strip_tags(e.text).strip_edges() - var cap := "Chosen (every option from variables)" if (i == 0 and table.is_dynamic()) else "Option %d%s" % [i + (0 if table.is_dynamic() else 1), (" · " + label) if label != "" else ""] - sb.add_child(field(cap, le)) - box.add_child(sb) - _show_if_box = sb - - -func _refresh_kind() -> void: - var s := settings() - var problems := kind_problems(table, s) - if _kind_problem: - _kind_problem.text = "\n".join(problems) - _kind_problem.visible = not problems.is_empty() - match table.kind: - RollTable.KIND_CHOICE: - _minmax_row.visible = _choice == "number" - var msg := "" - if _choice != table.choice and table.choice == "pick": - msg = "Only the first option is kept, as the Answer row (its effects and pipes stay)." - elif _choice != table.choice and _choice == "pick": - msg = "The Answer row becomes the first option; two more are added." - elif _choice == "pick" and _options_mode == "vars" and table.is_dynamic(): - msg = "The player picks one of the options from variables or a fixed extra, or Random." - elif _choice == "pick" and _options_mode == "fixed" and table.is_dynamic(): - msg = "Back to a fixed list: the Chosen row becomes an ordinary option (or goes, if it does nothing)." - elif _choice == "pick": - msg = "The player picks one of the card's options, or Random." - else: - msg = "The answer goes in {answer}; the Answer row's effects and pipes run after it." - _choice_note.text = msg - _mark(_save_as, s["save_as"] == "" or _re(SAVE_PATTERN).search(TemplateKit.probe(s["save_as"])) != null) - var pick := _choice == "pick" - _opt_mode_box.visible = pick - _options_box.visible = pick and _options_mode == "vars" - _show_if_box.visible = pick and not _show_if.is_empty() - if pick and _options_mode == "vars": - _mark(_opt_from, options_from_error(s["options_from"]) == "") - _mark(_opt_where, when_error(s["options_where"]) == "") - var desc := RollTable.new() - desc.options_from = s["options_from"] - desc.options_where = s["options_where"] - var how := "One option for %s, labelled with its name and value, after any fixed options. The Chosen row runs for whichever is picked; option, option_label and option_value hold it, e.g. @[option] += 1." % desc.options_description() \ - if options_from_error(s["options_from"]) == "" else "Write @skill_* for each set variable with that prefix, or @contacts for each item of a list." - if not table.is_dynamic(): - how += " A Chosen row is added first; the options already on the card stay as fixed extras." - _opt_note.text = how - elif pick and table.is_dynamic(): - _opt_note.text = "" - for eid: String in _show_if: - _mark(_show_if[eid] as LineEdit, when_error((_show_if[eid] as LineEdit).text) == "") - _mark(_min, Expr.check(TemplateKit.probe(s["min"])) == "" and s["min"] != "") - _mark(_max, Expr.check(TemplateKit.probe(s["max"])) == "" and s["max"] != "") - RollTable.KIND_LOOP: - _loop_note.text = LOOP_NOTES.get(_loop_mode, "") - _mark(_loop_expr, s["loop_expr"] != "" and Expr.check(TemplateKit.probe(s["loop_expr"])) == "") - RollTable.KIND_VARIABLE: - _mark(_var_name, _re(VAR_PATTERN).search(TemplateKit.probe(s["var_name"])) != null) - _mark(_initial, _initial_error(s["initial"], _var_type) == "") - RollTable.KIND_SHEET: - var ctx := Roller.live_context(table_board(), _live_vars()) - _template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \ - else "[color=#69726b]Preview appears here.[/color]" - RollTable.KIND_ROUTER: - var cases: Array = s["cases"] - for i in _cases.size(): - _mark(_cases[i], when_error(str(cases[i])) == "") - var hint := router_hint(cases) - _case_note.text = hint - _case_note.visible = hint != "" - # The ranged/card-mode sections only apply to roll tables and pick choices. - var rolls := table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and _choice == "pick") - _type_box.visible = rolls - _card_box.visible = rolls - - -func _mark(le: LineEdit, ok: bool) -> void: - le.add_theme_color_override("font_color", Style.INK if ok else Style.DANGER_INK) - - -## The board and variables for the sheet preview, when the dialog sits in Main. -func table_board() -> TowerBoard: - var m := get_parent() as Main - return m.data if m else TowerBoard.new() - - -func _live_vars() -> Dictionary: - var m := get_parent() as Main - return m.persistent_vars if m else {} - - func _refresh() -> void: if _preview == null: return @@ -563,12 +252,12 @@ func _refresh() -> void: _dice_row.visible = _ranged _deck_block.visible = _card_mode var s := settings() - var dice_ok := not _ranged or dice_ok_text(s["dice"]) + var dice_ok := not _ranged or TableSettingsRules.dice_ok_text(s["dice"]) _dice.add_theme_color_override("font_color", Style.INK if dice_ok else Style.WARN_INK) var msgs := PackedStringArray() if _ranged and not table.is_ranged(): msgs.append("Each entry gets a range sized by its weight; adjust them on the card.") - if _ranged and extra_pipe_count(table) > 0: + if _ranged and TableSettingsRules.extra_pipe_count(table) > 0: msgs.append("A range takes one pipe, so extra pipes on an entry will be dropped.") if not _ranged and table.is_ranged(): msgs.append("Ranges are removed; entries become plain picks.") @@ -579,23 +268,23 @@ func _refresh() -> void: problem = "“%s” is not a valid dice expression." % s["dice"] elif _type_box == null or _type_box.visible: var clone := RollTable.from_dict(table.to_dict()) - apply_settings(clone, s) + TableSettingsRules.apply_settings(clone, s) problem = clone.range_problems() _problem.text = problem _problem.visible = problem != "" if _type_box != null: - _refresh_kind() + _kind.refresh() if is_inside_tree(): _fit() func _on_apply() -> void: var s := settings() - var r := apply_settings(table, s) + var r := TableSettingsRules.apply_settings(table, s) if not r["ok"]: - if _kind_problem and not kind_problems(table, s).is_empty(): - _kind_problem.text = r["error"] - _kind_problem.visible = true + if _kind.problem and not TableSettingsRules.kind_problems(table, s).is_empty(): + _kind.problem.text = r["error"] + _kind.problem.visible = true else: _problem.text = r["error"] _problem.visible = true @@ -604,300 +293,16 @@ func _on_apply() -> void: close() -## Problems with the kind-specific settings (empty when fine). -static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray: - var out := PackedStringArray() - match t.kind: - RollTable.KIND_CHOICE: - # Template placeholders ({$name}) check as a plain name (TemplateKit.probe). - var save := TemplateKit.probe(str(s.get("save_as", t.save_as)).strip_edges()) - if save != "" and _re(SAVE_PATTERN).search(save) == null: - out.append("Save as: use a name like career, or @career to keep it.") - if str(s.get("choice", t.choice)) == "pick": - if str(s.get("options_mode", "vars" if t.options_from != "" else "fixed")) == "vars": - var ferr := options_from_error(str(s.get("options_from", t.options_from))) - if ferr != "": - out.append("Options from: " + ferr) - var werr := when_error(str(s.get("options_where", t.options_where))) - if werr != "": - out.append("Only where: " + werr) - var si: Dictionary = s.get("show_if", {}) - for eid: String in si: - var serr := when_error(str(si[eid])) - if serr != "": - var e := t.find_entry(eid) - var at := t.entries.find(e) if e != null else -1 - out.append("Show only if (%s): %s" % [("option %d" % (at + 1)) if at >= 0 else eid, serr]) - if str(s.get("choice", t.choice)) == "number": - for k in [["min", "Lowest"], ["max", "Highest"]]: - var src := TemplateKit.probe(str(s.get(k[0], "")).strip_edges()) - var err := Expr.check(src) if src != "" else "it's empty" - if err != "": - out.append("%s: %s" % [k[1], err]) - RollTable.KIND_LOOP: - var src := TemplateKit.probe(str(s.get("loop_expr", t.loop_expr)).strip_edges()) - if src == "": - out.append("The loop needs a count or a condition.") - elif Expr.check(src) != "": - out.append("Loop rule: " + Expr.check(src)) - RollTable.KIND_ROUTER: - var cases: Array = s.get("cases", []) - for i in cases.size(): - var err := when_error(str(cases[i])) - if err != "": - out.append("Case %d: %s" % [i + 1, err]) - RollTable.KIND_VARIABLE: - var n := TemplateKit.probe(str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@")) - if _re(VAR_PATTERN).search(n) == null: - out.append("Variable name: lowercase letters, digits and _ only.") - var err := _initial_error(str(s.get("initial", t.initial)), str(s.get("var_type", t.var_type))) - if err != "": - out.append("Starting value: " + err) - return out - - -## "" when a router case condition is usable (empty is Otherwise), else why not. -static func when_error(src: String) -> String: - src = TemplateKit.probe(src.strip_edges()) - return Expr.check(src) if src != "" else "" - - -## "" when an options_from pattern is usable, else why not ("" is refused). -static func options_from_error(src: String) -> String: - src = TemplateKit.probe(src.strip_edges()) - if src == "": - return "write @prefix_* or @list" - return str(RollTable.parse_options_from(src)["error"]) - - -## A hint about the order of router cases (an Otherwise that isn't last), or "". -static func router_hint(cases: Array) -> String: - for i in cases.size(): - if str(cases[i]).strip_edges() == "" and i < cases.size() - 1: - return "Case %d is Otherwise, so the cases after it can never be chosen. Move it to the end." % (i + 1) - return "" - - -static func _initial_error(src: String, type: String) -> String: - src = TemplateKit.probe(src.strip_edges()) - if src == "": - return "" - if type != "number" and RollTable._looks_literal(src): - return "" - return Expr.check(src) - - -static func _re(pattern: String) -> RegEx: - return RegEx.create_from_string(pattern) - - -## Dice text for a ranged table: plain dice (2d6) or an expression that uses a -## variable, dice or a function ("2d6 + dm(@end)", "@terms"). A lone word -## such as "banana" is not accepted. -static func dice_ok_text(text: String) -> bool: - var s := TemplateKit.probe(text.strip_edges()) - if Dice.is_valid_text(s): - return true - if s == "" or Expr.check(s) != "": - return false - return _re("^[A-Za-z_][A-Za-z0-9_]*$").search(s) == null - - -## Applies the kind-specific settings. Turning a pick choice into a number or -## text one keeps only its first entry (as the Answer); the other way, the -## Answer becomes the first of three options. -static func _apply_kind(t: RollTable, s: Dictionary) -> void: - match t.kind: - RollTable.KIND_CHOICE: - var c := str(s.get("choice", t.choice)) - if RollTable.CHOICES.has(c) and c != t.choice: - if c == "pick": - if not t.entries.is_empty(): - t.entries[0].text = "Option 1" - for n in range(t.entries.size() + 1, 4): - t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option %d" % n)) - else: - while t.entries.size() > 1: - t.entries.remove_at(t.entries.size() - 1) - if t.entries.is_empty(): - t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Answer")) - t.entries[0].text = "Answer" - t.entries[0].has_range = false - t.card_mode = false - t.choice = c - t.prompt = str(s.get("prompt", t.prompt)) - t.save_as = str(s.get("save_as", t.save_as)).strip_edges() - var si: Dictionary = s.get("show_if", {}) - for eid: String in si: - var se := t.find_entry(eid) - if se != null: - se.show_if = str(si[eid]).strip_edges() - if t.choice != "pick": - t.options_from = "" - t.options_where = "" - elif s.has("options_mode"): - _apply_options(t, str(s["options_mode"]) == "vars", str(s.get("options_from", "")), str(s.get("options_where", ""))) - if t.choice == "number": - t.min_expr = str(s.get("min", t.min_expr)).strip_edges() - t.max_expr = str(s.get("max", t.max_expr)).strip_edges() - RollTable.KIND_LOOP: - var m := str(s.get("loop_mode", t.loop_mode)) - if RollTable.LOOPS.has(m): - t.loop_mode = m - t.loop_expr = str(s.get("loop_expr", t.loop_expr)).strip_edges() - RollTable.KIND_VARIABLE: - t.var_name = str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@") - var vt := str(s.get("var_type", t.var_type)) - if RollTable.VAR_TYPES.has(vt): - t.var_type = vt - t.initial = str(s.get("initial", t.initial)).strip_edges() - RollTable.KIND_ROUTER: - var cases: Array = s.get("cases", []) - for i in mini(cases.size(), t.entries.size()): - t.entries[i].when = str(cases[i]).strip_edges() - RollTable.KIND_SHEET: - if s.has("template"): - if t.entries.is_empty(): - t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "")) - t.entries[0].text = str(s["template"]) - - -## Switches a pick card between a fixed list and options from variables. -## Turning variables on adds a Chosen entry first (untouched default -## "Option N" entries go; anything else stays as a fixed extra). Turning them -## off makes the Chosen entry an ordinary option, or drops it if it does -## nothing (no effects, pipes, details or text of its own). -static func _apply_options(t: RollTable, on: bool, from: String, where: String) -> void: - if on: - if not t.is_dynamic(): - var keep: Array[TableEntry] = [] - for e in t.entries: - var blank := e.effects.strip_edges() == "" and e.pipes.is_empty() and e.details.strip_edges() == "" \ - and e.show_if.strip_edges() == "" and RegEx.create_from_string("^Option \\d+$").search(e.text.strip_edges()) != null - if not blank: - keep.append(e) - t.entries = keep - t.entries.insert(0, TableEntry.new(TowerBoard.new_id("e"), Roller.CHOSEN)) - t.options_from = from.strip_edges() - t.options_where = where.strip_edges() - return - if t.is_dynamic() and not t.entries.is_empty(): - var c := t.entries[0] - var txt := Formatter.strip_tags(c.text).strip_edges() - if c.effects.strip_edges() == "" and c.pipes.is_empty() and c.details.strip_edges() == "" and (txt == "" or txt == Roller.CHOSEN): - t.entries.remove_at(0) - t.options_from = "" - t.options_where = "" - if t.entries.is_empty(): - t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option 1")) - - -# ---------- Pure editing logic ---------- - -## Wraps text[sel.x:sel.y] in open/close_tag. With an empty range, inserts the -## pair. Returns {text, caret}: the caret sits inside an inserted pair, or -## after the closing tag of a wrapped selection. -static func wrap_text(text: String, sel: Vector2i, open: String, close_tag: String) -> Dictionary: - var a := clampi(mini(sel.x, sel.y), 0, text.length()) - var b := clampi(maxi(sel.x, sel.y), 0, text.length()) - var out := text.substr(0, a) + open + text.substr(a, b - a) + close_tag + text.substr(b) - var caret := a + open.length() if a == b else b + open.length() + close_tag.length() - return {"text": out, "caret": caret} - - -## "a, b ,, a" -> ["a", "b"]. -static func parse_tags(text: String) -> Array[String]: - var out: Array[String] = [] - for part in text.split(","): - var t := part.strip_edges() - if t != "" and not out.has(t): - out.append(t) - return out - - -## Number of pipes beyond the first, summed over entries (lost when going ranged). -static func extra_pipe_count(t: RollTable) -> int: - var n := 0 - for e in t.entries: - n += maxi(0, e.pipes.size() - 1) - return n - - -## Applies a settings Dictionary (name, details, tags, ranged, dice, card_mode, -## deck_empty) to the table. Returns {ok, error, deck_reset}: on a bad dice -## expression nothing is changed. deck_reset says the card deck no longer fits -## (type, dice or card mode changed), so a saved deck should be cleared. +## TableSettingsRules.apply_settings. static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary: - var problems := kind_problems(t, s) - if not problems.is_empty(): - return {"ok": false, "error": "\n".join(problems), "deck_reset": false} - var ranged: bool = s.get("ranged", false) - # Only roll tables and pick choices can be ranged or dealt as cards. - var choice := str(s.get("choice", t.choice)) - var rolls := t.kind == RollTable.KIND_ROLL or (t.kind == RollTable.KIND_CHOICE and choice == "pick") - if not rolls: - ranged = false - var dice := str(s.get("dice", t.dice)).strip_edges() - if ranged and not dice_ok_text(dice): - return {"ok": false, "error": "“%s” is not a valid dice expression." % dice, "deck_reset": false} - var was_ranged := t.is_ranged() - var old_dice := t.dice - var old_card := t.card_mode - var new_name := str(s.get("name", t.name)).strip_edges() - if new_name != "": - t.name = new_name - t.details = str(s.get("details", t.details)) - t.tags = parse_tags(str(s.get("tags", ""))) - t.card_mode = bool(s.get("card_mode", t.card_mode)) and rolls - t.deck_empty = "stop" if str(s.get("deck_empty", t.deck_empty)) == "stop" else "reshuffle" - if ranged: - t.dice = dice - if not was_ranged: - assign_ranges(t) - elif was_ranged: - drop_ranges(t) - _apply_kind(t, s) - var deck_reset := was_ranged != ranged or old_card != t.card_mode or (ranged and old_dice != t.dice) - return {"ok": true, "error": "", "deck_reset": deck_reset} + return TableSettingsRules.apply_settings(t, s) -## Gives entries ranges on the table's dice, sized by weight (at least one -## value each while there is room). Entries of weight 0 get no range. Each -## entry keeps only its first pipe, since a range takes one pipe. -static func assign_ranges(t: RollTable) -> void: - var d := t.dice_obj() - var lo := d.min_value() - var hi := d.max_value() - var live: Array[TableEntry] = [] - var total := 0 - for e in t.entries: - e.has_range = false - if e.weight > 0: - live.append(e) - total += e.weight - while e.pipes.size() > 1: - e.remove_pipe(e.pipes[e.pipes.size() - 1]) - var span := hi - lo + 1 - var cum := 0 - var prev := lo - 1 - for i in live.size(): - var e := live[i] - if prev >= hi: - break - cum += e.weight - var end := lo - 1 + roundi(float(span) * cum / total) - end = mini(end, hi - (live.size() - 1 - i)) - end = clampi(maxi(end, prev + 1), prev + 1, hi) - if i == live.size() - 1: - end = hi - e.has_range = true - e.range_lo = prev + 1 - e.range_hi = end - prev = end +## TableSettingsRules.when_error. +static func when_error(src: String) -> String: + return TableSettingsRules.when_error(src) -static func drop_ranges(t: RollTable) -> void: - for e in t.entries: - e.has_range = false - e.range_lo = 1 - e.range_hi = 1 +## TableSettingsRules.dice_ok_text. +static func dice_ok_text(text: String) -> bool: + return TableSettingsRules.dice_ok_text(text) diff --git a/ui/table_settings_rules.gd b/ui/table_settings_rules.gd new file mode 100644 index 0000000..8eb6d83 --- /dev/null +++ b/ui/table_settings_rules.gd @@ -0,0 +1,307 @@ +class_name TableSettingsRules +extends RefCounted +## The editing rules behind TableSettingsDialog: checking a settings +## Dictionary and applying it to a table. Static, so they can be tested +## without a window. + +const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$" +const VAR_PATTERN := "^[a-z0-9_]+$" + + +## Problems with the kind-specific settings (empty when fine). +static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray: + var out := PackedStringArray() + match t.kind: + RollTable.KIND_CHOICE: + # Template placeholders ({$name}) check as a plain name (TemplateKit.probe). + var save := TemplateKit.probe(str(s.get("save_as", t.save_as)).strip_edges()) + if save != "" and _re(SAVE_PATTERN).search(save) == null: + out.append("Save as: use a name like career, or @career to keep it.") + if str(s.get("choice", t.choice)) == "pick": + if str(s.get("options_mode", "vars" if t.options_from != "" else "fixed")) == "vars": + var ferr := options_from_error(str(s.get("options_from", t.options_from))) + if ferr != "": + out.append("Options from: " + ferr) + var werr := when_error(str(s.get("options_where", t.options_where))) + if werr != "": + out.append("Only where: " + werr) + var si: Dictionary = s.get("show_if", {}) + for eid: String in si: + var serr := when_error(str(si[eid])) + if serr != "": + var e := t.find_entry(eid) + var at := t.entries.find(e) if e != null else -1 + out.append("Show only if (%s): %s" % [("option %d" % (at + 1)) if at >= 0 else eid, serr]) + if str(s.get("choice", t.choice)) == "number": + for k in [["min", "Lowest"], ["max", "Highest"]]: + var src := TemplateKit.probe(str(s.get(k[0], "")).strip_edges()) + var err := Expr.check(src) if src != "" else "it's empty" + if err != "": + out.append("%s: %s" % [k[1], err]) + RollTable.KIND_LOOP: + var src := TemplateKit.probe(str(s.get("loop_expr", t.loop_expr)).strip_edges()) + if src == "": + out.append("The loop needs a count or a condition.") + elif Expr.check(src) != "": + out.append("Loop rule: " + Expr.check(src)) + RollTable.KIND_ROUTER: + var cases: Array = s.get("cases", []) + for i in cases.size(): + var err := when_error(str(cases[i])) + if err != "": + out.append("Case %d: %s" % [i + 1, err]) + RollTable.KIND_VARIABLE: + var n := TemplateKit.probe(str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@")) + if _re(VAR_PATTERN).search(n) == null: + out.append("Variable name: lowercase letters, digits and _ only.") + var err := _initial_error(str(s.get("initial", t.initial)), str(s.get("var_type", t.var_type))) + if err != "": + out.append("Starting value: " + err) + return out + + +## "" when a router case condition is usable (empty is Otherwise), else why not. +static func when_error(src: String) -> String: + src = TemplateKit.probe(src.strip_edges()) + return Expr.check(src) if src != "" else "" + + +## "" when an options_from pattern is usable, else why not ("" is refused). +static func options_from_error(src: String) -> String: + src = TemplateKit.probe(src.strip_edges()) + if src == "": + return "write @prefix_* or @list" + return str(RollTable.parse_options_from(src)["error"]) + + +## A hint about the order of router cases (an Otherwise that isn't last), or "". +static func router_hint(cases: Array) -> String: + for i in cases.size(): + if str(cases[i]).strip_edges() == "" and i < cases.size() - 1: + return "Case %d is Otherwise, so the cases after it can never be chosen. Move it to the end." % (i + 1) + return "" + + +static func _initial_error(src: String, type: String) -> String: + src = TemplateKit.probe(src.strip_edges()) + if src == "": + return "" + if type != "number" and RollTable._looks_literal(src): + return "" + return Expr.check(src) + + +static func _re(pattern: String) -> RegEx: + return RegEx.create_from_string(pattern) + + +## Dice text for a ranged table: plain dice (2d6) or an expression that uses a +## variable, dice or a function ("2d6 + dm(@end)", "@terms"). A lone word +## such as "banana" is not accepted. +static func dice_ok_text(text: String) -> bool: + var s := TemplateKit.probe(text.strip_edges()) + if Dice.is_valid_text(s): + return true + if s == "" or Expr.check(s) != "": + return false + return _re("^[A-Za-z_][A-Za-z0-9_]*$").search(s) == null + + +## Applies the kind-specific settings. Turning a pick choice into a number or +## text one keeps only its first entry (as the Answer); the other way, the +## Answer becomes the first of three options. +static func _apply_kind(t: RollTable, s: Dictionary) -> void: + match t.kind: + RollTable.KIND_CHOICE: + var c := str(s.get("choice", t.choice)) + if RollTable.CHOICES.has(c) and c != t.choice: + if c == "pick": + if not t.entries.is_empty(): + t.entries[0].text = "Option 1" + for n in range(t.entries.size() + 1, 4): + t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option %d" % n)) + else: + while t.entries.size() > 1: + t.entries.remove_at(t.entries.size() - 1) + if t.entries.is_empty(): + t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Answer")) + t.entries[0].text = "Answer" + t.entries[0].has_range = false + t.card_mode = false + t.choice = c + t.prompt = str(s.get("prompt", t.prompt)) + t.save_as = str(s.get("save_as", t.save_as)).strip_edges() + var si: Dictionary = s.get("show_if", {}) + for eid: String in si: + var se := t.find_entry(eid) + if se != null: + se.show_if = str(si[eid]).strip_edges() + if t.choice != "pick": + t.options_from = "" + t.options_where = "" + elif s.has("options_mode"): + _apply_options(t, str(s["options_mode"]) == "vars", str(s.get("options_from", "")), str(s.get("options_where", ""))) + if t.choice == "number": + t.min_expr = str(s.get("min", t.min_expr)).strip_edges() + t.max_expr = str(s.get("max", t.max_expr)).strip_edges() + RollTable.KIND_LOOP: + var m := str(s.get("loop_mode", t.loop_mode)) + if RollTable.LOOPS.has(m): + t.loop_mode = m + t.loop_expr = str(s.get("loop_expr", t.loop_expr)).strip_edges() + RollTable.KIND_VARIABLE: + t.var_name = str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@") + var vt := str(s.get("var_type", t.var_type)) + if RollTable.VAR_TYPES.has(vt): + t.var_type = vt + t.initial = str(s.get("initial", t.initial)).strip_edges() + RollTable.KIND_ROUTER: + var cases: Array = s.get("cases", []) + for i in mini(cases.size(), t.entries.size()): + t.entries[i].when = str(cases[i]).strip_edges() + RollTable.KIND_SHEET: + if s.has("template"): + if t.entries.is_empty(): + t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "")) + t.entries[0].text = str(s["template"]) + + +## Switches a pick card between a fixed list and options from variables. +## Turning variables on adds a Chosen entry first (untouched default +## "Option N" entries go; anything else stays as a fixed extra). Turning them +## off makes the Chosen entry an ordinary option, or drops it if it does +## nothing (no effects, pipes, details or text of its own). +static func _apply_options(t: RollTable, on: bool, from: String, where: String) -> void: + if on: + if not t.is_dynamic(): + var keep: Array[TableEntry] = [] + for e in t.entries: + var blank := e.effects.strip_edges() == "" and e.pipes.is_empty() and e.details.strip_edges() == "" \ + and e.show_if.strip_edges() == "" and RegEx.create_from_string("^Option \\d+$").search(e.text.strip_edges()) != null + if not blank: + keep.append(e) + t.entries = keep + t.entries.insert(0, TableEntry.new(TowerBoard.new_id("e"), Roller.CHOSEN)) + t.options_from = from.strip_edges() + t.options_where = where.strip_edges() + return + if t.is_dynamic() and not t.entries.is_empty(): + var c := t.entries[0] + var txt := Formatter.strip_tags(c.text).strip_edges() + if c.effects.strip_edges() == "" and c.pipes.is_empty() and c.details.strip_edges() == "" and (txt == "" or txt == Roller.CHOSEN): + t.entries.remove_at(0) + t.options_from = "" + t.options_where = "" + if t.entries.is_empty(): + t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option 1")) + + +# ---------- Pure editing logic ---------- + +## Wraps text[sel.x:sel.y] in open/close_tag. With an empty range, inserts the +## pair. Returns {text, caret}: the caret sits inside an inserted pair, or +## after the closing tag of a wrapped selection. +static func wrap_text(text: String, sel: Vector2i, open: String, close_tag: String) -> Dictionary: + var a := clampi(mini(sel.x, sel.y), 0, text.length()) + var b := clampi(maxi(sel.x, sel.y), 0, text.length()) + var out := text.substr(0, a) + open + text.substr(a, b - a) + close_tag + text.substr(b) + var caret := a + open.length() if a == b else b + open.length() + close_tag.length() + return {"text": out, "caret": caret} + + +## "a, b ,, a" -> ["a", "b"]. +static func parse_tags(text: String) -> Array[String]: + var out: Array[String] = [] + for part in text.split(","): + var t := part.strip_edges() + if t != "" and not out.has(t): + out.append(t) + return out + + +## Number of pipes beyond the first, summed over entries (lost when going ranged). +static func extra_pipe_count(t: RollTable) -> int: + var n := 0 + for e in t.entries: + n += maxi(0, e.pipes.size() - 1) + return n + + +## Applies a settings Dictionary (name, details, tags, ranged, dice, card_mode, +## deck_empty) to the table. Returns {ok, error, deck_reset}: on a bad dice +## expression nothing is changed. deck_reset says the card deck no longer fits +## (type, dice or card mode changed), so a saved deck should be cleared. +static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary: + var problems := kind_problems(t, s) + if not problems.is_empty(): + return {"ok": false, "error": "\n".join(problems), "deck_reset": false} + var ranged: bool = s.get("ranged", false) + # Only roll tables and pick choices can be ranged or dealt as cards. + var choice := str(s.get("choice", t.choice)) + var rolls := t.kind == RollTable.KIND_ROLL or (t.kind == RollTable.KIND_CHOICE and choice == "pick") + if not rolls: + ranged = false + var dice := str(s.get("dice", t.dice)).strip_edges() + if ranged and not dice_ok_text(dice): + return {"ok": false, "error": "“%s” is not a valid dice expression." % dice, "deck_reset": false} + var was_ranged := t.is_ranged() + var old_dice := t.dice + var old_card := t.card_mode + var new_name := str(s.get("name", t.name)).strip_edges() + if new_name != "": + t.name = new_name + t.details = str(s.get("details", t.details)) + t.tags = parse_tags(str(s.get("tags", ""))) + t.card_mode = bool(s.get("card_mode", t.card_mode)) and rolls + t.deck_empty = "stop" if str(s.get("deck_empty", t.deck_empty)) == "stop" else "reshuffle" + if ranged: + t.dice = dice + if not was_ranged: + assign_ranges(t) + elif was_ranged: + drop_ranges(t) + _apply_kind(t, s) + var deck_reset := was_ranged != ranged or old_card != t.card_mode or (ranged and old_dice != t.dice) + return {"ok": true, "error": "", "deck_reset": deck_reset} + + +## Gives entries ranges on the table's dice, sized by weight (at least one +## value each while there is room). Entries of weight 0 get no range. Each +## entry keeps only its first pipe, since a range takes one pipe. +static func assign_ranges(t: RollTable) -> void: + var d := t.dice_obj() + var lo := d.min_value() + var hi := d.max_value() + var live: Array[TableEntry] = [] + var total := 0 + for e in t.entries: + e.has_range = false + if e.weight > 0: + live.append(e) + total += e.weight + while e.pipes.size() > 1: + e.remove_pipe(e.pipes[e.pipes.size() - 1]) + var span := hi - lo + 1 + var cum := 0 + var prev := lo - 1 + for i in live.size(): + var e := live[i] + if prev >= hi: + break + cum += e.weight + var end := lo - 1 + roundi(float(span) * cum / total) + end = mini(end, hi - (live.size() - 1 - i)) + end = clampi(maxi(end, prev + 1), prev + 1, hi) + if i == live.size() - 1: + end = hi + e.has_range = true + e.range_lo = prev + 1 + e.range_hi = end + prev = end + + +static func drop_ranges(t: RollTable) -> void: + for e in t.entries: + e.has_range = false + e.range_lo = 1 + e.range_hi = 1 diff --git a/ui/table_settings_rules.gd.uid b/ui/table_settings_rules.gd.uid new file mode 100644 index 0000000..eb2ef59 --- /dev/null +++ b/ui/table_settings_rules.gd.uid @@ -0,0 +1 @@ +uid://b18xy6h3qarji diff --git a/ui/tray_chips.gd b/ui/tray_chips.gd new file mode 100644 index 0000000..dbcaae9 --- /dev/null +++ b/ui/tray_chips.gd @@ -0,0 +1,166 @@ +class_name TrayChips +extends RefCounted +## Builders for the pieces of ResultTray's chain: result chips (with their +## effect lines and "Why this?" button), the brass links between them, the +## open-question chip and the "+N earlier steps" toggle. + +## Most effect lines listed under one chip. +const EFFECT_LINES := 3 + + +## The chip for steps[index]; `last` marks the final result of a finished roll. +static func chip(tray: ResultTray, step: Dictionary, last: bool, steps: Array = [], index: int = -1) -> Control: + var main := tray.main + var inline: bool = step.get("inline", false) + var p := PanelContainer.new() + var sb := Style.box(Style.LIT if last else Style.CARD, 9, [10, 5, 10, 6] if inline else [12, 7, 12, 8]) + sb.shadow_color = Color(0, 0, 0, 0.25) + sb.shadow_size = 1 + sb.shadow_offset = Vector2(0, 3) + if last: + Style.bordered(sb, 2, Style.BRASS) + sb.set_expand_margin_all(2) + if inline: + sb.bg_color = sb.bg_color.darkened(0.04) + p.add_theme_stylebox_override("panel", sb) + p.size_flags_vertical = Control.SIZE_SHRINK_CENTER + p.mouse_filter = Control.MOUSE_FILTER_PASS + var v := VBoxContainer.new() + v.add_theme_constant_override("separation", 1) + p.add_child(v) + var plain := RulesView.plain(main) + var caption := TrayText.caption_for(step, main.data, plain) + var has_why := index >= 0 and WhyPopover.has_why(steps, index) + var has_details := main.details().step_has_details(step) + if has_details: + caption += " " + RichText.INFO_MARK + var cap := Style.make_label(caption, Style.body(), 11 if inline else 12, Style.MUTED) + cap.mouse_filter = Control.MOUSE_FILTER_IGNORE + v.add_child(cap) + var raw := str(step["text"]) + if str(step.get("kind", "")) == RollTable.KIND_SHEET: + raw = TrayText.one_line(raw) + if step.has("answer") and Formatter.strip_tags(raw).strip_edges() == "": + raw = "[i]no answer[/i]" + var shown := RichText.decorate(raw) + var body := RichText.display_label(shown, 16 if inline else 20, Style.DANGER_INK if step.get("stop", false) else Style.INK) + if Formatter.strip_tags(shown).length() > 56: + body.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + body.custom_minimum_size = Vector2(420, 0) + RichText.hook_hover(body, main) + v.add_child(body) + var fx: Array = step.get("effects", []) + if not fx.is_empty(): + v.add_child(_effect_lines(TrayText.effect_lines_for(step, main.data, plain))) + if has_why: + var wb := _why_button() + wb.pressed.connect(func() -> void: tray.open_why(index, wb)) + tray.why_buttons[index] = wb + v.add_child(wb) + if has_details or has_why: + p.mouse_entered.connect(func() -> void: + if not tray.why_popover().visible: + main.details().show_step(p, step, steps, index)) + return p + + +## The small "Why this?" pill under a chip. +static func _why_button() -> Button: + var b := Button.new() + b.text = "Why this?" + b.tooltip_text = "What decided this step" + b.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN + b.focus_mode = Control.FOCUS_NONE + var n := Style.bordered(Style.box(Color.WHITE, 10, [9, 1, 9, 2]), 1, Style.RULE) + var h := Style.bordered(Style.box(Style.LIT, 10, [9, 1, 9, 2]), 1, Style.BRASS_DARK) + Style.skin_button(b, n, h, h, Style.COPPER_DARK, Style.INK) + b.add_theme_font_override("font", Style.body_bold()) + b.add_theme_font_size_override("font_size", 12) + return b + + +## The effect log under a chip: a few compact lines, errors in red. +static func _effect_lines(fx: Array) -> Control: + var box := VBoxContainer.new() + box.add_theme_constant_override("separation", 0) + box.mouse_filter = Control.MOUSE_FILTER_IGNORE + var shown := 0 + var errors := 0 + for l: Variant in fx: + var d: Dictionary = l if l is Dictionary else {"text": str(l)} + var bad: bool = d.get("error", false) + if bad: + errors += 1 + # Errors are always listed; ordinary lines up to EFFECT_LINES. + if shown >= EFFECT_LINES and not bad: + continue + var lab := Style.make_label(("⚠ " if bad else "") + str(d.get("text", "")), Style.body_bold() if bad else Style.body(), 12, + Style.DANGER_INK if bad else Style.COPPER_DARK) + lab.mouse_filter = Control.MOUSE_FILTER_IGNORE + lab.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS + lab.custom_minimum_size.x = 0 + box.add_child(lab) + shown += 1 + var more := fx.size() - shown + if more > 0: + box.add_child(Style.make_label("+%d more" % more, Style.body(), 11, Style.MUTED)) + var tip := Effects.log_text(fx) + box.tooltip_text = "\n".join(tip) + return box + + +## The brass pipe piece between two chips (thinner for an inline step). +static func link(inline: bool = false) -> Control: + var l := Panel.new() + var sb := Style.box(Style.BRASS) + sb.border_width_top = 2 + sb.border_width_bottom = 2 + sb.border_color = Style.BRASS_DARK + if inline: + sb = Style.box(Color(Style.BRASS, 0.55)) + l.add_theme_stylebox_override("panel", sb) + l.custom_minimum_size = Vector2(16, 4) if inline else Vector2(22, 8) + l.size_flags_vertical = Control.SIZE_SHRINK_CENTER + l.mouse_filter = Control.MOUSE_FILTER_IGNORE + return l + + +## A dashed placeholder chip for the question that is open right now. +static func asking_chip(title: String) -> Control: + var p := PanelContainer.new() + var sb := Style.box(Color(1, 1, 1, 0.05), 9, [12, 7, 12, 8]) + Style.bordered(sb, 1, Color(Style.BRASS, 0.6)) + p.add_theme_stylebox_override("panel", sb) + p.size_flags_vertical = Control.SIZE_SHRINK_CENTER + var v := VBoxContainer.new() + v.add_theme_constant_override("separation", 1) + p.add_child(v) + v.add_child(Style.make_label(title, Style.body(), 12, Style.ON_FELT_MUTED)) + v.add_child(Style.make_label("Waiting for your answer…", Style.display(), 20, Style.BRASS)) + return p + + +## "+N earlier steps" (or "Hide earlier steps") at the start of a long chain. +static func earlier_toggle(tray: ResultTray, first: int, total: int) -> Control: + var b := Button.new() + if tray.expanded: + b.text = "Hide earlier steps" if first == 0 else "Hide earlier steps (%s not shown)" % TrayText.thousands(first) + else: + b.text = "+%s earlier steps" % TrayText.thousands(first) + b.tooltip_text = "This chain has %s steps" % TrayText.thousands(total) + b.size_flags_vertical = Control.SIZE_SHRINK_CENTER + var n := Style.bordered(Style.box(Color(1, 1, 1, 0.04), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16)) + var h := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 8, [12, 6, 12, 6]), 1, Color(Style.BRASS, 0.5)) + Style.skin_button(b, n, h, h, Style.ON_FELT_MUTED, Style.ON_FELT) + b.add_theme_font_size_override("font_size", 14) + b.pressed.connect(func() -> void: + tray.expanded = not tray.expanded + tray.render() + ) + var wrap := HBoxContainer.new() + wrap.add_theme_constant_override("separation", 0) + wrap.add_child(b) + var gap := Control.new() + gap.custom_minimum_size = Vector2(10, 0) + wrap.add_child(gap) + return wrap diff --git a/ui/tray_chips.gd.uid b/ui/tray_chips.gd.uid new file mode 100644 index 0000000..a526d28 --- /dev/null +++ b/ui/tray_chips.gd.uid @@ -0,0 +1 @@ +uid://u0s6b77l6g77 diff --git a/ui/tray_text.gd b/ui/tray_text.gd new file mode 100644 index 0000000..45c6940 --- /dev/null +++ b/ui/tray_text.gd @@ -0,0 +1,134 @@ +class_name TrayText +extends RefCounted +## The words of ResultTray's chips: captions, effect lines and the sheet +## headline's step. Static, so they can be tested without a tray. + + +## The muted line above a chip's text: table name and how it got its result. +## With `plain`, rules read in plain words ("Loot · Tier 1 · rolled 4 on 1D + +## Tier", "Force the gate · rolled 7, +1 → 8"), labelled from `board`. +static func caption_for(step: Dictionary, board: TowerBoard = null, plain: bool = false) -> String: + var caption := Formatter.strip_tags(str(step["table"])) + var num: String = str(step.get("num", "")) + var ins: Variant = step.get("inputs") + if ins is Dictionary: + for nm: Variant in ins: + if plain: + caption += " · %s %s" % [Describe.label(str(nm), board), Expr.format_value(ins[nm])] + else: + caption += " · %s=%s" % [nm, Expr.format_value(ins[nm])] + match str(step.get("kind", "")): + RollTable.KIND_CHECK: + var c: Variant = step.get("check") + if c is Dictionary: + var mod := int(c.get("mod", 0)) + var ms := "" + if mod != 0: + ms = ("+%d" % mod) if mod > 0 else (Describe.MINUS + str(-mod)) + if plain: + caption += " · rolled %s%s → %s" % [Expr.format_value(c.get("nat")), (", " + ms) if ms != "" else "", Expr.format_value(c.get("total"))] + else: + caption += " · %s%s = %s vs %s" % [Expr.format_value(c.get("nat")), ms.replace(Describe.MINUS, "-"), Expr.format_value(c.get("total")), Expr.format_value(c.get("target"))] + RollTable.KIND_CHOICE: + if step.get("cancelled", false): + pass + elif step.has("answer"): + caption += " · answered" + elif step.get("picked", false): + caption += " · picked" + elif step.get("random", false): + caption += " · random" + if num != "": + caption += ", rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))] + RollTable.KIND_LOOP: + if step.has("pass"): + caption += " · pass %s" % str(step["pass"]) + elif step.get("after", false): + caption += " · afterwards" + RollTable.KIND_SHEET: + caption += " · sheet" + RollTable.KIND_ROUTER: + if step.has("case"): + var said := false + if plain and board != null: + var rt := board.get_table(str(step.get("table_id", ""))) + var k := int(step["case"]) + if rt != null and k >= 0 and k < rt.entries.size(): + caption += " · " + RulesView.cut(RulesView.case_label(rt.entries[k], board, true), 44) + said = true + if not said: + caption += " · case %d" % (int(step["case"]) + 1) + _: + if num != "": + var dl := str(step.get("dice", "d%d" % int(step.get("die", 0)))) + if plain and dl.contains(" "): + dl = RulesView.cut(Describe.dice(dl, board), 30) + caption += " · rolled %s on %s" % [num, dl] + if step.get("reshuffled", false): + caption += " · deck reshuffled" + if str(step.get("save_as", "")) != "": + if plain: + caption += " · saved as %s" % Describe.label(str(step["save_as"]), board) + else: + caption += " · saved as {%s}" % step["save_as"] + return caption + + +## A step's effect lines for its chip: in plain words, one per value that +## changed ("Luck 2 → 1", "Town = Millbrook", "Cleared all Skills (3)") from +## its why facts, then any errors from its log; else the log as it is. +static func effect_lines_for(step: Dictionary, board: TowerBoard, plain: bool) -> Array: + var fx: Array = step.get("effects", []) + if not plain or not (step.get("why") is Array): + return fx + var out: Array = [] + for f: Variant in step["why"]: + if f is Dictionary and str(f.get("type", "")) == "effect": + out.append({"text": effect_fact_line(f, board)}) + if out.is_empty(): + return fx + for l: Variant in fx: + if l is Dictionary and (l as Dictionary).get("error", false): + out.append(l) + return out + + +## "Luck 2 → 1", "Town = Millbrook", "Loot cleared", "Cleared all Skills (3)". +static func effect_fact_line(f: Dictionary, board: TowerBoard) -> String: + var lab := Describe.label(str(f.get("var", "")), board) + if f.has("count"): + return "Cleared all %s (%s)" % [lab, Expr.format_value(f["count"])] + var before: Variant = f.get("before") + var after: Variant = f.get("after") + if after == null: + return "%s cleared" % lab + var a := Expr.format_value(after) + if before == null or Expr.format_value(before) == "": + return "%s = %s" % [lab, a if a != "" else "(none)"] + return "%s %s → %s" % [lab, Expr.format_value(before), a if a != "" else "(none)"] + + +## The first line of a (sheet's) multi-line text, with "…" when there's more. +static func one_line(text: String) -> String: + var nl := text.find("\n") + if nl < 0: + return text + return Formatter.close_open_tags(text.substr(0, nl)) + " …" + + +## The last sheet step of a chain (the headline), or {}. +static func sheet_step(steps: Array) -> Dictionary: + for k in range(steps.size() - 1, -1, -1): + var s: Dictionary = steps[k] + if str(s.get("kind", "")) == RollTable.KIND_SHEET and not s.get("stop", false): + return s + return {} + + +static func thousands(n: int) -> String: + var s := str(n) + var out := "" + while s.length() > 3: + out = "," + s.substr(s.length() - 3) + out + s = s.substr(0, s.length() - 3) + return s + out diff --git a/ui/tray_text.gd.uid b/ui/tray_text.gd.uid new file mode 100644 index 0000000..0724df7 --- /dev/null +++ b/ui/tray_text.gd.uid @@ -0,0 +1 @@ +uid://mvmiep4jv2bh