Compare commits

..

9 commits

Author SHA1 Message Date
6208e42f75 Docs: architecture map for the split files, shared builders, history
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:21:46 -06:00
0f3e8c278f Remove duplicated code found by the coderstanding audit
- Style.menu_button / font_colors / field_colors replace five copies of the
  "copy a bar button's skin onto a MenuButton" block, nine single-colour
  font loops and four field colour blocks.
- GroupCard uses TableCard.vbox/hbox instead of its own copies.
- InspectorKit.focused_tag / clear / refocus / as_text_link replace the
  focus-keeping render frame and "Edit as text" link shared by the
  condition and effects builders.
- InspectorCard._setting_line replaces three copies of a bound setting field.
- Main.file_dialog / export_dialog replace four FileDialog setups.
- JsonIO.entry_line / finish_import replace copies in canvas_io,
  dot_exporter and graphml_io.
- Dead code: TableCard's unused inline-editor fields and the no-op
  --edit-details / --edit-effects flags, an unused error counter in the
  tray, and an unreachable "settings not available" fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:21:26 -06:00
26ed4a5cbe Merge branch 'split-main' into token-diet
# Conflicts:
#	tests/test_logic_ui.gd
2026-11-09 08:15:52 -06:00
0202312688 Split ui/main.gd into area helpers (no behaviour change)
Main (3679 lines) becomes a shell: shared state, start-up, cards, input,
rules view and one-line delegators for the methods other files call. Each
area moves with its state into a RefCounted helper holding a back-reference
(m: Main):

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:14:19 -06:00
59ea771825 Merge branch 'split-table-card' into token-diet 2026-11-09 08:11:16 -06:00
d05109e941 Split TableCard into header, rows, editing, value-body and text helpers
ui/table_card.gd keeps the card node (setup, rebuild, styling, selection,
highlights API, geometry, drag input) and delegates to RefCounted helpers
that own their own state: TableCardHeader, TableCardRows, TableCardEditing,
TableCardValue, plus static TableCardText. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:10:57 -06:00
35dbdcf435 Merge branch 'split-dialogs' into token-diet 2026-11-09 08:07:51 -06:00
9d601ea570 Split TableSettingsDialog and ResultTray into smaller files
TableSettingsDialog keeps the common fields; its static editing rules move
to TableSettingsRules and the kind-specific fields to SettingsKindFields.
ResultTray keeps the layout and render loop; chip builders move to
TrayChips, captions and effect lines to TrayText, and the Earlier tab to
EarlierRolls. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:07:31 -06:00
bb75837131 Split core/roller.gd into RollPipes, RollCards, RollChoice, RollTree and RollLint
The execution loop, node helpers and live display stay in Roller; every
Roller function and constant used elsewhere keeps a one-line delegator.
No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:05:46 -06:00
85 changed files with 7517 additions and 6996 deletions

View file

@ -155,7 +155,7 @@ tools/test_window.sh -- --screenshot=/tmp/board.png [--build] [--expand-all] [--
Logic-card views: `--board=examples/logic_demo.json --roll=start "--answers=Brin|3"` answers
the first questions and leaves the next pop-up open; `--menu=add`, `--open-settings=<id>`,
`--edit-effects=<id>`, `--demo-long=<n>` (a chain of n steps) and `--confirm-reset` show the
`--demo-long=<n>` (a chain of n steps) and `--confirm-reset` show the
rest.
Test board: `--test-board` opens the dialog, `--test-board-run=<runs>` also starts a run.

267
core/roll_cards.gd Normal file
View file

@ -0,0 +1,267 @@
class_name RollCards
extends RefCounted
## How the Roller runs each card kind other than choices: a plain roll's pick
## (card mode, ranges or weights), routers, checks and loops. The handlers
## build nodes with Roller's node helpers and push frames on its work stack.
## Rolls an entry the normal way (card mode, ranges or weights). Returns a node
## with no children yet, or a stop node.
static func pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
var rng := ctx.rng
var index: int
var value: int
var reshuffled := false
var fact: Dictionary
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]
if deck.cards_left(t).y <= 0:
return Roller._stop(t, "This table has no results")
if deck.cards_left(t).x <= 0:
if t.deck_empty == "stop":
return Roller._stop(t, "Deck empty")
deck.reshuffle()
reshuffled = true
var card := deck.draw(t, rng)
index = int(card["index"])
value = int(card["value"])
fact = {"type": "roll", "pick": "card", "dice": t.dice_label(), "total": value}
elif t.is_ranged():
var was: Variant = ctx.faces
ctx.faces = []
var rv := t.roll_value(ctx)
var faces: Array = ctx.faces
ctx.faces = was
if was != null:
(was as Array).append_array(faces)
if rv["error"] != "":
return Roller._stop(t, "Can't roll %s: %s" % [t.dice, rv["error"]])
value = int(rv["value"])
fact = {"type": "roll", "pick": "dice", "dice": t.dice.strip_edges(), "faces": faces, "total": value}
if not faces.is_empty():
var nat := 0
for x: int in faces:
nat += x
fact["nat"] = nat
fact["mod"] = value - nat
index = t.entry_index_clamped(value) if t.is_expr_dice() else t.entry_index_for(value)
if index < 0:
return Roller._stop(t, "No result for %s" % t.fmt(value), {"value": value})
else:
index = pick_weighted(t, rng)
if index < 0:
return Roller._stop(t, "No result can come up")
value = index + 1
fact = {"type": "roll", "pick": "weighted", "dice": t.dice_label(), "total": value}
var node := {"table": t, "index": index, "value": value, "entry": t.entries[index], "children": [],
"summary": "", "why": [fact]}
if reshuffled:
node["reshuffled"] = true
# "nat" for the caller (Roller._do_roll sets the chain value and drops the key):
# the dice alone, or a plain table's die value. An expression without
# dice ("@terms") has none.
if fact.has("nat"):
node["nat"] = fact["nat"]
elif str(fact["pick"]) != "dice":
node["nat"] = value
return node
## Index of a weighted random entry, or -1 if every weight is 0.
static func pick_weighted(t: RollTable, rng: RandomNumberGenerator) -> int:
var total := t.total_weight()
if total <= 0:
return -1
var pick := rng.randi_range(0, total - 1)
for i in t.entries.size():
pick -= maxi(0, t.entries[i].weight)
if pick < 0:
return i
return -1
# ---------- Routers ----------
## The index of the first router case whose condition is true (an empty
## condition, the Otherwise case, always matches), or -1. Errors count as
## false and add a line to `log`. `why` gets one fact per case tried:
## {"type": "case", "index", "expr" ("" for Otherwise), "values", "result",
## "error"?}.
static func route(t: RollTable, ctx: RollContext, log: Array = [], why: Array = []) -> int:
for k in t.entries.size():
var w := t.entries[k].when.strip_edges()
if w == "":
why.append({"type": "case", "index": k, "expr": "", "values": {}, "result": true})
return k
var r := Expr.evaluate(w, ctx)
var fact := {"type": "case", "index": k, "expr": w, "values": Expr.values_read(w, ctx), "result": false}
why.append(fact)
if r["error"] != "":
log.append({"text": "Case %s: %s" % [w, r["error"]], "error": true})
fact["error"] = str(r["error"])
elif Expr.truthy(r["value"]):
fact["result"] = true
return k
return -1
static func do_router(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var log: Array = []
var why: Array = []
var k := route(t, ctx, log, why)
if k < 0:
var stop := Roller._stop(t, Roller.NO_CASE, {"kind": RollTable.KIND_ROUTER})
Roller._log(stop, log)
Roller._why(stop, why)
Roller._attach(f, stop, ctx)
return
var node := {"table": t, "index": k, "entry": t.entries[k], "children": [], "summary": "",
"kind": RollTable.KIND_ROUTER, "case": k}
Roller._log(node, log)
Roller._why(node, why)
Roller._attach(f, node, ctx)
await Roller._enter(node, f, ctx, stack)
# ---------- Checks ----------
## Rolls a check card's dice, modifier and target (docs/PLAIN.md §4.1):
## {"nat", "mod", "total", "target", "success", "faces" (the dice faces),
## "error" ("" when fine)}. An empty modifier is 0. Numbers are whole
## (floored).
static func check_roll(t: RollTable, ctx: RollContext) -> Dictionary:
var out := {"nat": 0, "mod": 0, "total": 0, "target": 0, "success": false, "faces": [], "error": ""}
var was: Variant = ctx.faces
ctx.faces = []
var r := Expr.evaluate(t.check_dice, ctx)
var faces: Array = ctx.faces
ctx.faces = was
if was != null:
(was as Array).append_array(faces)
out["faces"] = faces
if r["error"] != "":
out["error"] = "Check dice %s: %s" % [t.check_dice, r["error"]]
return out
if not Expr.is_number(r["value"]):
out["error"] = "Check dice %s gave \"%s\", not a number" % [t.check_dice, Expr.format_value(r["value"])]
return out
var nat := Expr.as_int(r, 0)
var mod := 0
if t.check_mod.strip_edges() != "":
var m := Expr.evaluate(t.check_mod, ctx)
if m["error"] != "" or not Expr.is_number(m["value"]):
out["error"] = "Check modifier %s: %s" % [t.check_mod, m["error"] if m["error"] != "" else "not a number"]
return out
mod = Expr.as_int(m, 0)
var g := Expr.evaluate(t.check_target, ctx)
if g["error"] != "" or not Expr.is_number(g["value"]):
out["error"] = "Check target %s: %s" % [t.check_target, g["error"] if g["error"] != "" else "not a number"]
return out
var target := Expr.as_int(g, 0)
var total := nat + mod
out["nat"] = nat
out["mod"] = mod
out["total"] = total
out["target"] = target
out["success"] = total <= target if t.check_cmp == "le" else total >= target
return out
static func do_check(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var c := check_roll(t, ctx)
if str(c["error"]) != "":
var stop := Roller._stop(t, "Can't roll the check: %s" % c["error"], {"kind": RollTable.KIND_CHECK})
stop["effects"] = [{"text": str(c["error"]), "error": true}]
Roller._attach(f, stop, ctx)
return
ctx.chain_vars["nat"] = c["nat"]
ctx.chain_vars["total"] = c["total"]
ctx.chain_vars["effect"] = int(c["total"]) - int(c["target"])
var k := 0 if c["success"] else 1
var info := {"nat": c["nat"], "mod": c["mod"], "total": c["total"], "target": c["target"], "success": c["success"]}
var fact := {"type": "check", "dice": t.check_dice.strip_edges(), "mod_expr": t.check_mod.strip_edges(),
"target_expr": t.check_target.strip_edges(), "faces": c["faces"], "nat": c["nat"], "mod": c["mod"],
"total": c["total"], "target": c["target"], "cmp": t.check_cmp, "success": c["success"]}
if k >= t.entries.size():
var none := Roller._stop(t, "This check has no Failure result", {"kind": RollTable.KIND_CHECK, "check": info, "value": c["total"]})
Roller._why(none, [fact])
Roller._attach(f, none, ctx)
return
var node := {"table": t, "index": k, "entry": t.entries[k], "value": c["total"], "children": [], "summary": "",
"kind": RollTable.KIND_CHECK, "check": info, "why": [fact]}
Roller._attach(f, node, ctx)
await Roller._enter(node, f, ctx, stack)
# ---------- Loops ----------
static func _repeated(n: int) -> String:
return "Repeated 1 time" if n == 1 else "Repeated %d times" % n
static func start_loop(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var header := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": _repeated(0),
"kind": RollTable.KIND_LOOP, "passes": 0}
Roller._attach(f, header, ctx)
var total := 0
if t.loop_mode == "times":
var r := Expr.evaluate(t.loop_expr, ctx)
if r["error"] != "":
header["effects"] = [{"text": "Repeat %s: %s" % [t.loop_expr, r["error"]], "error": true}]
else:
total = maxi(0, Expr.as_int(r, 0))
stack.append({"op": Roller.OP_LOOP, "node": header, "table": t, "i": 0, "total": total, "depth": f.get("depth", 0),
"save": f.get("save", ""), "had_i": ctx.chain_vars.has("i"), "prev_i": ctx.chain_vars.get("i")})
## 1 true, 0 false, -1 error (logged on the header).
static func _cond(t: RollTable, header: Dictionary, ctx: RollContext) -> int:
var r := Expr.evaluate(t.loop_expr, ctx)
if r["error"] != "":
if not header.has("effects"):
header["effects"] = []
(header["effects"] as Array).append({"text": "%s %s: %s" % [t.loop_mode.capitalize(), t.loop_expr, r["error"]], "error": true})
return -1
return 1 if Expr.truthy(r["value"]) else 0
static func do_loop(f: Dictionary, ctx: RollContext, stack: Array) -> void:
var t: RollTable = f["table"]
var header: Dictionary = f["node"]
var i := int(f["i"])
var go := false
match t.loop_mode:
"times":
go = i < int(f["total"])
"while":
go = _cond(t, header, ctx) == 1
"until":
go = i == 0 or _cond(t, header, ctx) == 0
if go:
if not Roller._take_action({"parent": header}, t, ctx):
return
i += 1
f["i"] = i
ctx.chain_vars["i"] = i
header["passes"] = i
header["summary"] = _repeated(i)
var pass_node := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "",
"kind": RollTable.KIND_LOOP, "pass": i, "value": i}
(header["children"] as Array).append(pass_node)
stack.append(f)
await Roller._enter(pass_node, {"depth": f["depth"]}, ctx, stack)
return
if f["had_i"]:
ctx.chain_vars["i"] = f["prev_i"]
else:
ctx.chain_vars.erase("i")
if str(f["save"]) != "":
ctx.save(str(f["save"]), i, t.id)
if t.entries.size() > 1:
var after := {"table": t, "index": 1, "entry": t.entries[1], "children": [], "summary": "",
"kind": RollTable.KIND_LOOP, "after": true}
(header["children"] as Array).append(after)
await Roller._enter(after, {"depth": f["depth"]}, ctx, stack)

1
core/roll_cards.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://34tk0cnvk0xc

260
core/roll_choice.gd Normal file
View file

@ -0,0 +1,260 @@
class_name RollChoice
extends RefCounted
## Choice cards for the Roller: the prompt request, show_if and dynamic
## options (options_from / options_where), asking the player, and running the
## answer.
## The prompt request for a choice card (docs/LOGIC.md §8):
## {table_id, kind ("pick" | "number" | "text"), title, prompt (BBCode,
## 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 why: Array = []
var hidden := 0
var chosen_hidden := false
if t.choice == "pick":
var ranged := t.is_ranged()
for k in range(t.fixed_start(), t.entries.size()):
var e := t.entries[k]
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 not option_shown(t.entries[0], ctx, log):
chosen_hidden = true
elif t.is_dynamic() and not t.entries.is_empty():
var chosen := t.entries[0]
var cands := dynamic_options(t, ctx, log, why)
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
if t.choice == "number":
def = lo
elif t.choice == "text":
def = ""
if hidden > 0 or chosen_hidden:
why.push_front({"type": "show_if", "hidden": hidden, "chosen_hidden": chosen_hidden})
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, "log": log, "hidden": hidden, "why": why}
## 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`. With a filter, `why` gets
## {"type": "options_where", "from", "expr", "kept", "total"}.
static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = [], why: 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)
why.append({"type": "options_where", "from": t.options_from.strip_edges(), "expr": where, "kept": out.size(), "total": cands.size()})
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, ""
## for text.
static func default_reply(req: Dictionary) -> Variant:
match str(req.get("kind", "pick")):
"number":
return int(req.get("min", 0))
"text":
return ""
return -1
## Asks the player through ctx.prompt, or gives the headless answer.
static func ask(ctx: RollContext, req: Dictionary) -> Variant:
if ctx.no_prompt or not ctx.prompt.is_valid():
return default_reply(req)
return await ctx.prompt.call(req)
static func run(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 := Roller._stop(t, Roller.NO_OPTIONS, {"kind": RollTable.KIND_CHOICE})
Roller._log(none, req["log"])
Roller._why(none, req["why"])
Roller._attach(f, none, ctx)
return
var reply: Variant = await ask(ctx, req)
if reply == null:
Roller._attach(f, Roller._stop(t, Roller.CANCELLED, {"kind": RollTable.KIND_CHOICE, "cancelled": true}), ctx)
ctx.halted = Roller.CANCELLED
return
match t.choice:
"number":
var v := int(req["min"])
if reply is int or reply is float:
v = int(reply)
elif reply is String and (reply as String).strip_edges().is_valid_int():
v = (reply as String).strip_edges().to_int()
v = clampi(v, int(req["min"]), int(req["max"]))
await _answered(t, f, ctx, stack, v, str(v))
"text":
var s := str(reply)
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 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 = RollCards.pick_node(t, ctx)
node.erase("nat")
node["random"] = true
else:
var k := _pick_option(opts, ctx.rng)
if k < 0:
node = Roller._stop(t, "No result can come up")
else:
node = _option_node(t, opts[k], ctx)
node["random"] = true
node["kind"] = RollTable.KIND_CHOICE
Roller._log(node, req["log"])
Roller._why(node, req["why"])
Roller._attach(f, node, ctx)
if node.has("stop"):
return
await Roller._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 != "":
ctx.save(t.save_as, value, t.id)
var node := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": summary,
"kind": RollTable.KIND_CHOICE, "answer": value}
Roller._attach(f, node, ctx)
await Roller._enter(node, f, ctx, stack, false)

1
core/roll_choice.gd.uid Normal file
View file

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

231
core/roll_lint.gd Normal file
View file

@ -0,0 +1,231 @@
class_name RollLint
extends RefCounted
## Static checks of a board for the Roller's logic, nothing rolled: endless
## pipe cycles and the lint_* problem lists.
## Ids of tables that can never finish rolling: every result they can give
## leads, through pipes, back into such a table. A table that loops on only
## some of its entries is fine, and so is a pipe whose count is an expression
## (it may come to 0) or a conditional pipe (it may not run).
static func endless_cycles(board: TowerBoard) -> Array[String]:
var done := {}
var changed := true
while changed:
changed = false
for t in board.tables:
if done.has(t.id):
continue
if _can_finish(t, board, done):
done[t.id] = true
changed = true
var out: Array[String] = []
for t in board.tables:
if not done.has(t.id):
out.append(t.id)
return out
static func _entry_finishes(e: TableEntry, board: TowerBoard, done: Dictionary) -> bool:
for p in e.pipes:
if e.count_expr(p) != "" or e.is_conditional(p):
continue
if board.get_table(p) != null and not done.has(p):
return false
return true
static func _can_finish(t: RollTable, board: TowerBoard, done: Dictionary) -> bool:
if t.entries.is_empty() or t.kind == RollTable.KIND_VARIABLE:
return true
if t.kind == RollTable.KIND_LOOP:
# Every entry runs (a while/until loop ends on its condition).
for e in t.entries:
if not _entry_finishes(e, board, done):
return false
return true
var player := t.kind != RollTable.KIND_ROLL
for e in t.entries:
if not player and not t.can_come_up(e):
continue
if _entry_finishes(e, board, done):
return true
if player:
return false
# No entry can come up at all: the roll just stops.
for e in t.entries:
if t.can_come_up(e):
return false
return true
## Problems with conditional pipes and router cards, for a board check. Pure:
## nothing is rolled. Each item: {table_id, entry_id ("" for the whole card),
## message}.
## - a pipe condition, or a router case condition, that doesn't parse
## - an entry whose "otherwise" pipe comes before one of its conditional
## pipes (a hint: it still works, since the snapshot is taken first)
## - an "otherwise" pipe on an entry with no conditional pipe (always runs)
## - a router with no cases, or whose Otherwise case isn't the last one
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))
out.append_array(lint_check(t))
out.append_array(lint_inputs(board, t))
for i in t.entries.size():
var e := t.entries[i]
var first_other := ""
var has_when := false
var warned := false
for p in e.pipes:
var pw := e.when_for(p)
if pw != "":
has_when = true
if Expr.check(pw) != "":
out.append({"table_id": t.id, "entry_id": e.id,
"message": "Pipe condition %s: %s" % [pw, Expr.check(pw)]})
if first_other != "" and not warned:
warned = true
out.append({"table_id": t.id, "entry_id": e.id,
"message": "The otherwise pipe to %s comes before a conditional pipe; put it last so it reads in order" % _table_name(board, first_other)})
elif e.is_otherwise(p) and first_other == "":
first_other = p
if first_other != "" and not has_when:
out.append({"table_id": t.id, "entry_id": e.id,
"message": "The otherwise pipe to %s always runs: no pipe on this entry has a condition" % _table_name(board, first_other)})
return out
## The router part of lint_pipes() for one card (empty for other kinds): no
## cases, an Otherwise case that isn't last, case conditions that don't parse.
static func lint_router(t: RollTable) -> Array[Dictionary]:
var out: Array[Dictionary] = []
if t.kind != RollTable.KIND_ROUTER:
return out
if t.entries.is_empty():
out.append({"table_id": t.id, "entry_id": "", "message": "This router has no cases"})
for i in t.entries.size():
var e := t.entries[i]
var w := e.when.strip_edges()
if w == "":
if i < t.entries.size() - 1:
out.append({"table_id": t.id, "entry_id": e.id,
"message": "The Otherwise case isn't last, so the cases after it can never be chosen"})
elif Expr.check(w) != "":
out.append({"table_id": t.id, "entry_id": e.id, "message": "Case %s: %s" % [w, Expr.check(w)]})
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
## Problems with a check card (empty for other kinds): dice, modifier or
## target expressions that don't parse or are empty, and a missing Success or
## Failure result. Items also carry "kind": "check" and "level": "error".
static func lint_check(t: RollTable) -> Array[Dictionary]:
var out: Array[Dictionary] = []
if t.kind != RollTable.KIND_CHECK:
return out
for pair: Array in [["Check dice", t.check_dice], ["Check modifier", t.check_mod], ["Check target", t.check_target]]:
var src := str(pair[1]).strip_edges()
var msg := ""
if src == "":
if pair[0] != "Check modifier":
msg = "%s is empty" % pair[0]
elif Expr.check(src) != "":
msg = "%s %s: %s" % [pair[0], src, Expr.check(src)]
if msg != "":
out.append({"table_id": t.id, "entry_id": "", "message": msg, "kind": "check", "level": "error"})
if t.entries.size() < 2:
out.append({"table_id": t.id, "entry_id": "", "kind": "check", "level": "error",
"message": "A check needs a Success result and a Failure result"})
return out
## Problems with card inputs and the pipes that pass them (docs/PLAIN.md
## §4.2): declared inputs with a bad or repeated name or a default that
## doesn't parse ("level": "error"), pipe "with" expressions that don't parse
## (error), and a "with" naming an input the target doesn't declare
## ("level": "hint": it still works, as a chain value). Items carry "kind":
## "inputs".
static func lint_inputs(board: TowerBoard, t: RollTable) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var seen := {}
for inp: Dictionary in t.inputs:
var nm := str(inp.get("name", ""))
if not _is_name(nm):
out.append({"table_id": t.id, "entry_id": "", "kind": "inputs", "level": "error",
"message": "Input \"%s\" isn't a name (lowercase letters, digits and _)" % nm})
elif seen.has(nm):
out.append({"table_id": t.id, "entry_id": "", "kind": "inputs", "level": "error",
"message": "Input %s is declared twice" % nm})
seen[nm] = true
var def := str(inp.get("default", "")).strip_edges()
if def != "" and Expr.check(def) != "":
out.append({"table_id": t.id, "entry_id": "", "kind": "inputs", "level": "error",
"message": "Input %s default %s: %s" % [nm, def, Expr.check(def)]})
for e in t.entries:
if e.pipe_with.is_empty():
continue
for p in e.pipes:
var w := e.with_for(p)
if w.is_empty():
continue
var target := board.get_table(p)
for nm: String in w:
var src := str(w[nm])
if Expr.check(src) != "":
out.append({"table_id": t.id, "entry_id": e.id, "kind": "inputs", "level": "error",
"message": "Pipe input %s = %s: %s" % [nm, src, Expr.check(src)]})
if target != null and target.find_input(nm).is_empty():
out.append({"table_id": t.id, "entry_id": e.id, "kind": "inputs", "level": "hint",
"message": "The pipe to %s passes %s, but that card has no input called %s" % [_table_name(board, p), nm, nm]})
return out
static var _name_re: RegEx = null
static func _is_name(s: String) -> bool:
if _name_re == null:
_name_re = RegEx.create_from_string("^[a-z_][a-z0-9_]*$")
return _name_re.search(s) != null
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

1
core/roll_lint.gd.uid Normal file
View file

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

125
core/roll_pipes.gd Normal file
View file

@ -0,0 +1,125 @@
class_name RollPipes
extends RefCounted
## Pipe snapshots and card inputs for the Roller: what an entry's pipes do
## (pipe_plan()), the values they pass, and binding a card's inputs for the
## subtree it runs.
## The snapshot of an entry's pipes, taken once after the entry's effects ran
## and its text expanded: one item per pipe, in pipe order,
## {"to": table id, "run": bool, "count": int, "with": {name: value}} ("with"
## only on a pipe that runs and passes input values; a value whose expression
## fails is left out, so the target's default applies, with an error line).
## - A pipe with a condition ("when") runs only if it's true. An error
## counts as false and adds an error line to `log`.
## - An "otherwise" pipe runs only if none of the entry's conditions was true.
## - Any other pipe always runs.
## Counts are worked out only for pipes that run (0 for the others); an
## expression count's error gives 0 and an error line. `why` gets the trace
## facts: {"type": "when", "to", "expr", "values": {name: value}, "result":
## bool, "error"?} per conditional pipe and {"type": "otherwise", "to",
## "result"} per otherwise pipe.
static func pipe_plan(e: TableEntry, ctx: RollContext, log: Array = [], why: Array = []) -> Array:
var plan: Array = []
var any_true := false
for p in e.pipes:
var w := e.when_for(p)
var run := true
if w != "":
var r := Expr.evaluate(w, ctx)
var fact := {"type": "when", "to": p, "expr": w, "values": Expr.values_read(w, ctx), "result": false}
if r["error"] != "":
log.append({"text": "Pipe condition %s: %s" % [w, r["error"]], "error": true})
run = false
fact["error"] = str(r["error"])
else:
run = Expr.truthy(r["value"])
fact["result"] = run
why.append(fact)
any_true = any_true or run
plan.append({"to": p, "run": run, "count": 0, "otherwise": w == "" and e.is_otherwise(p)})
for item: Dictionary in plan:
if item["otherwise"]:
item["run"] = not any_true
why.append({"type": "otherwise", "to": item["to"], "result": item["run"]})
item.erase("otherwise")
if item["run"]:
item["count"] = e.count_value(str(item["to"]), ctx, log)
if not e.pipe_with.is_empty() and e.pipe_with.has(item["to"]):
item["with"] = with_values(e, str(item["to"]), ctx, log)
return plan
## The input values a pipe passes, worked out now: {name: value}. A value
## whose expression fails is left out (the target's default applies) and adds
## an error line to `log`.
static func with_values(e: TableEntry, target: String, ctx: RollContext, log: Array = []) -> Dictionary:
var out := {}
var w: Variant = e.pipe_with.get(target)
if not (w is Dictionary):
return out
for nm: String in w:
var src := str(w[nm])
var r := Expr.evaluate(src, ctx)
if r["error"] != "":
log.append({"text": "Pipe input %s = %s: %s" % [nm, src, r["error"]], "error": true})
else:
out[nm] = Expr.normalize(r["value"])
return out
# ---------- Card inputs ----------
## Binds a card's inputs as chain values for the subtree about to run: the
## pipe's "with" values (f["with"]), and each declared input's default for the
## rest. Pushes a Roller.OP_RESTORE frame first, so the previous values come
## back when the subtree ends. The trace facts and error lines go on the node
## via Roller._attach().
static func bind_inputs(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var given: Dictionary = f.get("with", {})
if t.inputs.is_empty() and given.is_empty():
return
var values := {}
var facts: Array = []
var log: Array = []
for inp: Dictionary in t.inputs:
var nm := str(inp.get("name", ""))
if nm == "" or values.has(nm):
continue
if given.has(nm):
values[nm] = given[nm]
facts.append({"type": "input", "name": nm, "value": given[nm], "from": "pipe"})
continue
var def := str(inp.get("default", "")).strip_edges()
var v: Variant = 0
if def != "":
var r := Expr.evaluate(def, ctx)
if r["error"] != "":
log.append({"text": "Input %s default %s: %s" % [nm, def, r["error"]], "error": true})
else:
v = Expr.normalize(r["value"])
values[nm] = v
facts.append({"type": "input", "name": nm, "value": v, "from": "default"})
for nm: String in given:
if not values.has(nm):
values[nm] = given[nm]
facts.append({"type": "input", "name": nm, "value": given[nm], "from": "pipe"})
var saved := {}
for nm: String in values:
saved[nm] = [ctx.chain_vars.has(nm), ctx.chain_vars.get(nm)]
ctx.chain_vars[nm] = values[nm]
stack.append({"op": Roller.OP_RESTORE, "saved": saved})
f["inputs"] = values
f["pre_why"] = facts
f["pre_log"] = log
## Puts back the chain values a card's inputs hid.
static func restore(f: Dictionary, ctx: RollContext) -> void:
var saved: Dictionary = f["saved"]
for nm: String in saved:
var pair: Array = saved[nm]
if pair[0]:
ctx.chain_vars[nm] = pair[1]
else:
ctx.chain_vars.erase(nm)

1
core/roll_pipes.gd.uid Normal file
View file

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

151
core/roll_tree.gd Normal file
View file

@ -0,0 +1,151 @@
class_name RollTree
extends RefCounted
## Reading a Roller result tree: tray steps (step_of(), flatten()), searches
## over it, and the lit entry / pipe / reference keys the board highlights.
## One line of the result tray for a single node. Plain data only, because it
## is saved in the roll history. "text" is BBCode with internal markers.
## Logic-card keys (only when they apply): kind, effects (Array of {text,
## error?}), answer, passes, pass, after, picked, random, limit, cancelled,
## case (router nodes: the matched case's index), option, check ({nat, mod,
## total, target, success}), inputs ({name: value}) and why (the trace facts,
## a copy of the array; the facts themselves are shared, don't change them).
static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
var t: RollTable = n["table"]
var step := {
"table": t.name,
"table_id": t.id,
"num": t.fmt(n["value"]) if n.has("value") else "",
"die": t.die_size(),
"dice": t.dice_label(),
"text": str(n.get("summary", n.get("stop", ""))),
"depth": depth,
}
if n.has("entry"):
step["entry_id"] = (n["entry"] as TableEntry).id
if n.has("stop"):
step["stop"] = true
if n.get("inline", false):
step["inline"] = true
if n.get("reshuffled", false):
step["reshuffled"] = true
if n.has("save_as"):
step["save_as"] = n["save_as"]
if n.has("kind"):
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", "option", "check", "inputs"]:
if n.has(k):
step[k] = n[k]
if n.has("why"):
step["why"] = (n["why"] as Array).duplicate()
return step
## The whole chain in the order it was rolled. Iterative, so any length is
## fine; works on a partial tree (ctx.root while a roll is running) too.
static func flatten(n: Dictionary, out: Array = [], depth: int = 0) -> Array:
if n.is_empty():
return out
var stack: Array = [[n, depth]]
while not stack.is_empty():
var top: Array = stack.pop_back()
var node: Dictionary = top[0]
var d: int = top[1]
out.append(step_of(node, d))
var kids: Array = node.get("children", [])
for k in range(kids.size() - 1, -1, -1):
stack.append([kids[k], d + 1])
return out
static func reaches(n: Dictionary, table_id: String) -> bool:
if n.is_empty():
return false
var stack: Array = [n]
while not stack.is_empty():
var node: Dictionary = stack.pop_back()
if (node["table"] as RollTable).id == table_id:
return true
stack.append_array(node.get("children", []))
return false
## The last sheet node reached in a tree, or {} (the result headline when a
## chain reaches a sheet card).
static func last_sheet(n: Dictionary) -> Dictionary:
var found := {}
if n.is_empty():
return found
var stack: Array = [n]
while not stack.is_empty():
var node: Dictionary = stack.pop_back()
if str(node.get("kind", "")) == RollTable.KIND_SHEET and not node.has("stop"):
found = node
var kids: Array = node.get("children", [])
for k in range(kids.size() - 1, -1, -1):
stack.append(kids[k])
return found
## Marks every entry, pipe and reference pipe along the chain as lit. When
## given, `texts` gets each lit entry's expanded text (entry key -> BBCode).
## Iterative. A loop's pass and Afterwards nodes light their entries but no
## pipe (they aren't reached through one).
static func collect_lit(n: Dictionary, entries: Dictionary, pipes: Dictionary, texts: Dictionary = {}) -> void:
if n.is_empty():
return
var stack: Array = [n]
while not stack.is_empty():
var node: Dictionary = stack.pop_back()
if node.is_empty() or node.has("stop"):
continue
var t: RollTable = node["table"]
var e: TableEntry = node["entry"]
entries[entry_key(t.id, e.id)] = true
texts[entry_key(t.id, e.id)] = str(node.get("summary", e.text))
var kids: Array = node["children"]
for c: Dictionary in kids:
if not (c.has("pass") or c.has("after")):
pipes[link_key(t.id, e.id, c)] = true
for k in range(kids.size() - 1, -1, -1):
stack.append(kids[k])
static func entry_key(table_id: String, entry_id: String) -> String:
return table_id + ":" + entry_id
static func pipe_key(table_id: String, entry_id: String, to_id: String) -> String:
return "%s:%s>%s" % [table_id, entry_id, to_id]
## Key of a reference pipe: a [[reference]] in an entry's text to another table.
static func ref_key(table_id: String, entry_id: String, to_id: String) -> String:
return "%s:%s~%s" % [table_id, entry_id, to_id]
static func is_ref_key(key: String) -> bool:
return key.contains("~")
## The pipe or reference-pipe key that led from an entry to child node `c`.
static func link_key(table_id: String, entry_id: String, c: Dictionary) -> String:
var to := (c["table"] as RollTable).id
return ref_key(table_id, entry_id, to) if c.get("inline", false) else pipe_key(table_id, entry_id, to)
## Ids of the tables an entry's text references, resolved against the board,
## without duplicates or missing tables.
static func ref_targets(board: TowerBoard, text: String) -> Array[String]:
var out: Array[String] = []
if not text.contains("[[") and not text.contains("|"):
return out
var res := func(name: String) -> String: return Roller.resolve(board, name)
for name in TextExpander.references(text, res):
var id := Roller.resolve(board, name)
if id != "" and not out.has(id):
out.append(id)
return out

1
core/roll_tree.gd.uid Normal file
View file

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

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
# TableTower — Design and Status
**Engine:** Godot 4.7.2 (GDScript) · **Started:** 2026-11-08 · **Last updated:** 2026-11-08 (`main` at `adb93c5`)
**Engine:** Godot 4.7.2 (GDScript) · **Started:** 2026-11-08 · **Last updated:** 2026-11-09 (big files split; see §10)
This is the starting point for anyone picking the project up, including a new Claude
session. It records what TableTower is, how it's built, how to work on it, where things
@ -94,8 +94,13 @@ core/ engine, no UI, testable headless
tower_board.gd a collection (tables, groups), JSON, format v2 + migration
roll_table.gd a card: kind, dice, entries, logic fields, factories (RollTable.create)
table_entry.gd a result: text, weight, range, effects, pipes (+count/save/when/otherwise/with), show_if, when
roller.gd coroutine roller with an explicit stack; pipe_plan snapshot, route, choices,
checks, inputs, why facts, lint_*, endless_cycles, flatten, apply_starting_values
roller.gd coroutine roller with an explicit stack (_chain loop, roll/pipe steps,
apply_starting_values) plus delegators to its parts:
roll_pipes.gd pipe_plan snapshot, card inputs (`with`)
roll_cards.gd weighted picks, router, check, loops
roll_choice.gd choice requests, dynamic options, show_if, asking
roll_tree.gd flatten, step lookups, lit keys, pipe/entry keys
roll_lint.gd lint_*, endless_cycles
roll_context.gd per-roll state: chain and board variables, prompt hook, actions, depth
expr.gd / effects.gd expression evaluation (Godot Expression + rewrites), effect statements
text_expander.gd [[refs]], {vars}, {@prefix_*}, {= expr}; formatter.gd: BBCode safety and stripping
@ -106,12 +111,19 @@ core/ engine, no UI, testable headless
library_store.gd / state_store.gd collections on disk / local state (decks, variables, history, settings)
table_group.gd, template_kit.gd, template_library.gd, sample_board.gd
io/ json_io (canonical + import), canvas_io, graphml_io, mermaid_exporter, dot_exporter
ui/ main.gd (the app: top bar, modes, rolling, editing actions, undo, CLI flags) and its parts:
board_view, card_layer, pipe_layer, port_layer, group_layer, group_card, minimap,
table_card, result_tray, why_popover, choice_dialog, table_preview, details_popup,
inspector*, value_picker, rules_view, search_panel, board_search, board_layout,
edit_history, test_board_dialog, template_*, table_settings_dialog, io_menu,
collection_switcher, variables_panel, modal_card, rich_text, style
ui/ main.gd: the app shell (shared fields, _ready, cards, collapse, input) with one-line
delegators to RefCounted helpers that hold `m: Main`:
main_cli (every CLI/screenshot flag), main_rolling, main_editing, main_groups,
main_history (undo), main_navigation (search/focus/minimap/arrange),
main_top_bar (bar, toast, rules switch), main_state (decks, variables),
main_collections, main_templates, main_inspector
table_card.gd + table_card_{header,rows,editing,value,text}.gd
result_tray.gd + tray_chips, tray_text, earlier_rolls
table_settings_dialog.gd + table_settings_rules (validation/apply), settings_kind_fields
and: board_view, card_layer, pipe_layer, port_layer, group_layer, group_card, minimap,
why_popover, choice_dialog, table_preview, details_popup, inspector*, value_picker,
rules_view, search_panel, board_search, board_layout, edit_history, test_board_dialog,
template_*, io_menu, collection_switcher, variables_panel, modal_card, rich_text, style
tools/ simulate_board.gd (headless simulator CLI), test_window.sh (background test windows)
tests/ test_*.gd: 25 headless suites
templates/ built-in templates · examples/logic_demo.json (original demo board) · assets/fonts (OFL)
@ -124,6 +136,10 @@ templates/ built-in templates · examples/logic_demo.json (original demo board)
- **Prompts.** The roller awaits `ctx.prompt` for choices, and the UI shows progress before each pop-up.
- **Rules display.** The UI reads plain or text mode through `RulesView` and `main.rules_plain()`,
and `main.rules_view_changed` signals a switch.
- **Shared builders, use them rather than copying:** `Style.menu_button`, `Style.font_colors`,
`Style.field_colors`, `TableCard.vbox/hbox`, `InspectorKit.*` (fields, `focused_tag`/`refocus`,
`as_text_link`), `Main.file_dialog`/`export_dialog`, `JsonIO.entry_line`/`finish_import`.
- **Keep files small.** Aim for under ~400 lines; split by area into helper objects as above.
## 4. Data and storage
- **Collections:** `user://collections/<id>.json`, format_version 2 (`{format_version, id,
@ -148,7 +164,7 @@ templates/ built-in templates · examples/logic_demo.json (original demo board)
Wayland, in `~/.config/kwinrulesrc`) keeps that class unfocused and behind other windows.
- Never open a test window with plain `godot --path .`.
- Don't minimize test windows; Godot stops rendering when minimized.
- **Screenshot and state flags**, read in `_run_cli*` in `ui/main.gd` and in some UI files; README lists the main ones:
- **Screenshot and state flags**, read in `ui/main_cli.gd` and in some UI files; README lists the main ones:
- Setup and roll: `--board`, `--roll`, `--fast`, `--answers`, `--build`, `--rules=text`, `--why`.
- Inspector and focus: `--inspect=tid[:eid][>to]`, `--search`, `--focus`, `--minimap`.
- Tools and layout: `--test-board`, `--pack`, `--perf`, `--window=WxH`.
@ -260,3 +276,9 @@ templates/ built-in templates · examples/logic_demo.json (original demo board)
**Plain Build**
9. The usability mockup, then Plain Build: plain words, the inspector with builders, Check
cards, card inputs, collections, Why this?, the Plain/Text switch, and starting values applied.
**2026-11-09: token diet**
10. Split the oversized files (main.gd 3679 → 617 lines plus 11 helpers; table_card, roller,
table_settings_dialog and result_tray likewise) with no behaviour change, then a duplicate-code
pass guided by the Coderstanding scanner (shared Style/InspectorKit/JsonIO/Main helpers, dead
flags and fields removed). A terminology audit produced suggestions only (not yet applied).

View file

@ -212,7 +212,7 @@ more, with `le` (roll-under) when it is the target or less. It has two fixed ent
- A dice, modifier or target expression that fails, or gives text, stops the node with
"Can't roll the check: …" (a dead end in the board test). A check with no Failure entry
stops with "This check has no Failure result" when it fails.
- `Roller.check_roll(table, ctx)` does the roll alone; `Roller.lint_check(table)` reports
- `RollCards.check_roll(table, ctx)` does the roll alone; `Roller.lint_check(table)` reports
expressions that don't parse, an empty dice or target, and a missing Success or Failure entry.
### `nat` on roll tables

View file

@ -40,7 +40,7 @@ static func export_canvas(collection: Dictionary) -> String:
var entries: Array = t["entries"]
for ei in entries.size():
var e: Dictionary = entries[ei]
var text := _visible_text(e, dmax)
var text := JsonIO.entry_line(e, dmax)
var h := _node_height(text)
var nid := "t%de%d" % [ti, ei]
entry_ids["%s\t%s" % [t["id"], e["id"]]] = nid
@ -103,17 +103,6 @@ static func _entry_extra(e: Dictionary) -> Dictionary:
return extra
static func _visible_text(e: Dictionary, dmax: int) -> String:
var plain := JsonIO.strip_bbcode(str(e["text"]))
if e.has("range"):
var r: Array = e["range"]
return "%s: %s" % [JsonIO.range_text(int(r[0]), int(r[1]), dmax), plain]
var w: Variant = e.get("weight", 1)
if w != 1:
return "%s × %s" % [str(w), plain]
return plain
static func _node_height(text: String) -> int:
var lines := 0
for part in text.split("\n"):
@ -271,14 +260,7 @@ static func import_canvas(text: String, sanitize: Callable = Callable()) -> Dict
}
if doc_extra.is_empty():
guesses.append("No collection name in the canvas; using a default.")
var imported := JsonIO.import_dict(raw, sanitize)
for w in imported["warnings"]:
warnings.append(w)
for er in imported["errors"]:
errors.append(er)
result["ok"] = imported["ok"]
result["collection"] = imported["collection"]
return result
return JsonIO.finish_import(raw, sanitize, result)
static func _containing_group(node: Dictionary, groups: Array[Dictionary]) -> Dictionary:

View file

@ -47,7 +47,7 @@ static func export_dot(collection: Dictionary) -> String:
hidden += 1
continue
shown += 1
rows.append("<TR><TD PORT=\"e%d\" ALIGN=\"LEFT\">%s</TD></TR>" % [ei, escape_html(_row_text(e, dmax))])
rows.append("<TR><TD PORT=\"e%d\" ALIGN=\"LEFT\">%s</TD></TR>" % [ei, escape_html(JsonIO.entry_line(e, dmax))])
if hidden > 0:
rows.append("<TR><TD ALIGN=\"LEFT\"><I>… and %d more</I></TD></TR>" % hidden)
out.append("\t%s [label=<<TABLE BORDER=\"1\" CELLBORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"4\">%s</TABLE>>];" % [node_of[t["id"]], "".join(rows)])
@ -87,14 +87,3 @@ static func escape_string(text: String) -> String:
## Escapes text for an HTML-like DOT label.
static func escape_html(text: String) -> String:
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("\n", " ")
static func _row_text(e: Dictionary, dmax: int) -> String:
var plain := JsonIO.strip_bbcode(str(e["text"]))
if e.has("range"):
var r: Array = e["range"]
return "%s: %s" % [JsonIO.range_text(int(r[0]), int(r[1]), dmax), plain]
var w: Variant = e.get("weight", 1)
if w != 1:
return "%s × %s" % [str(w), plain]
return plain

View file

@ -235,11 +235,4 @@ static func import_graphml(text: String, sanitize: Callable = Callable()) -> Dic
"name": str(graph_data.get("collection_name", "")),
"tables": tables,
}
var imported := JsonIO.import_dict(raw, sanitize)
for w in imported["warnings"]:
warnings.append(w)
for er in imported["errors"]:
errors.append(er)
result["ok"] = imported["ok"]
result["collection"] = imported["collection"]
return result
return JsonIO.finish_import(raw, sanitize, result)

View file

@ -585,3 +585,26 @@ static func _is_power_of_ten(n: int) -> bool:
while n >= 10 and n % 10 == 0:
n /= 10
return n == 1
## An entry as one plain line for an export: "3-4: text", "2 × text" or "text".
static func entry_line(e: Dictionary, dmax: int) -> String:
var plain := strip_bbcode(str(e["text"]))
if e.has("range"):
var r: Array = e["range"]
return "%s: %s" % [range_text(int(r[0]), int(r[1]), dmax), plain]
var w: Variant = e.get("weight", 1)
if w != 1:
return "%s × %s" % [str(w), plain]
return plain
## Imports a converted collection (`raw`) and adds its warnings, errors and
## result to an importer's `result` ({ok, collection, errors, warnings, ...}).
static func finish_import(raw: Dictionary, sanitize: Callable, result: Dictionary) -> Dictionary:
var imported := import_dict(raw, sanitize)
(result["warnings"] as Array).append_array(imported["warnings"])
(result["errors"] as Array).append_array(imported["errors"])
result["ok"] = imported["ok"]
result["collection"] = imported["collection"]
return result

View file

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

View file

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

View file

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

View file

@ -45,8 +45,8 @@ func _init() -> void:
func _load_demo() -> void:
main.prompt_hook = main._ask_player
await main._load_board_file(DEMO)
main.prompt_hook = main.rolling._ask_player
await main.cli._load_board_file(DEMO)
for i in 3:
await process_frame
@ -72,7 +72,7 @@ func _past_spend(d: ChoiceDialog) -> ChoiceDialog:
d.answer(int(o["index"]))
break
await process_frame
return main.pending_choice()
return main.rolling.pending_choice()
func _var(name: String) -> Variant:
@ -102,8 +102,8 @@ func _test_cards() -> void:
var check := main.card_for("room_check")
_check(check != null and check.rows.size() == 3, "the check table shows its three ranges")
var nums: Array = []
for eid: String in check._row_parts:
var num: Label = check._row_parts[eid]["num"]
for eid: String in check.rows_ui.parts:
var num: Label = check.rows_ui.parts[eid]["num"]
nums.append(num.text if num else "")
_eq(nums, ["≤6", "7–9", "10+"], "expression dice label the ends ≤N and N+")
var loop := main.card_for("explore")
@ -114,7 +114,7 @@ func _test_cards() -> void:
_check(hp.rows.is_empty() and hp.anchor_for("x").is_empty(), "a variable card has no outlets")
var sheet := main.card_for("report")
_check(sheet.rows.size() == 1 and not sheet.anchor_for("e1").is_empty(), "a sheet card has one outlet")
_eq(TableCard.effect_summary("@hp -= 2\n@gold += 1; @luck = 3", main.data), "Hit points -= 2 · Gold += 1 · +1",
_eq(TableCardText.effect_summary("@hp -= 2\n@gold += 1; @luck = 3", main.data), "Hit points -= 2 · Gold += 1 · +1",
"effect summaries use the variable card's name")
@ -149,17 +149,17 @@ func _test_scripted() -> void:
_check(picked, "the picked option is the step")
# Live cards after the roll.
var hp := main.card_for("v_hp")
_eq(hp._var_value.text, Expr.format_value(_var("hp")), "the HP card shows the new value after the roll")
_eq(hp.value_ui.var_value.text, Expr.format_value(_var("hp")), "the HP card shows the new value after the roll")
var sheet := main.card_for("report")
_check(Formatter.strip_tags(sheet._sheet_label.text).contains("HP %s" % Expr.format_value(_var("hp"))), "the sheet card is up to date")
_check(Formatter.strip_tags(sheet._sheet_label.text).begins_with("Brin the delver"), "the sheet shows the name")
main.prompt_hook = main._ask_player
_check(Formatter.strip_tags(sheet.rows_ui.sheet_label.text).contains("HP %s" % Expr.format_value(_var("hp"))), "the sheet card is up to date")
_check(Formatter.strip_tags(sheet.rows_ui.sheet_label.text).begins_with("Brin the delver"), "the sheet shows the name")
main.prompt_hook = main.rolling._ask_player
func _test_dialog_answers() -> void:
main.start_roll("start", true)
await process_frame
var d := main.pending_choice()
var d := main.rolling.pending_choice()
_check(d != null and d.kind == "text", "the text pop-up opens (fast roll still asks)")
if d == null:
return
@ -172,7 +172,7 @@ func _test_dialog_answers() -> void:
d._text.text = "Ann"
d._confirm()
await process_frame
d = main.pending_choice()
d = main.rolling.pending_choice()
_check(d != null and d.kind == "number", "then the number pop-up")
if d == null:
return
@ -181,14 +181,14 @@ func _test_dialog_answers() -> void:
d._spin.value = 2
d._confirm()
await process_frame
d = await _past_spend(main.pending_choice())
d = await _past_spend(main.rolling.pending_choice())
_check(d != null and d.kind == "pick" and d._options.size() == 3, "then the pick pop-up with three options")
if d == null:
return
_check(main.is_entry_lit("explore", "e1") and main.is_entry_lit("explore", "e2"), "the loop's steps are lit before the pick")
d.answer(-1)
await process_frame
_check(main.pending_choice() == null and main.current.get("done", false), "Random finishes the roll")
_check(main.rolling.pending_choice() == null and main.current.get("done", false), "Random finishes the roll")
_eq(_var("name"), "Ann", "typed name saved")
_eq(_var("rooms"), 2, "typed number saved")
var random := false
@ -201,13 +201,13 @@ func _test_dialog_answers() -> void:
func _test_cancel() -> void:
main.start_roll("start")
await process_frame
var d := main.pending_choice()
var d := main.rolling.pending_choice()
_check(d != null, "a pop-up is open")
if d == null:
return
d.close() # Esc does this
await process_frame
_check(main.pending_choice() == null, "Esc closes the pop-up")
_check(main.rolling.pending_choice() == null, "Esc closes the pop-up")
_eq(main.current.get("halted", ""), "Cancelled", "Cancel stops the roll with Cancelled")
_check(main.current.get("done", false), "the cancelled roll is shown, not left hanging")
var last: Dictionary = (main.current["all"] as Array).back()
@ -217,7 +217,7 @@ func _test_cancel() -> void:
# Freeing the dialog some other way also answers Cancel.
main.start_roll("start")
await process_frame
d = main.pending_choice()
d = main.rolling.pending_choice()
if d:
d.free()
await process_frame
@ -227,14 +227,14 @@ func _test_cancel() -> void:
func _test_replace() -> void:
main.start_roll("start")
await process_frame
var first := main.pending_choice()
var first := main.rolling.pending_choice()
_check(first != null, "first roll asks")
var first_reply := first.reply if first else null
var history := main.history.size()
main.start_roll("start")
_check(first_reply != null and first_reply.finished, "a new roll answers the old question with Cancel")
await process_frame
var second := main.pending_choice()
var second := main.rolling.pending_choice()
_check(second != null and second != first, "the new roll opens its own pop-up")
_check(not is_instance_valid(first) or first.is_queued_for_deletion(), "the old pop-up goes away")
_check(not main.current.has("halted"), "the old roll doesn't overwrite the new one")
@ -244,11 +244,11 @@ func _test_replace() -> void:
second._text.text = "Cy"
second._confirm()
await process_frame
var n := main.pending_choice()
var n := main.rolling.pending_choice()
if n:
n.answer(1)
await process_frame
var p := main.pending_choice()
var p := main.rolling.pending_choice()
if p:
p.answer(2)
await process_frame
@ -259,12 +259,12 @@ func _test_replace() -> void:
func _test_keys() -> void:
main.start_roll("start")
await process_frame
var d := main.pending_choice()
var d := main.rolling.pending_choice()
if d:
d._text.text = "Dee"
d._confirm()
await process_frame
d = main.pending_choice()
d = main.rolling.pending_choice()
if d:
# Typing in the number field, then Enter.
var le := d._spin.get_line_edit()
@ -273,7 +273,7 @@ func _test_keys() -> void:
le.text_submitted.emit(le.text)
await process_frame
_eq(_var("rooms"), 4, "a typed number is used")
d = await _past_spend(main.pending_choice())
d = await _past_spend(main.rolling.pending_choice())
_check(d != null and d.kind == "pick", "pick pop-up for the key test")
if d == null:
return
@ -282,7 +282,7 @@ func _test_keys() -> void:
ev.pressed = true
d._input(ev)
await process_frame
_check(main.pending_choice() == null and main.current.get("done", false), "pressing 3 answers")
_check(main.rolling.pending_choice() == null and main.current.get("done", false), "pressing 3 answers")
var paid := false
for s: Dictionary in main.current["all"]:
if s.get("table_id") == "way_out" and Formatter.strip_tags(str(s["text"])) == "Pay the toll":
@ -295,15 +295,15 @@ func _test_keys() -> void:
func _test_live_edits() -> void:
main.set_variable("gold", "42")
_eq(_var("gold"), 42, "a number variable stays a number")
_eq(main.card_for("v_gold")._var_value.text, "42", "the variable card follows an edit")
_check(Formatter.strip_tags(main.card_for("report")._sheet_label.text).contains("Gold 42"), "the sheet follows an edit")
_eq(main.card_for("v_gold").value_ui.var_value.text, "42", "the variable card follows an edit")
_check(Formatter.strip_tags(main.card_for("report").rows_ui.sheet_label.text).contains("Gold 42"), "the sheet follows an edit")
main.reset_variable("gold")
_eq(_var("gold"), 0, "reset goes back to the starting value")
main.set_variable("hp", "3")
main.persistent_vars["stray"] = {"value": "x", "source": ""}
main.reset_all_variables()
_check(_var("hp") == 10 and not main.persistent_vars.has("stray"), "Reset all: declared to start, undeclared cleared")
_eq(main.card_for("v_hp")._var_value.text, "10", "cards show the reset values")
_eq(main.card_for("v_hp").value_ui.var_value.text, "10", "cards show the reset values")
main.tray.set_side(ResultTray.Side.VARIABLES)
main.tray.render()
var rows := 0
@ -316,10 +316,10 @@ func _test_live_edits() -> void:
dlg.close()
main.tray.set_side(ResultTray.Side.EARLIER)
# Rendering live cards doesn't happen per frame: the sheet's text stays put.
var before := main.card_for("report")._sheet_label.text
var before := main.card_for("report").rows_ui.sheet_label.text
for i in 3:
await process_frame
_eq(main.card_for("report")._sheet_label.text, before, "live cards only re-render on change")
_eq(main.card_for("report").rows_ui.sheet_label.text, before, "live cards only re-render on change")
# ---------------------------------------------------------------- build rules
@ -363,12 +363,12 @@ func _test_settings_rules() -> void:
func _test_add_kinds() -> void:
main.set_mode(Main.Mode.BUILD)
var n := main.data.tables.size()
for k: Array in Main.ADD_KINDS:
var t := main.add_table(str(k[1]), str(k[2]))
for k: Array in MainEditing.ADD_KINDS:
var t := main.editing.add_table(str(k[1]), str(k[2]))
_check(t.kind == k[1] and main.card_for(t.id) != null, "+ Table adds a %s" % str(k[0]))
_eq(main.data.tables.size(), n + Main.ADD_KINDS.size(), "one card per menu item")
var v1 := main.add_table(RollTable.KIND_VARIABLE, "number")
var v2 := main.add_table(RollTable.KIND_VARIABLE, "number")
_eq(main.data.tables.size(), n + MainEditing.ADD_KINDS.size(), "one card per menu item")
var v1 := main.editing.add_table(RollTable.KIND_VARIABLE, "number")
var v2 := main.editing.add_table(RollTable.KIND_VARIABLE, "number")
_check(v1.var_name != v2.var_name, "new variable cards get distinct names")
main.set_mode(Main.Mode.PLAY)
@ -425,8 +425,8 @@ func _test_long_chain() -> void:
_eq(_chips(), ResultTray.MAX_EXPANDED, "expanding shows more steps (capped)")
_check(ms < 4000, "lighting 3,000 steps is quick (%d ms)" % ms)
print(" (3,001-step roll, lit and shown in %d ms)" % ms)
_check(main.result_text(all, ResultTray.COPY_TEXT).length() < 3001 * 40, "copy text indents are capped")
var line := ResultTray.earlier_line({"root_name": "x", "steps": all})
_check(main.rolling.result_text(all, ResultTray.COPY_TEXT).length() < 3001 * 40, "copy text indents are capped")
var line := EarlierRolls.earlier_line({"root_name": "x", "steps": all})
_check(line.length() < 2000, "Earlier rows show the last few steps of a long chain")
await process_frame

View file

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

View file

@ -515,7 +515,7 @@ func _test_settings() -> void:
var bad := s.duplicate(true)
bad["options_from"] = "skill"
bad["show_if"] = {"keep": "@x >"}
var probs := TableSettingsDialog.kind_problems(t, bad)
var probs := TableSettingsRules.kind_problems(t, bad)
_check(probs.size() == 2, "a bad pattern and a bad show_if are refused (%s)" % [probs])
bad = s.duplicate(true)
bad["options_from"] = ""
@ -571,10 +571,10 @@ func _test_card() -> void:
main.add_child(d)
await process_frame
_check(_has_ci(d, "Options from (@prefix_* or a @list)") and _has_ci(d, "Show only if") and _has_ci(d, "From variables (+ fixed extras)"), "the settings dialog has the options fields")
_check(d._options_box.visible and d._opt_from.text == "@skill_*", "From variables is selected with its pattern")
d._opt_where.text = "option_value >="
_check(d._kind._options_box.visible and d._kind._opt_from.text == "@skill_*", "From variables is selected with its pattern")
d._kind._opt_where.text = "option_value >="
d._refresh()
_check(d._kind_problem.visible, "a bad filter is flagged live")
_check(d._kind.problem.visible, "a bad filter is flagged live")
d.queue_free()
main.set_mode(Main.Mode.PLAY)
main.queue_free()

View file

@ -221,8 +221,8 @@ func _test_rules_view_helpers() -> void:
_eq(RulesView.dice("2d6 + dm(@str)", b, true), "2D + Strength modifier", "expression dice")
_eq(Describe.condition("@luck != \"\"", b), "Luck is not empty", "empty text reads as empty")
_eq(RulesView.check_outlets(b.get_table("gate")), ["8+", "≤7"] as Array[String], "check outlets")
_eq(ResultTray.effect_fact_line({"type": "effect", "var": "@luck", "op": "-=", "before": 2, "after": 1}, b), "Luck 2 → 1", "tray effect line")
_eq(ResultTray.effect_fact_line({"type": "effect", "var": "@skill_*", "op": "reset", "count": 3}, b), "Cleared all Skills (3)", "tray prefix reset line")
_eq(TrayText.effect_fact_line({"type": "effect", "var": "@luck", "op": "-=", "before": 2, "after": 1}, b), "Luck 2 → 1", "tray effect line")
_eq(TrayText.effect_fact_line({"type": "effect", "var": "@skill_*", "op": "reset", "count": 3}, b), "Cleared all Skills (3)", "tray prefix reset line")
# ---------------------------------------------------------------- cards
@ -360,7 +360,7 @@ func _test_roll_why() -> void:
_check(not steps.is_empty() and str(steps[0].get("kind", "")) == RollTable.KIND_CHECK, "the check rolled")
if steps.is_empty():
return
var cap := ResultTray.caption_for(steps[0], main.data, true)
var cap := TrayText.caption_for(steps[0], main.data, true)
_check(cap.begins_with("Force the gate · rolled ") and cap.contains("→"), "the check's caption reads rolled N, ±M → total: " + cap)
_check(main.tray.why_buttons.has(0), "a real check step has a Why button")
var lines := WhyPopover.why_lines(steps, 0, main.data, true)
@ -371,7 +371,7 @@ func _test_roll_why() -> void:
_check(not main.details().step_for("gate", lit).is_empty(), "a lit row finds its step for the hover reasons")
for s: Dictionary in steps:
if str(s.get("table_id", "")) == "loot":
_check(ResultTray.caption_for(s, main.data, true).contains("Tier "), "an inputs step's caption names its input")
_check(TrayText.caption_for(s, main.data, true).contains("Tier "), "an inputs step's caption names its input")
func _test_build_rows() -> void:

View file

@ -408,7 +408,7 @@ func _test_ui_helpers() -> void:
_check(not bad["ok"] and str(bad["error"]).begins_with("Case 1"), "settings refuse a bad case: %s" % str(bad))
var ok := TableSettingsDialog.apply_settings(r, {"name": "R", "cases": ["@a = 1", ""], "card_mode": true, "ranged": true})
_check(ok["ok"] and r.entries[0].when == "@a = 1" and not r.card_mode and not r.is_ranged(), "settings set case conditions; no card mode or ranges: %s" % str(ok))
_check(TableSettingsDialog.router_hint(["", "@a"]) != "" and TableSettingsDialog.router_hint(["@a", ""]) == "", "router order hint")
_check(TableSettingsRules.router_hint(["", "@a"]) != "" and TableSettingsRules.router_hint(["@a", ""]) == "", "router order hint")
_eq(TablePreview.kind_line(r), "Router · if / else if / otherwise", "preview kind line")

View file

@ -61,13 +61,13 @@ func _test_ranges() -> void:
t.entries[0].weight = 1
t.entries[1].weight = 3
t.dice = "1d100"
TableSettingsDialog.assign_ranges(t)
TableSettingsRules.assign_ranges(t)
_check(t.entries[0].range_lo == 1 and t.entries[0].range_hi == 25, "weight 1 of 4 gets 1-25")
_check(t.entries[1].range_lo == 26 and t.entries[1].range_hi == 100, "weight 3 of 4 gets 26-100")
# More entries than values: everything stays valid and in span.
var many := _plain_table(8)
many.dice = "1d6"
TableSettingsDialog.assign_ranges(many)
TableSettingsRules.assign_ranges(many)
var lit := 0
for e in many.entries:
if e.has_range:
@ -78,15 +78,15 @@ func _test_ranges() -> void:
var z := _plain_table(3)
z.entries[1].weight = 0
z.entries[0].pipes = ["a", "b"] as Array[String]
TableSettingsDialog.assign_ranges(z)
TableSettingsRules.assign_ranges(z)
_check(not z.entries[1].has_range and z.entries[0].pipes.size() == 1, "weight 0 skipped, extra pipe dropped")
_check(z.entries[2].range_hi == 100, "last live entry reaches the top")
func _test_wrap() -> void:
var r := TableSettingsDialog.wrap_text("hello world", Vector2i(0, 5), "[b]", "[/b]")
var r := TableSettingsRules.wrap_text("hello world", Vector2i(0, 5), "[b]", "[/b]")
_check(r["text"] == "[b]hello[/b] world" and r["caret"] == 12, "bold wraps selection")
var r2 := TableSettingsDialog.wrap_text("ab", Vector2i(1, 1), "[i]", "[/i]")
var r2 := TableSettingsRules.wrap_text("ab", Vector2i(1, 1), "[i]", "[/i]")
_check(r2["text"] == "a[i][/i]b" and r2["caret"] == 4, "empty selection inserts a pair")

View file

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

View file

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

View file

@ -17,17 +17,9 @@ var _ids: Array[String] = []
func setup(p_main: Main) -> void:
main = p_main
var ref := ModalCard.bar_menu_button("")
for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]:
add_theme_stylebox_override(n, ref.get_theme_stylebox(n))
for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
add_theme_color_override(c, ref.get_theme_color(c))
Style.menu_button(text, false, self)
add_theme_color_override("font_disabled_color", Style.ON_FELT)
add_theme_font_override("font", Style.body_bold())
add_theme_font_size_override("font_size", 15)
ref.free()
mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
flat = false
tooltip_text = "Collections"
ModalCard.style_popup(get_popup())
get_popup().about_to_popup.connect(_fill)

65
ui/earlier_rolls.gd Normal file
View file

@ -0,0 +1,65 @@
class_name EarlierRolls
extends VBoxContainer
## ResultTray's Earlier tab: one row per past roll, newest first, as
## "12:04 Root: a → b → c".
var main: Main
var _rows: VBoxContainer
var _empty: Label
func setup(p_main: Main) -> void:
main = p_main
add_theme_constant_override("separation", 6)
_rows = VBoxContainer.new()
_rows.add_theme_constant_override("separation", 6)
add_child(_rows)
_empty = Style.make_label("Older rolls show here.", Style.body(), 15, Style.ON_FELT_MUTED)
add_child(_empty)
func render() -> void:
for c in _rows.get_children():
_rows.remove_child(c)
c.queue_free()
_empty.visible = main.history.is_empty()
for rec in main.history:
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 8)
var time := Style.make_label(clock(rec["time"]), Style.body(), 14, Style.ON_FELT_MUTED)
time.custom_minimum_size = Vector2(44, 0)
time.size_flags_vertical = SIZE_SHRINK_BEGIN
row.add_child(time)
var line := RichText.label(earlier_line(rec), 14, Style.ON_FELT, false)
line.size_flags_horizontal = SIZE_EXPAND_FILL
RichText.hook_hover(line, main)
row.add_child(line)
_rows.add_child(row)
## One Earlier row: "Root: a → b → c", with only the last few steps of a long
## chain.
static func earlier_line(rec: Dictionary) -> String:
var texts := PackedStringArray()
var all: Array = rec.get("steps", [])
var shown := 0
var skipped := 0
for k in range(all.size() - 1, -1, -1):
var s: Dictionary = all[k]
if s.get("inline", false):
continue
if shown >= 6:
skipped += 1
continue
texts.insert(0, RichText.decorate(TrayText.one_line(str(s["text"])), true))
shown += 1
var lead := "[color=#%s]%s:[/color] " % [Style.ON_FELT_MUTED.to_html(false), RichText.plain(Formatter.strip_tags(str(rec.get("root_name", ""))))]
if skipped > 0:
lead += "[color=#%s]… %d earlier →[/color] " % [Style.ON_FELT_MUTED.to_html(false), skipped]
return lead + " → ".join(texts)
static func clock(unix: float) -> String:
var bias: int = Time.get_time_zone_from_system().get("bias", 0)
var d := Time.get_datetime_dict_from_unix_time(int(unix) + bias * 60)
return "%02d:%02d" % [d["hour"], d["minute"]]

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

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

View file

@ -143,7 +143,7 @@ func _build_frame() -> void:
bar.mouse_entered.connect(_show_details.bind(bar))
col.add_child(bar)
_header = bar
var h := _hbox(8)
var h := TableCard.hbox(8)
h.size_flags_vertical = SIZE_SHRINK_CENTER
bar.add_child(h)
var chevron := ChevronButton.new()
@ -200,7 +200,7 @@ func _build_compact() -> void:
_card.accept_event()
)
add_child(_card)
var col := _vbox(0)
var col := TableCard.vbox(0)
_card.add_child(col)
var header := PanelContainer.new()
@ -214,7 +214,7 @@ func _build_compact() -> void:
header.mouse_entered.connect(_show_details.bind(header))
col.add_child(header)
_header = header
var row := _hbox(8)
var row := TableCard.hbox(8)
header.add_child(row)
var chevron := ChevronButton.new()
chevron.open = false
@ -226,7 +226,7 @@ func _build_compact() -> void:
if build:
row.add_child(_name_edit(false))
else:
var titles := _vbox(3)
var titles := TableCard.vbox(3)
titles.size_flags_horizontal = SIZE_EXPAND_FILL
titles.mouse_filter = MOUSE_FILTER_IGNORE
var title := Style.make_label(Formatter.strip_tags(group.name), Style.display(true), 20, Style.INK)
@ -249,7 +249,7 @@ func _build_compact() -> void:
pad.add_theme_constant_override("margin_top", 6)
pad.add_theme_constant_override("margin_bottom", 8)
col.add_child(pad)
var list := _vbox(2)
var list := TableCard.vbox(2)
pad.add_child(list)
var shown := _lit_keys.slice(maxi(0, _lit_keys.size() - MAX_LIT))
if _lit_keys.size() > shown.size():
@ -310,7 +310,7 @@ func _lit_row(key: String) -> Control:
var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS
row.add_theme_stylebox_override("panel", Style.box(Style.LIT, 0, [14, 5, 22, 6]))
var v := _vbox(1)
var v := TableCard.vbox(1)
row.add_child(v)
var cap := Style.make_label(Formatter.strip_tags(t.name if t else tid).to_upper(), Style.caps(), 10, Style.COPPER_DARK)
cap.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
@ -340,20 +340,6 @@ func set_rolling(on: bool) -> void:
# ---------- Shared parts ----------
func _vbox(sep: int) -> VBoxContainer:
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", sep)
v.mouse_filter = MOUSE_FILTER_PASS
return v
func _hbox(sep: int) -> HBoxContainer:
var h := HBoxContainer.new()
h.add_theme_constant_override("separation", sep)
h.mouse_filter = MOUSE_FILTER_PASS
return h
func _name_edit(on_felt: bool) -> LineEdit:
var le := LineEdit.new()
le.text = group.name
@ -394,8 +380,7 @@ func _menu_button(on_felt: bool) -> MenuButton:
for n in ["hover", "pressed", "hover_pressed"]:
mb.add_theme_stylebox_override(n, hover)
var fg := Style.ON_FELT if on_felt else Style.MUTED
for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
mb.add_theme_color_override(c, fg)
Style.font_colors(mb, fg)
mb.mouse_default_cursor_shape = CURSOR_POINTING_HAND
menu_button = mb
var pm := mb.get_popup()

View file

@ -558,31 +558,30 @@ static func add_case(insp: Inspector) -> void:
# ---------- Variable ----------
static func _variable(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var err := InspectorKit.error_label()
var vn := InspectorKit.line(t.var_name, "luck")
InspectorKit.code(vn)
InspectorKit.tag(vn, "card.var_name")
insp.fields["var_name"] = vn
vn.text_changed.connect(func(s: String) -> void:
var msg := insp.apply_settings({"var_name": s})
InspectorKit.mark(vn, msg == "")
## A field for one card setting: applied as you type, marked and explained in `err` when refused.
static func _setting_line(insp: Inspector, key: String, text: String, placeholder: String, err: Label) -> LineEdit:
var le := InspectorKit.line(text, placeholder)
InspectorKit.tag(le, "card." + key)
insp.fields[key] = le
le.text_changed.connect(func(s: String) -> void:
var msg := insp.apply_settings({key: s})
InspectorKit.mark(le, msg == "")
InspectorKit.show_error(err, msg)
)
return le
static func _variable(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var err := InspectorKit.error_label()
var vn := _setting_line(insp, "var_name", t.var_name, "luck", err)
InspectorKit.code(vn)
box.add_child(InspectorKit.field("Name in rules (@name)", vn))
var types := ["number", "text", "list"]
var seg := ModalCard.segmented(["Number", "Text", "List"], maxi(0, types.find(t.var_type)), func(i: int) -> void:
InspectorKit.show_error(err, insp.apply_settings({"var_type": types[i]}, true))
)
box.add_child(InspectorKit.field("Type", seg))
var init := InspectorKit.line(t.initial, "0" if t.var_type == "number" else "nothing")
InspectorKit.tag(init, "card.initial")
insp.fields["initial"] = init
init.text_changed.connect(func(s: String) -> void:
var msg := insp.apply_settings({"initial": s})
InspectorKit.mark(init, msg == "")
InspectorKit.show_error(err, msg)
)
var init := _setting_line(insp, "initial", t.initial, "0" if t.var_type == "number" else "nothing", err)
box.add_child(InspectorKit.field("Starting value", init))
box.add_child(err)
@ -591,15 +590,8 @@ static func _variable(insp: Inspector, box: VBoxContainer, t: RollTable) -> void
static func _collection(insp: Inspector, box: VBoxContainer, t: RollTable) -> void:
var err := InspectorKit.error_label()
var vn := InspectorKit.line(t.var_name, "skill")
var vn := _setting_line(insp, "var_name", t.var_name, "skill", err)
InspectorKit.code(vn)
InspectorKit.tag(vn, "card.var_name")
insp.fields["var_name"] = vn
vn.text_changed.connect(func(s: String) -> void:
var msg := insp.apply_settings({"var_name": s})
InspectorKit.mark(vn, msg == "")
InspectorKit.show_error(err, msg)
)
box.add_child(InspectorKit.field("Members are named", vn))
box.add_child(InspectorKit.note("Each member is the value @%s_<name>, e.g. @%s_pilot. Choices can offer “one of your %s”." % [t.var_name, t.var_name, Inspector._title_of(t.name, "members")], Style.MUTED, 13))

View file

@ -139,13 +139,8 @@ func set_raw(t: String) -> void:
# ---------- UI ----------
func _render() -> void:
var focus_key := ""
var f := get_viewport().gui_get_focus_owner() if is_inside_tree() else null
if f and is_ancestor_of(f) and f.has_meta(InspectorKit.KEY):
focus_key = str(f.get_meta(InspectorKit.KEY))
for c in get_children():
remove_child(c)
c.queue_free()
var focus_key := InspectorKit.focused_tag(self)
InspectorKit.clear(self)
if text_mode:
_render_text()
else:
@ -165,15 +160,9 @@ func _render() -> void:
var add := InspectorKit.link(add_label, "Add a comparison")
add.pressed.connect(func() -> void: add_clause())
foot.add_child(add)
var as_text := InspectorKit.link("Edit as text", "Edit this condition as rule text")
as_text.add_theme_color_override("font_color", Style.MUTED)
as_text.pressed.connect(func() -> void: set_text_mode(true))
foot.add_child(as_text)
foot.add_child(InspectorKit.as_text_link("Edit this condition as rule text", set_text_mode.bind(true)))
add_child(foot)
if focus_key != "":
var c := InspectorKit.find_tagged(self, focus_key)
if c:
c.grab_focus.call_deferred()
InspectorKit.refocus(self, focus_key)
func _render_text() -> void:

View file

@ -167,13 +167,8 @@ func set_raw(t: String) -> void:
# ---------- UI ----------
func _render() -> void:
var focus_key := ""
var f := get_viewport().gui_get_focus_owner() if is_inside_tree() else null
if f and is_ancestor_of(f) and f.has_meta(InspectorKit.KEY):
focus_key = str(f.get_meta(InspectorKit.KEY))
for c in get_children():
remove_child(c)
c.queue_free()
var focus_key := InspectorKit.focused_tag(self)
InspectorKit.clear(self)
if text_mode:
_render_text()
else:
@ -184,15 +179,9 @@ func _render() -> void:
add.pressed.connect(add_row)
InspectorKit.tag(add, _key + ".add")
foot.add_child(add)
var as_text := InspectorKit.link("Edit as text", "Edit these changes as rule text")
as_text.add_theme_color_override("font_color", Style.MUTED)
as_text.pressed.connect(func() -> void: set_text_mode(true))
foot.add_child(as_text)
foot.add_child(InspectorKit.as_text_link("Edit these changes as rule text", set_text_mode.bind(true)))
add_child(foot)
if focus_key != "":
var c := InspectorKit.find_tagged(self, focus_key)
if c:
c.grab_focus.call_deferred()
InspectorKit.refocus(self, focus_key)
func _render_text() -> void:

View file

@ -26,10 +26,7 @@ static func line(text: String, placeholder: String = "", min_w: float = 0.0) ->
le.add_theme_stylebox_override("normal", _field_box(Style.RULE))
le.add_theme_stylebox_override("focus", _field_box(Style.COPPER))
le.add_theme_stylebox_override("read_only", _field_box(Style.RULE))
le.add_theme_color_override("font_color", Style.INK)
le.add_theme_color_override("caret_color", Style.INK)
le.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
le.add_theme_color_override("font_placeholder_color", Style.MUTED)
Style.field_colors(le)
le.add_theme_font_override("font", Style.body())
le.add_theme_font_size_override("font_size", 15)
le.add_theme_constant_override("minimum_character_width", 0)
@ -59,10 +56,7 @@ static func text_box(text: String, placeholder: String = "", min_h: float = 70.0
te.scroll_fit_content_height = true
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(FIELD_BG, 6, [8, 6, 8, 6]), 1, Style.RULE))
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(FIELD_BG, 6, [8, 6, 8, 6]), 1, Style.COPPER))
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
Style.field_colors(te)
te.add_theme_color_override("background_color", Color(0, 0, 0, 0))
te.add_theme_font_override("font", Style.body())
te.add_theme_font_size_override("font_size", 15)
@ -176,8 +170,7 @@ static func check_box(text: String, on: bool) -> CheckBox:
cb.button_pressed = on
cb.add_theme_font_override("font", Style.body_bold())
cb.add_theme_font_size_override("font_size", 15)
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_hover_pressed_color", "font_focus_color"]:
cb.add_theme_color_override(c, Style.INK)
Style.font_colors(cb, Style.INK)
cb.add_theme_color_override("font_disabled_color", Style.MUTED)
return cb
@ -218,6 +211,37 @@ static func tag(c: Control, key: String) -> Control:
return c
## The tag of the focused control inside `root` ("" if none), so a rebuild
## can give focus back with `refocus`.
static func focused_tag(root: Control) -> String:
var f := root.get_viewport().gui_get_focus_owner() if root.is_inside_tree() else null
if f and root.is_ancestor_of(f) and f.has_meta(KEY):
return str(f.get_meta(KEY))
return ""
static func refocus(root: Node, key: String) -> void:
if key == "":
return
var c := find_tagged(root, key)
if c:
c.grab_focus.call_deferred()
static func clear(box: Node) -> void:
for c in box.get_children():
box.remove_child(c)
c.queue_free()
## The muted "Edit as text" link at the foot of a builder.
static func as_text_link(tip: String, on_press: Callable) -> Button:
var b := link("Edit as text", tip)
b.add_theme_color_override("font_color", Style.MUTED)
b.pressed.connect(on_press)
return b
static func find_tagged(root: Node, key: String) -> Control:
for c in root.get_children():
if c is Control and c.has_meta(KEY) and str(c.get_meta(KEY)) == key:

View file

@ -32,16 +32,7 @@ signal test_requested
func setup(can_reset: bool, can_import: bool) -> void:
var ref := ModalCard.bar_menu_button("")
for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]:
add_theme_stylebox_override(n, ref.get_theme_stylebox(n))
for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
add_theme_color_override(c, ref.get_theme_color(c))
add_theme_font_size_override("font_size", 15)
ref.free()
mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
flat = false
text = "Board ▾"
Style.menu_button("Board ▾", false, self)
tooltip_text = "Reset, import and export"
var pm := get_popup()
ModalCard.style_popup(pm)

3580
ui/main.gd

File diff suppressed because it is too large Load diff

479
ui/main_cli.gd Normal file
View file

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

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

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

164
ui/main_collections.gd Normal file
View file

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

View file

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

372
ui/main_editing.gd Normal file
View file

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

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

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

372
ui/main_groups.gd Normal file
View file

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

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

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

357
ui/main_history.gd Normal file
View file

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

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

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

109
ui/main_inspector.gd Normal file
View file

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

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

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

328
ui/main_navigation.gd Normal file
View file

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

View file

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

398
ui/main_rolling.gd Normal file
View file

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

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

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

255
ui/main_state.gd Normal file
View file

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

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

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

141
ui/main_templates.gd Normal file
View file

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

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

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

318
ui/main_top_bar.gd Normal file
View file

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

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

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

View file

@ -173,10 +173,7 @@ static func segmented(options: Array, selected: int, on_change: Callable) -> Pan
static func style_line_edit(le: LineEdit) -> void:
le.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.DASH))
le.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
le.add_theme_color_override("font_color", Style.INK)
le.add_theme_color_override("caret_color", Style.INK)
le.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
le.add_theme_color_override("font_placeholder_color", Style.MUTED)
Style.field_colors(le)
le.add_theme_constant_override("minimum_character_width", 4)
le.size_flags_horizontal = SIZE_EXPAND_FILL
@ -184,10 +181,7 @@ static func style_line_edit(le: LineEdit) -> void:
static func style_text_edit(te: TextEdit) -> void:
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 7, [10, 7, 10, 7]), 1, Style.DASH))
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 7, [10, 7, 10, 7]), 1, Style.COPPER))
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
Style.field_colors(te)
te.add_theme_color_override("background_color", Color(0, 0, 0, 0))
@ -209,19 +203,9 @@ static func style_popup(pm: PopupMenu) -> void:
## A top-bar styled MenuButton (same look as Style.bar_button).
static func bar_menu_button(text: String) -> MenuButton:
var mb := MenuButton.new()
mb.text = text
var ref := Style.bar_button(text)
for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]:
mb.add_theme_stylebox_override(n, ref.get_theme_stylebox(n))
for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
mb.add_theme_color_override(c, ref.get_theme_color(c))
var mb := Style.menu_button(text)
mb.add_theme_color_override("font_disabled_color", Style.ON_FELT_MUTED)
mb.add_theme_font_size_override("font_size", 15)
mb.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
mb.flat = false
style_popup(mb.get_popup())
ref.free()
return mb

View file

@ -11,6 +11,9 @@ extends PanelContainer
## the chip shows the same reasons. Screenshot flag: --why[=<step index>]
## opens the pop-over for that step (default: the last one with reasons)
## after a roll.
##
## Pieces: TrayChips builds the chips and links, TrayText words them, and
## EarlierRolls is the Earlier tab.
enum Side { EARLIER, VARIABLES }
@ -25,9 +28,7 @@ var _again: Button
var _copy: MenuButton
var _flow: HFlowContainer
var _empty: Label
var _earlier_box: VBoxContainer
var _earlier: VBoxContainer
var _earlier_empty: Label
var _earlier: EarlierRolls
var _vars: VariablesPanel
var _tab_earlier: Button
var _tab_vars: Button
@ -56,8 +57,6 @@ const TAIL := 12
const MAX_EXPANDED := 300
## The chips area scrolls past this height instead of pushing the board up.
const MAX_FLOW_HEIGHT := 200.0
## Most effect lines listed under one chip.
const EFFECT_LINES := 3
func setup(p_main: Main) -> void:
@ -159,14 +158,9 @@ func setup(p_main: Main) -> void:
_tab_vars.pressed.connect(func() -> void: set_side(Side.VARIABLES))
tabs.add_child(_tab_vars)
_earlier_box = VBoxContainer.new()
_earlier_box.add_theme_constant_override("separation", 6)
right.add_child(_earlier_box)
_earlier = VBoxContainer.new()
_earlier.add_theme_constant_override("separation", 6)
_earlier_box.add_child(_earlier)
_earlier_empty = Style.make_label("Older rolls show here.", Style.body(), 15, Style.ON_FELT_MUTED)
_earlier_box.add_child(_earlier_empty)
_earlier = EarlierRolls.new()
_earlier.setup(main)
right.add_child(_earlier)
_vars = VariablesPanel.new()
_vars.setup(main)
right.add_child(_vars)
@ -200,7 +194,7 @@ func set_side(s: int) -> void:
side = s
_tab_earlier.set_pressed_no_signal(s == Side.EARLIER)
_tab_vars.set_pressed_no_signal(s == Side.VARIABLES)
_earlier_box.visible = s == Side.EARLIER
_earlier.visible = s == Side.EARLIER
_vars.visible = s == Side.VARIABLES
if s == Side.VARIABLES:
_vars.render()
@ -261,12 +255,12 @@ func render() -> void:
_copy.visible = done
var first := visible_from(steps.size(), expanded)
if first > 0 or expanded and steps.size() > TAIL:
_flow.add_child(_earlier_toggle(first, steps.size()))
_flow.add_child(TrayChips.earlier_toggle(self, first, steps.size()))
for i in range(first, steps.size()):
var step: Dictionary = steps[i]
if i > first:
_flow.add_child(_link(step.get("inline", false)))
var chip := _chip(step, done and i == steps.size() - 1, steps, i)
_flow.add_child(TrayChips.link(step.get("inline", false)))
var chip := TrayChips.chip(self, step, done and i == steps.size() - 1, steps, i)
_flow.add_child(chip)
if i >= fresh_from and not current.get("fast", false):
chip.modulate.a = 0.3
@ -274,25 +268,10 @@ func render() -> void:
var asking := str(current.get("asking", ""))
if asking != "" and not done:
if steps.size() > first:
_flow.add_child(_link(false))
_flow.add_child(_asking_chip(asking))
_flow.add_child(TrayChips.link(false))
_flow.add_child(TrayChips.asking_chip(asking))
for c in _earlier.get_children():
_earlier.remove_child(c)
c.queue_free()
_earlier_empty.visible = main.history.is_empty()
for rec in main.history:
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 8)
var time := Style.make_label(clock(rec["time"]), Style.body(), 14, Style.ON_FELT_MUTED)
time.custom_minimum_size = Vector2(44, 0)
time.size_flags_vertical = SIZE_SHRINK_BEGIN
row.add_child(time)
var line := RichText.label(earlier_line(rec), 14, Style.ON_FELT, false)
line.size_flags_horizontal = SIZE_EXPAND_FILL
RichText.hook_hover(line, main)
row.add_child(line)
_earlier.add_child(row)
_earlier.render()
var n := main.variable_names().size()
_tab_vars.text = "VARIABLES · %d" % n if n > 0 else "VARIABLES"
@ -356,36 +335,6 @@ static func visible_from(count: int, is_expanded: bool) -> int:
return count - TAIL
## One Earlier row: "Root: a → b → c", with only the last few steps of a long
## chain.
static func earlier_line(rec: Dictionary) -> String:
var texts := PackedStringArray()
var all: Array = rec.get("steps", [])
var shown := 0
var skipped := 0
for k in range(all.size() - 1, -1, -1):
var s: Dictionary = all[k]
if s.get("inline", false):
continue
if shown >= 6:
skipped += 1
continue
texts.insert(0, RichText.decorate(_one_line(str(s["text"])), true))
shown += 1
var lead := "[color=#%s]%s:[/color] " % [Style.ON_FELT_MUTED.to_html(false), RichText.plain(Formatter.strip_tags(str(rec.get("root_name", ""))))]
if skipped > 0:
lead += "[color=#%s]… %d earlier →[/color] " % [Style.ON_FELT_MUTED.to_html(false), skipped]
return lead + " → ".join(texts)
## The first line of a (sheet's) multi-line text, with "…" when there's more.
static func _one_line(text: String) -> String:
var nl := text.find("\n")
if nl < 0:
return text
return Formatter.close_open_tags(text.substr(0, nl)) + " …"
## The "Cancelled" / "Stopped after 10,000 actions" pill, and the sheet headline.
func _render_status(current: Dictionary, steps: Array) -> void:
var halted := str(current.get("halted", ""))
@ -400,7 +349,7 @@ func _render_status(current: Dictionary, steps: Array) -> void:
_halt_label.text = ("✕ " if halted == Roller.CANCELLED else "⚠ ") + halted
_halt.tooltip_text = "The roll was cancelled at a question; what came before is kept." if halted == Roller.CANCELLED \
else "This roll took too many steps, so it stopped; everything up to that point is kept."
var sheet := sheet_step(steps) if current.get("done", false) else {}
var sheet := TrayText.sheet_step(steps) if current.get("done", false) else {}
_headline.visible = not sheet.is_empty()
if not sheet.is_empty():
_headline_cap.text = Formatter.strip_tags(str(sheet.get("table", ""))).to_upper()
@ -408,15 +357,6 @@ func _render_status(current: Dictionary, steps: Array) -> void:
_fit_headline()
## The last sheet step of a chain (the headline), or {}.
static func sheet_step(steps: Array) -> Dictionary:
for k in range(steps.size() - 1, -1, -1):
var s: Dictionary = steps[k]
if str(s.get("kind", "")) == RollTable.KIND_SHEET and not s.get("stop", false):
return s
return {}
func _fit_scroll() -> void:
if _scroll == null or _flow == null:
return
@ -431,280 +371,6 @@ func _fit_scroll() -> void:
_scroll.scroll_vertical = int(_scroll.get_v_scroll_bar().max_value)
## "+N earlier steps" (or "Hide earlier steps") at the start of a long chain.
func _earlier_toggle(first: int, total: int) -> Control:
var b := Button.new()
if expanded:
b.text = "Hide earlier steps" if first == 0 else "Hide earlier steps (%s not shown)" % _thousands(first)
else:
b.text = "+%s earlier steps" % _thousands(first)
b.tooltip_text = "This chain has %s steps" % _thousands(total)
b.size_flags_vertical = SIZE_SHRINK_CENTER
var n := Style.bordered(Style.box(Color(1, 1, 1, 0.04), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16))
var h := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 8, [12, 6, 12, 6]), 1, Color(Style.BRASS, 0.5))
Style.skin_button(b, n, h, h, Style.ON_FELT_MUTED, Style.ON_FELT)
b.add_theme_font_size_override("font_size", 14)
b.pressed.connect(func() -> void:
expanded = not expanded
render()
)
var wrap := HBoxContainer.new()
wrap.add_theme_constant_override("separation", 0)
wrap.add_child(b)
var gap := Control.new()
gap.custom_minimum_size = Vector2(10, 0)
wrap.add_child(gap)
return wrap
static func _thousands(n: int) -> String:
var s := str(n)
var out := ""
while s.length() > 3:
out = "," + s.substr(s.length() - 3) + out
s = s.substr(0, s.length() - 3)
return s + out
## A dashed placeholder chip for the question that is open right now.
func _asking_chip(title: String) -> Control:
var p := PanelContainer.new()
var sb := Style.box(Color(1, 1, 1, 0.05), 9, [12, 7, 12, 8])
Style.bordered(sb, 1, Color(Style.BRASS, 0.6))
p.add_theme_stylebox_override("panel", sb)
p.size_flags_vertical = SIZE_SHRINK_CENTER
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 1)
p.add_child(v)
v.add_child(Style.make_label(title, Style.body(), 12, Style.ON_FELT_MUTED))
v.add_child(Style.make_label("Waiting for your answer…", Style.display(), 20, Style.BRASS))
return p
## The muted line above a chip's text: table name and how it got its result.
## With `plain`, rules read in plain words ("Loot · Tier 1 · rolled 4 on 1D +
## Tier", "Force the gate · rolled 7, +1 → 8"), labelled from `board`.
static func caption_for(step: Dictionary, board: TowerBoard = null, plain: bool = false) -> String:
var caption := Formatter.strip_tags(str(step["table"]))
var num: String = str(step.get("num", ""))
var ins: Variant = step.get("inputs")
if ins is Dictionary:
for nm: Variant in ins:
if plain:
caption += " · %s %s" % [Describe.label(str(nm), board), Expr.format_value(ins[nm])]
else:
caption += " · %s=%s" % [nm, Expr.format_value(ins[nm])]
match str(step.get("kind", "")):
RollTable.KIND_CHECK:
var c: Variant = step.get("check")
if c is Dictionary:
var mod := int(c.get("mod", 0))
var ms := ""
if mod != 0:
ms = ("+%d" % mod) if mod > 0 else (Describe.MINUS + str(-mod))
if plain:
caption += " · rolled %s%s → %s" % [Expr.format_value(c.get("nat")), (", " + ms) if ms != "" else "", Expr.format_value(c.get("total"))]
else:
caption += " · %s%s = %s vs %s" % [Expr.format_value(c.get("nat")), ms.replace(Describe.MINUS, "-"), Expr.format_value(c.get("total")), Expr.format_value(c.get("target"))]
RollTable.KIND_CHOICE:
if step.get("cancelled", false):
pass
elif step.has("answer"):
caption += " · answered"
elif step.get("picked", false):
caption += " · picked"
elif step.get("random", false):
caption += " · random"
if num != "":
caption += ", rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))]
RollTable.KIND_LOOP:
if step.has("pass"):
caption += " · pass %s" % str(step["pass"])
elif step.get("after", false):
caption += " · afterwards"
RollTable.KIND_SHEET:
caption += " · sheet"
RollTable.KIND_ROUTER:
if step.has("case"):
var said := false
if plain and board != null:
var rt := board.get_table(str(step.get("table_id", "")))
var k := int(step["case"])
if rt != null and k >= 0 and k < rt.entries.size():
caption += " · " + RulesView.cut(RulesView.case_label(rt.entries[k], board, true), 44)
said = true
if not said:
caption += " · case %d" % (int(step["case"]) + 1)
_:
if num != "":
var dl := str(step.get("dice", "d%d" % int(step.get("die", 0))))
if plain and dl.contains(" "):
dl = RulesView.cut(Describe.dice(dl, board), 30)
caption += " · rolled %s on %s" % [num, dl]
if step.get("reshuffled", false):
caption += " · deck reshuffled"
if str(step.get("save_as", "")) != "":
if plain:
caption += " · saved as %s" % Describe.label(str(step["save_as"]), board)
else:
caption += " · saved as {%s}" % step["save_as"]
return caption
func _chip(step: Dictionary, last: bool, steps: Array = [], index: int = -1) -> Control:
var inline: bool = step.get("inline", false)
var p := PanelContainer.new()
var sb := Style.box(Style.LIT if last else Style.CARD, 9, [10, 5, 10, 6] if inline else [12, 7, 12, 8])
sb.shadow_color = Color(0, 0, 0, 0.25)
sb.shadow_size = 1
sb.shadow_offset = Vector2(0, 3)
if last:
Style.bordered(sb, 2, Style.BRASS)
sb.set_expand_margin_all(2)
if inline:
sb.bg_color = sb.bg_color.darkened(0.04)
p.add_theme_stylebox_override("panel", sb)
p.size_flags_vertical = SIZE_SHRINK_CENTER
p.mouse_filter = MOUSE_FILTER_PASS
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 1)
p.add_child(v)
var plain := RulesView.plain(main)
var caption := caption_for(step, main.data, plain)
var has_why := index >= 0 and WhyPopover.has_why(steps, index)
var has_details := main.details().step_has_details(step)
if has_details:
caption += " " + RichText.INFO_MARK
var cap := Style.make_label(caption, Style.body(), 11 if inline else 12, Style.MUTED)
cap.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(cap)
var raw := str(step["text"])
if str(step.get("kind", "")) == RollTable.KIND_SHEET:
raw = _one_line(raw)
if step.has("answer") and Formatter.strip_tags(raw).strip_edges() == "":
raw = "[i]no answer[/i]"
var shown := RichText.decorate(raw)
var body := RichText.display_label(shown, 16 if inline else 20, Style.DANGER_INK if step.get("stop", false) else Style.INK)
if Formatter.strip_tags(shown).length() > 56:
body.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
body.custom_minimum_size = Vector2(420, 0)
RichText.hook_hover(body, main)
v.add_child(body)
var fx: Array = step.get("effects", [])
if not fx.is_empty():
v.add_child(_effect_lines(effect_lines_for(step, main.data, plain)))
if has_why:
var wb := _why_button()
wb.pressed.connect(func() -> void: open_why(index, wb))
why_buttons[index] = wb
v.add_child(wb)
if has_details or has_why:
p.mouse_entered.connect(func() -> void:
if not _why.visible:
main.details().show_step(p, step, steps, index))
return p
## The small "Why this?" pill under a chip.
func _why_button() -> Button:
var b := Button.new()
b.text = "Why this?"
b.tooltip_text = "What decided this step"
b.size_flags_horizontal = SIZE_SHRINK_BEGIN
b.focus_mode = Control.FOCUS_NONE
var n := Style.bordered(Style.box(Color.WHITE, 10, [9, 1, 9, 2]), 1, Style.RULE)
var h := Style.bordered(Style.box(Style.LIT, 10, [9, 1, 9, 2]), 1, Style.BRASS_DARK)
Style.skin_button(b, n, h, h, Style.COPPER_DARK, Style.INK)
b.add_theme_font_override("font", Style.body_bold())
b.add_theme_font_size_override("font_size", 12)
return b
## A step's effect lines for its chip: in plain words, one per value that
## changed ("Luck 2 → 1", "Town = Millbrook", "Cleared all Skills (3)") from
## its why facts, then any errors from its log; else the log as it is.
static func effect_lines_for(step: Dictionary, board: TowerBoard, plain: bool) -> Array:
var fx: Array = step.get("effects", [])
if not plain or not (step.get("why") is Array):
return fx
var out: Array = []
for f: Variant in step["why"]:
if f is Dictionary and str(f.get("type", "")) == "effect":
out.append({"text": effect_fact_line(f, board)})
if out.is_empty():
return fx
for l: Variant in fx:
if l is Dictionary and (l as Dictionary).get("error", false):
out.append(l)
return out
## "Luck 2 → 1", "Town = Millbrook", "Loot cleared", "Cleared all Skills (3)".
static func effect_fact_line(f: Dictionary, board: TowerBoard) -> String:
var lab := Describe.label(str(f.get("var", "")), board)
if f.has("count"):
return "Cleared all %s (%s)" % [lab, Expr.format_value(f["count"])]
var before: Variant = f.get("before")
var after: Variant = f.get("after")
if after == null:
return "%s cleared" % lab
var a := Expr.format_value(after)
if before == null or Expr.format_value(before) == "":
return "%s = %s" % [lab, a if a != "" else "(none)"]
return "%s %s → %s" % [lab, Expr.format_value(before), a if a != "" else "(none)"]
## The effect log under a chip: a few compact lines, errors in red.
func _effect_lines(fx: Array) -> Control:
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 0)
box.mouse_filter = MOUSE_FILTER_IGNORE
var shown := 0
var errors := 0
for l: Variant in fx:
var d: Dictionary = l if l is Dictionary else {"text": str(l)}
var bad: bool = d.get("error", false)
if bad:
errors += 1
# Errors are always listed; ordinary lines up to EFFECT_LINES.
if shown >= EFFECT_LINES and not bad:
continue
var lab := Style.make_label(("⚠ " if bad else "") + str(d.get("text", "")), Style.body_bold() if bad else Style.body(), 12,
Style.DANGER_INK if bad else Style.COPPER_DARK)
lab.mouse_filter = MOUSE_FILTER_IGNORE
lab.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
lab.custom_minimum_size.x = 0
box.add_child(lab)
shown += 1
var more := fx.size() - shown
if more > 0:
box.add_child(Style.make_label("+%d more" % more, Style.body(), 11, Style.MUTED))
var tip := Effects.log_text(fx)
box.tooltip_text = "\n".join(tip)
return box
func _link(inline: bool = false) -> Control:
var link := Panel.new()
var sb := Style.box(Style.BRASS)
sb.border_width_top = 2
sb.border_width_bottom = 2
sb.border_color = Style.BRASS_DARK
if inline:
sb = Style.box(Color(Style.BRASS, 0.55))
link.add_theme_stylebox_override("panel", sb)
link.custom_minimum_size = Vector2(16, 4) if inline else Vector2(22, 8)
link.size_flags_vertical = SIZE_SHRINK_CENTER
link.mouse_filter = MOUSE_FILTER_IGNORE
return link
static func clock(unix: float) -> String:
var bias: int = Time.get_time_zone_from_system().get("bias", 0)
var d := Time.get_datetime_dict_from_unix_time(int(unix) + bias * 60)
return "%02d:%02d" % [d["hour"], d["minute"]]
## Sizes the sheet headline's scroll area to its text, up to HEADLINE_MAX_H.
func _fit_headline() -> void:
await get_tree().process_frame

327
ui/settings_kind_fields.gd Normal file
View file

@ -0,0 +1,327 @@
class_name SettingsKindFields
extends RefCounted
## The kind-specific part of a TableSettingsDialog (docs/LOGIC.md): the
## fields shown for a choice, loop, variable, sheet or router card, their
## part of the settings Dictionary, and their live checks.
var d: TableSettingsDialog
var table: RollTable
## The kind's problems, shown under its fields (null for roll tables).
var problem: Label
var _choice := "pick"
var _choice_note: Label
var _prompt: LineEdit
var _save_as: LineEdit
var _min: LineEdit
var _max: LineEdit
var _minmax_row: Control
## Pick choices: "fixed" or "vars" (options from variables, plus fixed extras).
var _options_mode := "fixed"
var _options_box: Control
var _opt_mode_box: Control
var _opt_from: LineEdit
var _opt_where: LineEdit
var _opt_note: Label
var _show_if_box: Control
## entry id -> its Show only if field.
var _show_if: Dictionary = {}
var _loop_mode := "times"
var _loop_expr: LineEdit
var _loop_note: Label
var _var_name: LineEdit
var _var_type := "number"
var _initial: LineEdit
var _template: TextEdit
var _template_preview: RichTextLabel
## Router cards: one condition field per case, in order.
var _cases: Array[LineEdit] = []
var _case_note: Label
func _init(dialog: TableSettingsDialog) -> void:
d = dialog
table = dialog.table
_choice = table.choice
_options_mode = "vars" if table.options_from.strip_edges() != "" else "fixed"
_loop_mode = table.loop_mode
_var_type = table.var_type
## Adds the kind's settings to `s`.
func add_settings(s: Dictionary) -> void:
match table.kind:
RollTable.KIND_CHOICE:
s["choice"] = _choice
s["prompt"] = _prompt.text
s["save_as"] = _save_as.text.strip_edges()
s["min"] = _min.text.strip_edges()
s["max"] = _max.text.strip_edges()
s["options_mode"] = _options_mode
s["options_from"] = _opt_from.text.strip_edges()
s["options_where"] = _opt_where.text.strip_edges()
var si := {}
for eid: String in _show_if:
si[eid] = (_show_if[eid] as LineEdit).text.strip_edges()
s["show_if"] = si
RollTable.KIND_LOOP:
s["loop_mode"] = _loop_mode
s["loop_expr"] = _loop_expr.text.strip_edges()
RollTable.KIND_VARIABLE:
s["var_name"] = _var_name.text.strip_edges().trim_prefix("@")
s["var_type"] = _var_type
s["initial"] = _initial.text.strip_edges()
RollTable.KIND_SHEET:
s["template"] = _template.text
RollTable.KIND_ROUTER:
var cases: Array = []
for le in _cases:
cases.append(le.text.strip_edges())
s["cases"] = cases
func build() -> void:
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 10)
match table.kind:
RollTable.KIND_CHOICE:
box.add_child(ModalCard.section("Question type"))
box.add_child(ModalCard.segmented(TableSettingsDialog.CHOICE_LABELS, RollTable.CHOICES.find(_choice), func(i: int) -> void:
_choice = RollTable.CHOICES[i]
d._refresh()
))
_choice_note = ModalCard.note("")
box.add_child(_choice_note)
_prompt = LineEdit.new()
_prompt.text = table.prompt
_prompt.placeholder_text = "Which way out? You have {@gold} gold."
ModalCard.style_line_edit(_prompt)
_prompt.text_changed.connect(func(_t: String) -> void: d._refresh())
box.add_child(ModalCard.field("Question (BBCode, {@var} works)", _prompt))
_save_as = LineEdit.new()
_save_as.text = table.save_as
_save_as.placeholder_text = "@name to keep, or a name for this roll"
ModalCard.style_line_edit(_save_as)
_save_as.text_changed.connect(func(_t: String) -> void: d._refresh())
box.add_child(ModalCard.field("Save the answer as (optional)", _save_as))
var mm := HBoxContainer.new()
mm.add_theme_constant_override("separation", 12)
_min = LineEdit.new()
_min.text = table.min_expr
ModalCard.style_line_edit(_min)
_min.text_changed.connect(func(_t: String) -> void: d._refresh())
_max = LineEdit.new()
_max.text = table.max_expr
ModalCard.style_line_edit(_max)
_max.text_changed.connect(func(_t: String) -> void: d._refresh())
mm.add_child(ModalCard.field("Lowest", _min))
mm.add_child(ModalCard.field("Highest", _max))
for c in mm.get_children():
(c as Control).size_flags_horizontal = Control.SIZE_EXPAND_FILL
_minmax_row = mm
box.add_child(mm)
_build_options(box)
RollTable.KIND_LOOP:
box.add_child(ModalCard.section("Repeat"))
box.add_child(ModalCard.segmented(TableSettingsDialog.LOOP_LABELS, RollTable.LOOPS.find(_loop_mode), func(i: int) -> void:
_loop_mode = RollTable.LOOPS[i]
d._refresh()
))
_loop_expr = LineEdit.new()
_loop_expr.text = table.loop_expr
ModalCard.style_line_edit(_loop_expr)
_loop_expr.text_changed.connect(func(_t: String) -> void: d._refresh())
box.add_child(ModalCard.field("How many times / condition", _loop_expr))
_loop_note = ModalCard.note("")
box.add_child(_loop_note)
RollTable.KIND_VARIABLE:
_var_name = LineEdit.new()
_var_name.text = table.var_name
_var_name.placeholder_text = "hp"
ModalCard.style_line_edit(_var_name)
_var_name.text_changed.connect(func(_t: String) -> void: d._refresh())
box.add_child(ModalCard.field("Variable name (used as @name)", _var_name))
box.add_child(ModalCard.section("Type"))
box.add_child(ModalCard.segmented(["Number", "Text", "List", "Collection"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void:
_var_type = RollTable.VAR_TYPES[i]
d._refresh()
))
_initial = LineEdit.new()
_initial.text = table.initial
_initial.placeholder_text = "10, 2d6, or a word"
ModalCard.style_line_edit(_initial)
_initial.text_changed.connect(func(_t: String) -> void: d._refresh())
box.add_child(ModalCard.field("Starting value", _initial))
box.add_child(ModalCard.note("reset @name, and Reset in the Variables tab, put it back to this."))
RollTable.KIND_SHEET:
_template = TextEdit.new()
_template.text = table.entries[0].text if not table.entries.is_empty() else ""
_template.placeholder_text = "[b]{@name}[/b]\nHP {@hp} · Gold {@gold}\nSkills: {@skill_*}"
_template.custom_minimum_size.y = 120
_template.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
ModalCard.style_text_edit(_template)
_template.text_changed.connect(d._refresh)
box.add_child(ModalCard.field("Template (BBCode with {@var}, {@prefix_*} and {= expr})", _template))
_template_preview = RichTextLabel.new()
_template_preview.bbcode_enabled = true
_template_preview.fit_content = true
_template_preview.scroll_active = false
var pbox := PanelContainer.new()
pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7]))
pbox.add_child(_template_preview)
box.add_child(pbox)
RollTable.KIND_ROUTER:
box.add_child(ModalCard.section("Cases (if / else if / otherwise)"))
box.add_child(ModalCard.note("Checked top to bottom when the chain arrives; the first true case is chosen, and its effects, text and pipes run like a rolled result. An empty condition is Otherwise: it always matches, so keep it last. Add, remove and reorder cases on the card."))
for i in table.entries.size():
var e := table.entries[i]
var le := LineEdit.new()
le.text = e.when
le.placeholder_text = "Otherwise (always)"
ModalCard.style_line_edit(le)
le.text_changed.connect(func(_t: String) -> void: d._refresh())
_cases.append(le)
var label := Formatter.strip_tags(e.text).strip_edges()
box.add_child(ModalCard.field("Case %d%s" % [i + 1, (" · " + label) if label != "" else ""], le))
if table.entries.is_empty():
box.add_child(ModalCard.note("This router has no cases yet: add some on the card."))
_case_note = ModalCard.note("", Style.WARN_INK)
box.add_child(_case_note)
_:
box.free() # roll tables have no kind fields
return
problem = ModalCard.note("", Style.DANGER_INK)
box.add_child(problem)
d.body.add_child(box)
## Pick choices: where the options come from, and a Show only if field per
## option.
func _build_options(box: VBoxContainer) -> void:
var mb := VBoxContainer.new()
mb.add_theme_constant_override("separation", 6)
mb.add_child(ModalCard.section("Options"))
mb.add_child(ModalCard.segmented(TableSettingsDialog.OPTION_LABELS, 1 if _options_mode == "vars" else 0, func(i: int) -> void:
_options_mode = "vars" if i == 1 else "fixed"
d._refresh()
))
box.add_child(mb)
_opt_mode_box = mb
var ob := VBoxContainer.new()
ob.add_theme_constant_override("separation", 8)
_opt_from = LineEdit.new()
_opt_from.text = table.options_from
_opt_from.placeholder_text = "@skill_* or @contacts"
ModalCard.style_line_edit(_opt_from)
_opt_from.text_changed.connect(func(_t: String) -> void: d._refresh())
ob.add_child(ModalCard.field("Options from (@prefix_* or a @list)", _opt_from))
_opt_where = LineEdit.new()
_opt_where.text = table.options_where
_opt_where.placeholder_text = "option_value >= 1 (optional)"
ModalCard.style_line_edit(_opt_where)
_opt_where.text_changed.connect(func(_t: String) -> void: d._refresh())
ob.add_child(ModalCard.field("Only where (optional)", _opt_where))
_opt_note = ModalCard.note("")
ob.add_child(_opt_note)
box.add_child(ob)
_options_box = ob
var sb := VBoxContainer.new()
sb.add_theme_constant_override("separation", 6)
sb.add_child(ModalCard.section("Show only if"))
sb.add_child(ModalCard.note("Checked when the card is reached. An option whose condition is false isn't offered, not even to Random. Empty means always."))
for i in table.entries.size():
var e := table.entries[i]
var le := LineEdit.new()
le.text = e.show_if
le.placeholder_text = "always"
ModalCard.style_line_edit(le)
le.text_changed.connect(func(_t: String) -> void: d._refresh())
_show_if[e.id] = le
var label := Formatter.strip_tags(e.text).strip_edges()
var cap := "Chosen (every option from variables)" if (i == 0 and table.is_dynamic()) else "Option %d%s" % [i + (0 if table.is_dynamic() else 1), (" · " + label) if label != "" else ""]
sb.add_child(ModalCard.field(cap, le))
box.add_child(sb)
_show_if_box = sb
func refresh() -> void:
var s := d.settings()
var problems := TableSettingsRules.kind_problems(table, s)
if problem:
problem.text = "\n".join(problems)
problem.visible = not problems.is_empty()
match table.kind:
RollTable.KIND_CHOICE:
_minmax_row.visible = _choice == "number"
var msg := ""
if _choice != table.choice and table.choice == "pick":
msg = "Only the first option is kept, as the Answer row (its effects and pipes stay)."
elif _choice != table.choice and _choice == "pick":
msg = "The Answer row becomes the first option; two more are added."
elif _choice == "pick" and _options_mode == "vars" and table.is_dynamic():
msg = "The player picks one of the options from variables or a fixed extra, or Random."
elif _choice == "pick" and _options_mode == "fixed" and table.is_dynamic():
msg = "Back to a fixed list: the Chosen row becomes an ordinary option (or goes, if it does nothing)."
elif _choice == "pick":
msg = "The player picks one of the card's options, or Random."
else:
msg = "The answer goes in {answer}; the Answer row's effects and pipes run after it."
_choice_note.text = msg
_mark(_save_as, s["save_as"] == "" or TableSettingsRules._re(TableSettingsRules.SAVE_PATTERN).search(TemplateKit.probe(s["save_as"])) != null)
var pick := _choice == "pick"
_opt_mode_box.visible = pick
_options_box.visible = pick and _options_mode == "vars"
_show_if_box.visible = pick and not _show_if.is_empty()
if pick and _options_mode == "vars":
_mark(_opt_from, TableSettingsRules.options_from_error(s["options_from"]) == "")
_mark(_opt_where, TableSettingsRules.when_error(s["options_where"]) == "")
var desc := RollTable.new()
desc.options_from = s["options_from"]
desc.options_where = s["options_where"]
var how := "One option for %s, labelled with its name and value, after any fixed options. The Chosen row runs for whichever is picked; option, option_label and option_value hold it, e.g. @[option] += 1." % desc.options_description() \
if TableSettingsRules.options_from_error(s["options_from"]) == "" else "Write @skill_* for each set variable with that prefix, or @contacts for each item of a list."
if not table.is_dynamic():
how += " A Chosen row is added first; the options already on the card stay as fixed extras."
_opt_note.text = how
elif pick and table.is_dynamic():
_opt_note.text = ""
for eid: String in _show_if:
_mark(_show_if[eid] as LineEdit, TableSettingsRules.when_error((_show_if[eid] as LineEdit).text) == "")
_mark(_min, Expr.check(TemplateKit.probe(s["min"])) == "" and s["min"] != "")
_mark(_max, Expr.check(TemplateKit.probe(s["max"])) == "" and s["max"] != "")
RollTable.KIND_LOOP:
_loop_note.text = TableSettingsDialog.LOOP_NOTES.get(_loop_mode, "")
_mark(_loop_expr, s["loop_expr"] != "" and Expr.check(TemplateKit.probe(s["loop_expr"])) == "")
RollTable.KIND_VARIABLE:
_mark(_var_name, TableSettingsRules._re(TableSettingsRules.VAR_PATTERN).search(TemplateKit.probe(s["var_name"])) != null)
_mark(_initial, TableSettingsRules._initial_error(s["initial"], _var_type) == "")
RollTable.KIND_SHEET:
var ctx := Roller.live_context(table_board(), _live_vars())
_template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \
else "[color=#69726b]Preview appears here.[/color]"
RollTable.KIND_ROUTER:
var cases: Array = s["cases"]
for i in _cases.size():
_mark(_cases[i], TableSettingsRules.when_error(str(cases[i])) == "")
var hint := TableSettingsRules.router_hint(cases)
_case_note.text = hint
_case_note.visible = hint != ""
# The ranged/card-mode sections only apply to roll tables and pick choices.
var rolls := table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and _choice == "pick")
d._type_box.visible = rolls
d._card_box.visible = rolls
func _mark(le: LineEdit, ok: bool) -> void:
le.add_theme_color_override("font_color", Style.INK if ok else Style.DANGER_INK)
## The board and variables for the sheet preview, when the dialog sits in Main.
func table_board() -> TowerBoard:
var m := d.get_parent() as Main
return m.data if m else TowerBoard.new()
func _live_vars() -> Dictionary:
var m := d.get_parent() as Main
return m.persistent_vars if m else {}

View file

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

View file

@ -160,6 +160,43 @@ static func bar_button(text: String, primary: bool = false) -> Button:
return b
## A MenuButton skinned like bar_button (copies its boxes and colours onto
## `onto`, or a new MenuButton). The caller styles the popup.
static func menu_button(text: String, primary: bool = false, onto: MenuButton = null) -> MenuButton:
var mb := onto if onto else MenuButton.new()
mb.text = text
var ref := bar_button(text, primary)
for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]:
mb.add_theme_stylebox_override(n, ref.get_theme_stylebox(n))
for c in BUTTON_FONT_COLORS:
mb.add_theme_color_override(c, ref.get_theme_color(c))
ref.free()
if primary:
mb.add_theme_font_override("font", body_bold())
mb.add_theme_font_size_override("font_size", 15)
mb.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
mb.flat = false
return mb
const BUTTON_FONT_COLORS: Array[String] = ["font_color", "font_hover_color", "font_focus_color",
"font_pressed_color", "font_hover_pressed_color"]
## One font colour for every state of a button (normal, hover, focus, pressed).
static func font_colors(c: Control, color: Color) -> void:
for n in BUTTON_FONT_COLORS:
c.add_theme_color_override(n, color)
## Ink text, caret, brass selection and muted placeholder for a LineEdit or TextEdit.
static func field_colors(c: Control) -> void:
c.add_theme_color_override("font_color", INK)
c.add_theme_color_override("caret_color", INK)
c.add_theme_color_override("selection_color", Color(BRASS, 0.55))
c.add_theme_color_override("font_placeholder_color", MUTED)
## The Plain words / Text switch's look (docs/PLAIN.md §5; the switch itself
## is Main's): two segment buttons on the felt, the chosen one card-coloured.
## Adds them to `into` and returns [plain_button, text_button]; `on_change`

File diff suppressed because it is too large Load diff

235
ui/table_card_editing.gd Normal file
View file

@ -0,0 +1,235 @@
class_name TableCardEditing
extends RefCounted
## A TableCard's Build-mode controls: the inline result-text, weight and range
## fields, router case rows with move and delete, and the footer (add a
## result, option or case; delete the table). Everything else is edited in
## Main's inspector.
var card: TableCard
func _init(p_card: TableCard) -> void:
card = p_card
## Build mode: the inline result-text field of a row. Focusing it selects the
## result for the inspector.
func text_edit(e: TableEntry, index: int, chosen: bool) -> LineEdit:
var table := card.table
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 = Control.SIZE_EXPAND_FILL
edit.size_flags_vertical = Control.SIZE_SHRINK_CENTER
edit.custom_minimum_size = Vector2(40, 0)
edit.add_theme_font_size_override("font_size", 15)
var loop_rows := TableCardRows.LOOP_ROWS
if table.kind == RollTable.KIND_LOOP:
edit.placeholder_text = loop_rows[clampi(index, 0, 1)]
edit.tooltip_text = "%s: shown each pass ({i} is the pass number)" % loop_rows[0] if index == 0 else "%s: runs once when the loop ends" % loop_rows[1]
elif table.kind == RollTable.KIND_ROUTER:
edit.placeholder_text = "Result text"
edit.text_changed.connect(func(s: String) -> void:
e.text = s
card.main.mark_dirty()
)
edit.focus_entered.connect(func() -> void: card.select_entry(e.id))
return edit
## Build mode: a click on a row (outside its fields) selects the result for
## the inspector.
func hook_select(row: Control, eid: String) -> void:
row.gui_input.connect(func(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT and mb.pressed:
card.select_entry(eid)
)
## Build mode: one router case. The first line is its condition, in plain
## words or as written (edited in the inspector), with move up / down and
## delete; the second is its result text, then its effects chip.
func make_case_row(e: TableEntry, index: int, numw: float) -> Control:
var table := card.table
var main := card.main
var plain := card.plain
var row := PanelContainer.new()
row.mouse_filter = Control.MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var outer := TableCard.hbox(4)
row.add_child(outer)
var num := Style.make_label(str(index + 1), Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(numw, 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = Control.SIZE_SHRINK_BEGIN
outer.add_child(num)
var v := TableCard.vbox(3)
v.size_flags_horizontal = Control.SIZE_EXPAND_FILL
outer.add_child(v)
var top := TableCard.hbox(4)
v.add_child(top)
var w := e.when.strip_edges()
var bad := w != "" and Expr.check(TemplateKit.probe(w)) != ""
var cond := Style.make_label(RulesView.case_label(e, main.data, plain), Style.body_bold(true), 14, Style.DANGER_INK if bad else Style.COPPER_DARK)
cond.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
cond.size_flags_horizontal = Control.SIZE_EXPAND_FILL
cond.size_flags_vertical = Control.SIZE_SHRINK_CENTER
cond.mouse_filter = Control.MOUSE_FILTER_PASS
cond.tooltip_text = ("⚠ " + Expr.check(TemplateKit.probe(w))) if bad else (("if " + w) if plain and w != "" else "Cases are checked top to bottom; the first true one is chosen")
cond.set_meta("case_line", true)
top.add_child(cond)
top.add_child(mini_button("↑", "Move this case up", index > 0, func() -> void: _move_case(index, -1)))
top.add_child(mini_button("↓", "Move this case down", index < table.entries.size() - 1, func() -> void: _move_case(index, 1)))
top.add_child(mini_button("×", "Delete this case", true, func() -> void: main.delete_entry(table.id, e.id)))
v.add_child(text_edit(e, index, false))
card.rows_ui.add_rule_chips(v, e)
hook_select(row, e.id)
card.rows_ui.register(e, row, num, null, index)
return row
static func mini_button(glyph: String, tip: String, enabled: bool, on_press: Callable) -> Button:
var b := Button.new()
b.text = glyph
b.tooltip_text = tip
b.disabled = not enabled
b.custom_minimum_size = Vector2(22, 22)
b.size_flags_vertical = Control.SIZE_SHRINK_CENTER
b.add_theme_font_size_override("font_size", 16 if glyph == "×" else 13)
Style.skin_button(b, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK if glyph == "×" else Style.INK)
b.add_theme_color_override("font_disabled_color", Color(Style.MUTED, 0.35))
b.pressed.connect(on_press)
return b
## Moves router case `index` up (-1) or down (+1).
func _move_case(index: int, by: int) -> void:
var table := card.table
var to := index + by
if to < 0 or to >= table.entries.size():
return
var e := table.entries[index]
table.entries.remove_at(index)
table.entries.insert(to, e)
card.rebuild()
card.main.mark_dirty()
## Adds a router case just before the Otherwise case (or at the end). It
## starts as "if false", so it never matches until its condition is written.
func add_case() -> void:
var table := card.table
var e := TableEntry.new(TowerBoard.new_id("e"), "New case")
e.when = "false"
var at := table.otherwise_index()
if at < 0 or at != table.entries.size() - 1:
at = table.entries.size()
table.entries.insert(at, e)
table.collapsed = false
card.rebuild()
card.main.mark_dirty()
## Weight on a plain table, shown as ×N. Also the number of copies in card mode.
func weight_edit(e: TableEntry) -> LineEdit:
var edit := LineEdit.new()
edit.text = "×%d" % e.weight
edit.custom_minimum_size = Vector2(34, 0)
edit.alignment = HORIZONTAL_ALIGNMENT_CENTER
edit.max_length = 4
edit.tooltip_text = "Weight: how likely this result is, relative to the others (0 = never)"
edit.size_flags_vertical = Control.SIZE_SHRINK_CENTER
edit.add_theme_font_override("font", Style.display(true))
edit.add_theme_font_size_override("font_size", 14)
edit.add_theme_color_override("font_color", Style.MUTED)
var commit := func() -> void:
var digits := ""
for ch in edit.text:
if ch >= "0" and ch <= "9":
digits += ch
var w := clampi(digits.to_int(), 0, 999) if digits != "" else e.weight
edit.text = "×%d" % w
if w != e.weight:
e.weight = w
card.update_deck()
card.main.mark_dirty()
edit.text_submitted.connect(func(_t: String) -> void: commit.call())
edit.focus_exited.connect(commit)
return edit
func range_edit(e: TableEntry, is_lo: bool) -> LineEdit:
var table := card.table
var edit := LineEdit.new()
edit.text = str(e.range_lo if is_lo else e.range_hi)
edit.custom_minimum_size = Vector2(40, 0)
edit.alignment = HORIZONTAL_ALIGNMENT_CENTER
edit.max_length = 3
edit.tooltip_text = "Range start" if is_lo else "Range end"
edit.add_theme_font_override("font", Style.display(true))
edit.add_theme_font_size_override("font_size", 15)
edit.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.RULE))
edit.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.COPPER))
var commit := func() -> void:
var v := clampi(edit.text.to_int(), table.min_value(), table.die_size())
if is_lo:
e.range_lo = v
else:
e.range_hi = v
if e.range_lo > e.range_hi:
var tmp := e.range_lo
e.range_lo = e.range_hi
e.range_hi = tmp
edit.text = str(e.range_lo if is_lo else e.range_hi)
card.update_warning()
card.main.mark_dirty()
edit.text_submitted.connect(func(_t: String) -> void: commit.call())
edit.focus_exited.connect(commit)
return edit
func make_footer(ranged: bool) -> Control:
var table := card.table
var main := card.main
var wrap := MarginContainer.new()
wrap.mouse_filter = Control.MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 12)
wrap.add_theme_constant_override("margin_right", 10)
wrap.add_theme_constant_override("margin_bottom", 10)
var h := TableCard.hbox(8)
wrap.add_child(h)
# Loops, sheets, variables and number/text choices have fixed rows.
if table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and table.choice == "pick"):
var label := "+ Add range" if ranged else ("+ Add option" if table.kind == RollTable.KIND_CHOICE else "+ Add result")
var add := footer_button(label, Style.INK)
add.pressed.connect(func() -> void: main.add_entry(table.id))
h.add_child(add)
elif table.kind == RollTable.KIND_ROUTER:
var addc := footer_button("+ Add case", Style.INK)
addc.tooltip_text = "Add a case before Otherwise"
addc.pressed.connect(add_case)
h.add_child(addc)
var spacer := Control.new()
spacer.size_flags_horizontal = Control.SIZE_EXPAND_FILL
spacer.mouse_filter = Control.MOUSE_FILTER_IGNORE
h.add_child(spacer)
var del := footer_button("Delete", Style.DANGER_INK)
del.tooltip_text = "Delete this table"
del.pressed.connect(func() -> void: main.delete_table(table.id))
h.add_child(del)
return wrap
static func footer_button(text: String, hover_color: Color) -> Button:
var b := Button.new()
b.text = text
b.add_theme_font_size_override("font_size", 14)
var normal := Style.bordered(Style.box(Color(0, 0, 0, 0), 6, [10, 4, 10, 4]), 1, Style.DASH)
var hover := Style.bordered(Style.box(Color(0, 0, 0, 0), 6, [10, 4, 10, 4]), 1, hover_color if hover_color != Style.INK else Style.MUTED)
Style.skin_button(b, normal, hover, hover, Style.MUTED, hover_color)
return b

View file

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

410
ui/table_card_header.gd Normal file
View file

@ -0,0 +1,410 @@
class_name TableCardHeader
extends RefCounted
## The top of a TableCard: collapse chevron, name (or its inline editor and
## settings gear in Build), the go button, the card-mode deck row and the
## kind-specific lines under the title, plus the dashed inputs box. Owns the
## live labels refresh_live() updates (a choice's question, "3 available now").
var card: TableCard
var die_icon: DieIcon
var deck_label: Label
## Play mode: "3 available now" on a dynamic pick card.
var options_label: Label
var prompt_label: RichTextLabel
func _init(p_card: TableCard) -> void:
card = p_card
## Drops the references to the previous build's labels.
func clear() -> void:
deck_label = null
prompt_label = null
options_label = null
func make(build: bool, ranged: bool) -> Control:
var table := card.table
var main := card.main
var header := PanelContainer.new()
var hs := Style.box(Color(0, 0, 0, 0), 0, [12, 10, 10, 9])
hs.border_width_bottom = 1
hs.border_color = Style.RULE
header.add_theme_stylebox_override("panel", hs)
header.mouse_filter = Control.MOUSE_FILTER_PASS
header.mouse_default_cursor_shape = Control.CURSOR_MOVE
header.gui_input.connect(card._on_header_input.bind(header))
var row := TableCard.hbox(8)
var head_box := TableCard.vbox(4)
header.add_child(head_box)
head_box.add_child(row)
if card.can_collapse():
var chevron := ChevronButton.new()
chevron.open = not table.collapsed
chevron.tooltip_text = ("Expand " if table.collapsed else "Collapse ") + table.name
chevron.size_flags_vertical = Control.SIZE_SHRINK_CENTER
chevron.pressed.connect(func() -> void: main.toggle_collapse(table.id))
row.add_child(chevron)
header.mouse_entered.connect(func() -> void:
if not card._dragging and main.mode == Main.Mode.PLAY:
main.details().show_table(header, table.id, true)
)
if build:
var name_edit := LineEdit.new()
name_edit.text = table.name
name_edit.size_flags_horizontal = Control.SIZE_EXPAND_FILL
name_edit.size_flags_vertical = Control.SIZE_SHRINK_CENTER
name_edit.custom_minimum_size = Vector2(40, 0)
name_edit.add_theme_font_override("font", Style.display(true))
name_edit.add_theme_font_size_override("font_size", 18)
name_edit.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 6, [7, 3, 7, 3]), 1, Style.RULE))
name_edit.text_changed.connect(func(s: String) -> void:
table.name = s
main.mark_dirty()
)
row.add_child(name_edit)
var gear := Button.new()
gear.text = "⚙"
gear.tooltip_text = "Table settings"
gear.custom_minimum_size = Vector2(26, 26)
gear.size_flags_vertical = Control.SIZE_SHRINK_CENTER
gear.add_theme_font_size_override("font_size", 16)
Style.skin_button(gear, Style.box(Color(0, 0, 0, 0), 6), Style.box(Color("#e6dfcd"), 6), Style.box(Color("#e6dfcd"), 6), Style.MUTED, Style.INK)
gear.pressed.connect(func() -> void: main.request_table_settings(table.id))
row.add_child(gear)
else:
var titles := TableCard.vbox(3)
titles.size_flags_horizontal = Control.SIZE_EXPAND_FILL
titles.size_flags_vertical = Control.SIZE_SHRINK_CENTER
titles.mouse_filter = Control.MOUSE_FILTER_IGNORE
var title := Style.make_label(Formatter.strip_tags(table.name), Style.display(true), 20, Style.INK)
title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
if table.details.strip_edges() != "":
# A small ⓘ after the name says hovering shows the table's details.
var name_row := TableCard.hbox(4)
name_row.mouse_filter = Control.MOUSE_FILTER_IGNORE
title.size_flags_horizontal = Control.SIZE_EXPAND_FILL
name_row.add_child(title)
var mark := Style.make_label(RichText.INFO_MARK, Style.body(true), 12, Color("#9a9483"))
mark.size_flags_vertical = Control.SIZE_SHRINK_CENTER
name_row.add_child(mark)
titles.add_child(name_row)
else:
titles.add_child(title)
var sub := _subtitle()
if sub != "":
var cl := Style.make_label(sub, Style.body(true), 12, Style.MUTED)
cl.mouse_filter = Control.MOUSE_FILTER_IGNORE
cl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
titles.add_child(cl)
row.add_child(titles)
var deck_row: Control = null
if table.card_mode:
deck_row = _make_deck_row()
var go := _make_go_button()
if go != null:
row.add_child(go)
if deck_row != null:
head_box.add_child(deck_row)
var extra := _make_kind_header(build)
if extra != null:
head_box.add_child(extra)
return header
## The small line under the title in Play mode ("2d6 + dm(@end) · 2 ranges").
func _subtitle() -> String:
var table := card.table
match table.kind:
RollTable.KIND_ROLL:
if table.is_ranged():
var n := "%d ranges" % table.entries.size()
if table.is_expr_dice():
var dl := ("Roll " + Describe.dice(table.dice, card.main.data)) if card.plain else table.dice_label()
return "%s · %s" % [dl, n]
return n
if table.collapsed:
return "%d results" % table.entries.size()
RollTable.KIND_CHOICE:
if table.collapsed:
return "%d options" % table.entries.size()
RollTable.KIND_ROUTER:
return "if / else if / otherwise · %d %s" % [table.entries.size(), "case" if table.entries.size() == 1 else "cases"]
RollTable.KIND_CHECK:
return "Check card"
return ""
## The header button that starts a roll: the die on roll tables, a "?" badge on
## choice cards, a loop arrow on loop cards and "Print" on sheets. Variable
## cards have none.
func _make_go_button() -> Button:
var table := card.table
die_icon = null
if table.kind == RollTable.KIND_VARIABLE:
return null
var b := Button.new()
b.size_flags_vertical = Control.SIZE_SHRINK_CENTER
b.add_theme_font_override("font", Style.display(true))
b.add_theme_font_size_override("font_size", 17)
var left := 10
match table.kind:
RollTable.KIND_CHOICE:
b.text = "?"
b.add_theme_font_size_override("font_size", 20)
b.custom_minimum_size = Vector2(36, 0)
b.tooltip_text = "Ask: %s" % Formatter.strip_tags(table.prompt if table.prompt != "" else table.name)
RollTable.KIND_LOOP:
b.custom_minimum_size = Vector2(38, 32)
b.tooltip_text = "Run %s" % Formatter.strip_tags(table.name)
var icon := Control.new()
icon.mouse_filter = Control.MOUSE_FILTER_IGNORE
icon.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
icon.draw.connect(func() -> void: Icons.draw_loop(icon, icon.size / 2.0 + Vector2(0, -1), 7.0, Style.BRASS, 2.2))
b.add_child(icon)
RollTable.KIND_ROUTER:
b.custom_minimum_size = Vector2(38, 32)
b.tooltip_text = "Route %s: the first case that's true is chosen" % Formatter.strip_tags(table.name)
var fork := Control.new()
fork.mouse_filter = Control.MOUSE_FILTER_IGNORE
fork.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
fork.draw.connect(func() -> void: draw_fork(fork, fork.size / 2.0 + Vector2(0, 0), 8.0, Style.BRASS, 2.2))
b.add_child(fork)
RollTable.KIND_SHEET:
b.text = "Print"
b.add_theme_font_override("font", Style.body_bold(true))
b.add_theme_font_size_override("font_size", 14)
b.tooltip_text = "Print this sheet in the tray"
RollTable.KIND_CHECK:
b.text = TableCardText.check_badge(table)
b.custom_minimum_size = Vector2(38, 0)
b.tooltip_text = "Roll the check: %s\nShift-click to skip the animation" % RulesView.check_line(table, card.main.data, card.plain)
_:
left = 34
var label := "d%d" % table.die_size()
if table.is_expr_dice():
label = table.dice_label() if table.dice_label().length() <= 5 else "Roll"
b.text = label
b.tooltip_text = "Roll %s on %s\nShift-click to skip the animation" % [table.dice_label(), table.name]
var rn := Style.box(Style.FELT, 8, [left, 6, 10, 6])
rn.border_width_bottom = 2
rn.border_color = Style.FELT_DEEP
var rh := rn.duplicate() as StyleBoxFlat
rh.bg_color = Style.FELT_HOVER
var rp := rn.duplicate() as StyleBoxFlat
rp.border_width_bottom = 1
rp.content_margin_top = 7
rp.content_margin_bottom = 5
Style.skin_button(b, rn, rh, rp, Style.BRASS)
if table.kind == RollTable.KIND_ROLL:
var die := DieIcon.new()
die.spinning = card._rolling
die_icon = die
b.add_child(die)
b.resized.connect(func() -> void: die.position = Vector2(8, (b.size.y - 20.0) / 2.0 - 1.0))
b.pressed.connect(func() -> void: card.main.start_roll(table.id))
return b
## Kind-specific lines under the header: a choice card's question, a loop's
## rule, a variable's name.
func _make_kind_header(_build: bool) -> Control:
var table := card.table
var data := card.main.data
var plain := card.plain
match table.kind:
RollTable.KIND_CHOICE:
var v := TableCard.vbox(3)
prompt_label = RichText.label("", 15, Style.INK, true)
prompt_label.mouse_filter = Control.MOUSE_FILTER_IGNORE
v.add_child(prompt_label)
var kinds := {"pick": "Pick one", "number": "A number", "text": "Your words"}
var info := str(kinds.get(table.choice, ""))
if table.choice == "number":
info += " · %s to %s" % [RulesView.dice(table.min_expr, data, plain), RulesView.dice(table.max_expr, data, plain)]
if table.save_as != "":
info += " · saves %s" % RulesView.value_name(table.save_as, data, plain)
var l := Style.make_label(info, Style.body(true), 12, Style.MUTED)
l.mouse_filter = Control.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(RulesView.options_line(table, data, plain), Style.body_bold(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
ol.mouse_filter = Control.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 = Control.MOUSE_FILTER_IGNORE
v.add_child(options_label)
return v
RollTable.KIND_LOOP:
var chip := PanelContainer.new()
chip.mouse_filter = Control.MOUSE_FILTER_PASS
chip.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(Style.BRASS, 0.16), 6, [8, 1, 8, 2]), 1, Color(Style.BRASS_DARK, 0.35)))
var err := Expr.check(table.loop_expr) if table.loop_expr.strip_edges() != "" else "No rule yet"
var rule := RulesView.loop_rule(table, data, plain)
var l := Style.make_label(rule, Style.display(true), 16, Style.DANGER_INK if err != "" else Style.COPPER_DARK)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
if rule.length() > 26:
# A long plain rule wraps across the card instead of widening it.
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
chip.size_flags_horizontal = Control.SIZE_FILL
chip.add_child(l)
chip.tooltip_text = err if err != "" else (TableCardText.loop_rule(table) if plain else "")
return chip
RollTable.KIND_ROUTER:
if not _build:
return null
var rl := Style.make_label("Router · the first true case is chosen", Style.body(true), 12, Style.MUTED)
rl.mouse_filter = Control.MOUSE_FILTER_IGNORE
rl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
return rl
RollTable.KIND_VARIABLE:
var txt := "@%s · %s" % [table.var_name, table.var_type]
if table.is_collection():
txt = "Collection · kept between rolls" if plain else "@%s_* (board values)" % table.var_name
elif plain:
txt = "%s · kept between rolls" % table.var_type.capitalize()
var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
l.tooltip_text = "@" + table.var_name if plain and not table.is_collection() else ""
if l.tooltip_text != "":
l.mouse_filter = Control.MOUSE_FILTER_PASS
return l
RollTable.KIND_CHECK:
var cl := RichText.label(TableCardText.check_sentence(table, data, plain), 14, Style.INK, true)
cl.mouse_filter = Control.MOUSE_FILTER_IGNORE
return cl
return null
## Re-renders the header's live labels: a dynamic pick's available count and a
## choice's question.
func refresh_live() -> void:
var table := card.table
var main := card.main
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:
p = RichText.preview(table.prompt, main.data)
else:
p = RichText.decorate(TextExpander.render(table.prompt, Roller.live_context(main.data, main.persistent_vars)))
if prompt_label.text != p:
prompt_label.text = p
prompt_label.visible = table.prompt.strip_edges() != ""
## A dashed box under the header naming the card's inputs: "Input Tier ·
## starts at 1" (plain) or "input tier · default 1" (text), one line each.
func make_inputs_box() -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = Control.MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 10)
wrap.add_theme_constant_override("margin_right", 10)
wrap.add_theme_constant_override("margin_top", 8)
var p := PanelContainer.new()
p.mouse_filter = Control.MOUSE_FILTER_PASS
p.add_theme_stylebox_override("panel", DashedBox.new())
p.tooltip_text = "Values a pipe into this card can pass (\"with\"); a roll that starts here uses the starting values"
wrap.add_child(p)
var v := TableCard.vbox(2)
p.add_child(v)
for inp: Dictionary in card.table.inputs:
var line := RichText.label(TableCardText.input_line(inp, card.main.data, card.plain), 13, Style.MUTED, true)
line.mouse_filter = Control.MOUSE_FILTER_IGNORE
line.set_meta("input_line", true)
v.add_child(line)
wrap.set_meta("inputs_box", true)
return wrap
## A dashed rounded outline (the inputs box), since StyleBoxFlat has no
## dashes.
class DashedBox extends StyleBox:
func _init() -> void:
content_margin_left = 9
content_margin_right = 9
content_margin_top = 6
content_margin_bottom = 6
func _draw(to_canvas_item: RID, rect: Rect2) -> void:
var r := rect.grow(-0.5)
var pts := PackedVector2Array([r.position, Vector2(r.end.x, r.position.y), r.end, Vector2(r.position.x, r.end.y), r.position])
var col := Style.DASH
for i in 4:
var a := pts[i]
var b := pts[i + 1]
var seg_len := a.distance_to(b)
var d := 0.0
while d < seg_len:
var e := minf(d + 5.0, seg_len)
RenderingServer.canvas_item_add_line(to_canvas_item, a.lerp(b, d / seg_len), a.lerp(b, e / seg_len), col, 1.2, true)
d += 9.0
## A fork: one stem splitting into two branches, each ending in a dot (the
## router card's go button). `r` is about half the icon's height.
static func draw_fork(ci: CanvasItem, c: Vector2, r: float, color: Color, width: float = 2.0) -> void:
var base := c + Vector2(-r, 0)
var split := c + Vector2(-r * 0.15, 0)
ci.draw_line(base, split, color, width, true)
var up := c + Vector2(r * 0.85, -r * 0.75)
var down := c + Vector2(r * 0.85, r * 0.75)
for tip: Vector2 in [up, down]:
var pts := PackedVector2Array()
for k in 9:
var u := float(k) / 8.0
pts.append(split.bezier_interpolate(split + Vector2(r * 0.5, 0), tip - Vector2(r * 0.45, 0), tip, u))
ci.draw_polyline(pts, color, width, true)
ci.draw_circle(tip, width * 1.25, color)
ci.draw_circle(base, width * 0.9, color)
## Card mode: "4 / 6 left" and a small Reshuffle link under the title.
func _make_deck_row() -> Control:
var h := TableCard.hbox(6)
var pad := Control.new()
pad.custom_minimum_size = Vector2(26, 0)
pad.mouse_filter = Control.MOUSE_FILTER_IGNORE
h.add_child(pad)
deck_label = Style.make_label("", Style.body(true), 12, Style.MUTED)
deck_label.size_flags_vertical = Control.SIZE_SHRINK_CENTER
deck_label.mouse_filter = Control.MOUSE_FILTER_IGNORE
h.add_child(deck_label)
var b := Button.new()
b.text = "↻ Reshuffle"
b.tooltip_text = "Put every card back in the deck"
b.add_theme_font_override("font", Style.body(true))
b.add_theme_font_size_override("font_size", 12)
b.size_flags_vertical = Control.SIZE_SHRINK_CENTER
var n := Style.box(Color(0, 0, 0, 0), 5, [5, 0, 5, 1])
var hv := Style.box(Color("#e6dfcd"), 5, [5, 0, 5, 1])
Style.skin_button(b, n, hv, hv, Style.COPPER, Style.INK)
b.pressed.connect(func() -> void: card.main.reshuffle_table(card.table.id))
h.add_child(b)
update_deck()
return h
## Refreshes the cards-left count of a card-mode table.
func update_deck() -> void:
if deck_label == null or not is_instance_valid(deck_label):
return
var left := card.main.cards_left(card.table.id)
deck_label.text = "%d / %d left" % [left.x, left.y]
deck_label.add_theme_color_override("font_color", Style.DANGER_INK if left.x == 0 else Style.MUTED)

View file

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

424
ui/table_card_rows.gd Normal file
View file

@ -0,0 +1,424 @@
class_name TableCardRows
extends RefCounted
## A TableCard's result rows: building them (plain, check outlet, sheet and the
## collapsed card's "more" row), their Play-mode text and rule chips, and their
## highlight state (normal, flickering during a roll, lit, with the copper bar
## of the inspector's selected result). Build-only controls come from
## TableCardEditing.
enum RowState { NORMAL, FLICK, LIT }
const LOOP_ROWS := ["Each time", "Afterwards"]
## Longest effects summary shown on a chip.
const CHIP_CHARS := 30
const PLAIN_CHIP_CHARS := 38
var card: TableCard
## entry id -> {num, text, entry, index}, for the rows currently shown.
var parts: Dictionary = {}
var more_label: Label
var sheet_label: RichTextLabel
var _row_styles: Array[StyleBoxFlat] = []
var _flick_id := ""
func _init(p_card: TableCard) -> void:
card = p_card
for c in [Color(0, 0, 0, 0), Style.FLICK, Style.LIT]:
_row_styles.append(Style.box(c, 0, [12, 6, 22, 6]))
# The same, with the copper bar of the inspector's selected result.
for c in [Color(0, 0, 0, 0), Style.FLICK, Style.LIT]:
var sel := Style.box(c, 0, [12, 6, 22, 6])
sel.border_width_left = 3
sel.border_color = Style.COPPER
sel.anti_aliasing = false
_row_styles.append(sel)
## Forgets the previous build's rows.
func clear() -> void:
parts.clear()
more_label = null
_flick_id = ""
sheet_label = null
func register(e: TableEntry, row: PanelContainer, num: Label, text: RichTextLabel, index: int) -> void:
card.rows[e.id] = row
parts[e.id] = {"num": num, "text": text, "entry": e, "index": index}
func _is_pick() -> bool:
return card.table.kind == RollTable.KIND_CHOICE and card.table.choice == "pick"
## True for the Chosen row of a dynamic pick card.
func _is_chosen_row(index: int) -> bool:
return index == 0 and card.table.is_dynamic()
func make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float) -> Control:
var table := card.table
var main := card.main
var edit := card.edit_ui
var row := PanelContainer.new()
row.mouse_filter = Control.MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var h := TableCard.hbox(8)
row.add_child(h)
# 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:
var r := TableCard.hbox(2)
r.custom_minimum_size = Vector2(numw, 0)
r.size_flags_vertical = Control.SIZE_SHRINK_CENTER
r.add_child(edit.range_edit(e, true))
r.add_child(Style.make_label("–", Style.display(true), 15, Style.MUTED))
r.add_child(edit.range_edit(e, false))
h.add_child(r)
else:
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 = Control.SIZE_SHRINK_CENTER
if fixed:
num.text = "↻" if table.kind == RollTable.KIND_LOOP and index == 0 else "→"
num.add_theme_font_override("font", Style.body_bold(true))
num.add_theme_font_size_override("font_size", 14)
h.add_child(num)
var text: RichTextLabel = null
if build:
h.add_theme_constant_override("separation", 4)
var col := TableCard.vbox(2)
col.size_flags_horizontal = Control.SIZE_EXPAND_FILL
col.size_flags_vertical = Control.SIZE_SHRINK_CENTER
h.add_child(col)
if table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
var al := Style.make_label("Answer", Style.body_italic(true), 15, Style.MUTED)
al.size_flags_horizontal = Control.SIZE_EXPAND_FILL
al.size_flags_vertical = Control.SIZE_SHRINK_CENTER
al.mouse_filter = Control.MOUSE_FILTER_PASS
al.tooltip_text = "Its effects and pipes run after the player answers ({answer} holds the answer)"
col.add_child(al)
else:
if chosen:
# A caption over the text field, so the field keeps its width.
var cl := Style.make_label("Chosen · runs for the picked option", Style.body_italic(true), 11, Style.COPPER_DARK)
cl.mouse_filter = Control.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()
col.add_child(cl)
col.add_child(edit.text_edit(e, index, chosen))
add_rule_chips(col, e)
if not ranged and not fixed:
h.add_child(edit.weight_edit(e))
if not fixed and not chosen:
h.add_child(TableCardEditing.mini_button("×", "Delete this result", true, func() -> void: main.delete_entry(table.id, e.id)))
edit.hook_select(row, e.id)
else:
var col := TableCard.vbox(3)
col.size_flags_horizontal = Control.SIZE_EXPAND_FILL
col.size_flags_vertical = Control.SIZE_SHRINK_CENTER
text = RichText.label(row_text(e), 16, Style.INK, true)
text.size_flags_horizontal = Control.SIZE_EXPAND_FILL
RichText.hook_hover(text, main)
col.add_child(text)
add_rule_chips(col, e)
h.add_child(col)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
if ranged and table.has_chances():
var pct := Style.make_label("%d%%" % roundi(table.chance(e) * 100.0), Style.body(true), 12, Style.MUTED)
pct.size_flags_vertical = Control.SIZE_SHRINK_CENTER
h.add_child(pct)
register(e, row, num, text, index)
return row
## The plain chips under a row's text: a pick option's "only if …" and the
## entry's effects ("Luck −1"). Used in Play and Build alike.
func add_rule_chips(col: VBoxContainer, e: TableEntry) -> void:
var plain := card.plain
if _is_pick() and e.show_if.strip_edges() != "":
var bad := Expr.check(TemplateKit.probe(e.show_if.strip_edges())) != ""
var si := Style.make_label(RulesView.show_if_line(e, card.main.data, plain), Style.body_bold(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
si.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
si.mouse_filter = Control.MOUSE_FILTER_PASS
si.tooltip_text = ("only if " + e.show_if.strip_edges()) if plain else ""
si.set_meta("show_if_line", true)
col.add_child(si)
if e.effects.strip_edges() != "":
col.add_child(_effects_chip(e))
## One outlet of a check card: "8+ Success · the bars give" / "≤7 Failure",
## with the outlet named in green or red. Build edits the text after the name.
func make_check_row(e: TableEntry, index: int, build: bool, numw: float) -> Control:
var table := card.table
var main := card.main
var row := PanelContainer.new()
row.mouse_filter = Control.MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var h := TableCard.hbox(8)
row.add_child(h)
var outs := RulesView.check_outlets(table)
var num := Style.make_label(outs[index] if index < 2 else str(index + 1), Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(maxf(numw, 34.0), 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = Control.SIZE_SHRINK_CENTER
h.add_child(num)
var col := TableCard.vbox(2)
col.size_flags_horizontal = Control.SIZE_EXPAND_FILL
col.size_flags_vertical = Control.SIZE_SHRINK_CENTER
h.add_child(col)
var text: RichTextLabel = null
if build:
var line := TableCard.hbox(6)
col.add_child(line)
var nm := Style.make_label(TableCardText.check_outlet_name(index), Style.body_bold(true), 15, TableCardText.check_outlet_color(index))
nm.size_flags_vertical = Control.SIZE_SHRINK_CENTER
line.add_child(nm)
var edit := card.edit_ui.text_edit(e, index, false)
# The outlet name is already shown, so a result text that just repeats
# it ("Success") shows as an empty field with a hint instead.
if e.text.strip_edges() == TableCardText.check_outlet_name(index):
edit.text = ""
edit.placeholder_text = "What happens on a %s (optional)" % TableCardText.check_outlet_name(index).to_lower()
line.add_child(edit)
add_rule_chips(col, e)
card.edit_ui.hook_select(row, e.id)
else:
text = RichText.label(row_text(e), 16, Style.INK, true)
text.size_flags_horizontal = Control.SIZE_EXPAND_FILL
RichText.hook_hover(text, main)
col.add_child(text)
add_rule_chips(col, e)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
register(e, row, num, text, index)
return row
## Play-mode text of a row: the last rolled (expanded) text when the row is
## lit, otherwise the entry as written with its references shown readably.
## Loop rows read "Each time · …"; a number/text choice's row is its answer;
## a router case leads with its condition, a check outlet with its name.
func row_text(e: TableEntry) -> String:
var table := card.table
var main := card.main
var rolled := main.lit_text(table.id, e.id)
var s := RichText.decorate(rolled) if rolled != "" else RichText.preview(e.text, main.data)
var muted := Style.MUTED.to_html(false)
if table.kind == RollTable.KIND_LOOP:
var index := table.entries.find(e)
var cap: String = LOOP_ROWS[clampi(index, 0, 1)]
var plain_text := Formatter.strip_tags(e.text).strip_edges()
if plain_text == "" or plain_text == cap:
s = "[b]%s[/b]" % cap
else:
s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s]
elif table.kind == RollTable.KIND_ROUTER:
var bad := e.when.strip_edges() != "" and Expr.check(e.when.strip_edges()) != ""
var label := RulesView.case_label(e, main.data, card.plain)
var cond := "[color=#%s][b]%s[/b][/color]" % [(Style.DANGER_INK if bad else Style.COPPER_DARK).to_html(false), RichText.plain(label)]
var plain_text := Formatter.strip_tags(e.text).strip_edges()
if plain_text == "" or plain_text == TableCardText.case_label(e) or plain_text == label or plain_text == "if …" or (plain_text == "Otherwise" and e.when.strip_edges() == ""):
s = cond
else:
s = "%s\n%s" % [cond, s]
elif table.kind == RollTable.KIND_CHECK:
var index := table.entries.find(e)
var nm := TableCardText.check_outlet_name(index)
var head := "[color=#%s][b]%s[/b][/color]" % [TableCardText.check_outlet_color(index).to_html(false), nm]
var own := Formatter.strip_tags(rolled if rolled != "" else e.text).strip_edges()
s = head if own == "" or own == nm else "%s · %s" % [head, s]
elif table.is_dynamic() and table.entries.find(e) == 0:
var own := Formatter.strip_tags(e.text).strip_edges()
if rolled != "":
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)]
else:
s = "[i][color=#%s]Answer[/color][/i]" % muted
if e.details.strip_edges() != "":
s += RichText.info_mark()
return s
## A subtle brass chip summarising an entry's effects: "Luck −1 · Gold + 2D"
## in plain words, "@luck -= 1 · @gold += 2d6" as text. Its tooltip has the
## other form, every statement on its own line.
func _effects_chip(e: TableEntry) -> Control:
var plain := card.plain
var bad := not Effects.validate(TemplateKit.probe(e.effects)).is_empty()
var chip := PanelContainer.new()
chip.mouse_filter = Control.MOUSE_FILTER_PASS
chip.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
var bg := Color(Style.DANGER_INK, 0.1) if bad else Color(Style.BRASS, 0.2)
var line := Color(Style.DANGER_INK, 0.4) if bad else Color(Style.BRASS_DARK, 0.3)
chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(bg, 5, [6, 0, 6, 1]), 1, line))
var summary := RulesView.effects_line(e.effects, card.main.data, card.table, plain)
# Cut long summaries by hand: a clipped Label would collapse to nothing.
summary = RulesView.cut(summary, PLAIN_CHIP_CHARS if plain else CHIP_CHARS)
var l := Style.make_label(summary, Style.body_bold(true) if plain else Style.body(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
chip.add_child(l)
chip.set_meta("effects_chip", summary)
if plain:
chip.tooltip_text = "\n".join(Effects.split(e.effects))
else:
chip.tooltip_text = "\n".join(Describe.effects(e.effects, card.main.data, card.table))
return chip
## A sheet card's one row: the rendered template in Play, its editor in Build.
func make_sheet_row(e: TableEntry, build: bool) -> Control:
var main := card.main
var row := PanelContainer.new()
row.mouse_filter = Control.MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var v := TableCard.vbox(6)
row.add_child(v)
if build:
var te := TextEdit.new()
te.text = e.text
te.placeholder_text = "[b]Name[/b] {@name}\nHP {@hp} · Skills {@skill_*}"
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
te.custom_minimum_size = Vector2(0, 90)
te.scroll_fit_content_height = true
te.add_theme_font_override("font", Style.body(true))
te.add_theme_font_size_override("font_size", 14)
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.RULE))
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.COPPER))
te.tooltip_text = "The sheet's template: BBCode with {@var}, {@prefix_*} and {= expr}"
te.text_changed.connect(func() -> void:
e.text = te.text
main.mark_dirty()
)
te.focus_entered.connect(func() -> void: card.select_entry(e.id))
v.add_child(te)
var tools := TableCard.vbox(2)
if e.effects.strip_edges() != "":
tools.add_child(_effects_chip(e))
var pv := Style.make_label("Preview on the board in Play", Style.body_italic(true), 12, Style.MUTED)
pv.size_flags_vertical = Control.SIZE_SHRINK_CENTER
tools.add_child(pv)
v.add_child(tools)
card.edit_ui.hook_select(row, e.id)
sheet_label = null
else:
sheet_label = RichText.label("", 15, Style.INK, true)
sheet_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL
RichText.hook_hover(sheet_label, main)
v.add_child(sheet_label)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, card.table.id, e.id))
register(e, row, null, null, 0)
return row
## Re-renders a sheet card's template from the current variables.
func refresh_sheet() -> void:
if is_instance_valid(sheet_label):
var main := card.main
var s := RichText.decorate(Roller.render_sheet(main.data, main.persistent_vars, card.table))
if sheet_label.text != s:
sheet_label.text = s
func make_more_row(numw: float) -> PanelContainer:
var more_row := PanelContainer.new()
var normal := Style.box(Color(0, 0, 0, 0), 0, [12, 6, 22, 6])
var hover := Style.box(Style.HOVER_ROW, 0, [12, 6, 22, 6])
more_row.add_theme_stylebox_override("panel", normal)
more_row.custom_minimum_size = Vector2(0, 36)
more_row.mouse_filter = Control.MOUSE_FILTER_STOP
more_row.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
more_row.tooltip_text = "Show every result"
more_row.mouse_entered.connect(func() -> void: more_row.add_theme_stylebox_override("panel", hover))
more_row.mouse_exited.connect(func() -> void: more_row.add_theme_stylebox_override("panel", normal))
more_row.gui_input.connect(func(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT and not mb.pressed:
card.main.toggle_collapse.call_deferred(card.table.id)
)
var h := TableCard.hbox(8)
more_row.add_child(h)
var dots := Style.make_label("…", Style.display(true), 16, Style.MUTED)
dots.custom_minimum_size = Vector2(numw, 0)
dots.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
h.add_child(dots)
more_label = Style.make_label(more_text(), Style.body_italic(true), 14, Style.MUTED)
more_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL
more_label.size_flags_vertical = Control.SIZE_SHRINK_CENTER
h.add_child(more_label)
return more_row
func more_text() -> String:
var table := card.table
var hidden := table.entries.size() - card.rows.size()
if card.rows.size() > 0:
return "%d more · show all" % hidden
return "%d %s · show all" % [table.entries.size(), "ranges" if table.is_ranged() else "results"]
# ---------- State ----------
func set_row_state(eid: String, state: RowState) -> void:
if not card.rows.has(eid):
return
var k := int(state) + (3 if eid == card.selected_entry() else 0)
(card.rows[eid] as PanelContainer).add_theme_stylebox_override("panel", _row_styles[k])
var p: Dictionary = parts[eid]
var num: Label = p["num"]
if num:
num.add_theme_color_override("font_color", Style.INK if state == RowState.LIT else Style.MUTED)
var text: RichTextLabel = p["text"]
if text:
RichText.set_fonts(text, 16, true, state == RowState.LIT)
## Sets a row lit or normal, from whether its result is lit now.
func restate(eid: String) -> void:
set_row_state(eid, RowState.LIT if card.main.is_entry_lit(card.table.id, eid) else RowState.NORMAL)
## Re-renders a Play-mode row's text (it shows the rolled text while lit).
func update_row_text(eid: String) -> void:
var p: Dictionary = parts.get(eid, {})
var text: RichTextLabel = p.get("text")
if text:
var want := row_text(p["entry"])
if text.text != want:
text.text = want
func flick_random() -> void:
clear_flick()
if card.rows.is_empty():
return
var keys := card.rows.keys()
_flick_id = keys[card.main.rng.randi_range(0, keys.size() - 1)]
set_row_state(_flick_id, RowState.FLICK)
func clear_flick() -> void:
if _flick_id != "":
restate(_flick_id)
_flick_id = ""

View file

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

99
ui/table_card_text.gd Normal file
View file

@ -0,0 +1,99 @@
class_name TableCardText
extends RefCounted
## The short texts a table card shows for its rules (check badges and
## sentences, input lines, router case labels, loop rules, effect summaries).
## Static; TableCard keeps delegators for the ones other files call on it.
## The check card's "2D" badge (its dice in plain words, "Roll" when long).
static func check_badge(t: RollTable) -> String:
var d := Describe.dice(t.check_dice, null)
return d if d.length() <= 5 else "Roll"
## The check card's sentence under its header, as BBCode: "Roll 2D +
## Strength modifier, need [b]8 or more[/b]" (plain) or "[code]2d6 + dm(@str)
## vs 8+[/code]" style text.
static func check_sentence(t: RollTable, board: TowerBoard, plain: bool) -> String:
var s := RulesView.check_line(t, board, plain)
if not plain:
return "[color=#%s]%s[/color]" % [Style.COPPER_DARK.to_html(false), RichText.plain(s)]
var at := s.rfind(", need ")
if at < 0:
return RichText.plain(s)
return "%s, need [b]%s[/b]" % [RichText.plain(s.substr(0, at)), RichText.plain(s.substr(at + 7))]
## One input as BBCode: "Input [b]Tier[/b] · starts at [b]1[/b]".
static func input_line(inp: Dictionary, board: TowerBoard, plain: bool) -> String:
var nm := str(inp.get("name", ""))
var def := str(inp.get("default", "")).strip_edges()
var ink := Style.INK.to_html(false)
if not plain:
return "input [color=#%s]%s[/color] · default [color=#%s]%s[/color]" % [ink, RichText.plain(nm), ink, RichText.plain(def if def != "" else "0")]
var lab := str(inp.get("label", "")).strip_edges()
if lab == "":
lab = Describe.label(nm, board)
var shown := Describe.dice(def, board) if def != "" else "0"
return "Input [color=#%s][b]%s[/b][/color] · starts at [color=#%s][b]%s[/b][/color]" % [ink, RichText.plain(lab), ink, RichText.plain(shown)]
## "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
## 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()
return "Otherwise" if w == "" else "if " + w
## "× @answer", "while @alive = 1", "until @done".
static func loop_rule(t: RollTable) -> String:
var e := t.loop_expr.strip_edges()
if e == "":
e = "?"
match t.loop_mode:
"while":
return "while " + e
"until":
return "until " + e
return "× " + e
static func check_outlet_name(index: int) -> String:
return "Success" if index == 0 else ("Failure" if index == 1 else "Result %d" % (index + 1))
static func check_outlet_color(index: int) -> Color:
return Style.OK_INK if index == 0 else Style.NO_INK
## A short summary of effect text as written: the first two statements, with
## declared variables by their card's name ("STR = 2d6 · Terms += 1 · +3").
static func effect_summary(text: String, board: TowerBoard) -> String:
var list := Effects.split(text)
var parts := PackedStringArray()
for k in mini(2, list.size()):
var st := Effects.parse_statement(list[k])
if st.has("error"):
parts.append("⚠ " + list[k])
continue
var target: String = st["target"]
var shown := target
if board != null and target.begins_with("@") and not target.ends_with("*"):
for t in board.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name == target.substr(1):
shown = Formatter.strip_tags(t.name).strip_edges()
break
if st["op"] == "reset":
parts.append("reset " + shown)
else:
parts.append("%s %s %s" % [shown, st["op"], st["expr"]])
if list.size() > 2:
parts.append("+%d" % (list.size() - 2))
return " · ".join(parts)

View file

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

176
ui/table_card_value.gd Normal file
View file

@ -0,0 +1,176 @@
class_name TableCardValue
extends RefCounted
## The body of a variable card (its live value, big) or a collection card (its
## members with live values), re-rendered by refresh() after rolls and edits.
var card: TableCard
var var_value: Label
var var_hint: Label
## Collection cards: the member list, refilled by refresh().
var members_box: VBoxContainer
var members_cache := ""
func _init(p_card: TableCard) -> void:
card = p_card
## Drops the references to the previous build's labels.
func clear() -> void:
var_value = null
var_hint = null
members_box = null
members_cache = ""
## A variable card's body: its live value, big, and in Build its starting value
## and a reset button.
func make_variable_body(build: bool) -> Control:
var table := card.table
var main := card.main
var wrap := MarginContainer.new()
wrap.mouse_filter = Control.MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 14)
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_top", 6)
wrap.add_theme_constant_override("margin_bottom", 10)
var v := TableCard.vbox(2)
wrap.add_child(v)
var_value = Style.make_label("", Style.display(true), 34, Style.INK)
var_value.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
var_value.mouse_filter = Control.MOUSE_FILTER_PASS
v.add_child(var_value)
var_hint = Style.make_label("", Style.body(true), 12, Style.MUTED)
var_hint.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
var_hint.mouse_filter = Control.MOUSE_FILTER_IGNORE
v.add_child(var_hint)
if build:
var h := TableCard.hbox(8)
var init := RulesView.dice(table.initial, main.data, card.plain) if table.initial.strip_edges() != "" else ""
var start := Style.make_label("Starts at %s" % (init if init != "" else ("0" if table.var_type == "number" else "nothing")),
Style.body(true), 12, Style.MUTED)
start.size_flags_horizontal = Control.SIZE_EXPAND_FILL
start.size_flags_vertical = Control.SIZE_SHRINK_CENTER
h.add_child(start)
var reset := Button.new()
reset.text = "↺ Reset"
reset.tooltip_text = "Set @%s back to its starting value" % table.var_name
reset.add_theme_font_override("font", Style.body(true))
reset.add_theme_font_size_override("font_size", 12)
var n := Style.box(Color(0, 0, 0, 0), 5, [5, 0, 5, 1])
var hv := Style.box(Color("#e6dfcd"), 5, [5, 0, 5, 1])
Style.skin_button(reset, n, hv, hv, Style.COPPER, Style.INK)
reset.pressed.connect(func() -> void: main.reset_variable(table.var_name))
h.add_child(reset)
v.add_child(h)
return wrap
## A collection card's body: its members with their live values (refilled by
## refresh()), and in Build "+ Add …", which selects the card so the
## inspector can add a member.
func make_collection_body(build: bool) -> Control:
var table := card.table
var main := card.main
var wrap := MarginContainer.new()
wrap.mouse_filter = Control.MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 12)
wrap.add_theme_constant_override("margin_right", 14)
wrap.add_theme_constant_override("margin_top", 6)
wrap.add_theme_constant_override("margin_bottom", 10)
var v := TableCard.vbox(6)
wrap.add_child(v)
members_box = TableCard.vbox(0)
v.add_child(members_box)
if build:
var add := TableCardEditing.footer_button("+ Add " + Describe._singular(Formatter.strip_tags(table.name).strip_edges().to_lower()), Style.INK)
add.size_flags_horizontal = Control.SIZE_FILL
add.tooltip_text = "Add a member in the inspector"
add.set_meta("collection_add", true)
add.pressed.connect(func() -> void:
if main.has_method("select_card"):
main.call("select_card", table.id)
else:
main.request_table_settings(table.id)
)
v.add_child(add)
return wrap
## A collection's members: [{name ("@skill_pilot"), label ("Pilot"), value
## (Variant or null when not set)}], set members first, then members only
## named by the board's rules, each sorted by label.
static func collection_members(t: RollTable, board: TowerBoard, vars: Dictionary) -> Array[Dictionary]:
var out: Array[Dictionary] = []
if t == null or not t.is_collection() or t.var_name == "":
return out
var seen := {}
for v: Dictionary in RollContext.vars_with_prefix(vars, t.var_name + "_"):
var nm := "@" + str(v["name"])
seen[nm] = true
out.append({"name": nm, "label": Describe.label(nm, board), "value": v["value"]})
var named: Array[Dictionary] = []
for kv: Dictionary in Builder.known_values(board):
if str(kv.get("collection", "")) == "@%s_*" % t.var_name and not seen.has(str(kv["name"])):
seen[str(kv["name"])] = true
named.append({"name": str(kv["name"]), "label": str(kv["label"]), "value": null})
var by_label := func(a: Dictionary, b: Dictionary) -> bool: return str(a["label"]).naturalnocasecmp_to(str(b["label"])) < 0
out.sort_custom(by_label)
named.sort_custom(by_label)
out.append_array(named)
return out
func _refresh_members() -> void:
var plain := card.plain
var list := collection_members(card.table, card.main.data, card.main.persistent_vars)
var key := var_to_str(list) + str(plain)
if key == members_cache:
return
members_cache = key
for c in members_box.get_children():
members_box.remove_child(c)
c.queue_free()
if list.is_empty():
var none := Style.make_label("No members yet", Style.body_italic(true), 14, Style.MUTED)
none.mouse_filter = Control.MOUSE_FILTER_IGNORE
members_box.add_child(none)
return
for m: Dictionary in list:
var h := TableCard.hbox(8)
h.custom_minimum_size = Vector2(0, 28)
h.set_meta("member", str(m["name"]))
var nl := Style.make_label(str(m["label"]) if plain else str(m["name"]), Style.body(true), 15, Style.INK)
nl.size_flags_horizontal = Control.SIZE_EXPAND_FILL
nl.size_flags_vertical = Control.SIZE_SHRINK_CENTER
nl.mouse_filter = Control.MOUSE_FILTER_IGNORE
h.add_child(nl)
var val: Variant = m["value"]
var vl := Style.make_label("—" if val == null else Expr.format_value(val), Style.display(true), 17, Style.INK if val != null else Style.MUTED)
vl.size_flags_vertical = Control.SIZE_SHRINK_CENTER
vl.mouse_filter = Control.MOUSE_FILTER_IGNORE
h.add_child(vl)
members_box.add_child(h)
## Re-renders the member list or the variable's value and hint, touching only
## what changed.
func refresh() -> void:
if is_instance_valid(members_box):
_refresh_members()
if is_instance_valid(var_value):
var d := Roller.variable_display(card.main.data, card.main.persistent_vars, card.table)
var shown := str(d["text"]) if str(d["text"]) != "" else "—"
if var_value.text != shown:
var_value.text = shown
var size_px := 34 if shown.length() <= 8 else (24 if shown.length() <= 18 else 17)
var_value.add_theme_font_size_override("font_size", size_px)
var_value.add_theme_color_override("font_color", Style.INK if d["set"] else Style.MUTED)
var hint := ""
if str(d["error"]) != "":
hint = "⚠ " + str(d["error"])
elif not d["set"]:
hint = "Not set yet · starts at this"
var_hint.text = hint
var_hint.add_theme_color_override("font_color", Style.DANGER_INK if str(d["error"]) != "" else Style.MUTED)
var_hint.visible = hint != ""

View file

@ -0,0 +1 @@
uid://34phpd5ehw0c

View file

@ -1,8 +1,8 @@
class_name TableSettingsDialog
extends ModalCard
## Build-mode editor for one table's name, details, tags, type and card mode.
## The editing rules live in static functions (apply_settings and friends) so
## they can be tested without a window.
## The editing rules live in TableSettingsRules (static, tested without a
## window); the kind-specific fields in SettingsKindFields.
signal applied(settings: Dictionary)
## The footer's "Save as template…" (the dialog closes first; Main opens the save dialog).
@ -30,39 +30,9 @@ var _deck_block: Control
var _ranged := false
var _card_mode := false
var _deck_empty := "reshuffle"
# Logic-card fields (docs/LOGIC.md), shown for the matching kind.
var _type_box: Control
var _card_box: Control
var _kind_problem: Label
var _choice := "pick"
var _choice_note: Label
var _prompt: LineEdit
var _save_as: LineEdit
var _min: LineEdit
var _max: LineEdit
var _minmax_row: Control
## Pick choices: "fixed" or "vars" (options from variables, plus fixed extras).
var _options_mode := "fixed"
var _options_box: Control
var _opt_mode_box: Control
var _opt_from: LineEdit
var _opt_where: LineEdit
var _opt_note: Label
var _show_if_box: Control
## entry id -> its Show only if field.
var _show_if: Dictionary = {}
var _loop_mode := "times"
var _loop_expr: LineEdit
var _loop_note: Label
var _var_name: LineEdit
var _var_type := "number"
var _initial: LineEdit
var _template: TextEdit
var _template_preview: RichTextLabel
## Router cards: one condition field per case, in order.
var _cases: Array[LineEdit] = []
var _case_note: Label
var _kind: SettingsKindFields
const TITLES := {
RollTable.KIND_ROLL: "Table settings",
@ -80,8 +50,6 @@ const LOOP_NOTES := {
"while": "Checks the condition before each pass and stops when it's false. e.g. @hp > 0",
"until": "Runs a pass, then stops once the condition is true (at least one pass). e.g. @gold >= 100",
}
const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
const VAR_PATTERN := "^[a-z0-9_]+$"
func _init(p_table: RollTable = null) -> void:
@ -90,10 +58,7 @@ func _init(p_table: RollTable = null) -> void:
_ranged = table.is_ranged()
_card_mode = table.card_mode
_deck_empty = table.deck_empty
_choice = table.choice
_options_mode = "vars" if table.options_from.strip_edges() != "" else "fixed"
_loop_mode = table.loop_mode
_var_type = table.var_type
_kind = SettingsKindFields.new(self)
_build()
@ -104,7 +69,7 @@ func _build() -> void:
style_line_edit(_name)
_name.text_changed.connect(func(_t: String) -> void: _refresh())
body.add_child(field("Name", _name))
_build_kind()
_kind.build()
_details = TextEdit.new()
_details.text = table.details
@ -238,7 +203,7 @@ func _color_menu(anchor: Control) -> void:
## Wraps the selected text in the tags, or inserts an empty pair at the caret.
func _wrap_selection(open: String, close_tag: String) -> void:
var r := wrap_text(_details.text, _selection_range(), open, close_tag)
var r := TableSettingsRules.wrap_text(_details.text, _selection_range(), open, close_tag)
_details.text = r["text"]
_set_caret_at_offset(int(r["caret"]))
_details.grab_focus()
@ -275,286 +240,10 @@ func settings() -> Dictionary:
"ranged": _ranged, "dice": _dice.text.strip_edges(),
"card_mode": _card_mode, "deck_empty": _deck_empty,
}
match table.kind:
RollTable.KIND_CHOICE:
s["choice"] = _choice
s["prompt"] = _prompt.text
s["save_as"] = _save_as.text.strip_edges()
s["min"] = _min.text.strip_edges()
s["max"] = _max.text.strip_edges()
s["options_mode"] = _options_mode
s["options_from"] = _opt_from.text.strip_edges()
s["options_where"] = _opt_where.text.strip_edges()
var si := {}
for eid: String in _show_if:
si[eid] = (_show_if[eid] as LineEdit).text.strip_edges()
s["show_if"] = si
RollTable.KIND_LOOP:
s["loop_mode"] = _loop_mode
s["loop_expr"] = _loop_expr.text.strip_edges()
RollTable.KIND_VARIABLE:
s["var_name"] = _var_name.text.strip_edges().trim_prefix("@")
s["var_type"] = _var_type
s["initial"] = _initial.text.strip_edges()
RollTable.KIND_SHEET:
s["template"] = _template.text
RollTable.KIND_ROUTER:
var cases: Array = []
for le in _cases:
cases.append(le.text.strip_edges())
s["cases"] = cases
_kind.add_settings(s)
return s
# ---------- Kind-specific fields ----------
func _build_kind() -> void:
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 10)
match table.kind:
RollTable.KIND_CHOICE:
box.add_child(section("Question type"))
box.add_child(segmented(CHOICE_LABELS, RollTable.CHOICES.find(_choice), func(i: int) -> void:
_choice = RollTable.CHOICES[i]
_refresh()
))
_choice_note = note("")
box.add_child(_choice_note)
_prompt = LineEdit.new()
_prompt.text = table.prompt
_prompt.placeholder_text = "Which way out? You have {@gold} gold."
style_line_edit(_prompt)
_prompt.text_changed.connect(func(_t: String) -> void: _refresh())
box.add_child(field("Question (BBCode, {@var} works)", _prompt))
_save_as = LineEdit.new()
_save_as.text = table.save_as
_save_as.placeholder_text = "@name to keep, or a name for this roll"
style_line_edit(_save_as)
_save_as.text_changed.connect(func(_t: String) -> void: _refresh())
box.add_child(field("Save the answer as (optional)", _save_as))
var mm := HBoxContainer.new()
mm.add_theme_constant_override("separation", 12)
_min = LineEdit.new()
_min.text = table.min_expr
style_line_edit(_min)
_min.text_changed.connect(func(_t: String) -> void: _refresh())
_max = LineEdit.new()
_max.text = table.max_expr
style_line_edit(_max)
_max.text_changed.connect(func(_t: String) -> void: _refresh())
mm.add_child(field("Lowest", _min))
mm.add_child(field("Highest", _max))
for c in mm.get_children():
(c as Control).size_flags_horizontal = SIZE_EXPAND_FILL
_minmax_row = mm
box.add_child(mm)
_build_options(box)
RollTable.KIND_LOOP:
box.add_child(section("Repeat"))
box.add_child(segmented(LOOP_LABELS, RollTable.LOOPS.find(_loop_mode), func(i: int) -> void:
_loop_mode = RollTable.LOOPS[i]
_refresh()
))
_loop_expr = LineEdit.new()
_loop_expr.text = table.loop_expr
style_line_edit(_loop_expr)
_loop_expr.text_changed.connect(func(_t: String) -> void: _refresh())
box.add_child(field("How many times / condition", _loop_expr))
_loop_note = note("")
box.add_child(_loop_note)
RollTable.KIND_VARIABLE:
_var_name = LineEdit.new()
_var_name.text = table.var_name
_var_name.placeholder_text = "hp"
style_line_edit(_var_name)
_var_name.text_changed.connect(func(_t: String) -> void: _refresh())
box.add_child(field("Variable name (used as @name)", _var_name))
box.add_child(section("Type"))
box.add_child(segmented(["Number", "Text", "List", "Collection"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void:
_var_type = RollTable.VAR_TYPES[i]
_refresh()
))
_initial = LineEdit.new()
_initial.text = table.initial
_initial.placeholder_text = "10, 2d6, or a word"
style_line_edit(_initial)
_initial.text_changed.connect(func(_t: String) -> void: _refresh())
box.add_child(field("Starting value", _initial))
box.add_child(note("reset @name, and Reset in the Variables tab, put it back to this."))
RollTable.KIND_SHEET:
_template = TextEdit.new()
_template.text = table.entries[0].text if not table.entries.is_empty() else ""
_template.placeholder_text = "[b]{@name}[/b]\nHP {@hp} · Gold {@gold}\nSkills: {@skill_*}"
_template.custom_minimum_size.y = 120
_template.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
style_text_edit(_template)
_template.text_changed.connect(_refresh)
box.add_child(field("Template (BBCode with {@var}, {@prefix_*} and {= expr})", _template))
_template_preview = RichTextLabel.new()
_template_preview.bbcode_enabled = true
_template_preview.fit_content = true
_template_preview.scroll_active = false
var pbox := PanelContainer.new()
pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7]))
pbox.add_child(_template_preview)
box.add_child(pbox)
RollTable.KIND_ROUTER:
box.add_child(section("Cases (if / else if / otherwise)"))
box.add_child(note("Checked top to bottom when the chain arrives; the first true case is chosen, and its effects, text and pipes run like a rolled result. An empty condition is Otherwise: it always matches, so keep it last. Add, remove and reorder cases on the card."))
for i in table.entries.size():
var e := table.entries[i]
var le := LineEdit.new()
le.text = e.when
le.placeholder_text = "Otherwise (always)"
style_line_edit(le)
le.text_changed.connect(func(_t: String) -> void: _refresh())
_cases.append(le)
var label := Formatter.strip_tags(e.text).strip_edges()
box.add_child(field("Case %d%s" % [i + 1, (" · " + label) if label != "" else ""], le))
if table.entries.is_empty():
box.add_child(note("This router has no cases yet: add some on the card."))
_case_note = note("", Style.WARN_INK)
box.add_child(_case_note)
_:
box.free() # roll tables have no kind fields
return
_kind_problem = note("", Style.DANGER_INK)
box.add_child(_kind_problem)
body.add_child(box)
## Pick choices: where the options come from, and a Show only if field per
## option.
func _build_options(box: VBoxContainer) -> void:
var mb := VBoxContainer.new()
mb.add_theme_constant_override("separation", 6)
mb.add_child(section("Options"))
mb.add_child(segmented(OPTION_LABELS, 1 if _options_mode == "vars" else 0, func(i: int) -> void:
_options_mode = "vars" if i == 1 else "fixed"
_refresh()
))
box.add_child(mb)
_opt_mode_box = mb
var ob := VBoxContainer.new()
ob.add_theme_constant_override("separation", 8)
_opt_from = LineEdit.new()
_opt_from.text = table.options_from
_opt_from.placeholder_text = "@skill_* or @contacts"
style_line_edit(_opt_from)
_opt_from.text_changed.connect(func(_t: String) -> void: _refresh())
ob.add_child(field("Options from (@prefix_* or a @list)", _opt_from))
_opt_where = LineEdit.new()
_opt_where.text = table.options_where
_opt_where.placeholder_text = "option_value >= 1 (optional)"
style_line_edit(_opt_where)
_opt_where.text_changed.connect(func(_t: String) -> void: _refresh())
ob.add_child(field("Only where (optional)", _opt_where))
_opt_note = note("")
ob.add_child(_opt_note)
box.add_child(ob)
_options_box = ob
var sb := VBoxContainer.new()
sb.add_theme_constant_override("separation", 6)
sb.add_child(section("Show only if"))
sb.add_child(note("Checked when the card is reached. An option whose condition is false isn't offered, not even to Random. Empty means always."))
for i in table.entries.size():
var e := table.entries[i]
var le := LineEdit.new()
le.text = e.show_if
le.placeholder_text = "always"
style_line_edit(le)
le.text_changed.connect(func(_t: String) -> void: _refresh())
_show_if[e.id] = le
var label := Formatter.strip_tags(e.text).strip_edges()
var cap := "Chosen (every option from variables)" if (i == 0 and table.is_dynamic()) else "Option %d%s" % [i + (0 if table.is_dynamic() else 1), (" · " + label) if label != "" else ""]
sb.add_child(field(cap, le))
box.add_child(sb)
_show_if_box = sb
func _refresh_kind() -> void:
var s := settings()
var problems := kind_problems(table, s)
if _kind_problem:
_kind_problem.text = "\n".join(problems)
_kind_problem.visible = not problems.is_empty()
match table.kind:
RollTable.KIND_CHOICE:
_minmax_row.visible = _choice == "number"
var msg := ""
if _choice != table.choice and table.choice == "pick":
msg = "Only the first option is kept, as the Answer row (its effects and pipes stay)."
elif _choice != table.choice and _choice == "pick":
msg = "The Answer row becomes the first option; two more are added."
elif _choice == "pick" and _options_mode == "vars" and table.is_dynamic():
msg = "The player picks one of the options from variables or a fixed extra, or Random."
elif _choice == "pick" and _options_mode == "fixed" and table.is_dynamic():
msg = "Back to a fixed list: the Chosen row becomes an ordinary option (or goes, if it does nothing)."
elif _choice == "pick":
msg = "The player picks one of the card's options, or Random."
else:
msg = "The answer goes in {answer}; the Answer row's effects and pipes run after it."
_choice_note.text = msg
_mark(_save_as, s["save_as"] == "" or _re(SAVE_PATTERN).search(TemplateKit.probe(s["save_as"])) != null)
var pick := _choice == "pick"
_opt_mode_box.visible = pick
_options_box.visible = pick and _options_mode == "vars"
_show_if_box.visible = pick and not _show_if.is_empty()
if pick and _options_mode == "vars":
_mark(_opt_from, options_from_error(s["options_from"]) == "")
_mark(_opt_where, when_error(s["options_where"]) == "")
var desc := RollTable.new()
desc.options_from = s["options_from"]
desc.options_where = s["options_where"]
var how := "One option for %s, labelled with its name and value, after any fixed options. The Chosen row runs for whichever is picked; option, option_label and option_value hold it, e.g. @[option] += 1." % desc.options_description() \
if options_from_error(s["options_from"]) == "" else "Write @skill_* for each set variable with that prefix, or @contacts for each item of a list."
if not table.is_dynamic():
how += " A Chosen row is added first; the options already on the card stay as fixed extras."
_opt_note.text = how
elif pick and table.is_dynamic():
_opt_note.text = ""
for eid: String in _show_if:
_mark(_show_if[eid] as LineEdit, when_error((_show_if[eid] as LineEdit).text) == "")
_mark(_min, Expr.check(TemplateKit.probe(s["min"])) == "" and s["min"] != "")
_mark(_max, Expr.check(TemplateKit.probe(s["max"])) == "" and s["max"] != "")
RollTable.KIND_LOOP:
_loop_note.text = LOOP_NOTES.get(_loop_mode, "")
_mark(_loop_expr, s["loop_expr"] != "" and Expr.check(TemplateKit.probe(s["loop_expr"])) == "")
RollTable.KIND_VARIABLE:
_mark(_var_name, _re(VAR_PATTERN).search(TemplateKit.probe(s["var_name"])) != null)
_mark(_initial, _initial_error(s["initial"], _var_type) == "")
RollTable.KIND_SHEET:
var ctx := Roller.live_context(table_board(), _live_vars())
_template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \
else "[color=#69726b]Preview appears here.[/color]"
RollTable.KIND_ROUTER:
var cases: Array = s["cases"]
for i in _cases.size():
_mark(_cases[i], when_error(str(cases[i])) == "")
var hint := router_hint(cases)
_case_note.text = hint
_case_note.visible = hint != ""
# The ranged/card-mode sections only apply to roll tables and pick choices.
var rolls := table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and _choice == "pick")
_type_box.visible = rolls
_card_box.visible = rolls
func _mark(le: LineEdit, ok: bool) -> void:
le.add_theme_color_override("font_color", Style.INK if ok else Style.DANGER_INK)
## The board and variables for the sheet preview, when the dialog sits in Main.
func table_board() -> TowerBoard:
var m := get_parent() as Main
return m.data if m else TowerBoard.new()
func _live_vars() -> Dictionary:
var m := get_parent() as Main
return m.persistent_vars if m else {}
func _refresh() -> void:
if _preview == null:
return
@ -563,12 +252,12 @@ func _refresh() -> void:
_dice_row.visible = _ranged
_deck_block.visible = _card_mode
var s := settings()
var dice_ok := not _ranged or dice_ok_text(s["dice"])
var dice_ok := not _ranged or TableSettingsRules.dice_ok_text(s["dice"])
_dice.add_theme_color_override("font_color", Style.INK if dice_ok else Style.WARN_INK)
var msgs := PackedStringArray()
if _ranged and not table.is_ranged():
msgs.append("Each entry gets a range sized by its weight; adjust them on the card.")
if _ranged and extra_pipe_count(table) > 0:
if _ranged and TableSettingsRules.extra_pipe_count(table) > 0:
msgs.append("A range takes one pipe, so extra pipes on an entry will be dropped.")
if not _ranged and table.is_ranged():
msgs.append("Ranges are removed; entries become plain picks.")
@ -579,23 +268,23 @@ func _refresh() -> void:
problem = "“%s” is not a valid dice expression." % s["dice"]
elif _type_box == null or _type_box.visible:
var clone := RollTable.from_dict(table.to_dict())
apply_settings(clone, s)
TableSettingsRules.apply_settings(clone, s)
problem = clone.range_problems()
_problem.text = problem
_problem.visible = problem != ""
if _type_box != null:
_refresh_kind()
_kind.refresh()
if is_inside_tree():
_fit()
func _on_apply() -> void:
var s := settings()
var r := apply_settings(table, s)
var r := TableSettingsRules.apply_settings(table, s)
if not r["ok"]:
if _kind_problem and not kind_problems(table, s).is_empty():
_kind_problem.text = r["error"]
_kind_problem.visible = true
if _kind.problem and not TableSettingsRules.kind_problems(table, s).is_empty():
_kind.problem.text = r["error"]
_kind.problem.visible = true
else:
_problem.text = r["error"]
_problem.visible = true
@ -604,300 +293,16 @@ func _on_apply() -> void:
close()
## Problems with the kind-specific settings (empty when fine).
static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
var out := PackedStringArray()
match t.kind:
RollTable.KIND_CHOICE:
# Template placeholders ({$name}) check as a plain name (TemplateKit.probe).
var save := TemplateKit.probe(str(s.get("save_as", t.save_as)).strip_edges())
if save != "" and _re(SAVE_PATTERN).search(save) == null:
out.append("Save as: use a name like career, or @career to keep it.")
if str(s.get("choice", t.choice)) == "pick":
if str(s.get("options_mode", "vars" if t.options_from != "" else "fixed")) == "vars":
var ferr := options_from_error(str(s.get("options_from", t.options_from)))
if ferr != "":
out.append("Options from: " + ferr)
var werr := when_error(str(s.get("options_where", t.options_where)))
if werr != "":
out.append("Only where: " + werr)
var si: Dictionary = s.get("show_if", {})
for eid: String in si:
var serr := when_error(str(si[eid]))
if serr != "":
var e := t.find_entry(eid)
var at := t.entries.find(e) if e != null else -1
out.append("Show only if (%s): %s" % [("option %d" % (at + 1)) if at >= 0 else eid, serr])
if str(s.get("choice", t.choice)) == "number":
for k in [["min", "Lowest"], ["max", "Highest"]]:
var src := TemplateKit.probe(str(s.get(k[0], "")).strip_edges())
var err := Expr.check(src) if src != "" else "it's empty"
if err != "":
out.append("%s: %s" % [k[1], err])
RollTable.KIND_LOOP:
var src := TemplateKit.probe(str(s.get("loop_expr", t.loop_expr)).strip_edges())
if src == "":
out.append("The loop needs a count or a condition.")
elif Expr.check(src) != "":
out.append("Loop rule: " + Expr.check(src))
RollTable.KIND_ROUTER:
var cases: Array = s.get("cases", [])
for i in cases.size():
var err := when_error(str(cases[i]))
if err != "":
out.append("Case %d: %s" % [i + 1, err])
RollTable.KIND_VARIABLE:
var n := TemplateKit.probe(str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@"))
if _re(VAR_PATTERN).search(n) == null:
out.append("Variable name: lowercase letters, digits and _ only.")
var err := _initial_error(str(s.get("initial", t.initial)), str(s.get("var_type", t.var_type)))
if err != "":
out.append("Starting value: " + err)
return out
## "" when a router case condition is usable (empty is Otherwise), else why not.
static func when_error(src: String) -> String:
src = TemplateKit.probe(src.strip_edges())
return Expr.check(src) if src != "" else ""
## "" when an options_from pattern is usable, else why not ("" is refused).
static func options_from_error(src: String) -> String:
src = TemplateKit.probe(src.strip_edges())
if src == "":
return "write @prefix_* or @list"
return str(RollTable.parse_options_from(src)["error"])
## A hint about the order of router cases (an Otherwise that isn't last), or "".
static func router_hint(cases: Array) -> String:
for i in cases.size():
if str(cases[i]).strip_edges() == "" and i < cases.size() - 1:
return "Case %d is Otherwise, so the cases after it can never be chosen. Move it to the end." % (i + 1)
return ""
static func _initial_error(src: String, type: String) -> String:
src = TemplateKit.probe(src.strip_edges())
if src == "":
return ""
if type != "number" and RollTable._looks_literal(src):
return ""
return Expr.check(src)
static func _re(pattern: String) -> RegEx:
return RegEx.create_from_string(pattern)
## Dice text for a ranged table: plain dice (2d6) or an expression that uses a
## variable, dice or a function ("2d6 + dm(@end)", "@terms"). A lone word
## such as "banana" is not accepted.
static func dice_ok_text(text: String) -> bool:
var s := TemplateKit.probe(text.strip_edges())
if Dice.is_valid_text(s):
return true
if s == "" or Expr.check(s) != "":
return false
return _re("^[A-Za-z_][A-Za-z0-9_]*$").search(s) == null
## Applies the kind-specific settings. Turning a pick choice into a number or
## text one keeps only its first entry (as the Answer); the other way, the
## Answer becomes the first of three options.
static func _apply_kind(t: RollTable, s: Dictionary) -> void:
match t.kind:
RollTable.KIND_CHOICE:
var c := str(s.get("choice", t.choice))
if RollTable.CHOICES.has(c) and c != t.choice:
if c == "pick":
if not t.entries.is_empty():
t.entries[0].text = "Option 1"
for n in range(t.entries.size() + 1, 4):
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option %d" % n))
else:
while t.entries.size() > 1:
t.entries.remove_at(t.entries.size() - 1)
if t.entries.is_empty():
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Answer"))
t.entries[0].text = "Answer"
t.entries[0].has_range = false
t.card_mode = false
t.choice = c
t.prompt = str(s.get("prompt", t.prompt))
t.save_as = str(s.get("save_as", t.save_as)).strip_edges()
var si: Dictionary = s.get("show_if", {})
for eid: String in si:
var se := t.find_entry(eid)
if se != null:
se.show_if = str(si[eid]).strip_edges()
if t.choice != "pick":
t.options_from = ""
t.options_where = ""
elif s.has("options_mode"):
_apply_options(t, str(s["options_mode"]) == "vars", str(s.get("options_from", "")), str(s.get("options_where", "")))
if t.choice == "number":
t.min_expr = str(s.get("min", t.min_expr)).strip_edges()
t.max_expr = str(s.get("max", t.max_expr)).strip_edges()
RollTable.KIND_LOOP:
var m := str(s.get("loop_mode", t.loop_mode))
if RollTable.LOOPS.has(m):
t.loop_mode = m
t.loop_expr = str(s.get("loop_expr", t.loop_expr)).strip_edges()
RollTable.KIND_VARIABLE:
t.var_name = str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@")
var vt := str(s.get("var_type", t.var_type))
if RollTable.VAR_TYPES.has(vt):
t.var_type = vt
t.initial = str(s.get("initial", t.initial)).strip_edges()
RollTable.KIND_ROUTER:
var cases: Array = s.get("cases", [])
for i in mini(cases.size(), t.entries.size()):
t.entries[i].when = str(cases[i]).strip_edges()
RollTable.KIND_SHEET:
if s.has("template"):
if t.entries.is_empty():
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), ""))
t.entries[0].text = str(s["template"])
## Switches a pick card between a fixed list and options from variables.
## Turning variables on adds a Chosen entry first (untouched default
## "Option N" entries go; anything else stays as a fixed extra). Turning them
## off makes the Chosen entry an ordinary option, or drops it if it does
## nothing (no effects, pipes, details or text of its own).
static func _apply_options(t: RollTable, on: bool, from: String, where: String) -> void:
if on:
if not t.is_dynamic():
var keep: Array[TableEntry] = []
for e in t.entries:
var blank := e.effects.strip_edges() == "" and e.pipes.is_empty() and e.details.strip_edges() == "" \
and e.show_if.strip_edges() == "" and RegEx.create_from_string("^Option \\d+$").search(e.text.strip_edges()) != null
if not blank:
keep.append(e)
t.entries = keep
t.entries.insert(0, TableEntry.new(TowerBoard.new_id("e"), Roller.CHOSEN))
t.options_from = from.strip_edges()
t.options_where = where.strip_edges()
return
if t.is_dynamic() and not t.entries.is_empty():
var c := t.entries[0]
var txt := Formatter.strip_tags(c.text).strip_edges()
if c.effects.strip_edges() == "" and c.pipes.is_empty() and c.details.strip_edges() == "" and (txt == "" or txt == Roller.CHOSEN):
t.entries.remove_at(0)
t.options_from = ""
t.options_where = ""
if t.entries.is_empty():
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option 1"))
# ---------- Pure editing logic ----------
## Wraps text[sel.x:sel.y] in open/close_tag. With an empty range, inserts the
## pair. Returns {text, caret}: the caret sits inside an inserted pair, or
## after the closing tag of a wrapped selection.
static func wrap_text(text: String, sel: Vector2i, open: String, close_tag: String) -> Dictionary:
var a := clampi(mini(sel.x, sel.y), 0, text.length())
var b := clampi(maxi(sel.x, sel.y), 0, text.length())
var out := text.substr(0, a) + open + text.substr(a, b - a) + close_tag + text.substr(b)
var caret := a + open.length() if a == b else b + open.length() + close_tag.length()
return {"text": out, "caret": caret}
## "a, b ,, a" -> ["a", "b"].
static func parse_tags(text: String) -> Array[String]:
var out: Array[String] = []
for part in text.split(","):
var t := part.strip_edges()
if t != "" and not out.has(t):
out.append(t)
return out
## Number of pipes beyond the first, summed over entries (lost when going ranged).
static func extra_pipe_count(t: RollTable) -> int:
var n := 0
for e in t.entries:
n += maxi(0, e.pipes.size() - 1)
return n
## Applies a settings Dictionary (name, details, tags, ranged, dice, card_mode,
## deck_empty) to the table. Returns {ok, error, deck_reset}: on a bad dice
## expression nothing is changed. deck_reset says the card deck no longer fits
## (type, dice or card mode changed), so a saved deck should be cleared.
## TableSettingsRules.apply_settings.
static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary:
var problems := kind_problems(t, s)
if not problems.is_empty():
return {"ok": false, "error": "\n".join(problems), "deck_reset": false}
var ranged: bool = s.get("ranged", false)
# Only roll tables and pick choices can be ranged or dealt as cards.
var choice := str(s.get("choice", t.choice))
var rolls := t.kind == RollTable.KIND_ROLL or (t.kind == RollTable.KIND_CHOICE and choice == "pick")
if not rolls:
ranged = false
var dice := str(s.get("dice", t.dice)).strip_edges()
if ranged and not dice_ok_text(dice):
return {"ok": false, "error": "“%s” is not a valid dice expression." % dice, "deck_reset": false}
var was_ranged := t.is_ranged()
var old_dice := t.dice
var old_card := t.card_mode
var new_name := str(s.get("name", t.name)).strip_edges()
if new_name != "":
t.name = new_name
t.details = str(s.get("details", t.details))
t.tags = parse_tags(str(s.get("tags", "")))
t.card_mode = bool(s.get("card_mode", t.card_mode)) and rolls
t.deck_empty = "stop" if str(s.get("deck_empty", t.deck_empty)) == "stop" else "reshuffle"
if ranged:
t.dice = dice
if not was_ranged:
assign_ranges(t)
elif was_ranged:
drop_ranges(t)
_apply_kind(t, s)
var deck_reset := was_ranged != ranged or old_card != t.card_mode or (ranged and old_dice != t.dice)
return {"ok": true, "error": "", "deck_reset": deck_reset}
return TableSettingsRules.apply_settings(t, s)
## Gives entries ranges on the table's dice, sized by weight (at least one
## value each while there is room). Entries of weight 0 get no range. Each
## entry keeps only its first pipe, since a range takes one pipe.
static func assign_ranges(t: RollTable) -> void:
var d := t.dice_obj()
var lo := d.min_value()
var hi := d.max_value()
var live: Array[TableEntry] = []
var total := 0
for e in t.entries:
e.has_range = false
if e.weight > 0:
live.append(e)
total += e.weight
while e.pipes.size() > 1:
e.remove_pipe(e.pipes[e.pipes.size() - 1])
var span := hi - lo + 1
var cum := 0
var prev := lo - 1
for i in live.size():
var e := live[i]
if prev >= hi:
break
cum += e.weight
var end := lo - 1 + roundi(float(span) * cum / total)
end = mini(end, hi - (live.size() - 1 - i))
end = clampi(maxi(end, prev + 1), prev + 1, hi)
if i == live.size() - 1:
end = hi
e.has_range = true
e.range_lo = prev + 1
e.range_hi = end
prev = end
## TableSettingsRules.when_error.
static func when_error(src: String) -> String:
return TableSettingsRules.when_error(src)
static func drop_ranges(t: RollTable) -> void:
for e in t.entries:
e.has_range = false
e.range_lo = 1
e.range_hi = 1
## TableSettingsRules.dice_ok_text.
static func dice_ok_text(text: String) -> bool:
return TableSettingsRules.dice_ok_text(text)

307
ui/table_settings_rules.gd Normal file
View file

@ -0,0 +1,307 @@
class_name TableSettingsRules
extends RefCounted
## The editing rules behind TableSettingsDialog: checking a settings
## Dictionary and applying it to a table. Static, so they can be tested
## without a window.
const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
const VAR_PATTERN := "^[a-z0-9_]+$"
## Problems with the kind-specific settings (empty when fine).
static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
var out := PackedStringArray()
match t.kind:
RollTable.KIND_CHOICE:
# Template placeholders ({$name}) check as a plain name (TemplateKit.probe).
var save := TemplateKit.probe(str(s.get("save_as", t.save_as)).strip_edges())
if save != "" and _re(SAVE_PATTERN).search(save) == null:
out.append("Save as: use a name like career, or @career to keep it.")
if str(s.get("choice", t.choice)) == "pick":
if str(s.get("options_mode", "vars" if t.options_from != "" else "fixed")) == "vars":
var ferr := options_from_error(str(s.get("options_from", t.options_from)))
if ferr != "":
out.append("Options from: " + ferr)
var werr := when_error(str(s.get("options_where", t.options_where)))
if werr != "":
out.append("Only where: " + werr)
var si: Dictionary = s.get("show_if", {})
for eid: String in si:
var serr := when_error(str(si[eid]))
if serr != "":
var e := t.find_entry(eid)
var at := t.entries.find(e) if e != null else -1
out.append("Show only if (%s): %s" % [("option %d" % (at + 1)) if at >= 0 else eid, serr])
if str(s.get("choice", t.choice)) == "number":
for k in [["min", "Lowest"], ["max", "Highest"]]:
var src := TemplateKit.probe(str(s.get(k[0], "")).strip_edges())
var err := Expr.check(src) if src != "" else "it's empty"
if err != "":
out.append("%s: %s" % [k[1], err])
RollTable.KIND_LOOP:
var src := TemplateKit.probe(str(s.get("loop_expr", t.loop_expr)).strip_edges())
if src == "":
out.append("The loop needs a count or a condition.")
elif Expr.check(src) != "":
out.append("Loop rule: " + Expr.check(src))
RollTable.KIND_ROUTER:
var cases: Array = s.get("cases", [])
for i in cases.size():
var err := when_error(str(cases[i]))
if err != "":
out.append("Case %d: %s" % [i + 1, err])
RollTable.KIND_VARIABLE:
var n := TemplateKit.probe(str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@"))
if _re(VAR_PATTERN).search(n) == null:
out.append("Variable name: lowercase letters, digits and _ only.")
var err := _initial_error(str(s.get("initial", t.initial)), str(s.get("var_type", t.var_type)))
if err != "":
out.append("Starting value: " + err)
return out
## "" when a router case condition is usable (empty is Otherwise), else why not.
static func when_error(src: String) -> String:
src = TemplateKit.probe(src.strip_edges())
return Expr.check(src) if src != "" else ""
## "" when an options_from pattern is usable, else why not ("" is refused).
static func options_from_error(src: String) -> String:
src = TemplateKit.probe(src.strip_edges())
if src == "":
return "write @prefix_* or @list"
return str(RollTable.parse_options_from(src)["error"])
## A hint about the order of router cases (an Otherwise that isn't last), or "".
static func router_hint(cases: Array) -> String:
for i in cases.size():
if str(cases[i]).strip_edges() == "" and i < cases.size() - 1:
return "Case %d is Otherwise, so the cases after it can never be chosen. Move it to the end." % (i + 1)
return ""
static func _initial_error(src: String, type: String) -> String:
src = TemplateKit.probe(src.strip_edges())
if src == "":
return ""
if type != "number" and RollTable._looks_literal(src):
return ""
return Expr.check(src)
static func _re(pattern: String) -> RegEx:
return RegEx.create_from_string(pattern)
## Dice text for a ranged table: plain dice (2d6) or an expression that uses a
## variable, dice or a function ("2d6 + dm(@end)", "@terms"). A lone word
## such as "banana" is not accepted.
static func dice_ok_text(text: String) -> bool:
var s := TemplateKit.probe(text.strip_edges())
if Dice.is_valid_text(s):
return true
if s == "" or Expr.check(s) != "":
return false
return _re("^[A-Za-z_][A-Za-z0-9_]*$").search(s) == null
## Applies the kind-specific settings. Turning a pick choice into a number or
## text one keeps only its first entry (as the Answer); the other way, the
## Answer becomes the first of three options.
static func _apply_kind(t: RollTable, s: Dictionary) -> void:
match t.kind:
RollTable.KIND_CHOICE:
var c := str(s.get("choice", t.choice))
if RollTable.CHOICES.has(c) and c != t.choice:
if c == "pick":
if not t.entries.is_empty():
t.entries[0].text = "Option 1"
for n in range(t.entries.size() + 1, 4):
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option %d" % n))
else:
while t.entries.size() > 1:
t.entries.remove_at(t.entries.size() - 1)
if t.entries.is_empty():
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Answer"))
t.entries[0].text = "Answer"
t.entries[0].has_range = false
t.card_mode = false
t.choice = c
t.prompt = str(s.get("prompt", t.prompt))
t.save_as = str(s.get("save_as", t.save_as)).strip_edges()
var si: Dictionary = s.get("show_if", {})
for eid: String in si:
var se := t.find_entry(eid)
if se != null:
se.show_if = str(si[eid]).strip_edges()
if t.choice != "pick":
t.options_from = ""
t.options_where = ""
elif s.has("options_mode"):
_apply_options(t, str(s["options_mode"]) == "vars", str(s.get("options_from", "")), str(s.get("options_where", "")))
if t.choice == "number":
t.min_expr = str(s.get("min", t.min_expr)).strip_edges()
t.max_expr = str(s.get("max", t.max_expr)).strip_edges()
RollTable.KIND_LOOP:
var m := str(s.get("loop_mode", t.loop_mode))
if RollTable.LOOPS.has(m):
t.loop_mode = m
t.loop_expr = str(s.get("loop_expr", t.loop_expr)).strip_edges()
RollTable.KIND_VARIABLE:
t.var_name = str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@")
var vt := str(s.get("var_type", t.var_type))
if RollTable.VAR_TYPES.has(vt):
t.var_type = vt
t.initial = str(s.get("initial", t.initial)).strip_edges()
RollTable.KIND_ROUTER:
var cases: Array = s.get("cases", [])
for i in mini(cases.size(), t.entries.size()):
t.entries[i].when = str(cases[i]).strip_edges()
RollTable.KIND_SHEET:
if s.has("template"):
if t.entries.is_empty():
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), ""))
t.entries[0].text = str(s["template"])
## Switches a pick card between a fixed list and options from variables.
## Turning variables on adds a Chosen entry first (untouched default
## "Option N" entries go; anything else stays as a fixed extra). Turning them
## off makes the Chosen entry an ordinary option, or drops it if it does
## nothing (no effects, pipes, details or text of its own).
static func _apply_options(t: RollTable, on: bool, from: String, where: String) -> void:
if on:
if not t.is_dynamic():
var keep: Array[TableEntry] = []
for e in t.entries:
var blank := e.effects.strip_edges() == "" and e.pipes.is_empty() and e.details.strip_edges() == "" \
and e.show_if.strip_edges() == "" and RegEx.create_from_string("^Option \\d+$").search(e.text.strip_edges()) != null
if not blank:
keep.append(e)
t.entries = keep
t.entries.insert(0, TableEntry.new(TowerBoard.new_id("e"), Roller.CHOSEN))
t.options_from = from.strip_edges()
t.options_where = where.strip_edges()
return
if t.is_dynamic() and not t.entries.is_empty():
var c := t.entries[0]
var txt := Formatter.strip_tags(c.text).strip_edges()
if c.effects.strip_edges() == "" and c.pipes.is_empty() and c.details.strip_edges() == "" and (txt == "" or txt == Roller.CHOSEN):
t.entries.remove_at(0)
t.options_from = ""
t.options_where = ""
if t.entries.is_empty():
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option 1"))
# ---------- Pure editing logic ----------
## Wraps text[sel.x:sel.y] in open/close_tag. With an empty range, inserts the
## pair. Returns {text, caret}: the caret sits inside an inserted pair, or
## after the closing tag of a wrapped selection.
static func wrap_text(text: String, sel: Vector2i, open: String, close_tag: String) -> Dictionary:
var a := clampi(mini(sel.x, sel.y), 0, text.length())
var b := clampi(maxi(sel.x, sel.y), 0, text.length())
var out := text.substr(0, a) + open + text.substr(a, b - a) + close_tag + text.substr(b)
var caret := a + open.length() if a == b else b + open.length() + close_tag.length()
return {"text": out, "caret": caret}
## "a, b ,, a" -> ["a", "b"].
static func parse_tags(text: String) -> Array[String]:
var out: Array[String] = []
for part in text.split(","):
var t := part.strip_edges()
if t != "" and not out.has(t):
out.append(t)
return out
## Number of pipes beyond the first, summed over entries (lost when going ranged).
static func extra_pipe_count(t: RollTable) -> int:
var n := 0
for e in t.entries:
n += maxi(0, e.pipes.size() - 1)
return n
## Applies a settings Dictionary (name, details, tags, ranged, dice, card_mode,
## deck_empty) to the table. Returns {ok, error, deck_reset}: on a bad dice
## expression nothing is changed. deck_reset says the card deck no longer fits
## (type, dice or card mode changed), so a saved deck should be cleared.
static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary:
var problems := kind_problems(t, s)
if not problems.is_empty():
return {"ok": false, "error": "\n".join(problems), "deck_reset": false}
var ranged: bool = s.get("ranged", false)
# Only roll tables and pick choices can be ranged or dealt as cards.
var choice := str(s.get("choice", t.choice))
var rolls := t.kind == RollTable.KIND_ROLL or (t.kind == RollTable.KIND_CHOICE and choice == "pick")
if not rolls:
ranged = false
var dice := str(s.get("dice", t.dice)).strip_edges()
if ranged and not dice_ok_text(dice):
return {"ok": false, "error": "“%s” is not a valid dice expression." % dice, "deck_reset": false}
var was_ranged := t.is_ranged()
var old_dice := t.dice
var old_card := t.card_mode
var new_name := str(s.get("name", t.name)).strip_edges()
if new_name != "":
t.name = new_name
t.details = str(s.get("details", t.details))
t.tags = parse_tags(str(s.get("tags", "")))
t.card_mode = bool(s.get("card_mode", t.card_mode)) and rolls
t.deck_empty = "stop" if str(s.get("deck_empty", t.deck_empty)) == "stop" else "reshuffle"
if ranged:
t.dice = dice
if not was_ranged:
assign_ranges(t)
elif was_ranged:
drop_ranges(t)
_apply_kind(t, s)
var deck_reset := was_ranged != ranged or old_card != t.card_mode or (ranged and old_dice != t.dice)
return {"ok": true, "error": "", "deck_reset": deck_reset}
## Gives entries ranges on the table's dice, sized by weight (at least one
## value each while there is room). Entries of weight 0 get no range. Each
## entry keeps only its first pipe, since a range takes one pipe.
static func assign_ranges(t: RollTable) -> void:
var d := t.dice_obj()
var lo := d.min_value()
var hi := d.max_value()
var live: Array[TableEntry] = []
var total := 0
for e in t.entries:
e.has_range = false
if e.weight > 0:
live.append(e)
total += e.weight
while e.pipes.size() > 1:
e.remove_pipe(e.pipes[e.pipes.size() - 1])
var span := hi - lo + 1
var cum := 0
var prev := lo - 1
for i in live.size():
var e := live[i]
if prev >= hi:
break
cum += e.weight
var end := lo - 1 + roundi(float(span) * cum / total)
end = mini(end, hi - (live.size() - 1 - i))
end = clampi(maxi(end, prev + 1), prev + 1, hi)
if i == live.size() - 1:
end = hi
e.has_range = true
e.range_lo = prev + 1
e.range_hi = end
prev = end
static func drop_ranges(t: RollTable) -> void:
for e in t.entries:
e.has_range = false
e.range_lo = 1
e.range_hi = 1

View file

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

View file

@ -61,11 +61,10 @@ func _build() -> void:
start_pick = OptionButton.new()
start_pick.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.DASH))
start_pick.add_theme_stylebox_override("hover", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
start_pick.add_theme_stylebox_override("pressed", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
start_pick.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color", "font_hover_pressed_color"]:
start_pick.add_theme_color_override(c, Style.INK)
var lit := Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER)
for n in ["hover", "pressed", "focus"]:
start_pick.add_theme_stylebox_override(n, lit)
Style.font_colors(start_pick, Style.INK)
start_pick.add_theme_font_size_override("font_size", 16)
start_pick.clip_text = true
start_pick.fit_to_longest_item = false
@ -301,8 +300,7 @@ func _add_section(title: String, hint: String, items: Array, open: bool) -> void
header.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
header.add_theme_font_override("font", Style.body_bold())
header.add_theme_font_size_override("font_size", 16)
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color", "font_hover_pressed_color"]:
header.add_theme_color_override(c, Style.INK if not items.is_empty() else Style.MUTED)
Style.font_colors(header, Style.INK if not items.is_empty() else Style.MUTED)
header.add_theme_color_override("font_disabled_color", Style.MUTED)
header.tooltip_text = hint
var list := VBoxContainer.new()
@ -338,8 +336,7 @@ func _item_button(item: Dictionary) -> Button:
b.size_flags_horizontal = SIZE_EXPAND_FILL
b.add_theme_font_override("font", Style.body())
b.add_theme_font_size_override("font_size", 14)
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color", "font_hover_pressed_color"]:
b.add_theme_color_override(c, Style.INK)
Style.font_colors(b, Style.INK)
b.add_theme_stylebox_override("hover", Style.box(Style.HOVER_ROW, 5, [8, 3, 8, 3]))
b.add_theme_stylebox_override("pressed", Style.box(Style.HOVER_ROW, 5, [8, 3, 8, 3]))
b.add_theme_stylebox_override("normal", Style.box(Color(0, 0, 0, 0), 5, [8, 3, 8, 3]))

163
ui/tray_chips.gd Normal file
View file

@ -0,0 +1,163 @@
class_name TrayChips
extends RefCounted
## Builders for the pieces of ResultTray's chain: result chips (with their
## effect lines and "Why this?" button), the brass links between them, the
## open-question chip and the "+N earlier steps" toggle.
## Most effect lines listed under one chip.
const EFFECT_LINES := 3
## The chip for steps[index]; `last` marks the final result of a finished roll.
static func chip(tray: ResultTray, step: Dictionary, last: bool, steps: Array = [], index: int = -1) -> Control:
var main := tray.main
var inline: bool = step.get("inline", false)
var p := PanelContainer.new()
var sb := Style.box(Style.LIT if last else Style.CARD, 9, [10, 5, 10, 6] if inline else [12, 7, 12, 8])
sb.shadow_color = Color(0, 0, 0, 0.25)
sb.shadow_size = 1
sb.shadow_offset = Vector2(0, 3)
if last:
Style.bordered(sb, 2, Style.BRASS)
sb.set_expand_margin_all(2)
if inline:
sb.bg_color = sb.bg_color.darkened(0.04)
p.add_theme_stylebox_override("panel", sb)
p.size_flags_vertical = Control.SIZE_SHRINK_CENTER
p.mouse_filter = Control.MOUSE_FILTER_PASS
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 1)
p.add_child(v)
var plain := RulesView.plain(main)
var caption := TrayText.caption_for(step, main.data, plain)
var has_why := index >= 0 and WhyPopover.has_why(steps, index)
var has_details := main.details().step_has_details(step)
if has_details:
caption += " " + RichText.INFO_MARK
var cap := Style.make_label(caption, Style.body(), 11 if inline else 12, Style.MUTED)
cap.mouse_filter = Control.MOUSE_FILTER_IGNORE
v.add_child(cap)
var raw := str(step["text"])
if str(step.get("kind", "")) == RollTable.KIND_SHEET:
raw = TrayText.one_line(raw)
if step.has("answer") and Formatter.strip_tags(raw).strip_edges() == "":
raw = "[i]no answer[/i]"
var shown := RichText.decorate(raw)
var body := RichText.display_label(shown, 16 if inline else 20, Style.DANGER_INK if step.get("stop", false) else Style.INK)
if Formatter.strip_tags(shown).length() > 56:
body.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
body.custom_minimum_size = Vector2(420, 0)
RichText.hook_hover(body, main)
v.add_child(body)
var fx: Array = step.get("effects", [])
if not fx.is_empty():
v.add_child(_effect_lines(TrayText.effect_lines_for(step, main.data, plain)))
if has_why:
var wb := _why_button()
wb.pressed.connect(func() -> void: tray.open_why(index, wb))
tray.why_buttons[index] = wb
v.add_child(wb)
if has_details or has_why:
p.mouse_entered.connect(func() -> void:
if not tray.why_popover().visible:
main.details().show_step(p, step, steps, index))
return p
## The small "Why this?" pill under a chip.
static func _why_button() -> Button:
var b := Button.new()
b.text = "Why this?"
b.tooltip_text = "What decided this step"
b.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
b.focus_mode = Control.FOCUS_NONE
var n := Style.bordered(Style.box(Color.WHITE, 10, [9, 1, 9, 2]), 1, Style.RULE)
var h := Style.bordered(Style.box(Style.LIT, 10, [9, 1, 9, 2]), 1, Style.BRASS_DARK)
Style.skin_button(b, n, h, h, Style.COPPER_DARK, Style.INK)
b.add_theme_font_override("font", Style.body_bold())
b.add_theme_font_size_override("font_size", 12)
return b
## The effect log under a chip: a few compact lines, errors in red.
static func _effect_lines(fx: Array) -> Control:
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 0)
box.mouse_filter = Control.MOUSE_FILTER_IGNORE
var shown := 0
for l: Variant in fx:
var d: Dictionary = l if l is Dictionary else {"text": str(l)}
var bad: bool = d.get("error", false)
# Errors are always listed; ordinary lines up to EFFECT_LINES.
if shown >= EFFECT_LINES and not bad:
continue
var lab := Style.make_label(("⚠ " if bad else "") + str(d.get("text", "")), Style.body_bold() if bad else Style.body(), 12,
Style.DANGER_INK if bad else Style.COPPER_DARK)
lab.mouse_filter = Control.MOUSE_FILTER_IGNORE
lab.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
lab.custom_minimum_size.x = 0
box.add_child(lab)
shown += 1
var more := fx.size() - shown
if more > 0:
box.add_child(Style.make_label("+%d more" % more, Style.body(), 11, Style.MUTED))
var tip := Effects.log_text(fx)
box.tooltip_text = "\n".join(tip)
return box
## The brass pipe piece between two chips (thinner for an inline step).
static func link(inline: bool = false) -> Control:
var l := Panel.new()
var sb := Style.box(Style.BRASS)
sb.border_width_top = 2
sb.border_width_bottom = 2
sb.border_color = Style.BRASS_DARK
if inline:
sb = Style.box(Color(Style.BRASS, 0.55))
l.add_theme_stylebox_override("panel", sb)
l.custom_minimum_size = Vector2(16, 4) if inline else Vector2(22, 8)
l.size_flags_vertical = Control.SIZE_SHRINK_CENTER
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
return l
## A dashed placeholder chip for the question that is open right now.
static func asking_chip(title: String) -> Control:
var p := PanelContainer.new()
var sb := Style.box(Color(1, 1, 1, 0.05), 9, [12, 7, 12, 8])
Style.bordered(sb, 1, Color(Style.BRASS, 0.6))
p.add_theme_stylebox_override("panel", sb)
p.size_flags_vertical = Control.SIZE_SHRINK_CENTER
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 1)
p.add_child(v)
v.add_child(Style.make_label(title, Style.body(), 12, Style.ON_FELT_MUTED))
v.add_child(Style.make_label("Waiting for your answer…", Style.display(), 20, Style.BRASS))
return p
## "+N earlier steps" (or "Hide earlier steps") at the start of a long chain.
static func earlier_toggle(tray: ResultTray, first: int, total: int) -> Control:
var b := Button.new()
if tray.expanded:
b.text = "Hide earlier steps" if first == 0 else "Hide earlier steps (%s not shown)" % TrayText.thousands(first)
else:
b.text = "+%s earlier steps" % TrayText.thousands(first)
b.tooltip_text = "This chain has %s steps" % TrayText.thousands(total)
b.size_flags_vertical = Control.SIZE_SHRINK_CENTER
var n := Style.bordered(Style.box(Color(1, 1, 1, 0.04), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16))
var h := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 8, [12, 6, 12, 6]), 1, Color(Style.BRASS, 0.5))
Style.skin_button(b, n, h, h, Style.ON_FELT_MUTED, Style.ON_FELT)
b.add_theme_font_size_override("font_size", 14)
b.pressed.connect(func() -> void:
tray.expanded = not tray.expanded
tray.render()
)
var wrap := HBoxContainer.new()
wrap.add_theme_constant_override("separation", 0)
wrap.add_child(b)
var gap := Control.new()
gap.custom_minimum_size = Vector2(10, 0)
wrap.add_child(gap)
return wrap

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

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

134
ui/tray_text.gd Normal file
View file

@ -0,0 +1,134 @@
class_name TrayText
extends RefCounted
## The words of ResultTray's chips: captions, effect lines and the sheet
## headline's step. Static, so they can be tested without a tray.
## The muted line above a chip's text: table name and how it got its result.
## With `plain`, rules read in plain words ("Loot · Tier 1 · rolled 4 on 1D +
## Tier", "Force the gate · rolled 7, +1 → 8"), labelled from `board`.
static func caption_for(step: Dictionary, board: TowerBoard = null, plain: bool = false) -> String:
var caption := Formatter.strip_tags(str(step["table"]))
var num: String = str(step.get("num", ""))
var ins: Variant = step.get("inputs")
if ins is Dictionary:
for nm: Variant in ins:
if plain:
caption += " · %s %s" % [Describe.label(str(nm), board), Expr.format_value(ins[nm])]
else:
caption += " · %s=%s" % [nm, Expr.format_value(ins[nm])]
match str(step.get("kind", "")):
RollTable.KIND_CHECK:
var c: Variant = step.get("check")
if c is Dictionary:
var mod := int(c.get("mod", 0))
var ms := ""
if mod != 0:
ms = ("+%d" % mod) if mod > 0 else (Describe.MINUS + str(-mod))
if plain:
caption += " · rolled %s%s → %s" % [Expr.format_value(c.get("nat")), (", " + ms) if ms != "" else "", Expr.format_value(c.get("total"))]
else:
caption += " · %s%s = %s vs %s" % [Expr.format_value(c.get("nat")), ms.replace(Describe.MINUS, "-"), Expr.format_value(c.get("total")), Expr.format_value(c.get("target"))]
RollTable.KIND_CHOICE:
if step.get("cancelled", false):
pass
elif step.has("answer"):
caption += " · answered"
elif step.get("picked", false):
caption += " · picked"
elif step.get("random", false):
caption += " · random"
if num != "":
caption += ", rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))]
RollTable.KIND_LOOP:
if step.has("pass"):
caption += " · pass %s" % str(step["pass"])
elif step.get("after", false):
caption += " · afterwards"
RollTable.KIND_SHEET:
caption += " · sheet"
RollTable.KIND_ROUTER:
if step.has("case"):
var said := false
if plain and board != null:
var rt := board.get_table(str(step.get("table_id", "")))
var k := int(step["case"])
if rt != null and k >= 0 and k < rt.entries.size():
caption += " · " + RulesView.cut(RulesView.case_label(rt.entries[k], board, true), 44)
said = true
if not said:
caption += " · case %d" % (int(step["case"]) + 1)
_:
if num != "":
var dl := str(step.get("dice", "d%d" % int(step.get("die", 0))))
if plain and dl.contains(" "):
dl = RulesView.cut(Describe.dice(dl, board), 30)
caption += " · rolled %s on %s" % [num, dl]
if step.get("reshuffled", false):
caption += " · deck reshuffled"
if str(step.get("save_as", "")) != "":
if plain:
caption += " · saved as %s" % Describe.label(str(step["save_as"]), board)
else:
caption += " · saved as {%s}" % step["save_as"]
return caption
## A step's effect lines for its chip: in plain words, one per value that
## changed ("Luck 2 → 1", "Town = Millbrook", "Cleared all Skills (3)") from
## its why facts, then any errors from its log; else the log as it is.
static func effect_lines_for(step: Dictionary, board: TowerBoard, plain: bool) -> Array:
var fx: Array = step.get("effects", [])
if not plain or not (step.get("why") is Array):
return fx
var out: Array = []
for f: Variant in step["why"]:
if f is Dictionary and str(f.get("type", "")) == "effect":
out.append({"text": effect_fact_line(f, board)})
if out.is_empty():
return fx
for l: Variant in fx:
if l is Dictionary and (l as Dictionary).get("error", false):
out.append(l)
return out
## "Luck 2 → 1", "Town = Millbrook", "Loot cleared", "Cleared all Skills (3)".
static func effect_fact_line(f: Dictionary, board: TowerBoard) -> String:
var lab := Describe.label(str(f.get("var", "")), board)
if f.has("count"):
return "Cleared all %s (%s)" % [lab, Expr.format_value(f["count"])]
var before: Variant = f.get("before")
var after: Variant = f.get("after")
if after == null:
return "%s cleared" % lab
var a := Expr.format_value(after)
if before == null or Expr.format_value(before) == "":
return "%s = %s" % [lab, a if a != "" else "(none)"]
return "%s %s → %s" % [lab, Expr.format_value(before), a if a != "" else "(none)"]
## The first line of a (sheet's) multi-line text, with "…" when there's more.
static func one_line(text: String) -> String:
var nl := text.find("\n")
if nl < 0:
return text
return Formatter.close_open_tags(text.substr(0, nl)) + " …"
## The last sheet step of a chain (the headline), or {}.
static func sheet_step(steps: Array) -> Dictionary:
for k in range(steps.size() - 1, -1, -1):
var s: Dictionary = steps[k]
if str(s.get("kind", "")) == RollTable.KIND_SHEET and not s.get("stop", false):
return s
return {}
static func thousands(n: int) -> String:
var s := str(n)
var out := ""
while s.length() > 3:
out = "," + s.substr(s.length() - 3) + out
s = s.substr(0, s.length() - 3)
return s + out

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

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