Compare commits

...

5 commits

Author SHA1 Message Date
adb93c545c Join the inspector and display halves; starting values apply to rolls
- Cards read the inspector's selection ({kind, tid, eid}) and the
  inspector marks the selected row on every card when it changes.
- A variable card's starting value now applies: before a top-level
  roll, each declared variable that isn't set yet and has a starting
  value is set to it (a "starts at 9" Strength no longer reads as 0).
- Check cards in Build no longer repeat "Success Success": a result
  text equal to the outlet name shows as an empty field with a hint.
- test_options switches to the Text view through Main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:36:29 -06:00
c61d5c375c Merge branch 'worktree-agent-a2d9617f1052488e2' into plain-build 2026-11-08 21:31:52 -06:00
44a814cba9 Plain Build display: plain rules on cards, pipes and tray, Why this?, check/collection/inputs visuals
- 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 <noreply@anthropic.com>
2026-11-08 21:30:55 -06:00
2703faf212 Inspector polish: pinned New value, title follows typing, CLI flags, README
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:29:59 -06:00
ac3863d582 Build inspector with fill-in editors, value picker and Plain/Text switch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:24:25 -06:00
35 changed files with 5106 additions and 368 deletions

View file

@ -21,9 +21,16 @@ godot --path .
last few rolls.
- **Build mode** is for setting up tables. Edit names, results, weights and details in place,
add or delete results and tables, and drag a card by its header. Drag from a result's ●
onto another table to lay a pipe. Click a pipe to set how many times it rolls, save its
result as a variable, or remove it. The ⚙ on a card opens its settings: details, tags,
plain or dice table (e.g. 2d6), and Card mode.
onto another table to lay a pipe. The **inspector** docked on the right edits whatever is
selected: click a card's title (or its ⚙) for the card, a result's text for the result, or
a pipe for the pipe. Results get fill-in rows for their changes ("Subtract [1] from
[Luck ▾]") and a box per pipe with its inputs, **Only if** conditions ("[Luck ▾] [is at
least ▾] [2]"), **Otherwise**, count and "saves as". Cards get their kind's fields (check
dice, modifier and target; choice options; loop rules; router cases; collection members;
inputs). Value dropdowns list the board's values with search and **+ New value…**. "Edit
as text" switches any builder to the rule text. **More settings…** opens the card's full
settings (Card mode and the rest). The top bar's **Plain / Text** switch shows rules in
plain words or as rule text. » hides the inspector.
- **Undo and redo:** every change to the board can be undone: typing, weights, effects,
details and settings, adding and deleting results, cards and pipes, pipe options, moves,
groups, templates, Pack and Reset sample. **Ctrl+Z** undoes and **Ctrl+Shift+Z** or
@ -40,8 +47,8 @@ godot --path .
`[[Names -> hero]]` (saves the result as `{hero}` for the rest of the roll). `{@town|Towns}`
keeps a value across rolls until you clear it in the tray's Variables tab. BBCode such as
`[b]bold[/b]` works anywhere you type.
- **Logic cards** (see `docs/LOGIC.md`): Build mode's **+ Table ▾** also adds choice cards
(which option, how many, open ended), loops, variables and sheets. A choice card pauses the
- **Logic cards** (see `docs/LOGIC.md`): Build mode's **+ Card ▾** also adds check cards,
choice cards (which option, how many, open ended), loops, variables, collections and sheets. A choice card pauses the
roll with a pop-up (1–9 pick, R for Random, Enter confirms, Esc cancels); the steps so far
light up behind it. Loops show their rule (`× @rooms`, `while @hp > 0`); variable cards show
their live value; sheet cards show their template filled in, and become the tray's
@ -51,7 +58,7 @@ godot --path .
- **Branching:** click a pipe in Build mode to give it an **Only if** condition
(`@str >= 8`), or mark it **Otherwise** so it runs only when none of that result's
conditions are true. All of a result's conditions and pipe counts are checked once, before
any pipe runs, and only the pipes taken light up. A **Router** card (+ Table ▾) lists cases
any pipe runs, and only the pipes taken light up. A **Router** card (+ Card ▾) lists cases
("if @species = "Aslan"", "if @str >= 10", "Otherwise") and takes the first true one.
- **Options from variables:** a pick card's settings can take its options from variables
(`@skill_*` gives one option per set skill, `@contacts` one per list item), filtered with
@ -66,7 +73,7 @@ godot --path .
- **Collapsing:** the arrow beside a table's name collapses it. A collapsed table still shows
its last result. **Collapse all / Expand all** in the top bar does every table at once.
- **Groups:** in Build mode, Ctrl- or Shift-click card headers (or Ctrl-drag on the felt) to
select cards, then **Group** (Ctrl+G, the selection bar, or **+ Table ▾**). A group is a
select cards, then **Group** (Ctrl+G, the selection bar, or **+ Card ▾**). A group is a
frame behind its cards; drag its title bar to move them all, drop a card into a frame to
add it, drag it out to take it out. The chevron collapses the group into one compact
card that still shows its cards' last results, with pipes attached to its edges. The
@ -74,7 +81,7 @@ godot --path .
group and its cards (with undo). **Collapse all** and **Fit** include groups.
- **Templates:** save a card (⚙ → Save as template…), a group (⋯ → Save as template…) or a
selection as a reusable template. Write `{$name}` in any text to make a parameter; the
save dialog finds them and asks for a label and default. **+ Table ▾ → From template…**
save dialog finds them and asks for a label and default. **+ Card ▾ → From template…**
lists your templates and the built-in ones (2D skill check, ask-and-repeat, pick menu,
counter, simple sheet), asks for the parameters and drops fresh copies at the view
centre. Pipes to cards outside the template relink by name, or are listed if they can't.

View file

@ -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):

View file

@ -126,9 +126,28 @@ static func roll_async(board: TowerBoard, table_id: String, ctx: RollContext, de
ctx.halted = ""
ctx.root = {}
ctx.forget_declarations()
apply_starting_values(board, ctx)
return await _chain(board, table_id, depth, ctx)
## A variable card that says "starts at …" gives its variable that value
## the first time a roll needs it: before a top-level roll, each declared
## variable that isn't set yet and has a starting value is set to it (and
## saved like any other change). Variables with no starting value stay unset,
## and collections are left alone.
static func apply_starting_values(board: TowerBoard, ctx: RollContext) -> void:
if board == null:
return
for t in board.tables:
if t.kind != RollTable.KIND_VARIABLE or t.is_collection() or t.var_name == "":
continue
if t.initial.strip_edges() == "" or ctx.get_value("@" + t.var_name) != null:
continue
var r := t.initial_value(ctx)
if str(r.get("error", "")) == "":
ctx.save("@" + t.var_name, r["value"], t.id)
## The steps of the tree built so far (ctx.root), e.g. while a prompt is open.
static func progress(ctx: RollContext) -> Array:
return flatten(ctx.root, [])

View file

@ -170,7 +170,7 @@ lazy). No existing test changed.
## 3b. Router cards
A router (`kind: "router"`, "Router" in the **+ Table ▾** menu, "if / else if / otherwise")
A router (`kind: "router"`, "Router" in the **+ Card ▾** menu, "if / else if / otherwise")
has no dice. Its entries are **cases**, each with an entry-level `when` expression.
- When the chain reaches it, the cases are checked top to bottom and the **first** true case

View file

@ -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")

570
tests/test_inspector.gd Normal file
View file

@ -0,0 +1,570 @@
extends SceneTree
## The Build inspector (docs/PLAIN.md §6): selection, the effects and
## condition builders, Otherwise, pipe inputs, check fields and the modifier
## picker, collection members, options source, the value picker, the
## Plain/Text switch, undo, and dirty/save.
## Run: godot --headless --path . -s res://tests/test_inspector.gd -- --sample
var _failures := 0
var main: Main
var insp: Inspector
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
main = load("res://ui/main.tscn").instantiate()
root.add_child(main)
for i in 5:
await process_frame
if main._saving_enabled:
print("Saving is enabled; refusing to run.")
quit(2)
return
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
main.size = Vector2(1440, 900)
main.set_mode(Main.Mode.BUILD)
insp = main.inspector
await _load()
await _test_selection()
await _test_effects()
await _test_unparseable()
await _test_conditions()
await _test_otherwise()
await _test_pipe_inputs()
await _test_check()
await _test_collection()
await _test_options()
await _test_value_picker()
await _test_rules_view()
await _test_undo()
await _test_dirty_and_save()
await _test_other_cards()
await _test_add_kinds()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _check(ok: bool, what: String) -> void:
if ok:
print(" ok %s" % what)
else:
_failures += 1
print(" FAIL %s" % what)
func _eq(a: Variant, b: Variant, what: String) -> void:
_check(a == b, "%s (got %s, want %s)" % [what, JSON.stringify(a), JSON.stringify(b)])
func _frames(n: int = 2) -> void:
for i in n:
await process_frame
func _board_dict() -> Dictionary:
return {"format_version": 2, "id": "insp-test", "name": "Inspector test", "tables": [
{"id": "gate", "name": "Force the gate", "kind": "check", "x": 40, "y": 40, "check_dice": "2d6",
"check_mod": "dm(@str)", "check_cmp": "ge", "check_target": "8",
"entries": [{"id": "e1", "text": "Success", "pipes": ["beyond"]}, {"id": "e2", "text": "Failure"}]},
{"id": "beyond", "name": "Beyond the gate", "x": 340, "y": 40, "entries": [
{"id": "e1", "text": "Store room"},
{"id": "e2", "text": "The warden's vault", "effects": "@luck -= 1", "pipes": [
{"table": "loot", "with": {"tier": "3"}, "when": "@luck >= 2"},
{"table": "curios", "with": {"tier": "1"}, "otherwise": true}]}]},
{"id": "loot", "name": "Loot", "x": 700, "y": 20, "inputs": [{"name": "tier", "label": "Tier", "default": "1"}],
"entries": [{"id": "e1", "text": "Silver"}]},
{"id": "curios", "name": "Curios", "x": 700, "y": 300, "inputs": [{"name": "tier", "label": "Tier", "default": "1"}],
"entries": [{"id": "e1", "text": "A curio"}]},
{"id": "learn", "name": "Learn", "kind": "choice", "choice": "pick", "x": 340, "y": 380,
"entries": [{"id": "e1", "text": "Option 1"}, {"id": "e2", "text": "Option 2"}]},
{"id": "str", "name": "Strength", "kind": "variable", "var_name": "str", "var_type": "number", "initial": "9", "x": 40, "y": 330, "entries": []},
{"id": "luck", "name": "Luck", "kind": "variable", "var_name": "luck", "var_type": "number", "initial": "2", "x": 40, "y": 470, "entries": []},
{"id": "skills", "name": "Skills", "kind": "variable", "var_name": "skill", "var_type": "collection", "x": 40, "y": 610, "entries": []},
{"id": "rt", "name": "Router", "kind": "router", "x": 1000, "y": 40, "entries": [
{"id": "c1", "text": "Strong", "when": "@str >= 8"}, {"id": "c2", "text": "Otherwise"}]},
{"id": "lp", "name": "Repeat", "kind": "loop", "loop_mode": "times", "loop_expr": "3", "x": 1000, "y": 300,
"entries": [{"id": "e1", "text": "Each time"}, {"id": "e2", "text": "Afterwards"}]},
]}
func _load() -> void:
main.data.load_dict(_board_dict())
main.lit_entries.clear()
main.lit_pipes.clear()
main.persistent_vars.clear()
main._rebuild_cards()
main.clear_inspector()
await _frames(4)
func _t(id: String) -> RollTable:
return main.data.get_table(id)
func _vault() -> TableEntry:
return _t("beyond").find_entry("e2")
# ---------- Selection ----------
func _test_selection() -> void:
print("Selection")
_check(insp.visible, "the inspector shows in Build mode")
_check(insp.selection.is_empty(), "nothing is selected at first")
_check(_has_text(insp, "Select a card, a result or a pipe to edit it."), "the empty state says how to select")
main.select_card("gate")
_eq(main.inspector_selection(), {"kind": "card", "tid": "gate"}, "select_card")
_check(insp.fields.has("check_dice"), "a check card shows its dice field")
main.select_result("beyond", "e2")
_eq(insp.selection.get("kind"), "result", "select_result")
_check(insp.effects != null and insp.pipe_parts.has("loot") and insp.pipe_parts.has("curios"), "a result shows its effects and both pipes")
main.select_pipe("beyond:e2>loot")
_eq(insp.selection.get("to"), "loot", "select_pipe")
_eq(insp.pipe_parts.keys(), ["loot"], "a pipe shows only its own box")
_eq(main.board.pipes.select_key, "beyond:e2>loot", "the selected pipe is highlighted on the board")
main.clear_inspector()
_check(insp.selection.is_empty(), "clear_inspector")
main.open_pipe_options("beyond:e2>curios", Vector2(10, 10))
_eq(insp.selection.get("to"), "curios", "clicking a pipe in Build selects it in the inspector")
main.request_table_settings("loot")
_eq(insp.selection, {"kind": "card", "tid": "loot"}, "the card's ⚙ selects the card")
main.select_result("beyond", "nope")
_eq(insp.selection.get("tid"), "loot", "a missing result isn't selected")
main.set_mode(Main.Mode.PLAY)
_check(not insp.visible and insp.selection.is_empty(), "Play hides and clears the inspector")
main.set_mode(Main.Mode.BUILD)
_check(insp.visible, "Build shows it again")
insp.set_collapsed(true)
_check(insp.custom_minimum_size.x == Inspector.STRIP, "the inspector collapses to a strip")
main.select_card("gate")
_check(not insp.collapsed, "selecting something opens it again")
# Deleting the selected card empties the inspector.
main.select_card("lp")
var keep := _t("lp").to_dict()
main.delete_table("lp")
await _frames(2)
_check(insp.selection.is_empty(), "deleting the selected card clears the inspector")
main.undo()
await _frames(2)
_check(_t("lp") != null, "(undo brings the card back)")
_eq(_t("lp").to_dict()["name"], keep["name"], "(same card)")
func _has_text(n: Node, s: String) -> bool:
for c in n.get_children():
if (c is Label and (c as Label).text == s) or _has_text(c, s):
return true
return false
# ---------- Effects ----------
func _test_effects() -> void:
print("Effects builder")
main.select_result("beyond", "e2")
var fx := insp.effects
_eq(fx.rows.size(), 1, "one row per statement")
_eq([fx.rows[0]["op"], fx.rows[0]["var"], fx.rows[0]["amount"]], ["subtract", "@luck", "1"], "the row reads Subtract 1 from Luck")
fx.set_row_amount(0, "2")
_eq(_vault().effects, "@luck -= 2", "changing the amount writes the statement")
fx.set_row_op(0, "add")
_eq(_vault().effects, "@luck += 2", "changing the op")
fx.add_row()
_eq(_vault().effects, "@luck += 2", "a new row isn't written until it's filled in")
fx.set_row_var(1, "@str")
_eq(_vault().effects, "@luck += 2\n@str += 1", "picking its value writes it, joined by a newline")
fx.set_row_op(1, "set")
fx.set_row_amount(1, "Millbrook")
_eq(_vault().effects, "@luck += 2\n@str = \"Millbrook\"", "a word typed as an amount becomes quoted text")
fx.set_row_amount(1, "1d6 + 2")
_eq(_vault().effects, "@luck += 2\n@str = 1d6 + 2", "an expression stays as written")
fx.set_row_op(1, "append")
fx.set_row_var(1, "@traits")
fx.set_row_amount(1, "Psionic")
_eq(_vault().effects, "@luck += 2\n@traits += \"Psionic\"", "Add to list")
fx.set_row_op(1, "remove")
_eq(_vault().effects, "@luck += 2\n@traits -= \"Psionic\"", "Remove from list")
fx.set_row_op(1, "reset")
_eq(_vault().effects, "@luck += 2\nreset @traits", "Clear")
fx.set_row_op(1, "multiply")
_eq(_vault().effects, "@luck += 2\n@traits *= 1", "Multiply after Clear starts at 1")
fx.remove_row(1)
_eq(_vault().effects, "@luck += 2", "× removes the row")
# Typing in the row's field.
var amt := InspectorKit.find_tagged(fx, "res.fx.0.amount") as LineEdit
amt.text = "3"
amt.text_changed.emit("3")
_eq(_vault().effects, "@luck += 3", "typing in the amount field writes the statement")
# Edit as text and back.
fx.set_text_mode(true)
_check(fx.text_mode and InspectorKit.find_tagged(fx, "res.fx.raw") != null, "Edit as text shows the whole effects text")
fx.set_raw("@luck -= 1\n@str += 2")
_eq(_vault().effects, "@luck -= 1\n@str += 2", "the text is written as typed")
fx.set_text_mode(false)
_eq(fx.rows.size(), 2, "Use the builder brings back one row per statement")
_eq(Builder.parse_effects(_vault().effects).size(), 2, "(still two statements)")
await _frames()
func _test_unparseable() -> void:
print("Unparseable statements")
_vault().effects = "@luck -= 1\n@gold += 2 +\n@str += 1"
main.mark_dirty()
await _frames(2)
var fx := insp.effects
_eq(fx.rows.size(), 3, "every statement gets a row")
_check(not fx.rows[1]["ok"], "the broken statement isn't a builder row")
var le := InspectorKit.find_tagged(fx, "res.fx.1.src") as LineEdit
_check(le != null and le.text == "@gold += 2 +", "it shows as a text field with its text")
fx.set_row_amount(0, "5")
_eq(_vault().effects, "@luck -= 5\n@gold += 2 +\n@str += 1", "editing another row keeps it exactly")
fx.set_text_mode(true)
fx.set_text_mode(false)
_check(fx.text_mode, "Use the builder waits until every statement parses")
fx.set_raw("@luck -= 5\n@gold += 2\n@str += 1")
fx.set_text_mode(false)
_check(not fx.text_mode and fx.rows.size() == 3 and fx.rows[1]["ok"], "then the builder takes over")
_vault().effects = "@luck -= 1"
main.mark_dirty()
await _frames(2)
# ---------- Conditions ----------
func _test_conditions() -> void:
print("Condition builder")
main.select_result("beyond", "e2")
var cond: ConditionBuilder = insp.pipe_parts["loot"]["when"]
_eq(cond.clauses, [{"var": "@luck", "cmp": "ge", "value": "2"}], "the Only if reads as one clause")
cond.add_clause()
_eq(_vault().when_for("loot"), "@luck >= 2", "an empty clause isn't written")
cond.set_clause_var(1, "@str")
cond.set_clause_value(1, "8")
_eq(_vault().when_for("loot"), "@luck >= 2 and @str >= 8", "two clauses join with and")
cond.set_join("or")
_eq(_vault().when_for("loot"), "@luck >= 2 or @str >= 8", "the switch makes it or")
cond.set_clause_cmp(1, "eq")
cond.set_clause_value(1, "Aslan")
_eq(_vault().when_for("loot"), "@luck >= 2 or @str = \"Aslan\"", "a word is compared as quoted text")
cond.set_clause_cmp(1, "set")
_eq(_vault().when_for("loot"), "@luck >= 2 or @str", "is set has no amount")
cond.remove_clause(1)
_eq(_vault().when_for("loot"), "@luck >= 2", "× removes a clause")
# A condition the builder can't show stays text.
_vault().set_pipe_when("loot", "@luck >= 2 and @str > 1 or @x")
main.mark_dirty()
await _frames(2)
cond = insp.pipe_parts["loot"]["when"]
_check(cond.text_mode, "mixed and/or shows as text")
cond.set_raw("@luck >= 3")
_eq(_vault().when_for("loot"), "@luck >= 3", "the text is written")
cond.set_raw("@luck >= = 3")
_eq(_vault().when_for("loot"), "@luck >= 3", "text that doesn't work isn't written")
cond.set_raw("@luck >= 2")
cond.set_text_mode(false)
_check(not cond.text_mode and cond.clauses.size() == 1, "Use the builder once it parses")
await _frames()
func _test_otherwise() -> void:
print("Otherwise")
main.select_result("beyond", "e2")
var loot_other: CheckBox = insp.pipe_parts["loot"]["otherwise"]
var cur_other: CheckBox = insp.pipe_parts["curios"]["otherwise"]
_check(cur_other.button_pressed and not cur_other.disabled, "the otherwise pipe is ticked")
_check(loot_other.disabled and not loot_other.button_pressed, "Otherwise is off while Only if is set")
insp.set_pipe_when("loot", "")
_check(not loot_other.disabled, "clearing Only if allows Otherwise")
insp.set_pipe_otherwise("loot", true)
_check(_vault().is_otherwise("loot") and loot_other.button_pressed, "ticking Otherwise writes it")
insp.set_pipe_when("loot", "@luck >= 2")
_check(not _vault().is_otherwise("loot") and loot_other.disabled, "an Only if turns Otherwise off")
insp.set_pipe_otherwise("curios", false)
_check(not _vault().is_otherwise("curios"), "unticking")
cur_other.toggled.emit(true)
_check(_vault().is_otherwise("curios"), "the checkbox writes it too")
insp.set_pipe_count("loot", "2")
_eq(_vault().count_text("loot"), "2", "count")
insp.set_pipe_count("loot", "@x +")
_eq(_vault().count_text("loot"), "2", "a bad count isn't written")
insp.set_pipe_save("loot", "@weapon")
_eq(_vault().save_for("loot"), "@weapon", "saves as")
insp.set_pipe_save("loot", "not a name")
_eq(_vault().save_for("loot"), "@weapon", "a bad name isn't saved")
insp.set_pipe_save("loot", "")
insp.set_pipe_count("loot", "1")
await _frames()
func _test_pipe_inputs() -> void:
print("Pipe inputs")
main.select_result("beyond", "e2")
var le: LineEdit = insp.pipe_parts["loot"]["inputs"]["tier"]
_eq(le.text, "3", "the target's input shows the passed value")
_eq(le.placeholder_text, "1", "its default is the placeholder")
le.text = "5"
le.text_changed.emit("5")
_eq(_vault().with_for("loot"), {"tier": "5"}, "typing writes pipe_with")
insp.set_pipe_input("loot", "tier", "@luck + 1")
_eq(_vault().with_for("loot"), {"tier": "@luck + 1"}, "an expression")
insp.set_pipe_input("loot", "tier", "@luck +")
_eq(_vault().with_for("loot"), {"tier": "@luck + 1"}, "a broken one isn't written")
insp.set_pipe_input("loot", "tier", "")
_eq(_vault().with_for("loot"), {}, "empty uses the default")
insp.set_pipe_input("loot", "tier", "3")
await _frames()
# ---------- Cards ----------
func _test_check() -> void:
print("Check card")
main.select_card("gate")
var t := _t("gate")
var sentence: Label = insp.fields["sentence"]
_eq(sentence.text, Describe.check(t, main.data), "a live sentence")
_check(sentence.text.contains("Strength"), "it names the modifier's value: %s" % sentence.text)
InspectorCard.set_check(insp, "check_target", "9")
_eq(t.check_target, "9", "target")
_check(sentence.text.contains("9"), "the sentence follows: %s" % sentence.text)
InspectorCard.set_check(insp, "check_cmp", "le")
_check(t.check_cmp == "le" and sentence.text.contains("or less"), "or less")
InspectorCard.set_check(insp, "check_dice", "3d6")
_eq(t.check_dice, "3d6", "dice")
InspectorCard.set_check(insp, "check_dice", "")
_eq(t.check_dice, "3d6", "empty dice aren't written")
_eq(InspectorCard.modifier_value("dm(@str)"), "@str", "dm(@str) reads as Strength in the picker")
_eq(InspectorCard.modifier_value(""), InspectorCard.NONE, "empty is none")
_eq(InspectorCard.modifier_value("@str + 1"), InspectorCard.AS_TEXT, "anything else is text")
var picker: ValuePicker = insp.fields["check_mod_picker"]
_eq(picker.value, "@str", "the picker shows the modifier's value")
picker.choose("@luck")
_eq(t.check_mod, "dm(@luck)", "picking Luck writes dm(@luck)")
InspectorCard.choose_modifier(insp, InspectorCard.NONE)
_eq(t.check_mod, "", "none clears it")
InspectorCard.choose_modifier(insp, InspectorCard.AS_TEXT)
var le: LineEdit = insp.fields.get("check_mod")
_check(le != null, "Edit as text shows the modifier as a field")
le.text = "@str - 1"
le.text_changed.emit("@str - 1")
_eq(t.check_mod, "@str - 1", "typed text is written")
insp.rebuild()
_check(insp.fields.has("check_mod"), "a modifier the picker can't show stays text")
InspectorCard.set_check(insp, "check_mod", "dm(@str)")
InspectorCard.set_check(insp, "check_cmp", "ge")
InspectorCard.set_check(insp, "check_target", "8")
InspectorCard.set_check(insp, "check_dice", "2d6")
await _frames()
func _test_collection() -> void:
print("Collection members")
main.select_card("skills")
var t := _t("skills")
_eq(insp.members(t), [], "no members at first")
var item := InspectorCard.add_member(insp, t)
_eq(item, "new", "+ Add member")
_eq(main.persistent_vars.get("skill_new", {}).get("value"), 0, "it's the board value @skill_new = 0")
InspectorCard.set_member(insp, t, "new", "2")
InspectorCard.rename_member(insp, t, "new", "pilot")
_check(not main.persistent_vars.has("skill_new"), "renaming drops the old name")
_eq(main.persistent_vars.get("skill_pilot", {}).get("value"), 2, "and keeps the value under the new one")
InspectorCard.add_member(insp, t)
InspectorCard.rename_member(insp, t, "new", "gun_combat")
_eq(insp.members(t), [["gun_combat", "0"], ["pilot", "2"]], "members list name and value")
_check(InspectorKit.find_tagged(insp, "member.pilot.value") != null, "each member has a value field")
InspectorCard.remove_member(insp, t, "gun_combat")
_eq(insp.members(t), [["pilot", "2"]], "× removes a member")
_eq(Describe.label("@skill_pilot", main.data), "Pilot", "(members are labelled through the collection)")
await _frames()
func _test_options() -> void:
print("Options source")
main.select_card("learn")
var t := _t("learn")
_check(not t.is_dynamic(), "a fixed list at first")
var err := InspectorCard.set_options(insp, "@skill_*", "")
_eq(err, "", "From a collection")
_check(t.is_dynamic() and t.options_from == "@skill_*", "options come from Skills")
var where: ConditionBuilder = insp.fields.get("options_where")
_check(where != null, "a where builder")
where.add_clause("option_value", "ge", "1")
_eq(t.options_where, "option_value >= 1", "where Its value is at least 1")
var picker: ValuePicker = insp.fields["options_from"]
_eq(picker.value, "@skill_*", "the source picker shows the collection")
_check(picker.items().any(func(it: Dictionary) -> bool: return it["name"] == "@skill_*"), "it offers collections")
_check(not picker.items().any(func(it: Dictionary) -> bool: return it["name"] == "@luck"), "but not numbers")
_eq(insp.apply_settings({"options_mode": "fixed"}, true), "", "back to a fixed list")
_check(t.options_from == "" and not t.is_dynamic(), "options_from is cleared")
await _frames()
func _test_value_picker() -> void:
print("Value picker")
var p := ValuePicker.new(main, "")
root.add_child(p)
var names := p.items().map(func(it: Dictionary) -> String: return it["name"])
_check(names.has("@luck") and names.has("@str"), "it lists the board's values")
var luck: Dictionary = p.items().filter(func(it: Dictionary) -> bool: return it["name"] == "@luck")[0]
_eq([luck["label"], luck["kind"], luck["group"]], ["Luck", "number", "Variables"], "with label, kind and group")
_check(names.find("@luck") < names.find("@skill_pilot") or not names.has("@skill_pilot"), "variables come first")
_check(names.has("@skill_pilot"), "collection members with values are offered")
_check(not names.has("@skill_*"), "collection patterns only where they fit")
p.allow_patterns = true
_check(p.items().any(func(it: Dictionary) -> bool: return it["name"] == "@skill_*" and it["group"] == "Collections"), "grouped under Collections")
_eq(p.filtered("lu").map(func(it: Dictionary) -> String: return it["name"]), ["@luck"], "search by label")
p.open_menu()
await _frames()
_check(p.shown_names().has("@luck"), "the open menu lists them")
p.close_menu()
var got: Array = []
p.value_chosen.connect(func(n: String) -> void: got.append(n))
p.choose("@str")
_eq(got, ["@str"], "choosing emits value_chosen")
_check(p.text.begins_with("Strength"), "the button shows the label: %s" % p.text)
var n := p.create_value("Fame", true)
_eq(n, "@fame", "+ New value… names it")
var card := main.variable_card("fame")
_check(card != null and card.name == "Fame", "Show on the board adds a variable card")
_eq(got.back(), "@fame", "and picks it")
var steps := main.edits.undo_stack.size()
n = p.create_value("Mood", false)
_eq(n, "@mood", "without a card")
_check(main.variable_card("mood") == null and main.edits.undo_stack.size() == steps, "no card, no board change")
p.queue_free()
await _frames()
func _test_rules_view() -> void:
print("Plain / Text switch")
var got: Array = []
main.rules_view_changed.connect(func(v: String) -> void: got.append(v))
_check(main.rules_plain() and main.rules_view() == "plain", "plain words by default")
main.select_result("beyond", "e2")
main.set_rules_view("text")
_eq(got, ["text"], "rules_view_changed fires")
_check(not main.rules_plain(), "rules_plain() follows")
_check(insp.effects.text_mode, "the inspector shows rule text")
_check((insp.pipe_parts["loot"]["when"] as ConditionBuilder).text_mode, "conditions too")
main.set_rules_view("text")
_eq(got.size(), 1, "setting the same view again doesn't fire")
main.set_rules_view("bogus")
_eq(main.rules_view(), "text", "unknown views are ignored")
main._rules_buttons[0].pressed.emit()
_eq(main.rules_view(), "plain", "the top-bar switch sets it")
_check(not insp.effects.text_mode, "builders are back")
await _frames()
func _test_undo() -> void:
print("Undo")
main._commit_edits()
main.select_result("beyond", "e2")
var before := _vault().effects
insp.effects.set_row_amount(0, "7")
main._commit_edits()
_eq(_vault().effects, "@luck -= 7", "(the edit)")
main.undo()
await _frames(2)
_eq(_vault().effects, before, "undo puts the effects back")
_eq(insp.effects.rows[0]["amount"], "1", "the inspector shows the old text")
_eq(insp.selection.get("eid"), "e2", "and keeps the selection")
main.redo()
await _frames(2)
_eq(_vault().effects, "@luck -= 7", "redo")
# Typing in a field is one step once it pauses.
var le: LineEdit = insp.fields["text"]
le.grab_focus()
var steps := main.edits.undo_stack.size()
for s in ["The vault", "The vaults", "The vaults!"]:
le.text = s
le.text_changed.emit(s)
_eq(main.edits.undo_stack.size(), steps, "typing waits for a pause")
main._commit_edits()
_eq(main.edits.undo_stack.size(), steps + 1, "then makes one step")
le.release_focus()
main.undo()
await _frames(2)
_eq(_vault().text, "The warden's vault", "one undo takes all the typing back")
await _frames()
func _test_dirty_and_save() -> void:
print("Dirty and save")
main.select_card("loot")
var rev := main.edit_rev
main._saving_enabled = true
main._save_timer.stop()
insp.apply_settings({"tags": "loot, treasure"})
_check(main.edit_rev > rev, "an inspector edit marks the board dirty")
_check(not main._save_timer.is_stopped(), "and schedules a save")
main._save_timer.stop()
main._saving_enabled = false
_eq(_t("loot").tags, ["loot", "treasure"], "tags")
var copy := TowerBoard.new()
copy.load_dict(main.data.to_dict())
_eq(copy.get_table("loot").tags, ["loot", "treasure"], "the saved form has it")
_eq(copy.get_table("beyond").find_entry("e2").with_for("loot"), {"tier": "3"}, "pipe inputs are saved")
main._commit_edits()
_check(main.can_undo(), "and it's an undo step")
await _frames()
func _test_other_cards() -> void:
print("Other cards")
main.select_card("loot")
var t := _t("loot")
var rows: Array = insp.fields["inputs_rows"]
_eq(rows.size(), 1, "declared inputs are listed")
var le := InspectorKit.find_tagged(insp, "card.in.0.default") as LineEdit
le.text = "2"
le.text_changed.emit("2")
_eq(t.inputs, [{"name": "tier", "label": "Tier", "default": "2"}], "editing a default")
(InspectorKit.find_tagged(insp, "card.name") as LineEdit).text_changed.emit("Treasure")
_eq(t.name, "Treasure", "name")
# Router cases.
main.select_card("rt")
var rt := _t("rt")
InspectorCard.add_case(insp)
_eq(rt.entries.size(), 3, "+ Add case")
_eq(rt.entries[2].id, "c2", "it goes before the Otherwise case")
insp.set_case_when(rt.entries[1].id, "@luck >= 1")
_eq(rt.entries[1].when, "@luck >= 1", "a case's condition")
_eq(Roller.lint_router(rt), [], "the router is fine")
# A router case from the result side.
main.select_result("rt", "c1")
_check(insp.case_builder != null and insp.case_builder.clauses.size() == 1, "a case result shows its condition builder")
# Loop.
main.select_card("lp")
InspectorCard.set_loop_mode(insp, "while")
_check(_t("lp").loop_mode == "while" and _t("lp").loop_expr == "i < 3", "a loop switches to while with a condition")
(insp.fields["loop_cond"] as ConditionBuilder).set_clause_value(0, "5")
_eq(_t("lp").loop_expr, "i < 5", "and the builder edits it")
InspectorCard.set_loop_mode(insp, "times")
_eq(_t("lp").loop_expr, "3", "back to times")
# Variable card.
main.select_card("luck")
_eq(insp.apply_settings({"initial": "3"}), "", "a variable's starting value")
_eq(_t("luck").initial, "3", "(written)")
_check(insp.apply_settings({"var_name": "Bad Name"}) != "", "a bad name is refused")
await _frames()
func _test_add_kinds() -> void:
print("+ Card ▾")
var labels: Array = main.ADD_KINDS.map(func(k: Array) -> String: return k[0])
_check(labels.any(func(s: String) -> bool: return s.begins_with("Check")), "Check card is in the menu")
_check(labels.any(func(s: String) -> bool: return s.begins_with("Collection")), "Collection is in the menu")
_eq(main._add_menu.text, "+ Card ▾", "the button reads + Card ▾")
var c := main.add_table(RollTable.KIND_CHECK)
_check(c.kind == RollTable.KIND_CHECK and c.name == "Check" and c.entries.size() == 2, "adding a check card")
_eq(insp.selection.get("tid"), c.id, "a new card is selected in the inspector")
var col := main.add_table(RollTable.KIND_VARIABLE, RollTable.VAR_COLLECTION)
_check(col.is_collection() and col.name == "Skills" and col.var_name == "skill_2", "adding a collection (%s, @%s)" % [col.name, col.var_name])
var v := main.add_table(RollTable.KIND_VARIABLE, "number")
_eq(v.name, "New variable", "a plain variable keeps its name")
await _frames()

View file

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

View file

@ -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,10 @@ 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
if main.has_method("set_rules_view"):
main.set_rules_view("text")
main._rebuild_cards()
await process_frame
var card := main.card_for("raise_card")
@ -547,9 +561,12 @@ 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
if main.has_method("set_rules_view"):
main.set_rules_view("plain")
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

408
tests/test_plain_display.gd Normal file
View file

@ -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

View file

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

View file

@ -291,6 +291,7 @@ func _gui_input(ev: InputEvent) -> void:
if build_left:
var key := pipes.pipe_at(world_mouse(), 11.0)
if key != "":
# The pipe opens in the inspector (Main.open_pipe_options).
main.open_pipe_options(key, mb.global_position)
accept_event()
return
@ -310,6 +311,7 @@ func _gui_input(ev: InputEvent) -> void:
# A plain click on the felt (no drag) clears the selection.
if build_left and _press_at.x >= 0.0 and mb.position.distance_to(_press_at) < 4.0:
main.clear_selection()
main.clear_inspector()
_press_at = Vector2(-1, -1)
_panning = false
mouse_default_cursor_shape = CURSOR_ARROW

View file

@ -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

View file

@ -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)

669
ui/inspector.gd Normal file
View file

@ -0,0 +1,669 @@
class_name Inspector
extends PanelContainer
## The Build-mode inspector (docs/PLAIN.md §6): a panel docked right of the
## board that edits the selected card, result or pipe with fill-in builders.
## Plain words mode shows builders; Text mode shows the rule text.
##
## Every change goes through Main (mark_dirty), so it is saved and is an undo
## step; typing is one step once it pauses. The panel rebuilds when the
## selected card changes from outside (an undo, an edit on the card), and
## keeps focus in the field being typed in.
const WIDTH := 340.0
const STRIP := 30.0
var main: Main
## {kind: "card" | "result" | "pipe", tid, eid?, to?}, or {} for nothing.
var selection: Dictionary = {}
var collapsed := false
var _body: VBoxContainer
var _scroll: ScrollContainer
var _content: VBoxContainer
var _strip: PanelContainer
var _sig := ""
var _sync_queued := false
var _writing := false
## Run after every write, to refresh live sentences and problem lines.
var _live: Array[Callable] = []
var _title_label: Label
# Parts the tests drive (rebuilt with the panel).
var effects: EffectsBuilder
var show_if_builder: ConditionBuilder
var case_builder: ConditionBuilder
## target id -> {box, when (ConditionBuilder), otherwise (CheckBox), count, save, inputs: {name: LineEdit}, taken}
var pipe_parts: Dictionary = {}
## Named fields of the card section ("name", "dice", "check_mod", ...).
var fields: Dictionary = {}
func setup(p_main: Main) -> void:
main = p_main
theme = Style.card_theme()
custom_minimum_size = Vector2(WIDTH, 0)
size_flags_vertical = Control.SIZE_EXPAND_FILL
var sb := Style.box(Style.CARD, 0, [0, 0, 0, 0])
sb.border_width_left = 1
sb.border_color = Color(0, 0, 0, 0.25)
add_theme_stylebox_override("panel", sb)
var stack := Control.new()
stack.size_flags_vertical = Control.SIZE_EXPAND_FILL
add_child(stack)
_body = VBoxContainer.new()
_body.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
_body.add_theme_constant_override("separation", 0)
stack.add_child(_body)
_scroll = ScrollContainer.new()
_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
_scroll.size_flags_vertical = Control.SIZE_EXPAND_FILL
_body.add_child(_scroll)
var pad := MarginContainer.new()
pad.size_flags_horizontal = Control.SIZE_EXPAND_FILL
for k in ["margin_left", "margin_right"]:
pad.add_theme_constant_override(k, 16)
pad.add_theme_constant_override("margin_top", 14)
pad.add_theme_constant_override("margin_bottom", 18)
_scroll.add_child(pad)
_content = InspectorKit.vbox(14)
pad.add_child(_content)
_strip = PanelContainer.new()
_strip.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
_strip.add_theme_stylebox_override("panel", Style.box(Style.CARD, 0, [2, 8, 2, 8]))
var open := Button.new()
open.text = "«"
open.tooltip_text = "Show the inspector"
open.size_flags_vertical = Control.SIZE_SHRINK_BEGIN
Style.skin_button(open, Style.box(Color(0, 0, 0, 0), 5, [4, 2, 4, 2]), Style.box(Style.HOVER_ROW, 5, [4, 2, 4, 2]),
Style.box(Style.HOVER_ROW, 5, [4, 2, 4, 2]), Style.COPPER_DARK)
open.add_theme_font_size_override("font_size", 18)
open.pressed.connect(func() -> void: set_collapsed(false))
_strip.add_child(open)
_strip.hide()
stack.add_child(_strip)
rebuild()
# ---------- Selection ----------
func select(sel: Dictionary) -> void:
if collapsed:
set_collapsed(false)
selection = sel
rebuild()
_mark_cards()
func clear() -> void:
selection = {}
rebuild()
_mark_cards()
## Puts the copper selection bar on the selected result's row, and clears it
## everywhere else.
func _mark_cards() -> void:
if main == null:
return
var tid := str(selection.get("tid", ""))
var eid := str(selection.get("eid", "")) if str(selection.get("kind", "")) == "result" else ""
for c in main.cards.values():
var card := c as TableCard
if card and card.has_method("set_selected_entry"):
card.set_selected_entry(eid if card.table.id == tid else "")
func set_collapsed(on: bool) -> void:
collapsed = on
custom_minimum_size.x = STRIP if on else WIDTH
_body.visible = not on
_strip.visible = on
if main and main.state:
main.state.set_setting("inspector_collapsed", on)
func selected_table() -> RollTable:
if selection.is_empty() or main == null:
return null
return main.data.get_table(str(selection.get("tid", "")))
func selected_entry() -> TableEntry:
var t := selected_table()
if t == null or not selection.has("eid"):
return null
return t.find_entry(str(selection["eid"]))
## Rebuilds once, at the end of the frame, if the selection changed from outside.
func sync() -> void:
if _writing or _sync_queued:
return
_sync_queued = true
_do_sync.call_deferred()
func _do_sync() -> void:
_sync_queued = false
if _signature() != _sig:
rebuild()
func _signature() -> String:
var t := selected_table()
if selection.is_empty():
return ""
if t == null or (selection.has("eid") and selected_entry() == null):
return "gone"
var d := t.to_dict()
for k in ["x", "y", "collapsed"]:
d.erase(k)
var parts := PackedStringArray([JSON.stringify(d), main.rules_view(), str(main.mode)])
for x in main.data.tables:
if x.kind == RollTable.KIND_VARIABLE:
parts.append("%s|%s|%s" % [x.name, x.var_name, x.var_type])
for e in t.entries:
for p in e.pipes:
var target := main.data.get_table(p)
parts.append(("%s|%s" % [target.name, JSON.stringify(target.inputs)]) if target else "-")
parts.append(str(main.lit_pipes.has(Roller.pipe_key(t.id, e.id, p))))
parts.append(str(main.is_entry_lit(t.id, e.id)))
if t.is_collection():
parts.append(JSON.stringify(members(t)))
return str(hash("\n".join(parts)))
# ---------- Writing ----------
## After the inspector changed table `t`: Main refreshes the card(s) and
## records the undo step. `rebuild_panel` redraws the inspector too (for
## changes that add or remove rows).
func wrote(t: RollTable, all_cards: bool = false, rebuild_panel: bool = false) -> void:
_writing = true
main.inspector_edited(t.id, all_cards)
main.mark_dirty()
_writing = false
_sig = _signature()
for f in _live:
if f.is_valid():
f.call()
_refresh_title()
if rebuild_panel:
rebuild()
## Applies table settings through TableSettingsDialog.apply_settings (the
## same rules as the settings dialog). Returns "" or the problem.
func apply_settings(over: Dictionary, rebuild_panel: bool = false) -> String:
var t := selected_table()
if t == null:
return "Nothing selected"
var s := {"name": t.name, "details": t.details, "tags": ", ".join(t.tags), "ranged": t.is_ranged(),
"dice": t.dice, "card_mode": t.card_mode, "deck_empty": t.deck_empty}
s.merge(over, true)
var r := TableSettingsDialog.apply_settings(t, s)
if not r["ok"]:
return str(r["error"])
if r.get("deck_reset", false) and main.state and main.data.id != "":
main.state.clear_deck(main.data.id, t.id)
wrote(t, t.kind == RollTable.KIND_VARIABLE, rebuild_panel)
return ""
func set_entry_text(s: String) -> void:
var e := selected_entry()
if e and e.text != s:
e.text = s
wrote(selected_table())
func set_entry_details(s: String) -> void:
var e := selected_entry()
if e and e.details != s:
e.details = s
wrote(selected_table())
func set_entry_effects(s: String) -> void:
var e := selected_entry()
if e and e.effects != s:
e.effects = s
wrote(selected_table())
func set_entry_show_if(s: String) -> void:
var e := selected_entry()
if e and e.show_if != s.strip_edges() and TableSettingsDialog.when_error(s) == "":
e.show_if = s.strip_edges()
wrote(selected_table())
## A router case's condition ("" makes it the Otherwise case).
func set_case_when(eid: String, s: String) -> void:
var t := selected_table()
var e := t.find_entry(eid) if t else null
if e and e.when != s.strip_edges() and TableSettingsDialog.when_error(s) == "":
e.when = s.strip_edges()
wrote(t)
func _pipe_entry() -> TableEntry:
return selected_entry()
func set_pipe_when(to: String, s: String) -> void:
var e := _pipe_entry()
if e == null or PipePopover.when_error(s) != "" or s.strip_edges() == e.when_for(to):
return
e.set_pipe_when(to, s)
wrote(selected_table())
_refresh_otherwise(to)
func set_pipe_otherwise(to: String, on: bool) -> void:
var e := _pipe_entry()
if e == null or on == e.is_otherwise(to):
return
e.set_pipe_otherwise(to, on)
wrote(selected_table())
_refresh_otherwise(to)
## Sets one input value passed down the pipe ("" uses the card's default).
func set_pipe_input(to: String, input_name: String, expr: String) -> void:
var e := _pipe_entry()
if e == null:
return
var w := e.with_for(to)
var s := expr.strip_edges()
if s != "" and InspectorKit.expr_error(s) != "":
return
if s == "":
w.erase(input_name)
else:
w[input_name] = s
if w == e.with_for(to):
return
e.set_pipe_with(to, w)
wrote(selected_table())
func set_pipe_count(to: String, s: String) -> void:
var e := _pipe_entry()
if e == null or PipePopover._count_error(s) != "":
return
var before := e.count_text(to)
e.set_pipe_count(to, s.strip_edges() if s.strip_edges() != "" else "1")
if e.count_text(to) != before:
wrote(selected_table())
func set_pipe_save(to: String, s: String) -> void:
var e := _pipe_entry()
if e == null or _save_error(s) != "" or s.strip_edges() == e.save_for(to):
return
e.set_pipe_save(to, s)
wrote(selected_table())
func remove_pipe(to: String) -> void:
var t := selected_table()
var e := selected_entry()
if t == null or e == null:
return
var was_pipe := str(selection.get("kind", "")) == "pipe"
main.remove_pipe(Roller.pipe_key(t.id, e.id, to))
if was_pipe:
select({"kind": "result", "tid": t.id, "eid": e.id})
else:
rebuild()
static func _save_error(s: String) -> String:
var t := TemplateKit.probe(s.strip_edges())
if t == "" or RegEx.create_from_string(PipePopover.SAVE_PATTERN).search(t) != null:
return ""
return "Use a name like weapon, or @weapon to keep it between rolls."
# ---------- Collections ----------
## A collection card's members: Array of [item, value] (item without the stem).
func members(t: RollTable) -> Array:
var out: Array = []
var pre := t.var_name + "_"
var names: Array = main.persistent_vars.keys()
names.sort_custom(func(a: String, b: String) -> bool: return a.naturalnocasecmp_to(b) < 0)
for n: String in names:
if n.begins_with(pre) and n.length() > pre.length():
var v: Variant = main.persistent_vars[n]
out.append([n.substr(pre.length()), Expr.format_value(v.get("value") if v is Dictionary else v)])
return out
# ---------- Building ----------
func rebuild() -> void:
var focus_key := ""
var caret := -1
var f := get_viewport().gui_get_focus_owner() if is_inside_tree() else null
if f and is_ancestor_of(f) and f.has_meta(InspectorKit.KEY):
focus_key = str(f.get_meta(InspectorKit.KEY))
if f is LineEdit:
caret = (f as LineEdit).caret_column
for c in _content.get_children():
_content.remove_child(c)
c.queue_free()
_live.clear()
effects = null
show_if_builder = null
case_builder = null
pipe_parts.clear()
fields.clear()
var t := selected_table()
var e := selected_entry()
if selection.has("eid") and e == null:
t = null
if t == null:
selection = {}
_empty()
else:
match str(selection.get("kind", "card")):
"result":
_result_section(t, e)
"pipe":
_pipe_section(t, e, str(selection.get("to", "")))
_:
InspectorCard.build(self, _content, t)
_sig = _signature()
if main and main.board and main.board.pipes:
main.board.pipes.select_key = Roller.pipe_key(t.id, e.id, str(selection["to"])) if t and str(selection.get("kind", "")) == "pipe" else ""
if focus_key != "":
var c := InspectorKit.find_tagged(_content, focus_key)
if c:
c.grab_focus()
if c is LineEdit and caret >= 0:
(c as LineEdit).caret_column = caret
func _head(kind: String, title: String) -> Control:
var h := InspectorKit.hbox(6)
var v := InspectorKit.vbox(2)
v.size_flags_horizontal = Control.SIZE_EXPAND_FILL
v.add_child(InspectorKit.flabel(kind))
var tl := Style.make_label(title, Style.display(), 22, Style.INK)
_title_label = tl
tl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
tl.custom_minimum_size = Vector2(120, 0)
v.add_child(tl)
h.add_child(v)
var hide_b := Button.new()
hide_b.text = "»"
hide_b.tooltip_text = "Hide the inspector"
hide_b.size_flags_vertical = Control.SIZE_SHRINK_BEGIN
Style.skin_button(hide_b, Style.box(Color(0, 0, 0, 0), 5, [6, 0, 6, 2]), Style.box(Style.HOVER_ROW, 5, [6, 0, 6, 2]),
Style.box(Style.HOVER_ROW, 5, [6, 0, 6, 2]), Style.MUTED, Style.INK)
hide_b.add_theme_font_size_override("font_size", 18)
hide_b.focus_mode = Control.FOCUS_NONE
hide_b.pressed.connect(func() -> void: set_collapsed(true))
h.add_child(hide_b)
return h
## Keeps the heading in step with the name or text being typed.
func _refresh_title() -> void:
if not is_instance_valid(_title_label):
return
var t := selected_table()
match str(selection.get("kind", "")):
"card":
if t:
_title_label.text = _title_of(t.name, "(no name)")
"result":
var e := selected_entry()
if e:
_title_label.text = _title_of(e.text, "(no text)")
func _empty() -> void:
_content.add_child(_head("Inspector", "Nothing selected"))
_content.add_child(InspectorKit.note("Select a card, a result or a pipe to edit it.", Style.MUTED, 15))
_content.add_child(InspectorKit.note("Click a card's title for the card, a result's text for the result, or a pipe on the felt for its options.", Style.MUTED, 13))
static func _title_of(s: String, fallback: String) -> String:
var t := Formatter.strip_tags(s).strip_edges()
return t if t != "" else fallback
## A link back to the card the result or pipe belongs to.
func _card_link(t: RollTable) -> Button:
var b := InspectorKit.link("On %s · edit the card" % _title_of(t.name, "this card"), "Show the card's settings")
b.add_theme_color_override("font_color", Style.MUTED)
b.pressed.connect(func() -> void: select({"kind": "card", "tid": t.id}))
return b
func _result_section(t: RollTable, e: TableEntry) -> void:
_content.add_child(_head("Selected result", _title_of(e.text, "(no text)")))
_content.add_child(_card_link(t))
var plain := main.rules_plain()
if t.kind != RollTable.KIND_SHEET:
var le := InspectorKit.line(e.text, "What this result says")
InspectorKit.tag(le, "res.text")
le.text_changed.connect(set_entry_text)
fields["text"] = le
_content.add_child(InspectorKit.field("Text", le))
var det := InspectorKit.text_box(e.details, "Shown on hover (optional)", 36.0)
InspectorKit.tag(det, "res.details")
det.text_changed.connect(func() -> void: set_entry_details(det.text))
fields["details"] = det
_content.add_child(InspectorKit.field("Details", det))
if t.kind == RollTable.KIND_CHOICE and t.choice == "pick" and not (t.is_dynamic() and t.entries.find(e) == 0):
show_if_builder = ConditionBuilder.new()
show_if_builder.setup(main, e.show_if, not plain, "res.show_if", {"empty_note": "Always offered."})
show_if_builder.changed.connect(set_entry_show_if)
_content.add_child(InspectorKit.field("Offer only if", show_if_builder))
if t.kind == RollTable.KIND_ROUTER:
_content.add_child(InspectorCard.case_block(self, t, e))
effects = EffectsBuilder.new()
effects.setup(main, e.effects, t, not plain, "res.fx")
effects.changed.connect(set_entry_effects)
_content.add_child(InspectorKit.field("When this comes up", effects))
var go := InspectorKit.vbox(8)
if e.pipes.is_empty():
go.add_child(InspectorKit.note("No pipes yet. Drag from the ● at the end of this result to a card.", Style.MUTED, 14))
for p in e.pipes:
go.add_child(_pipe_box(t, e, p))
_content.add_child(InspectorKit.field("Then go to", go))
_lint_lines(t, e)
func _pipe_section(t: RollTable, e: TableEntry, to: String) -> void:
if not e.pipes.has(to):
_result_section(t, e)
return
var target := main.data.get_table(to)
_content.add_child(_head("Selected pipe", "%s → %s" % [_title_of(e.text, "(no text)"), _title_of(target.name, to) if target else to]))
var back := InspectorKit.link("Edit the whole result", "Show the result this pipe leaves from")
back.add_theme_color_override("font_color", Style.MUTED)
back.pressed.connect(func() -> void: select({"kind": "result", "tid": t.id, "eid": e.id}))
_content.add_child(back)
_content.add_child(_pipe_box(t, e, to))
_lint_lines(t, e)
## Problems and hints the board check finds on this result's pipes.
func _lint_lines(t: RollTable, e: TableEntry) -> void:
var box := InspectorKit.vbox(3)
var fill := func() -> void:
for c in box.get_children():
box.remove_child(c)
c.queue_free()
for it: Dictionary in Roller.lint_pipes(main.data):
if str(it["table_id"]) == t.id and str(it["entry_id"]) == e.id:
var hint := str(it.get("level", "error")) == "hint" or str(it["message"]).contains("otherwise")
box.add_child(InspectorKit.note(("Note: " if hint else "Problem: ") + str(it["message"]) + ".",
Style.MUTED if hint else Style.DANGER_INK, 13))
box.visible = box.get_child_count() > 0
fill.call()
_live.append(fill)
_content.add_child(box)
func _pipe_box(t: RollTable, e: TableEntry, to: String) -> Control:
var target := main.data.get_table(to)
var parts := {"inputs": {}}
var taken := main.lit_pipes.has(Roller.pipe_key(t.id, e.id, to))
var panel := PanelContainer.new()
var sb := Style.bordered(Style.box(InspectorKit.TAKEN_BG if taken else InspectorKit.BOX_BG, 8, [10, 9, 10, 10]), 1, Style.BRASS if taken else Style.RULE)
panel.add_theme_stylebox_override("panel", sb)
var v := InspectorKit.vbox(8)
panel.add_child(v)
parts["box"] = panel
parts["taken"] = taken
var head := InspectorKit.hbox(8)
head.add_child(InspectorKit.word("→", Style.COPPER, true))
var tn := Style.make_label(_title_of(target.name, to) if target else to + " (missing)", Style.display(), 19, Style.INK)
tn.size_flags_horizontal = Control.SIZE_EXPAND_FILL
tn.clip_text = true
head.add_child(tn)
if taken:
head.add_child(_chip("taken last roll", Style.BRASS_DARK, Style.LIT))
elif main.is_entry_lit(t.id, e.id):
head.add_child(Style.make_label("not taken", Style.body_bold(), 12, Style.MUTED))
v.add_child(head)
# Inputs the target declares (and any extra names the pipe passes).
var w := e.with_for(to)
var names: Array = target.input_names() if target else []
for nm: String in w:
if not names.has(nm):
names.append(nm)
for nm: String in names:
var decl: Dictionary = target.find_input(nm) if target else {}
var row := InspectorKit.hbox(6)
var lab := str(decl.get("label", "")) if not decl.is_empty() else ""
var cap := InspectorKit.word(lab if lab != "" else RollContext.pretty_name(nm))
cap.custom_minimum_size = Vector2(64, 0)
cap.tooltip_text = "Input %s of %s" % [nm, target.name if target else to]
row.add_child(cap)
var def := str(decl.get("default", ""))
var le := InspectorKit.amount(str(w.get(nm, "")), def if def != "" else "0")
le.tooltip_text = "An expression passed as %s. Empty uses the card's default%s." % [nm, (" (" + def + ")") if def != "" else ""]
InspectorKit.tag(le, "pipe.%s.in.%s" % [to, nm])
var err := InspectorKit.error_label()
var nm_c := nm
le.text_changed.connect(func(s: String) -> void:
var msg := InspectorKit.expr_error(s, "This value")
InspectorKit.show_error(err, msg)
InspectorKit.mark(le, msg == "")
set_pipe_input(to, nm_c, s)
)
row.add_child(le)
if decl.is_empty():
row.add_child(InspectorKit.word("(not an input of this card)", Style.MUTED))
(parts["inputs"] as Dictionary)[nm] = le
v.add_child(row)
v.add_child(err)
# Only if / Otherwise.
var cond := ConditionBuilder.new()
cond.setup(main, e.when_for(to), not main.rules_plain(), "pipe.%s.when" % to,
{"add_label": "+ Only if…" if e.when_for(to) == "" else "+ Add condition"})
cond.changed.connect(func(s: String) -> void: set_pipe_when(to, s))
parts["when"] = cond
var when_box := InspectorKit.vbox(4)
when_box.add_child(InspectorKit.flabel("Only if"))
when_box.add_child(cond)
v.add_child(when_box)
var other := InspectorKit.check_box("Otherwise", e.is_otherwise(to))
other.tooltip_text = "Runs only when none of this result's \"Only if\" pipes is true"
other.toggled.connect(func(on: bool) -> void: set_pipe_otherwise(to, on))
parts["otherwise"] = other
v.add_child(other)
# Count and saves as.
var cr := InspectorKit.flow()
cr.add_child(InspectorKit.word("Rolls"))
var count := InspectorKit.amount(e.count_text(to), "1")
count.tooltip_text = "A number, or an expression such as @terms, answer or 1d3 (worked out when the pipe runs)"
InspectorKit.tag(count, "pipe.%s.count" % to)
var cerr := InspectorKit.error_label()
count.text_changed.connect(func(s: String) -> void:
var msg := PipePopover._count_error(s)
InspectorKit.show_error(cerr, msg)
InspectorKit.mark(count, msg == "")
set_pipe_count(to, s)
)
cr.add_child(count)
cr.add_child(InspectorKit.word("times"))
var sr := InspectorKit.hbox(6)
sr.add_child(InspectorKit.word("Saves as"))
var save := InspectorKit.line(e.save_for(to), "nothing (or a name)")
save.tooltip_text = "Keep the result as a value: a name lasts one roll, @name is kept between rolls"
InspectorKit.tag(save, "pipe.%s.save" % to)
save.text_changed.connect(func(s: String) -> void:
var msg := _save_error(s)
InspectorKit.show_error(cerr, msg)
InspectorKit.mark(save, msg == "")
set_pipe_save(to, s)
)
sr.add_child(save)
parts["count"] = count
parts["save"] = save
v.add_child(cr)
v.add_child(sr)
v.add_child(cerr)
var rm := InspectorKit.link("Remove pipe", "Delete this pipe")
rm.add_theme_color_override("font_color", Style.DANGER_INK)
rm.add_theme_color_override("font_hover_color", Style.DANGER_INK)
rm.pressed.connect(func() -> void: remove_pipe(to))
v.add_child(rm)
pipe_parts[to] = parts
_refresh_otherwise(to)
return panel
## Otherwise is off and disabled while the pipe has an Only if.
func _refresh_otherwise(to: String) -> void:
var parts: Dictionary = pipe_parts.get(to, {})
var e := _pipe_entry()
if parts.is_empty() or e == null:
return
var cb := parts["otherwise"] as CheckBox
var has_when := e.when_for(to) != ""
cb.disabled = has_when
cb.set_pressed_no_signal(e.is_otherwise(to))
cb.tooltip_text = "Turn off \"Only if\" first: a pipe with a condition isn't an otherwise pipe" if has_when \
else "Runs only when none of this result's \"Only if\" pipes is true"
static func _chip(text: String, fg: Color, bg: Color) -> Control:
var p := PanelContainer.new()
p.add_theme_stylebox_override("panel", Style.bordered(Style.box(bg, 9, [7, 1, 7, 2]), 1, Style.BRASS))
p.add_child(Style.make_label(text, Style.body_bold(), 12, fg))
p.size_flags_vertical = Control.SIZE_SHRINK_CENTER
return p
## Closes any open value-picker menu (before an undo rebuilds the board).
func close_menus() -> void:
_close_pickers(self)
func _close_pickers(n: Node) -> void:
for c in n.get_children():
if c is ValuePicker:
(c as ValuePicker).close_menu()
_close_pickers(c)

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

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

694
ui/inspector_card.gd Normal file
View file

@ -0,0 +1,694 @@
class_name InspectorCard
extends RefCounted
## The card section of the inspector: name, details, tags and inputs for
## every card, then the kind's own fields (roll dice, check, choice, loop,
## router cases, variable, collection members, sheet template). Writes go
## through Inspector (apply_settings / wrote), so the settings dialog's rules
## and the undo history apply.
const KIND_NAMES := {
RollTable.KIND_ROLL: "Roll table", RollTable.KIND_CHOICE: "Choice", RollTable.KIND_LOOP: "Loop",
RollTable.KIND_VARIABLE: "Variable", RollTable.KIND_SHEET: "Sheet", RollTable.KIND_ROUTER: "Router",
RollTable.KIND_CHECK: "Check",
}
const DM_PATTERN := "^dm\\(\\s*(@[a-z_][a-z0-9_]*)\\s*\\)$"
const NONE := "__none"
const AS_TEXT := "__text"
static func build(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var kind := "Collection" if t.is_collection() else str(KIND_NAMES.get(t.kind, "Card"))
box.add_child(insp._head("Selected card · " + kind, Inspector._title_of(t.name, "(no name)")))
var plain := insp.main.rules_plain()
var name := InspectorKit.line(t.name, "Name")
InspectorKit.tag(name, "card.name")
name.text_changed.connect(func(s: String) -> void:
if s.strip_edges() != "":
insp.apply_settings({"name": s})
)
insp.fields["name"] = name
box.add_child(InspectorKit.field("Label" if t.kind == RollTable.KIND_VARIABLE else "Name", name))
match t.kind:
RollTable.KIND_ROLL:
_roll(insp, box, t)
RollTable.KIND_CHECK:
_check(insp, box, t, plain)
RollTable.KIND_CHOICE:
_choice(insp, box, t, plain)
RollTable.KIND_LOOP:
_loop(insp, box, t, plain)
RollTable.KIND_ROUTER:
_router(insp, box, t, plain)
RollTable.KIND_VARIABLE:
if t.is_collection():
_collection(insp, box, t)
else:
_variable(insp, box, t)
RollTable.KIND_SHEET:
_sheet(insp, box, t)
var det := InspectorKit.text_box(t.details, "Notes about this card (optional)", 36.0)
InspectorKit.tag(det, "card.details")
det.text_changed.connect(func() -> void: insp.apply_settings({"details": det.text}))
insp.fields["details"] = det
box.add_child(InspectorKit.field("Details", det))
var tags := InspectorKit.line(", ".join(t.tags), "e.g. loot, town")
InspectorKit.tag(tags, "card.tags")
tags.text_changed.connect(func(s: String) -> void: insp.apply_settings({"tags": s}))
insp.fields["tags"] = tags
box.add_child(InspectorKit.field("Tags", tags))
if t.kind != RollTable.KIND_VARIABLE:
box.add_child(_inputs(insp, t))
var more := InspectorKit.link("More settings…", "Card mode, colours and the other settings")
more.pressed.connect(func() -> void: insp.main.open_table_settings(t.id))
box.add_child(more)
# ---------- Inputs (every rollable card) ----------
static func _inputs(insp: Inspector, t: RollTable) -> Control:
var v := InspectorKit.vbox(5)
v.add_child(InspectorKit.flabel("Inputs"))
v.add_child(InspectorKit.note("Values a pipe into this card can pass, like a Tier. Each one has a starting value.", Style.MUTED, 13))
var rows: Array = []
for inp: Dictionary in t.inputs:
rows.append(inp.duplicate())
insp.fields["inputs_rows"] = rows
var grid := GridContainer.new()
grid.columns = 4
grid.add_theme_constant_override("h_separation", 5)
grid.add_theme_constant_override("v_separation", 5)
v.add_child(grid)
var err := InspectorKit.error_label()
var write := func() -> void:
t.inputs = RollTable.clean_inputs(rows)
insp.wrote(t)
var lint := func() -> void:
var msgs := PackedStringArray()
for it: Dictionary in Roller.lint_inputs(insp.main.data, t):
if str(it["entry_id"]) == "":
msgs.append(str(it["message"]) + ".")
InspectorKit.show_error(err, "\n".join(msgs))
if not rows.is_empty():
for h in ["Name", "Label", "Default", ""]:
grid.add_child(InspectorKit.flabel(h))
for i in rows.size():
var r: Dictionary = rows[i]
for k in ["name", "label", "default"]:
var le := InspectorKit.line(str(r.get(k, "")), {"name": "tier", "label": "Tier", "default": "1"}[k], 0.0)
le.custom_minimum_size = Vector2(70, 0)
InspectorKit.tag(le, "card.in.%d.%s" % [i, k])
var key: String = k
le.text_changed.connect(func(s: String) -> void:
r[key] = s.strip_edges().trim_prefix("@").to_lower() if key == "name" else s
write.call()
)
grid.add_child(le)
var x := InspectorKit.xbutton("Remove this input")
x.pressed.connect(func() -> void:
rows.remove_at(i)
t.inputs = RollTable.clean_inputs(rows)
insp.wrote(t, false, true)
)
grid.add_child(x)
var add := InspectorKit.link("+ Add input")
add.pressed.connect(func() -> void:
var used := t.input_names()
var nm := "tier"
var k := 2
while used.has(nm):
nm = "input_%d" % k
k += 1
t.inputs.append({"name": nm, "label": RollContext.pretty_name(nm), "default": "1"})
insp.wrote(t, false, true)
)
v.add_child(add)
v.add_child(err)
lint.call()
insp._live.append(lint)
return v
# ---------- Roll ----------
static func _roll(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var v := InspectorKit.vbox(6)
var ranged := t.is_ranged()
var dice := InspectorKit.line(t.dice, "2d6", 90.0)
InspectorKit.tag(dice, "card.dice")
insp.fields["dice"] = dice
var err := InspectorKit.error_label()
var seg := ModalCard.segmented(["Plain", "Ranged"], 1 if ranged else 0, func(i: int) -> void:
var msg := insp.apply_settings({"ranged": i == 1, "dice": dice.text.strip_edges() if dice.text.strip_edges() != "" else "1d6"}, true)
InspectorKit.show_error(err, msg)
)
v.add_child(seg)
if ranged:
var row := InspectorKit.hbox(6)
row.add_child(InspectorKit.word("Roll"))
row.add_child(dice)
v.add_child(row)
v.add_child(InspectorKit.note(Describe.dice(t.dice, insp.main.data), Style.MUTED, 13))
dice.text_changed.connect(func(s: String) -> void:
if not TableSettingsDialog.dice_ok_text(s):
InspectorKit.show_error(err, "“%s” isn't dice such as 2d6 or 1d100." % s.strip_edges())
InspectorKit.mark(dice, false)
return
InspectorKit.mark(dice, true)
InspectorKit.show_error(err, insp.apply_settings({"ranged": true, "dice": s.strip_edges()}))
)
var probs := t.range_problems()
if probs != "":
v.add_child(InspectorKit.note(probs, Style.WARN_INK, 13))
else:
v.add_child(InspectorKit.note("Each result is equally likely, unless you give it a weight on the card.", Style.MUTED, 13))
v.add_child(err)
box.add_child(InspectorKit.field("Rolls", v))
# ---------- Check ----------
## The modifier picker's value for check_mod text: "" -> none, "dm(@str)" ->
## "@str", anything else -> AS_TEXT.
static func modifier_value(mod: String) -> String:
var s := mod.strip_edges()
if s == "":
return NONE
var m := RegEx.create_from_string(DM_PATTERN).search(s)
return m.get_string(1) if m else AS_TEXT
static func _check(insp: Inspector, box: VBoxContainer, t: RollTable, plain: bool) -> void:
var main := insp.main
var sentence := InspectorKit.note("", Style.INK, 15)
sentence.add_theme_font_override("font", Style.body_bold())
var sp := PanelContainer.new()
sp.add_theme_stylebox_override("panel", Style.bordered(Style.box(InspectorKit.TAKEN_BG, 8, [10, 7, 10, 8]), 1, Style.BRASS))
sp.add_child(sentence)
box.add_child(sp)
insp.fields["sentence"] = sentence
var errs := InspectorKit.error_label()
var refresh := func() -> void:
sentence.text = Describe.check(t, main.data) if plain else "Roll %s%s, need %s %s" % [t.check_dice, (" + " + t.check_mod) if t.check_mod != "" else "", t.check_target, "or more" if t.check_cmp == "ge" else "or less"]
var msgs := PackedStringArray()
for it: Dictionary in Roller.lint_check(t):
msgs.append(str(it["message"]) + ".")
InspectorKit.show_error(errs, "\n".join(msgs))
insp._live.append(refresh)
var dice := InspectorKit.line(t.check_dice, "2d6", 80.0)
InspectorKit.tag(dice, "card.check_dice")
insp.fields["check_dice"] = dice
dice.text_changed.connect(func(s: String) -> void: set_check(insp, "check_dice", s))
var r1 := InspectorKit.flow()
r1.add_child(InspectorKit.word("Roll"))
r1.add_child(dice)
box.add_child(InspectorKit.field("Dice", r1))
# Modifier: [Strength ▾] modifier, none, or text.
var mv := modifier_value(t.check_mod)
var mod_box := InspectorKit.vbox(5)
var once := insp.has_meta("mod_text_once")
if once:
insp.remove_meta("mod_text_once")
if mv == AS_TEXT or not plain or once:
var le := InspectorKit.line(t.check_mod, "e.g. dm(@str) or @skill_melee")
InspectorKit.code(le)
InspectorKit.tag(le, "card.check_mod")
insp.fields["check_mod"] = le
var merr := InspectorKit.error_label()
le.text_changed.connect(func(s: String) -> void:
var msg := InspectorKit.expr_error(s, "The modifier")
InspectorKit.show_error(merr, msg)
InspectorKit.mark(le, msg == "")
if msg == "":
set_check(insp, "check_mod", s)
)
mod_box.add_child(le)
mod_box.add_child(merr)
var back := InspectorKit.link("Use the picker", "Pick a value's modifier instead")
back.disabled = modifier_value(t.check_mod) == AS_TEXT
back.tooltip_text = "Pick a value's modifier instead" if not back.disabled else "The picker shows \"none\" or one value's modifier, dm(@value)"
back.pressed.connect(func() -> void: insp.rebuild())
if plain:
mod_box.add_child(back)
else:
var row := InspectorKit.flow()
var picker := ValuePicker.new(main, mv if mv != NONE else NONE)
picker.kinds = ["number"]
picker.extras = [{"name": NONE, "label": "none", "kind": ""}, {"name": AS_TEXT, "label": "Edit as text…", "kind": ""}]
picker.set_value(mv)
insp.fields["check_mod_picker"] = picker
picker.value_chosen.connect(func(n: String) -> void: choose_modifier(insp, n))
row.add_child(picker)
row.add_child(InspectorKit.word("modifier" if mv != NONE else "", Style.INK))
mod_box.add_child(row)
mod_box.add_child(InspectorKit.note("A value's modifier is dm(value): −1 at 3–5, 0 at 6–8, +1 at 9–11 and so on.", Style.MUTED, 12))
box.add_child(InspectorKit.field("Modifier", mod_box))
var r3 := InspectorKit.flow()
r3.add_child(InspectorKit.word("Need"))
var target := InspectorKit.amount(t.check_target, "8")
InspectorKit.tag(target, "card.check_target")
insp.fields["check_target"] = target
target.text_changed.connect(func(s: String) -> void: set_check(insp, "check_target", s))
r3.add_child(target)
var cmp := InspectorKit.dropdown(["or more", "or less"], 0 if t.check_cmp == "ge" else 1)
cmp.item_selected.connect(func(k: int) -> void: set_check(insp, "check_cmp", "ge" if k == 0 else "le"))
insp.fields["check_cmp"] = cmp
r3.add_child(cmp)
box.add_child(InspectorKit.field("Target", r3))
box.add_child(errs)
box.add_child(InspectorKit.note("Success and Failure are the card's two results; select one to give it changes and pipes.", Style.MUTED, 13))
refresh.call()
## Sets a check field (check_dice, check_mod, check_target, check_cmp).
static func set_check(insp: Inspector, key: String, value: String) -> void:
var t := insp.selected_table()
if t == null or t.kind != RollTable.KIND_CHECK:
return
var s := value.strip_edges()
if key == "check_cmp":
if not RollTable.CHECK_CMPS.has(s):
return
elif key != "check_mod" and s == "":
return
if str(t.get(key)) == s:
return
t.set(key, s)
insp.wrote(t)
## The modifier picker: none, a value (dm(@value)) or Edit as text.
static func choose_modifier(insp: Inspector, n: String) -> void:
match n:
NONE:
set_check(insp, "check_mod", "")
insp.rebuild()
AS_TEXT:
_rebuild_as_text(insp)
_:
set_check(insp, "check_mod", "dm(%s)" % n)
insp.rebuild()
static func _rebuild_as_text(insp: Inspector) -> void:
# A one-shot flag: the next build shows the modifier as text.
insp.set_meta("mod_text_once", true)
insp.rebuild()
# ---------- Choice ----------
static func _choice(insp: Inspector, box: VBoxContainer, t: RollTable, plain: bool) -> void:
var main := insp.main
var err := InspectorKit.error_label()
var seg := ModalCard.segmented(TableSettingsDialog.CHOICE_LABELS, maxi(0, RollTable.CHOICES.find(t.choice)), func(i: int) -> void:
InspectorKit.show_error(err, insp.apply_settings({"choice": RollTable.CHOICES[i]}, true))
)
box.add_child(InspectorKit.field("Type", seg))
var q := InspectorKit.line(t.prompt, "Which one?")
InspectorKit.tag(q, "card.prompt")
q.text_changed.connect(func(s: String) -> void: insp.apply_settings({"prompt": s}))
insp.fields["prompt"] = q
box.add_child(InspectorKit.field("Question", q))
var save := InspectorKit.line(t.save_as, "nothing (e.g. career, or @career to keep)")
InspectorKit.tag(save, "card.save_as")
insp.fields["save_as"] = save
save.text_changed.connect(func(s: String) -> void:
var msg := Inspector._save_error(s)
InspectorKit.mark(save, msg == "")
InspectorKit.show_error(err, msg if msg != "" else insp.apply_settings({"save_as": s}))
)
box.add_child(InspectorKit.field("Save the answer as", save))
if t.choice == "number":
var r := InspectorKit.flow()
r.add_child(InspectorKit.word("From"))
var lo := InspectorKit.amount(t.min_expr, "0")
var hi := InspectorKit.amount(t.max_expr, "99")
InspectorKit.tag(lo, "card.min")
InspectorKit.tag(hi, "card.max")
lo.text_changed.connect(func(s: String) -> void: InspectorKit.show_error(err, insp.apply_settings({"min": s, "max": hi.text})))
hi.text_changed.connect(func(s: String) -> void: InspectorKit.show_error(err, insp.apply_settings({"min": lo.text, "max": s})))
r.add_child(lo)
r.add_child(InspectorKit.word("to"))
r.add_child(hi)
box.add_child(InspectorKit.field("Allowed answers", r))
if t.choice == "pick":
box.add_child(_options(insp, t, plain, err))
box.add_child(err)
## Pick cards: Fixed list, or From [collection or list ▾] where [condition].
static func _options(insp: Inspector, t: RollTable, plain: bool, err: Label) -> Control:
var main := insp.main
var v := InspectorKit.vbox(6)
var dynamic := t.is_dynamic()
var from_picker := ValuePicker.new(main, t.options_from)
from_picker.kinds = ["collection", "list"]
from_picker.allow_patterns = true
from_picker.placeholder = "a collection or list"
insp.fields["options_from"] = from_picker
var seg := ModalCard.segmented(["Fixed list", "From a value"], 1 if dynamic else 0, func(i: int) -> void:
if i == 0:
InspectorKit.show_error(err, insp.apply_settings({"options_mode": "fixed"}, true))
else:
var first := _first_source(main.data)
if first == "":
InspectorKit.show_error(err, "Add a collection (+ Card ▾ → Collection) or a list value first, then pick it here.")
return
InspectorKit.show_error(err, set_options(insp, first, ""))
)
v.add_child(seg)
if dynamic:
var row := InspectorKit.flow()
row.add_child(InspectorKit.word("From"))
from_picker.value_chosen.connect(func(n: String) -> void:
InspectorKit.show_error(err, set_options(insp, n, t.options_where)))
row.add_child(from_picker)
v.add_child(row)
var where := ConditionBuilder.new()
where.setup(main, t.options_where, not plain, "card.where", {"empty_note": "Every one is offered.",
"extras": [{"name": "option_value", "label": "Its value", "kind": "number"}, {"name": "option_label", "label": "Its name", "kind": "text"}],
"add_label": "+ Only where…"})
where.changed.connect(func(s: String) -> void:
if TableSettingsDialog.when_error(s) == "":
InspectorKit.show_error(err, set_options(insp, t.options_from, s)))
insp.fields["options_where"] = where
v.add_child(InspectorKit.word("where", Style.MUTED))
v.add_child(where)
var desc := Describe.options(t, main.data)
if desc != "" and plain:
v.add_child(InspectorKit.note("Offers %s, plus the fixed options. The Chosen result runs for the one picked." % desc, Style.MUTED, 13))
else:
v.add_child(InspectorKit.note("The player picks one of the card's results, or Random.", Style.MUTED, 13))
return InspectorKit.field("Options", v)
## The first collection (@stem_*) or list value on the board, or "".
static func _first_source(board: TowerBoard) -> String:
for k: Dictionary in Builder.known_values(board):
if str(k["kind"]) == "collection" or str(k["kind"]) == "list":
return str(k["name"])
return ""
## Options from `from` where `where` (a pick card). Returns "" or the problem.
static func set_options(insp: Inspector, from: String, where: String) -> String:
var t := insp.selected_table()
var was := t.is_dynamic()
return insp.apply_settings({"options_mode": "vars", "options_from": from, "options_where": where}, not was or from != t.options_from)
# ---------- Loop ----------
static func _loop(insp: Inspector, box: VBoxContainer, t: RollTable, plain: bool) -> void:
var labels := ["Times", "While", "Until"]
var err := InspectorKit.error_label()
var seg := ModalCard.segmented(labels, maxi(0, RollTable.LOOPS.find(t.loop_mode)), func(i: int) -> void:
set_loop_mode(insp, RollTable.LOOPS[i])
)
box.add_child(InspectorKit.field("Repeat", seg))
if t.loop_mode == "times":
var r := InspectorKit.flow()
r.add_child(InspectorKit.word("Run Each time"))
var n := InspectorKit.amount(t.loop_expr, "3")
InspectorKit.tag(n, "card.loop_expr")
insp.fields["loop_expr"] = n
n.text_changed.connect(func(s: String) -> void:
var msg := "Fill in how many times." if s.strip_edges() == "" else InspectorKit.expr_error(s, "The count")
InspectorKit.show_error(err, msg)
InspectorKit.mark(n, msg == "")
if msg == "" and s.strip_edges() != t.loop_expr:
t.loop_expr = s.strip_edges()
insp.wrote(t)
)
r.add_child(n)
r.add_child(InspectorKit.word("times, then Afterwards."))
box.add_child(r)
else:
var cond := ConditionBuilder.new()
cond.setup(insp.main, t.loop_expr, not plain, "card.loop_cond", {})
cond.changed.connect(func(s: String) -> void:
if s.strip_edges() != "" and TableSettingsDialog.when_error(s) == "" and s.strip_edges() != t.loop_expr:
t.loop_expr = s.strip_edges()
insp.wrote(t)
)
insp.fields["loop_cond"] = cond
var cap := "Keep going while" if t.loop_mode == "while" else "Stop once"
box.add_child(InspectorKit.field(cap, cond))
box.add_child(InspectorKit.note(TableSettingsDialog.LOOP_NOTES.get(t.loop_mode, ""), Style.MUTED, 13))
box.add_child(err)
static func set_loop_mode(insp: Inspector, m: String) -> void:
var t := insp.selected_table()
if t == null or m == t.loop_mode or not RollTable.LOOPS.has(m):
return
var cond_like := Builder.parse_condition(t.loop_expr)
var is_cond: bool = cond_like["ok"] and not (cond_like["clauses"] as Array).is_empty() \
and str((cond_like["clauses"] as Array)[0]["cmp"]) != "set"
if m == "times" and is_cond:
t.loop_expr = "3"
elif m != "times" and not is_cond:
t.loop_expr = "i < 3"
t.loop_mode = m
insp.wrote(t, false, true)
# ---------- Router ----------
static func _router(insp: Inspector, box: VBoxContainer, t: RollTable, plain: bool) -> void:
var v := InspectorKit.vbox(8)
for e in t.entries:
v.add_child(case_block(insp, t, e, true))
var add := InspectorKit.link("+ Add case", "Add a case before the Otherwise case")
add.pressed.connect(func() -> void: add_case(insp))
v.add_child(add)
var lint := InspectorKit.error_label()
var fill := func() -> void:
var msgs := PackedStringArray()
for it: Dictionary in Roller.lint_router(t):
msgs.append(str(it["message"]) + ".")
InspectorKit.show_error(lint, "\n".join(msgs))
fill.call()
insp._live.append(fill)
v.add_child(lint)
box.add_child(InspectorKit.field("Cases (the first that holds is taken)", v))
## One router case: its condition, or Otherwise for the last case.
static func case_block(insp: Inspector, t: RollTable, e: TableEntry, framed: bool = false) -> Control:
var i := t.entries.find(e)
var last := i == t.entries.size() - 1
var v := InspectorKit.vbox(6)
if framed:
var head := InspectorKit.hbox(6)
var cap := InspectorKit.word("%d. %s" % [i + 1, Inspector._title_of(e.text, "(no text)")], Style.INK, true)
cap.size_flags_horizontal = Control.SIZE_EXPAND_FILL
cap.clip_text = true
head.add_child(cap)
var open := InspectorKit.link("Edit", "Edit this case's result")
open.pressed.connect(func() -> void: insp.select({"kind": "result", "tid": t.id, "eid": e.id}))
head.add_child(open)
if t.entries.size() > 1:
var x := InspectorKit.xbutton("Delete this case")
x.pressed.connect(func() -> void: insp.main.delete_entry(t.id, e.id))
head.add_child(x)
v.add_child(head)
var other := e.when.strip_edges() == ""
if last:
var cb := InspectorKit.check_box("Otherwise (when no case above holds)", other)
cb.toggled.connect(func(on: bool) -> void:
if on:
insp.set_case_when(e.id, "")
insp.rebuild()
else:
insp.set_meta("open_case", e.id)
insp.rebuild()
)
v.add_child(cb)
var opening := insp.has_meta("open_case") and str(insp.get_meta("open_case")) == e.id
if not (last and other) or opening:
var cond := ConditionBuilder.new()
cond.setup(insp.main, e.when, not insp.main.rules_plain(), "case.%s" % e.id, {})
if other and cond.clauses.is_empty() and not cond.text_mode:
cond.add_clause()
cond.changed.connect(func(s: String) -> void:
if s.strip_edges() != "":
insp.set_case_when(e.id, s))
if not framed:
insp.case_builder = cond
var cap := "Taken when" if framed else "This case is taken when"
var fv := InspectorKit.vbox(4)
fv.add_child(InspectorKit.flabel(cap))
fv.add_child(cond)
if other and not last:
fv.add_child(InspectorKit.note("Empty, so this case is an Otherwise and the cases after it never run.", Style.WARN_INK, 13))
v.add_child(fv)
if opening:
insp.remove_meta("open_case")
if framed:
var p := PanelContainer.new()
p.add_theme_stylebox_override("panel", Style.bordered(Style.box(InspectorKit.BOX_BG, 8, [10, 8, 10, 9]), 1, Style.RULE))
p.add_child(v)
return p
return v
## Adds a case before a final Otherwise case (or at the end).
static func add_case(insp: Inspector) -> void:
var t := insp.selected_table()
if t == null:
return
var e := TableEntry.new(TowerBoard.new_id("e"), "Case %d" % (t.entries.size() + 1))
var at := t.entries.size()
if not t.entries.is_empty() and t.entries.back().when.strip_edges() == "":
at -= 1
t.entries.insert(at, e)
insp.set_meta("open_case", e.id)
insp.wrote(t, false, true)
# ---------- Variable ----------
static func _variable(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var err := InspectorKit.error_label()
var vn := InspectorKit.line(t.var_name, "luck")
InspectorKit.code(vn)
InspectorKit.tag(vn, "card.var_name")
insp.fields["var_name"] = vn
vn.text_changed.connect(func(s: String) -> void:
var msg := insp.apply_settings({"var_name": s})
InspectorKit.mark(vn, msg == "")
InspectorKit.show_error(err, msg)
)
box.add_child(InspectorKit.field("Name in rules (@name)", vn))
var types := ["number", "text", "list"]
var seg := ModalCard.segmented(["Number", "Text", "List"], maxi(0, types.find(t.var_type)), func(i: int) -> void:
InspectorKit.show_error(err, insp.apply_settings({"var_type": types[i]}, true))
)
box.add_child(InspectorKit.field("Type", seg))
var init := InspectorKit.line(t.initial, "0" if t.var_type == "number" else "nothing")
InspectorKit.tag(init, "card.initial")
insp.fields["initial"] = init
init.text_changed.connect(func(s: String) -> void:
var msg := insp.apply_settings({"initial": s})
InspectorKit.mark(init, msg == "")
InspectorKit.show_error(err, msg)
)
box.add_child(InspectorKit.field("Starting value", init))
box.add_child(err)
# ---------- Collection ----------
static func _collection(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var err := InspectorKit.error_label()
var vn := InspectorKit.line(t.var_name, "skill")
InspectorKit.code(vn)
InspectorKit.tag(vn, "card.var_name")
insp.fields["var_name"] = vn
vn.text_changed.connect(func(s: String) -> void:
var msg := insp.apply_settings({"var_name": s})
InspectorKit.mark(vn, msg == "")
InspectorKit.show_error(err, msg)
)
box.add_child(InspectorKit.field("Members are named", vn))
box.add_child(InspectorKit.note("Each member is the value @%s_<name>, e.g. @%s_pilot. Choices can offer “one of your %s”." % [t.var_name, t.var_name, Inspector._title_of(t.name, "members")], Style.MUTED, 13))
var v := InspectorKit.vbox(5)
var list := insp.members(t)
insp.fields["members"] = list
if list.is_empty():
v.add_child(InspectorKit.note("No members yet.", Style.MUTED, 14))
var grid := GridContainer.new()
grid.columns = 3
grid.add_theme_constant_override("h_separation", 6)
grid.add_theme_constant_override("v_separation", 5)
for pair: Array in list:
var item := str(pair[0])
var nm := InspectorKit.line(RollContext.pretty_name(item), item, 0.0)
nm.size_flags_horizontal = Control.SIZE_EXPAND_FILL
nm.tooltip_text = "@%s_%s" % [t.var_name, item]
InspectorKit.tag(nm, "member.%s.name" % item)
var commit_name := func() -> void:
var slug := JsonIO.slug(nm.text, "")
if slug == "" or slug == item:
return
rename_member(insp, t, item, slug)
nm.text_submitted.connect(func(_s: String) -> void: commit_name.call())
nm.focus_exited.connect(commit_name)
grid.add_child(nm)
var val := InspectorKit.amount(str(pair[1]), "0")
InspectorKit.tag(val, "member.%s.value" % item)
var commit_val := func() -> void:
if val.text.strip_edges() != str(pair[1]):
set_member(insp, t, item, val.text.strip_edges())
val.text_submitted.connect(func(_s: String) -> void: commit_val.call())
val.focus_exited.connect(commit_val)
grid.add_child(val)
var x := InspectorKit.xbutton("Remove this member")
x.pressed.connect(func() -> void: remove_member(insp, t, item))
grid.add_child(x)
v.add_child(grid)
var add := InspectorKit.link("+ Add member")
add.pressed.connect(func() -> void: add_member(insp, t))
v.add_child(add)
v.add_child(InspectorKit.note("Members are saved values of this board, like the Variables panel shows; they aren't part of undo.", Style.MUTED, 12))
box.add_child(InspectorKit.field("Members", v))
box.add_child(err)
static func set_member(insp: Inspector, t: RollTable, item: String, value: String) -> void:
insp.main.set_collection_member(t, item, value)
insp.rebuild()
static func rename_member(insp: Inspector, t: RollTable, old_item: String, new_item: String) -> void:
var cur: Variant = insp.main.persistent_vars.get("%s_%s" % [t.var_name, old_item])
var value := Expr.format_value(cur.get("value") if cur is Dictionary else cur)
insp.main.remove_collection_member(t, old_item)
insp.main.set_collection_member(t, new_item, value)
insp.rebuild()
static func remove_member(insp: Inspector, t: RollTable, item: String) -> void:
insp.main.remove_collection_member(t, item)
insp.rebuild()
static func add_member(insp: Inspector, t: RollTable) -> String:
var used := {}
for pair: Array in insp.members(t):
used[str(pair[0])] = true
var item := "new"
var k := 2
while used.has(item):
item = "new_%d" % k
k += 1
insp.main.set_collection_member(t, item, "0")
insp.rebuild()
var nm := InspectorKit.find_tagged(insp, "member.%s.name" % item) as LineEdit
if nm and nm.is_inside_tree():
nm.grab_focus()
nm.select_all()
return item
# ---------- Sheet ----------
static func _sheet(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var tpl := InspectorKit.text_box(t.entries[0].text if not t.entries.is_empty() else "", "[b]{@name}[/b]\nStrength {@str}", 120.0)
InspectorKit.code(tpl)
InspectorKit.tag(tpl, "card.template")
insp.fields["template"] = tpl
tpl.text_changed.connect(func() -> void: insp.apply_settings({"template": tpl.text}))
box.add_child(InspectorKit.field("Template", tpl))
box.add_child(InspectorKit.note("Write {@value} where a value goes. The sheet shows the values as they are now.", Style.MUTED, 13))

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

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

247
ui/inspector_condition.gd Normal file
View file

@ -0,0 +1,247 @@
class_name ConditionBuilder
extends VBoxContainer
## A condition editor: clauses `[value ▾] [comparison ▾] [amount] ×`, an
## and/or switch once there are two, and "+ Add condition"
## (Builder.parse_condition / condition_text). A condition the builder can't
## show (mixed and/or, dice, functions…) is a text field with its problem;
## "Edit as text" and "Use the builder" switch between the two.
## Emits `changed(text)`; clauses not filled in yet are left out.
signal changed(text: String)
const CMPS := ["eq", "ne", "ge", "le", "gt", "lt", "has", "set", "unset"]
const CMP_LABELS := ["is", "is not", "is at least", "is at most", "is more than", "is less than", "includes", "is set", "is not set"]
var main: Main
var join := "and"
var clauses: Array[Dictionary] = []
var text_mode := false
## What an empty condition means, shown when there are no clauses ("Always").
var empty_note := ""
## Extra values for the pickers ([{name, label, kind}]), e.g. option_value.
var extras: Array = []
## Names that stay unquoted in amounts (chain names, inputs).
var known: Array = []
var add_label := "+ Add condition"
var _raw := ""
var _key := "cond"
func setup(p_main: Main, expr: String, as_text: bool, key: String = "cond", opts: Dictionary = {}) -> void:
main = p_main
_key = key
empty_note = str(opts.get("empty_note", ""))
extras = opts.get("extras", [])
add_label = str(opts.get("add_label", add_label))
known = []
for x: Dictionary in extras:
known.append(str(x["name"]))
if main:
for k: Dictionary in Builder.known_values(main.data):
if not str(k["name"]).begins_with("@"):
known.append(str(k["name"]))
add_theme_constant_override("separation", 6)
size_flags_horizontal = Control.SIZE_EXPAND_FILL
_raw = expr.strip_edges()
var m := Builder.parse_condition(_raw)
text_mode = as_text or not m["ok"]
if m["ok"]:
join = str(m["join"])
clauses.clear()
for c: Dictionary in m["clauses"]:
clauses.append(c.duplicate())
_render()
func text() -> String:
if text_mode:
return _raw.strip_edges()
var parts := PackedStringArray()
for c in clauses:
var t := Builder.clause_text(c)
if t != "":
parts.append(t)
return (" %s " % join).join(parts)
func _emit() -> void:
changed.emit(text())
# ---------- Editing (also used by tests) ----------
func add_clause(v: String = "", cmp: String = "ge", value: String = "") -> void:
clauses.append({"var": v, "cmp": cmp, "value": value})
_render()
_emit()
func remove_clause(i: int) -> void:
if i < 0 or i >= clauses.size():
return
clauses.remove_at(i)
_render()
_emit()
func set_join(j: String) -> void:
if j != "and" and j != "or":
return
join = j
_render()
_emit()
func set_clause_var(i: int, n: String) -> void:
clauses[i]["var"] = n
_render()
_emit()
func set_clause_cmp(i: int, cmp: String) -> void:
clauses[i]["cmp"] = cmp
if cmp == "set" or cmp == "unset":
clauses[i]["value"] = ""
_render()
_emit()
## Sets a clause's amount from what a person typed (text gets quoted).
func set_clause_value(i: int, typed: String) -> void:
clauses[i]["value"] = InspectorKit.value_token(typed, known)
_emit()
func set_text_mode(on: bool) -> void:
if on == text_mode:
return
if on:
_raw = text()
text_mode = true
else:
var m := Builder.parse_condition(_raw)
if not m["ok"]:
return
join = str(m["join"])
clauses.clear()
for c: Dictionary in m["clauses"]:
clauses.append(c.duplicate())
text_mode = false
_render()
func set_raw(t: String) -> void:
_raw = t
if TableSettingsDialog.when_error(t) == "":
_emit()
# ---------- UI ----------
func _render() -> void:
var focus_key := ""
var f := get_viewport().gui_get_focus_owner() if is_inside_tree() else null
if f and is_ancestor_of(f) and f.has_meta(InspectorKit.KEY):
focus_key = str(f.get_meta(InspectorKit.KEY))
for c in get_children():
remove_child(c)
c.queue_free()
if text_mode:
_render_text()
else:
if clauses.is_empty() and empty_note != "":
add_child(InspectorKit.note(empty_note, Style.MUTED, 14))
if clauses.size() > 1:
var jr := InspectorKit.hbox(6)
jr.add_child(InspectorKit.word("Needs", Style.MUTED))
var jd := InspectorKit.dropdown(["all of these (and)", "any of these (or)"], 0 if join == "and" else 1)
jd.tooltip_text = "And: every condition must hold. Or: one is enough."
jd.item_selected.connect(func(k: int) -> void: set_join("and" if k == 0 else "or"))
jr.add_child(jd)
add_child(jr)
for i in clauses.size():
add_child(_clause_row(i))
var foot := InspectorKit.hbox(12)
var add := InspectorKit.link(add_label, "Add a comparison")
add.pressed.connect(func() -> void: add_clause())
foot.add_child(add)
var as_text := InspectorKit.link("Edit as text", "Edit this condition as rule text")
as_text.add_theme_color_override("font_color", Style.MUTED)
as_text.pressed.connect(func() -> void: set_text_mode(true))
foot.add_child(as_text)
add_child(foot)
if focus_key != "":
var c := InspectorKit.find_tagged(self, focus_key)
if c:
c.grab_focus.call_deferred()
func _render_text() -> void:
var le := InspectorKit.line(_raw, "e.g. @str >= 8 (empty: always)")
InspectorKit.code(le)
InspectorKit.tag(le, _key + ".raw")
var err := InspectorKit.error_label()
var back := InspectorKit.link("Use the builder", "Show this condition as rows")
var check := func() -> void:
var e := TableSettingsDialog.when_error(_raw)
InspectorKit.show_error(err, "" if e == "" else "This condition can't be worked out: " + e)
InspectorKit.mark(le, e == "")
var m := Builder.parse_condition(_raw)
back.disabled = not m["ok"]
back.tooltip_text = "Show this condition as rows" if m["ok"] else "The builder can't show this (%s), so it stays as text" % str(m.get("error", "")).to_lower()
le.text_changed.connect(func(s: String) -> void:
set_raw(s)
check.call()
)
add_child(le)
add_child(err)
back.pressed.connect(func() -> void: set_text_mode(false))
add_child(back)
check.call()
func _clause_row(i: int) -> Control:
var c := clauses[i]
var v := InspectorKit.vbox(3)
var f := InspectorKit.flow()
v.add_child(f)
var picker := ValuePicker.new(main, str(c["var"]))
picker.extras = extras
picker.value_chosen.connect(func(n: String) -> void: set_clause_var(i, n))
f.add_child(picker)
var cmp := str(c["cmp"])
var dd := InspectorKit.dropdown(CMP_LABELS, maxi(0, CMPS.find(cmp)))
dd.item_selected.connect(func(k: int) -> void: set_clause_cmp(i, CMPS[k]))
f.add_child(dd)
var err := InspectorKit.error_label()
var le: LineEdit = null
if cmp != "set" and cmp != "unset":
le = InspectorKit.amount(InspectorKit.shown_token(str(c["value"])), "8")
le.tooltip_text = "A number, a word, or a value such as @soc"
InspectorKit.tag(le, "%s.%d.value" % [_key, i])
var lref := le
le.text_changed.connect(func(s: String) -> void:
set_clause_value(i, s)
_check_clause(i, lref, err)
)
f.add_child(le)
var x := InspectorKit.xbutton("Remove this condition")
x.pressed.connect(remove_clause.bind(i))
f.add_child(x)
v.add_child(err)
_check_clause(i, le, err)
return v
func _check_clause(i: int, le: LineEdit, err: Label) -> void:
var c := clauses[i]
var msg := ""
if str(c["var"]) == "":
msg = "Pick a value to compare."
elif str(c["cmp"]) != "set" and str(c["cmp"]) != "unset" and str(c["value"]) == "":
msg = "Fill in what to compare with."
elif Builder.clause_text(c) != "" and TableSettingsDialog.when_error(Builder.clause_text(c)) != "":
msg = "This can't be worked out: " + TableSettingsDialog.when_error(Builder.clause_text(c))
InspectorKit.show_error(err, msg)
if le:
InspectorKit.mark(le, msg == "" or str(c["var"]) == "")

View file

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

319
ui/inspector_effects.gd Normal file
View file

@ -0,0 +1,319 @@
class_name EffectsBuilder
extends VBoxContainer
## The inspector's "When this comes up" editor: one row per effect statement
## (Builder.parse_effects), each `[op ▾] [amount] to/from [value ▾] ×`, plus
## "+ Add a change". A statement the builder can't show stays a text field
## with its problem. "Edit as text" switches to the whole effects text, and
## "Use the builder" switches back when every statement parses.
## Emits `changed(text)` with the statements (Builder.effect_text) joined by
## newlines; rows not filled in yet are left out.
signal changed(text: String)
const OPS := ["set", "add", "subtract", "multiply", "divide", "reset", "append", "remove"]
const OP_LABELS := ["Set", "Add", "Subtract", "Multiply", "Divide", "Clear", "Add to list", "Remove from list"]
var main: Main
var table: RollTable
## Each row: a Builder model ({ok, op, var, amount}) or {ok: false, src, error}.
var rows: Array[Dictionary] = []
var text_mode := false
var _raw := ""
var _key := "fx"
func setup(p_main: Main, text: String, p_table: RollTable, as_text: bool, key: String = "fx") -> void:
main = p_main
table = p_table
_key = key
_raw = text
add_theme_constant_override("separation", 6)
size_flags_horizontal = Control.SIZE_EXPAND_FILL
rows.clear()
for m in Builder.parse_effects(text):
rows.append(m)
# One unreadable statement doesn't turn the whole field into text: it
# shows as a text row among the others. Text mode starts as text.
text_mode = as_text
_render()
static func _all_ok(text: String) -> bool:
for m in Builder.parse_effects(text):
if not m["ok"]:
return false
return true
## The effects text the rows stand for.
func text() -> String:
if text_mode:
return _raw.strip_edges()
var parts := PackedStringArray()
for m in rows:
var t := ""
if m["ok"]:
t = Builder.effect_text(m)
else:
t = str(m.get("src", "")).strip_edges()
if t != "":
parts.append(t)
return "\n".join(parts)
func _emit() -> void:
changed.emit(text())
func _known_names() -> Array:
var out: Array = []
if main:
for k: Dictionary in Builder.known_values(main.data):
if not str(k["name"]).begins_with("@"):
out.append(str(k["name"]))
if table:
out.append_array(table.input_names())
return out
# ---------- Editing (also used by tests) ----------
func add_row() -> void:
rows.append({"ok": true, "op": "add", "var": "", "amount": "1"})
_render()
_emit()
func remove_row(i: int) -> void:
if i < 0 or i >= rows.size():
return
rows.remove_at(i)
_render()
_emit()
func set_row_op(i: int, op: String) -> void:
var m := rows[i]
if not m["ok"] or not OPS.has(op):
return
var was := str(m["op"])
m["op"] = op
var amt := str(m.get("amount", ""))
var listy := op == "append" or op == "remove"
var was_listy := was == "append" or was == "remove"
if op == "reset":
m["amount"] = ""
elif listy and not was_listy:
m["amount"] = Builder.unquote(amt)
elif not listy and was_listy:
m["amount"] = InspectorKit.amount_expr(amt, _known_names()) if amt != "" else ""
elif amt == "" and was == "reset":
m["amount"] = "1"
_render()
_emit()
## Sets a row's amount from what a person typed (quoted when it's text).
func set_row_amount(i: int, typed: String, render: bool = false) -> void:
var m := rows[i]
if not m["ok"]:
return
var listy := str(m["op"]) == "append" or str(m["op"]) == "remove"
m["amount"] = typed.strip_edges() if listy else InspectorKit.amount_expr(typed, _known_names())
if render:
_render()
_emit()
func set_row_var(i: int, n: String) -> void:
var m := rows[i]
if not m["ok"]:
return
m["var"] = n
_render()
_emit()
## A text row's statement.
func set_row_src(i: int, src: String) -> void:
var m := rows[i]
m["src"] = src
var p := Builder.parse_effect(src)
m["error"] = str(p.get("error", ""))
_emit()
func set_text_mode(on: bool) -> void:
if on == text_mode:
return
if on:
_raw = text()
text_mode = true
else:
if not _all_ok(_raw):
return
rows.clear()
for m in Builder.parse_effects(_raw):
rows.append(m)
text_mode = false
_render()
func set_raw(t: String) -> void:
_raw = t
_emit()
# ---------- UI ----------
func _render() -> void:
var focus_key := ""
var f := get_viewport().gui_get_focus_owner() if is_inside_tree() else null
if f and is_ancestor_of(f) and f.has_meta(InspectorKit.KEY):
focus_key = str(f.get_meta(InspectorKit.KEY))
for c in get_children():
remove_child(c)
c.queue_free()
if text_mode:
_render_text()
else:
for i in rows.size():
add_child(_row(i))
var foot := InspectorKit.hbox(12)
var add := InspectorKit.link("+ Add a change", "Add a statement that changes a value")
add.pressed.connect(add_row)
InspectorKit.tag(add, _key + ".add")
foot.add_child(add)
var as_text := InspectorKit.link("Edit as text", "Edit these changes as rule text")
as_text.add_theme_color_override("font_color", Style.MUTED)
as_text.pressed.connect(func() -> void: set_text_mode(true))
foot.add_child(as_text)
add_child(foot)
if focus_key != "":
var c := InspectorKit.find_tagged(self, focus_key)
if c:
c.grab_focus.call_deferred()
func _render_text() -> void:
var te := InspectorKit.text_box(_raw, "@luck -= 1", 60.0)
InspectorKit.code(te)
InspectorKit.tag(te, _key + ".raw")
var err := InspectorKit.error_label()
var back := InspectorKit.link("Use the builder", "Show these changes as rows again")
var check := func() -> void:
var problems := Effects.validate(_raw)
var lines := PackedStringArray()
for p: Dictionary in problems:
lines.append("Line %d (%s) can't be used: %s" % [int(p["index"]) + 1, p["src"], p["error"]])
InspectorKit.show_error(err, "\n".join(lines))
InspectorKit.mark(te, problems.is_empty())
back.disabled = not _all_ok(_raw)
back.tooltip_text = "Show these changes as rows again" if not back.disabled else "Some of this text doesn't fit the builder, so it stays as text"
te.text_changed.connect(func() -> void:
_raw = te.text
check.call()
if Effects.validate(_raw).is_empty():
_emit()
)
add_child(te)
add_child(err)
back.pressed.connect(func() -> void: set_text_mode(false))
add_child(back)
check.call()
func _row(i: int) -> Control:
var m := rows[i]
var v := InspectorKit.vbox(3)
var f := InspectorKit.flow()
v.add_child(f)
var x := InspectorKit.xbutton("Remove this change")
x.pressed.connect(remove_row.bind(i))
if not m["ok"]:
var le := InspectorKit.line(str(m.get("src", "")), "@luck -= 1")
InspectorKit.code(le)
InspectorKit.tag(le, "%s.%d.src" % [_key, i])
le.custom_minimum_size = Vector2(200, 0)
var err := InspectorKit.error_label()
var check := func() -> void:
var e := Effects.validate(str(m.get("src", "")))
var msg := ""
if not e.is_empty():
msg = "This can't be used: %s" % e[0]["error"]
else:
msg = "The builder can't show this, so it stays as text. It works as written."
InspectorKit.show_error(err, msg)
err.add_theme_color_override("font_color", Style.DANGER_INK if not e.is_empty() else Style.MUTED)
InspectorKit.mark(le, e.is_empty())
le.text_changed.connect(func(s: String) -> void:
set_row_src(i, s)
check.call()
)
f.add_child(le)
f.add_child(x)
v.add_child(err)
check.call()
return v
var op := str(m["op"])
var dd := InspectorKit.dropdown(OP_LABELS, OPS.find(op))
dd.tooltip_text = "What to do"
dd.item_selected.connect(func(k: int) -> void: set_row_op(i, OPS[k]))
f.add_child(dd)
var picker := ValuePicker.new(main, str(m["var"]))
picker.allow_patterns = op == "reset"
if op == "append" or op == "remove":
picker.kinds = ["list", "text"]
picker.value_chosen.connect(func(n: String) -> void: set_row_var(i, n))
var amt_le: LineEdit = null
var err := InspectorKit.error_label()
if op != "reset":
var listy := op == "append" or op == "remove"
var shown := str(m["amount"]) if listy else InspectorKit.shown_token(str(m["amount"]))
amt_le = InspectorKit.amount(shown, "item" if listy else "1")
amt_le.tooltip_text = "A number, dice such as 1d6, or a value" if not listy else "The item's text"
InspectorKit.tag(amt_le, "%s.%d.amount" % [_key, i])
var le := amt_le
le.text_changed.connect(func(s: String) -> void:
set_row_amount(i, s)
_check_row(i, le, err)
)
match op:
"set":
f.add_child(picker)
f.add_child(InspectorKit.word("to"))
f.add_child(amt_le)
"add", "append":
f.add_child(amt_le)
f.add_child(InspectorKit.word("to"))
f.add_child(picker)
"subtract", "remove":
f.add_child(amt_le)
f.add_child(InspectorKit.word("from"))
f.add_child(picker)
"multiply", "divide":
f.add_child(picker)
f.add_child(InspectorKit.word("by"))
f.add_child(amt_le)
"reset":
f.add_child(picker)
f.add_child(x)
v.add_child(err)
_check_row(i, amt_le, err)
return v
func _check_row(i: int, amt_le: LineEdit, err: Label) -> void:
var m := rows[i]
var msg := ""
if str(m["var"]) == "":
msg = "Pick the value to change."
elif str(m["op"]) != "reset":
var a := str(m["amount"]).strip_edges()
if a == "":
msg = "Fill in the amount."
elif str(m["op"]) != "append" and str(m["op"]) != "remove":
msg = InspectorKit.expr_error(a, "The amount")
InspectorKit.show_error(err, msg)
if amt_le:
InspectorKit.mark(amt_le, msg == "" or str(m["var"]) == "")

View file

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

276
ui/inspector_kit.gd Normal file
View file

@ -0,0 +1,276 @@
class_name InspectorKit
extends RefCounted
## Small styled controls and helpers shared by the Build inspector and its
## builders (docs/PLAIN.md §6): fields, dropdowns, link buttons, error lines,
## and the rules for turning what a person types into rule tokens.
const FIELD_BG := Color.WHITE
const VAR_BG := Color("#fdf6dc")
const VAR_BORDER := Color("#e3c97a")
const BOX_BG := Color("#f7f5ee")
const TAKEN_BG := Color("#fbf3d6")
## Meta key naming a control inside the inspector, so focus can come back to
## the same field after a rebuild.
const KEY := "insp_key"
static func _field_box(border: Color) -> StyleBoxFlat:
return Style.bordered(Style.box(FIELD_BG, 6, [8, 4, 8, 4]), 1, border)
## A one-line field. `min_w` 0 lets it fill the row.
static func line(text: String, placeholder: String = "", min_w: float = 0.0) -> LineEdit:
var le := LineEdit.new()
le.text = text
le.placeholder_text = placeholder
le.add_theme_stylebox_override("normal", _field_box(Style.RULE))
le.add_theme_stylebox_override("focus", _field_box(Style.COPPER))
le.add_theme_stylebox_override("read_only", _field_box(Style.RULE))
le.add_theme_color_override("font_color", Style.INK)
le.add_theme_color_override("caret_color", Style.INK)
le.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
le.add_theme_color_override("font_placeholder_color", Style.MUTED)
le.add_theme_font_override("font", Style.body())
le.add_theme_font_size_override("font_size", 15)
le.add_theme_constant_override("minimum_character_width", 0)
if min_w > 0.0:
le.custom_minimum_size = Vector2(min_w, 0)
else:
le.size_flags_horizontal = Control.SIZE_EXPAND_FILL
return le
## A short centred field for an amount ("1", "2d6", "Psionic"). It widens
## with its text up to `max_w`.
static func amount(text: String, placeholder: String = "") -> LineEdit:
var le := line(text, placeholder, 52.0)
le.alignment = HORIZONTAL_ALIGNMENT_CENTER
le.add_theme_font_override("font", Style.body_bold())
le.expand_to_text_length = true
return le
static func text_box(text: String, placeholder: String = "", min_h: float = 70.0) -> TextEdit:
var te := TextEdit.new()
te.text = text
te.placeholder_text = placeholder
te.custom_minimum_size = Vector2(0, min_h)
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
te.scroll_fit_content_height = true
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(FIELD_BG, 6, [8, 6, 8, 6]), 1, Style.RULE))
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(FIELD_BG, 6, [8, 6, 8, 6]), 1, Style.COPPER))
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
te.add_theme_color_override("background_color", Color(0, 0, 0, 0))
te.add_theme_font_override("font", Style.body())
te.add_theme_font_size_override("font_size", 15)
return te
## Monospaced rule text (Text mode fields).
static func code(c: Control) -> Control:
var f := SystemFont.new()
f.font_names = PackedStringArray(["IBM Plex Mono", "DejaVu Sans Mono", "monospace"])
c.add_theme_font_override("font", f)
c.add_theme_font_size_override("font_size", 14)
return c
## Red border (and ink) on a field whose text can't be used.
static func mark(c: Control, ok: bool) -> void:
if c is LineEdit:
c.add_theme_stylebox_override("normal", _field_box(Style.RULE if ok else Style.DANGER))
c.add_theme_stylebox_override("focus", _field_box(Style.COPPER if ok else Style.DANGER))
elif c is TextEdit:
var b := Style.bordered(Style.box(FIELD_BG, 6, [8, 6, 8, 6]), 1, Style.RULE if ok else Style.DANGER)
var f := Style.bordered(Style.box(FIELD_BG, 6, [8, 6, 8, 6]), 1, Style.COPPER if ok else Style.DANGER)
c.add_theme_stylebox_override("normal", b)
c.add_theme_stylebox_override("focus", f)
## A dropdown styled like the mockup's .dd chips.
static func dropdown(items: Array, selected: int) -> OptionButton:
var ob := OptionButton.new()
for i in items.size():
ob.add_item(str(items[i]), i)
ob.select(selected)
ob.fit_to_longest_item = false
var n := Style.bordered(Style.box(FIELD_BG, 6, [8, 3, 6, 3]), 1, Style.RULE)
var h := Style.bordered(Style.box(Style.HOVER_ROW, 6, [8, 3, 6, 3]), 1, Style.DASH)
Style.skin_button(ob, n, h, h, Style.INK)
ob.add_theme_font_override("font", Style.body_bold())
ob.add_theme_font_size_override("font_size", 15)
ob.add_theme_color_override("font_focus_color", Style.INK)
ob.add_theme_constant_override("arrow_margin", 6)
ModalCard.style_popup(ob.get_popup())
return ob
## Small caps heading ("WHEN THIS COMES UP").
static func flabel(text: String) -> Label:
return Style.make_label(text.to_upper(), Style.caps(), 12, Style.MUTED)
## A word inside a builder row ("to", "from", "Only if").
static func word(text: String, color: Color = Style.INK, bold: bool = false) -> Label:
var l := Style.make_label(text, Style.body_bold() if bold else Style.body(), 15, color)
l.size_flags_vertical = Control.SIZE_SHRINK_CENTER
return l
static func note(text: String, color: Color = Style.MUTED, size: int = 13) -> Label:
var l := Style.make_label(text, Style.body(), size, color)
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
l.size_flags_horizontal = Control.SIZE_EXPAND_FILL
l.custom_minimum_size = Vector2(60, 0)
return l
## An error line in plain words (hidden while empty).
static func error_label() -> Label:
var l := note("", Style.DANGER_INK, 13)
l.visible = false
return l
static func show_error(l: Label, msg: String) -> void:
l.text = msg
l.visible = msg != ""
## The × that removes a row.
static func xbutton(tip: String) -> Button:
var b := Button.new()
b.text = "×"
b.tooltip_text = tip
b.custom_minimum_size = Vector2(24, 24)
var n := Style.box(Color(0, 0, 0, 0), 5, [4, 0, 4, 0])
var h := Style.box(Style.WARN_BG, 5, [4, 0, 4, 0])
Style.skin_button(b, n, h, h, Style.MUTED, Style.DANGER_INK)
b.add_theme_font_size_override("font_size", 17)
b.size_flags_vertical = Control.SIZE_SHRINK_CENTER
return b
## A text link ("+ Add a change", "Edit as text").
static func link(text: String, tip: String = "") -> Button:
var b := Button.new()
b.text = text
b.tooltip_text = tip
b.flat = true
var n := Style.box(Color(0, 0, 0, 0), 4, [2, 1, 2, 1])
var h := Style.box(Color(Style.COPPER, 0.12), 4, [2, 1, 2, 1])
Style.skin_button(b, n, h, h, Style.COPPER_DARK)
b.add_theme_font_override("font", Style.body_bold())
b.add_theme_font_size_override("font_size", 14)
b.add_theme_color_override("font_disabled_color", Style.MUTED)
b.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
return b
static func check_box(text: String, on: bool) -> CheckBox:
var cb := CheckBox.new()
cb.text = text
cb.button_pressed = on
cb.add_theme_font_override("font", Style.body_bold())
cb.add_theme_font_size_override("font_size", 15)
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_hover_pressed_color", "font_focus_color"]:
cb.add_theme_color_override(c, Style.INK)
cb.add_theme_color_override("font_disabled_color", Style.MUTED)
return cb
## A wrapping row of builder parts.
static func flow() -> HFlowContainer:
var f := HFlowContainer.new()
f.add_theme_constant_override("h_separation", 6)
f.add_theme_constant_override("v_separation", 6)
f.size_flags_horizontal = Control.SIZE_EXPAND_FILL
return f
static func vbox(sep: int = 6) -> VBoxContainer:
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", sep)
v.size_flags_horizontal = Control.SIZE_EXPAND_FILL
return v
static func hbox(sep: int = 6) -> HBoxContainer:
var h := HBoxContainer.new()
h.add_theme_constant_override("separation", sep)
return h
## A heading over a block of fields.
static func field(heading: String, c: Control) -> VBoxContainer:
var v := vbox(5)
v.add_child(flabel(heading))
v.add_child(c)
return v
## Names a control so focus can return to it after the inspector rebuilds.
static func tag(c: Control, key: String) -> Control:
c.set_meta(KEY, key)
return c
static func find_tagged(root: Node, key: String) -> Control:
for c in root.get_children():
if c is Control and c.has_meta(KEY) and str(c.get_meta(KEY)) == key:
return c
var r := find_tagged(c, key)
if r:
return r
return null
# ---------- Typed text <-> rule tokens ----------
## The rule token for a value a person typed into a comparison or a list
## item: numbers, @names, quoted text, true/false and the `known` chain names
## stay as they are; anything else becomes quoted text ("Aslan").
static func value_token(typed: String, known: Array = []) -> String:
var s := typed.strip_edges()
if s == "":
return ""
if s.is_valid_float() or s.begins_with("@") or Builder.is_text_literal(s) or s == "true" or s == "false" or known.has(s):
return s
return Builder.quote(s)
## How a value token shows in a field: quoted text without its quotes.
static func shown_token(tok: String) -> String:
return Builder.unquote(tok) if Builder.is_text_literal(tok) else tok
## The expression for an amount a person typed: an expression stays as
## written; a single word or phrase that isn't one (and isn't a `known`
## name) becomes quoted text, so "Millbrook" sets text rather than reading a
## value called Millbrook.
static func amount_expr(typed: String, known: Array = []) -> String:
var s := typed.strip_edges()
if s == "":
return ""
if s.is_valid_float() or Builder.is_text_literal(s) or known.has(s):
return s
var toks := Builder.tokens(s)
if toks.size() == 1 and str(toks[0]["t"]) == "name" and not ["true", "false"].has(s):
return Builder.quote(s)
if toks.is_empty() or Expr.check(TemplateKit.probe(s)) != "":
# Words with spaces ("the old mill") read as text too.
if not s.contains("(") and not s.contains("@") and not s.contains("\""):
return Builder.quote(s)
return s
## "" when an expression a person typed is usable, else why not, in plain words.
static func expr_error(src: String, what: String = "This") -> String:
var s := TemplateKit.probe(src.strip_edges())
if s == "":
return ""
var err := Expr.check(s)
return "" if err == "" else "%s can't be worked out: %s" % [what, err]

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

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

View file

@ -6,11 +6,14 @@ extends Control
enum Mode { PLAY, BUILD }
## The rules view changed ("plain" or "text"; see set_rules_view).
signal rules_view_changed(view: String)
const HISTORY_SIZE := 6
const SAVE_DELAY := 0.6
const HINTS := {
Mode.PLAY: "Click a die to roll. Shift-click skips straight to the result.",
Mode.BUILD: "Type to edit. Drag from a ● to another table to lay a pipe. Click a pipe for its options.",
Mode.BUILD: "Click a card, a result or a pipe to edit it in the inspector. Drag from a ● to another card to lay a pipe.",
}
var data: TowerBoard
@ -30,6 +33,8 @@ var edit_rev := 0
var board: BoardView
var tray: ResultTray
## The Build-mode inspector docked right of the board (ui/inspector.gd).
var inspector: Inspector
var _token := 0
var _pulse_tween: Tween
@ -140,9 +145,20 @@ func _build_ui() -> void:
root.add_theme_constant_override("separation", 0)
add_child(root)
root.add_child(_build_top_bar())
var middle := HBoxContainer.new()
middle.add_theme_constant_override("separation", 0)
middle.size_flags_vertical = SIZE_EXPAND_FILL
root.add_child(middle)
board = BoardView.new()
board.setup(self)
root.add_child(board)
board.size_flags_horizontal = SIZE_EXPAND_FILL
middle.add_child(board)
inspector = Inspector.new()
inspector.setup(self)
inspector.visible = false
if state and bool(state.get_setting("inspector_collapsed", false)):
inspector.set_collapsed(true)
middle.add_child(inspector)
_build_selection_bar()
tray = ResultTray.new()
tray.setup(self)
@ -167,7 +183,7 @@ func _build_top_bar() -> Control:
sb.border_color = Color(1, 1, 1, 0.07)
bar.add_theme_stylebox_override("panel", sb)
var h := HBoxContainer.new()
h.add_theme_constant_override("separation", 16)
h.add_theme_constant_override("separation", 10)
bar.add_child(h)
var brand := HBoxContainer.new()
@ -231,6 +247,8 @@ func _build_top_bar() -> Control:
_endless_chip = _make_endless_chip()
h.add_child(_endless_chip)
h.add_child(_make_rules_switch())
_search_button = _make_search_button()
h.add_child(_search_button)
@ -364,6 +382,12 @@ func _rebuild_cards() -> void:
_rebuild_groups()
_update_selection_bar()
_update_collapse_all()
# A board loaded or replaced starts with nothing in the inspector; an
# undo keeps the selection (the inspector follows the board).
if inspector and not _keep_history:
inspector.clear()
elif inspector:
inspector.sync()
func _refresh_lit() -> void:
@ -371,6 +395,8 @@ func _refresh_lit() -> void:
for card in cards.values():
(card as TableCard).refresh_lit()
_refresh_group_lits()
if inspector:
inspector.sync()
func set_mode(m: Mode) -> void:
@ -385,9 +411,15 @@ func set_mode(m: Mode) -> void:
# the (empty) label still stretches to push the right-hand buttons over.
_hint.text = HINTS[m] if m == Mode.PLAY else ""
_hint.tooltip_text = HINTS[m]
_hint.custom_minimum_size.x = 60.0 if m == Mode.PLAY else 0.0
# Build's bar has no room for Collapse all; it's in Arrange ▾ there.
_collapse_all.visible = m != Mode.BUILD
_build_tools.visible = m == Mode.BUILD
board.pipes.hover_key = ""
clear_selection()
inspector.visible = m == Mode.BUILD
if m != Mode.BUILD:
inspector.clear()
for card in cards.values():
(card as TableCard).rebuild()
for n in _group_nodes.values():
@ -430,6 +462,8 @@ func _board_changed() -> void:
_schedule_endless_check()
if mode == Mode.BUILD:
refresh_live()
if inspector:
inspector.sync()
## True when an expanded group, or a table that isn't hidden in a collapsed
@ -479,15 +513,17 @@ func set_all_collapsed(collapsed: bool) -> void:
mark_dirty("", false)
## The "+ Table ▾" kinds: [label, kind, sub, default name].
## The "+ Card ▾" kinds: [label, kind, sub, default name].
const ADD_KINDS := [
["Roll table", RollTable.KIND_ROLL, "", "New table"],
["Check card: roll against a target", RollTable.KIND_CHECK, "", "Check"],
["Choice: which option", RollTable.KIND_CHOICE, "pick", "New choice"],
["Choice: how many", RollTable.KIND_CHOICE, "number", "How many?"],
["Choice: open ended", RollTable.KIND_CHOICE, "text", "What is it?"],
["Loop", RollTable.KIND_LOOP, "times", "Repeat"],
["Router: if / else if / otherwise", RollTable.KIND_ROUTER, "", "Router"],
["Variable", RollTable.KIND_VARIABLE, "number", "New variable"],
["Collection (Skills, Contacts…)", RollTable.KIND_VARIABLE, RollTable.VAR_COLLECTION, "Skills"],
["Sheet", RollTable.KIND_SHEET, "", "Sheet"],
]
@ -496,7 +532,7 @@ var _add_menu: MenuButton
func _make_add_menu() -> MenuButton:
var mb := MenuButton.new()
mb.text = "+ Table ▾"
mb.text = "+ Card ▾"
mb.tooltip_text = "Add a roll table or a logic card"
mb.flat = false
var ref := Style.bar_button("", true)
@ -547,12 +583,19 @@ func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "") -> RollTabl
_begin_edit()
var center := board.screen_to_world(board.size / 2.0)
var name := "New table"
var found := false
for k: Array in ADD_KINDS:
if k[1] == kind and (sub == "" or k[2] == sub or kind != RollTable.KIND_CHOICE):
if k[1] == kind and k[2] == sub:
name = str(k[3])
found = true
break
if not found:
for k: Array in ADD_KINDS:
if k[1] == kind and (sub == "" or kind != RollTable.KIND_CHOICE) and k[2] != RollTable.VAR_COLLECTION:
name = str(k[3])
break
var t := RollTable.create(kind, TowerBoard.new_id("t"), name, sub)
if kind == RollTable.KIND_ROLL:
if kind == RollTable.KIND_ROLL or kind == RollTable.KIND_CHECK:
for e in t.entries:
e.id = TowerBoard.new_id("e")
if kind == RollTable.KIND_VARIABLE:
@ -564,6 +607,29 @@ func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "") -> RollTabl
card.setup(self, t)
cards[t.id] = card
_end_edit()
if mode == Mode.BUILD:
select_card(t.id)
return t
## Adds a variable card declaring @`var_name` (labelled `label`) beside the
## view's centre, for the value pickers' "+ New value…". An existing card
## for that name is returned as it is.
func add_variable_card(label: String, var_name: String, type: String = "number") -> RollTable:
var have := variable_card(var_name)
if have:
return have
_begin_edit()
var center := board.screen_to_world(board.size / 2.0)
var t := RollTable.create(RollTable.KIND_VARIABLE, TowerBoard.new_id("t"), label, type)
t.var_name = _free_var_name(var_name)
t.position = Vector2(maxf(20.0, roundf(center.x - 300.0)), maxf(20.0, roundf(center.y + 40.0)))
data.tables.append(t)
var card := TableCard.new()
board.cards.add_child(card)
card.setup(self, t)
cards[t.id] = card
_end_edit("Add value %s" % label)
return t
@ -1002,6 +1068,8 @@ func _frame_at(p: Vector2) -> TableGroup:
# ----- Card drags (TableCard calls these) -----
func begin_card_drag(card: TableCard) -> void:
if mode == Mode.BUILD and card and card.table:
select_card(card.table.id)
_begin_edit()
_drag_set.clear()
if mode == Mode.BUILD and selection.has(card.table.id) and selection.size() > 1:
@ -2445,8 +2513,13 @@ func details() -> DetailsPopup:
return _details_popup
## Build mode: the options for a clicked pipe (count, save as, remove).
## Build mode: a clicked pipe opens in the inspector. The old pop-up
## (PipePopover) is only a fallback for when there is no inspector.
func open_pipe_options(key: String, at: Vector2) -> void:
if inspector != null:
details().hide_for()
select_pipe(key)
return
if _pipe_popover == null:
_pipe_popover = PipePopover.new()
add_child(_pipe_popover)
@ -2458,6 +2531,9 @@ func open_pipe_options(key: String, at: Vector2) -> void:
## The card's ⚙ button. Main.open_table_settings comes from the app-shell work;
## until it exists this only says so.
func request_table_settings(tid: String) -> void:
if mode == Mode.BUILD and inspector != null:
select_card(tid)
return
if has_method("open_table_settings"):
call("open_table_settings", tid)
else:
@ -2503,6 +2579,7 @@ func _run_cli_extras(args: PackedStringArray) -> void:
var pipe := _arg_value(args, "--pipe")
if pipe != "":
open_pipe_options(pipe, Vector2(size.x * 0.45, size.y * 0.3))
await _run_inspector_cli(args)
var hover := _arg_value(args, "--hover")
if hover.contains(","):
# Synthetic mouse move, to check hover pop-ups in screenshots.
@ -2843,6 +2920,7 @@ func _nav_mode_changed() -> void:
const PACK_GAP := 60.0
const ARRANGE_PACK := 0
const ARRANGE_COLLAPSE := 1
func _make_arrange_menu() -> MenuButton:
@ -2862,9 +2940,15 @@ func _make_arrange_menu() -> MenuButton:
ModalCard.style_popup(pm)
pm.add_item("Pack collapsed groups", ARRANGE_PACK)
pm.set_item_tooltip(0, "Move collapsed groups and the cards between them together, closing the gaps, in reading order")
# Build mode's bar has no room for the Collapse all button, so it lives here.
pm.add_item("Collapse all", ARRANGE_COLLAPSE)
pm.about_to_popup.connect(func() -> void:
pm.set_item_text(pm.get_item_index(ARRANGE_COLLAPSE), "Collapse all" if _any_expanded() else "Expand all"))
pm.id_pressed.connect(func(id: int) -> void:
if id == ARRANGE_PACK:
pack_collapsed_groups())
pack_collapsed_groups()
elif id == ARRANGE_COLLAPSE:
set_all_collapsed(_any_expanded()))
return mb
@ -3047,6 +3131,7 @@ func _build_edit_timer() -> void:
func _on_focus_changed(c: Control) -> void:
if _edit_pending and _edit_focus != 0 and (c == null or c.get_instance_id() != _edit_focus):
_queue_commit()
_inspect_focus(c)
## Picks this collection's history (making one) and takes the board as its
@ -3158,6 +3243,8 @@ func _apply_history(e: Dictionary, verb: String) -> void:
_restoring = true
if _pipe_popover and _pipe_popover.visible:
_pipe_popover.hide()
if inspector:
inspector.close_menus()
details().hide_for()
board.pipes.hover_key = ""
_drop_card = null
@ -3370,3 +3457,223 @@ func _schedule_endless_check() -> void:
_endless_timer.timeout.connect(_update_endless_chip)
add_child(_endless_timer)
_endless_timer.start()
# ---------- Inspector and rules view (docs/PLAIN.md §5–6) ----------
# The inspector edits the selected card, result or pipe (Build mode). The
# display side calls select_card / select_result / select_pipe /
# clear_inspector; Main also selects from the board: a card's title (drag
# start), focus entering a result's field on a card, a clicked pipe, the ⚙.
## When there's no `state` (--sample), the rules view lives here.
var _rules_view_mem := "plain"
var _rules_buttons: Array[Button] = []
## "plain" (Describe's phrases) or "text" (the stored rule text).
func rules_view() -> String:
return state.rules_view() if state else _rules_view_mem
func rules_plain() -> bool:
return rules_view() == "plain"
## Shows rules as "plain" words or as "text"; saved as a setting. Emits
## rules_view_changed when it changes.
func set_rules_view(v: String) -> void:
if v != "plain" and v != "text":
return
if v == rules_view():
_sync_rules_switch()
return
if state:
state.set_rules_view(v)
state.save()
_rules_view_mem = v
_sync_rules_switch()
if inspector:
inspector.rebuild()
rules_view_changed.emit(v)
func _sync_rules_switch() -> void:
if _rules_buttons.size() == 2:
_rules_buttons[0].set_pressed_no_signal(rules_plain())
_rules_buttons[1].set_pressed_no_signal(not rules_plain())
## The top bar's compact "Plain | Text" rules switch.
func _make_rules_switch() -> Control:
var seg := PanelContainer.new()
seg.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.28), 9, [3, 3, 3, 3]))
seg.size_flags_vertical = SIZE_SHRINK_CENTER
seg.tooltip_text = "Show rules in plain words, or as the rule text they're stored as"
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 0)
seg.add_child(row)
var group := ButtonGroup.new()
_rules_buttons.clear()
for pair in [["Plain", "plain"], ["Text", "text"]]:
var b := _seg_button(str(pair[0]), group)
b.add_theme_font_size_override("font_size", 14)
for n in ["normal", "hover", "pressed", "hover_pressed"]:
var sb := b.get_theme_stylebox(n) as StyleBoxFlat
if sb:
sb.content_margin_left = 10
sb.content_margin_right = 10
sb.content_margin_top = 4
sb.content_margin_bottom = 4
b.tooltip_text = "Rules: show them in plain words" if pair[1] == "plain" else "Rules: show them as rule text (@luck -= 1)"
b.focus_mode = Control.FOCUS_NONE
var v: String = pair[1]
b.pressed.connect(func() -> void: set_rules_view(v))
row.add_child(b)
_rules_buttons.append(b)
_sync_rules_switch()
return seg
func select_card(table_id: String) -> void:
if inspector == null or data.get_table(table_id) == null:
return
inspector.select({"kind": "card", "tid": table_id})
func select_result(table_id: String, entry_id: String) -> void:
var t := data.get_table(table_id)
if inspector == null or t == null or t.find_entry(entry_id) == null:
return
inspector.select({"kind": "result", "tid": table_id, "eid": entry_id})
## `key` is a pipe key, "tid:eid>to" (Roller.pipe_key).
func select_pipe(key: String) -> void:
var from := key.get_slice(">", 0)
var tid := from.get_slice(":", 0)
var eid := from.get_slice(":", 1)
var to := key.get_slice(">", 1)
var t := data.get_table(tid)
var e := t.find_entry(eid) if t else null
if inspector == null or e == null or not e.pipes.has(to):
return
inspector.select({"kind": "pipe", "tid": tid, "eid": eid, "to": to})
func clear_inspector() -> void:
if inspector:
inspector.clear()
## What the inspector shows: {kind: "card" | "result" | "pipe", tid, eid?, to?} or {}.
func inspector_selection() -> Dictionary:
return inspector.selection.duplicate() if inspector else {}
## After the inspector changed a card: refreshes it (every card when a
## variable's name or label changed, since other cards show it).
func inspector_edited(tid: String, all_cards: bool = false) -> void:
_ref_cache.clear()
if all_cards:
for c in cards.values():
(c as TableCard).rebuild()
else:
var card := card_for(tid)
if card:
card.rebuild()
## Focus entering a field on a card in Build selects that result (or the card).
func _inspect_focus(c: Control) -> void:
if mode != Mode.BUILD or inspector == null or c == null or inspector.is_ancestor_of(c):
return
var n: Node = c
while n != null and not (n is TableCard):
n = n.get_parent()
var card := n as TableCard
if card == null or card.table == null:
return
for eid: String in card.rows:
var row: Node = card.rows[eid]
if is_instance_valid(row) and row.is_ancestor_of(c):
var s := inspector.selection
if str(s.get("tid", "")) != card.table.id or str(s.get("eid", "")) != eid or str(s.get("kind", "")) == "card":
select_result(card.table.id, eid)
return
if str(inspector.selection.get("tid", "")) != card.table.id:
select_card(card.table.id)
## Sets a collection member's saved value (@<stem>_<item>), keeping numbers
## as numbers. Members are local values like the Variables panel's.
func set_collection_member(t: RollTable, item: String, value: String) -> void:
var n := "%s_%s" % [t.var_name, item]
persistent_vars[n] = {"value": Expr.to_value(value) if Expr.is_number(value) else value, "source": t.id}
_variables_changed()
func remove_collection_member(t: RollTable, item: String) -> void:
if persistent_vars.erase("%s_%s" % [t.var_name, item]):
_variables_changed()
# --inspect=<table id>[:<entry id>][><target id>] select that card, result or pipe
# --rules=text show rules as text
# --pick-open open the inspector's first value picker
# --vars=name=value,… set board values (e.g. collection members)
# --light=<pipe key>,… light pipes and their results, as if rolled
# --window=<w>x<h> resize the window first (screenshots)
# --inspect-scroll=<px> scroll the inspector down
func _run_inspector_cli(args: PackedStringArray) -> void:
var win := _arg_value(args, "--window")
if win.contains("x"):
get_window().size = Vector2i(win.get_slice("x", 0).to_int(), win.get_slice("x", 1).to_int())
for i in 3:
await get_tree().process_frame
var rv := _arg_value(args, "--rules")
if rv != "":
set_rules_view(rv)
var vars := _arg_value(args, "--vars")
if vars != "":
for pair in vars.split(",", false):
var v := pair.get_slice("=", 1)
persistent_vars[pair.get_slice("=", 0)] = {"value": Expr.to_value(v) if Expr.is_number(v) else v, "source": ""}
_variables_changed()
var light := _arg_value(args, "--light")
if light != "":
for k in light.split(",", false):
lit_pipes[k] = true
lit_entries[k.get_slice(">", 0)] = true
_refresh_lit()
var sel := _arg_value(args, "--inspect")
if sel == "":
return
if mode != Mode.BUILD:
set_mode(Mode.BUILD)
if sel.contains(">"):
select_pipe(sel)
elif sel.contains(":"):
select_result(sel.get_slice(":", 0), sel.get_slice(":", 1))
else:
select_card(sel)
var scroll := _arg_value(args, "--inspect-scroll")
if scroll != "":
for i in 3:
await get_tree().process_frame
inspector._scroll.scroll_vertical = scroll.to_int()
if args.has("--pick-open"):
for i in 3:
await get_tree().process_frame
var p := _first_picker(inspector)
if p:
p.open_menu()
func _first_picker(n: Node) -> ValuePicker:
for c in n.get_children():
if c is ValuePicker and (c as ValuePicker).is_visible_in_tree():
return c
var r := _first_picker(c)
if r:
return r
return null

View file

@ -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)

View file

@ -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[=<step index>]
## 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[=<step index>]: 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()

147
ui/rules_view.gd Normal file
View file

@ -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() + "…"

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

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

View file

@ -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:

View file

@ -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,19 @@ 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 = ""
# The inspector reports {kind, tid, eid}; older callers used {table_id, entry_id}.
if sel is Dictionary:
var d := sel as Dictionary
var tid := str(d.get("tid", d.get("table_id", "")))
if tid == table.id and str(d.get("kind", "result")) == "result":
_selected_eid = str(d.get("eid", d.get("entry_id", "")))
var build := main.mode == Main.Mode.BUILD
custom_minimum_size = Vector2(card_width(), 0)
@ -137,16 +182,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 +224,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 +383,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 +394,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 +438,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 +481,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 +506,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 +525,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 +749,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 +782,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 +795,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 +894,82 @@ 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)
# The outlet name is already shown, so a result text that just repeats
# it ("Success") shows as an empty field with a hint instead.
if e.text.strip_edges() == check_outlet_name(index):
edit.text = ""
edit.placeholder_text = "What happens on a %s (optional)" % check_outlet_name(index).to_lower()
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 +1011,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 +1034,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 +1065,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 +1076,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 +1116,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 +1143,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 +1186,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 +1206,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 +1360,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 +1473,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 +1510,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:

View file

@ -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)

317
ui/value_picker.gd Normal file
View file

@ -0,0 +1,317 @@
class_name ValuePicker
extends Button
## A dropdown of the values a board uses (Builder.known_values), with search,
## grouped as variables, collections, other values and roll values. Each item
## shows its label and kind. "+ New value…" asks for a name and adds it,
## making a variable card when "Show on the board" is ticked.
## Used by the inspector's effect, condition, modifier and options builders.
signal value_chosen(name: String)
const GROUPS := ["", "Variables", "Collections", "Other values", "Roll values"]
const KIND_WORDS := {"number": "number", "text": "text", "list": "list", "collection": "collection"}
var main: Main
## The chosen value's name ("@luck", "@skill_*", "tier"), or "".
var value := ""
## Kinds offered ([] for all): "number", "text", "list", "collection".
var kinds: Array = []
## Extra items listed first: Array of {name, label, kind?}.
var extras: Array = []
## Collection patterns (@skill_*) are only offered when true.
var allow_patterns := false
var allow_new := true
var placeholder := "choose a value"
var _popup: PopupPanel
var _search: LineEdit
var _list: VBoxContainer
var _scroll: ScrollContainer
var _new_button: Button
## Names currently listed (after the search), in order.
var _shown: Array[String] = []
func _init(p_main: Main = null, p_value: String = "") -> void:
main = p_main
value = p_value
var n := Style.bordered(Style.box(InspectorKit.VAR_BG, 6, [8, 3, 8, 3]), 1, InspectorKit.VAR_BORDER)
var h := Style.bordered(Style.box(InspectorKit.VAR_BG.darkened(0.04), 6, [8, 3, 8, 3]), 1, Style.COPPER)
Style.skin_button(self, n, h, h, Style.INK)
add_theme_font_override("font", Style.body_bold())
add_theme_font_size_override("font_size", 15)
add_theme_color_override("font_focus_color", Style.INK)
size_flags_vertical = Control.SIZE_SHRINK_CENTER
pressed.connect(open_menu)
_refresh_text()
func set_value(n: String) -> void:
value = n
_refresh_text()
func _refresh_text() -> void:
if value == "":
text = placeholder + " ▾"
add_theme_color_override("font_color", Style.MUTED)
else:
text = label_of(value) + " ▾"
add_theme_color_override("font_color", Style.INK)
tooltip_text = value if value != "" else "Pick a value"
custom_minimum_size = Vector2(0, 0)
func label_of(n: String) -> String:
for x: Dictionary in extras:
if str(x["name"]) == n:
return str(x["label"])
return Describe.label(n, main.data if main else null)
## Every value offered, before the search: Array of {name, label, kind, group}.
func items() -> Array:
var out: Array = []
var seen := {}
for x: Dictionary in extras:
out.append({"name": x["name"], "label": x["label"], "kind": str(x.get("kind", "")), "group": ""})
seen[x["name"]] = true
var board: TowerBoard = main.data if main else null
var known: Array = Builder.known_values(board) if board else []
# Members of a collection that only exist as saved values (not yet named
# in any rule) are offered too.
if main:
var stems: Array = []
for t in board.tables:
if t.is_collection() and t.var_name != "":
stems.append(t)
var names: Array = main.persistent_vars.keys()
names.sort()
for n: String in names:
for t: RollTable in stems:
if n.begins_with(t.var_name + "_") and n.length() > t.var_name.length() + 1:
known.append({"name": "@" + n, "label": Describe.label("@" + n, board), "kind": "number",
"source": "member", "collection": "@%s_*" % t.var_name})
break
for k: Dictionary in known:
var n := str(k["name"])
if seen.has(n):
continue
var kind := str(k["kind"])
if n.ends_with("*") and not allow_patterns:
continue
if not kinds.is_empty() and not kinds.has(kind):
continue
seen[n] = true
var g := "Other values"
match str(k["source"]):
"variable":
g = "Variables"
"collection":
g = "Collections"
"chain":
g = "Roll values"
"input":
g = "Roll values"
if k.has("collection"):
g = "Collections"
out.append({"name": n, "label": str(k["label"]), "kind": kind, "group": g})
var ordered: Array = []
for g: String in GROUPS:
for it: Dictionary in out:
if it["group"] == g:
ordered.append(it)
return ordered
## Items matching `query` (label or name, any case).
func filtered(query: String) -> Array:
var q := query.strip_edges().to_lower()
var out: Array = []
for it: Dictionary in items():
if q == "" or str(it["label"]).to_lower().contains(q) or str(it["name"]).to_lower().contains(q):
out.append(it)
return out
## Names listed in the open menu.
func shown_names() -> Array[String]:
return _shown
func open_menu() -> void:
if _popup == null:
_build_popup()
_search.text = ""
_fill("")
var r := get_global_rect()
_popup.reset_size()
var view := get_viewport_rect().size
var p := Vector2(r.position.x, r.end.y + 4)
var sz := Vector2(260, 0)
p.x = clampf(p.x, 8.0, view.x - sz.x - 12.0)
if p.y + 340.0 > view.y:
p.y = maxf(8.0, r.position.y - 344.0)
_popup.popup(Rect2i(Vector2i(p), Vector2i(260, 0)))
_search.grab_focus.call_deferred()
func is_menu_open() -> bool:
return _popup != null and _popup.visible
func close_menu() -> void:
if _popup:
_popup.hide()
func _build_popup() -> void:
_popup = PopupPanel.new()
_popup.theme = Style.card_theme()
var sb := Style.bordered(Style.box(Style.CARD, 8, [6, 6, 6, 6]), 1, Style.DASH)
sb.shadow_color = Color(0, 0, 0, 0.3)
sb.shadow_size = 12
sb.shadow_offset = Vector2(0, 5)
_popup.add_theme_stylebox_override("panel", sb)
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 4)
v.custom_minimum_size = Vector2(248, 0)
_popup.add_child(v)
_search = InspectorKit.line("", "Search values")
_search.text_changed.connect(_fill)
_search.text_submitted.connect(func(s: String) -> void:
if not _shown.is_empty():
choose(_shown[0])
elif allow_new and s.strip_edges() != "":
_ask_new(s.strip_edges())
)
v.add_child(_search)
_scroll = ScrollContainer.new()
_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
_scroll.custom_minimum_size = Vector2(0, 40)
v.add_child(_scroll)
_list = VBoxContainer.new()
_list.add_theme_constant_override("separation", 0)
_list.size_flags_horizontal = Control.SIZE_EXPAND_FILL
_scroll.add_child(_list)
_new_button = _row_button("+ New value…", "", true)
_new_button.pressed.connect(func() -> void: _ask_new(_search.text.strip_edges()))
v.add_child(_new_button)
add_child(_popup)
func _fill(query: String) -> void:
for c in _list.get_children():
_list.remove_child(c)
c.queue_free()
_shown.clear()
var last_group := "-"
for it: Dictionary in filtered(query):
if it["group"] != last_group:
last_group = str(it["group"])
if last_group != "":
var h := InspectorKit.flabel(last_group)
h.add_theme_constant_override("line_spacing", 0)
var m := MarginContainer.new()
m.add_theme_constant_override("margin_left", 6)
m.add_theme_constant_override("margin_top", 6)
m.add_child(h)
_list.add_child(m)
_list.add_child(_item_button(it))
_shown.append(str(it["name"]))
var q := query.strip_edges()
_new_button.visible = allow_new
_new_button.text = "+ New value…" if q == "" else "+ New value “%s”…" % q
if _shown.is_empty():
_list.add_child(InspectorKit.note("Nothing matches.", Style.MUTED, 14))
_scroll.custom_minimum_size.y = clampf(_list.get_combined_minimum_size().y, 40.0, 300.0)
if _popup.visible:
_popup.reset_size()
func _item_button(it: Dictionary) -> Button:
var kind := str(it.get("kind", ""))
var b := _row_button(str(it["label"]), KIND_WORDS.get(kind, kind), false)
if str(it["name"]) == value:
b.add_theme_stylebox_override("normal", Style.box(Style.LIT, 5, [8, 4, 8, 4]))
b.tooltip_text = str(it["name"])
var n := str(it["name"])
b.pressed.connect(func() -> void: choose(n))
return b
func _row_button(label: String, right: String, accent: bool) -> Button:
var b := Button.new()
b.alignment = HORIZONTAL_ALIGNMENT_LEFT
b.text = label
b.clip_text = true
var n := Style.box(Color(0, 0, 0, 0), 5, [8, 4, 8, 4])
var h := Style.box(Style.HOVER_ROW, 5, [8, 4, 8, 4])
Style.skin_button(b, n, h, h, Style.COPPER_DARK if accent else Style.INK)
b.add_theme_font_override("font", Style.body_bold() if accent else Style.body())
b.add_theme_font_size_override("font_size", 15)
b.focus_mode = Control.FOCUS_NONE
if right != "":
var k := Style.make_label(right, Style.body(), 12, Style.MUTED)
k.set_anchors_and_offsets_preset(Control.PRESET_CENTER_RIGHT)
k.offset_left = -80
k.offset_right = -8
k.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
k.mouse_filter = Control.MOUSE_FILTER_IGNORE
b.add_child(k)
return b
## Picks `n` (as if clicked).
func choose(n: String) -> void:
close_menu()
set_value(n)
value_chosen.emit(n)
func _ask_new(initial: String) -> void:
close_menu()
var d := ModalCard.new("New value", 420.0)
var le := LineEdit.new()
le.text = initial
le.placeholder_text = "e.g. Luck"
ModalCard.style_line_edit(le)
d.body.add_child(ModalCard.field("Name", le))
var cb := InspectorKit.check_box("Show on the board", true)
cb.tooltip_text = "Adds a variable card, so the value has a label and a starting value, and shows while you play"
d.body.add_child(cb)
var hint := ModalCard.note("")
d.body.add_child(hint)
var upd := func(_s: String = "") -> void:
var nm := JsonIO.slug(le.text.strip_edges(), "")
hint.text = "In rules: @%s" % nm if nm != "" else "Give it a name."
le.text_changed.connect(upd)
upd.call()
var accept := func() -> void:
if le.text.strip_edges() == "":
return
d.close()
create_value(le.text.strip_edges(), cb.button_pressed)
le.text_submitted.connect(func(_t: String) -> void: accept.call())
d.add_button("Cancel", "plain", d.close)
d.add_button("Add", "primary", accept)
d.ready.connect(func() -> void:
le.grab_focus()
le.select_all()
)
if main:
main.add_child(d)
## Adds a value named `label_text` ("Luck" -> @luck) and picks it. With
## `on_board`, a variable card declares it (Main.add_variable_card).
## Returns the value's name.
func create_value(label_text: String, on_board: bool) -> String:
var nm := JsonIO.slug(label_text.strip_edges(), "value")
if on_board and main:
var t := main.add_variable_card(label_text.strip_edges(), nm)
nm = t.var_name
var full := "@" + nm
set_value(full)
value_chosen.emit(full)
return full

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

@ -0,0 +1 @@
uid://2e7nrxufi5y

197
ui/why_popover.gd Normal file
View file

@ -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)

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

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