Compare commits

...

4 commits

Author SHA1 Message Date
6ada00ad99 Run the endless-loop check after edits pause, not on every change
Roller.endless_cycles walks the whole board (about 30 ms on an 800-card
board) and ran on every keystroke in Build mode. It now runs 0.4 s after
edits stop, so a change costs about 0.4 ms instead of 34 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 19:03:39 -06:00
292d45e179 Merge branch 'worktree-agent-a694f3c612ebce597' into undo-options 2026-11-08 19:01:35 -06:00
ff7c2023c2 Undo and redo for every Build edit
EditHistory (ui/edit_history.gd) keeps an undo and a redo stack of
whole-board snapshots per collection. Each table and group is its own
JSON string, shared with the previous snapshot when unchanged, so a step
costs about the size of the cards it changed. Collapsed flags are kept
apart: collapsing isn't a step and undo leaves it as it is. Labels come
from diffing the snapshots ("Delete table Loot", "Add pipe Loot → Gems",
"Move 3 cards", "Group Careers"), or from the caller.

Main.mark_dirty records steps: typing commits when it pauses (0.8 s) and
merges until focus moves, other edits commit at the end of the frame (a
drag is one step), and quick edits to the same card or pipe merge.
Actions in main.gd bracket their changes with _begin_edit/_end_edit.
Undo patches only the changed tables and groups in place and rebuilds
their cards, keeping view, mode, search and lit results, then flashes
what changed. Ctrl+Z, Ctrl+Shift+Z / Ctrl+Y outside text fields (Play
too), Undo/Redo buttons with step tooltips in the Build bar, and the
toast's Undo now goes through the history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 19:00:47 -06:00
86d1b214c3 Dynamic pick options, show_if and indirect @[expr] names
Pick choice cards can take their options from variables (options_from:
@prefix_* or a @list, filtered by options_where with option, option_label
and option_value bound). A Chosen entry runs for whichever dynamic option
is picked; fixed entries stay as extras, listed first. Random weighs each
dynamic option as the Chosen entry and fixed ones by weight. Any pick
option can have show_if, which hides it from the pop-up and from Random;
with nothing offered the node stops with "No options available".

@[expr] reads or writes the variable named by expr in expressions,
effects (including reset) and text ({@[expr]}); bad computed names are
effect errors. JSON round trip, lint_options in lint_pipes, choice
pop-up value badges and previews, card and settings UI, docs, demo board
(Spend a find) and tests/test_options.gd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:55:38 -06:00
24 changed files with 3358 additions and 111 deletions

View file

@ -23,7 +23,19 @@ godot --path .
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. Deletions can be undone from the toast.
plain or dice table (e.g. 2d6), and Card mode.
- **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
**Ctrl+Y** redoes; Build mode's top bar has **Undo** and **Redo** buttons whose tooltips
name the step ("Undo: Delete table Loot"), and the message after a deletion has an Undo
button too. While a text field has focus, Ctrl+Z undoes typing in that field; click the
felt first to undo on the board. Typing in one field until you move on is
one step, a whole drag is one step, and quick changes to the same card or pipe merge.
Undo keeps your view, mode, search and lit results, and rings the cards it changed.
Collapsing and expanding cards and groups isn't an undo step (it's left as it is), and
neither are rolls, decks or variables. In Play mode Ctrl+Z still works, for cards you
moved there. Each collection keeps its own history (up to 200 steps) while the app runs.
- **Text in results** can roll on other tables inline with `[[Table]]`, `[[3x Gems]]` or
`[[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
@ -41,6 +53,12 @@ godot --path .
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
("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
**Only where** (`option_value >= 1`); its **Chosen** row runs for whichever is picked, with
`option` holding the name, so `@[option] += 1` raises it. Fixed options can stay alongside,
and any option can have a **Show only if** condition (the **if** toggle on its row) that
hides it from the pop-up and from Random.
- **Collections:** the switcher in the top bar holds separate sets of tables. Build mode's
**Board ▾** menu imports and exports TableTower JSON, JSON Canvas, Mermaid, DOT and GraphML.
- **Ranged tables** (like *Wilderness Travel*) roll a d100 where each range's size sets its
@ -141,6 +159,9 @@ Groups and templates: `--select=<id>,<id>`, `--group-selected[=<name>]`, `--coll
`--save-template=<table>`, `--save-group-template=first`, `--view=<x>,<y>[,<zoom>]`, `--fit` and
`--clear-result`.
Undo: `--undo-demo[=<table id>]` deletes a table and undoes it (the toast says so),
`--undo-tooltip` makes an edit and hovers the Undo button.
Navigation: `--search=<text>` (the search panel with results), `--focus=<table id>[:<entry id>]`,
`--minimap` / `--no-minimap`, `--pack` (Build), and `--perf` (prints load time and idle and
panning frame times with vsync off, then quits; `--perf-layers` adds a per-layer breakdown).

View file

@ -9,6 +9,8 @@ extends RefCounted
## @age *= 2 multiply (/= divides, rounding down)
## reset @name back to the variable card's starting value, or deleted
## reset @skill_* every variable with that prefix
## @[expr] += 1 the variable named by expr (indirect), e.g.
## @[option] += 1, reset @["skill_" + option]
##
## A target without "@" is a chain variable. Unset counts as 0 (or "" when the
## value added is text). run() never stops on a bad statement: it logs an error
@ -51,6 +53,9 @@ static func split(text: String) -> Array[String]:
static func parse_statement(src: String) -> Dictionary:
_compile()
var s := src.strip_edges()
var ind := _parse_indirect(s)
if not ind.is_empty():
return ind
var m := _reset_re.search(s)
if m != null:
var target := "@" + m.get_string(1).to_lower() + m.get_string(2)
@ -69,6 +74,55 @@ static func parse_statement(src: String) -> Dictionary:
return {"src": s, "op": m.get_string(2), "target": t, "expr": expr}
## An indirect statement ("@[expr] op value" or "reset @[expr]"), parsed into
## the same shape with "target_expr" (the expression naming the variable) and
## target "@[expr]"; {} when `s` isn't one.
static func _parse_indirect(s: String) -> Dictionary:
var at := -1
var is_reset := false
if s.begins_with("@["):
at = 1
elif s.to_lower().begins_with("reset") and s.substr(5).strip_edges().begins_with("@["):
is_reset = true
at = s.find("@[") + 1
if at < 0:
return {}
var close := Expr.bracket_end(s, at)
if close < 0:
return {"src": s, "error": "@[ is missing its closing ]"}
var inner := s.substr(at + 1, close - at - 1).strip_edges()
if inner == "":
return {"src": s, "error": "Write an expression inside @[ ], e.g. @[option]"}
var target := s.substr(at - 1, close - at + 2)
var rest := s.substr(close + 1).strip_edges()
if is_reset:
if rest != "":
return {"src": s, "error": "Write reset @[expr]"}
return {"src": s, "op": "reset", "target": target, "target_expr": inner, "expr": ""}
for op: String in ["+=", "-=", "*=", "/=", "="]:
if rest.begins_with(op) and not (op == "=" and rest.begins_with("==")):
var expr := rest.substr(op.length()).strip_edges()
if expr == "":
return {"src": s, "error": "Nothing after %s" % op}
return {"src": s, "op": op, "target": target, "target_expr": inner, "expr": expr}
return {"src": s, "error": "Not a statement; try @[name] = value"}
## The real target of a statement: its "target", or for an indirect one
## "@name" from its expression. {"target", "error"}: the error is set when
## the expression fails or doesn't give a valid name.
static func resolve_target(st: Dictionary, ctx: RollContext) -> Dictionary:
if not st.has("target_expr"):
return {"target": st["target"], "error": ""}
var r := Expr.evaluate(str(st["target_expr"]), ctx)
if r["error"] != "":
return {"target": "", "error": str(r["error"])}
var nm := Expr.indirect_name(r["value"])
if nm["error"] != "":
return {"target": "", "error": str(nm["error"])}
return {"target": "@" + str(nm["name"]), "error": ""}
## Problems in effect text for the Build-mode editor: Array of {index (0-based
## statement number), src, error}. Empty when everything parses.
static func validate(text: String) -> Array[Dictionary]:
@ -77,6 +131,8 @@ static func validate(text: String) -> Array[Dictionary]:
for k in list.size():
var st := parse_statement(list[k])
var err := str(st.get("error", ""))
if err == "" and st.has("target_expr"):
err = Expr.check(st["target_expr"])
if err == "" and st["op"] != "reset":
err = Expr.check(st["expr"])
if err != "":
@ -96,6 +152,12 @@ static func run(text: String, ctx: RollContext, source_id: String = "") -> Array
if st.has("error"):
log.append({"text": "%s: %s" % [src, st["error"]], "error": true})
continue
if st.has("target_expr"):
var rt := resolve_target(st, ctx)
if rt["error"] != "":
log.append({"text": "%s: %s" % [src, rt["error"]], "error": true})
continue
st["target"] = rt["target"]
if st["op"] == "reset":
log.append(_reset(st["target"], ctx))
else:

View file

@ -6,6 +6,8 @@ extends RefCounted
## name a chain variable (answer, i, or anything saved with -> name)
## 2d6 d20 3D D3 dice, rolled fresh every time (a missing count is 1, missing
## sides are 6)
## @[expr] the board variable named by expr (indirect), e.g.
## @[option] or @["skill_" + option]
## a = b a lone "=" means equals
## dm(x) has(list, item) count(prefix), plus Expression's built-ins
## (min max clamp abs floor ceil round ...)
@ -25,6 +27,7 @@ const _KEYWORDS := ["and", "or", "not", "in", "true", "false", "null", "if", "el
## text_side: Array[bool] per input (an unset value reads as ""), error: String}
static var _cache: Dictionary = {}
static var _dice_re: RegEx = null
static var _name_re: RegEx = null
## Evaluates `src` against a roll context. `ctx` may be null (variables then
@ -198,6 +201,45 @@ static func has_item(list: Variant, item: Variant) -> bool:
return false
## The board variable name an indirect @[expr] computed: {"name": String
## (no "@"), "error": String}. Names are lowercase letters, digits and "_"
## (a leading "@" is dropped and capitals are lowered).
static func indirect_name(v: Variant) -> Dictionary:
var s := format_value(v).strip_edges().trim_prefix("@").to_lower()
if s == "":
return {"name": "", "error": "@[…] gave an empty variable name"}
if _name_re == null:
_name_re = RegEx.create_from_string("^[a-z_][a-z0-9_]*$")
if _name_re.search(s) == null:
return {"name": "", "error": "@[…] gave \"%s\", which isn't a variable name (lowercase letters, digits and _)" % format_value(v)}
return {"name": s, "error": ""}
## Index of the "]" that closes the "[" at `open` in `s`, skipping quoted text
## and nested brackets; -1 when there isn't one.
static func bracket_end(s: String, open: int) -> int:
var depth := 0
var quote := ""
var k := open
while k < s.length():
var c := s[k]
if quote != "":
if c == "\\":
k += 1
elif c == quote:
quote = ""
elif c == "\"" or c == "'":
quote = c
elif c == "[":
depth += 1
elif c == "]":
depth -= 1
if depth == 0:
return k
k += 1
return -1
## Rolls NdM with `rng` (a fresh one when null).
static func roll_dice(n: int, sides: int, rng: RandomNumberGenerator) -> int:
if rng == null:
@ -248,6 +290,10 @@ static func _rewrite(src: String) -> Dictionary:
var vars: Array = []
var text_side: Array = []
var slot := {} # "@name" / "name" -> input index
# Open brackets: true for an indirect @[ (closes with ")"), false for a
# plain "[".
var brackets: Array[bool] = []
var n_ind := 0
# Tokens as [kind, text]: kind "str", "var", "op", "other" (for text_side).
var toks: Array = []
var i := 0
@ -267,6 +313,33 @@ static func _rewrite(src: String) -> Dictionary:
toks.append(["str", lit])
i = j + 1
continue
if c == "@" and i + 1 < n and src[i + 1] == "[":
# @[expr]: an indirect variable, read through _iv() (or _ivt() when
# it sits beside text, so unset reads as "").
out += "\u0001%d\u0001" % n_ind
toks.append(["ivo", n_ind])
brackets.append(true)
n_ind += 1
i += 2
continue
if c == "[":
brackets.append(false)
elif c == "]" and not brackets.is_empty():
if brackets.pop_back():
var id := -1
var depth := 0
for t in range(toks.size() - 1, -1, -1):
if toks[t][0] == "ivc":
depth += 1
elif toks[t][0] == "ivo":
if depth == 0:
id = toks[t][1]
break
depth -= 1
out += ")"
toks.append(["ivc", id])
i += 1
continue
if c == "@":
var j := i + 1
while j < n and _is_word(src[j]):
@ -351,6 +424,22 @@ static func _rewrite(src: String) -> Dictionary:
toks.append(["op", c])
out += c
i += 1
if brackets.has(true):
return {"text": "", "inputs": [], "vars": [], "text_side": [], "error": "@[ is missing its closing ]"}
# An indirect @[…] beside a text literal (or `in`) reads as "" when unset.
var beside := func(u: int) -> bool:
return u >= 0 and u < toks.size() and (toks[u][0] == "str" or (toks[u][0] == "op" and toks[u][1] == "in"))
for t in toks.size():
if toks[t][0] != "ivo":
continue
var id: int = toks[t][1]
var close := t
for u in range(t + 1, toks.size()):
if toks[u][0] == "ivc" and toks[u][1] == id:
close = u
break
var text_side_ind: bool = beside.call(t - 1) or beside.call(t - 2) or beside.call(close + 1) or beside.call(close + 2)
out = out.replace("\u0001%d\u0001" % id, "_ivt(" if text_side_ind else "_iv(")
# A variable directly beside a text literal (or `in`) reads as "" when unset.
for t in toks.size():
if toks[t][0] != "var":
@ -404,6 +493,23 @@ class _Base:
func has(list: Variant, item: Variant) -> bool:
return Expr.has_item(list, item)
func _iv(name: Variant) -> Variant:
return _indirect(name, 0)
func _ivt(name: Variant) -> Variant:
return _indirect(name, "")
func _indirect(name: Variant, unset: Variant) -> Variant:
var r := Expr.indirect_name(name)
if r["error"] != "":
if error == "":
error = r["error"]
return unset
if ctx == null:
return unset
var v: Variant = ctx.get_value("@" + str(r["name"]))
return unset if v == null else Expr.to_value(v)
func count(prefix: Variant) -> int:
if ctx == null:
return 0

View file

@ -55,6 +55,15 @@ var choice: String = "pick"
var prompt: String = ""
## Choice cards: variable the answer is saved under ("@name" or a chain name).
var save_as: String = ""
## Pick choices: options from variables (docs/LOGIC.md §2a). "@prefix_*"
## gives one option per set variable with that prefix, "@list" one option per
## item of a list variable. "" for a fixed list. When it's set, entries[0] is
## the Chosen entry (it happens for whichever dynamic option is picked) and
## any other entries are fixed extras.
var options_from: String = ""
## Pick choices with options_from: an expression each candidate must pass,
## with the chain variables option, option_label and option_value bound.
var options_where: String = ""
## Number choices: bounds, as expressions.
var min_expr: String = "0"
var max_expr: String = "99"
@ -123,6 +132,51 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = "
return t
## True for a pick choice whose options come from variables (options_from).
func is_dynamic() -> bool:
return kind == KIND_CHOICE and choice == "pick" and options_from.strip_edges() != ""
## Index of the first fixed option on a pick choice: 1 when entries[0] is the
## Chosen entry of a dynamic card, else 0.
func fixed_start() -> int:
return 1 if is_dynamic() else 0
## Parses an options_from pattern: {"kind": "prefix" | "list" | "", "name":
## the prefix or list variable name without "@" and "*", "error": String}.
## "@skill_*" is a prefix, "@contacts" a list variable.
static func parse_options_from(src: String) -> Dictionary:
var s := src.strip_edges()
if s == "":
return {"kind": "", "name": "", "error": ""}
if not s.begins_with("@"):
return {"kind": "", "name": "", "error": "Write @prefix_* (each set variable with that prefix) or @list (each item of a list variable)"}
var prefix := s.ends_with("*")
var name := s.substr(1, s.length() - (2 if prefix else 1)).to_lower()
if name == "":
return {"kind": "", "name": "", "error": "Give a name after @, e.g. @skill_* or @contacts"}
if RegEx.create_from_string("^[a-z_][a-z0-9_]*$").search(name) == null:
return {"kind": "", "name": "", "error": "\"%s\" isn't a variable name (lowercase letters, digits and _)" % s}
return {"kind": "prefix" if prefix else "list", "name": name, "error": ""}
## "each @skill_* that's set, where option_value >= 1" (for previews and cards).
func options_description() -> String:
var p := parse_options_from(options_from)
var s := ""
match str(p["kind"]):
"prefix":
s = "each @%s* that's set" % p["name"]
"list":
s = "each item of @%s" % p["name"]
_:
s = options_from.strip_edges()
if options_where.strip_edges() != "":
s += ", where " + options_where.strip_edges()
return s
## Router cards: index of the first case that is an Otherwise case (empty
## `when`), or -1.
func otherwise_index() -> int:
@ -388,6 +442,10 @@ func to_dict() -> Dictionary:
d["prompt"] = prompt
if save_as != "":
d["save_as"] = save_as
if options_from.strip_edges() != "":
d["options_from"] = options_from.strip_edges()
if options_where.strip_edges() != "":
d["options_where"] = options_where.strip_edges()
if min_expr != "0":
d["min"] = min_expr
if max_expr != "99":
@ -426,6 +484,8 @@ static func from_dict(d: Dictionary) -> RollTable:
t.choice = c if CHOICES.has(c) else "pick"
t.prompt = str(d.get("prompt", ""))
t.save_as = str(d.get("save_as", ""))
t.options_from = str(d.get("options_from", "")).strip_edges() if d.get("options_from") != null else ""
t.options_where = expr_text(d.get("options_where", ""), "").strip_edges()
t.min_expr = expr_text(d.get("min", "0"), "0")
t.max_expr = expr_text(d.get("max", "99"), "99")
var lm := str(d.get("loop", "times"))

View file

@ -17,6 +17,7 @@ extends RefCounted
## effects: Array of {"text": String, "error": true?}, the effect log
## answer: the player's answer on a number/text choice (int or String)
## picked: true when the player picked a pick option; random: true for Random
## option: on a pick node for a dynamic option (options_from), its label
## passes: int, on a loop's header node ("Repeated N times"); its children
## are one node per pass ("pass": i, "value": i) and then the Afterwards
## node ("after": true)
@ -37,6 +38,7 @@ const MAX_DEPTH := RollContext.DEFAULT_MAX_DEPTH
const MAX_ACTIONS := RollContext.DEFAULT_MAX_ACTIONS
const CANCELLED := "Cancelled"
const NO_CASE := "No case matched"
const NO_OPTIONS := "No options available"
enum { OP_ROLL, OP_PIPE, OP_LOOP }
@ -284,6 +286,12 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
c["inline"] = true
kids.append(c)
node["summary"] = ex["text"]
# The Chosen entry of a dynamic pick reads as the option's label unless
# it has text of its own.
if node.has("option"):
var plain := Formatter.strip_tags(e.text).strip_edges()
if plain == "" or plain == CHOSEN:
node["summary"] = Formatter.escape_literal(str(node["option"]))
if ctx.halted != "":
return
var save := str(f.get("save", ""))
@ -293,7 +301,10 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
# A picked option is saved under the choice's save_as before the pipe
# snapshot, so its own pipe conditions can read it.
if t.kind == RollTable.KIND_CHOICE and t.save_as != "" and not node.has("answer"):
ctx.save(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id)
if node.has("option"):
ctx.save(t.save_as, str(node["option"]), t.id)
else:
ctx.save(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id)
if e.pipes.is_empty():
return
var log: Array = []
@ -468,13 +479,38 @@ static func _do_loop(f: Dictionary, ctx: RollContext, stack: Array) -> void:
## The prompt request for a choice card (docs/LOGIC.md §8):
## {table_id, kind ("pick" | "number" | "text"), title, prompt (BBCode,
## rendered), options: [{index, text, details}], min, max, default}.
## rendered), options: [{index, entry, text, details, weight, ...}], min, max,
## default, log (error lines from show_if and options_where), hidden (how many
## fixed options show_if hid)}.
## A pick's options are its fixed options whose show_if holds (index = entry
## = the entry's index), then, on a dynamic card (options_from), one option
## per candidate variable or list item (index = entries.size() + j, entry =
## 0, the Chosen entry, plus "dynamic": true, "option", "label", "value" and
## "value_text"). The reply is an option's index, or -1 for Random.
static func request_for(t: RollTable, ctx: RollContext) -> Dictionary:
var options: Array = []
var log: Array = []
var hidden := 0
if t.choice == "pick":
for k in t.entries.size():
var ranged := t.is_ranged()
for k in range(t.fixed_start(), t.entries.size()):
var e := t.entries[k]
options.append({"index": k, "text": TextExpander.render(e.text, ctx), "details": e.details})
if not option_shown(e, ctx, log):
hidden += 1
continue
options.append({"index": k, "entry": k, "text": TextExpander.render(e.text, ctx), "details": e.details,
"weight": e.span() if ranged else maxi(0, e.weight)})
if t.is_dynamic() and not t.entries.is_empty() and option_shown(t.entries[0], ctx, log):
var chosen := t.entries[0]
var cands := dynamic_options(t, ctx, log)
for j in cands.size():
var c: Dictionary = cands[j]
var vt := Expr.format_value(c["value"]) if str(c["kind"]) == "prefix" else ""
var label := str(c["label"])
var shown := label if vt == "" else "%s %s" % [label, vt]
options.append({"index": t.entries.size() + j, "entry": 0, "text": Formatter.escape_literal(shown),
"details": chosen.details, "weight": maxi(0, chosen.weight), "dynamic": true,
"option": c["option"], "label": label, "value": c["value"], "value_text": vt})
var lo := Expr.eval_int(t.min_expr, ctx, 0)
var hi := maxi(lo, Expr.eval_int(t.max_expr, ctx, 99))
var def: Variant = -1
@ -483,7 +519,86 @@ static func request_for(t: RollTable, ctx: RollContext) -> Dictionary:
elif t.choice == "text":
def = ""
return {"table_id": t.id, "kind": t.choice, "title": t.name, "prompt": TextExpander.render(t.prompt, ctx),
"options": options, "min": lo, "max": hi, "default": def}
"options": options, "min": lo, "max": hi, "default": def, "log": log, "hidden": hidden}
## Whether a pick option is offered now: its show_if is empty or true. An
## error counts as false and adds a line to `log`.
static func option_shown(e: TableEntry, ctx: RollContext, log: Array = []) -> bool:
var w := e.show_if.strip_edges()
if w == "":
return true
var r := Expr.evaluate(w, ctx)
if r["error"] != "":
log.append({"text": "Show only if %s: %s" % [w, r["error"]], "error": true})
return false
return Expr.truthy(r["value"])
## The candidates of a dynamic pick card (options_from, filtered by
## options_where), in order: Array of {kind ("prefix" | "list"), option (the
## variable name without "@", or the list item), label, value}. A prefix
## gives one per set variable, sorted by label ("Pilot"); a list gives one
## per item, in list order (label and value are the item). A filter error
## counts as false and adds one line to `log`.
static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = []) -> Array:
var out: Array = []
var src := RollTable.parse_options_from(t.options_from)
if str(src["error"]) != "":
log.append({"text": "Options from %s: %s" % [t.options_from.strip_edges(), src["error"]], "error": true})
return out
var name := str(src["name"])
var cands: Array = []
match str(src["kind"]):
"prefix":
for v in ctx.list_vars(name):
cands.append({"kind": "prefix", "option": v["name"], "label": v["label"], "value": v["value"]})
"list":
var cur: Variant = ctx.get_value("@" + name)
for item in Expr.list_items(cur if cur != null else ""):
cands.append({"kind": "list", "option": item, "label": item, "value": item})
var where := t.options_where.strip_edges()
if where == "":
return cands
var saved := {}
for k in OPTION_VARS:
if ctx.chain_vars.has(k):
saved[k] = ctx.chain_vars[k]
var failed := false
for c: Dictionary in cands:
_bind_option(ctx, c)
var r := Expr.evaluate(where, ctx)
if r["error"] != "":
if not failed:
failed = true
log.append({"text": "Only where %s: %s" % [where, r["error"]], "error": true})
elif Expr.truthy(r["value"]):
out.append(c)
for k in OPTION_VARS:
if saved.has(k):
ctx.chain_vars[k] = saved[k]
else:
ctx.chain_vars.erase(k)
return out
## How many options a pick card offers right now (show_if and options_from
## included); for the card's live count.
static func available_count(t: RollTable, ctx: RollContext) -> int:
return (request_for(t, ctx)["options"] as Array).size()
## The chain variables a dynamic option sets.
const OPTION_VARS: Array[String] = ["option", "option_label", "option_value"]
## The default text of a dynamic card's Chosen entry: the result then reads as
## the picked option's label.
const CHOSEN := "Chosen"
static func _bind_option(ctx: RollContext, c: Dictionary) -> void:
ctx.chain_vars["option"] = c["option"]
ctx.chain_vars["option_label"] = c["label"]
ctx.chain_vars["option_value"] = Expr.normalize(c["value"])
## The headless answer to a request: Random for a pick, min for a number, ""
@ -506,6 +621,12 @@ static func ask(ctx: RollContext, req: Dictionary) -> Variant:
static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var req := request_for(t, ctx)
var opts: Array = req["options"]
if t.choice == "pick" and opts.is_empty():
var none := _stop(t, NO_OPTIONS, {"kind": RollTable.KIND_CHOICE})
_log(none, req["log"])
_attach(f, none, ctx)
return
var reply: Variant = await ask(ctx, req)
if reply == null:
_attach(f, _stop(t, CANCELLED, {"kind": RollTable.KIND_CHOICE, "cancelled": true}), ctx)
@ -525,26 +646,71 @@ static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Arr
await _answered(t, f, ctx, stack, s, Formatter.close_open_tags(s))
_:
var idx := int(reply) if (reply is int or reply is float) else -1
var opt: Dictionary = {}
for o: Dictionary in opts:
if int(o["index"]) == idx:
opt = o
break
var node: Dictionary
if idx >= 0 and idx < t.entries.size():
node = {"table": t, "index": idx, "entry": t.entries[idx], "children": [], "summary": "", "picked": true}
if t.card_mode:
var decks: Dictionary = ctx.get_meta("decks", {})
if not decks.has(t.id):
decks[t.id] = DeckState.new()
var deck: DeckState = decks[t.id]
var eid := t.entries[idx].id
deck.drawn[eid] = int(deck.drawn.get(eid, 0)) + 1
else:
if not opt.is_empty():
node = _option_node(t, opt, ctx)
node["picked"] = true
elif not t.is_dynamic() and int(req["hidden"]) == 0:
# A plain fixed list: Random rolls the card the usual way
# (weights, ranges, card mode).
node = _pick_node(t, ctx)
node["random"] = true
else:
var k := _pick_option(opts, ctx.rng)
if k < 0:
node = _stop(t, "No result can come up")
else:
node = _option_node(t, opts[k], ctx)
node["random"] = true
node["kind"] = RollTable.KIND_CHOICE
_log(node, req["log"])
_attach(f, node, ctx)
if node.has("stop"):
return
await _enter(node, f, ctx, stack)
## The node for a pick option from a request: a fixed entry (a card-mode deck
## counts the draw), or the Chosen entry for a dynamic option, which binds
## option, option_label and option_value first.
static func _option_node(t: RollTable, o: Dictionary, ctx: RollContext) -> Dictionary:
var ei := int(o.get("entry", o["index"]))
var node := {"table": t, "index": ei, "entry": t.entries[ei], "children": [], "summary": ""}
if o.get("dynamic", false):
_bind_option(ctx, {"option": o["option"], "label": o["label"], "value": o["value"]})
node["option"] = str(o["label"])
elif t.card_mode:
var decks: Dictionary = ctx.get_meta("decks", {})
if not decks.has(t.id):
decks[t.id] = DeckState.new()
var deck: DeckState = decks[t.id]
var eid := t.entries[ei].id
deck.drawn[eid] = int(deck.drawn.get(eid, 0)) + 1
return node
## Random among a request's options by their "weight" (each dynamic option
## weighs as much as the Chosen entry; fixed ones their own weight, or span
## on a ranged card). Position in `opts`, or -1 when every weight is 0.
static func _pick_option(opts: Array, rng: RandomNumberGenerator) -> int:
var total := 0
for o: Dictionary in opts:
total += maxi(0, int(o.get("weight", 1)))
if total <= 0:
return -1
var pick := rng.randi_range(0, total - 1)
for k in opts.size():
pick -= maxi(0, int((opts[k] as Dictionary).get("weight", 1)))
if pick < 0:
return k
return -1
static func _answered(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array, value: Variant, summary: String) -> void:
ctx.chain_vars["answer"] = value
if t.save_as != "":
@ -653,7 +819,7 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
step["kind"] = n["kind"]
if n.has("effects"):
step["effects"] = (n["effects"] as Array).duplicate(true)
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "case"]:
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "case", "option"]:
if n.has(k):
step[k] = n[k]
return step
@ -807,6 +973,7 @@ static func lint_pipes(board: TowerBoard) -> Array[Dictionary]:
var out: Array[Dictionary] = []
for t in board.tables:
out.append_array(lint_router(t))
out.append_array(lint_options(t))
for i in t.entries.size():
var e := t.entries[i]
var first_other := ""
@ -851,6 +1018,41 @@ static func lint_router(t: RollTable) -> Array[Dictionary]:
return out
## Problems with a card's dynamic and conditional options (empty when fine):
## a bad options_from pattern or options_where filter, a filter without
## options_from, options_from or show_if on a card that isn't a pick choice
## (they do nothing there), show_if conditions that don't parse, and a
## dynamic card with no Chosen entry.
static func lint_options(t: RollTable) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var pick := t.kind == RollTable.KIND_CHOICE and t.choice == "pick"
var from := t.options_from.strip_edges()
var where := t.options_where.strip_edges()
if from != "":
if not pick:
out.append({"table_id": t.id, "entry_id": "", "message": "Options from %s does nothing: only Which option cards take options from variables" % from})
else:
var p := RollTable.parse_options_from(from)
if str(p["error"]) != "":
out.append({"table_id": t.id, "entry_id": "", "message": "Options from %s: %s" % [from, p["error"]]})
if t.entries.is_empty():
out.append({"table_id": t.id, "entry_id": "", "message": "This card takes options from %s but has no Chosen entry" % from})
if where != "":
if from == "":
out.append({"table_id": t.id, "entry_id": "", "message": "Only where %s does nothing without Options from" % where})
elif Expr.check(where) != "":
out.append({"table_id": t.id, "entry_id": "", "message": "Only where %s: %s" % [where, Expr.check(where)]})
for e in t.entries:
var w := e.show_if.strip_edges()
if w == "":
continue
if not pick:
out.append({"table_id": t.id, "entry_id": e.id, "message": "Show only if %s does nothing: only Which option cards hide options" % w})
elif Expr.check(w) != "":
out.append({"table_id": t.id, "entry_id": e.id, "message": "Show only if %s: %s" % [w, Expr.check(w)]})
return out
static func _table_name(board: TowerBoard, id: String) -> String:
var t := board.get_table(id)
return Formatter.strip_tags(t.name) if t else id

View file

@ -33,6 +33,9 @@ var pipe_otherwise: Dictionary = {}
## Router cards: this case's condition. "" is the Otherwise case (always
## matches). Ignored on other kinds.
var when: String = ""
## Pick choices: the option is offered (in the pop-up and to Random) only when
## this expression is true when the card is reached. "" means always.
var show_if: String = ""
var has_range: bool = false
var range_lo: int = 1
var range_hi: int = 1
@ -182,6 +185,8 @@ func to_dict() -> Dictionary:
d["effects"] = effects
if when.strip_edges() != "":
d["when"] = when.strip_edges()
if show_if.strip_edges() != "":
d["show_if"] = show_if.strip_edges()
if not pipes.is_empty():
var list: Array = []
for p in pipes:
@ -217,6 +222,7 @@ static func from_dict(d: Dictionary) -> TableEntry:
e.weight = maxi(0, int(d.get("weight", 1)))
e.effects = str(d.get("effects", ""))
e.when = str(d.get("when", "")).strip_edges() if d.get("when") != null else ""
e.show_if = str(d.get("show_if", "")).strip_edges() if d.get("show_if") != null else ""
for p: Variant in d.get("pipes", []):
if p is Dictionary:
var target := str(p.get("table", ""))

View file

@ -14,6 +14,7 @@ extends RefCounted
## {@skill_*} every set variable with that prefix, sorted:
## "Gun Combat 1, Pilot 0"
## {= expr} a computed value (see Expr), e.g. {= dm(@str)}
## {@[expr]} the board variable named by expr, e.g. {@[option]}
##
## Inserted pieces are wrapped in internal url tags so the UI can show hover
## pop-ups through RichTextLabel's meta_hover_started signal:
@ -101,6 +102,12 @@ static func expand_async(text: String, ctx: RollContext, live: bool = false) ->
out += _expand_expr(text.substr(i + 2, close - i - 2), ctx)
i = close + 1
continue
if i + 2 < n and text[i + 1] == "@" and text[i + 2] == "[":
var close_b := Expr.bracket_end(text, i + 2)
if close_b > 0 and close_b + 1 < n and text[close_b + 1] == "}":
out += _indirect_var(text.substr(i + 3, close_b - i - 3), ctx)
i = close_b + 2
continue
var lm: RegExMatch = _re(_LIST_PATTERN).search(text, i)
if lm != null and lm.get_start() == i:
out += Formatter.close_open_tags(ctx.list_text(lm.get_string(1)))
@ -149,6 +156,18 @@ static func error_marker(message: String) -> String:
return "[url=error:expr]⚠ %s[/url]" % Formatter.escape_literal(message)
## {@[expr]}: the value of the board variable expr names, its unset marker,
## or an error marker for a bad expression or name.
static func _indirect_var(src: String, ctx: RollContext) -> String:
var r := Expr.evaluate(src.strip_edges(), ctx)
if r["error"] != "":
return error_marker(str(r["error"]))
var nm := Expr.indirect_name(r["value"])
if nm["error"] != "":
return error_marker(str(nm["error"]))
return _live_var("@" + str(nm["name"]), ctx)
static func _live_ref(ref: Dictionary, ctx: RollContext) -> String:
var name: String = ref["name"]
var id: String = ctx.resolve(name)

View file

@ -43,6 +43,81 @@ or ranges.
The pop-up also has **Cancel**, which stops the whole roll with a visible "Cancelled" marker.
Fast roll (Shift-click) still asks questions, because they are the player's decisions.
## 2a. Options from variables and conditional options
A `pick` card can build its options when the chain reaches it, from the board's variables,
and any option can be hidden when it doesn't apply. This covers "raise a skill you already
have", "convert one of your Contacts" or "the Officer table only when commissioned" without
a generated table per case.
### Options from variables
`options_from` (**Options: From variables** in the settings dialog) is one of:
| Pattern | Options |
|---|---|
| `@skill_*` (a prefix) | one per **set** board variable whose name starts with `skill_`, sorted by label. The label is the rest of the name, title-cased (`skill_gun_combat` → "Gun Combat"); the pop-up shows it with the value ("Gun Combat 2") |
| `@contacts` (a list variable) | one per comma-separated item, in list order. The label is the item |
`options_where` (**Only where**, optional) is an expression checked for every candidate, with
three chain variables bound: `option` (the variable name without `@`, such as `skill_pilot`,
or the list item), `option_label` ("Pilot") and `option_value` (the variable's value; for a
list, the item again). Only candidates for which it's true are offered, e.g.
`option_value >= 1` or `option != @last_contact`. An error counts as false for every
candidate and adds one red line ("Only where …: …") to the node.
**The Chosen entry.** A dynamic card's first entry is its **Chosen** entry (like the Answer
entry of a number card). Whichever dynamic option is picked:
1. `option`, `option_label` and `option_value` are set as chain variables (they last for the
rest of the roll, like `answer`);
2. `save_as`, if set, stores the label;
3. the Chosen entry happens like a rolled entry: its effects run, its text expands and its
pipes follow (with the snapshot rule of §3a).
The Chosen entry's text is the result text. Left as `Chosen` (the default) or empty, the result
reads as the option's label; otherwise it expands normally, e.g.
`Raised {option_label} to {@[option]}`. Indirect names (§4) let its effects change the picked
variable: `@[option] += 1`.
**Fixed extras.** Any entries after the Chosen entry are ordinary fixed options ("None of
these", "Learn something new"). They keep their own effects, text and pipes and never set
`option`. The pop-up lists the fixed options first (keys 1, 2, …), then the dynamic ones.
**Random.** Random picks among every offered option by weight: each dynamic option weighs as
much as the Chosen entry (1 unless changed), each fixed option its own weight (its range's
span on a ranged card). So three skills and a weight-2 "Something else" come up 20/20/20/40%,
and a fixed extra with weight 0 is offered to the player but never picked by Random. A plain
fixed card with nothing hidden rolls exactly as before (weights, ranges, card mode).
**No options.** When nothing is offered (no candidate passes and there are no visible fixed
options), the card doesn't ask: the node stops with a visible "No options available". A board
routes around that with a router or a conditional pipe before the card, e.g. a pipe
`when count(@skill_*) > 0`.
### Conditional options (`show_if`)
Any option of a `pick` card, fixed ones and the Chosen entry included, can have a `show_if`
expression (**Show only if**, edited under the option's row with the **if** toggle in Build
mode, or in the settings dialog). It's evaluated when the card is reached, before the pop-up
opens. When it's false the option isn't offered: not in the pop-up and not to Random, and it
never runs (a reply naming a hidden option counts as Random among the offered ones). A
`show_if` on the Chosen entry hides every dynamic option at once. An error counts as false and
adds a red line ("Show only if …: …"). If every option is hidden, the node stops with "No
options available", as above. `show_if` does nothing on other kinds (routers have their own
cases).
Examples: `@commissioned` (the Officer option), `@last_career != "Army"` (not the career you
just left), `@gold >= 10` (only when affordable).
### On the board and in previews
A dynamic card says "Options from @skill_* · where option_value >= 1" under its question,
and in Play mode how many options are available right now. Its first row is **Chosen**; fixed
rows are numbered from 1. Options with a condition show "only if …". The choice pop-up's
preview for a dynamic option names the variable behind it and shows the Chosen entry's effects
and pipes; a card preview (`TablePreview`) says "Options: each @skill_* that's set, where …".
## 3. Loop cards
A loop card has a `loop` mode and a `loop_expr` expression, plus two fixed entries:
@ -111,7 +186,8 @@ has no dice. Its entries are **cases**, each with an entry-level `when` expressi
settings dialog.
`Roller.lint_pipes(board)` lists problems for a board check: `when` or case conditions that
don't parse, an otherwise pipe listed before a `when` pipe on the same entry (a hint: it still
don't parse, bad `options_from` patterns, `options_where` and `show_if` expressions that don't
parse, `options_from`/`show_if` on cards where they do nothing (§2a), an otherwise pipe listed before a `when` pipe on the same entry (a hint: it still
works), an otherwise pipe on an entry with no `when` pipe (it always runs), and routers with
no cases or whose Otherwise case isn't last. Each item is `{table_id, entry_id, message}`.
@ -127,6 +203,11 @@ evaluated with Godot's `Expression`, after a small rewrite.
- **Variables:**
- `@name` reads a board variable (§5). If it's unset, it reads as `0` in arithmetic and as
`""` next to text.
- `@[expr]` reads the board variable **named by** `expr` (an indirect name), e.g.
`@[option]` or `@["skill_" + option]`. The computed name is lowercased and a leading `@`
is dropped; it must then be lowercase letters, digits and `_` (not starting with a
digit), or the expression fails with "@[…] gave "Old Bill", which isn't a variable name".
Unset reads as `0` (or `""` next to text), like `@name`.
- A bare `name` reads a chain variable (`answer`, `i`, or anything saved with `-> name`).
- **Dice:** `2d6`, `d20`, `3D`, `D3`, `2D`. A missing count means 1, and missing sides mean 6, so
`2D` is 2d6. Every die in an expression is rolled fresh.
@ -172,8 +253,14 @@ follow.
@skill_vacc_suit = max(@skill_vacc_suit, 0) gain at level 0
@traits += "Psionic"
reset @skill_*
@[option] += 1 the variable named by option (indirect)
@["skill_" + option] = max(@["skill_" + option], 0)
reset @[option]
```
An indirect target `@[expr]` is worked out when the statement runs. A bad expression or a
computed name that isn't a valid variable name is a red effect line, and nothing is written.
Each statement that runs is listed under its step in the result tray (e.g. "STR = 9"). A bad
statement shows a red marker in the tray and in Build mode rather than stopping the roll.
@ -182,6 +269,8 @@ statement shows a red marker in the tray and in Build mode rather than stopping
- `{@skill_*}` lists every set variable with that prefix, sorted, as `Gun Combat 1, Pilot 0`.
The name after the prefix is title-cased, with `_` read as a space.
- `{= expr}` shows a computed value, e.g. `STR {@str} ({= dm(@str)})`.
- `{@[expr]}` shows the variable named by `expr`, e.g. `{@[option]}`; unset shows its
`{@name?}` marker, a bad name an error marker.
- The existing `{@var|Table}`, `{hero}` and `[[refs]]` work as before.
## 6. Sheet cards
@ -195,6 +284,7 @@ step's result.
being rolled or answered, a router choosing a case, or one loop pass. Past that, the roll stops with "Stopped after
10,000 actions", and everything up to that point is kept.
- **Inline references:** `[[refs]]` inside text still nest at most 32 deep.
- **Picks:** a dynamic option counts the same single action as any pick.
- **Implementation:** pipes and loops must not use GDScript recursion proportional to chain
length. Long chains (thousands of steps) must not overflow the call stack. That applies to
the roller and to everything that walks a result (flatten, lighting, history).
@ -203,7 +293,13 @@ step's result.
- The roller is a coroutine. It `await`s `ctx.prompt.call(request)` whenever a choice card is
reached. With no prompt hook (tests, headless), `pick` chooses Random, `number` answers
`min`, and `text` answers `""`.
- **Request:** `{table_id, kind, prompt, options: [{index, text, details}], min, max, default}`.
- **Request:** `{table_id, kind, prompt, options: [{index, entry, text, details, weight}], min,
max, default, log, hidden}`. A pick's options are only the offered ones (§2a): fixed
options have `index` = `entry` = the entry's index; dynamic ones have `index` =
entries count + their position, `entry` 0 (the Chosen entry) and `dynamic`, `option`,
`label`, `value` and `value_text`. `log` holds `show_if`/`options_where` error lines and
`hidden` counts fixed options `show_if` hid. Replies must be one of the offered indices
(or -1); the UI and `BoardTester.answer()` both pick from `options`.
- **Reply:** `pick` returns an entry index or `-1` for Random. `number` returns an int.
`text` returns a String. `null` means Cancel.
- In the UI, when a prompt is needed, the steps so far appear instantly (lit on the board and
@ -217,12 +313,14 @@ step's result.
Table keys:
- `kind` (`roll` is the default and is omitted)
- `choice`, `prompt`, `save_as`, `min`, `max` (choice cards)
- `options_from`, `options_where` (pick choices with options from variables, §2a)
- `loop`, `loop_expr` (loop cards)
- `var_name`, `var_type`, `initial` (variable cards)
Entry keys:
- `effects` (String)
- `when` (String, router cases; empty or missing is Otherwise)
- `show_if` (String, pick options; empty or missing is always shown)
Pipe objects may have `"count": "<expression>"`, `"when": "<expression>"` and
`"otherwise": true` (left out when the pipe has a `when`).

View file

@ -111,7 +111,7 @@
"entries": [
{ "id": "e1", "text": "A trap snaps shut", "effects": "@hp -= 2", "range": [2, 6] },
{ "id": "e2", "text": "Dust and echoes", "range": [7, 9] },
{ "id": "e3", "text": "A glinting cache", "effects": "@gold += 2d6\n@loot += \"gem\"", "range": [10, 12] }
{ "id": "e3", "text": "A glinting cache", "effects": "@gold += 2d6\n@loot += if(1d6 <= 3, \"gem\", if(1d6 <= 3, \"silver idol\", \"old map\"))", "range": [10, 12] }
]
},
{
@ -124,7 +124,22 @@
"entries": [
{ "id": "e1", "text": "Carried up by a passing patrol", "when": "@hp <= 0", "effects": "@hp = 1", "pipes": ["report"] },
{ "id": "e2", "text": "Pockets heavy with gold", "when": "@gold >= 12", "details": "The guard at the top has noticed.", "pipes": ["way_out"] },
{ "id": "e3", "text": "Up the stairs", "pipes": ["way_out"] }
{ "id": "e3", "text": "Up the stairs", "pipes": [{ "table": "spend_find", "when": "@loot != \"\"" }, { "table": "way_out", "otherwise": true }] }
]
},
{
"id": "spend_find",
"name": "Spend a find",
"kind": "choice",
"prompt": "A shrine at the foot of the stairs. Leave one of your finds for luck?",
"options_from": "@loot",
"x": 1320,
"y": 640,
"details": "One option per item in Loot, plus two fixed ones. The last is only offered to a wounded delver.",
"entries": [
{ "id": "e1", "text": "Left the {option} at the shrine", "details": "Luck grows by one.", "effects": "@loot -= option\n@luck += 1", "pipes": ["way_out"] },
{ "id": "e2", "text": "Keep everything", "pipes": ["way_out"] },
{ "id": "e3", "text": "Trade it all for a healing draught", "show_if": "@hp <= 6", "details": "Only offered when HP is 6 or less.", "effects": "reset @loot\n@hp += 4", "pipes": ["way_out"] }
]
},
{

View file

@ -8,9 +8,11 @@ extends RefCounted
## {"format_version": 2, "id", "name", "tables": [table, ...], ["groups": [group, ...]]}
## group: id, name, x, y, w, h, [collapsed], [details], members (table ids)
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
## [deck_empty], [kind], [choice], [prompt], [save_as], [min], [max],
## [deck_empty], [kind], [choice], [prompt], [save_as], [options_from],
## [options_where], [min], [max],
## [loop], [loop_expr], [var_name], [var_type], [initial], entries
## entry: id, text, [details], [weight], [range], [effects], [when], [pipes]
## entry: id, text, [details], [weight], [range], [effects], [when], [show_if],
## [pipes]
## pipe: a table id String, or {"table": id, "count": n or "<expression>",
## "save_as": name, "when": "<expression>", "otherwise": true}
## ("otherwise" is dropped when the pipe has a "when")
@ -157,6 +159,8 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
ed["effects"] = clean.call(str(ed["effects"]))
if ed.has("when"):
ed["when"] = clean.call(str(ed["when"]))
if ed.has("show_if"):
ed["show_if"] = clean.call(str(ed["show_if"]))
if ed.has("range"):
var r: Array = ed["range"]
if int(r[0]) > int(r[1]):
@ -308,7 +312,7 @@ static func _canon_table(td: Dictionary) -> Dictionary:
var kind := str(td.get("kind", "roll"))
if RollTable.KINDS.has(kind) and kind != "roll":
t["kind"] = kind
var defaults := {"choice": "pick", "prompt": "", "save_as": "", "min": "0", "max": "99",
var defaults := {"choice": "pick", "prompt": "", "save_as": "", "options_from": "", "options_where": "", "min": "0", "max": "99",
"loop": "times", "loop_expr": "", "var_name": "", "var_type": "number", "initial": ""}
for key: String in defaults:
if not td.has(key) or td[key] == null:
@ -345,6 +349,9 @@ static func _canon_entry(ev: Variant) -> Dictionary:
var when := str(ed.get("when", "")).strip_edges() if ed.get("when") != null else ""
if when != "":
e["when"] = when
var show_if := str(ed.get("show_if", "")).strip_edges() if ed.get("show_if") != null else ""
if show_if != "":
e["show_if"] = show_if
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
var pipes: Array = []
if src_pipes is Array:

View file

@ -61,6 +61,20 @@ func _scripted(answers: Dictionary, log: Array) -> Callable:
return a
## When the open question is the demo's optional "Spend a find" (asked only
## when the delver found loot), answers "Keep everything" and returns the
## next question; otherwise returns `d` unchanged.
func _past_spend(d: ChoiceDialog) -> ChoiceDialog:
if d == null or str(d.request.get("table_id", "")) != "spend_find":
return d
for o: Dictionary in d.request["options"]:
if Formatter.strip_tags(str(o["text"])) == "Keep everything":
d.answer(int(o["index"]))
break
await process_frame
return main.pending_choice()
func _var(name: String) -> Variant:
var v: Variant = main.persistent_vars.get(name)
return (v as Dictionary).get("value") if v is Dictionary else null
@ -167,7 +181,7 @@ func _test_dialog_answers() -> void:
d._spin.value = 2
d._confirm()
await process_frame
d = main.pending_choice()
d = await _past_spend(main.pending_choice())
_check(d != null and d.kind == "pick" and d._options.size() == 3, "then the pick pop-up with three options")
if d == null:
return
@ -259,7 +273,7 @@ func _test_keys() -> void:
le.text_submitted.emit(le.text)
await process_frame
_eq(_var("rooms"), 4, "a typed number is used")
d = main.pending_choice()
d = await _past_spend(main.pending_choice())
_check(d != null and d.kind == "pick", "pick pop-up for the key test")
if d == null:
return

608
tests/test_options.gd Normal file
View file

@ -0,0 +1,608 @@
extends SceneTree
## Headless checks for dynamic pick options (options_from / options_where),
## conditional options (show_if) and indirect variable names (@[expr]), as in
## docs/LOGIC.md §2a: candidates, labels and values, fixed extras, Random,
## "No options available", the file format, lint, a small "raise a skill you
## already have" board and the choice pop-up's rendering.
## Run: godot --headless --path . -s res://tests/test_options.gd -- --sample
var _failures := 0
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_prefix_options()
_test_list_options()
_test_fixed_and_dynamic()
_test_random_distribution()
_test_no_options()
_test_show_if()
_test_indirect()
_test_json()
_test_lint()
await _test_raise_skill_board()
await _test_tester()
await _test_dialog()
_test_settings()
await _test_card()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
# ---------------------------------------------------------------- helpers
func _rng(seed_value: int = 1) -> RandomNumberGenerator:
var r := RandomNumberGenerator.new()
r.seed = seed_value
return r
func _board(tables: Array) -> TowerBoard:
var b := TowerBoard.new()
b.id = "options-test"
for t in tables:
b.tables.append(t)
return b
## Board variables as stored: name -> {value, source}.
func _vars(d: Dictionary) -> Dictionary:
var out := {}
for k: String in d:
out[k] = {"value": d[k], "source": ""}
return out
func _var(vars: Dictionary, name: String) -> Variant:
var v: Variant = vars.get(name)
return (v as Dictionary).get("value") if v is Dictionary else null
## A dynamic pick card: entries[0] is the Chosen entry.
func _dyn(id: String, from: String, where: String = "", effects: String = "", text: String = "Chosen") -> RollTable:
var t := RollTable.create(RollTable.KIND_CHOICE, id, id.capitalize(), "pick")
t.entries.clear()
var e := TableEntry.new("chosen", text)
e.effects = effects
t.entries.append(e)
t.options_from = from
t.options_where = where
return t
func _ctx(b: TowerBoard, vars: Dictionary, seed_value: int = 1) -> RollContext:
return Roller.new_context(b, _rng(seed_value), vars)
func _texts_of(req: Dictionary) -> Array:
var out := []
for o: Dictionary in req["options"]:
out.append(Formatter.strip_tags(str(o["text"])))
return out
## Replies with the option whose plain text is `want` (or Cancel when none).
func _answer_text(want: String) -> Callable:
return func(req: Dictionary) -> Variant:
for o: Dictionary in req["options"]:
if Formatter.strip_tags(str(o["text"])) == want:
return int(o["index"])
return null
func _errors(tree: Dictionary) -> Array:
var out := []
for s: Dictionary in Roller.flatten(tree):
for fx: Dictionary in s.get("effects", []):
if fx.get("error", false):
out.append(str(fx["text"]))
return out
# ---------------------------------------------------------------- options_from
func _test_prefix_options() -> void:
var t := _dyn("raise", "@skill_*", "option_value >= 1")
var b := _board([t])
var vars := _vars({"skill_pilot": 1, "skill_gun_combat": 2, "skill_admin": 0, "str": 7})
var ctx := _ctx(b, vars)
var req := Roller.request_for(t, ctx)
_check(_texts_of(req) == ["Gun Combat 2", "Pilot 1"], "prefix options are filtered, sorted and show their values (%s)" % [_texts_of(req)])
var o: Dictionary = req["options"][1]
_check(str(o["option"]) == "skill_pilot" and str(o["label"]) == "Pilot" and int(o["value"]) == 1, "an option carries its variable name, label and value")
_check(int(o["entry"]) == 0 and o.get("dynamic", false), "a dynamic option maps to the Chosen entry")
_check(int(o["index"]) >= t.entries.size(), "a dynamic option's index is past the entries")
_check(not ctx.chain_vars.has("option"), "the filter's bindings don't leak")
# Without the filter, Admin 0 is there too.
t.options_where = ""
_check(_texts_of(Roller.request_for(t, ctx)) == ["Admin 0", "Gun Combat 2", "Pilot 1"], "without a filter every set variable is an option")
# Picking one sets the chain variables and save_as gets the label.
t.options_where = "option_value >= 1"
t.save_as = "@raised"
t.entries[0].effects = "@picked_name = option\n@picked_value = option_value"
ctx = _ctx(b, vars)
ctx.prompt = _answer_text("Pilot 1")
var tree: Dictionary = await Roller.roll_async(b, "raise", ctx)
_check(tree.get("picked", false) and str(tree["option"]) == "Pilot", "the picked node records the option's label")
_check(str(ctx.chain_vars.get("option")) == "skill_pilot" and str(ctx.chain_vars.get("option_label")) == "Pilot" \
and int(ctx.chain_vars.get("option_value")) == 1, "option, option_label and option_value are set")
_check(str(_var(vars, "raised")) == "Pilot", "save_as stores the label")
_check(str(_var(vars, "picked_name")) == "skill_pilot" and int(_var(vars, "picked_value")) == 1, "the Chosen entry's effects see the option")
_check(Formatter.strip_tags(str(tree["summary"])) == "Pilot", "a Chosen entry with its default text reads as the label")
var step: Dictionary = Roller.flatten(tree)[0]
_check(str(step.get("option", "")) == "Pilot" and str(step["entry_id"]) == "chosen", "the step keeps the option and the Chosen entry")
# Text of its own expands with the chain variables.
t.entries[0].text = "Trained {option_label} ({option_value})"
ctx = _ctx(b, vars)
ctx.prompt = _answer_text("Gun Combat 2")
tree = await Roller.roll_async(b, "raise", ctx)
_check(Formatter.strip_tags(str(tree["summary"])) == "Trained Gun Combat (2)", "the Chosen entry's own text expands (%s)" % tree["summary"])
func _test_list_options() -> void:
var t := _dyn("convert", "@contacts", "option != \"Rex\"", "@contacts -= option\n@allies += option")
var b := _board([t])
var vars := _vars({"contacts": "Ana, Rex, Old Bill"})
var ctx := _ctx(b, vars)
var req := Roller.request_for(t, ctx)
_check(_texts_of(req) == ["Ana", "Old Bill"], "list options keep list order and pass the filter (%s)" % [_texts_of(req)])
_check(str(req["options"][1]["option"]) == "Old Bill" and str(req["options"][1]["value_text"]) == "", "a list item is its own option, with no value shown")
ctx.prompt = _answer_text("Old Bill")
await Roller.roll_async(b, "convert", ctx)
_check(str(_var(vars, "contacts")) == "Ana, Rex" and str(_var(vars, "allies")) == "Old Bill", "the Chosen entry moves the picked item")
# An unset list has no candidates.
_check(Roller.dynamic_options(t, _ctx(b, {})).is_empty(), "an unset list gives no options")
func _test_fixed_and_dynamic() -> void:
var t := _dyn("spend", "@loot", "", "@loot -= option")
var none := TableEntry.new("none", "Keep everything")
none.effects = "@kept = 1"
t.entries.append(none)
var b := _board([t])
var vars := _vars({"loot": "gem, map"})
var ctx := _ctx(b, vars)
var req := Roller.request_for(t, ctx)
_check(_texts_of(req) == ["Keep everything", "gem", "map"], "fixed options come first, then the dynamic ones")
_check(int(req["options"][0]["index"]) == 1 and int(req["options"][0]["entry"]) == 1, "a fixed option's index is its entry")
ctx.prompt = _answer_text("Keep everything")
var tree: Dictionary = await Roller.roll_async(b, "spend", ctx)
_check(int(tree["index"]) == 1 and not tree.has("option") and int(_var(vars, "kept")) == 1, "a fixed option runs its own entry")
_check(str(_var(vars, "loot")) == "gem, map", "the Chosen entry didn't run")
ctx = _ctx(b, vars)
ctx.prompt = _answer_text("map")
tree = await Roller.roll_async(b, "spend", ctx)
_check(int(tree["index"]) == 0 and str(_var(vars, "loot")) == "gem", "a dynamic option runs the Chosen entry")
func _test_random_distribution() -> void:
var t := _dyn("pick3", "@skill_*")
var fixed := TableEntry.new("f", "Something else")
fixed.weight = 2
t.entries.append(fixed)
var b := _board([t])
var vars := _vars({"skill_a": 1, "skill_b": 1, "skill_c": 1})
var counts := {}
var ctx := _ctx(b, vars, 3)
for k in 5000:
var tree := Roller.roll(b, "pick3", ctx.rng, 0, {}, ctx)
var key := str(tree.get("option", "fixed"))
counts[key] = int(counts.get(key, 0)) + 1
# Weights: A, B, C 1 each (the Chosen entry's weight), fixed 2: 20/20/20/40%.
var ok := true
for key in ["A", "B", "C"]:
ok = ok and absf(float(counts.get(key, 0)) / 5000.0 - 0.2) < 0.03
ok = ok and absf(float(counts.get("fixed", 0)) / 5000.0 - 0.4) < 0.03
_check(ok, "Random weighs each dynamic option as the Chosen entry and fixed ones by weight (%s)" % [counts])
# A fixed extra with weight 0 is never chosen by Random.
fixed.weight = 0
var seen_fixed := false
for k in 300:
var tree2 := Roller.roll(b, "pick3", ctx.rng, 0, {}, ctx)
seen_fixed = seen_fixed or not tree2.has("option")
_check(not seen_fixed, "weight 0 keeps a fixed extra out of Random")
# The headless tester's answers map to real options.
var req := Roller.request_for(t, ctx)
var valid := {-1: true}
for o: Dictionary in req["options"]:
valid[int(o["index"])] = true
var all_ok := true
var r := _rng(9)
for k in 200:
all_ok = all_ok and valid.has(BoardTester.answer(req, r))
_check(all_ok, "BoardTester.answer() only replies with offered indices")
func _test_no_options() -> void:
var t := _dyn("raise", "@skill_*", "option_value >= 1")
var b := _board([t])
var tree := Roller.roll(b, "raise", _rng(), 0, {}, _ctx(b, _vars({"skill_x": 0})))
_check(str(tree.get("stop", "")) == Roller.NO_OPTIONS and str(tree.get("kind", "")) == RollTable.KIND_CHOICE, "nothing matching stops with \"No options available\"")
# A prompt is never shown for it.
var asked := [false]
var ctx := _ctx(b, {})
ctx.prompt = func(_req: Dictionary) -> Variant:
asked[0] = true
return -1
tree = await Roller.roll_async(b, "raise", ctx)
_check(not asked[0] and str(tree.get("stop", "")) == Roller.NO_OPTIONS, "no pop-up opens when there is nothing to choose")
# A filter error counts as false and is logged.
t.options_where = "option_value >= "
tree = Roller.roll(b, "raise", _rng(), 0, {}, _ctx(b, _vars({"skill_x": 3})))
_check(str(tree.get("stop", "")) == Roller.NO_OPTIONS and _errors(tree).size() == 1 and str(_errors(tree)[0]).begins_with("Only where"), "a bad filter hides everything with one error line")
func _test_show_if() -> void:
var t := RollTable.create(RollTable.KIND_CHOICE, "career", "Career", "pick")
t.entries.clear()
var army := TableEntry.new("army", "Army")
army.show_if = "@last_career != \"Army\""
var officer := TableEntry.new("officer", "Officer")
officer.show_if = "@commissioned"
officer.effects = "@ran = 1"
var drifter := TableEntry.new("drifter", "Drifter")
t.entries.append_array([army, officer, drifter] as Array[TableEntry])
var b := _board([t])
var vars := _vars({"last_career": "Army"})
var req := Roller.request_for(t, _ctx(b, vars))
_check(_texts_of(req) == ["Drifter"] and int(req["hidden"]) == 2, "show_if hides options that don't apply")
vars = _vars({"commissioned": 1})
_check(_texts_of(Roller.request_for(t, _ctx(b, vars))) == ["Army", "Officer", "Drifter"], "true conditions show their options")
# Random never picks a hidden option, and a hidden option never runs.
vars = _vars({"last_career": "Army"})
var ctx := _ctx(b, vars)
var only_drifter := true
for k in 200:
var tree := Roller.roll(b, "career", ctx.rng, 0, {}, ctx)
only_drifter = only_drifter and str(tree["entry"].id) == "drifter"
_check(only_drifter and _var(vars, "ran") == null, "Random only picks shown options; hidden ones never run")
# A stale reply for a hidden option is treated as Random among the shown ones.
ctx = _ctx(b, vars)
ctx.prompt = func(_r: Dictionary) -> Variant: return 1
var t2: Dictionary = await Roller.roll_async(b, "career", ctx)
_check(str(t2["entry"].id) == "drifter" and _var(vars, "ran") == null, "a reply naming a hidden option can't run it")
# Errors count as false with an error line; all hidden -> no options.
drifter.show_if = "@x >"
var tree3 := Roller.roll(b, "career", _rng(), 0, {}, _ctx(b, vars))
_check(str(tree3.get("stop", "")) == Roller.NO_OPTIONS, "every option hidden: \"No options available\"")
_check(_errors(tree3).size() == 1 and str(_errors(tree3)[0]).begins_with("Show only if"), "a bad show_if is an error line")
drifter.show_if = ""
# show_if on the Chosen entry hides all the dynamic options.
var d := _dyn("d", "@skill_*")
d.entries[0].show_if = "@allowed"
var fixed := TableEntry.new("f", "Fixed")
d.entries.append(fixed)
var b2 := _board([d])
_check(_texts_of(Roller.request_for(d, _ctx(b2, _vars({"skill_a": 1})))) == ["Fixed"], "show_if on the Chosen entry hides the dynamic options")
_check(Roller.available_count(d, _ctx(b2, _vars({"skill_a": 1, "allowed": 1}))) == 2, "available_count counts what's offered")
# ---------------------------------------------------------------- @[expr]
func _test_indirect() -> void:
var b := _board([])
var vars := _vars({"skill_pilot": 2, "which": "skill_pilot", "name": "Ana"})
var ctx := _ctx(b, vars)
ctx.chain_vars["option"] = "skill_pilot"
var r := Expr.evaluate("@[option] + 1", ctx)
_check(r["error"] == "" and int(r["value"]) == 3, "@[option] reads the variable it names")
r = Expr.evaluate("@[\"skill_\" + \"pilot\"] * 2", ctx)
_check(r["error"] == "" and int(r["value"]) == 4, "@[\"skill_\" + …] builds the name")
r = Expr.evaluate("@[@which]", ctx)
_check(r["error"] == "" and int(r["value"]) == 2, "@[@var] reads a name from a variable")
r = Expr.evaluate("@[\"skill_none\"] + 1", ctx)
_check(r["error"] == "" and int(r["value"]) == 1, "an unset indirect variable reads as 0")
r = Expr.evaluate("\"x\" + @[\"nothing\"]", ctx)
_check(r["error"] == "" and str(r["value"]) == "x", "an unset indirect variable beside text reads as \"\"")
r = Expr.evaluate("max(@[option], 5)", ctx)
_check(r["error"] == "" and int(r["value"]) == 5, "@[…] works inside function calls")
r = Expr.evaluate("[1, 2][1] + @[option]", ctx)
_check(r["error"] == "" and int(r["value"]) == 4, "plain brackets still work beside @[…]")
r = Expr.evaluate("@[\"Old Bill\"]", ctx)
_check(r["error"] != "" and str(r["error"]).contains("isn't a variable name"), "a bad computed name is an error, not a crash")
_check(Expr.check("@[option") != "", "Expr.check catches a missing ]")
_check(Expr.check("@[option] >= 1") == "", "Expr.check accepts @[…]")
# Effects: write, add, max and reset.
var log := Effects.run("@[option] += 1\n@[\"skill_\" + \"vacc_suit\"] = max(@[\"skill_vacc_suit\"], 0)", ctx, "t")
_check(int(_var(vars, "skill_pilot")) == 3 and int(_var(vars, "skill_vacc_suit")) == 0, "indirect effects write the named variables (%s)" % [Effects.log_text(log)])
_check(str(log[0]["text"]).begins_with("Skill Pilot"), "the effect log names the real variable")
Effects.run("reset @[option]", ctx, "t")
_check(_var(vars, "skill_pilot") == null, "reset @[option] resets the named variable")
ctx.chain_vars["option"] = "Old Bill"
log = Effects.run("@[option] += 1", ctx, "t")
_check(log.size() == 1 and log[0].get("error", false) and str(log[0]["text"]).contains("isn't a variable name"), "a bad computed name is an effect error")
_check(not vars.has("old bill") and not vars.has(""), "nothing is written for a bad name")
_check(Effects.validate("@[option] += 1\nreset @[option]").is_empty(), "Effects.validate accepts indirect statements")
_check(Effects.validate("@[option += 1").size() == 1, "Effects.validate catches a missing ]")
_check(Effects.validate("@[option +] = 1").size() == 1, "Effects.validate checks the name expression")
_check(Effects.validate("@[option] == 1").size() == 1, "== isn't an assignment")
# Text.
ctx.chain_vars["option"] = "name"
var ex := TextExpander.expand("Hi {@[option]}, {@[\"skill_x\"]} {@[\"Bad Name\"]}", ctx)
var plain := Formatter.strip_tags(str(ex["text"]))
_check(plain.begins_with("Hi Ana, {@skill_x?}") and plain.contains("isn't a variable name"), "{@[…]} shows the value, the unset marker or an error marker (%s)" % plain)
_check(Formatter.strip_tags(TextExpander.render("{@[option]}", ctx)) == "Ana", "{@[…]} renders live too")
# ---------------------------------------------------------------- file format and lint
func _test_json() -> void:
var t := _dyn("raise", "@skill_*", "option_value >= 1", "@[option] += 1")
var extra := TableEntry.new("none", "None of these")
extra.show_if = "@terms > 2"
t.entries.append(extra)
var d := t.to_dict()
_check(str(d.get("options_from", "")) == "@skill_*" and str(d.get("options_where", "")) == "option_value >= 1", "to_dict writes options_from and options_where")
_check(str((d["entries"][1] as Dictionary).get("show_if", "")) == "@terms > 2", "to_dict writes show_if")
_check(not (d["entries"][0] as Dictionary).has("show_if"), "an empty show_if is left out")
var back := RollTable.from_dict(d)
_check(back.options_from == "@skill_*" and back.options_where == "option_value >= 1" and back.entries[1].show_if == "@terms > 2", "from_dict reads them back")
var plain := RollTable.create(RollTable.KIND_CHOICE, "p", "P", "pick").to_dict()
_check(not plain.has("options_from") and not plain.has("options_where"), "a fixed pick card has no options keys")
var col := {"format_version": 2, "id": "c", "name": "C", "tables": [d]}
var res := JsonIO.import_json(JsonIO.export_json(col))
_check(res["ok"], "the collection imports")
var td: Dictionary = (res["collection"]["tables"] as Array)[0]
_check(str(td.get("options_from", "")) == "@skill_*" and str(td.get("options_where", "")) == "option_value >= 1" \
and str((td["entries"][1] as Dictionary).get("show_if", "")) == "@terms > 2", "export and import keep them")
var canon := JsonIO.canonical({"tables": [{"id": "x", "name": "X", "kind": "choice", "options_from": "", "entries": [{"text": "a", "show_if": ""}]}]})
var ct: Dictionary = (canon["tables"] as Array)[0]
_check(not ct.has("options_from") and not (ct["entries"][0] as Dictionary).has("show_if"), "canonical drops empty keys")
func _test_lint() -> void:
var bad := _dyn("bad", "skill_*", "option_value >=")
var bad2 := _dyn("bad2", "@Skill Name*")
var where_only := RollTable.create(RollTable.KIND_CHOICE, "w", "W", "pick")
where_only.options_where = "option_value > 1"
where_only.entries[1].show_if = "@x >"
var num := RollTable.create(RollTable.KIND_CHOICE, "n", "N", "number")
num.options_from = "@skill_*"
var good := _dyn("good", "@skill_*", "option_value >= 1")
good.entries[0].show_if = "@ok"
var b := _board([bad, bad2, where_only, num, good])
var msgs := {}
for item: Dictionary in Roller.lint_pipes(b):
var tid := str(item["table_id"])
if not msgs.has(tid):
msgs[tid] = []
(msgs[tid] as Array).append(str(item["message"]))
_check(msgs.has("bad") and (msgs["bad"] as Array).size() == 2, "a pattern without @ and a bad filter are flagged (%s)" % [msgs.get("bad")])
_check(msgs.has("bad2"), "a pattern that isn't a variable name is flagged")
_check(msgs.has("w") and (msgs["w"] as Array).size() == 2, "a filter without options_from and a bad show_if are flagged")
_check(msgs.has("n"), "options_from on a number card is flagged")
_check(not msgs.has("good"), "a good dynamic card is clean")
var problems := BoardTester.static_checks(b)
var seen := false
for p: Dictionary in problems:
seen = seen or (str(p["table_id"]) == "bad" and str(p["text"]).begins_with("Only where"))
_check(seen, "BoardTester's static checks include them")
# ---------------------------------------------------------------- a mini board
## "Raise a skill you already have": start -> raise (options from @skill_*
## where option_value >= 1, plus "Learn something new" when nothing is high
## enough... shown only if no skill is at 1+) -> sheet.
func _test_raise_skill_board() -> void:
var start := RollTable.new("start", "Start")
var se := TableEntry.new("e1", "Training")
se.effects = "@skill_pilot = 1\n@skill_admin = 0\n@skill_gun_combat = 2"
se.add_pipe("raise")
start.entries.append(se)
var raise := _dyn("raise", "@skill_*", "option_value >= 1", "@[option] += 1", "Raised {option_label} to {@[option]}")
raise.prompt = "Raise a skill you already have"
var fresh := TableEntry.new("fresh", "Learn Admin")
fresh.show_if = "count(@skill_*) = 0"
fresh.effects = "@skill_admin = 1"
raise.entries.append(fresh)
raise.entries[0].add_pipe("sheet")
var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Sheet")
sheet.entries[0].text = "Skills: {@skill_*}"
var b := _board([start, raise, sheet])
var vars := {}
var ctx := _ctx(b, vars)
var asked: Array = []
ctx.prompt = func(req: Dictionary) -> Variant:
asked.append(_texts_of(req))
for o: Dictionary in req["options"]:
if str(o.get("option", "")) == "skill_gun_combat":
return int(o["index"])
return -1
var tree: Dictionary = await Roller.roll_async(b, "start", ctx)
_check(asked.size() == 1 and asked[0] == ["Gun Combat 2", "Pilot 1"], "only skills already at 1+ are offered (%s)" % [asked])
_check(int(_var(vars, "skill_gun_combat")) == 3 and int(_var(vars, "skill_pilot")) == 1, "the picked skill went up by one")
var steps := Roller.flatten(tree)
_check(steps.size() == 3 and Formatter.strip_tags(str(steps[1]["text"])) == "Raised Gun Combat to 3", "the result text names the skill and its new level (%s)" % [steps[1]["text"] if steps.size() > 1 else ""])
_check(Formatter.strip_tags(str(Roller.last_sheet(tree).get("summary", ""))) == "Skills: Admin 0, Gun Combat 3, Pilot 1", "the sheet shows the raised skill")
_check(_errors(tree).is_empty(), "no errors")
## The simulator on a dynamic board: no errors, and the Chosen entry counts as
## chosen.
func _test_tester() -> void:
var start := RollTable.new("start", "Start")
var se := TableEntry.new("e1", "Go")
se.effects = "@loot = \"gem, map, idol\""
se.add_pipe("spend")
start.entries.append(se)
var spend := _dyn("spend", "@loot", "", "@loot -= option")
spend.entries.append(TableEntry.new("keep", "Keep it all"))
var b := _board([start, spend])
var report: Dictionary = await BoardTester.simulate(b, "start", {"runs": 100, "seed": 4})
_check(BoardTester.is_clean(report), "the simulator runs a dynamic board cleanly")
_check(not (report["unchosen"] as Dictionary).has("spend"), "both the Chosen entry and the fixed extra get chosen")
# ---------------------------------------------------------------- the pop-up
func _test_dialog() -> void:
var t := _dyn("raise", "@skill_*", "", "@[option] += 1")
t.prompt = "Raise which skill?"
t.entries[0].details = "Goes up by one"
t.entries[0].add_pipe("next")
var none := TableEntry.new("none", "None of these")
t.entries.append(none)
var next := RollTable.new("next", "Next step")
next.entries.append(TableEntry.new("e1", "Onwards"))
var b := _board([t, next])
var vars := _vars({"skill_pilot": 1, "skill_gun_combat": 2})
var req := Roller.request_for(t, _ctx(b, vars))
var d := ChoiceDialog.new(req)
d.board = b
d.vars = vars
root.add_child(d)
await process_frame
_check(d._options.size() == 3, "the pop-up lists the fixed option and both dynamic ones")
var texts0 := _texts(d._options[0])
var texts1 := _texts(d._options[1])
_check(texts0.has("1") and _joined(texts0).contains("None of these"), "the fixed option comes first, on key 1")
_check(texts1.has("2") and _joined(texts1).contains("Gun Combat") and texts1.has("2"), "a dynamic option shows its label and value")
var badge := false
for c in _all(d._options[2]):
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 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")
p.free()
# Key 3 answers the third option (Pilot).
var got := [null]
d.reply.done.connect(func(v: Variant) -> void: got[0] = v)
var ev := InputEventKey.new()
ev.keycode = KEY_3
ev.pressed = true
d._input(ev)
_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")
_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")
_check(_has(tp, "only if @terms > 2"), "the preview shows show_if conditions")
tp.free()
# ---------------------------------------------------------------- settings and card
func _test_settings() -> void:
var t := RollTable.create(RollTable.KIND_CHOICE, "c", "C", "pick")
var keep := TableEntry.new("keep", "None of these")
t.entries.append(keep)
var s := {"choice": "pick", "options_mode": "vars", "options_from": "@skill_*", "options_where": "option_value >= 1",
"show_if": {"keep": "@terms > 1"}}
var r := TableSettingsDialog.apply_settings(t, s)
_check(r["ok"] and t.is_dynamic(), "From variables makes the card dynamic")
_check(t.entries.size() == 2 and t.entries[0].text == Roller.CHOSEN and t.entries[1].id == "keep", "a Chosen entry comes first; default options go, others stay as extras")
_check(t.options_where == "option_value >= 1" and keep.show_if == "@terms > 1", "the filter and show_if are applied")
var bad := s.duplicate(true)
bad["options_from"] = "skill"
bad["show_if"] = {"keep": "@x >"}
var probs := TableSettingsDialog.kind_problems(t, bad)
_check(probs.size() == 2, "a bad pattern and a bad show_if are refused (%s)" % [probs])
bad = s.duplicate(true)
bad["options_from"] = ""
_check(not TableSettingsDialog.apply_settings(t, bad)["ok"], "From variables needs a pattern")
# Back to a fixed list: the unused Chosen entry goes.
r = TableSettingsDialog.apply_settings(t, {"choice": "pick", "options_mode": "fixed"})
_check(r["ok"] and not t.is_dynamic() and t.entries.size() == 1 and t.entries[0].id == "keep", "a fixed list drops the unused Chosen entry")
# A Chosen entry that does something stays as an option.
TableSettingsDialog.apply_settings(t, s)
t.entries[0].effects = "@[option] += 1"
TableSettingsDialog.apply_settings(t, {"choice": "pick", "options_mode": "fixed"})
_check(t.entries.size() == 2 and t.entries[0].effects != "", "a Chosen entry with effects is kept as an option")
func _test_card() -> void:
var main: Main = load("res://ui/main.tscn").instantiate()
root.add_child(main)
for i in 5:
await process_frame
if main._saving_enabled:
_check(false, "saving must be off for the card test")
return
var t := _dyn("raise_card", "@skill_*", "option_value >= 1", "@[option] += 1")
t.prompt = "Raise which skill?"
var extra := TableEntry.new("none", "None of these")
extra.show_if = "@terms > 2"
t.entries.append(extra)
t.position = Vector2(40, 2000)
main.data.tables.append(t)
main.persistent_vars["skill_pilot"] = {"value": 1, "source": ""}
main.persistent_vars["skill_admin"] = {"value": 0, "source": ""}
main._rebuild_cards()
await process_frame
var card := main.card_for("raise_card")
_check(card != null and _has(card, "Options from @skill_* · where option_value >= 1"), "the card says where its options come from")
_check(_has(card, "1 option available now"), "in Play it counts the options available now")
_check(_has(card, "only if @terms > 2"), "a show_if option shows its condition")
_check(_has(card, "Chosen"), "the card has a Chosen row")
main.set_mode(Main.Mode.BUILD)
await process_frame
card = main.card_for("raise_card")
card._open_show_if["none"] = true
card.rebuild()
_check(_has(card, "Show only if"), "Build mode edits show_if under the option")
var d := TableSettingsDialog.new(t)
main.add_child(d)
await process_frame
_check(_has_ci(d, "Options from (@prefix_* or a @list)") and _has_ci(d, "Show only if") and _has_ci(d, "From variables (+ fixed extras)"), "the settings dialog has the options fields")
_check(d._options_box.visible and d._opt_from.text == "@skill_*", "From variables is selected with its pattern")
d._opt_where.text = "option_value >="
d._refresh()
_check(d._kind_problem.visible, "a bad filter is flagged live")
d.queue_free()
main.set_mode(Main.Mode.PLAY)
main.queue_free()
await process_frame
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))
for c in n.get_children():
_texts(c, out)
return out
func _joined(a: PackedStringArray) -> String:
return " | ".join(a)
func _all(n: Node, out: Array = []) -> Array:
out.append(n)
for c in n.get_children():
_all(c, out)
return out
func _has_ci(n: Node, needle: String) -> bool:
for s in _texts(n):
if s.to_lower().contains(needle.to_lower()):
return true
for c in _all(n):
if c is Button and (c as Button).text.to_lower().contains(needle.to_lower()):
return true
return false
func _has(n: Node, needle: String) -> bool:
for s in _texts(n):
if s.contains(needle):
return true
return false
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)

View file

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

655
tests/test_undo.gd Normal file
View file

@ -0,0 +1,655 @@
extends SceneTree
## Undo and redo of Build edits (EditHistory and Main's "Undo and redo"):
## every kind of edit, coalescing, redo being cleared, the cap, per-collection
## histories, labels, view and lit state, the toast's Undo, lazily built cards,
## the shortcuts and buttons, and the snapshot cost on a big board.
## Run: godot --headless --path . -s res://tests/test_undo.gd -- --sample
## [--big-board=<collection.json>] times a real board instead of a made-up
## 800-card one.
var _failures := 0
var main: Main
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_history_unit()
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)
await _load()
await _test_typing()
await _test_card_fields()
await _test_results_and_tables()
await _test_pipes()
await _test_drag()
await _test_groups()
await _test_template_and_reset()
await _test_pack()
await _test_redo_cleared()
await _test_view_kept()
await _test_toast()
await _test_lazy_cards()
await _test_collapse_not_undoable()
await _test_shortcuts_and_buttons()
await _test_play_mode()
await _test_collections()
await _test_big_board()
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)
## Loot (two results, one piping to Gems), Gems, Weapons and Armor in the
## group Careers, far to the right.
func _board_dict() -> Dictionary:
return {"format_version": 2, "id": "undo-test", "name": "Undo test", "tables": [
{"id": "a", "name": "Loot", "x": 40, "y": 60, "entries": [
{"id": "e1", "text": "Gold", "pipes": ["b"]},
{"id": "e2", "text": "Silver"}]},
{"id": "b", "name": "Gems", "x": 400, "y": 60, "entries": [{"id": "e1", "text": "Ruby"}]},
{"id": "c", "name": "Weapons", "x": 1500, "y": 90, "entries": [{"id": "e1", "text": "Sword"}]},
{"id": "d", "name": "Armor", "x": 1860, "y": 90, "entries": [{"id": "e1", "text": "Mail"}]},
], "groups": [
{"id": "g1", "name": "Careers", "x": 1478, "y": 22, "w": 700, "h": 300, "members": ["c", "d"]},
]}
func _load(d: Dictionary = {}) -> void:
main.data.load_dict(d if not d.is_empty() else _board_dict())
main.lit_entries.clear()
main.lit_pipes.clear()
main.lit_texts.clear()
main._rebuild_cards()
for i in 4:
await process_frame
func _frames(n: int = 2) -> void:
for i in n:
await process_frame
func _t(id: String) -> RollTable:
return main.data.get_table(id)
func _label() -> String:
return main.edits.undo_label()
func _steps() -> int:
return main.edits.undo_stack.size()
func _line_edit_with(n: Node, text: String) -> LineEdit:
for c in n.get_children():
if c is LineEdit and (c as LineEdit).text == text:
return c
var r := _line_edit_with(c, text)
if r:
return r
return null
# ---------- EditHistory on its own ----------
func _test_history_unit() -> void:
print("EditHistory")
var b := TowerBoard.new()
b.load_dict(_board_dict())
var h := EditHistory.new(b)
_check(not h.can_undo() and not h.can_redo(), "a new history is empty")
b.get_table("a").collapsed = true
_check(not h.commit(b)["step"], "collapsing alone isn't a step")
b.get_table("a").entries[0].text = "Platinum"
var r := h.commit(b)
_check(r["step"] and h.undo_label() == "Edit Loot", "an edit is a step named from the diff: %s" % h.undo_label())
b.get_table("b").name = "Jewels"
h.commit(b, "", 0, 100.0)
_check(h.undo_label() == "Rename Gems → Jewels", "a rename: %s" % h.undo_label())
var later := int(h.undo_stack.back()["snap"]["bytes"])
var full := EditHistory.full_bytes(h.cache)
_check(later < full / 2, "a later snapshot shares the unchanged cards' text: %d of %d" % [later, full])
var e := h.pop_undo()
h.cache = EditHistory.restore(b, e["snap"])
_check(b.get_table("b").name == "Gems" and h.can_redo() and h.redo_label() == "Rename Gems → Jewels", "undo restores the name and offers redo")
_check(b.get_table("a").collapsed, "restoring keeps a table collapsed as it is now")
# The cap.
var h2 := EditHistory.new(b)
for i in EditHistory.MAX_STEPS + 50:
b.get_table("a").entries[1].weight = i + 2
h2.commit(b, "", 0, float(i) * 10.0)
_check(h2.undo_stack.size() == EditHistory.MAX_STEPS, "the history keeps at most %d steps: %d" % [EditHistory.MAX_STEPS, h2.undo_stack.size()])
_check(h2.bytes() < EditHistory.MAX_BYTES, "and stays within its memory budget: %d bytes" % h2.bytes())
# Same-thing edits close together merge; different things don't.
var h3 := EditHistory.new(b)
b.get_table("a").entries[1].weight = 5
h3.commit(b, "", 0, 1000.0)
b.get_table("a").entries[1].weight = 6
h3.commit(b, "", 0, 1000.3)
_check(h3.undo_stack.size() == 1, "two quick edits to one card are one step")
b.get_table("b").entries[0].text = "Opal"
h3.commit(b, "", 0, 1000.5)
_check(h3.undo_stack.size() == 2, "an edit to another card is a new step")
b.get_table("b").entries[0].text = "Ruby"
h3.commit(b, "", 0, 1000.6)
_check(h3.undo_stack.size() == 1, "typing something and putting it back leaves no step")
# ---------- Edits through the app ----------
func _test_typing() -> void:
print("Typing coalesces")
var card := main.card_for("a")
var le := _line_edit_with(card, "Loot")
_check(le != null, "the card has a name field")
if le == null:
return
le.grab_focus()
var s := "Loot"
for ch in " of the deep":
s += ch
le.text = s
le.text_changed.emit(s)
_check(not main.edits.can_undo() and main.can_undo(), "while typing nothing is committed yet, but Undo is offered")
await create_timer(Main.EDIT_PAUSE + 0.3).timeout
_check(_steps() == 1 and _label() == "Rename Loot → Loot of the deep", "a pause commits the typing as one step: %d, %s" % [_steps(), _label()])
for ch in "!!":
s += ch
le.text = s
le.text_changed.emit(s)
main._commit_edits()
_check(_steps() == 1 and _t("a").name == "Loot of the deep!!", "more typing in the same field joins that step: %d" % _steps())
le.release_focus()
main.undo()
_check(_t("a").name == "Loot", "undo puts the old name back")
_check(main._toast_label.text == "Undid: Rename Loot → Loot of the deep!!", "a toast says what was undone: %s" % main._toast_label.text)
main.redo()
_check(_t("a").name == "Loot of the deep!!" and main._toast_label.text.begins_with("Redid: "), "redo brings it back")
main.undo()
await _frames()
func _test_card_fields() -> void:
print("Weights, effects, details, settings")
var n0 := _steps()
_t("a").entries[0].weight = 4
main.mark_dirty()
await _frames()
_check(_steps() == n0 + 1 and _label() == "Edit Loot", "a weight is a step: %s" % _label())
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
_t("a").entries[0].effects = "@hp -= 1"
main.mark_dirty()
await _frames()
_t("a").details = "Treasure"
main.mark_dirty()
await _frames()
_check(_steps() == n0 + 2, "an effect and details right after merge into one step on the same card: %d" % (_steps() - n0))
main.undo()
_check(_t("a").entries[0].effects == "" and _t("a").details == "" and _t("a").entries[0].weight == 4, "undo takes both back, leaving the weight")
main.undo()
_check(_t("a").entries[0].weight == 1, "and then the weight")
# Settings go through the dialog's applied signal.
main.open_table_settings("b")
await _frames()
var dlg: TableSettingsDialog = null
for c in main.get_children():
if c is TableSettingsDialog:
dlg = c
_check(dlg != null, "the settings dialog opens")
if dlg:
_t("b").card_mode = true
dlg.applied.emit({})
dlg.close()
await _frames()
_check(_label() == "Edit settings of Gems", "settings are a step: %s" % _label())
main.undo()
_check(not _t("b").card_mode, "undo puts the settings back")
func _test_results_and_tables() -> void:
print("Results and tables")
main.add_entry("a")
_check(_label() == "Add result to Loot" and _t("a").entries.size() == 3, "adding a result: %s" % _label())
main.undo()
_check(_t("a").entries.size() == 2, "undo removes it")
main.redo()
_check(_t("a").entries.size() == 3, "redo adds it back")
main.undo()
main.delete_entry("a", "e2")
_check(_label() == "Delete result “Silver” from Loot", "deleting a result: %s" % _label())
main.undo()
_check(_t("a").find_entry("e2") != null and _t("a").find_entry("e2").text == "Silver", "undo brings the result back")
var t := main.add_table()
_check(_label() == "Add table New table", "adding a table: %s" % _label())
main.undo()
_check(_t(t.id) == null and main.card_for(t.id) == null, "undo removes the table and its card")
main.add_table(RollTable.KIND_CHOICE, "pick")
_check(_label() == "Add choice New choice", "adding a choice card: %s" % _label())
main.undo()
main.delete_table("b")
_check(_label() == "Delete table Gems" and _t("a").entries[0].pipes.is_empty(), "deleting a table: %s" % _label())
main.undo()
await _frames()
_check(_t("b") != null and main.card_for("b") != null and _t("a").entries[0].pipes == ["b"], "undo brings the table, its card and the pipe into it back")
func _test_pipes() -> void:
print("Pipes")
main._begin_edit()
_t("a").entries[1].pipes.append("c")
main.mark_dirty()
await _frames()
_check(_label() == "Add pipe Loot → Weapons", "laying a pipe: %s" % _label())
main.undo()
_check(_t("a").entries[1].pipes.is_empty(), "undo takes the pipe away")
main.remove_pipe("a:e1>b")
_check(_label() == "Remove pipe Loot → Gems" and main._toast_undo.visible, "removing a pipe, with an undo toast: %s" % _label())
main.undo()
_check(_t("a").entries[0].pipes == ["b"], "undo lays it again")
var e := _t("a").entries[0]
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
var n0 := _steps()
e.set_pipe_count("b", 3)
main.mark_dirty()
await _frames()
e.set_pipe_count("b", 4)
main.mark_dirty()
await _frames()
_check(_steps() == n0 + 1 and _label() == "Edit pipe Loot → Gems", "nudging a pipe's count twice is one step: %s" % _label())
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
e.set_pipe_save("b", "gem")
main.mark_dirty()
await _frames()
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
e.set_pipe_when("b", "@hp > 2")
main.mark_dirty()
await _frames()
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
e.set_pipe_when("b", "")
e.set_pipe_otherwise("b", true)
main.mark_dirty()
await _frames()
_check(_steps() == n0 + 4, "save as, Only if and Otherwise are steps of their own: %d" % (_steps() - n0))
main.undo()
_check(_t("a").entries[0].when_for("b") == "@hp > 2" and not _t("a").entries[0].is_otherwise("b"), "undo: Only if back")
main.undo()
_check(_t("a").entries[0].when_for("b") == "" and _t("a").entries[0].save_for("b") == "gem", "undo: condition gone, save kept")
main.undo()
main.undo()
_check(_t("a").entries[0].count_for("b") == 1 and _t("a").entries[0].save_for("b") == "", "undo: count back to 1")
func _test_drag() -> void:
print("Drags")
var card := main.card_for("b")
var p0 := card.position
var n0 := _steps()
main.begin_card_drag(card)
main.end_card_drag(card)
await _frames()
_check(_steps() == n0, "a click on a header without a drag isn't a step")
main.begin_card_drag(card)
for i in 10:
main.drag_card(card, p0 + Vector2(10 * i, 5 * i))
await process_frame
main.end_card_drag(card)
await _frames()
_check(_steps() == n0 + 1 and _label() == "Move Gems", "a whole drag is one step: %d, %s" % [_steps() - n0, _label()])
main.undo()
_check(_t("b").position == p0 and main.card_for("b").position == p0, "undo moves the card back")
# Dragging into a group frame joins it.
card = main.card_for("b")
main.begin_card_drag(card)
main.drag_card(card, Vector2(1600, 140))
main.end_card_drag(card)
await _frames()
_check(_label() == "Add 1 card to group Careers" and main.data.group_of("b") != null, "dropping into a group: %s" % _label())
main.undo()
await _frames()
_check(main.data.group_of("b") == null and _t("b").position == p0, "undo takes it back out")
# Several selected cards move together as one step.
main.set_selection(["a", "b"])
card = main.card_for("a")
var pa := card.position
main.begin_card_drag(card)
main.drag_card(card, pa + Vector2(0, 300))
main.end_card_drag(card)
await _frames()
_check(_label() == "Move 2 cards", "moving a selection: %s" % _label())
main.undo()
_check(_t("a").position == pa and main.selection.is_empty(), "undo moves them back and clears the selection")
func _test_groups() -> void:
print("Groups")
main.set_selection(["a", "b"])
var g := main.group_selection()
_check(_label() == "Group %s" % g.name, "grouping: %s" % _label())
main.undo()
_check(main.data.get_group(g.id) == null and main.group_node(g.id) == null, "undo removes the group")
main.redo()
_check(main.data.get_group(g.id) != null and main.group_node(g.id) != null, "redo makes it again")
main.undo()
main.ungroup("g1")
_check(_label() == "Ungroup Careers", "ungrouping: %s" % _label())
main.undo()
_check(main.data.get_group("g1") != null and main.data.get_group("g1").members == ["c", "d"], "undo puts the group back")
main.delete_group("g1")
_check(_label() == "Delete group Careers" and _t("c") == null, "deleting a group: %s" % _label())
main.undo()
await _frames()
_check(_t("c") != null and main.card_for("d") != null and main.group_node("g1") != null, "undo brings the group and its cards back")
var gpos := main.data.get_group("g1").position
var cpos := _t("c").position
main.move_group("g1", Vector2(100, 50))
main.mark_dirty()
await _frames()
_check(_label() == "Move group Careers", "moving a group: %s" % _label())
main.undo()
_check(_t("c").position == cpos and main.data.get_group("g1").position == gpos, "undo moves it back")
main.data.get_group("g1").name = "Jobs"
main.mark_dirty()
await _frames()
_check(_label() == "Rename group Jobs", "renaming a group: %s" % _label())
main.undo()
_check(main.data.get_group("g1").name == "Careers", "undo restores the name")
main.data.remove_from_group("d")
main.mark_dirty()
await _frames()
_check(_label() == "Take 1 card out of group Careers", "taking a card out: %s" % _label())
main.undo()
_check(main.data.get_group("g1").members.has("d"), "undo puts it back in")
func _test_template_and_reset() -> void:
print("Templates and Reset sample")
var tpl := TemplateKit.make(main.data, ["a"], "card", "Loot copy")
var r := main.insert_template(tpl, {})
await _frames()
var nt: RollTable = r["tables"][0]
_check(_label() == "Insert template Loot copy" and _t(nt.id) != null, "inserting a template: %s" % _label())
main.undo()
_check(_t(nt.id) == null and main.card_for(nt.id) == null, "undo removes the inserted cards")
await main.reset_sample()
_check(_label() == "Reset sample" and _t("a") == null, "Reset sample is a step: %s" % _label())
main.undo()
await _frames()
_check(_t("a") != null and _t("a").name == "Loot" and main.data.get_group("g1") != null, "undo brings the board back")
func _test_pack() -> void:
print("Pack")
main.set_group_collapsed("g1", true)
await _frames(3)
_check(not main.edits.can_redo() or true, "collapsing")
var gpos := main.data.get_group("g1").position
var moved: int = await main.pack_collapsed_groups()
_check(moved > 0 and _label() == "Pack collapsed groups", "Pack is a step: %s" % _label())
main.undo()
await _frames()
_check(main.data.get_group("g1").position == gpos, "undo puts the group back")
_check(main.data.get_group("g1").collapsed, "and leaves it collapsed")
main.set_group_collapsed("g1", false)
await _frames(3)
func _test_redo_cleared() -> void:
print("Redo is cleared by a new edit")
main.add_entry("b")
main.undo()
_check(main.edits.can_redo(), "after undo, redo is offered")
main.add_entry("a")
_check(not main.edits.can_redo(), "a new edit clears it")
main.undo()
func _test_view_kept() -> void:
print("View, lit state, search and mode")
await _frames(3)
main.board.stop_animation()
main.board.set_zoom(0.6)
main.board.world.position = Vector2(-123, 45)
main.lit_entries["a:e1"] = true
main.lit_entries["b:e1"] = true
var panel := main.open_search()
panel.field.text = "loot"
panel.refresh()
main.delete_table("b")
main.undo()
await _frames()
_check(is_equal_approx(main.board.zoom, 0.6) and main.board.world.position == Vector2(-123, 45), "zoom and pan stay")
_check(main.lit_entries.has("a:e1") and main.lit_entries.has("b:e1") and main.is_entry_lit("b", "e1"), "lit results stay lit, also on the table brought back")
_check(panel.visible and panel.field.text == "loot", "the search stays open")
_check(main.mode == Main.Mode.BUILD, "and the mode stays")
panel.close()
main.lit_entries.clear()
# A change on screen flashes.
main.board.fit()
await _frames()
main.add_entry("a")
main.undo()
await _frames(3)
_check(main.board.cards.is_flashing() and main.board.cards.flash_rect() == Rect2(main.card_for("a").position, main.card_for("a").size), "the changed card flashes")
func _test_toast() -> void:
print("Toast Undo")
main.delete_entry("a", "e2")
_check(main._toast.visible and main._toast_undo.visible, "deleting shows an undo toast")
main._toast_undo.pressed.emit()
_check(_t("a").find_entry("e2") != null and main.edits.can_redo(), "its Undo goes through the history (redo is offered)")
main.redo()
main.undo()
main.delete_table("b")
_check(main._toast_undo.visible, "another undo toast")
main.add_entry("a")
_check(not main._toast_undo.visible, "a newer edit hides the toast's Undo, so it can't undo the wrong thing")
main.undo()
main.undo()
_check(_t("b") != null, "undo twice brings the table back")
func _test_lazy_cards() -> void:
print("Lazily built cards")
main.set_group_collapsed("g1", true)
await _frames(3)
_check(main.card_for("c") == null, "Weapons is hidden in the collapsed group, with no card")
_t("c").entries[0].text = "Axe"
main.mark_dirty()
await _frames()
_check(_label() == "Edit Weapons", "an edit to a hidden card is a step: %s" % _label())
main.undo()
await _frames(3)
_check(_t("c").entries[0].text == "Sword" and main.card_for("c") == null, "undo restores it and still doesn't build the card")
_check(main.data.get_group("g1").collapsed and main.group_node("g1") != null, "the group stays collapsed")
main.delete_group("g1")
main.undo()
await _frames(3)
_check(main.data.get_group("g1").collapsed and main.card_for("c") == null, "a deleted collapsed group comes back collapsed, cards unbuilt")
main.set_group_collapsed("g1", false)
await _frames(3)
var c := main.card_for("c")
_check(c != null and c.visible and _line_edit_with(c, "Sword") != null, "expanding it builds the restored card")
func _test_collapse_not_undoable() -> void:
print("Collapsing isn't a step")
var n0 := _steps()
main.toggle_collapse("a")
main.set_all_collapsed(true)
main.set_all_collapsed(false)
main.toggle_collapse("b")
await _frames()
_check(_steps() == n0, "collapsing and expanding add no steps")
main.add_entry("a")
main.undo()
_check(_t("b").collapsed, "undo leaves Gems collapsed as it is")
main.toggle_collapse("b")
func _test_shortcuts_and_buttons() -> void:
print("Shortcuts and buttons")
main.add_entry("a")
_check(not main._undo_button.disabled and main._undo_button.tooltip_text == "Undo: Add result to Loot (Ctrl+Z)", "the Undo button names the step: %s" % main._undo_button.tooltip_text)
_check(main._redo_button.disabled, "Redo is disabled with nothing to redo")
main._shortcut_input(_key(KEY_Z, false))
_check(_t("a").entries.size() == 2, "Ctrl+Z undoes")
_check(not main._redo_button.disabled and main._redo_button.tooltip_text.begins_with("Redo: Add result to Loot"), "Redo is enabled and named: %s" % main._redo_button.tooltip_text)
main._shortcut_input(_key(KEY_Z, true))
_check(_t("a").entries.size() == 3, "Ctrl+Shift+Z redoes")
main._shortcut_input(_key(KEY_Z, false))
main._shortcut_input(_key(KEY_Y, false))
_check(_t("a").entries.size() == 3, "Ctrl+Y redoes too")
var le := _line_edit_with(main.card_for("a"), "Loot")
le.grab_focus()
main._shortcut_input(_key(KEY_Z, false))
_check(_t("a").entries.size() == 3, "with a text field focused, Ctrl+Z is left to the field")
le.release_focus()
main._undo_button.pressed.emit()
_check(_t("a").entries.size() == 2, "the Undo button undoes")
while main.edits.can_undo():
main.undo()
_check(main._undo_button.disabled and main._undo_button.tooltip_text == "Nothing to undo", "with nothing left, Undo is disabled")
main.redo()
func _key(code: Key, shift: bool) -> InputEventKey:
var k := InputEventKey.new()
k.keycode = code
k.ctrl_pressed = true
k.shift_pressed = shift
k.pressed = true
return k
func _test_play_mode() -> void:
print("Play mode")
main.set_mode(Main.Mode.PLAY)
var card := main.card_for("b")
var p0 := card.position
main.begin_card_drag(card)
main.drag_card(card, p0 + Vector2(200, 0))
main.end_card_drag(card)
await _frames()
_check(_label() == "Move Gems", "moving a card in Play is a step too")
main._shortcut_input(_key(KEY_Z, false))
_check(_t("b").position == p0 and main.mode == Main.Mode.PLAY, "Ctrl+Z undoes it in Play, staying in Play")
main.set_mode(Main.Mode.BUILD)
func _test_collections() -> void:
print("Per-collection history")
main.add_entry("a")
var first := main.data
var h := main.edits
var other := TowerBoard.new()
other.load_dict({"format_version": 2, "id": "other", "name": "Other", "tables": [
{"id": "x", "name": "X", "x": 0, "y": 0, "entries": [{"id": "e1", "text": "x"}]}]})
await main._show_collection(other)
_check(main.edits != h and not main.edits.can_undo(), "another collection has its own, empty history")
main.add_entry("x")
_check(main.edits.undo_label() == "Add result to X", "edits there go to its history")
await main._show_collection(first)
_check(main.edits == h and main.edits.undo_label() == "Add result to Loot", "switching back keeps the first history")
var n_before := _t("a").entries.size()
main.undo()
_check(_t("a").entries.size() == n_before - 1, "and undo still works: %d -> %d" % [n_before, _t("a").entries.size()])
func _test_big_board() -> void:
print("Big board")
var d: Dictionary = {}
var path := ""
for a in OS.get_cmdline_user_args():
if a.begins_with("--big-board="):
path = a.trim_prefix("--big-board=")
if path != "" and FileAccess.file_exists(path):
d = JSON.parse_string(FileAccess.get_file_as_string(path))
else:
d = _synthetic_board(800)
await _load(d)
var t := main.data.tables[main.data.tables.size() / 2]
var u := main.data.tables[main.data.tables.size() / 3]
var n := main.data.tables.size()
var full := EditHistory.full_bytes(main.edits.cache)
# One committed edit: what typing costs once it pauses.
t.name = t.name + " (edited)"
main.mark_dirty()
var t1 := Time.get_ticks_usec()
main._commit_edits()
var commit_ms := (Time.get_ticks_usec() - t1) / 1000.0
var cap_ms := main.edits.last_capture_usec / 1000.0
u.name = u.name + " (edited)"
main.mark_dirty()
main._commit_edits()
# The oldest step holds the whole board; later ones only what changed.
var step_bytes := int(main.edits.undo_stack.back()["snap"]["bytes"])
# A keystroke: the history's part (restarting a timer) against all of mark_dirty.
var le := LineEdit.new()
main.add_child(le)
le.grab_focus()
var t2 := Time.get_ticks_usec()
for i in 20:
t.name += "x"
main.mark_dirty()
var key_ms := (Time.get_ticks_usec() - t2) / 1000.0 / 20.0
var t4 := Time.get_ticks_usec()
for i in 20:
main._board_changed()
var base_ms := (Time.get_ticks_usec() - t4) / 1000.0 / 20.0
_check(main.edits.undo_stack.size() == 2, "keystrokes in a text field don't commit until typing pauses")
le.release_focus()
le.queue_free()
main._commit_edits()
var t3 := Time.get_ticks_usec()
main.undo()
var undo_ms := (Time.get_ticks_usec() - t3) / 1000.0
var undo_one_ms := main._last_restore_usec / 1000.0
# Undoing a deletion rebuilds the whole board.
main.delete_table(u.id)
var t5 := Time.get_ticks_usec()
main.undo()
var undo_del_ms := (Time.get_ticks_usec() - t5) / 1000.0
_check(_t(u.id) != null, "undoing a deletion on the big board brings the card back")
print(" TIMING %d cards: one committed edit %.1f ms (snapshot %.1f ms); keystroke %.2f ms, of which mark_dirty's existing refresh %.2f ms; undo of an edit %.1f ms (board update %.1f ms); undo of a deletion %.1f ms; board %d chars, later step %d bytes" % [
n, commit_ms, cap_ms, key_ms, base_ms, undo_ms, undo_one_ms, undo_del_ms, full, step_bytes])
_check(commit_ms < 250.0, "committing one edit stays quick: %.1f ms" % commit_ms)
_check(key_ms - base_ms < 1.0, "a keystroke doesn't snapshot the board: %.2f ms over %.2f ms" % [key_ms, base_ms])
_check(step_bytes < full / 10, "a later step stores only the changed cards: %d of %d" % [step_bytes, full])
_check(_t(t.id).name.ends_with("(edited)") and not _t(t.id).name.ends_with("x"), "undo works on the big board")
func _synthetic_board(n: int) -> Dictionary:
var tables: Array = []
var groups: Array = []
for i in n:
var entries: Array = []
for j in 8:
entries.append({"id": "e%d" % j, "text": "Result %d of table %d with some text" % [j, i], "pipes": ["t%d" % ((i + 1) % n)] if j == 0 else []})
tables.append({"id": "t%d" % i, "name": "Table %d" % i, "x": (i % 40) * 300, "y": (i / 40) * 400, "entries": entries})
for k in n / 40:
var members: Array = []
for i in range(k * 40, k * 40 + 40):
members.append("t%d" % i)
groups.append({"id": "g%d" % k, "name": "Group %d" % k, "x": 0, "y": k * 400, "w": 12000, "h": 380, "members": members, "collapsed": true})
return {"format_version": 2, "id": "big", "name": "Big", "tables": tables, "groups": groups}

1
tests/test_undo.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://6w0wkvln8c5d

View file

@ -276,6 +276,10 @@ func _gui_input(ev: InputEvent) -> void:
MOUSE_BUTTON_LEFT, MOUSE_BUTTON_MIDDLE:
var build_left := mb.button_index == MOUSE_BUTTON_LEFT and main.mode == Main.Mode.BUILD
if mb.pressed:
# Clicking the felt leaves a text field, so Ctrl+Z undoes on the board.
var f := get_viewport().gui_get_focus_owner()
if f is LineEdit or f is TextEdit:
f.release_focus()
if build_left and (mb.ctrl_pressed or mb.meta_pressed):
# Ctrl-drag on the felt: rubber-band selection.
_banding = true

View file

@ -22,6 +22,8 @@ var far := false
var _shadow: StyleBoxFlat
var _ring: StyleBoxFlat
var _flash_node: Control = null
## More nodes ringed along with _flash_node (flash_all: an undo's changes).
var _flash_extra: Array[Control] = []
var _flash_row: Rect2 = Rect2()
var _flash_left := 0.0
@ -51,6 +53,7 @@ func _draw() -> void:
## Flashes a ring around `node` (a TableCard or GroupCard) for FLASH_TIME.
## `row` is a world rect inside it to ring as well (Rect2() for none).
func flash(node: Control, row: Rect2 = Rect2()) -> void:
_flash_extra.clear()
_flash_node = node
_flash_row = row
_flash_left = FLASH_TIME
@ -58,6 +61,14 @@ func flash(node: Control, row: Rect2 = Rect2()) -> void:
overlay.queue_redraw()
## Flashes rings around several nodes at once (none: nothing happens).
func flash_all(nodes: Array[Control]) -> void:
if nodes.is_empty():
return
flash(nodes[0])
_flash_extra = nodes.slice(1)
func is_flashing() -> bool:
return _flash_left > 0.0 and is_instance_valid(_flash_node)
@ -78,6 +89,7 @@ func _process(delta: float) -> void:
overlay.queue_redraw()
if _flash_left <= 0.0:
_flash_node = null
_flash_extra.clear()
set_process(false)
@ -90,10 +102,16 @@ func _draw_flash() -> void:
# Two quick pulses, then a fade.
var pulse := 0.65 + 0.35 * cos((1.0 - t) * TAU * 2.0)
var a := minf(1.0, t * 2.5) * pulse
var r := Rect2(_flash_node.position, _flash_node.size).grow(8.0)
overlay.draw_style_box(_glow_box(a), r.grow(6.0))
_ring.border_color = Color(Style.BRASS, a)
overlay.draw_style_box(_ring, r)
var glow := _glow_box(a)
for v: Variant in [_flash_node] + _flash_extra:
if not is_instance_valid(v):
continue
var n := v as Control
if n.visible:
var r := Rect2(n.position, n.size).grow(8.0)
overlay.draw_style_box(glow, r.grow(6.0))
overlay.draw_style_box(_ring, r)
if _flash_row.size != Vector2.ZERO:
overlay.draw_rect(_flash_row, Color(Style.BRASS, 0.28 * a))
overlay.draw_rect(_flash_row, Color(Style.BRASS_DARK, a), false, 2.5)

View file

@ -17,6 +17,9 @@ extends ModalCard
## option's details and effects, and a TablePreview for every table it pipes
## to or mentions. Number and text questions preview where the Answer leads.
##
## 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.
##
## 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,
@ -143,7 +146,9 @@ func _option_row(k: int, o: Dictionary) -> Control:
col.size_flags_horizontal = SIZE_EXPAND_FILL
col.mouse_filter = MOUSE_FILTER_IGNORE
row.add_child(col)
var text := RichText.label(RichText.decorate(str(o.get("text", ""))), 17, Style.INK, false, true, true)
var dynamic: bool = o.get("dynamic", false)
var shown := Formatter.escape_literal(str(o.get("label", ""))) if dynamic else str(o.get("text", ""))
var text := RichText.label(RichText.decorate(shown), 17, Style.INK, false, true, true)
text.mouse_filter = MOUSE_FILTER_IGNORE
col.add_child(text)
var det := Formatter.strip_tags(str(o.get("details", ""))).strip_edges()
@ -155,6 +160,17 @@ func _option_row(k: int, o: Dictionary) -> Control:
sub.mouse_filter = MOUSE_FILTER_IGNORE
col.add_child(sub)
b.tooltip_text = det
var vt := str(o.get("value_text", ""))
if dynamic and vt != "":
var badge := PanelContainer.new()
badge.mouse_filter = MOUSE_FILTER_IGNORE
badge.size_flags_vertical = SIZE_SHRINK_CENTER
badge.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(Style.BRASS, 0.18), 6, [9, 1, 9, 2]), 1, Color(Style.BRASS_DARK, 0.4)))
var vl := Style.make_label(vt, Style.display(), 18, Style.COPPER_DARK)
vl.mouse_filter = MOUSE_FILTER_IGNORE
vl.set_meta("option_value", true)
badge.add_child(vl)
row.add_child(badge)
b.add_child(row)
# Buttons don't size to their children, so follow the row's height.
var fit := func() -> void: b.custom_minimum_size.y = row.get_combined_minimum_size().y + 17.0
@ -536,7 +552,8 @@ func _entry_for(k: int) -> TableEntry:
var opts: Array = request.get("options", [])
if k < 0 or k >= opts.size():
return null
index = int((opts[k] as Dictionary).get("index", k))
var o: Dictionary = opts[k]
index = int(o.get("entry", o.get("index", k)))
return t.entries[index] if index >= 0 and index < t.entries.size() else null
@ -556,6 +573,17 @@ func preview_for_option(k: int) -> Control:
heading.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.add_child(heading)
var any := false
var o: Dictionary = (request.get("options", []) as Array)[k] if kind == "pick" else {}
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"])
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
box.add_child(ol)
var det := e.details.strip_edges()
if det != "":
any = true

596
ui/edit_history.gd Normal file
View file

@ -0,0 +1,596 @@
class_name EditHistory
extends RefCounted
## Undo and redo for one collection's Build edits: a stack of whole-board
## snapshots each way, plus `cache`, the snapshot of the last committed state
## (the "before" of the next edit). Main keeps one per collection.
##
## A snapshot holds each table and group as its own compact JSON string, with
## the collapsed flags kept apart (collapsing is view state, not an edit; see
## restore). A table that didn't change shares its string with the snapshot
## before it (Godot strings are copy-on-write), so a step costs roughly the
## size of the cards it changed, not the whole board.
##
## Step labels come from diffing the snapshots on either side of the step
## (label_for), unless the caller gives one.
## Most steps kept, and roughly the most memory they may use between them.
const MAX_STEPS := 200
const MAX_BYTES := 48 * 1024 * 1024
## Edits to the same thing this close together become one step.
const COALESCE_SECS := 0.8
var undo_stack: Array[Dictionary] = [] # {snap, label, key, time, focus, serial}
var redo_stack: Array[Dictionary] = [] # {snap, label, serial}
var cache: Dictionary = {}
## How long the last capture took (microseconds), and its size in characters.
var last_capture_usec := 0
var _serial := 0
func _init(board: TowerBoard = null) -> void:
if board:
cache = capture(board)
func can_undo() -> bool:
return not undo_stack.is_empty()
func can_redo() -> bool:
return not redo_stack.is_empty()
func undo_label() -> String:
return str(undo_stack.back()["label"]) if can_undo() else ""
func redo_label() -> String:
return str(redo_stack.back()["label"]) if can_redo() else ""
## The serial of the newest undo step (-1 when there is none).
func top_serial() -> int:
return int(undo_stack.back()["serial"]) if can_undo() else -1
func clear() -> void:
undo_stack.clear()
redo_stack.clear()
## Takes the board as the new baseline. If it differs from the cached state
## (the collection was replaced from outside), the history no longer applies
## and is cleared.
func resync(board: TowerBoard) -> void:
var snap := capture(board, cache)
if cache.is_empty() or not is_empty_diff(diff(cache, snap)):
clear()
cache = snap
## Records the board's current state. Returns {step, merged, label, diff}:
## `step` is false when nothing undoable changed (only collapsing, or group
## frames refitting around their cards), in which case the baseline just
## catches up. Without a `label`, an edit to the same single thing as the
## newest step merges into it when it comes within COALESCE_SECS or from the
## same text field (`focus`, an instance id, 0 for none).
func commit(board: TowerBoard, label: String = "", focus: int = 0, now: float = -1.0) -> Dictionary:
if now < 0.0:
now = Time.get_ticks_msec() / 1000.0
var t0 := Time.get_ticks_usec()
var snap := capture(board, cache)
last_capture_usec = Time.get_ticks_usec() - t0
var d := diff(cache, snap)
if is_empty_diff(d):
# The old baseline goes, but strings it shared with the stacks stay
# with the new one: count them there.
snap["bytes"] = mini(int(snap["bytes"]) + int(cache.get("bytes", 0)), full_bytes(snap))
cache = snap
return {"step": false, "merged": false, "label": "", "diff": d}
var key := coalesce_key(cache, snap, d) if label == "" else ""
if key != "" and can_undo() and redo_stack.is_empty():
var top: Dictionary = undo_stack.back()
if str(top["key"]) == key and (now - float(top["time"]) < COALESCE_SECS or (focus != 0 and focus == int(top["focus"]))):
var d2 := diff(top["snap"], snap)
cache = snap
if is_empty_diff(d2):
# Typed and then put back: nothing left to undo.
undo_stack.pop_back()
return {"step": true, "merged": true, "label": "", "diff": d}
top["label"] = label_for(top["snap"], snap, d2)
top["time"] = now
top["focus"] = focus
return {"step": true, "merged": true, "label": top["label"], "diff": d}
redo_stack.clear()
_serial += 1
var lbl := label if label != "" else label_for(cache, snap, d)
undo_stack.push_back({"snap": cache, "label": lbl, "key": key, "time": now, "focus": focus, "serial": _serial})
cache = snap
_trim()
return {"step": true, "merged": false, "label": lbl, "diff": d}
## Pops the newest step for undoing: returns {snap (to restore), label, from
## (the state being left)} and moves the current state onto the redo stack.
## The caller restores `snap` and then sets `cache` (restore's result).
func pop_undo() -> Dictionary:
var e: Dictionary = undo_stack.pop_back()
redo_stack.push_back({"snap": cache, "label": e["label"], "serial": e["serial"]})
return {"snap": e["snap"], "label": e["label"], "from": cache}
func pop_redo() -> Dictionary:
var e: Dictionary = redo_stack.pop_back()
undo_stack.push_back({"snap": cache, "label": e["label"], "key": "", "time": 0.0, "focus": 0, "serial": e["serial"]})
return {"snap": e["snap"], "label": e["label"], "from": cache}
## Rough memory held by the stacks (unshared characters plus per-card overhead).
func bytes() -> int:
var n := 0
for e in undo_stack:
n += int(e["snap"].get("bytes", 0))
for e in redo_stack:
n += int(e["snap"].get("bytes", 0))
return n
func _trim() -> void:
while undo_stack.size() > MAX_STEPS:
undo_stack.pop_front()
var total := bytes()
while undo_stack.size() > 1 and total > MAX_BYTES:
total -= int(undo_stack[0]["snap"].get("bytes", 0))
undo_stack.pop_front()
# ---------- Snapshots ----------
## The board as {ids, tables, gids, groups, collapsed, bytes}. Strings equal
## to the ones in `prev` are shared with it; `bytes` counts the rest.
static func capture(board: TowerBoard, prev: Dictionary = {}) -> Dictionary:
var old_t := _strings_by_id(prev, "ids", "tables")
var old_g := _strings_by_id(prev, "gids", "groups")
var ids := PackedStringArray()
var tables := PackedStringArray()
var gids := PackedStringArray()
var groups := PackedStringArray()
var collapsed := {}
var n := 0
for t in board.tables:
var d := t.to_dict()
d.erase("collapsed")
var s := JSON.stringify(d)
var o: Variant = old_t.get(t.id)
if o != null and o == s:
s = o
else:
n += s.length()
ids.append(t.id)
tables.append(s)
if t.collapsed:
collapsed["t:" + t.id] = true
for g in board.groups:
var d := g.to_dict()
d.erase("collapsed")
var s := JSON.stringify(d)
var o: Variant = old_g.get(g.id)
if o != null and o == s:
s = o
else:
n += s.length()
gids.append(g.id)
groups.append(s)
if g.collapsed:
collapsed["g:" + g.id] = true
n += (ids.size() + gids.size()) * 16
return {"ids": ids, "tables": tables, "gids": gids, "groups": groups, "collapsed": collapsed, "bytes": n}
## A snapshot's size if it shared nothing.
static func full_bytes(snap: Dictionary) -> int:
var n := 0
for k in ["tables", "groups"]:
for s in (snap[k] as PackedStringArray):
n += s.length()
return n + ((snap["ids"] as PackedStringArray).size() + (snap["gids"] as PackedStringArray).size()) * 16
static func _strings_by_id(snap: Dictionary, ids_key: String, strs_key: String) -> Dictionary:
var out := {}
if snap.is_empty():
return out
var ids: PackedStringArray = snap[ids_key]
var strs: PackedStringArray = snap[strs_key]
for i in ids.size():
out[ids[i]] = strs[i]
return out
## Replaces the board's tables and groups with the snapshot's. Collapsing
## isn't undone: tables and groups that exist now keep their collapsed state;
## ones brought back take the state they had. The collection's id and name
## stay. Returns the snapshot with its collapsed flags as applied.
static func restore(board: TowerBoard, snap: Dictionary) -> Dictionary:
var now := {}
for t in board.tables:
now["t:" + t.id] = t.collapsed
for g in board.groups:
now["g:" + g.id] = g.collapsed
var was: Dictionary = snap["collapsed"]
var collapsed := {}
var tables: Array = []
var ids: PackedStringArray = snap["ids"]
var strs: PackedStringArray = snap["tables"]
for i in ids.size():
var d: Dictionary = JSON.parse_string(strs[i])
var k := "t:" + ids[i]
if (bool(now[k]) if now.has(k) else was.has(k)):
d["collapsed"] = true
collapsed[k] = true
tables.append(d)
var groups: Array = []
var gids: PackedStringArray = snap["gids"]
var gstrs: PackedStringArray = snap["groups"]
for i in gids.size():
var d: Dictionary = JSON.parse_string(gstrs[i])
var k := "g:" + gids[i]
if (bool(now[k]) if now.has(k) else was.has(k)):
d["collapsed"] = true
collapsed[k] = true
groups.append(d)
board.load_dict({"format_version": TowerBoard.FORMAT_VERSION, "tables": tables, "groups": groups})
var out := snap.duplicate()
out["collapsed"] = collapsed
return out
## Restores a snapshot by touching only what differs from `from` (the board's
## current snapshot): tables and groups whose text changed are updated in
## place, new ones are made and missing ones dropped, so every other object
## (and the card showing it) stays. Collapsed flags as in restore. Returns
## {snap (as restore), tables (ids updated in place), added, removed, groups
## (ids updated in place), groups_changed (true when any group came, went or
## changed more than its frame)}, or {} without a `from`.
static func patch(board: TowerBoard, snap: Dictionary, from: Dictionary) -> Dictionary:
if from.is_empty():
return {}
var old_t := _strings_by_id(from, "ids", "tables")
var old_g := _strings_by_id(from, "gids", "groups")
var was: Dictionary = snap["collapsed"]
var collapsed := {}
var by_id := {}
for t in board.tables:
by_id[t.id] = t
var ids: PackedStringArray = snap["ids"]
var strs: PackedStringArray = snap["tables"]
var tables: Array[RollTable] = []
var updated: Array = []
var added: Array = []
for i in ids.size():
var t: RollTable = by_id.get(ids[i])
if t == null:
t = RollTable.from_dict(JSON.parse_string(strs[i]))
t.collapsed = was.has("t:" + ids[i])
added.append(t.id)
elif old_t.get(t.id) != strs[i]:
var fresh := RollTable.from_dict(JSON.parse_string(strs[i]))
fresh.collapsed = t.collapsed
_copy_fields(fresh, t)
updated.append(t.id)
by_id.erase(ids[i])
if t.collapsed:
collapsed["t:" + t.id] = true
tables.append(t)
var removed: Array = by_id.keys()
var gby_id := {}
for g in board.groups:
gby_id[g.id] = g
var gids: PackedStringArray = snap["gids"]
var gstrs: PackedStringArray = snap["groups"]
var groups: Array[TableGroup] = []
var gupdated: Array = []
var regroup := false
for i in gids.size():
var g: TableGroup = gby_id.get(gids[i])
if g == null:
g = TableGroup.from_dict(JSON.parse_string(gstrs[i]))
g.collapsed = was.has("g:" + gids[i])
regroup = true
elif old_g.get(g.id) != gstrs[i]:
var fresh := TableGroup.from_dict(JSON.parse_string(gstrs[i]))
fresh.collapsed = g.collapsed
if fresh.name != g.name or fresh.details != g.details or fresh.members != g.members:
regroup = true
_copy_fields(fresh, g)
gupdated.append(g.id)
gby_id.erase(gids[i])
if g.collapsed:
collapsed["g:" + g.id] = true
groups.append(g)
if not gby_id.is_empty():
regroup = true
board.tables = tables
board.groups = groups
var out := snap.duplicate()
out["collapsed"] = collapsed
return {"snap": out, "tables": updated, "added": added, "removed": removed, "groups": gupdated, "groups_changed": regroup}
## Copies every script variable of `src` onto `dst` (same class).
static func _copy_fields(src: Object, dst: Object) -> void:
for p: Dictionary in src.get_property_list():
if int(p["usage"]) & PROPERTY_USAGE_SCRIPT_VARIABLE:
dst.set(p["name"], src.get(p["name"]))
# ---------- Diffs and labels ----------
## What changed from snapshot a to b, by id: tables added, removed, changed
## (anything but position) and moved (position only); groups likewise, where
## gmoved (frame only) is ignored for groups with members, whose frames
## follow their cards.
static func diff(a: Dictionary, b: Dictionary) -> Dictionary:
var out := {"added": [], "removed": [], "changed": [], "moved": [],
"gadded": [], "gremoved": [], "gchanged": [], "gmoved": [], "gmoved_empty": []}
_diff_lists(_strings_by_id(a, "ids", "tables"), _strings_by_id(b, "ids", "tables"),
["x", "y"], out, "added", "removed", "changed", "moved")
_diff_lists(_strings_by_id(a, "gids", "groups"), _strings_by_id(b, "gids", "groups"),
["x", "y", "w", "h"], out, "gadded", "gremoved", "gchanged", "gmoved")
var gb := _strings_by_id(b, "gids", "groups")
for gid: String in out["gmoved"]:
var d: Variant = JSON.parse_string(gb[gid])
if d is Dictionary and (d.get("members", []) as Array).is_empty():
out["gmoved_empty"].append(gid)
return out
static func _diff_lists(ma: Dictionary, mb: Dictionary, geometry: Array, out: Dictionary,
k_add: String, k_rem: String, k_chg: String, k_mov: String) -> void:
for id: String in mb:
if not ma.has(id):
out[k_add].append(id)
elif ma[id] != mb[id]:
var da: Dictionary = JSON.parse_string(ma[id])
var db: Dictionary = JSON.parse_string(mb[id])
for g: String in geometry:
da.erase(g)
db.erase(g)
out[k_chg if da != db else k_mov].append(id)
for id: String in ma:
if not mb.has(id):
out[k_rem].append(id)
static func is_empty_diff(d: Dictionary) -> bool:
for k in ["added", "removed", "changed", "moved", "gadded", "gremoved", "gchanged", "gmoved_empty"]:
if not (d[k] as Array).is_empty():
return false
return true
## Table ids whose cards changed in any way (added, changed or moved).
static func touched_tables(d: Dictionary) -> Array:
return (d["added"] as Array) + (d["changed"] as Array) + (d["moved"] as Array)
## A key for edits that may merge with the step before: one table's or one
## group's fields (text, weight, pipe options...), with nothing added or taken
## away. "" for anything else.
static func coalesce_key(a: Dictionary, b: Dictionary, d: Dictionary) -> String:
for k in ["added", "removed", "moved", "gadded", "gremoved", "gmoved_empty"]:
if not (d[k] as Array).is_empty():
return ""
var ch: Array = d["changed"]
var gch: Array = d["gchanged"]
if ch.size() == 1 and gch.is_empty():
var ta: Dictionary = _parsed(a, "ids", "tables", ch[0])
var tb: Dictionary = _parsed(b, "ids", "tables", ch[0])
var e := _entry_changes(ta, tb)
if e["added"].is_empty() and e["removed"].is_empty() and e["pipes_added"].is_empty() and e["pipes_removed"].is_empty():
return "t:" + str(ch[0])
elif gch.size() == 1 and ch.is_empty():
var ga: Dictionary = _parsed(a, "gids", "groups", gch[0])
var gb: Dictionary = _parsed(b, "gids", "groups", gch[0])
if ga.get("members") == gb.get("members"):
return "g:" + str(gch[0])
return ""
## Describes the step from a to b ("Edit Loot", "Delete table Weapons", "Add
## pipe Loot → Gems", "Move 3 cards", "Group Careers"...).
static func label_for(a: Dictionary, b: Dictionary, d: Dictionary = {}) -> String:
if d.is_empty():
d = diff(a, b)
var added: Array = d["added"]
var removed: Array = d["removed"]
var gadded: Array = d["gadded"]
var gremoved: Array = d["gremoved"]
if not gadded.is_empty() and not added.is_empty():
return "Add %s" % _count(added.size(), "card")
if gadded.size() == 1:
return "Group %s" % _name(b, "gids", "groups", gadded[0])
if gremoved.size() == 1:
var gname := _name(a, "gids", "groups", gremoved[0])
return ("Delete group %s" if not removed.is_empty() else "Ungroup %s") % gname
if not gadded.is_empty() or not gremoved.is_empty():
return "Change groups"
if added.size() == 1:
return "Add %s %s" % [_kind_word(_parsed(b, "ids", "tables", added[0])), _name(b, "ids", "tables", added[0])]
if not added.is_empty():
return "Add %s" % _count(added.size(), "card")
if removed.size() == 1:
return "Delete %s %s" % [_kind_word(_parsed(a, "ids", "tables", removed[0])), _name(a, "ids", "tables", removed[0])]
if not removed.is_empty():
return "Delete %s" % _count(removed.size(), "card")
var changed: Array = d["changed"]
var gchanged: Array = d["gchanged"]
# Group membership (a card dragged into or out of a group).
for gid: String in gchanged:
var ga := _parsed(a, "gids", "groups", gid)
var gb := _parsed(b, "gids", "groups", gid)
var ma: Array = ga.get("members", [])
var mb: Array = gb.get("members", [])
if ma != mb:
var ins := 0
var outs := 0
for m: Variant in mb:
if not ma.has(m):
ins += 1
for m: Variant in ma:
if not mb.has(m):
outs += 1
var gname := Formatter.strip_tags(str(gb.get("name", "")))
if ins > 0 and outs == 0:
return "Add %s to group %s" % [_count(ins, "card"), gname]
if outs > 0 and ins == 0:
return "Take %s out of group %s" % [_count(outs, "card"), gname]
return "Change group %s" % gname
if changed.size() == 1:
return _table_label(_parsed(a, "ids", "tables", changed[0]), _parsed(b, "ids", "tables", changed[0]), b)
if changed.size() > 1:
return "Edit %s" % _count(changed.size(), "card")
if gchanged.size() == 1:
var ga := _parsed(a, "gids", "groups", gchanged[0])
var gb := _parsed(b, "gids", "groups", gchanged[0])
var gname := Formatter.strip_tags(str(gb.get("name", "")))
if ga.get("name") != gb.get("name"):
return "Rename group %s" % gname
return "Edit group %s" % gname
if gchanged.size() > 1:
return "Edit %s" % _count(gchanged.size(), "group")
var moved: Array = d["moved"]
if not moved.is_empty():
# All the moved cards belong to one group whose frame moved too.
for gid: String in d["gmoved"]:
var gb := _parsed(b, "gids", "groups", gid)
var members: Array = gb.get("members", [])
var all := true
for tid: Variant in moved:
if not members.has(tid):
all = false
break
if all and moved.size() == members.size():
return "Move group %s" % Formatter.strip_tags(str(gb.get("name", "")))
if moved.size() == 1:
return "Move %s" % _name(b, "ids", "tables", moved[0])
return "Move %s" % _count(moved.size(), "card")
if not (d["gmoved_empty"] as Array).is_empty():
return "Move group %s" % _name(b, "gids", "groups", d["gmoved_empty"][0])
return "Edit"
## One table's change: results added or deleted, pipes laid, removed or
## changed, a rename, a reorder, or a plain edit.
static func _table_label(ta: Dictionary, tb: Dictionary, b: Dictionary) -> String:
var tname := Formatter.strip_tags(str(tb.get("name", "")))
var e := _entry_changes(ta, tb)
if not e["added"].is_empty():
return ("Add result to %s" % tname) if e["added"].size() == 1 else "Add %d results to %s" % [e["added"].size(), tname]
if not e["removed"].is_empty():
if e["removed"].size() == 1:
return "Delete result “%s” from %s" % [_short(Formatter.strip_tags(str(e["removed"][0].get("text", "")))), tname]
return "Delete %d results from %s" % [e["removed"].size(), tname]
if not e["pipes_added"].is_empty():
return "Add pipe %s → %s" % [tname, _name(b, "ids", "tables", e["pipes_added"][0])]
if not e["pipes_removed"].is_empty():
return "Remove pipe %s → %s" % [tname, _name(b, "ids", "tables", e["pipes_removed"][0])]
if not e["pipes_changed"].is_empty():
return "Edit pipe %s → %s" % [tname, _name(b, "ids", "tables", e["pipes_changed"][0])]
if ta.get("name") != tb.get("name"):
var rest_a := ta.duplicate()
var rest_b := tb.duplicate()
rest_a.erase("name")
rest_b.erase("name")
if rest_a == rest_b:
return "Rename %s → %s" % [Formatter.strip_tags(str(ta.get("name", ""))), tname]
if e["reordered"]:
return "Reorder %s" % tname
return "Edit %s" % tname
## Entries added and removed (dicts), pipe targets added, removed and changed,
## and whether the order changed.
static func _entry_changes(ta: Dictionary, tb: Dictionary) -> Dictionary:
var ea := {}
var order_a: Array = []
for x: Variant in ta.get("entries", []):
if x is Dictionary:
ea[str(x.get("id", ""))] = x
order_a.append(str(x.get("id", "")))
var eb := {}
var order_b: Array = []
for x: Variant in tb.get("entries", []):
if x is Dictionary:
eb[str(x.get("id", ""))] = x
order_b.append(str(x.get("id", "")))
var out := {"added": [], "removed": [], "pipes_added": [], "pipes_removed": [], "pipes_changed": [], "reordered": false}
for id: String in eb:
if not ea.has(id):
out["added"].append(eb[id])
for id: String in ea:
if not eb.has(id):
out["removed"].append(ea[id])
continue
var pa := _pipes(ea[id])
var pb := _pipes(eb[id])
for to: String in pb:
if not pa.has(to):
out["pipes_added"].append(to)
elif typeof(pa[to]) != typeof(pb[to]) or pa[to] != pb[to]:
out["pipes_changed"].append(to)
for to: String in pa:
if not pb.has(to):
out["pipes_removed"].append(to)
if out["added"].is_empty() and out["removed"].is_empty() and order_a != order_b:
out["reordered"] = true
return out
## target table id -> the pipe as written (an id or a dict of options).
static func _pipes(entry: Dictionary) -> Dictionary:
var out := {}
for p: Variant in entry.get("pipes", []):
if p is Dictionary:
out[str(p.get("table", ""))] = p
else:
out[str(p)] = p
return out
static func _parsed(snap: Dictionary, ids_key: String, strs_key: String, id: String) -> Dictionary:
var ids: PackedStringArray = snap[ids_key]
var i := ids.find(id)
if i < 0:
return {}
var v: Variant = JSON.parse_string((snap[strs_key] as PackedStringArray)[i])
return v if v is Dictionary else {}
static func _name(snap: Dictionary, ids_key: String, strs_key: String, id: String) -> String:
var d := _parsed(snap, ids_key, strs_key, id)
var n := Formatter.strip_tags(str(d.get("name", ""))).strip_edges()
return n if n != "" else id
static func _kind_word(d: Dictionary) -> String:
match str(d.get("kind", RollTable.KIND_ROLL)):
RollTable.KIND_CHOICE:
return "choice"
RollTable.KIND_LOOP:
return "loop"
RollTable.KIND_ROUTER:
return "router"
RollTable.KIND_VARIABLE:
return "variable"
RollTable.KIND_SHEET:
return "sheet"
return "table"
static func _count(n: int, noun: String) -> String:
return "%d %s%s" % [n, noun, "" if n == 1 else "s"]
static func _short(s: String) -> String:
return s if s.length() <= 28 else s.substr(0, 27) + "…"

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

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

View file

@ -1,7 +1,8 @@
class_name Main
extends Control
## The app window: top bar, felt board and result tray. Owns the board data,
## the Play/Build mode, roll animation, and editing actions with undo.
## the Play/Build mode, roll animation, and editing actions with undo and
## redo (EditHistory, one per collection; see "Undo and redo" below).
enum Mode { PLAY, BUILD }
@ -44,7 +45,8 @@ var _toast_label: Label
var _toast_undo: Button
var _toast_timer: Timer
var _save_timer: Timer
var _undo_snapshot := ""
## The undo step the toast's Undo button undoes (EditHistory serial), or -1.
var _toast_serial := -1
var _saving_enabled := true
# Local state for the current collection (see load_local_state). Kept in memory
@ -146,6 +148,7 @@ func _build_ui() -> void:
tray.setup(self)
root.add_child(tray)
_build_toast()
_build_edit_timer()
_save_timer = Timer.new()
_save_timer.one_shot = true
@ -210,6 +213,7 @@ func _build_top_bar() -> Control:
var tools := HBoxContainer.new()
tools.add_theme_constant_override("separation", 6)
_build_tools = tools
_make_history_buttons(tools)
_add_menu = _make_add_menu()
tools.add_child(_add_menu)
_board_menu = IoMenu.new()
@ -294,6 +298,7 @@ func _build_toast() -> void:
var uh := Style.box(Style.FELT_HOVER, 7, [12, 5, 12, 5])
Style.skin_button(_toast_undo, un, uh, uh, Style.BRASS)
_toast_undo.pressed.connect(_undo)
_toast_undo.focus_mode = Control.FOCUS_NONE
h.add_child(_toast_undo)
_toast.hide()
add_child(_toast)
@ -302,15 +307,17 @@ func _build_toast() -> void:
_toast_timer.wait_time = 5.0
_toast_timer.timeout.connect(func() -> void:
_toast.hide()
_undo_snapshot = ""
_toast_serial = -1
)
add_child(_toast_timer)
func toast(message: String, snapshot: String = "") -> void:
_undo_snapshot = snapshot
## Shows a message at the bottom. With `undoable`, it has an Undo button for
## the edit just committed (it goes through the edit history, like Ctrl+Z).
func toast(message: String, undoable: bool = false) -> void:
_toast_serial = edits.top_serial() if undoable and edits else -1
_toast_label.text = message
_toast_undo.visible = snapshot != ""
_toast_undo.visible = _toast_serial >= 0
_toast.show()
_toast.reset_size()
_place_toast()
@ -323,18 +330,16 @@ func _place_toast() -> void:
_toast.position = Vector2((size.x - _toast.size.x) / 2.0, size.y - _toast.size.y - 20.0)
## The toast's Undo button: undoes the step the toast was about, if it is
## still the newest one.
func _undo() -> void:
if _undo_snapshot == "":
_commit_edits()
if _toast_serial < 0 or edits == null or edits.top_serial() != _toast_serial:
_toast_undo.hide()
if edits and edits.can_undo():
toast("Newer edits came after that one. Undo (Ctrl+Z) steps back through them.")
return
data.load_json(_undo_snapshot)
_undo_snapshot = ""
_toast.hide()
_rebuild_cards()
mark_dirty()
func _snapshot() -> String:
return data.to_json()
undo()
# ---------- Cards ----------
@ -349,8 +354,11 @@ func is_entry_lit(tid: String, eid: String) -> bool:
## Rebuilds every card. Cards hidden in collapsed groups aren't built at all
## (card_for gives null for them) until their group expands; see
## _apply_group_visibility.
## _apply_group_visibility. Called from outside an edit (a board loaded or
## replaced), it also takes the board as the edit history's new baseline.
func _rebuild_cards() -> void:
if not _keep_history:
_sync_history()
for c in board.cards.get_children():
board.cards.remove_child(c)
c.queue_free()
@ -388,14 +396,38 @@ func set_mode(m: Mode) -> void:
_nav_mode_changed()
func mark_dirty() -> void:
## Call after changing the saved collection: schedules the save, refreshes
## what depends on the board and records an undo step (see "Undo and redo").
## `label` names the step and commits it at once; without one the step is
## named from the change, and committed at the end of the frame, or once
## typing pauses when a text field has focus. `undoable` false is for saved
## view state (collapsing), which isn't an undo step.
func mark_dirty(label: String = "", undoable: bool = true) -> void:
_board_changed()
if not undoable or edits == null or _restoring:
return
_edit_pending = true
if label != "":
_commit_edits(label)
return
var f := get_viewport().gui_get_focus_owner() if is_inside_tree() else null
if f is LineEdit or f is TextEdit:
_edit_focus = f.get_instance_id()
_edit_timer.start()
else:
_edit_focus = 0
_queue_commit()
## What every change to the board needs: a save soon, fresh caches and redraws.
func _board_changed() -> void:
if _saving_enabled:
_save_timer.start()
_ref_cache.clear()
view_rev += 1
edit_rev += 1
_update_collapse_all()
_update_endless_chip()
_schedule_endless_check()
if mode == Mode.BUILD:
refresh_live()
@ -426,7 +458,7 @@ func toggle_collapse(tid: String) -> void:
return
t.collapsed = not t.collapsed
card_for(tid).rebuild()
mark_dirty()
mark_dirty("", false)
## Collapses or expands every table and every group.
@ -444,7 +476,7 @@ func set_all_collapsed(collapsed: bool) -> void:
changed = true
if changed:
_rebuild_groups()
mark_dirty()
mark_dirty("", false)
## The "+ Table ▾" kinds: [label, kind, sub, default name].
@ -512,6 +544,7 @@ const MENU_SAVE_SELECTION := 102
## Adds a card of any kind (RollTable.create) in the middle of the view.
func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "") -> RollTable:
_begin_edit()
var center := board.screen_to_world(board.size / 2.0)
var name := "New table"
for k: Array in ADD_KINDS:
@ -530,7 +563,7 @@ func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "") -> RollTabl
board.cards.add_child(card)
card.setup(self, t)
cards[t.id] = card
mark_dirty()
_end_edit()
return t
@ -549,20 +582,23 @@ func _free_var_name(base: String) -> String:
func reset_sample() -> void:
var snap := _snapshot()
_begin_edit()
data.tables = SampleBoard.create().tables
data.groups.clear()
lit_entries.clear()
lit_pipes.clear()
_keep_history = true
_rebuild_cards()
mark_dirty()
_keep_history = false
_end_edit("Reset sample")
await get_tree().process_frame
await get_tree().process_frame
board.fit()
toast("Board reset to the sample tables", snap)
toast("Board reset to the sample tables", true)
func add_entry(tid: String) -> void:
_begin_edit()
var t := data.get_table(tid)
var e := TableEntry.new(TowerBoard.new_id("e"), "Result %d" % (t.entries.size() + 1))
if t.is_ranged():
@ -576,7 +612,7 @@ func add_entry(tid: String) -> void:
t.entries.append(e)
t.collapsed = false
card_for(tid).rebuild()
mark_dirty()
_end_edit()
func delete_entry(tid: String, eid: String) -> void:
@ -584,18 +620,18 @@ func delete_entry(tid: String, eid: String) -> void:
var e := t.find_entry(eid)
if e == null:
return
var snap := _snapshot()
_begin_edit()
t.entries.erase(e)
card_for(tid).rebuild()
mark_dirty()
toast("Deleted “%s”" % e.text, snap)
_end_edit()
toast("Deleted “%s”" % e.text, true)
func delete_table(tid: String) -> void:
var t := data.get_table(tid)
if t == null:
return
var snap := _snapshot()
_begin_edit()
var in_group := data.group_of(tid)
data.remove_table(tid)
forget_table_state(tid)
@ -609,8 +645,8 @@ func delete_table(tid: String) -> void:
if in_group:
_groups_changed()
_update_selection_bar()
mark_dirty()
toast("Deleted %s" % t.name, snap)
_end_edit()
toast("Deleted %s" % t.name, true)
func remove_pipe(key: String) -> void:
@ -623,13 +659,15 @@ func remove_pipe(key: String) -> void:
var e := t.find_entry(from.get_slice(":", 1))
if e == null:
return
var snap := _snapshot()
_begin_edit()
e.pipes.erase(to)
lit_pipes.erase(key)
board.pipes.hover_key = ""
card_for(t.id).rebuild()
mark_dirty()
toast("Removed pipe from “%s” to %s" % [e.text, target.name if target else to], snap)
var card := card_for(t.id)
if card:
card.rebuild()
_end_edit()
toast("Removed pipe from “%s” to %s" % [e.text, target.name if target else to], true)
func start_link(tid: String, eid: String) -> void:
@ -662,6 +700,7 @@ func finish_link() -> void:
if over.table.kind == RollTable.KIND_VARIABLE:
toast("Variable cards aren't rolled, so pipes can't lead into them. Use an effect such as @%s += 1." % over.table.var_name)
return
_begin_edit()
# Each range on a ranged table takes a single pipe, so a new one replaces the old.
var replaced: RollTable = null
if t.is_ranged():
@ -670,11 +709,11 @@ func finish_link() -> void:
e.pipes.clear()
e.pipes.append(over.table.id)
card_for(t.id).rebuild()
mark_dirty()
_end_edit()
var msg := "“%s” now rolls on %s" % [e.text, over.table.name]
if replaced:
msg += " instead of %s" % replaced.name
toast(msg)
toast(msg, true)
func _card_under_mouse() -> TableCard:
@ -697,6 +736,7 @@ var _group_nodes: Dictionary = {} # group id -> GroupCard
var _hidden_cache: Variant = null # table id -> GroupCard, or null when stale
## Ids of the cards being dragged and the group the pointer is over (Build).
var _drag_set: Array[String] = []
var _drag_from: Dictionary = {} # table id -> its position when the drag began
var _drag_over: GroupCard
@ -813,12 +853,12 @@ func toggle_group(gid: String) -> void:
g.collapsed = not g.collapsed
details().hide_for()
_groups_changed()
mark_dirty()
mark_dirty("", false)
if not g.collapsed:
var room := _make_room_for(g, compact, blocks)
if int(room["moved"]) > 0:
toast("Opened %s and moved %d %s to make room" % [Formatter.strip_tags(g.name), room["moved"],
"block" if int(room["moved"]) == 1 else "blocks"], room["snap"])
"block" if int(room["moved"]) == 1 else "blocks"], true)
func set_group_collapsed(gid: String, collapsed: bool) -> void:
@ -862,7 +902,7 @@ func group_selection() -> TableGroup:
if ids.is_empty():
toast("Select some cards first: Ctrl- or Shift-click their headers, or Ctrl-drag on the felt")
return null
var snap := _snapshot()
_begin_edit()
var g := data.add_group(_free_group_name(), ids)
var rects: Array = []
for tid in ids:
@ -872,8 +912,8 @@ func group_selection() -> TableGroup:
# Groups don't nest: emptied groups stay, so they can be refilled or ungrouped.
clear_selection()
_groups_changed()
mark_dirty()
toast("Grouped %d %s as “%s”" % [ids.size(), "card" if ids.size() == 1 else "cards", g.name], snap)
_end_edit()
toast("Grouped %d %s as “%s”" % [ids.size(), "card" if ids.size() == 1 else "cards", g.name], true)
return g
@ -882,11 +922,11 @@ func ungroup(gid: String) -> void:
var g := data.get_group(gid)
if g == null:
return
var snap := _snapshot()
_begin_edit()
data.ungroup(gid)
_groups_changed()
mark_dirty()
toast("Ungrouped “%s”" % Formatter.strip_tags(g.name), snap)
_end_edit()
toast("Ungrouped “%s”" % Formatter.strip_tags(g.name), true)
func confirm_delete_group(gid: String) -> void:
@ -904,7 +944,7 @@ func delete_group(gid: String) -> void:
var g := data.get_group(gid)
if g == null:
return
var snap := _snapshot()
_begin_edit()
var gname := Formatter.strip_tags(g.name)
var gone := data.delete_group(gid)
for tid in gone:
@ -918,8 +958,8 @@ func delete_group(gid: String) -> void:
for c in cards.values():
(c as TableCard).rebuild()
_groups_changed()
mark_dirty()
toast("Deleted “%s” and its %d %s" % [gname, gone.size(), "card" if gone.size() == 1 else "cards"], snap)
_end_edit()
toast("Deleted “%s” and its %d %s" % [gname, gone.size(), "card" if gone.size() == 1 else "cards"], true)
## The group details editor (Build): a card-styled dialog with the text.
@ -937,12 +977,13 @@ func edit_group_details(gid: String) -> void:
d.body.add_child(te)
d.add_button("Cancel", "plain", d.close)
d.add_button("Save", "primary", func() -> void:
_begin_edit()
g.details = te.text.strip_edges()
d.close()
var n := group_node(gid)
if n:
n.rebuild()
mark_dirty()
_end_edit()
)
_add_modal(d)
@ -961,6 +1002,7 @@ func _frame_at(p: Vector2) -> TableGroup:
# ----- Card drags (TableCard calls these) -----
func begin_card_drag(card: TableCard) -> void:
_begin_edit()
_drag_set.clear()
if mode == Mode.BUILD and selection.has(card.table.id) and selection.size() > 1:
for tid: String in selection:
@ -968,8 +1010,10 @@ func begin_card_drag(card: TableCard) -> void:
_drag_set.append(tid)
else:
_drag_set.append(card.table.id)
_drag_from.clear()
# The frames of the dragged cards' groups hold still, so a card can leave them.
for tid in _drag_set:
_drag_from[tid] = data.get_table(tid).position
var g := data.group_of(tid)
if g:
board.groups.frozen[g.id] = true
@ -1025,7 +1069,13 @@ func end_card_drag(_card: TableCard) -> void:
data.remove_from_group(tid)
left += 1
board.groups.frozen.clear()
var moved := false
for tid in _drag_set:
var t := data.get_table(tid)
if t and t.position != _drag_from.get(tid, t.position):
moved = true
_drag_set.clear()
_drag_from.clear()
if not joined.is_empty() or left > 0:
_groups_changed()
var parts := PackedStringArray()
@ -1034,8 +1084,11 @@ func end_card_drag(_card: TableCard) -> void:
if left > 0:
parts.append("took %d out of %s" % [left, "its group" if left == 1 else "their groups"])
var msg := ", ".join(parts)
toast(msg.substr(0, 1).to_upper() + msg.substr(1))
mark_dirty()
_end_edit()
toast(msg.substr(0, 1).to_upper() + msg.substr(1), true)
return
# A click on a header without a drag isn't an edit.
mark_dirty("", moved)
# ----- Selection (Build) -----
@ -1221,7 +1274,7 @@ func begin_template_insert(tpl: Dictionary) -> void:
## outside pipes relinked by name (or dropped and reported). Returns
## TemplateKit.instantiate's result.
func insert_template(tpl: Dictionary, values: Dictionary) -> Dictionary:
var snap := _snapshot()
_begin_edit()
var ext := TemplateKit.extent(tpl)
var center := board.screen_to_world(board.size / 2.0)
var origin := (center - ext / 2.0).round()
@ -1235,7 +1288,7 @@ func insert_template(tpl: Dictionary, values: Dictionary) -> Dictionary:
card.setup(self, t)
cards[t.id] = card
_groups_changed()
mark_dirty()
_end_edit("Insert template %s" % Formatter.strip_tags(str(tpl.get("name", "template"))))
var n := (r["tables"] as Array).size()
var msg := "Inserted “%s” (%d %s)" % [str(tpl.get("name", "template")), n, "card" if n == 1 else "cards"]
var relinked: Array = r["relinked"]
@ -1243,9 +1296,9 @@ func insert_template(tpl: Dictionary, values: Dictionary) -> Dictionary:
msg += " · %d %s relinked by name" % [relinked.size(), "pipe" if relinked.size() == 1 else "pipes"]
var dropped: Array = r["dropped"]
if dropped.is_empty():
toast(msg, snap)
toast(msg, true)
else:
toast(msg + " · %d left out" % dropped.size(), snap)
toast(msg + " · %d left out" % dropped.size(), true)
var d := ModalCard.new("Inserted “%s”" % str(tpl.get("name", "template")), 540.0)
d.body.add_child(ModalCard.note("These pipes led to cards outside the template, and this collection has no card with that name, so they were left out. Lay them again by hand, or rename a card and insert again.", Style.INK))
d.body.add_child(ModalCard.section("Left out (%d)" % dropped.size()))
@ -1718,7 +1771,7 @@ func open_table_settings(table_id: String) -> void:
return
var d := TableSettingsDialog.new(t)
d.template_requested.connect(func() -> void: save_template_from([table_id], "card"))
var snap := _snapshot()
_begin_edit()
d.applied.connect(func(result: Dictionary) -> void:
if result.get("deck_reset", false) and state and data.id != "":
state.clear_deck(data.id, t.id)
@ -1730,9 +1783,9 @@ func open_table_settings(table_id: String) -> void:
var card := card_for(t.id)
if card:
card.rebuild()
mark_dirty()
_end_edit("Edit settings of %s" % Formatter.strip_tags(t.name))
refresh_live()
toast("Updated %s" % t.name, snap)
toast("Updated %s" % t.name, true)
)
_add_modal(d)
@ -1742,6 +1795,7 @@ func open_table_settings(table_id: String) -> void:
func switch_collection(id: String) -> void:
if not collections_enabled() or id == data.id:
return
_commit_edits()
_save_timer.stop()
var b := CollectionSwitcher.switch_collection(library, data, id)
if b == null:
@ -1754,6 +1808,8 @@ func switch_collection(id: String) -> void:
## history (lighting its last roll), rebuilds the cards, fits the view and
## remembers it as the last collection.
func _show_collection(b: TowerBoard) -> void:
# Waiting edits belong to the collection being left.
_commit_edits()
data = b
_token += 1
cancel_choice()
@ -1809,8 +1865,10 @@ func delete_collection() -> void:
var msg := "Delete “%s” and its saved decks, variables and history? This can't be undone." % data.name
_add_modal(ModalCard.confirm("Delete collection", msg, "Delete", func() -> void:
var gone := data.name
var gone_id := data.id
var next := CollectionSwitcher.delete_collection(library, data)
if next:
_histories.erase(gone_id)
_show_collection(next)
toast("Deleted “%s”" % gone)
, true))
@ -2427,6 +2485,7 @@ func _load_board_file(path: String) -> void:
func _run_cli_extras(args: PackedStringArray) -> void:
if args.has("--perf"):
_run_perf()
await _run_undo_cli(args)
_run_nav_cli(args)
if args.has("--clear-result"):
# Keeps the board lit but empties the tray (a tall sheet result can fill it).
@ -2601,7 +2660,12 @@ func open_search() -> SearchPanel:
func _shortcut_input(ev: InputEvent) -> void:
var k := ev as InputEventKey
if k == null or not k.pressed or k.echo:
if k == null or not k.pressed:
return
if _history_shortcut(k):
get_viewport().set_input_as_handled()
return
if k.echo:
return
if k.keycode == KEY_F and (k.ctrl_pressed or k.meta_pressed) and not k.alt_pressed:
open_search()
@ -2628,7 +2692,7 @@ func focus_table(table_id: String, entry_id: String = "") -> void:
if entry_id != "" and t.find_entry(entry_id) == null:
entry_id = ""
var notes := PackedStringArray()
var snap := ""
var undoable := false
var settle := false
var g := data.group_of(table_id)
if g and g.collapsed:
@ -2636,14 +2700,14 @@ func focus_table(table_id: String, entry_id: String = "") -> void:
notes.append("Opened group %s" % Formatter.strip_tags(g.name))
if int(info["moved"]) > 0:
notes.append("moved %d %s to make room" % [info["moved"], "block" if int(info["moved"]) == 1 else "blocks"])
snap = info["snap"]
undoable = true
settle = true
if entry_id != "" and t.collapsed and t.kind != RollTable.KIND_VARIABLE and t.kind != RollTable.KIND_SHEET:
t.collapsed = false
var c0 := card_for(table_id)
if c0:
c0.rebuild()
mark_dirty()
mark_dirty("", false)
settle = true
var card := card_for(table_id)
if card == null:
@ -2663,7 +2727,7 @@ func focus_table(table_id: String, entry_id: String = "") -> void:
board.animate_to(_focus_point(r), _focus_zoom(r))
board.cards.flash(card)
if not notes.is_empty():
toast(", ".join(notes), snap)
toast(", ".join(notes), undoable)
if entry_id != "":
# The list scrolls on the next layout pass; ring the row after it.
await get_tree().process_frame
@ -2717,7 +2781,7 @@ func _focus_point(r: Rect2) -> Vector2:
## Expands a collapsed group (saved) and makes room for it. Returns
## _make_room_for's {moved, snap}.
## _make_room_for's {moved}.
func _expand_group(g: TableGroup) -> Dictionary:
var n := group_node(g.id)
var compact := Rect2(n.position, n.size) if n else Rect2()
@ -2725,7 +2789,7 @@ func _expand_group(g: TableGroup) -> Dictionary:
g.collapsed = false
details().hide_for()
_groups_changed()
mark_dirty()
mark_dirty("", false)
return _make_room_for(g, compact, blocks)
@ -2860,7 +2924,7 @@ func pack_collapsed_groups() -> int:
for b: Dictionary in blocks:
rects.append(b["rect"])
var offsets := BoardLayout.pack(rects, PACK_GAP, PACK_GAP)
var snap := _snapshot()
_begin_edit()
var moved := 0
for i in blocks.size():
var d := offsets[i].round()
@ -2870,8 +2934,8 @@ func pack_collapsed_groups() -> int:
if moved == 0:
toast("Already packed")
return 0
mark_dirty()
toast("Packed the board: moved %d %s" % [moved, "block" if moved == 1 else "blocks"], snap)
_end_edit("Pack collapsed groups")
toast("Packed the board: moved %d %s" % [moved, "block" if moved == 1 else "blocks"], true)
await get_tree().process_frame
await get_tree().process_frame
board.fit()
@ -2881,11 +2945,11 @@ func pack_collapsed_groups() -> int:
## After a group expands in place: if its frame now covers other blocks, they
## shift right or down to clear it (BoardLayout.make_room). `blocks` are the
## other blocks (_layout_blocks) measured before the group expanded, while
## every group card was laid out. Returns {moved, snap}, snap being the board
## before the move (for an undo toast).
## every group card was laid out. Returns {moved}; the move is an undo step
## of its own (expanding the group isn't one).
func _make_room_for(g: TableGroup, compact: Rect2, blocks: Array) -> Dictionary:
if compact.size == Vector2.ZERO or blocks.is_empty():
return {"moved": 0, "snap": ""}
return {"moved": 0}
var grown := g.rect()
var rects: Array = []
var hits := false
@ -2895,8 +2959,8 @@ func _make_room_for(g: TableGroup, compact: Rect2, blocks: Array) -> Dictionary:
if r.intersects(grown):
hits = true
if not hits:
return {"moved": 0, "snap": ""}
var snap := _snapshot()
return {"moved": 0}
_begin_edit()
var offsets := BoardLayout.make_room(rects, compact, grown, PACK_GAP)
var moved := 0
for i in blocks.size():
@ -2905,8 +2969,8 @@ func _make_room_for(g: TableGroup, compact: Rect2, blocks: Array) -> Dictionary:
_move_block(blocks[i], d)
moved += 1
if moved > 0:
mark_dirty()
return {"moved": moved, "snap": snap}
_end_edit("Make room for %s" % Formatter.strip_tags(g.name))
return {"moved": moved}
# ----- Navigation screenshot flags -----
@ -2933,3 +2997,370 @@ func _run_nav_cli(args: PackedStringArray) -> void:
var p := open_search()
p.field.text = q
p.refresh()
# ---------- Undo and redo ----------
# Every change to the saved collection goes through mark_dirty, which records
# an undo step in `edits` (EditHistory; one per collection, kept in memory
# while the app runs, so switching collections and back keeps it). Steps are
# whole-board snapshots, so undo needs nothing from the card editors.
#
# Coalescing: typing in a text field commits once typing pauses for
# EDIT_PAUSE, and later typing in the same field merges into that step until
# focus moves; other edits commit at the end of the frame (a whole drag is one
# step), and repeated edits to the same card or pipe within
# EditHistory.COALESCE_SECS merge. Actions in this file call _begin_edit
# before changing anything (committing pending typing as its own step) and
# _end_edit after, which commits at once.
#
# Collapsing cards and groups is saved but treated as view state: it isn't a
# step, and undo leaves things collapsed or expanded as they are.
#
# Ctrl+Z undoes, Ctrl+Shift+Z or Ctrl+Y redoes, in Build and Play, unless a
# text field has focus (it keeps its own Ctrl+Z for the text being typed) or
# a dialog is open.
const EDIT_PAUSE := 0.8
var edits: EditHistory
var _histories: Dictionary = {} # collection id -> EditHistory
var _edit_timer: Timer
var _edit_pending := false
var _edit_focus := 0
var _commit_queued := false
var _restoring := false
var _keep_history := false
var _undo_button: Button
var _redo_button: Button
func _build_edit_timer() -> void:
_edit_timer = Timer.new()
_edit_timer.one_shot = true
_edit_timer.wait_time = EDIT_PAUSE
_edit_timer.timeout.connect(func() -> void: _commit_edits())
add_child(_edit_timer)
get_viewport().gui_focus_changed.connect(_on_focus_changed)
## Typing in one field and then moving to another makes two steps.
func _on_focus_changed(c: Control) -> void:
if _edit_pending and _edit_focus != 0 and (c == null or c.get_instance_id() != _edit_focus):
_queue_commit()
## Picks this collection's history (making one) and takes the board as its
## baseline; a history whose board changed from outside starts over.
func _sync_history() -> void:
if data == null:
return
if _edit_timer:
_edit_timer.stop()
_edit_pending = false
var h: EditHistory = _histories.get(data.id)
if h == null:
h = EditHistory.new(data)
_histories[data.id] = h
else:
h.resync(data)
edits = h
_update_undo_buttons()
## Before an action changes the board: commits edits still waiting (typing)
## as a step of their own, so the action's step starts from here.
func _begin_edit() -> void:
_commit_edits()
## After an action changed the board: like mark_dirty, but the step is
## committed now (named `label`, or from the change).
func _end_edit(label: String = "") -> void:
_board_changed()
if edits == null or _restoring:
return
_edit_pending = true
_commit_edits(label)
func _queue_commit() -> void:
if not _commit_queued:
_commit_queued = true
_commit_edits.call_deferred()
## Records waiting edits as an undo step now (see EditHistory.commit).
func _commit_edits(label: String = "") -> void:
_commit_queued = false
if _edit_timer:
_edit_timer.stop()
if not _edit_pending or edits == null:
return
_edit_pending = false
var r := edits.commit(data, label, _edit_focus)
if r["step"]:
if _toast_serial >= 0 and edits.top_serial() != _toast_serial:
_toast_serial = -1
_toast_undo.hide()
_update_undo_buttons()
func can_undo() -> bool:
return edits != null and (edits.can_undo() or _edit_pending)
func can_redo() -> bool:
return edits != null and edits.can_redo() and not _edit_pending
## Steps back one edit. Returns false when there was nothing to undo (or it
## has to wait for a roll or a dialog).
func undo() -> bool:
if not _history_ready():
return false
_commit_edits()
if not edits.can_undo():
toast("Nothing to undo")
return false
var e := edits.pop_undo()
_apply_history(e, "Undid")
return true
func redo() -> bool:
if not _history_ready():
return false
_commit_edits()
if not edits.can_redo():
toast("Nothing to redo")
return false
var e := edits.pop_redo()
_apply_history(e, "Redid")
return true
func _history_ready() -> bool:
if edits == null:
return false
if rolling_ctx != null or _choice_waiting("Answer the waiting question first"):
toast("Wait for the roll to finish before undoing")
return false
return true
## Puts the board back to a snapshot from the history, keeping the view, the
## mode, the open search and the lit results of tables that still exist. Only
## what changed is rebuilt (EditHistory.patch, _refresh_patched); cards hidden
## in collapsed groups stay unbuilt.
func _apply_history(e: Dictionary, verb: String) -> void:
var t0 := Time.get_ticks_usec()
var d := EditHistory.diff(e["from"], e["snap"])
_restoring = true
if _pipe_popover and _pipe_popover.visible:
_pipe_popover.hide()
details().hide_for()
board.pipes.hover_key = ""
_drop_card = null
_link_from = {}
clear_selection()
var p := EditHistory.patch(data, e["snap"], e["from"])
if not p.is_empty():
edits.cache = p["snap"]
_refresh_patched(p, d)
else:
edits.cache = EditHistory.restore(data, e["snap"])
_keep_history = true
_rebuild_cards()
_keep_history = false
_restoring = false
_board_changed()
_refresh_lit()
tray.render()
_update_undo_buttons()
toast("%s: %s" % [verb, e["label"]])
_last_restore_usec = Time.get_ticks_usec() - t0
_flash_changes(d)
## After EditHistory.patch: frees the cards of removed tables, rebuilds the
## groups if they changed, builds cards for tables brought back (unless a
## collapsed group hides them) and moves and rebuilds the changed ones. A
## changed variable card rebuilds every card (other cards' effect chips name
## it).
func _refresh_patched(p: Dictionary, d: Dictionary) -> void:
for tid: String in p["removed"]:
var c := card_for(tid)
cards.erase(tid)
if c:
c.get_parent().remove_child(c)
c.queue_free()
if p["groups_changed"]:
_groups_changed()
else:
for gid: String in p["groups"]:
var n := group_node(gid)
if n:
n.sync_rect()
_apply_group_visibility()
var all := false
for tid: String in p["tables"]:
var t := data.get_table(tid)
if t and t.kind == RollTable.KIND_VARIABLE and (d["changed"] as Array).has(tid):
all = true
for tid: String in (cards.keys() if all else p["tables"]):
var c := card_for(tid)
if c == null:
continue
c.position = c.table.position
if all or (d["changed"] as Array).has(tid):
c.rebuild()
_update_collapse_all()
## How long the last undo or redo took to rebuild the board (microseconds).
var _last_restore_usec := 0
## Rings the cards an undo or redo changed, once they have laid out. One
## changed card that's off screen is brought into view (without changing the
## zoom); bigger changes leave the view alone.
func _flash_changes(d: Dictionary) -> void:
for i in 2:
await get_tree().process_frame
var nodes: Array[Control] = []
var hidden := hidden_groups()
for tid: String in EditHistory.touched_tables(d):
var n: Control = card_for(tid)
if n == null:
n = hidden.get(tid)
if n and is_instance_valid(n) and not nodes.has(n):
nodes.append(n)
for gid: String in (d["gadded"] as Array) + (d["gchanged"] as Array):
var n := group_node(gid)
if n and not nodes.has(n):
nodes.append(n)
if nodes.is_empty():
return
var view := board.view_rect()
if nodes.size() == 1 and not view.intersects(Rect2(nodes[0].position, nodes[0].size)):
board.animate_to(Rect2(nodes[0].position, nodes[0].size).get_center(), board.zoom)
view = Rect2()
var shown: Array[Control] = []
for n in nodes:
if view.size == Vector2.ZERO or view.intersects(Rect2(n.position, n.size)):
shown.append(n)
board.cards.flash_all(shown)
func _make_history_buttons(tools: HBoxContainer) -> void:
_undo_button = Style.bar_button("Undo")
_undo_button.pressed.connect(func() -> void: undo())
_bar_icon(_undo_button, func(c: Control) -> void: _draw_turn_arrow(c, false))
_redo_button = Style.bar_button("Redo")
_redo_button.pressed.connect(func() -> void: redo())
_bar_icon(_redo_button, func(c: Control) -> void: _draw_turn_arrow(c, true))
for b in [_undo_button, _redo_button]:
(b as Button).focus_mode = Control.FOCUS_NONE
(b as Button).add_theme_color_override("font_disabled_color", Color(Style.ON_FELT, 0.35))
tools.add_child(b)
## A curved arrow, pointing left (undo) or right (redo).
func _draw_turn_arrow(c: Control, right: bool) -> void:
var b := c.get_parent() as Button
var col := Style.ON_FELT if b == null or not b.disabled else Color(Style.ON_FELT, 0.35)
var s := -1.0 if right else 1.0
var o := Vector2(8, 9)
c.draw_arc(o, 5.0, -PI * 0.95 if not right else -PI * 0.05, PI * 0.5 if not right else -PI * 1.5, 16, col, 1.8, true)
var tip := o + Vector2(-5.0 * s, -0.4)
c.draw_colored_polygon(PackedVector2Array([tip + Vector2(-3.2 * s, -1.0), tip + Vector2(3.2 * s, -1.0), tip + Vector2(0, 3.6)]), col)
func _update_undo_buttons() -> void:
if _undo_button == null:
return
_undo_button.disabled = not can_undo()
_redo_button.disabled = not can_redo()
if edits and edits.can_undo() and not _edit_pending:
_undo_button.tooltip_text = "Undo: %s (Ctrl+Z)" % edits.undo_label()
elif _edit_pending:
_undo_button.tooltip_text = "Undo your latest edit (Ctrl+Z)"
else:
_undo_button.tooltip_text = "Nothing to undo"
_redo_button.tooltip_text = ("Redo: %s (Ctrl+Shift+Z or Ctrl+Y)" % edits.redo_label()) if can_redo() else "Nothing to redo"
for b in [_undo_button, _redo_button]:
for k in (b as Button).get_children():
(k as CanvasItem).queue_redraw()
## True while a dialog (a ModalCard) is open over the board.
func _modal_open() -> bool:
for c in get_children():
if c is ModalCard and (c as ModalCard).visible:
return true
return false
## Ctrl+Z / Ctrl+Shift+Z / Ctrl+Y outside text fields.
func _history_shortcut(k: InputEventKey) -> bool:
if not (k.ctrl_pressed or k.meta_pressed) or k.alt_pressed:
return false
var is_undo := k.keycode == KEY_Z and not k.shift_pressed
var is_redo := (k.keycode == KEY_Z and k.shift_pressed) or (k.keycode == KEY_Y and not k.shift_pressed)
if not is_undo and not is_redo:
return false
var f := get_viewport().gui_get_focus_owner()
if f is LineEdit or f is TextEdit or _modal_open():
return false
if is_undo:
undo()
else:
redo()
return true
# ----- Undo screenshot flags -----
# --undo-demo=<table id> delete that table (or the last one), then undo: the toast says so
# --undo-tooltip make an edit, then hover the Undo button so its tooltip shows
func _run_undo_cli(args: PackedStringArray) -> void:
var demo := _arg_value(args, "--undo-demo")
if args.has("--undo-demo") or demo != "":
set_mode(Mode.BUILD)
var t: RollTable = data.get_table(demo) if demo != "" else (data.tables.back() if not data.tables.is_empty() else null)
if t:
delete_table(t.id)
await get_tree().process_frame
undo()
if args.has("--undo-tooltip"):
set_mode(Mode.BUILD)
if not data.tables.is_empty():
delete_table(data.tables.back().id)
_toast.hide()
for i in 3:
await get_tree().process_frame
var at := _undo_button.get_global_rect().get_center()
get_viewport().notification(NOTIFICATION_VP_MOUSE_ENTER)
for i in 2:
var ev := InputEventMouseMotion.new()
ev.position = at + Vector2(i, 0)
ev.global_position = ev.position
get_viewport().push_input(ev)
await get_tree().process_frame
# ---------- Endless-loop check, debounced ----------
var _endless_timer: Timer
## The endless-loop check walks the whole board (about 30 ms on an 800-card
## board), so edits schedule it to run once typing pauses instead of on every
## keystroke.
func _schedule_endless_check() -> void:
if _endless_timer == null:
_endless_timer = Timer.new()
_endless_timer.one_shot = true
_endless_timer.wait_time = 0.4
_endless_timer.timeout.connect(_update_endless_chip)
add_child(_endless_timer)
_endless_timer.start()

View file

@ -12,6 +12,10 @@ extends PanelContainer
## per case, showing its condition ("if @str >= 8", "Otherwise") with its
## outlet. Live text (values, sheets, prompts) is only re-rendered by
## refresh_live(), which Main calls after rolls and edits, never per frame.
## 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.
const WIDTH := 256.0
## Build mode has more controls per row, so cards are a little wider there.
@ -53,6 +57,10 @@ var _deck_label: Label
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
var _table_details_open := false
## Live parts, updated by refresh_live().
var _prompt_label: RichTextLabel
@ -118,6 +126,7 @@ func rebuild() -> void:
_var_value = null
_var_hint = null
_sheet_label = null
_options_label = null
_live_cache.clear()
var build := main.mode == Main.Mode.BUILD
@ -178,6 +187,8 @@ func rebuild() -> void:
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):
@ -435,6 +446,17 @@ func _make_kind_header(_build: bool) -> Control:
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)
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()
v.add_child(ol)
if not _build:
_options_label = Style.make_label("", Style.body(true), 12, Style.MUTED)
_options_label.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_options_label)
return v
RollTable.KIND_LOOP:
var chip := PanelContainer.new()
@ -480,6 +502,23 @@ static func draw_fork(ci: CanvasItem, c: Vector2, r: float, color: Color, width:
ci.draw_circle(base, width * 0.9, color)
## "Options from @skill_* · where option_value >= 1" for a dynamic pick card.
static func options_line(t: RollTable) -> String:
var s := "Options from " + t.options_from.strip_edges()
if t.options_where.strip_edges() != "":
s += " · where " + t.options_where.strip_edges()
return s
func _is_pick() -> bool:
return table.kind == RollTable.KIND_CHOICE and table.choice == "pick"
## True for the Chosen row of a dynamic pick card.
func _is_chosen_row(index: int) -> bool:
return index == 0 and table.is_dynamic()
## A router case's condition as shown: "if @str >= 8", or "Otherwise".
static func case_label(e: TableEntry) -> String:
var w := e.when.strip_edges()
@ -543,6 +582,7 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
# Loop rows and the Answer row of number/text choices are fixed: no number,
# weight or delete.
var fixed := table.kind == RollTable.KIND_LOOP or (table.kind == RollTable.KIND_CHOICE and table.choice != "pick")
var chosen := _is_chosen_row(index)
var num: Label = null
if build and ranged:
@ -554,7 +594,10 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
r.add_child(_range_edit(e, false))
h.add_child(r)
else:
num = Style.make_label("" if fixed else (str(index + 1) if table.kind == RollTable.KIND_ROUTER else table.num_label(e, index)), Style.display(true), 16, Style.MUTED)
var nl := "" if fixed else (str(index + 1) if table.kind == RollTable.KIND_ROUTER else table.num_label(e, index))
if table.is_dynamic() and not ranged:
nl = "★" if chosen else str(index)
num = Style.make_label(nl, Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(numw, 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = SIZE_SHRINK_CENTER
@ -574,8 +617,21 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
al.tooltip_text = "Its effects and pipes run after the player answers ({answer} holds the answer)"
h.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)
@ -587,14 +643,23 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
e.text = s
main.mark_dirty()
)
h.add_child(edit)
if cbox != null:
cbox.add_child(edit)
else:
h.add_child(edit)
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:
if not fixed and not chosen:
var x := Button.new()
x.text = "×"
x.tooltip_text = "Delete this result"
@ -612,6 +677,11 @@ 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))
h.add_child(col)
@ -798,6 +868,14 @@ func _row_text(e: TableEntry) -> String:
s = cond
else:
s = "%s\n%s" % [cond, s]
elif table.is_dynamic() and table.entries.find(e) == 0:
var own := Formatter.strip_tags(e.text).strip_edges()
if rolled != "":
s = "[color=#%s]Chosen ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
elif own == "" or own == Roller.CHOSEN:
s = "[i][color=#%s]Chosen: the picked option[/color][/i]" % muted
else:
s = "[color=#%s]Chosen ·[/color] %s" % [muted, s]
elif table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
if rolled != "":
s = "[color=#%s]Answer ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
@ -854,6 +932,47 @@ 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()
@ -1014,6 +1133,11 @@ func refresh_live() -> void:
var s := RichText.decorate(Roller.render_sheet(main.data, main.persistent_vars, table))
if _sheet_label.text != s:
_sheet_label.text = s
if is_instance_valid(_options_label):
var n := Roller.available_count(table, Roller.live_context(main.data, main.persistent_vars))
var txt := "No options available now" if n == 0 else ("1 option available now" if n == 1 else "%d options available now" % n)
if _options_label.text != txt:
_options_label.text = txt
if is_instance_valid(_prompt_label):
var p: String
if main.mode == Main.Mode.BUILD:
@ -1166,6 +1290,8 @@ func _update_warning() -> void:
var lines := PackedStringArray()
for item: Dictionary in Roller.lint_router(table):
lines.append(str(item["message"]))
for item: Dictionary in Roller.lint_options(table):
lines.append(str(item["message"]))
if not lines.is_empty():
problems = ("%s\n" % problems if problems != "" else "") + "\n".join(lines)
_warn_label.text = problems

View file

@ -106,6 +106,8 @@ static func summary_line(t: RollTable) -> String:
return "%s (a whole number from %s to %s)" % [ask, t.min_expr, t.max_expr]
"text":
return ask + " (free text)"
if t.is_dynamic():
return "%s\nOptions: %s" % [ask, t.options_description()]
return ask
RollTable.KIND_LOOP:
var e := t.loop_expr.strip_edges()
@ -139,7 +141,14 @@ static func _row(t: RollTable, e: TableEntry, index: int) -> Control:
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)
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"
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
@ -161,7 +170,11 @@ static func _row(t: RollTable, e: TableEntry, index: int) -> Control:
static func row_label(t: RollTable, e: TableEntry, index: int) -> String:
match t.kind:
RollTable.KIND_CHOICE:
return str(index + 1) if t.choice == "pick" else "Answer"
if t.choice != "pick":
return "Answer"
if t.is_dynamic():
return "Chosen" if index == 0 else str(index)
return str(index + 1)
RollTable.KIND_LOOP:
return "Each" if index == 0 else "After"
RollTable.KIND_ROUTER:

View file

@ -42,6 +42,16 @@ var _save_as: LineEdit
var _min: LineEdit
var _max: LineEdit
var _minmax_row: Control
## Pick choices: "fixed" or "vars" (options from variables, plus fixed extras).
var _options_mode := "fixed"
var _options_box: Control
var _opt_mode_box: Control
var _opt_from: LineEdit
var _opt_where: LineEdit
var _opt_note: Label
var _show_if_box: Control
## entry id -> its Show only if field.
var _show_if: Dictionary = {}
var _loop_mode := "times"
var _loop_expr: LineEdit
var _loop_note: Label
@ -63,6 +73,7 @@ const TITLES := {
RollTable.KIND_ROUTER: "Router settings",
}
const CHOICE_LABELS := ["Which option", "How many", "Open ended"]
const OPTION_LABELS := ["Fixed list", "From variables (+ fixed extras)"]
const LOOP_LABELS := ["Times", "While", "Until"]
const LOOP_NOTES := {
"times": "Runs Each time this many times (worked out once), then Afterwards. e.g. 3, @answer, 1d3",
@ -80,6 +91,7 @@ func _init(p_table: RollTable = null) -> void:
_card_mode = table.card_mode
_deck_empty = table.deck_empty
_choice = table.choice
_options_mode = "vars" if table.options_from.strip_edges() != "" else "fixed"
_loop_mode = table.loop_mode
_var_type = table.var_type
_build()
@ -270,6 +282,13 @@ func settings() -> Dictionary:
s["save_as"] = _save_as.text.strip_edges()
s["min"] = _min.text.strip_edges()
s["max"] = _max.text.strip_edges()
s["options_mode"] = _options_mode
s["options_from"] = _opt_from.text.strip_edges()
s["options_where"] = _opt_where.text.strip_edges()
var si := {}
for eid: String in _show_if:
si[eid] = (_show_if[eid] as LineEdit).text.strip_edges()
s["show_if"] = si
RollTable.KIND_LOOP:
s["loop_mode"] = _loop_mode
s["loop_expr"] = _loop_expr.text.strip_edges()
@ -329,6 +348,7 @@ func _build_kind() -> void:
(c as Control).size_flags_horizontal = SIZE_EXPAND_FILL
_minmax_row = mm
box.add_child(mm)
_build_options(box)
RollTable.KIND_LOOP:
box.add_child(section("Repeat"))
box.add_child(segmented(LOOP_LABELS, RollTable.LOOPS.find(_loop_mode), func(i: int) -> void:
@ -403,6 +423,55 @@ func _build_kind() -> void:
body.add_child(box)
## Pick choices: where the options come from, and a Show only if field per
## option.
func _build_options(box: VBoxContainer) -> void:
var mb := VBoxContainer.new()
mb.add_theme_constant_override("separation", 6)
mb.add_child(section("Options"))
mb.add_child(segmented(OPTION_LABELS, 1 if _options_mode == "vars" else 0, func(i: int) -> void:
_options_mode = "vars" if i == 1 else "fixed"
_refresh()
))
box.add_child(mb)
_opt_mode_box = mb
var ob := VBoxContainer.new()
ob.add_theme_constant_override("separation", 8)
_opt_from = LineEdit.new()
_opt_from.text = table.options_from
_opt_from.placeholder_text = "@skill_* or @contacts"
style_line_edit(_opt_from)
_opt_from.text_changed.connect(func(_t: String) -> void: _refresh())
ob.add_child(field("Options from (@prefix_* or a @list)", _opt_from))
_opt_where = LineEdit.new()
_opt_where.text = table.options_where
_opt_where.placeholder_text = "option_value >= 1 (optional)"
style_line_edit(_opt_where)
_opt_where.text_changed.connect(func(_t: String) -> void: _refresh())
ob.add_child(field("Only where (optional)", _opt_where))
_opt_note = note("")
ob.add_child(_opt_note)
box.add_child(ob)
_options_box = ob
var sb := VBoxContainer.new()
sb.add_theme_constant_override("separation", 6)
sb.add_child(section("Show only if"))
sb.add_child(note("Checked when the card is reached. An option whose condition is false isn't offered, not even to Random. Empty means always."))
for i in table.entries.size():
var e := table.entries[i]
var le := LineEdit.new()
le.text = e.show_if
le.placeholder_text = "always"
style_line_edit(le)
le.text_changed.connect(func(_t: String) -> void: _refresh())
_show_if[e.id] = le
var label := Formatter.strip_tags(e.text).strip_edges()
var cap := "Chosen (every option from variables)" if (i == 0 and table.is_dynamic()) else "Option %d%s" % [i + (0 if table.is_dynamic() else 1), (" · " + label) if label != "" else ""]
sb.add_child(field(cap, le))
box.add_child(sb)
_show_if_box = sb
func _refresh_kind() -> void:
var s := settings()
var problems := kind_problems(table, s)
@ -417,12 +486,35 @@ func _refresh_kind() -> void:
msg = "Only the first option is kept, as the Answer row (its effects and pipes stay)."
elif _choice != table.choice and _choice == "pick":
msg = "The Answer row becomes the first option; two more are added."
elif _choice == "pick" and _options_mode == "vars" and table.is_dynamic():
msg = "The player picks one of the options from variables or a fixed extra, or Random."
elif _choice == "pick" and _options_mode == "fixed" and table.is_dynamic():
msg = "Back to a fixed list: the Chosen row becomes an ordinary option (or goes, if it does nothing)."
elif _choice == "pick":
msg = "The player picks one of the card's options, or Random."
else:
msg = "The answer goes in {answer}; the Answer row's effects and pipes run after it."
_choice_note.text = msg
_mark(_save_as, s["save_as"] == "" or _re(SAVE_PATTERN).search(TemplateKit.probe(s["save_as"])) != null)
var pick := _choice == "pick"
_opt_mode_box.visible = pick
_options_box.visible = pick and _options_mode == "vars"
_show_if_box.visible = pick and not _show_if.is_empty()
if pick and _options_mode == "vars":
_mark(_opt_from, options_from_error(s["options_from"]) == "")
_mark(_opt_where, when_error(s["options_where"]) == "")
var desc := RollTable.new()
desc.options_from = s["options_from"]
desc.options_where = s["options_where"]
var how := "One option for %s, labelled with its name and value, after any fixed options. The Chosen row runs for whichever is picked; option, option_label and option_value hold it, e.g. @[option] += 1." % desc.options_description() \
if options_from_error(s["options_from"]) == "" else "Write @skill_* for each set variable with that prefix, or @contacts for each item of a list."
if not table.is_dynamic():
how += " A Chosen row is added first; the options already on the card stay as fixed extras."
_opt_note.text = how
elif pick and table.is_dynamic():
_opt_note.text = ""
for eid: String in _show_if:
_mark(_show_if[eid] as LineEdit, when_error((_show_if[eid] as LineEdit).text) == "")
_mark(_min, Expr.check(TemplateKit.probe(s["min"])) == "" and s["min"] != "")
_mark(_max, Expr.check(TemplateKit.probe(s["max"])) == "" and s["max"] != "")
RollTable.KIND_LOOP:
@ -521,6 +613,21 @@ static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
var save := TemplateKit.probe(str(s.get("save_as", t.save_as)).strip_edges())
if save != "" and _re(SAVE_PATTERN).search(save) == null:
out.append("Save as: use a name like career, or @career to keep it.")
if str(s.get("choice", t.choice)) == "pick":
if str(s.get("options_mode", "vars" if t.options_from != "" else "fixed")) == "vars":
var ferr := options_from_error(str(s.get("options_from", t.options_from)))
if ferr != "":
out.append("Options from: " + ferr)
var werr := when_error(str(s.get("options_where", t.options_where)))
if werr != "":
out.append("Only where: " + werr)
var si: Dictionary = s.get("show_if", {})
for eid: String in si:
var serr := when_error(str(si[eid]))
if serr != "":
var e := t.find_entry(eid)
var at := t.entries.find(e) if e != null else -1
out.append("Show only if (%s): %s" % [("option %d" % (at + 1)) if at >= 0 else eid, serr])
if str(s.get("choice", t.choice)) == "number":
for k in [["min", "Lowest"], ["max", "Highest"]]:
var src := TemplateKit.probe(str(s.get(k[0], "")).strip_edges())
@ -555,6 +662,14 @@ static func when_error(src: String) -> String:
return Expr.check(src) if src != "" else ""
## "" when an options_from pattern is usable, else why not ("" is refused).
static func options_from_error(src: String) -> String:
src = TemplateKit.probe(src.strip_edges())
if src == "":
return "write @prefix_* or @list"
return str(RollTable.parse_options_from(src)["error"])
## A hint about the order of router cases (an Otherwise that isn't last), or "".
static func router_hint(cases: Array) -> String:
for i in cases.size():
@ -612,6 +727,16 @@ static func _apply_kind(t: RollTable, s: Dictionary) -> void:
t.choice = c
t.prompt = str(s.get("prompt", t.prompt))
t.save_as = str(s.get("save_as", t.save_as)).strip_edges()
var si: Dictionary = s.get("show_if", {})
for eid: String in si:
var se := t.find_entry(eid)
if se != null:
se.show_if = str(si[eid]).strip_edges()
if t.choice != "pick":
t.options_from = ""
t.options_where = ""
elif s.has("options_mode"):
_apply_options(t, str(s["options_mode"]) == "vars", str(s.get("options_from", "")), str(s.get("options_where", "")))
if t.choice == "number":
t.min_expr = str(s.get("min", t.min_expr)).strip_edges()
t.max_expr = str(s.get("max", t.max_expr)).strip_edges()
@ -637,6 +762,36 @@ static func _apply_kind(t: RollTable, s: Dictionary) -> void:
t.entries[0].text = str(s["template"])
## Switches a pick card between a fixed list and options from variables.
## Turning variables on adds a Chosen entry first (untouched default
## "Option N" entries go; anything else stays as a fixed extra). Turning them
## off makes the Chosen entry an ordinary option, or drops it if it does
## nothing (no effects, pipes, details or text of its own).
static func _apply_options(t: RollTable, on: bool, from: String, where: String) -> void:
if on:
if not t.is_dynamic():
var keep: Array[TableEntry] = []
for e in t.entries:
var blank := e.effects.strip_edges() == "" and e.pipes.is_empty() and e.details.strip_edges() == "" \
and e.show_if.strip_edges() == "" and RegEx.create_from_string("^Option \\d+$").search(e.text.strip_edges()) != null
if not blank:
keep.append(e)
t.entries = keep
t.entries.insert(0, TableEntry.new(TowerBoard.new_id("e"), Roller.CHOSEN))
t.options_from = from.strip_edges()
t.options_where = where.strip_edges()
return
if t.is_dynamic() and not t.entries.is_empty():
var c := t.entries[0]
var txt := Formatter.strip_tags(c.text).strip_edges()
if c.effects.strip_edges() == "" and c.pipes.is_empty() and c.details.strip_edges() == "" and (txt == "" or txt == Roller.CHOSEN):
t.entries.remove_at(0)
t.options_from = ""
t.options_where = ""
if t.entries.is_empty():
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option 1"))
# ---------- Pure editing logic ----------
## Wraps text[sel.x:sel.y] in open/close_tag. With an empty range, inserts the