Build inspector with fill-in editors, value picker and Plain/Text switch

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
RobinFiredrake 2026-11-08 21:24:25 -06:00
parent 6f583ea4f5
commit ac3863d582
16 changed files with 3361 additions and 9 deletions

570
tests/test_inspector.gd Normal file
View file

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

View file

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

View file

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

633
ui/inspector.gd Normal file
View file

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

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

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

694
ui/inspector_card.gd Normal file
View file

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

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

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

247
ui/inspector_condition.gd Normal file
View file

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

View file

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

319
ui/inspector_effects.gd Normal file
View file

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

View file

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

276
ui/inspector_kit.gd Normal file
View file

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

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

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

View file

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

315
ui/value_picker.gd Normal file
View file

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

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

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