From 44a814cba92703990f7989acb372bc98ae2238fb Mon Sep 17 00:00:00 2001 From: RobinFiredrake Date: Sun, 8 Nov 2026 21:30:55 -0600 Subject: [PATCH] Plain Build display: plain rules on cards, pipes and tray, Why this?, check/collection/inputs visuals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - RulesView (ui/rules_view.gd): plain-or-text helpers over Describe, reading Main.rules_plain() when present (else StateStore, else plain; --rules=text for screenshots) and refreshing on Main.rules_view_changed. - Cards: effect chips, router cases, option sources, show_if, loop rules, expression dice and variable kinds read in plain words. Build cards drop the inline effects / show_if / condition / details editors for plain chips; result text and names stay inline. Row clicks call main.select_result(); the selected row gets a copper bar (set_selected_entry / inspector_selection). - Check cards: 2D badge, the rule as a sentence, Success / Failure outlets. Collection cards: live members and "+ Add" (main.select_card). Inputs: a dashed "Input Tier · starts at 1" box. - Pipe labels via Describe.pipe, nudged apart and cut to the gap. - Tray: plain captions (inputs, checks, cases), effect lines from why facts, and a "Why this?" button opening a WhyPopover; hovers show the same reasons. - Previews and the choice pop-up read conditions, effects and option sources in plain words. Style.rules_switch() for the Plain words / Text switch. - Describe: empty text reads "empty" ("Loot is not empty"). - tests/test_plain_display.gd; option and choice tests pin the Text view where they check stored text. Co-Authored-By: Claude Opus 5.5 --- core/describe.gd | 3 +- tests/test_choice_dialog.gd | 10 + tests/test_options.gd | 21 +- tests/test_plain_display.gd | 408 ++++++++++++++++++ tests/test_plain_display.gd.uid | 1 + ui/choice_dialog.gd | 51 ++- ui/details_popup.gd | 86 +++- ui/pipe_layer.gd | 48 ++- ui/result_tray.gd | 179 +++++++- ui/rules_view.gd | 147 +++++++ ui/rules_view.gd.uid | 1 + ui/style.gd | 30 ++ ui/table_card.gd | 734 +++++++++++++++++++------------- ui/table_preview.gd | 75 +++- ui/why_popover.gd | 197 +++++++++ ui/why_popover.gd.uid | 1 + 16 files changed, 1642 insertions(+), 350 deletions(-) create mode 100644 tests/test_plain_display.gd create mode 100644 tests/test_plain_display.gd.uid create mode 100644 ui/rules_view.gd create mode 100644 ui/rules_view.gd.uid create mode 100644 ui/why_popover.gd create mode 100644 ui/why_popover.gd.uid diff --git a/core/describe.gd b/core/describe.gd index 42e8f5a..b2f43a3 100644 --- a/core/describe.gd +++ b/core/describe.gd @@ -243,7 +243,8 @@ static func _value(tok: String, L: Dictionary) -> String: if s == "false": return "no" if Builder.is_text_literal(s): - return Builder.unquote(s) + var u := Builder.unquote(s) + return u if u != "" else "empty" if s.begins_with("-") and Expr.is_number(s.substr(1)): return MINUS + s.substr(1) if Expr.is_number(s): diff --git a/tests/test_choice_dialog.gd b/tests/test_choice_dialog.gd index e098775..32b285c 100644 --- a/tests/test_choice_dialog.gd +++ b/tests/test_choice_dialog.gd @@ -132,6 +132,16 @@ func _test_preview_content() -> void: if d == null: return _check(d.board == main.data, "the dialog finds the board") + # Plain words (the default): effects and counts read as phrases. + _check(d.plain, "previews read in plain words by default") + var pp := d.preview_for_option(0) + _check(_has(pp, "Gold −5") and _has(pp, "WHEN THIS COMES UP"), "the plain preview lists the option's effects in words") + pp.free() + var pq := d.preview_for_option(1) + _check(_has(pq, "×Terms"), "the plain preview names an expression count by its label") + pq.free() + # The rest checks the stored text (Text view). + d.plain = false # Option 1 pipes to a ranged table, twice. var p := d.preview_for_option(0) _check(p != null, "an option that pipes on has a preview") diff --git a/tests/test_options.gd b/tests/test_options.gd index ab83e39..447641a 100644 --- a/tests/test_options.gd +++ b/tests/test_options.gd @@ -466,6 +466,10 @@ func _test_dialog() -> void: if c is Label and (c as Label).text == "1" and c.has_meta("option_value"): badge = true _check(badge, "the value shows as a badge") + var pp := d.preview_for_option(1) + _check(pp != null and _has(pp, "Chosen value +1") and _has(pp, "Gun Combat · level 2"), "the plain preview names the option, its level and the effect in words") + pp.free() + d.plain = false var p := d.preview_for_option(1) _check(p != null and _has(p, "@[option] += 1") and _has(p, "Next step"), "a dynamic option's preview shows the Chosen entry's effects and pipes") _check(_has(p, "skill_gun_combat"), "the preview names the variable behind the option") @@ -480,14 +484,20 @@ func _test_dialog() -> void: _check(got[0] != null and int(got[0]) == int((req["options"][2] as Dictionary)["index"]), "number keys answer the dynamic options") await process_frame # TablePreview describes the card. - var tp := TablePreview.build(b, "raise") + var tpp := TablePreview.build(b, "raise", {"plain": true}) + _check(_has(tpp, "Options: your Skill values"), "the plain preview says where the options come from") + tpp.free() + var tp := TablePreview.build(b, "raise", {"plain": false}) _check(_has(tp, "Options: each @skill_* that's set"), "the preview describes where the options come from") _check(_has(tp, "Chosen"), "the preview names the Chosen entry") tp.free() none.show_if = "@terms > 2" - tp = TablePreview.build(b, "raise") + tp = TablePreview.build(b, "raise", {"plain": false}) _check(_has(tp, "only if @terms > 2"), "the preview shows show_if conditions") tp.free() + tp = TablePreview.build(b, "raise", {"plain": true}) + _check(_has(tp, "only if Terms is more than 2"), "the plain preview shows show_if in words") + tp.free() # ---------------------------------------------------------------- settings and card @@ -537,6 +547,8 @@ func _test_card() -> void: main.data.tables.append(t) main.persistent_vars["skill_pilot"] = {"value": 1, "source": ""} main.persistent_vars["skill_admin"] = {"value": 0, "source": ""} + # These checks read the stored rule text (the Text view). + RulesView.fallback_plain = false main._rebuild_cards() await process_frame var card := main.card_for("raise_card") @@ -547,9 +559,10 @@ func _test_card() -> void: main.set_mode(Main.Mode.BUILD) await process_frame card = main.card_for("raise_card") - card._open_show_if["none"] = true + _check(_has(card, "only if @terms > 2"), "Build mode shows show_if under the option (edited in the inspector)") + RulesView.fallback_plain = true card.rebuild() - _check(_has(card, "Show only if"), "Build mode edits show_if under the option") + _check(_has(card, "only if Terms is more than 2"), "and in plain words in the Plain view") var d := TableSettingsDialog.new(t) main.add_child(d) await process_frame diff --git a/tests/test_plain_display.gd b/tests/test_plain_display.gd new file mode 100644 index 0000000..ba23036 --- /dev/null +++ b/tests/test_plain_display.gd @@ -0,0 +1,408 @@ +extends SceneTree +## The display side of Plain Build (docs/PLAIN.md §6): plain chips and lines +## on cards and their text-mode twins, the switch refreshing them, pipe +## labels, check / collection / inputs visuals, "Why this?" sentences and the +## tray's button, and Build-mode row selection. +## Run: godot --headless --path . -s res://tests/test_plain_display.gd -- --sample +## +## Main here is a small subclass with the hooks the Build inspector adds +## (rules_plain(), rules_view_changed, select_result(), select_card()), so the +## display can be tested on its own. + +var _failures := 0 +var main: Main + +const FAKE_MAIN := """extends Main +%s +var fake_plain := true +var picked: Array = [] +func rules_plain() -> bool: + return fake_plain +func select_result(tid: String, eid: String) -> void: + picked.append([tid, eid]) +func select_card(tid: String) -> void: + picked.append(["card", tid]) +""" + +const BOARD := { + "format_version": 2, "id": "plain-display", "name": "Plain display", + "tables": [ + {"id": "v_str", "name": "Strength", "kind": "variable", "var_name": "str", "initial": "9", "x": 40, "y": 600, "entries": []}, + {"id": "v_luck", "name": "Luck", "kind": "variable", "var_name": "luck", "initial": "2", "x": 360, "y": 600, "entries": []}, + {"id": "gate", "name": "Force the gate", "kind": "check", "check_dice": "2d6", "check_mod": "dm(@str)", "check_target": "8", + "x": 40, "y": 40, "entries": [ + {"id": "ok", "text": "the bars give", "pipes": ["beyond"]}, + {"id": "no", "text": "it holds", "effects": "@luck -= 1"}]}, + {"id": "beyond", "name": "Beyond the gate", "x": 380, "y": 40, "entries": [ + {"id": "e1", "text": "A storeroom", "pipes": [{"table": "loot", "with": {"tier": "1"}}]}, + {"id": "e2", "text": "The warden's vault", "effects": "@luck -= 1", + "pipes": [{"table": "loot", "when": "@luck >= 2", "with": {"tier": "3"}}, {"table": "learn", "otherwise": true}]}]}, + {"id": "loot", "name": "Loot", "dice": "1d6 + tier", "inputs": [{"name": "tier", "label": "Tier", "default": "1"}], + "x": 760, "y": 40, "entries": [ + {"id": "e1", "text": "A purse of coins", "range": [2, 3]}, + {"id": "e2", "text": "A curio", "range": [4, 6]}, + {"id": "e3", "text": "A relic", "range": [7, 9], "effects": "@skill_recon += 1"}]}, + {"id": "skills", "name": "Skills", "kind": "variable", "var_type": "collection", "var_name": "skill", "x": 760, "y": 600, "entries": []}, + {"id": "learn", "name": "Learn from it", "kind": "choice", "prompt": "Raise one of your skills.", + "options_from": "@skill_*", "options_where": "option_value >= 1", "x": 1100, "y": 40, "entries": [ + {"id": "chosen", "text": "Chosen", "effects": "@[option] += 1"}, + {"id": "rest", "text": "Rest instead", "show_if": "@luck <= 1"}]}, + {"id": "climb", "name": "Climb out", "kind": "router", "x": 380, "y": 400, "entries": [ + {"id": "c1", "text": "Haul yourself up", "when": "@str >= 10"}, + {"id": "c2", "text": "Slip back", "effects": "@luck -= 1"}]}, + {"id": "rounds", "name": "Rounds", "kind": "loop", "loop": "while", "loop_expr": "@luck > 0", "x": 1100, "y": 400, + "entries": [{"id": "e1", "text": "Each time"}, {"id": "e2", "text": "Afterwards"}]}, + ]} + + +func _init() -> void: + if not OS.get_cmdline_user_args().has("--sample"): + print("Run with -- --sample so the test can't touch saved data.") + quit(2) + return + _test_why_sentences() + _test_rules_view_helpers() + main = _make_main() + root.add_child(main) + for i in 5: + await process_frame + if main._saving_enabled: + print("Saving is enabled; refusing to roll.") + quit(2) + return + main.rng.seed = 7 + main.data.load_json(JSON.stringify(BOARD)) + main.current = {} + main._rebuild_cards() + main.tray.render() + for i in 3: + await process_frame + + _test_card_chips() + await _test_switch() + _test_pipe_labels() + _test_router_and_choice() + await _test_check_card() + await _test_collection_and_inputs() + await _test_tray_why() + await _test_roll_why() + await _test_build_rows() + + print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) + quit(1 if _failures else 0) + + +## Main with the inspector's hooks (only the signal is skipped when Main +## already declares it). +func _make_main() -> Main: + var has_signal := false + for s: Dictionary in (load("res://ui/main.gd") as Script).get_script_signal_list(): + if str(s["name"]) == "rules_view_changed": + has_signal = true + var sc := GDScript.new() + sc.source_code = FAKE_MAIN % ("" if has_signal else "signal rules_view_changed") + sc.reload() + var m: Main = sc.new() + m.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + return m + + +func _set_plain(on: bool) -> void: + main.set("fake_plain", on) + main.emit_signal("rules_view_changed") + + +# ---------------------------------------------------------------- helpers + +func _texts(n: Node, out: PackedStringArray = PackedStringArray()) -> PackedStringArray: + if n is Label: + out.append((n as Label).text) + elif n is RichTextLabel: + out.append(Formatter.strip_tags((n as RichTextLabel).text)) + elif n is Button: + out.append((n as Button).text) + elif n is LineEdit: + out.append((n as LineEdit).text) + for c in n.get_children(): + _texts(c, out) + return out + + +func _has(n: Node, needle: String) -> bool: + for t in _texts(n): + if t.contains(needle): + return true + return false + + +func _with_meta(n: Node, key: String, out: Array = []) -> Array: + if n.has_meta(key): + out.append(n) + for c in n.get_children(): + _with_meta(c, key, out) + return out + + +func _chips(card: TableCard) -> PackedStringArray: + var out := PackedStringArray() + for c: Node in _with_meta(card, "effects_chip"): + out.append(str(c.get_meta("effects_chip"))) + return out + + +func _check(ok: bool, what: String) -> void: + if not ok: + _failures += 1 + print(" ✗ ", what) + + +func _eq(got: Variant, want: Variant, what: String) -> void: + if got != want: + _failures += 1 + print(" ✗ %s: got %s, want %s" % [what, var_to_str(got), var_to_str(want)]) + + +# ---------------------------------------------------------------- pure parts + +func _board() -> TowerBoard: + var b := TowerBoard.new() + b.load_json(JSON.stringify(BOARD)) + return b + + +func _test_why_sentences() -> void: + var b := _board() + var check := {"type": "check", "dice": "2d6", "mod_expr": "dm(@str)", "target_expr": "8", "faces": [3, 4], + "nat": 7, "mod": 1, "total": 8, "target": 8, "cmp": "ge", "success": true} + var when_f := {"type": "when", "to": "loot", "expr": "@luck >= 2", "values": {"@luck": 1}, "result": false} + var other := {"type": "otherwise", "to": "learn", "result": true} + var case_f := {"type": "case", "index": 0, "expr": "@str >= 10", "values": {"@str": 9}, "result": false} + var eff := {"type": "effect", "var": "@luck", "op": "-=", "before": 2, "after": 1} + var inp := {"type": "input", "name": "tier", "value": 3, "from": "pipe"} + _eq(Describe.why(check, b), "Rolled 3 + 4 = 7, +1 = 8: needed 8 or more, success", "check fact") + _eq(Describe.why(when_f, b), "Skipped Loot because Luck was 1 (needs 2 or more)", "when fact") + _eq(Describe.why(other, b), "Took Learn from it because no condition was true", "otherwise fact") + _eq(Describe.why(case_f, b), "Case 1 didn't match because Strength was 9 (needs 10 or more)", "case fact") + _eq(Describe.why(eff, b), "Luck went from 2 to 1", "effect fact") + _eq(Describe.why(inp, b), "Tier was 3 (from the pipe)", "input fact") + _check(Describe.why(when_f, b, false).contains("@luck >= 2"), "text mode keeps the rule as written") + # A step's reasons: the parent's pipe choices aimed at it, the parent's + # effects on the values they read, then its own facts. + var steps := [ + {"table": "Beyond the gate", "table_id": "beyond", "text": "The warden's vault", "depth": 0, "why": [eff, when_f, other]}, + {"table": "Learn from it", "table_id": "learn", "text": "Rest instead", "depth": 1, "why": [inp]}, + {"table": "Old", "table_id": "learn", "text": "From an old record", "depth": 0}, + ] + var ls := WhyPopover.why_lines(steps, 1, b, true) + _eq(ls.size(), 2, "the child's reasons: the otherwise choice and its own input") + _check(ls.size() == 2 and ls[0].begins_with("Took Learn from it") and ls[1].begins_with("Tier was 3"), "reasons come in order") + var lp := WhyPopover.why_lines(steps, 0, b, true) + _check(lp.size() == 3 and lp[0] == "Luck went from 2 to 1.", "a step's own facts end with full stops") + var steps2 := [steps[0], {"table": "Loot", "table_id": "loot", "text": "A curio", "depth": 1}] + var lw := WhyPopover.why_lines(steps2, 1, b, true) + _check(lw.size() == 2 and lw[0].begins_with("The warden's vault: Luck went from 2 to 1") and lw[1].begins_with("Skipped Loot"), + "the parent's effect on a value its condition read comes first, named by the parent") + _check(not WhyPopover.has_why(steps, 2), "an old record without facts has no reasons") + _check(WhyPopover.title_for(steps[1]) == "Why Learn from it · Rest instead", "the pop-over title") + + +func _test_rules_view_helpers() -> void: + var b := _board() + var beyond := b.get_table("beyond") + var vault := beyond.entries[1] + _eq(RulesView.effects_line(vault.effects, b, beyond, true), "Luck −1", "plain effects line") + _eq(RulesView.effects_line(vault.effects, b, beyond, false), "@luck -= 1", "text effects line") + _eq(RulesView.effects_line("@a += 1; @b = 2; @c -= 3", b, null, true), "A +1 · B = 2 · +1", "long effects show two and a count") + _eq(RulesView.loop_rule(b.get_table("rounds"), b, true), "repeat while Luck is more than 0", "plain loop rule") + _eq(RulesView.loop_rule(b.get_table("rounds"), b, false), "while @luck > 0", "text loop rule") + var times := RollTable.create(RollTable.KIND_LOOP, "t", "T") + times.loop_expr = "@terms" + _eq(RulesView.loop_rule(times, b, true), "× Terms", "a count loop reads × Terms") + _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") + + +# ---------------------------------------------------------------- cards + +func _test_card_chips() -> void: + var beyond := main.card_for("beyond") + _check(_chips(beyond).has("Luck −1"), "an effects chip reads Luck −1") + var loot := main.card_for("loot") + _check(_has(loot, "Roll 1D + Tier · 3 ranges"), "expression dice read in words under the title") + _check(_has(main.card_for("rounds"), "repeat while Luck is more than 0"), "a loop's rule reads in words") + _check(_has(main.card_for("v_luck"), "Number · kept between rolls"), "a variable card says it's kept") + + +func _test_switch() -> void: + _set_plain(false) + await process_frame + var beyond := main.card_for("beyond") + _check(_chips(beyond).has("@luck -= 1"), "Text view: the chip shows the stored statement") + _check(_has(main.card_for("rounds"), "while @luck > 0"), "Text view: the loop rule as written") + _check(_has(main.card_for("learn"), "Options from @skill_* · where option_value >= 1"), "Text view: the options source as written") + _check(_has(main.card_for("loot"), "input tier · default 1"), "Text view: inputs by name") + main.board.pipes._process(0.0) + _check(main.board.pipes._drawn_state.back() == false, "the pipe layer redraws for the Text view") + _set_plain(true) + await process_frame + _check(_chips(main.card_for("beyond")).has("Luck −1"), "switching back refreshes the chips") + main.board.pipes._process(0.0) + _check(main.board.pipes._drawn_state.back() == true, "and the pipes") + + +func _test_pipe_labels() -> void: + var b := main.data + var vault := b.get_table("beyond").entries[1] + _eq(RulesView.pipe_label(vault, "loot", b, true), "Tier 3 · only if Luck is 2 or more", "plain pipe label") + _eq(RulesView.pipe_label(vault, "learn", b, true), "otherwise", "otherwise label") + _eq(RulesView.pipe_label(vault, "loot", b, false), "tier=3 if @luck >= 2", "text pipe label") + _eq(RulesView.pipe_label(b.get_table("gate").entries[0], "beyond", b, true), "", "a plain pipe has no label") + + +func _test_router_and_choice() -> void: + var climb := main.card_for("climb") + _check(_has(climb, "if Strength is 10 or more"), "a router case reads in words") + _check(_has(climb, "Otherwise"), "the last case reads Otherwise") + var learn := main.card_for("learn") + _check(_has(learn, "Options: your Skills, level 1 or more"), "a choice's options source reads in words") + _check(_has(learn, "only if Luck is at most 1"), "show_if reads only if …") + _check(_chips(learn).has("Chosen skill +1"), "the Chosen row's effect names the collection's member") + + +func _test_check_card() -> void: + var gate := main.card_for("gate") + _check(_has(gate, "Roll 2D + Strength modifier, need 8 or more"), "the check card's sentence") + _check(_has(gate, "2D"), "the 2D badge") + _check(_has(gate, "Success · the bars give") and _has(gate, "Failure · it holds"), "Success and Failure outlets with their labels") + _check(_has(gate, "8+") and _has(gate, "≤7"), "outlet ranges") + await process_frame + for eid in ["ok", "no"]: + _check(not gate.anchor_for(eid).is_empty(), "the %s outlet has a pipe anchor" % eid) + var ok_y: float = gate.anchor_for("ok").get("pos", Vector2.ZERO).y + var no_y: float = gate.anchor_for("no").get("pos", Vector2.ZERO).y + _check(no_y > ok_y, "Failure sits below Success") + + +func _test_collection_and_inputs() -> void: + main.persistent_vars["skill_mechanic"] = {"value": 2, "source": ""} + main.persistent_vars["skill_athletics"] = {"value": 1, "source": ""} + main.refresh_live() + var skills := main.card_for("skills") + var members := _with_meta(skills, "member") + var names := [] + for m: Node in members: + names.append(str(m.get_meta("member"))) + _eq(names, ["@skill_athletics", "@skill_mechanic", "@skill_recon"], "members: set ones by label, then ones the rules name") + _check(_has(skills, "Mechanic") and _has(skills, "2") and _has(skills, "—"), "members show live values") + _check(_has(skills, "Collection · kept between rolls"), "the collection's kind line") + main.persistent_vars["skill_mechanic"] = {"value": 3, "source": ""} + main.refresh_live() + _check(_has(skills, "3"), "values refresh live") + var loot := main.card_for("loot") + _check(not _with_meta(loot, "inputs_box").is_empty(), "a card with inputs has the dashed box") + _check(_has(loot, "Input Tier · starts at 1"), "the inputs box reads Input Tier · starts at 1") + await process_frame + for e in loot.table.entries: + _check(not loot.anchor_for(e.id).is_empty(), "every row of the inputs card has an anchor") + + +func _test_tray_why() -> void: + var b := main.data + main.current = {"root": "beyond", "root_name": "Beyond the gate", "done": true, "steps": [ + {"table": "Beyond the gate", "table_id": "beyond", "entry_id": "e2", "text": "The warden's vault", "depth": 0, "num": "2", "dice": "d2", + "effects": [{"text": "Luck −1 → 1"}], + "why": [{"type": "roll", "pick": "dice", "dice": "d2", "total": 2, "faces": [2]}, + {"type": "effect", "var": "@luck", "op": "-=", "before": 2, "after": 1}, + {"type": "when", "to": "loot", "expr": "@luck >= 2", "values": {"@luck": 1}, "result": false}, + {"type": "otherwise", "to": "learn", "result": true}]}, + {"table": "Old step", "table_id": "climb", "text": "Slip back", "depth": 1}, + ]} + main.tray.render() + await process_frame + _check(main.tray.why_buttons.has(0), "a step with facts gets a Why this? button") + _check(not main.tray.why_buttons.has(1), "a step without facts (old history) gets none") + _check(_has(main.tray, "Luck 2 → 1"), "the chip's effect line reads Luck 2 → 1") + (main.tray.why_buttons[0] as Button).emit_signal("pressed") + await process_frame + var pop := main.tray.why_popover() + _check(pop.visible, "the button opens the pop-over") + _check(pop.lines.size() == 4 and pop.lines[2] == "Skipped Loot because Luck was 1 (needs 2 or more).", "it lists the step's reasons") + _check(_has(pop, "WHY BEYOND THE GATE · THE WARDEN'S VAULT"), "it's titled by the step") + (main.tray.why_buttons[0] as Button).emit_signal("pressed") + _check(not pop.visible, "pressing again closes it") + # Text view: the same facts as rule text, and the effect log as it is. + _set_plain(false) + await process_frame + _check(_has(main.tray, "Luck −1 → 1"), "Text view keeps the effect log") + (main.tray.why_buttons[0] as Button).emit_signal("pressed") + _check(main.tray.why_popover().lines.size() == 4 and main.tray.why_popover().lines[2].contains("@luck >= 2"), "Text view reasons quote the rule") + main.tray.why_popover().close() + _set_plain(true) + await process_frame + # Hover summaries carry the same reasons. + var why := DetailsPopup.why_bbcode(main.current["steps"], 0, b, true) + _check(why.contains("Skipped Loot because Luck was 1"), "hover pop-ups get the reasons too") + _check(DetailsPopup.why_bbcode(main.current["steps"], 1, b, true) == "", "and nothing for a step without facts") + var rules := DetailsPopup.rules_bbcode(b.get_table("beyond"), b.get_table("beyond").entries[1], b, true) + _check(rules.contains("Luck −1") and rules.contains("Tier 3 · only if Luck is 2 or more"), "an entry's hover summary reads in words") + + +func _test_roll_why() -> void: + main.current = {} + main.prompt_hook = func(_req: Dictionary) -> Variant: return 1 + main.start_roll("gate", true) + for i in 10: + await process_frame + var steps: Array = main.current.get("steps", []) + _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) + _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) + _check(not lines.is_empty() and lines[0].begins_with("Rolled ") and lines[0].contains("needed 8 or more"), "its reason reads the roll against the target") + var lit := "ok" if main.is_entry_lit("gate", "ok") else "no" + _check(main.is_entry_lit("gate", lit), "an outlet lights after the roll") + # A lit row's hover finds its step. + _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") + + +func _test_build_rows() -> void: + main.set_mode(Main.Mode.BUILD) + await process_frame + var beyond := main.card_for("beyond") + _check(_chips(beyond).has("Luck −1"), "Build rows show plain chips") + _check(not _has(beyond, "ƒ") and not _has(beyond, "Details"), "the inline effects / details editors are gone") + _check(_with_meta(beyond, "effects_chip").size() == 1, "one chip for the one entry with effects") + var climb := main.card_for("climb") + _check(not _with_meta(climb, "case_line").is_empty() and _has(climb, "if Strength is 10 or more"), "a Build router case shows its condition in words") + var row: Control = beyond.rows["e2"] + var ev := InputEventMouseButton.new() + ev.button_index = MOUSE_BUTTON_LEFT + ev.pressed = true + row.emit_signal("gui_input", ev) + _eq(main.get("picked").back(), ["beyond", "e2"], "clicking a result row calls select_result") + _eq(beyond.selected_entry(), "e2", "the row is selected") + var sb := row.get_theme_stylebox("panel") as StyleBoxFlat + _check(sb != null and sb.border_width_left == 3 and sb.border_color == Style.COPPER, "the selected row has a copper bar") + var gate := main.card_for("gate") + (gate.rows["ok"] as Control).emit_signal("gui_input", ev) + _eq(beyond.selected_entry(), "", "selecting on another card clears this one") + _eq(main.get("picked").back(), ["gate", "ok"], "check outlets are selectable too") + gate.set_selected_entry("no") + _eq(gate.selected_entry(), "no", "the inspector can set the selection directly") + var adds := _with_meta(main.card_for("skills"), "collection_add") + _check(adds.size() == 1 and (adds[0] as Button).text == "+ Add skill", "the collection card has + Add skill in Build") + if adds.size() == 1: + (adds[0] as Button).emit_signal("pressed") + _eq(main.get("picked").back(), ["card", "skills"], "+ Add selects the card for the inspector") + _check(_has(main.card_for("loot"), "Input Tier · starts at 1"), "the inputs box shows in Build too") + main.set_mode(Main.Mode.PLAY) + await process_frame diff --git a/tests/test_plain_display.gd.uid b/tests/test_plain_display.gd.uid new file mode 100644 index 0000000..29164df --- /dev/null +++ b/tests/test_plain_display.gd.uid @@ -0,0 +1 @@ +uid://c875lktcqrdsq diff --git a/ui/choice_dialog.gd b/ui/choice_dialog.gd index 619589f..36ebfef 100644 --- a/ui/choice_dialog.gd +++ b/ui/choice_dialog.gd @@ -20,6 +20,10 @@ extends ModalCard ## Options from variables (docs/LOGIC.md §2a) come after the fixed ones, with ## their value as a badge on the right; their preview is the Chosen entry's. ## +## Previews read rules in plain words (effects "Luck −1", pipe conditions +## "only if Luck is 2 or more", option sources) unless Main's rules view is +## Text (RulesView.plain); `plain` can also be set directly. +## ## The answer arrives through `reply.done`, a signal on a separate object so ## the waiting roll never hangs: closing or freeing the dialog in any way ## (Esc, the window closing, a new roll replacing this one) answers null, @@ -49,6 +53,8 @@ const PREVIEW_WIDTH := 350.0 var board: TowerBoard ## Board variables, so previews can show sheets filled in. var vars: Dictionary = {} +## Rules in plain words in the previews (from Main when it has a rules view). +var plain := true var minimized := false var preview_panel: PanelContainer var pill: PanelContainer @@ -236,11 +242,13 @@ func _build_text() -> void: func _ready() -> void: super._ready() - if board == null: - var m := get_parent() as Main - if m: - board = m.data - vars = m.persistent_vars + var m := get_parent() as Main + if board == null and m: + board = m.data + vars = m.persistent_vars + if m: + plain = RulesView.plain(m) + RulesView.watch(m, _on_rules_view_changed) _refresh_preview() if _spin: _spin.get_line_edit().grab_focus() @@ -259,6 +267,14 @@ func _ready() -> void: minimize.call_deferred() +func _on_rules_view_changed(_v: Variant = null) -> void: + var m := get_parent() as Main + if m: + plain = RulesView.plain(m) + _preview_for = -2 + _refresh_preview() + + ## Enter on the number or text field, or OK. func _confirm() -> void: if _spin: @@ -574,12 +590,18 @@ func preview_for_option(k: int) -> Control: box.add_child(heading) var any := false var o: Dictionary = (request.get("options", []) as Array)[k] if kind == "pick" else {} + var t := board.get_table(str(request.get("table_id", ""))) if o.get("dynamic", false): # The variable (or list item) behind a dynamic option, and its value. any = true var what := "option = %s" % str(o.get("option", "")) if str(o.get("value_text", "")) != "": what += " · value %s" % str(o["value_text"]) + if plain: + var src := RulesView.options_line(t, board, true) if t != null else "" + what = "%s%s" % [Formatter.strip_tags(str(o.get("label", o.get("option", "")))), (" · level %s" % o["value_text"]) if str(o.get("value_text", "")) != "" else ""] + if src != "": + what += "\n" + src var ol := Style.make_label(what, Style.body_bold(), 13, RichText.VAR_INK) ol.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART ol.mouse_filter = Control.MOUSE_FILTER_IGNORE @@ -590,13 +612,13 @@ func preview_for_option(k: int) -> Control: var d := RichText.label(RichText.decorate(det), 14, Style.INK, false) d.mouse_filter = Control.MOUSE_FILTER_IGNORE box.add_child(d) - var fx := Effects.split(e.effects) + var fx: Array = Describe.effects(e.effects, board, t) if plain else Array(Effects.split(e.effects)) if not fx.is_empty(): any = true box.add_child(_rule()) - box.add_child(section("Effects")) - for st in fx: - var l := Style.make_label(st, Style.body_bold(), 13, RichText.VAR_INK) + box.add_child(section("When this comes up" if plain else "Effects")) + for st: Variant in fx: + var l := Style.make_label(str(st), Style.body_bold(), 13, RichText.VAR_INK) l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART l.mouse_filter = Control.MOUSE_FILTER_IGNORE box.add_child(l) @@ -605,7 +627,14 @@ func preview_for_option(k: int) -> Control: shown.append(tid) any = true box.add_child(_rule()) - box.add_child(TablePreview.build(board, tid, {"count": e.count_text(tid), "vars": vars})) + var how := Describe.pipe(e, tid, board) if plain else PipeLayer._pipe_tag(e, tid) + if how != "": + var hl := Style.make_label(("Then: " if plain else "pipe: ") + how, Style.body_bold(), 12, Style.COPPER_DARK) + hl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + hl.mouse_filter = Control.MOUSE_FILTER_IGNORE + hl.set_meta("pipe_line", true) + box.add_child(hl) + box.add_child(TablePreview.build(board, tid, {"count": e.count_text(tid), "vars": vars, "plain": plain})) var mentioned: Array[String] = [] for name in TextExpander.references(e.text, func(n: String) -> String: return Roller.resolve(board, n)): var rid := Roller.resolve(board, name) @@ -616,7 +645,7 @@ func preview_for_option(k: int) -> Control: box.add_child(_rule()) box.add_child(section("Mentioned in the text")) for rid in mentioned: - box.add_child(TablePreview.build(board, rid, {"vars": vars})) + box.add_child(TablePreview.build(board, rid, {"vars": vars, "plain": plain})) if not any: box.free() return null diff --git a/ui/details_popup.gd b/ui/details_popup.gd index 73e61d7..ed40bcd 100644 --- a/ui/details_popup.gd +++ b/ui/details_popup.gd @@ -5,6 +5,11 @@ extends PanelContainer ## ## It ignores the mouse, so it never blocks clicks, stays inside the window, ## and hides itself as soon as the control that opened it is no longer hovered. +## +## Hover summaries follow RulesView.plain(main): an entry's effects, show_if, +## router condition and pipe labels read in plain words or as written, and a +## step of the last roll (a chip, or a lit row on a card) adds its "Why this?" +## reasons (WhyPopover.why_lines). const WIDTH := 300.0 const DELAY := 0.28 @@ -133,12 +138,69 @@ func show_table(owner: Control, tid: String, only_if_details: bool = false) -> v func show_entry(owner: Control, tid: String, eid: String) -> void: var t := main.data.get_table(tid) var e := t.find_entry(eid) if t else null - if e == null or e.details.strip_edges() == "": + if e == null: + return + var plain := RulesView.plain(main) + var parts := PackedStringArray() + if e.details.strip_edges() != "": + parts.append(e.details) + var rules := rules_bbcode(t, e, main.data, plain) + if rules != "": + parts.append(rules) + if main.is_entry_lit(tid, eid): + var found := step_for(tid, eid) + if not found.is_empty(): + var why := why_bbcode(found["steps"], int(found["index"]), main.data, plain) + if why != "": + parts.append(why) + if parts.is_empty(): return var shown := main.lit_text(tid, eid) if shown == "": shown = RichText.preview(e.text, main.data) - show_for(owner, _short(Formatter.strip_tags(shown)), e.details, Formatter.strip_tags(t.name)) + show_for(owner, _short(Formatter.strip_tags(shown)), "\n\n".join(parts), Formatter.strip_tags(t.name)) + + +## An entry's rules as short BBCode lines: "only if …", "Changes: Luck −1 · +## Gold + 2D", and "→ Loot: Tier 3 · only if Luck is 2 or more" for each pipe +## with options. Router conditions are on the row itself, so they're left out. +static func rules_bbcode(t: RollTable, e: TableEntry, board: TowerBoard, plain: bool) -> String: + var muted := Style.MUTED.to_html(false) + var lines := PackedStringArray() + if t.kind == RollTable.KIND_CHOICE and t.choice == "pick" and e.show_if.strip_edges() != "": + lines.append("[color=#%s]Offered[/color] %s" % [muted, RichText.plain(RulesView.show_if_line(e, board, plain))]) + if e.effects.strip_edges() != "": + var fx: Array = Describe.effects(e.effects, board, t) if plain else Array(Effects.split(e.effects)) + var ss := PackedStringArray() + for f: Variant in fx: + ss.append(RichText.plain(str(f))) + lines.append("[color=#%s]Changes:[/color] [b]%s[/b]" % [muted, " · ".join(ss)]) + for to in e.pipes: + var lab := Describe.pipe(e, to, board) if plain else PipeLayer._pipe_tag(e, to) + if lab == "": + continue + var target := board.get_table(to) if board else null + var nm := Formatter.strip_tags(target.name) if target else to + lines.append("[color=#%s]→ %s:[/color] %s" % [muted, RichText.plain(nm), RichText.plain(lab)]) + return "\n".join(lines) + + +## The "Why this?" reasons for steps[index] as a small BBCode section, or "". +static func why_bbcode(steps: Array, index: int, board: TowerBoard, plain: bool) -> String: + var ls := WhyPopover.why_lines(steps, index, board, plain) + if ls.is_empty(): + return "" + return "[color=#%s][b]WHY THIS?[/b][/color]\n%s" % [Style.MUTED.to_html(false), WhyPopover.bbcode_list(ls)] + + +## The last step of the current roll for an entry: {"steps", "index"} or {}. +func step_for(tid: String, eid: String) -> Dictionary: + var steps: Array = main.current.get("steps", []) + for k in range(steps.size() - 1, -1, -1): + var s: Dictionary = steps[k] + if str(s.get("table_id", "")) == tid and str(s.get("entry_id", "")) == eid: + return {"steps": steps, "index": k} + return {} ## Plain one-line title, cut down to a readable length. @@ -149,13 +211,18 @@ static func _short(s: String) -> String: return s if s.length() <= 90 else s.substr(0, 88).strip_edges() + "…" -## A result chip: the entry's details, else the table's. -func show_step(owner: Control, step: Dictionary) -> void: +## A result chip: the entry's details, else the table's, then the step's +## "Why this?" reasons when `steps` and `index` are given. +func show_step(owner: Control, step: Dictionary, steps: Array = [], index: int = -1) -> void: var t := main.data.get_table(str(step.get("table_id", ""))) if t == null: return var e := t.find_entry(str(step.get("entry_id", ""))) var body := e.details if e and e.details.strip_edges() != "" else t.details + if index >= 0: + var why := why_bbcode(steps, index, main.data, RulesView.plain(main)) + if why != "": + body = (body.strip_edges() + "\n\n" + why) if body.strip_edges() != "" else why if body.strip_edges() == "": return var title := _short(Formatter.strip_tags(str(step.get("text", "")))) if e and e.details.strip_edges() != "" else Formatter.strip_tags(t.name) @@ -224,14 +291,21 @@ func table_summary(t: RollTable) -> String: RollTable.KIND_CHOICE: return {"pick": "Choice · %d options" % t.entries.size(), "number": "Choice · a number", "text": "Choice · open ended"}.get(t.choice, "Choice") RollTable.KIND_LOOP: - return "Loop · " + TableCard.loop_rule(t) + return "Loop · " + RulesView.loop_rule(t, main.data, RulesView.plain(main)) RollTable.KIND_VARIABLE: + if RulesView.plain(main): + return "Collection · kept between rolls" if t.is_collection() else "%s · kept between rolls" % t.var_type.capitalize() return "Variable @%s · %s" % [t.var_name, t.var_type] + RollTable.KIND_CHECK: + return RulesView.check_line(t, main.data, RulesView.plain(main)) RollTable.KIND_SHEET: return "Sheet" RollTable.KIND_ROUTER: return "Router · %d cases · the first true case is taken" % t.entries.size() - var parts := PackedStringArray([t.dice_label()]) + var dl := t.dice_label() + if t.is_expr_dice() and RulesView.plain(main): + dl = Describe.dice(t.dice, main.data) + var parts := PackedStringArray([dl]) parts.append("%d %s" % [t.entries.size(), "ranges" if t.is_ranged() else "results"]) if t.card_mode: var left := main.cards_left(t.id) diff --git a/ui/pipe_layer.gd b/ui/pipe_layer.gd index 7bc0db6..1e55663 100644 --- a/ui/pipe_layer.gd +++ b/ui/pipe_layer.gd @@ -7,8 +7,10 @@ extends Control ## the text, so they can't be clicked or removed here. ## ## Conditional pipes (an "Only if" condition, or "otherwise") have a small -## diamond at their source end and a label ("if @str >= 8", "otherwise"), so -## the branches of an entry read at a glance. +## diamond at their source end, and pipes with options a label, so the +## branches of an entry read at a glance. Labels read in plain words +## (Describe.pipe: "Tier 3 · only if Luck is 2 or more", "otherwise") or as +## the stored text ("if @luck >= 2"), following RulesView.plain(main). ## ## Pipes to or from tables hidden in a collapsed group attach to that group's ## card instead (GroupCard.inlet_point / anchor_for). They keep their keys, so @@ -60,7 +62,7 @@ func _init() -> void: func _process(_delta: float) -> void: if main == null or main.board == null: return - var state := [main.board.geometry_rev, hover_key, select_key, pulse_key, pulse_t, main.board.cards.far] + var state := [main.board.geometry_rev, hover_key, select_key, pulse_key, pulse_t, main.board.cards.far, RulesView.plain(main)] if state != _drawn_state: _drawn_state = state queue_redraw() @@ -166,6 +168,7 @@ func _draw() -> void: var diamonds: Array = [] # [point, lit, otherwise] var drawn := {} # endpoints of rerouted pipes already drawn (they overlap) var build := main.mode == Main.Mode.BUILD + var plain := RulesView.plain(main) # Tables hidden in a collapsed group -> that group's card. Their pipes leave # from the group card's right edge and arrive at its inlet. var hidden := main.hidden_groups() @@ -211,8 +214,8 @@ func _draw() -> void: diamonds.append([pts, lit, e.is_otherwise(to)]) if lit: (lit_refs if is_ref else lit_list).append(pts) - if not is_ref and not rerouted and e.is_conditional(to): - var lt := _pipe_tag(e, to) + if not is_ref and not rerouted: + var lt := RulesView.pipe_label(e, to, main.data, plain) if lt != "": labels.append([pts, lt, true]) continue @@ -228,7 +231,7 @@ func _draw() -> void: else: _batch_pipe(pts, build and (key == hover_key or key == select_key)) if not is_ref and not rerouted: - var tag := _pipe_tag(e, to) + var tag := RulesView.pipe_label(e, to, main.data, plain) if tag != "": labels.append([pts, tag, false]) # Lit pipes go on top so the path of the last roll reads clearly. @@ -238,8 +241,9 @@ func _draw() -> void: _draw_pipe(pts, true, false) for d in diamonds: _draw_diamond(d[0], d[1], d[2]) + var placed: Array[Rect2] = [] for l in labels: - _draw_tag(l[0], l[1], l[2]) + _draw_tag(l[0], l[1], l[2], placed) if pulse_key != "" and _paths.has(pulse_key): var p := point_along(_paths[pulse_key], pulse_t) var r := 0.75 if Roller.is_ref_key(pulse_key) else 1.0 @@ -248,9 +252,13 @@ func _draw() -> void: draw_circle(p, 7.0 * r, Style.PULSE) -## "if @str >= 8 ×2 → foe" / "otherwise" for a pipe with options, or "". +## The text-mode label: "tier=3 if @str >= 8 ×2 → foe" / "otherwise" for a +## pipe with options, or "". static func _pipe_tag(e: TableEntry, to: String) -> String: var parts := PackedStringArray() + var wv := e.with_for(to) + for nm: String in wv: + parts.append("%s=%s" % [nm, RulesView.cut(str(wv[nm]), 12)]) var w := e.when_for(to) if w != "": parts.append("if " + (w if w.length() <= 24 else w.substr(0, 23) + "…")) @@ -266,12 +274,30 @@ static func _pipe_tag(e: TableEntry, to: String) -> String: return " ".join(parts) -func _draw_tag(pts: PackedVector2Array, text: String, lit: bool = false) -> void: +## A label on a pipe, at its middle, or a little along it when that spot +## overlaps a label already drawn (`placed`, which it adds to). +func _draw_tag(pts: PackedVector2Array, text: String, lit: bool = false, placed: Array[Rect2] = []) -> void: var font := Style.body_bold(true) var fs := 12 var w := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x - var mid := point_along(pts, 0.5) - var r := Rect2(mid - Vector2(w / 2.0 + 6.0, 10.0), Vector2(w + 12.0, 19.0)) + # Labels sit behind the cards, so a long one is cut to the gap between + # the cards it joins (the whole rule shows in the row's hover summary). + var room := maxf(80.0, absf(pts[pts.size() - 1].x - pts[0].x) - 30.0) if pts.size() > 1 else 200.0 + while w + 12.0 > room and text.length() > 6: + text = text.substr(0, text.length() - 2).strip_edges() + "…" + w = font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x + var r := Rect2() + for t: float in [0.5, 0.62, 0.38, 0.74, 0.26]: + var mid := point_along(pts, t) + r = Rect2(mid - Vector2(w / 2.0 + 6.0, 10.0), Vector2(w + 12.0, 19.0)) + var clear := true + for q in placed: + if q.grow(2.0).intersects(r): + clear = false + break + if clear: + break + placed.append(r) draw_style_box(_lit_label_box if lit else _label_box, r) draw_string(font, Vector2(r.position.x + 6.0, r.position.y + 14.0), text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.INK if lit else Style.COPPER_DARK) diff --git a/ui/result_tray.gd b/ui/result_tray.gd index 62935aa..45b3971 100644 --- a/ui/result_tray.gd +++ b/ui/result_tray.gd @@ -3,6 +3,14 @@ extends PanelContainer ## The strip along the bottom: the current roll as a chain of result chips ## joined by brass pipe pieces, a Copy menu, and on the right either the ## earlier rolls (default) or the Variables tab. +## +## Captions and effect lines read in plain words ("Loot · Tier 1 · rolled 3", +## "Luck 2 → 1") or closer to the rule text, following RulesView.plain(main); +## the tray re-renders on Main's rules_view_changed. A chip whose step has +## why-trace facts gets a "Why this?" button that opens a WhyPopover; hovering +## 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. enum Side { EARLIER, VARIABLES } @@ -37,6 +45,10 @@ const HEADLINE_MAX_H := 220.0 ## True when "+N earlier steps" has been opened for the current roll. var expanded := false var _scroll_to_end := false +var _why: WhyPopover +## The "Why this?" buttons of the chips shown, by step index (tests). +var why_buttons: Dictionary = {} +var _why_flag_done := false ## A long chain shows only its last steps; the rest sit behind a toggle. const TAIL := 12 @@ -159,6 +171,14 @@ func setup(p_main: Main) -> void: _vars.setup(main) right.add_child(_vars) set_side(Side.EARLIER) + _why = WhyPopover.new() + add_child(_why) + RulesView.watch(main, _on_rules_view_changed) + + +func _on_rules_view_changed(_v: Variant = null) -> void: + _why.close() + render() func _tab(text: String) -> Button: @@ -223,6 +243,9 @@ func render() -> void: for c in _flow.get_children(): _flow.remove_child(c) c.queue_free() + why_buttons.clear() + if _why != null: + _why.close() _empty.visible = current.is_empty() _render_status(current, steps) if current.is_empty(): @@ -243,7 +266,7 @@ func render() -> void: 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) + var chip := _chip(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 @@ -277,6 +300,50 @@ func render() -> void: _vars.render() _scroll_to_end = not expanded _fit_scroll.call_deferred() + if not _why_flag_done and current.get("done", false): + _open_why_from_flag.call_deferred() + + +## --why[=]: opens the Why pop-over once after a roll (screenshots). +func _open_why_from_flag() -> void: + for a in OS.get_cmdline_user_args(): + if a == "--why" or a.begins_with("--why="): + _why_flag_done = true + await get_tree().create_timer(0.4).timeout + if not main.current.get("done", false): + _why_flag_done = false # a new roll began; wait for it to end + return + var at := -1 + if a == "--why": + for k: int in why_buttons: + at = maxi(at, k) + else: + at = a.get_slice("=", 1).to_int() + if why_buttons.has(at): + (why_buttons[at] as Button).emit_signal("pressed") + return + + +## Opens (or, from the same button, closes) the Why pop-over for steps[index]. +func open_why(index: int, from: Control = null) -> void: + if _why.visible and from != null and _why.opener == from: + _why.close() + return + var steps: Array = main.current.get("steps", []) + if index < 0 or index >= steps.size(): + return + main.details().hide_for() + var at := Rect2(global_position + Vector2(20, 20), Vector2.ZERO) + var chip: Control = null + if from != null: + # Above the whole chip, so it never hides the step it explains. + chip = from.get_parent().get_parent() as Control + at = chip.get_global_rect() if chip != null else from.get_global_rect() + _why.open(steps, index, main.data, RulesView.plain(main), at, from, chip) + + +func why_popover() -> WhyPopover: + return _why ## Index of the first chip shown for a chain of `count` steps: only the last @@ -415,10 +482,30 @@ func _asking_chip(title: String) -> Control: ## The muted line above a chip's text: table name and how it got its result. -static func caption_for(step: Dictionary) -> String: +## 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 @@ -439,18 +526,32 @@ static func caption_for(step: Dictionary) -> String: caption += " · sheet" RollTable.KIND_ROUTER: if step.has("case"): - caption += " · case %d" % (int(step["case"]) + 1) + 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 != "": - caption += " · rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))] + 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", "")) != "": - caption += " · saved as {%s}" % step["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) -> Control: +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]) @@ -468,7 +569,9 @@ func _chip(step: Dictionary, last: bool) -> Control: var v := VBoxContainer.new() v.add_theme_constant_override("separation", 1) p.add_child(v) - var caption := caption_for(step) + 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 @@ -489,12 +592,68 @@ func _chip(step: Dictionary, last: bool) -> Control: v.add_child(body) var fx: Array = step.get("effects", []) if not fx.is_empty(): - v.add_child(_effect_lines(fx)) - if has_details: - p.mouse_entered.connect(func() -> void: main.details().show_step(p, step)) + 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() diff --git a/ui/rules_view.gd b/ui/rules_view.gd new file mode 100644 index 0000000..381f748 --- /dev/null +++ b/ui/rules_view.gd @@ -0,0 +1,147 @@ +class_name RulesView +extends RefCounted +## The display side of docs/PLAIN.md §5: whether rules show in plain words +## (Describe) or as their stored text, and short display helpers that pick +## between the two. +## +## The switch itself lives in Main (the Build inspector work): when Main has +## rules_plain() that decides, else its StateStore's "rules_view" setting, else +## an in-memory default (plain, or text with the --rules=text screenshot flag). +## Displays refresh on Main's `rules_view_changed` signal when it has one +## (watch()). + +## Used when Main has neither rules_plain() nor a StateStore (--sample, tests). +static var fallback_plain := true +static var _args_read := false + +## Longest pipe label drawn on the board before it's cut with "…". +const PIPE_CHARS := 46 + + +## True when rules should read in plain words. +static func plain(main: Object) -> bool: + if main != null: + if main.has_method("rules_plain"): + return bool(main.call("rules_plain")) + var st: Variant = main.get("state") + if st is StateStore: + return (st as StateStore).rules_plain() + if not _args_read: + _args_read = true + if OS.get_cmdline_user_args().has("--rules=text"): + fallback_plain = false + return fallback_plain + + +## Calls `callable` whenever Main's rules view changes (when Main has the +## signal). Safe to call more than once with the same callable. +static func watch(main: Object, callable: Callable) -> void: + if main == null or not main.has_signal("rules_view_changed"): + return + if not main.is_connected("rules_view_changed", callable): + main.connect("rules_view_changed", callable) + + +## An effects field as one short line: "Luck −1 · Gold + 2D" (plain) or +## "@luck -= 1 · @gold += 2d6" (text). At most `most` statements, then "+N". +static func effects_line(text: String, board: TowerBoard, table: RollTable, is_plain: bool, most: int = 2) -> String: + var list: Array = Describe.effects(text, board, table) if is_plain else Array(Effects.split(text)) + var parts := PackedStringArray() + for k in mini(most, list.size()): + parts.append(str(list[k])) + if list.size() > most: + parts.append("+%d" % (list.size() - most)) + return " · ".join(parts) + + +## A condition in plain words or as written. +static func condition(expr: String, board: TowerBoard, is_plain: bool) -> String: + return Describe.condition(expr, board) if is_plain else expr.strip_edges() + + +## A router case: "if Strength is 10 or more" / "if @str >= 10", or +## "Otherwise". +static func case_label(e: TableEntry, board: TowerBoard, is_plain: bool) -> String: + var w := e.when.strip_edges() + if w == "": + return "Otherwise" + return "if " + condition(w, board, is_plain) + + +## A loop's rule: "repeat while Health is more than 0", "repeat until Done is +## set", "× Terms" (plain); "while @hp > 0", "× @terms" (text). +static func loop_rule(t: RollTable, board: TowerBoard, is_plain: bool) -> String: + if not is_plain: + return TableCard.loop_rule(t) + var e := t.loop_expr.strip_edges() + if e == "": + return "× ?" if t.loop_mode == "times" else "repeat %s ?" % t.loop_mode + match t.loop_mode: + "while": + return "repeat while " + Describe.condition(e, board) + "until": + return "repeat until " + Describe.condition(e, board) + return "× " + Describe.dice(e, board) + + +## A pick card's option source: "Options: your Skills, level 1 or more" or +## "Options from @skill_* · where option_value >= 1". +static func options_line(t: RollTable, board: TowerBoard, is_plain: bool) -> String: + if not is_plain: + return TableCard.options_line(t) + var d := Describe.options(t, board) + return "Options: " + (d if d != "" else t.options_from.strip_edges()) + + +## A pick option's show_if: "only if Hit points is at most 6". +static func show_if_line(e: TableEntry, board: TowerBoard, is_plain: bool) -> String: + return "only if " + condition(e.show_if, board, is_plain) + + +## A dice expression: "2D + Luck" or "2d6 + @luck". +static func dice(expr: String, board: TowerBoard, is_plain: bool) -> String: + return Describe.dice(expr, board) if is_plain else expr.strip_edges() + + +## A check card's rule: "Roll 2D + Strength modifier, need 8 or more" or +## "2d6 + dm(@str) vs 8+". +static func check_line(t: RollTable, board: TowerBoard, is_plain: bool) -> String: + if is_plain: + return Describe.check(t, board) + var roll := t.check_dice.strip_edges() + if t.check_mod.strip_edges() != "": + var m := t.check_mod.strip_edges() + roll += (" " + m) if m.begins_with("-") else " + " + m + return "%s vs %s%s" % [roll, t.check_target.strip_edges(), "-" if t.check_cmp == "le" else "+"] + + +## The two outlet labels of a check card ([success, failure]): "8+" and "≤7" +## for a number target, else "✓" and "✗". +static func check_outlets(t: RollTable) -> Array[String]: + var tg := t.check_target.strip_edges() + if not tg.is_valid_int(): + return ["✓", "✗"] + var n := tg.to_int() + if t.check_cmp == "le": + return ["≤%d" % n, "%d+" % (n + 1)] + return ["%d+" % n, "≤%d" % (n - 1)] + + +## A pipe's label: Describe.pipe (plain) or PipeLayer's text tag, cut to +## PIPE_CHARS. +static func pipe_label(e: TableEntry, to: String, board: TowerBoard, is_plain: bool) -> String: + var s := Describe.pipe(e, to, board) if is_plain else PipeLayer._pipe_tag(e, to) + return cut(s, PIPE_CHARS) + + +## A value's name: "Strength" or "@str". +static func value_name(name: String, board: TowerBoard, is_plain: bool) -> String: + return Describe.label(name, board) if is_plain else name + + +## `s`, or its first `most` characters and "…". +static func cut(s: String, most: int) -> String: + if s.length() <= most: + return s + return s.substr(0, most - 1).strip_edges() + "…" + diff --git a/ui/rules_view.gd.uid b/ui/rules_view.gd.uid new file mode 100644 index 0000000..dd1aa8d --- /dev/null +++ b/ui/rules_view.gd.uid @@ -0,0 +1 @@ +uid://baaog01nm2ofe diff --git a/ui/style.gd b/ui/style.gd index 236a071..62bdfac 100644 --- a/ui/style.gd +++ b/ui/style.gd @@ -22,6 +22,9 @@ const DANGER := Color("#e0574a") const DANGER_INK := Color("#a33a2c") const WARN_BG := Color("#f4dacb") const WARN_INK := Color("#8a2f1d") +## A check card's Success and Failure outlets. +const OK_INK := Color("#2f6b3f") +const NO_INK := Color("#8a2f1d") const DASH := Color("#bdb6a2") const PULSE := Color("#fff6d2") @@ -157,6 +160,33 @@ static func bar_button(text: String, primary: bool = false) -> Button: return b +## The Plain words / Text switch's look (docs/PLAIN.md §5; the switch itself +## is Main's): two segment buttons on the felt, the chosen one card-coloured. +## Adds them to `into` and returns [plain_button, text_button]; `on_change` +## gets true for Plain words. +static func rules_switch(into: HBoxContainer, is_plain: bool, on_change: Callable) -> Array[Button]: + var group := ButtonGroup.new() + var out: Array[Button] = [] + for k in 2: + var b := Button.new() + b.text = "Plain words" if k == 0 else "Text" + b.toggle_mode = true + b.button_group = group + b.button_pressed = (k == 0) == is_plain + b.tooltip_text = "Show rules in plain words" if k == 0 else "Show rules as their stored text" + var n := box(Color(0, 0, 0, 0), 7, [11, 4, 11, 5]) + var h := box(Color(1, 1, 1, 0.08), 7, [11, 4, 11, 5]) + var on := box(CARD, 7, [11, 4, 11, 5]) + skin_button(b, n, h, on, ON_FELT_MUTED, ON_FELT, INK) + b.add_theme_font_override("font", body_bold()) + b.add_theme_font_size_override("font_size", 13) + var want := k == 0 + b.pressed.connect(func() -> void: on_change.call(want)) + into.add_child(b) + out.append(b) + return out + + # ---------- Themes ---------- static func app_theme() -> Theme: diff --git a/ui/table_card.gd b/ui/table_card.gd index 678051a..29ef3c9 100644 --- a/ui/table_card.gd +++ b/ui/table_card.gd @@ -15,7 +15,22 @@ extends PanelContainer ## A pick card whose options come from variables (docs/LOGIC.md §2a) says ## "Options from @skill_* · where …" (in Play with how many are available ## now) and has a Chosen row first; any pick option can have a Show only if -## condition, edited under its row (the "if" toggle) in Build. +## condition, shown under its row ("only if …"). +## +## Rules read in plain words (docs/PLAIN.md §6, Describe) or as their stored +## text, following RulesView.plain(main); cards rebuild on Main's +## rules_view_changed. Build mode only edits result text and the card's name +## inline; everything else (effects, conditions, details, card fields) is +## edited in Main's inspector, so rows show plain chips instead. Clicking a +## result row in Build calls main.select_result(table id, entry id) when Main +## has it; the selected row gets a copper bar on its left, from +## main.inspector_selection() ({"table_id", "entry_id"}) at rebuild time or +## set_selected_entry(entry id), which the inspector can call on any card. +## +## Check cards have a "2D" badge, their rule as a sentence and two outlet rows, +## Success and Failure. Collection cards list their members with live values +## (and "+ Add" in Build, which selects the card for the inspector). A card +## with inputs shows them in a dashed box under the header. const WIDTH := 256.0 ## Build mode has more controls per row, so cards are a little wider there. @@ -53,11 +68,10 @@ var _style_selected: StyleBoxFlat var _selected := false var _deck_row: Control var _deck_label: Label -## Entry ids whose details editor is open (Build mode). +## Unused since the inspector took over the inline editors; kept because +## Main's screenshot flags (--edit-details, --edit-effects) still set them. var _open_details: Dictionary = {} -## Entry ids whose effects editor is open (Build mode). var _open_effects: Dictionary = {} -## Entry ids whose Show only if editor is open (Build mode, pick choices). var _open_show_if: Dictionary = {} ## Play mode: "3 available now" on a dynamic pick card. var _options_label: Label @@ -68,6 +82,13 @@ var _var_value: Label var _var_hint: Label var _sheet_label: RichTextLabel var _live_cache: Dictionary = {} +## Rules in plain words (read from RulesView at each rebuild). +var _plain := true +## The result picked in the inspector (copper bar), or "". +var _selected_eid := "" +## Collection cards: the member list, refilled by refresh_live(). +var _members_box: VBoxContainer +var _members_cache := "" func setup(p_main: Main, p_table: RollTable) -> void: @@ -105,8 +126,20 @@ func setup(p_main: Main, p_table: RollTable) -> void: for c in [Color(0, 0, 0, 0), Style.FLICK, Style.LIT]: _row_styles.append(Style.box(c, 0, [12, 6, 22, 6])) + # The same, with the copper bar of the inspector's selected result. + for c in [Color(0, 0, 0, 0), Style.FLICK, Style.LIT]: + var sel := Style.box(c, 0, [12, 6, 22, 6]) + sel.border_width_left = 3 + sel.border_color = Style.COPPER + sel.anti_aliasing = false + _row_styles.append(sel) minimum_size_changed.connect(func() -> void: _shrink.call_deferred()) + RulesView.watch(main, _on_rules_view_changed) + rebuild() + + +func _on_rules_view_changed(_v: Variant = null) -> void: rebuild() @@ -127,7 +160,15 @@ func rebuild() -> void: _var_hint = null _sheet_label = null _options_label = null + _members_box = null + _members_cache = "" _live_cache.clear() + _plain = RulesView.plain(main) + if main.has_method("inspector_selection"): + var sel: Variant = main.call("inspector_selection") + _selected_eid = "" + if sel is Dictionary and str((sel as Dictionary).get("table_id", "")) == table.id: + _selected_eid = str((sel as Dictionary).get("entry_id", "")) var build := main.mode == Main.Mode.BUILD custom_minimum_size = Vector2(card_width(), 0) @@ -137,16 +178,11 @@ func rebuild() -> void: var col := _vbox(0) add_child(col) col.add_child(_make_header(build, ranged)) - if build and _table_details_open: - var ted := _details_editor(table.details, "Details for this table (BBCode)", 12.0, - func(s: String) -> void: - table.details = s - main.mark_dirty()) - ted.add_theme_constant_override("margin_top", 8) - col.add_child(ted) + if not table.inputs.is_empty() and table.kind != RollTable.KIND_VARIABLE: + col.add_child(_make_inputs_box()) if table.kind == RollTable.KIND_VARIABLE: - col.add_child(_make_variable_body(build)) + col.add_child(_make_collection_body(build) if table.is_collection() else _make_variable_body(build)) _warn_panel = _make_warning() col.add_child(_warn_panel) _update_warning() @@ -184,18 +220,11 @@ func rebuild() -> void: _list_box.add_child(_make_sheet_row(e, build)) elif table.kind == RollTable.KIND_ROUTER and build: _list_box.add_child(_make_case_row(e, i, numw)) + elif table.kind == RollTable.KIND_CHECK: + _list_box.add_child(_make_check_row(e, i, build, numw)) else: _list_box.add_child(_make_row(e, i, build, ranged, numw)) _set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL) - if build and _open_show_if.has(e.id) and _is_pick(): - _list_box.add_child(_show_if_editor(e, 12.0 + numw + 4.0)) - if build and _open_effects.has(e.id): - _list_box.add_child(_effects_editor(e, 12.0 + numw + 4.0)) - if build and _open_details.has(e.id): - _list_box.add_child(_details_editor(e.details, "Details for this result (BBCode)", 12.0 + numw + 4.0, - func(s: String) -> void: - e.details = s - main.mark_dirty())) if collapsed: _list_box.add_child(_make_more_row(numw)) @@ -350,7 +379,10 @@ func _subtitle() -> String: RollTable.KIND_ROLL: if table.is_ranged(): var n := "%d ranges" % table.entries.size() - return "%s · %s" % [table.dice_label(), n] if table.is_expr_dice() else n + if table.is_expr_dice(): + var dl := ("Roll " + Describe.dice(table.dice, main.data)) if _plain else table.dice_label() + return "%s · %s" % [dl, n] + return n if table.collapsed: return "%d results" % table.entries.size() RollTable.KIND_CHOICE: @@ -358,6 +390,8 @@ func _subtitle() -> String: return "%d options" % table.entries.size() RollTable.KIND_ROUTER: return "if / else if / otherwise · %d %s" % [table.entries.size(), "case" if table.entries.size() == 1 else "cases"] + RollTable.KIND_CHECK: + return "Check card" return "" @@ -400,6 +434,10 @@ func _make_go_button() -> Button: b.add_theme_font_override("font", Style.body_bold(true)) b.add_theme_font_size_override("font_size", 14) b.tooltip_text = "Print this sheet in the tray" + RollTable.KIND_CHECK: + b.text = check_badge(table) + b.custom_minimum_size = Vector2(38, 0) + b.tooltip_text = "Roll the check: %s\nShift-click to skip the animation" % RulesView.check_line(table, main.data, _plain) _: left = 34 var label := "d%d" % table.die_size() @@ -439,16 +477,16 @@ func _make_kind_header(_build: bool) -> Control: var kinds := {"pick": "Pick one", "number": "A number", "text": "Your words"} var info := str(kinds.get(table.choice, "")) if table.choice == "number": - info += " · %s to %s" % [table.min_expr, table.max_expr] + info += " · %s to %s" % [RulesView.dice(table.min_expr, main.data, _plain), RulesView.dice(table.max_expr, main.data, _plain)] if table.save_as != "": - info += " · saves %s" % table.save_as + info += " · saves %s" % RulesView.value_name(table.save_as, main.data, _plain) var l := Style.make_label(info, Style.body(true), 12, Style.MUTED) l.mouse_filter = MOUSE_FILTER_IGNORE l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART v.add_child(l) if table.is_dynamic(): var bad := not Roller.lint_options(table).is_empty() - var ol := Style.make_label(options_line(table), Style.body_bold(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK) + var ol := Style.make_label(RulesView.options_line(table, main.data, _plain), Style.body_bold(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK) ol.mouse_filter = MOUSE_FILTER_PASS ol.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART ol.tooltip_text = "One option per %s; the Chosen row runs for whichever is picked (option, option_label and option_value hold it)" % table.options_description() @@ -464,10 +502,15 @@ func _make_kind_header(_build: bool) -> Control: chip.size_flags_horizontal = SIZE_SHRINK_BEGIN chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(Style.BRASS, 0.16), 6, [8, 1, 8, 2]), 1, Color(Style.BRASS_DARK, 0.35))) var err := Expr.check(table.loop_expr) if table.loop_expr.strip_edges() != "" else "No rule yet" - var l := Style.make_label(loop_rule(table), Style.display(true), 16, Style.DANGER_INK if err != "" else Style.COPPER_DARK) + var rule := RulesView.loop_rule(table, main.data, _plain) + var l := Style.make_label(rule, Style.display(true), 16, Style.DANGER_INK if err != "" else Style.COPPER_DARK) l.mouse_filter = MOUSE_FILTER_IGNORE + if rule.length() > 26: + # A long plain rule wraps across the card instead of widening it. + l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + chip.size_flags_horizontal = SIZE_FILL chip.add_child(l) - chip.tooltip_text = err + chip.tooltip_text = err if err != "" else (loop_rule(table) if _plain else "") return chip RollTable.KIND_ROUTER: if not _build: @@ -478,12 +521,104 @@ func _make_kind_header(_build: bool) -> Control: return rl RollTable.KIND_VARIABLE: var txt := "@%s · %s" % [table.var_name, table.var_type] + if table.is_collection(): + txt = "Collection · kept between rolls" if _plain else "@%s_* (board values)" % table.var_name + elif _plain: + txt = "%s · kept between rolls" % table.var_type.capitalize() var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED) l.mouse_filter = MOUSE_FILTER_IGNORE + l.tooltip_text = "@" + table.var_name if _plain and not table.is_collection() else "" + if l.tooltip_text != "": + l.mouse_filter = MOUSE_FILTER_PASS return l + RollTable.KIND_CHECK: + var cl := RichText.label(check_sentence(table, main.data, _plain), 14, Style.INK, true) + cl.mouse_filter = MOUSE_FILTER_IGNORE + return cl return null +## The check card's "2D" badge (its dice in plain words, "Roll" when long). +static func check_badge(t: RollTable) -> String: + var d := Describe.dice(t.check_dice, null) + return d if d.length() <= 5 else "Roll" + + +## The check card's sentence under its header, as BBCode: "Roll 2D + +## Strength modifier, need [b]8 or more[/b]" (plain) or "[code]2d6 + dm(@str) +## vs 8+[/code]" style text. +static func check_sentence(t: RollTable, board: TowerBoard, plain: bool) -> String: + var s := RulesView.check_line(t, board, plain) + if not plain: + return "[color=#%s]%s[/color]" % [Style.COPPER_DARK.to_html(false), RichText.plain(s)] + var at := s.rfind(", need ") + if at < 0: + return RichText.plain(s) + return "%s, need [b]%s[/b]" % [RichText.plain(s.substr(0, at)), RichText.plain(s.substr(at + 7))] + + +## A dashed box under the header naming the card's inputs: "Input Tier · +## starts at 1" (plain) or "input tier · default 1" (text), one line each. +func _make_inputs_box() -> Control: + var wrap := MarginContainer.new() + wrap.mouse_filter = MOUSE_FILTER_PASS + wrap.add_theme_constant_override("margin_left", 10) + wrap.add_theme_constant_override("margin_right", 10) + wrap.add_theme_constant_override("margin_top", 8) + var p := PanelContainer.new() + p.mouse_filter = MOUSE_FILTER_PASS + p.add_theme_stylebox_override("panel", DashedBox.new()) + p.tooltip_text = "Values a pipe into this card can pass (\"with\"); a roll that starts here uses the starting values" + wrap.add_child(p) + var v := _vbox(2) + p.add_child(v) + for inp: Dictionary in table.inputs: + var line := RichText.label(input_line(inp, main.data, _plain), 13, Style.MUTED, true) + line.mouse_filter = MOUSE_FILTER_IGNORE + line.set_meta("input_line", true) + v.add_child(line) + wrap.set_meta("inputs_box", true) + return wrap + + +## One input as BBCode: "Input [b]Tier[/b] · starts at [b]1[/b]". +static func input_line(inp: Dictionary, board: TowerBoard, plain: bool) -> String: + var nm := str(inp.get("name", "")) + var def := str(inp.get("default", "")).strip_edges() + var ink := Style.INK.to_html(false) + if not plain: + return "input [color=#%s]%s[/color] · default [color=#%s]%s[/color]" % [ink, RichText.plain(nm), ink, RichText.plain(def if def != "" else "0")] + var lab := str(inp.get("label", "")).strip_edges() + if lab == "": + lab = Describe.label(nm, board) + var shown := Describe.dice(def, board) if def != "" else "0" + return "Input [color=#%s][b]%s[/b][/color] · starts at [color=#%s][b]%s[/b][/color]" % [ink, RichText.plain(lab), ink, RichText.plain(shown)] + + +## A dashed rounded outline (the inputs box), since StyleBoxFlat has no +## dashes. +class DashedBox extends StyleBox: + func _init() -> void: + content_margin_left = 9 + content_margin_right = 9 + content_margin_top = 6 + content_margin_bottom = 6 + + func _draw(to_canvas_item: RID, rect: Rect2) -> void: + var r := rect.grow(-0.5) + var pts := PackedVector2Array([r.position, Vector2(r.end.x, r.position.y), r.end, Vector2(r.position.x, r.end.y), r.position]) + var col := Style.DASH + for i in 4: + var a := pts[i] + var b := pts[i + 1] + var seg_len := a.distance_to(b) + var d := 0.0 + while d < seg_len: + var e := minf(d + 5.0, seg_len) + RenderingServer.canvas_item_add_line(to_canvas_item, a.lerp(b, d / seg_len), a.lerp(b, e / seg_len), col, 1.2, true) + d += 9.0 + + ## A fork: one stem splitting into two branches, each ending in a dot (the ## router card's go button). `r` is about half the icon's height. static func draw_fork(ci: CanvasItem, c: Vector2, r: float, color: Color, width: float = 2.0) -> void: @@ -610,65 +745,31 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float var text: RichTextLabel = null if build: h.add_theme_constant_override("separation", 4) + var col := _vbox(2) + col.size_flags_horizontal = SIZE_EXPAND_FILL + col.size_flags_vertical = SIZE_SHRINK_CENTER + h.add_child(col) if table.kind == RollTable.KIND_CHOICE and table.choice != "pick": var al := Style.make_label("Answer", Style.body_italic(true), 15, Style.MUTED) al.size_flags_horizontal = SIZE_EXPAND_FILL al.size_flags_vertical = SIZE_SHRINK_CENTER + al.mouse_filter = MOUSE_FILTER_PASS al.tooltip_text = "Its effects and pipes run after the player answers ({answer} holds the answer)" - h.add_child(al) + col.add_child(al) else: - var cbox: VBoxContainer = null if chosen: # A caption over the text field, so the field keeps its width. - cbox = _vbox(0) - cbox.size_flags_horizontal = SIZE_EXPAND_FILL var cl := Style.make_label("Chosen · runs for the picked option", Style.body_italic(true), 11, Style.COPPER_DARK) cl.mouse_filter = MOUSE_FILTER_PASS cl.tooltip_text = "Runs for whichever option from %s is picked: option, option_label and option_value hold it" % table.options_from.strip_edges() - cbox.add_child(cl) - h.add_child(cbox) - var edit := LineEdit.new() - edit.text = e.text - if chosen: - edit.placeholder_text = "(the option's name)" - edit.tooltip_text = "The result text. Leave it as Chosen (or empty) to show the picked option's name; {option_label}, {option_value} and {@[option]} work" - edit.size_flags_horizontal = SIZE_EXPAND_FILL - edit.size_flags_vertical = SIZE_SHRINK_CENTER - edit.custom_minimum_size = Vector2(40, 0) - edit.add_theme_font_size_override("font_size", 15) - if table.kind == RollTable.KIND_LOOP: - edit.placeholder_text = LOOP_ROWS[clampi(index, 0, 1)] - edit.tooltip_text = "%s: shown each pass ({i} is the pass number)" % LOOP_ROWS[0] if index == 0 else "%s: runs once when the loop ends" % LOOP_ROWS[1] - edit.text_changed.connect(func(s: String) -> void: - e.text = s - main.mark_dirty() - ) - if cbox != null: - cbox.add_child(edit) - else: - h.add_child(edit) + col.add_child(cl) + col.add_child(_text_edit(e, index, chosen)) + _add_rule_chips(col, e) if not ranged and not fixed: h.add_child(_weight_edit(e)) - if _is_pick(): - var sbad := e.show_if.strip_edges() != "" and Expr.check(TemplateKit.probe(e.show_if.strip_edges())) != "" - var sb := _toggle_button("if", "Show only if: hide this option unless a condition is true when the card is reached", - _open_show_if, e.id, e.show_if.strip_edges() != "", sbad) - sb.add_theme_font_size_override("font_size", 11) - h.add_child(sb) - h.add_child(_toggle_button("ƒ", "Effects: statements such as @hp -= 1 that run when this comes up", - _open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty())) - h.add_child(_toggle_button("i", "Details shown when hovering this result", - _open_details, e.id, e.details.strip_edges() != "", false)) if not fixed and not chosen: - var x := Button.new() - x.text = "×" - x.tooltip_text = "Delete this result" - x.custom_minimum_size = Vector2(22, 22) - x.size_flags_vertical = SIZE_SHRINK_CENTER - x.add_theme_font_size_override("font_size", 18) - Style.skin_button(x, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK) - x.pressed.connect(func() -> void: main.delete_entry(table.id, e.id)) - h.add_child(x) + h.add_child(_mini_button("×", "Delete this result", true, func() -> void: main.delete_entry(table.id, e.id))) + _hook_select(row, e.id) else: var col := _vbox(3) col.size_flags_horizontal = SIZE_EXPAND_FILL @@ -677,13 +778,7 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float text.size_flags_horizontal = SIZE_EXPAND_FILL RichText.hook_hover(text, main) col.add_child(text) - if _is_pick() and e.show_if.strip_edges() != "": - var si := Style.make_label("only if " + e.show_if.strip_edges(), Style.body_bold(true), 12, Style.COPPER_DARK) - si.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART - si.mouse_filter = MOUSE_FILTER_IGNORE - col.add_child(si) - if e.effects.strip_edges() != "": - col.add_child(_effects_chip(e)) + _add_rule_chips(col, e) h.add_child(col) row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id)) if ranged and table.has_chances(): @@ -696,9 +791,88 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float return row -## Build mode: one router case. The first line is its condition (empty means -## Otherwise), validated as you type, with move up / down and delete; the -## second is its result text with the effects and details toggles. +## Build mode: the inline result-text field of a row. Focusing it selects the +## result for the inspector. +func _text_edit(e: TableEntry, index: int, chosen: bool) -> LineEdit: + var edit := LineEdit.new() + edit.text = e.text + if chosen: + edit.placeholder_text = "(the option's name)" + edit.tooltip_text = "The result text. Leave it as Chosen (or empty) to show the picked option's name; {option_label}, {option_value} and {@[option]} work" + edit.size_flags_horizontal = SIZE_EXPAND_FILL + edit.size_flags_vertical = SIZE_SHRINK_CENTER + edit.custom_minimum_size = Vector2(40, 0) + edit.add_theme_font_size_override("font_size", 15) + if table.kind == RollTable.KIND_LOOP: + edit.placeholder_text = LOOP_ROWS[clampi(index, 0, 1)] + edit.tooltip_text = "%s: shown each pass ({i} is the pass number)" % LOOP_ROWS[0] if index == 0 else "%s: runs once when the loop ends" % LOOP_ROWS[1] + elif table.kind == RollTable.KIND_ROUTER: + edit.placeholder_text = "Result text" + edit.text_changed.connect(func(s: String) -> void: + e.text = s + main.mark_dirty() + ) + edit.focus_entered.connect(func() -> void: _select_entry(e.id)) + return edit + + +## The plain chips under a row's text: a pick option's "only if …" and the +## entry's effects ("Luck −1"). Used in Play and Build alike. +func _add_rule_chips(col: VBoxContainer, e: TableEntry) -> void: + if _is_pick() and e.show_if.strip_edges() != "": + var bad := Expr.check(TemplateKit.probe(e.show_if.strip_edges())) != "" + var si := Style.make_label(RulesView.show_if_line(e, main.data, _plain), Style.body_bold(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK) + si.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + si.mouse_filter = MOUSE_FILTER_PASS + si.tooltip_text = ("only if " + e.show_if.strip_edges()) if _plain else "" + si.set_meta("show_if_line", true) + col.add_child(si) + if e.effects.strip_edges() != "": + col.add_child(_effects_chip(e)) + + +## Build mode: a click on a row (outside its fields) selects the result for +## the inspector. +func _hook_select(row: Control, eid: String) -> void: + row.gui_input.connect(func(ev: InputEvent) -> void: + var mb := ev as InputEventMouseButton + if mb and mb.button_index == MOUSE_BUTTON_LEFT and mb.pressed: + _select_entry(eid) + ) + + +## Selects a result for the inspector: main.select_result(table id, entry id) +## when Main has it, and the copper bar on this row (cleared on other cards). +func _select_entry(eid: String) -> void: + if main.mode != Main.Mode.BUILD: + return + if main.has_method("select_result"): + main.call("select_result", table.id, eid) + for c: Variant in main.cards.values(): + if c is TableCard and c != self: + (c as TableCard).set_selected_entry("") + set_selected_entry(eid) + + +## Shows the copper selection bar on one result row ("" for none). The +## inspector may call this on every card when its selection changes. +func set_selected_entry(eid: String) -> void: + if _selected_eid == eid: + return + var old := _selected_eid + _selected_eid = eid + for k: String in [old, eid]: + if k != "" and rows.has(k): + _set_row_state(k, RowState.LIT if main.is_entry_lit(table.id, k) else RowState.NORMAL) + + +func selected_entry() -> String: + return _selected_eid + + +## Build mode: one router case. The first line is its condition, in plain +## words or as written (edited in the inspector), with move up / down and +## delete; the second is its result text, then its effects chip. func _make_case_row(e: TableEntry, index: int, numw: float) -> Control: var row := PanelContainer.new() row.mouse_filter = MOUSE_FILTER_PASS @@ -716,63 +890,78 @@ func _make_case_row(e: TableEntry, index: int, numw: float) -> Control: var top := _hbox(4) v.add_child(top) - var if_label := Style.make_label("if", Style.body_bold(true), 14, Style.COPPER_DARK) - if_label.size_flags_vertical = SIZE_SHRINK_CENTER - top.add_child(if_label) - var cond := LineEdit.new() - cond.text = e.when - cond.placeholder_text = "Otherwise" + var w := e.when.strip_edges() + var bad := w != "" and Expr.check(TemplateKit.probe(w)) != "" + var cond := Style.make_label(RulesView.case_label(e, main.data, _plain), Style.body_bold(true), 14, Style.DANGER_INK if bad else Style.COPPER_DARK) + cond.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART cond.size_flags_horizontal = SIZE_EXPAND_FILL cond.size_flags_vertical = SIZE_SHRINK_CENTER - cond.custom_minimum_size = Vector2(40, 0) - cond.add_theme_font_override("font", Style.body_bold(true)) - cond.add_theme_font_size_override("font_size", 14) - cond.add_theme_color_override("font_color", Style.COPPER_DARK) - var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Color(Style.BRASS_DARK, 0.4)) - var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.COPPER) - var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.DANGER_INK) - var check := func() -> void: - var src := TemplateKit.probe(cond.text.strip_edges()) - var err := Expr.check(src) if src != "" else "" - cond.add_theme_stylebox_override("normal", bad_box if err != "" else ok_box) - cond.add_theme_stylebox_override("focus", bad_box if err != "" else focus_box) - cond.tooltip_text = ("⚠ " + err) if err != "" else "This case is chosen when this is true (cases are checked top to bottom). Leave it empty for Otherwise." - if_label.text = "if" if cond.text.strip_edges() != "" else "else" - cond.text_changed.connect(func(t: String) -> void: - e.when = t.strip_edges() - check.call() - _update_warning() - main.mark_dirty() - ) - check.call() + cond.mouse_filter = MOUSE_FILTER_PASS + cond.tooltip_text = ("⚠ " + Expr.check(TemplateKit.probe(w))) if bad else (("if " + w) if _plain and w != "" else "Cases are checked top to bottom; the first true one is chosen") + cond.set_meta("case_line", true) top.add_child(cond) top.add_child(_mini_button("↑", "Move this case up", index > 0, func() -> void: _move_case(index, -1))) top.add_child(_mini_button("↓", "Move this case down", index < table.entries.size() - 1, func() -> void: _move_case(index, 1))) top.add_child(_mini_button("×", "Delete this case", true, func() -> void: main.delete_entry(table.id, e.id))) - var bottom := _hbox(4) - v.add_child(bottom) - var edit := LineEdit.new() - edit.text = e.text - edit.placeholder_text = "Result text" - edit.size_flags_horizontal = SIZE_EXPAND_FILL - edit.size_flags_vertical = SIZE_SHRINK_CENTER - edit.custom_minimum_size = Vector2(40, 0) - edit.add_theme_font_size_override("font_size", 15) - edit.text_changed.connect(func(t: String) -> void: - e.text = t - main.mark_dirty() - ) - bottom.add_child(edit) - bottom.add_child(_toggle_button("ƒ", "Effects: statements such as @hp -= 1 that run when this case is chosen", - _open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty())) - bottom.add_child(_toggle_button("i", "Details shown when hovering this case", - _open_details, e.id, e.details.strip_edges() != "", false)) + v.add_child(_text_edit(e, index, false)) + _add_rule_chips(v, e) + _hook_select(row, e.id) rows[e.id] = row _row_parts[e.id] = {"num": num, "text": null, "entry": e, "index": index} return row +## One outlet of a check card: "8+ Success · the bars give" / "≤7 Failure", +## with the outlet named in green or red. Build edits the text after the name. +func _make_check_row(e: TableEntry, index: int, build: bool, numw: float) -> Control: + var row := PanelContainer.new() + row.mouse_filter = MOUSE_FILTER_PASS + row.custom_minimum_size = Vector2(0, 36) + var h := _hbox(8) + row.add_child(h) + var outs := RulesView.check_outlets(table) + var num := Style.make_label(outs[index] if index < 2 else str(index + 1), Style.display(true), 16, Style.MUTED) + num.custom_minimum_size = Vector2(maxf(numw, 34.0), 0) + num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT + num.size_flags_vertical = SIZE_SHRINK_CENTER + h.add_child(num) + var col := _vbox(2) + col.size_flags_horizontal = SIZE_EXPAND_FILL + col.size_flags_vertical = SIZE_SHRINK_CENTER + h.add_child(col) + var text: RichTextLabel = null + if build: + var line := _hbox(6) + col.add_child(line) + var nm := Style.make_label(check_outlet_name(index), Style.body_bold(true), 15, check_outlet_color(index)) + nm.size_flags_vertical = SIZE_SHRINK_CENTER + line.add_child(nm) + var edit := _text_edit(e, index, false) + edit.placeholder_text = check_outlet_name(index) + line.add_child(edit) + _add_rule_chips(col, e) + _hook_select(row, e.id) + else: + text = RichText.label(_row_text(e), 16, Style.INK, true) + text.size_flags_horizontal = SIZE_EXPAND_FILL + RichText.hook_hover(text, main) + col.add_child(text) + _add_rule_chips(col, e) + row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id)) + rows[e.id] = row + _row_parts[e.id] = {"num": num, "text": text, "entry": e, "index": index} + return row + + +static func check_outlet_name(index: int) -> String: + return "Success" if index == 0 else ("Failure" if index == 1 else "Result %d" % (index + 1)) + + +static func check_outlet_color(index: int) -> Color: + return Style.OK_INK if index == 0 else Style.NO_INK + + func _mini_button(glyph: String, tip: String, enabled: bool, on_press: Callable) -> Button: var b := Button.new() b.text = glyph @@ -814,40 +1003,15 @@ func add_case() -> void: const LOOP_ROWS := ["Each time", "Afterwards"] -## Longest effects summary shown on a Play-mode chip. +## Longest effects summary shown on a chip. const CHIP_CHARS := 30 - - -## A small round toggle in a Build row ("i" details, "ƒ" effects). `open` is -## the dictionary of entry ids whose editor is shown. -func _toggle_button(glyph: String, tip: String, open: Dictionary, eid: String, has: bool, bad: bool) -> Button: - var b := Button.new() - b.text = glyph - b.toggle_mode = true - b.button_pressed = open.has(eid) - b.tooltip_text = tip - b.custom_minimum_size = Vector2(22, 22) - b.size_flags_vertical = SIZE_SHRINK_CENTER - b.add_theme_font_override("font", Style.body_bold(true)) - b.add_theme_font_size_override("font_size", 13) - var ring := Style.DANGER_INK if bad else (Style.COPPER if has else Style.DASH) - var inn := Style.bordered(Style.box(Color(0, 0, 0, 0), 11), 1, ring) - var inh := Style.bordered(Style.box(Color("#e6dfcd"), 11), 1, Style.COPPER) - var inp := Style.bordered(Style.box(Style.LIT, 11), 1, Style.COPPER) - Style.skin_button(b, inn, inh, inp, ring if (has or bad) else Style.MUTED, Style.INK) - b.toggled.connect(func(on: bool) -> void: - if on: - open[eid] = true - else: - open.erase(eid) - rebuild() - ) - return b +const PLAIN_CHIP_CHARS := 38 ## Play-mode text of a row: the last rolled (expanded) text when the row is ## lit, otherwise the entry as written with its references shown readably. -## Loop rows read "Each time · …"; a number/text choice's row is its answer. +## Loop rows read "Each time · …"; a number/text choice's row is its answer; +## a router case leads with its condition, a check outlet with its name. func _row_text(e: TableEntry) -> String: var rolled := main.lit_text(table.id, e.id) var s := RichText.decorate(rolled) if rolled != "" else RichText.preview(e.text, main.data) @@ -862,12 +1026,19 @@ func _row_text(e: TableEntry) -> String: s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s] elif table.kind == RollTable.KIND_ROUTER: var bad := e.when.strip_edges() != "" and Expr.check(e.when.strip_edges()) != "" - var cond := "[color=#%s][b]%s[/b][/color]" % [(Style.DANGER_INK if bad else Style.COPPER_DARK).to_html(false), RichText.plain(case_label(e))] + var label := RulesView.case_label(e, main.data, _plain) + var cond := "[color=#%s][b]%s[/b][/color]" % [(Style.DANGER_INK if bad else Style.COPPER_DARK).to_html(false), RichText.plain(label)] var plain_text := Formatter.strip_tags(e.text).strip_edges() - if plain_text == "" or plain_text == case_label(e) or plain_text == "if …" or (plain_text == "Otherwise" and e.when.strip_edges() == ""): + if plain_text == "" or plain_text == case_label(e) or plain_text == label or plain_text == "if …" or (plain_text == "Otherwise" and e.when.strip_edges() == ""): s = cond else: s = "%s\n%s" % [cond, s] + elif table.kind == RollTable.KIND_CHECK: + var index := table.entries.find(e) + var nm := check_outlet_name(index) + var head := "[color=#%s][b]%s[/b][/color]" % [check_outlet_color(index).to_html(false), nm] + var own := Formatter.strip_tags(rolled if rolled != "" else e.text).strip_edges() + s = head if own == "" or own == nm else "%s · %s" % [head, s] elif table.is_dynamic() and table.entries.find(e) == 0: var own := Formatter.strip_tags(e.text).strip_edges() if rolled != "": @@ -886,7 +1057,9 @@ func _row_text(e: TableEntry) -> String: return s -## Play mode: a subtle brass chip summarising an entry's effects ("STR = 2d6"). +## A subtle brass chip summarising an entry's effects: "Luck −1 · Gold + 2D" +## in plain words, "@luck -= 1 · @gold += 2d6" as text. Its tooltip has the +## other form, every statement on its own line. func _effects_chip(e: TableEntry) -> Control: var bad := not Effects.validate(TemplateKit.probe(e.effects)).is_empty() var chip := PanelContainer.new() @@ -895,19 +1068,22 @@ func _effects_chip(e: TableEntry) -> Control: var bg := Color(Style.DANGER_INK, 0.1) if bad else Color(Style.BRASS, 0.2) var line := Color(Style.DANGER_INK, 0.4) if bad else Color(Style.BRASS_DARK, 0.3) chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(bg, 5, [6, 0, 6, 1]), 1, line)) - var summary := effect_summary(e.effects, main.data) + var summary := RulesView.effects_line(e.effects, main.data, table, _plain) # Cut long summaries by hand: a clipped Label would collapse to nothing. - if summary.length() > CHIP_CHARS: - summary = summary.substr(0, CHIP_CHARS - 1).strip_edges() + "…" - var l := Style.make_label(summary, Style.body(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK) + summary = RulesView.cut(summary, PLAIN_CHIP_CHARS if _plain else CHIP_CHARS) + var l := Style.make_label(summary, Style.body_bold(true) if _plain else Style.body(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK) l.mouse_filter = MOUSE_FILTER_IGNORE chip.add_child(l) - chip.tooltip_text = "\n".join(Effects.split(e.effects)) + chip.set_meta("effects_chip", summary) + if _plain: + chip.tooltip_text = "\n".join(Effects.split(e.effects)) + else: + chip.tooltip_text = "\n".join(Describe.effects(e.effects, main.data, table)) return chip -## A short summary of effect text: the first two statements, with declared -## variables by their card's name ("STR = 2d6 · Terms += 1 · +3"). +## A short summary of effect text as written: the first two statements, with +## declared variables by their card's name ("STR = 2d6 · Terms += 1 · +3"). static func effect_summary(text: String, board: TowerBoard) -> String: var list := Effects.split(text) var parts := PackedStringArray() @@ -932,94 +1108,6 @@ static func effect_summary(text: String, board: TowerBoard) -> String: return " · ".join(parts) -## Build mode: the Show only if editor under a pick option, validated as you -## type (like a router case's condition). -func _show_if_editor(e: TableEntry, left: float) -> Control: - var wrap := MarginContainer.new() - wrap.mouse_filter = MOUSE_FILTER_PASS - wrap.add_theme_constant_override("margin_left", int(left)) - wrap.add_theme_constant_override("margin_right", 12) - wrap.add_theme_constant_override("margin_top", 2) - wrap.add_theme_constant_override("margin_bottom", 6) - var h := _hbox(6) - wrap.add_child(h) - var lbl := Style.make_label("Show only if", Style.body_bold(true), 12, Style.COPPER_DARK) - lbl.size_flags_vertical = SIZE_SHRINK_CENTER - h.add_child(lbl) - var le := LineEdit.new() - le.text = e.show_if - le.placeholder_text = "always" if not _is_chosen_row(table.entries.find(e)) else "always (hides every option from variables when false)" - le.size_flags_horizontal = SIZE_EXPAND_FILL - le.custom_minimum_size = Vector2(40, 0) - le.add_theme_font_override("font", Style.body_bold(true)) - le.add_theme_font_size_override("font_size", 13) - le.add_theme_color_override("font_color", Style.COPPER_DARK) - var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Color(Style.BRASS_DARK, 0.4)) - var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.COPPER) - var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.DANGER_INK) - var check := func() -> void: - var src := TemplateKit.probe(le.text.strip_edges()) - var err := Expr.check(src) if src != "" else "" - le.add_theme_stylebox_override("normal", bad_box if err != "" else ok_box) - le.add_theme_stylebox_override("focus", bad_box if err != "" else focus_box) - le.tooltip_text = ("⚠ " + err) if err != "" else "Checked when the card is reached: when it's false this option isn't offered, not even to Random. e.g. @commissioned, @last_career != \"Army\"" - le.text_changed.connect(func(t: String) -> void: - e.show_if = t.strip_edges() - check.call() - main.mark_dirty() - ) - check.call() - h.add_child(le) - return wrap - - -## Build mode: the effects editor under a row, validated as you type. -func _effects_editor(e: TableEntry, left: float) -> Control: - var wrap := MarginContainer.new() - wrap.mouse_filter = MOUSE_FILTER_PASS - wrap.add_theme_constant_override("margin_left", int(left)) - wrap.add_theme_constant_override("margin_right", 12) - wrap.add_theme_constant_override("margin_top", 2) - wrap.add_theme_constant_override("margin_bottom", 6) - var v := _vbox(3) - wrap.add_child(v) - var te := TextEdit.new() - te.text = e.effects - te.placeholder_text = "@hp -= 1\n@gold += 2d6\nreset @loot" - te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY - te.custom_minimum_size = Vector2(0, 58) - te.scroll_fit_content_height = true - te.add_theme_font_override("font", Style.body(true)) - te.add_theme_font_size_override("font_size", 13) - te.add_theme_color_override("font_color", Style.INK) - te.add_theme_color_override("font_placeholder_color", Style.MUTED) - te.add_theme_color_override("caret_color", Style.INK) - te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55)) - var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Color(Style.BRASS_DARK, 0.4)) - var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Style.COPPER) - var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Style.DANGER_INK) - v.add_child(te) - var msg := Style.make_label("", Style.body(true), 12, Style.DANGER_INK) - msg.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART - v.add_child(msg) - var check := func() -> void: - var problems := Effects.validate(TemplateKit.probe(te.text)) - var lines := PackedStringArray() - for p: Dictionary in problems: - lines.append("⚠ %s: %s" % [p["src"], p["error"]]) - msg.text = "\n".join(lines) - msg.visible = not lines.is_empty() - te.add_theme_stylebox_override("normal", bad_box if not lines.is_empty() else ok_box) - te.add_theme_stylebox_override("focus", bad_box if not lines.is_empty() else focus_box) - te.text_changed.connect(func() -> void: - e.effects = te.text - check.call() - main.mark_dirty() - ) - check.call() - return wrap - - ## A sheet card's one row: the rendered template in Play, its editor in Build. func _make_sheet_row(e: TableEntry, build: bool) -> Control: var row := PanelContainer.new() @@ -1047,16 +1135,16 @@ func _make_sheet_row(e: TableEntry, build: bool) -> Control: e.text = te.text main.mark_dirty() ) + te.focus_entered.connect(func() -> void: _select_entry(e.id)) v.add_child(te) - var tools := _hbox(4) - tools.add_child(_toggle_button("ƒ", "Effects that run when the chain reaches this sheet", - _open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty())) - tools.add_child(_toggle_button("i", "Details shown when hovering the sheet", - _open_details, e.id, e.details.strip_edges() != "", false)) + var tools := _vbox(2) + if e.effects.strip_edges() != "": + tools.add_child(_effects_chip(e)) var pv := Style.make_label("Preview on the board in Play", Style.body_italic(true), 12, Style.MUTED) pv.size_flags_vertical = SIZE_SHRINK_CENTER tools.add_child(pv) v.add_child(tools) + _hook_select(row, e.id) _sheet_label = null else: _sheet_label = RichText.label("", 15, Style.INK, true) @@ -1090,7 +1178,8 @@ func _make_variable_body(build: bool) -> Control: v.add_child(_var_hint) if build: var h := _hbox(8) - var start := Style.make_label("Starts at %s" % (table.initial if table.initial.strip_edges() != "" else ("0" if table.var_type == "number" else "nothing")), + var init := RulesView.dice(table.initial, main.data, _plain) if table.initial.strip_edges() != "" else "" + var start := Style.make_label("Starts at %s" % (init if init != "" else ("0" if table.var_type == "number" else "nothing")), Style.body(true), 12, Style.MUTED) start.size_flags_horizontal = SIZE_EXPAND_FILL start.size_flags_vertical = SIZE_SHRINK_CENTER @@ -1109,10 +1198,96 @@ func _make_variable_body(build: bool) -> Control: return wrap +## A collection card's body: its members with their live values (refilled by +## refresh_live()), and in Build "+ Add …", which selects the card so the +## inspector can add a member. +func _make_collection_body(build: bool) -> Control: + var wrap := MarginContainer.new() + wrap.mouse_filter = MOUSE_FILTER_PASS + wrap.add_theme_constant_override("margin_left", 12) + wrap.add_theme_constant_override("margin_right", 14) + wrap.add_theme_constant_override("margin_top", 6) + wrap.add_theme_constant_override("margin_bottom", 10) + var v := _vbox(6) + wrap.add_child(v) + _members_box = _vbox(0) + v.add_child(_members_box) + if build: + var add := _footer_button("+ Add " + Describe._singular(Formatter.strip_tags(table.name).strip_edges().to_lower()), Style.INK) + add.size_flags_horizontal = SIZE_FILL + add.tooltip_text = "Add a member in the inspector" + add.set_meta("collection_add", true) + add.pressed.connect(func() -> void: + if main.has_method("select_card"): + main.call("select_card", table.id) + else: + main.request_table_settings(table.id) + ) + v.add_child(add) + return wrap + + +## A collection's members: [{name ("@skill_pilot"), label ("Pilot"), value +## (Variant or null when not set)}], set members first, then members only +## named by the board's rules, each sorted by label. +static func collection_members(t: RollTable, board: TowerBoard, vars: Dictionary) -> Array[Dictionary]: + var out: Array[Dictionary] = [] + if t == null or not t.is_collection() or t.var_name == "": + return out + var seen := {} + for v: Dictionary in RollContext.vars_with_prefix(vars, t.var_name + "_"): + var nm := "@" + str(v["name"]) + seen[nm] = true + out.append({"name": nm, "label": Describe.label(nm, board), "value": v["value"]}) + var named: Array[Dictionary] = [] + for kv: Dictionary in Builder.known_values(board): + if str(kv.get("collection", "")) == "@%s_*" % t.var_name and not seen.has(str(kv["name"])): + seen[str(kv["name"])] = true + named.append({"name": str(kv["name"]), "label": str(kv["label"]), "value": null}) + var by_label := func(a: Dictionary, b: Dictionary) -> bool: return str(a["label"]).naturalnocasecmp_to(str(b["label"])) < 0 + out.sort_custom(by_label) + named.sort_custom(by_label) + out.append_array(named) + return out + + +func _refresh_members() -> void: + var list := collection_members(table, main.data, main.persistent_vars) + var key := var_to_str(list) + str(_plain) + if key == _members_cache: + return + _members_cache = key + for c in _members_box.get_children(): + _members_box.remove_child(c) + c.queue_free() + if list.is_empty(): + var none := Style.make_label("No members yet", Style.body_italic(true), 14, Style.MUTED) + none.mouse_filter = MOUSE_FILTER_IGNORE + _members_box.add_child(none) + return + for m: Dictionary in list: + var h := _hbox(8) + h.custom_minimum_size = Vector2(0, 28) + h.set_meta("member", str(m["name"])) + var nl := Style.make_label(str(m["label"]) if _plain else str(m["name"]), Style.body(true), 15, Style.INK) + nl.size_flags_horizontal = SIZE_EXPAND_FILL + nl.size_flags_vertical = SIZE_SHRINK_CENTER + nl.mouse_filter = MOUSE_FILTER_IGNORE + h.add_child(nl) + var val: Variant = m["value"] + var vl := Style.make_label("—" if val == null else Expr.format_value(val), Style.display(true), 17, Style.INK if val != null else Style.MUTED) + vl.size_flags_vertical = SIZE_SHRINK_CENTER + vl.mouse_filter = MOUSE_FILTER_IGNORE + h.add_child(vl) + _members_box.add_child(h) + + ## Re-renders the live parts (a variable's value, a sheet, a choice's ## question) from the current variables. Only touches labels whose text ## changed. Main calls it after rolls and edits, never per frame. func refresh_live() -> void: + if is_instance_valid(_members_box): + _refresh_members() if is_instance_valid(_var_value): var d := Roller.variable_display(main.data, main.persistent_vars, table) var shown := str(d["text"]) if str(d["text"]) != "" else "—" @@ -1177,33 +1352,6 @@ func _weight_edit(e: TableEntry) -> LineEdit: return edit -## A multi-line details editor (BBCode), shown under a row or the header. -func _details_editor(initial: String, placeholder: String, left: float, on_change: Callable) -> Control: - var wrap := MarginContainer.new() - wrap.mouse_filter = MOUSE_FILTER_PASS - wrap.add_theme_constant_override("margin_left", int(left)) - wrap.add_theme_constant_override("margin_right", 12) - wrap.add_theme_constant_override("margin_top", 2) - wrap.add_theme_constant_override("margin_bottom", 6) - var te := TextEdit.new() - te.text = initial - te.placeholder_text = placeholder - te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY - te.custom_minimum_size = Vector2(0, 66) - te.scroll_fit_content_height = true - te.add_theme_font_override("font", Style.body(true)) - te.add_theme_font_size_override("font_size", 13) - te.add_theme_color_override("font_color", Style.INK) - te.add_theme_color_override("font_placeholder_color", Style.MUTED) - te.add_theme_color_override("caret_color", Style.INK) - te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55)) - te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.RULE)) - te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.COPPER)) - te.text_changed.connect(func() -> void: on_change.call(te.text)) - wrap.add_child(te) - return wrap - - func _range_edit(e: TableEntry, is_lo: bool) -> LineEdit: var edit := LineEdit.new() edit.text = str(e.range_lo if is_lo else e.range_hi) @@ -1317,15 +1465,6 @@ func _make_footer(ranged: bool) -> Control: addc.tooltip_text = "Add a case before Otherwise" addc.pressed.connect(add_case) h.add_child(addc) - var det := _footer_button("Details", Style.INK) - det.tooltip_text = "Details shown when hovering the table's name" - if table.details.strip_edges() != "": - det.add_theme_color_override("font_color", Style.COPPER) - det.pressed.connect(func() -> void: - _table_details_open = not _table_details_open - rebuild() - ) - h.add_child(det) var spacer := Control.new() spacer.size_flags_horizontal = SIZE_EXPAND_FILL spacer.mouse_filter = MOUSE_FILTER_IGNORE @@ -1363,7 +1502,8 @@ func _skin_scrollbar(bar: VScrollBar) -> void: func _set_row_state(eid: String, state: RowState) -> void: if not rows.has(eid): return - (rows[eid] as PanelContainer).add_theme_stylebox_override("panel", _row_styles[state]) + var k := int(state) + (3 if eid == _selected_eid else 0) + (rows[eid] as PanelContainer).add_theme_stylebox_override("panel", _row_styles[k]) var parts: Dictionary = _row_parts[eid] var num: Label = parts["num"] if num: diff --git a/ui/table_preview.gd b/ui/table_preview.gd index a63fb68..ac3b8cb 100644 --- a/ui/table_preview.gd +++ b/ui/table_preview.gd @@ -6,6 +6,9 @@ extends RefCounted ## entries that lead further. Used by the choice pop-up's preview panel; the ## board's hover pop-ups can use it too. ## +## Rules (conditions, effects, option sources, loop rules, a check's rule) +## read in plain words unless opts "plain" is false (docs/PLAIN.md §6). +## ## Usage: TablePreview.build(board, table_id, {"count": "2"}) -> Control. ## Nothing in it takes the mouse, so it never gets in the way of what is ## underneath. @@ -17,8 +20,10 @@ const NEXT_HINT := "→ Next table" ## `opts`: count (String, e.g. "2" or "@terms": shown as "×2" when not "1"), ## max_rows (int), width (float, minimum width of the block), -## heading (String shown in place of the kind line, optional). +## heading (String shown in place of the kind line, optional), plain (bool, +## default RulesView.plain(null): plain words unless the text view is on). static func build(board: TowerBoard, table_id: String, opts: Dictionary = {}) -> Control: + var plain := bool(opts.get("plain", RulesView.plain(null))) var box := VBoxContainer.new() box.add_theme_constant_override("separation", 4) box.mouse_filter = Control.MOUSE_FILTER_IGNORE @@ -39,7 +44,7 @@ static func build(board: TowerBoard, table_id: String, opts: Dictionary = {}) -> head.add_child(name) var count := str(opts.get("count", "1")).strip_edges() if count != "" and count != "1": - head.add_child(_label("×" + count, 15, Style.COPPER, true)) + head.add_child(_label("×" + (RulesView.cut(Describe.dice(count, board), 18) if plain else count), 15, Style.COPPER, true)) box.add_child(head) box.add_child(_label(str(opts["heading"]) if opts.has("heading") else kind_line(t), 12, Style.MUTED, false)) @@ -49,7 +54,7 @@ static func build(board: TowerBoard, table_id: String, opts: Dictionary = {}) -> d.mouse_filter = Control.MOUSE_FILTER_IGNORE box.add_child(d) - var extra := summary_line(t) + var extra := summary_line(t, board, plain) if extra != "": box.add_child(_label(extra, 13, Style.INK, false, true)) @@ -69,7 +74,7 @@ static func build(board: TowerBoard, table_id: String, opts: Dictionary = {}) -> for i in t.entries.size(): if shown >= cap: break - list.add_child(_row(t, t.entries[i], i)) + list.add_child(_row(t, t.entries[i], i, board, plain)) shown += 1 if list.get_child_count() > 0: box.add_child(list) @@ -86,17 +91,24 @@ static func kind_line(t: RollTable) -> String: RollTable.KIND_LOOP: return "Loop card" RollTable.KIND_VARIABLE: - return "Variable card" + return "Collection card" if t.is_collection() else "Variable card" RollTable.KIND_SHEET: return "Sheet card" RollTable.KIND_ROUTER: return "Router · if / else if / otherwise" + RollTable.KIND_CHECK: + return "Check card · " + t.check_dice.strip_edges() var s := "Roll table · " + t.dice_label() return s + " · deck" if t.card_mode else s -## The kind-specific line: a choice card's question, a loop's rule, ... -static func summary_line(t: RollTable) -> String: +## The kind-specific line: a choice card's question, a loop's rule, ... With +## `plain`, rules read in plain words (labelled from `board`). +static func summary_line(t: RollTable, board: TowerBoard = null, plain: bool = false) -> String: + if plain: + var s := _plain_summary(t, board) + if s != "": + return s match t.kind: RollTable.KIND_CHOICE: var q := Formatter.strip_tags(t.prompt).strip_edges() @@ -124,7 +136,40 @@ static func summary_line(t: RollTable) -> String: return "" -static func _row(t: RollTable, e: TableEntry, index: int) -> Control: +static func _plain_summary(t: RollTable, board: TowerBoard) -> String: + match t.kind: + RollTable.KIND_CHOICE: + var q := Formatter.strip_tags(t.prompt).strip_edges() + var ask := "Asks: " + q if q != "" else "Asks the player" + match t.choice: + "number": + return "%s (a whole number from %s to %s)" % [ask, Describe.dice(t.min_expr, board), Describe.dice(t.max_expr, board)] + "text": + return ask + " (free text)" + if t.is_dynamic(): + return "%s\n%s" % [ask, RulesView.options_line(t, board, true)] + return ask + RollTable.KIND_LOOP: + return _cap(RulesView.loop_rule(t, board, true)) + RollTable.KIND_VARIABLE: + if t.is_collection(): + return "Holds your %s" % Formatter.strip_tags(t.name).strip_edges() + return "Holds %s (%s), kept between rolls" % [Describe.label("@" + t.var_name, board), t.var_type] + RollTable.KIND_CHECK: + return Describe.check(t, board) + RollTable.KIND_ROLL: + if t.is_expr_dice(): + return "Roll " + Describe.dice(t.dice, board) + return "" + + +static func _cap(s: String) -> String: + if s.begins_with("×"): + return "Repeats " + s + return s.substr(0, 1).to_upper() + s.substr(1) + + +static func _row(t: RollTable, e: TableEntry, index: int, board: TowerBoard = null, plain: bool = false) -> Control: var row := HBoxContainer.new() row.add_theme_constant_override("separation", 8) row.mouse_filter = Control.MOUSE_FILTER_IGNORE @@ -137,22 +182,29 @@ static func _row(t: RollTable, e: TableEntry, index: int) -> Control: col.size_flags_horizontal = Control.SIZE_EXPAND_FILL col.mouse_filter = Control.MOUSE_FILTER_IGNORE if t.kind == RollTable.KIND_ROUTER: - var cond := _label(TableCard.case_label(e), 12, Style.COPPER_DARK, true, true) + var cond := _label(RulesView.case_label(e, board, plain), 12, Style.COPPER_DARK, true, true) cond.max_lines_visible = 2 cond.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS col.add_child(cond) if t.kind == RollTable.KIND_CHOICE and t.choice == "pick" and e.show_if.strip_edges() != "": - var si := _label("only if " + e.show_if.strip_edges(), 12, Style.COPPER_DARK, true, true) + var si := _label(RulesView.show_if_line(e, board, plain), 12, Style.COPPER_DARK, true, true) si.max_lines_visible = 2 si.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS col.add_child(si) var tx := Formatter.strip_tags(e.text).strip_edges() if t.is_dynamic() and index == 0 and (tx == "" or tx == Roller.CHOSEN): tx = "The picked option" + if t.kind == RollTable.KIND_CHECK and (tx == "" or tx == TableCard.check_outlet_name(index)): + tx = TableCard.check_outlet_name(index) var text := _label(tx if tx != "" else "(empty)", 13, Style.INK, false, true) text.max_lines_visible = 2 text.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS col.add_child(text) + if e.effects.strip_edges() != "": + var fx := _label(RulesView.effects_line(e.effects, board, t, plain), 11, Style.COPPER_DARK, true, true) + fx.max_lines_visible = 1 + fx.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS + col.add_child(fx) if not e.pipes.is_empty(): col.add_child(_label(NEXT_HINT, 11, Style.COPPER, false)) row.add_child(col) @@ -179,6 +231,9 @@ static func row_label(t: RollTable, e: TableEntry, index: int) -> String: return "Each" if index == 0 else "After" RollTable.KIND_ROUTER: return str(index + 1) + RollTable.KIND_CHECK: + var outs := RulesView.check_outlets(t) + return outs[index] if index < 2 else str(index + 1) return t.num_label(e, index) diff --git a/ui/why_popover.gd b/ui/why_popover.gd new file mode 100644 index 0000000..e5f2c00 --- /dev/null +++ b/ui/why_popover.gd @@ -0,0 +1,197 @@ +class_name WhyPopover +extends PanelContainer +## "Why this?" (docs/PLAIN.md §4.4, §6): a card-styled pop-over listing why a +## step of the last roll came out the way it did, one Describe.why() sentence +## per trace fact. +## +## A step's own facts (its inputs, roll or check, router cases, effects) come +## with the facts its parent step recorded about the pipe that led here: the +## "only if" / "otherwise" choices aimed at this card, and the parent's +## effects on the values those conditions read. Steps from old history +## records have no facts, so they get no button (has_why() is false). +## +## Opened by ResultTray's "Why this?" buttons; it sits above the button, closes +## on Esc, on a click outside it, or on the button again. The same lines show +## in hover pop-ups (DetailsPopup.why_bbcode()). + +const WIDTH := 460.0 + +var _title: Label +var _list: RichTextLabel +## The control that opened it (a second press on it closes). +var opener: Control +## Lines shown, for tests. +var lines: PackedStringArray = [] + + +func _init() -> void: + top_level = true + z_index = 90 + mouse_filter = MOUSE_FILTER_STOP + var sb := Style.box(Style.CARD, 9, [14, 10, 14, 12]) + Style.bordered(sb, 2, Style.BRASS) + sb.shadow_color = Color(0, 0, 0, 0.4) + sb.shadow_size = 16 + sb.shadow_offset = Vector2(0, 6) + add_theme_stylebox_override("panel", sb) + var v := VBoxContainer.new() + v.add_theme_constant_override("separation", 6) + v.mouse_filter = MOUSE_FILTER_IGNORE + add_child(v) + v.minimum_size_changed.connect(func() -> void: _place.call_deferred()) + _title = Style.make_label("", Style.caps(), 12, Style.MUTED) + _title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + _title.custom_minimum_size = Vector2(WIDTH, 0) + _title.mouse_filter = MOUSE_FILTER_IGNORE + v.add_child(_title) + _list = RichText.label("", 15, Style.INK, false) + _list.custom_minimum_size = Vector2(WIDTH, 0) + _list.mouse_filter = MOUSE_FILTER_IGNORE + v.add_child(_list) + hide() + + +## Shows the reasons for steps[index] above (or below) `at` (a global rect), +## or above `anchor` while it's on screen (it follows it as it moves). +func open(steps: Array, index: int, board: TowerBoard, plain: bool, at: Rect2, from: Control = null, anchor: Control = null) -> void: + opener = from + _anchor = anchor + lines = why_lines(steps, index, board, plain) + _title.text = title_for(steps[index]).to_upper() + _list.text = bbcode_list(lines) + _at = at + show() + _place() + # The list's height is known only after layout, so place it again then. + _place.call_deferred() + + +var _at := Rect2() +var _anchor: Control + + +func _place() -> void: + if not visible: + return + reset_size() + if _anchor != null and is_instance_valid(_anchor) and _anchor.is_visible_in_tree(): + _at = _anchor.get_global_rect() + var view := get_viewport_rect().size + var p := Vector2(_at.position.x, _at.position.y - size.y - 8.0) + if p.y < 8.0: + p.y = _at.end.y + 8.0 + p.x = clampf(p.x, 8.0, maxf(8.0, view.x - size.x - 8.0)) + global_position = p + + +## Keeps it placed while its text settles (a RichTextLabel learns its height +## a frame or two after it's filled). +func _process(_delta: float) -> void: + if visible: + _place() + + +func close() -> void: + opener = null + _anchor = null + hide() + + +func _input(ev: InputEvent) -> void: + if not visible: + return + var k := ev as InputEventKey + if k and k.pressed and k.keycode == KEY_ESCAPE: + close() + get_viewport().set_input_as_handled() + return + var mb := ev as InputEventMouseButton + if mb and mb.pressed and not get_global_rect().has_point(mb.global_position): + if opener != null and is_instance_valid(opener) and opener.get_global_rect().has_point(mb.global_position): + return # the button toggles it itself + close() + + +# ---------- Content (static, testable) ---------- + +## "Why Loot · A curio" +static func title_for(step: Dictionary) -> String: + var t := Formatter.strip_tags(str(step.get("table", ""))).strip_edges() + var s := Formatter.strip_tags(str(step.get("text", ""))).strip_edges().replace("\n", " ") + if s.length() > 48: + s = s.substr(0, 47).strip_edges() + "…" + return "Why %s · %s" % [t, s] if s != "" else "Why " + t + + +## True when steps[index] has something to explain. +static func has_why(steps: Array, index: int) -> bool: + return not facts_for(steps, index).is_empty() + + +## The facts that explain steps[index]: [[fact, prefix], ...]. The parent's +## facts come first (pipe choices aimed at this step's card, and its effects +## on the values they read, prefixed with the parent's text), then the step's +## own. +static func facts_for(steps: Array, index: int) -> Array: + var out: Array = [] + if index < 0 or index >= steps.size(): + return out + var step: Dictionary = steps[index] + var tid := str(step.get("table_id", "")) + var d := int(step.get("depth", 0)) + var parent: Dictionary = {} + if d > 0: + for k in range(index - 1, -1, -1): + var s: Dictionary = steps[k] + if int(s.get("depth", 0)) == d - 1: + parent = s + break + if not parent.is_empty() and parent.get("why") is Array: + var pipe_facts: Array = [] + var read := {} + for f: Variant in parent["why"]: + if not (f is Dictionary): + continue + var ty := str(f.get("type", "")) + if (ty == "when" or ty == "otherwise") and str(f.get("to", "")) == tid: + pipe_facts.append(f) + if f.get("values") is Dictionary: + for nm: Variant in f["values"]: + read[str(nm)] = true + if not pipe_facts.is_empty(): + var who := Formatter.strip_tags(str(parent.get("text", ""))).strip_edges().replace("\n", " ") + if who.length() > 40: + who = who.substr(0, 39).strip_edges() + "…" + for f: Variant in parent["why"]: + if f is Dictionary and str(f.get("type", "")) == "effect" and read.has(str(f.get("var", ""))): + out.append([f, who]) + for f: Variant in pipe_facts: + out.append([f, ""]) + if step.get("why") is Array: + for f: Variant in step["why"]: + if f is Dictionary: + out.append([f, ""]) + return out + + +## One sentence per fact, ending in a full stop. +static func why_lines(steps: Array, index: int, board: TowerBoard, plain: bool) -> PackedStringArray: + var out := PackedStringArray() + for pair: Array in facts_for(steps, index): + var s := Describe.why(pair[0], board, plain).strip_edges() + if s == "": + continue + if str(pair[1]) != "": + s = "%s: %s" % [pair[1], s] + if plain and not (s.ends_with(".") or s.ends_with("…")): + s += "." + out.append(s) + return out + + +## The lines as a BBCode bullet list (text escaped). +static func bbcode_list(ls: PackedStringArray) -> String: + var parts := PackedStringArray() + for l in ls: + parts.append("• " + RichText.plain(l)) + return "\n".join(parts) diff --git a/ui/why_popover.gd.uid b/ui/why_popover.gd.uid new file mode 100644 index 0000000..4574a0e --- /dev/null +++ b/ui/why_popover.gd.uid @@ -0,0 +1 @@ +uid://d178csgl7nfsc