Pick choice cards can take their options from variables (options_from:
@prefix_* or a @list, filtered by options_where with option, option_label
and option_value bound). A Chosen entry runs for whichever dynamic option
is picked; fixed entries stay as extras, listed first. Random weighs each
dynamic option as the Chosen entry and fixed ones by weight. Any pick
option can have show_if, which hides it from the pop-up and from Random;
with nothing offered the node stops with "No options available".
@[expr] reads or writes the variable named by expr in expressions,
effects (including reset) and text ({@[expr]}); bad computed names are
effect errors. JSON round trip, lint_options in lint_pipes, choice
pop-up value badges and previews, card and settings UI, docs, demo board
(Spend a find) and tests/test_options.gd.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
903 lines
34 KiB
GDScript
903 lines
34 KiB
GDScript
class_name TableSettingsDialog
|
|
extends ModalCard
|
|
## Build-mode editor for one table's name, details, tags, type and card mode.
|
|
## The editing rules live in static functions (apply_settings and friends) so
|
|
## they can be tested without a window.
|
|
|
|
signal applied(settings: Dictionary)
|
|
## The footer's "Save as template…" (the dialog closes first; Main opens the save dialog).
|
|
signal template_requested
|
|
|
|
const COLORS := [
|
|
["Red", Color("#a33a2c")],
|
|
["Copper", Color("#b8703a")],
|
|
["Green", Color("#2f6b4f")],
|
|
["Blue", Color("#2f5d8a")],
|
|
["Purple", Color("#6b3f8a")],
|
|
]
|
|
|
|
var table: RollTable
|
|
|
|
var _name: LineEdit
|
|
var _details: TextEdit
|
|
var _preview: RichTextLabel
|
|
var _tags: LineEdit
|
|
var _dice: LineEdit
|
|
var _dice_row: Control
|
|
var _type_note: Label
|
|
var _problem: Label
|
|
var _deck_block: Control
|
|
var _ranged := false
|
|
var _card_mode := false
|
|
var _deck_empty := "reshuffle"
|
|
|
|
# Logic-card fields (docs/LOGIC.md), shown for the matching kind.
|
|
var _type_box: Control
|
|
var _card_box: Control
|
|
var _kind_problem: Label
|
|
var _choice := "pick"
|
|
var _choice_note: Label
|
|
var _prompt: LineEdit
|
|
var _save_as: LineEdit
|
|
var _min: LineEdit
|
|
var _max: LineEdit
|
|
var _minmax_row: Control
|
|
## Pick choices: "fixed" or "vars" (options from variables, plus fixed extras).
|
|
var _options_mode := "fixed"
|
|
var _options_box: Control
|
|
var _opt_mode_box: Control
|
|
var _opt_from: LineEdit
|
|
var _opt_where: LineEdit
|
|
var _opt_note: Label
|
|
var _show_if_box: Control
|
|
## entry id -> its Show only if field.
|
|
var _show_if: Dictionary = {}
|
|
var _loop_mode := "times"
|
|
var _loop_expr: LineEdit
|
|
var _loop_note: Label
|
|
var _var_name: LineEdit
|
|
var _var_type := "number"
|
|
var _initial: LineEdit
|
|
var _template: TextEdit
|
|
var _template_preview: RichTextLabel
|
|
## Router cards: one condition field per case, in order.
|
|
var _cases: Array[LineEdit] = []
|
|
var _case_note: Label
|
|
|
|
const TITLES := {
|
|
RollTable.KIND_ROLL: "Table settings",
|
|
RollTable.KIND_CHOICE: "Choice settings",
|
|
RollTable.KIND_LOOP: "Loop settings",
|
|
RollTable.KIND_VARIABLE: "Variable settings",
|
|
RollTable.KIND_SHEET: "Sheet settings",
|
|
RollTable.KIND_ROUTER: "Router settings",
|
|
}
|
|
const CHOICE_LABELS := ["Which option", "How many", "Open ended"]
|
|
const OPTION_LABELS := ["Fixed list", "From variables (+ fixed extras)"]
|
|
const LOOP_LABELS := ["Times", "While", "Until"]
|
|
const LOOP_NOTES := {
|
|
"times": "Runs Each time this many times (worked out once), then Afterwards. e.g. 3, @answer, 1d3",
|
|
"while": "Checks the condition before each pass and stops when it's false. e.g. @hp > 0",
|
|
"until": "Runs a pass, then stops once the condition is true (at least one pass). e.g. @gold >= 100",
|
|
}
|
|
const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
|
|
const VAR_PATTERN := "^[a-z0-9_]+$"
|
|
|
|
|
|
func _init(p_table: RollTable = null) -> void:
|
|
super._init(TITLES.get(p_table.kind, "Table settings") if p_table else "Table settings", 560.0)
|
|
table = p_table
|
|
_ranged = table.is_ranged()
|
|
_card_mode = table.card_mode
|
|
_deck_empty = table.deck_empty
|
|
_choice = table.choice
|
|
_options_mode = "vars" if table.options_from.strip_edges() != "" else "fixed"
|
|
_loop_mode = table.loop_mode
|
|
_var_type = table.var_type
|
|
_build()
|
|
|
|
|
|
func _build() -> void:
|
|
_name = LineEdit.new()
|
|
_name.text = table.name
|
|
_name.placeholder_text = "Table name"
|
|
style_line_edit(_name)
|
|
_name.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
body.add_child(field("Name", _name))
|
|
_build_kind()
|
|
|
|
_details = TextEdit.new()
|
|
_details.text = table.details
|
|
_details.placeholder_text = "What this table is for. BBCode is allowed."
|
|
_details.custom_minimum_size.y = 84
|
|
_details.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
|
|
style_text_edit(_details)
|
|
_details.text_changed.connect(_refresh)
|
|
var tools := HBoxContainer.new()
|
|
tools.add_theme_constant_override("separation", 6)
|
|
tools.add_child(_tool_button("B", "Bold", func() -> void: _wrap_selection("[b]", "[/b]")))
|
|
tools.add_child(_tool_button("I", "Italic", func() -> void: _wrap_selection("[i]", "[/i]")))
|
|
var color := make_button("Color ▾", "plain")
|
|
color.pressed.connect(func() -> void: _color_menu(color))
|
|
color.add_theme_font_size_override("font_size", 14)
|
|
tools.add_child(color)
|
|
var dbox := VBoxContainer.new()
|
|
dbox.add_theme_constant_override("separation", 6)
|
|
dbox.add_child(section("Details"))
|
|
dbox.add_child(tools)
|
|
dbox.add_child(_details)
|
|
_preview = RichTextLabel.new()
|
|
_preview.bbcode_enabled = true
|
|
_preview.fit_content = true
|
|
_preview.scroll_active = false
|
|
_preview.custom_minimum_size.y = 24
|
|
var pbox := PanelContainer.new()
|
|
pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7]))
|
|
pbox.add_child(_preview)
|
|
dbox.add_child(pbox)
|
|
body.add_child(dbox)
|
|
|
|
_tags = LineEdit.new()
|
|
_tags.text = ", ".join(table.tags)
|
|
_tags.placeholder_text = "loot, treasure, magic"
|
|
style_line_edit(_tags)
|
|
body.add_child(field("Tags (comma-separated)", _tags))
|
|
|
|
var type_box := VBoxContainer.new()
|
|
type_box.add_theme_constant_override("separation", 6)
|
|
type_box.add_child(section("Table type"))
|
|
type_box.add_child(segmented(["Plain", "Ranged (dice)"], 1 if _ranged else 0, func(i: int) -> void:
|
|
_ranged = i == 1
|
|
_refresh()
|
|
))
|
|
_dice = LineEdit.new()
|
|
_dice.text = table.dice
|
|
_dice.placeholder_text = "1d100"
|
|
_dice.custom_minimum_size.x = 140
|
|
style_line_edit(_dice)
|
|
_dice.size_flags_horizontal = SIZE_SHRINK_BEGIN
|
|
_dice.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
var drow := HBoxContainer.new()
|
|
drow.add_theme_constant_override("separation", 10)
|
|
var dl := Style.make_label("Dice", Style.body(), 15, Style.INK)
|
|
dl.size_flags_vertical = SIZE_SHRINK_CENTER
|
|
drow.add_child(dl)
|
|
drow.add_child(_dice)
|
|
var eg := note("e.g. 1d100, 2d6, 1d8+2")
|
|
eg.size_flags_vertical = SIZE_SHRINK_CENTER
|
|
drow.add_child(eg)
|
|
_dice_row = drow
|
|
type_box.add_child(drow)
|
|
_type_note = note("")
|
|
type_box.add_child(_type_note)
|
|
_problem = note("", Style.WARN_INK)
|
|
type_box.add_child(_problem)
|
|
body.add_child(type_box)
|
|
_type_box = type_box
|
|
|
|
var card_box := VBoxContainer.new()
|
|
card_box.add_theme_constant_override("separation", 6)
|
|
card_box.add_child(section("Card mode"))
|
|
card_box.add_child(segmented(["Off", "On"], 1 if _card_mode else 0, func(i: int) -> void:
|
|
_card_mode = i == 1
|
|
_refresh()
|
|
))
|
|
card_box.add_child(note("Entries are dealt like cards, without repeats, until the deck runs out."))
|
|
var deck := VBoxContainer.new()
|
|
deck.add_theme_constant_override("separation", 6)
|
|
deck.add_child(section("When the deck runs out"))
|
|
deck.add_child(segmented(["Reshuffle", "Stop"], 1 if _deck_empty == "stop" else 0, func(i: int) -> void:
|
|
_deck_empty = "stop" if i == 1 else "reshuffle"
|
|
_refresh()
|
|
))
|
|
_deck_block = deck
|
|
card_box.add_child(deck)
|
|
body.add_child(card_box)
|
|
_card_box = card_box
|
|
|
|
var tpl := add_button("Save as template…", "plain", func() -> void:
|
|
close()
|
|
template_requested.emit()
|
|
)
|
|
tpl.tooltip_text = "Save this card as a reusable template ({$name} in any text becomes a parameter)"
|
|
var gap := Control.new()
|
|
gap.size_flags_horizontal = SIZE_EXPAND_FILL
|
|
footer.add_child(gap)
|
|
add_button("Close", "plain", close)
|
|
add_button("Apply", "primary", _on_apply)
|
|
_refresh()
|
|
|
|
|
|
func _ready() -> void:
|
|
super._ready()
|
|
# Now that the dialog sits in Main, the sheet preview can use its variables.
|
|
_refresh()
|
|
|
|
|
|
func _tool_button(text: String, tip: String, on_press: Callable) -> Button:
|
|
var b := make_button(text, "plain")
|
|
b.tooltip_text = tip
|
|
b.custom_minimum_size.x = 36
|
|
b.add_theme_font_size_override("font_size", 14)
|
|
b.pressed.connect(on_press)
|
|
return b
|
|
|
|
|
|
func _color_menu(anchor: Control) -> void:
|
|
var pm := PopupMenu.new()
|
|
style_popup(pm)
|
|
for i in COLORS.size():
|
|
pm.add_item(COLORS[i][0], i)
|
|
pm.id_pressed.connect(func(id: int) -> void:
|
|
_wrap_selection("[color=%s]" % (COLORS[id][1] as Color).to_html(false), "[/color]")
|
|
)
|
|
pm.popup_hide.connect(pm.queue_free)
|
|
add_child(pm)
|
|
pm.popup(Rect2i(Vector2i(anchor.get_screen_position()) + Vector2i(0, int(anchor.size.y)), Vector2i(0, 0)))
|
|
|
|
|
|
## Wraps the selected text in the tags, or inserts an empty pair at the caret.
|
|
func _wrap_selection(open: String, close_tag: String) -> void:
|
|
var r := wrap_text(_details.text, _selection_range(), open, close_tag)
|
|
_details.text = r["text"]
|
|
_set_caret_at_offset(int(r["caret"]))
|
|
_details.grab_focus()
|
|
_refresh()
|
|
|
|
|
|
func _selection_range() -> Vector2i:
|
|
if _details.has_selection():
|
|
return Vector2i(_offset_of(_details.get_selection_from_line(), _details.get_selection_from_column()),
|
|
_offset_of(_details.get_selection_to_line(), _details.get_selection_to_column()))
|
|
var c := _offset_of(_details.get_caret_line(), _details.get_caret_column())
|
|
return Vector2i(c, c)
|
|
|
|
|
|
func _offset_of(line: int, col: int) -> int:
|
|
var off := 0
|
|
for i in line:
|
|
off += _details.get_line(i).length() + 1
|
|
return off + col
|
|
|
|
|
|
func _set_caret_at_offset(off: int) -> void:
|
|
var line := 0
|
|
while line < _details.get_line_count() - 1 and off > _details.get_line(line).length():
|
|
off -= _details.get_line(line).length() + 1
|
|
line += 1
|
|
_details.set_caret_line(line)
|
|
_details.set_caret_column(clampi(off, 0, _details.get_line(line).length()))
|
|
|
|
|
|
func settings() -> Dictionary:
|
|
var s := {
|
|
"name": _name.text, "details": _details.text, "tags": _tags.text,
|
|
"ranged": _ranged, "dice": _dice.text.strip_edges(),
|
|
"card_mode": _card_mode, "deck_empty": _deck_empty,
|
|
}
|
|
match table.kind:
|
|
RollTable.KIND_CHOICE:
|
|
s["choice"] = _choice
|
|
s["prompt"] = _prompt.text
|
|
s["save_as"] = _save_as.text.strip_edges()
|
|
s["min"] = _min.text.strip_edges()
|
|
s["max"] = _max.text.strip_edges()
|
|
s["options_mode"] = _options_mode
|
|
s["options_from"] = _opt_from.text.strip_edges()
|
|
s["options_where"] = _opt_where.text.strip_edges()
|
|
var si := {}
|
|
for eid: String in _show_if:
|
|
si[eid] = (_show_if[eid] as LineEdit).text.strip_edges()
|
|
s["show_if"] = si
|
|
RollTable.KIND_LOOP:
|
|
s["loop_mode"] = _loop_mode
|
|
s["loop_expr"] = _loop_expr.text.strip_edges()
|
|
RollTable.KIND_VARIABLE:
|
|
s["var_name"] = _var_name.text.strip_edges().trim_prefix("@")
|
|
s["var_type"] = _var_type
|
|
s["initial"] = _initial.text.strip_edges()
|
|
RollTable.KIND_SHEET:
|
|
s["template"] = _template.text
|
|
RollTable.KIND_ROUTER:
|
|
var cases: Array = []
|
|
for le in _cases:
|
|
cases.append(le.text.strip_edges())
|
|
s["cases"] = cases
|
|
return s
|
|
|
|
|
|
# ---------- Kind-specific fields ----------
|
|
|
|
func _build_kind() -> void:
|
|
var box := VBoxContainer.new()
|
|
box.add_theme_constant_override("separation", 10)
|
|
match table.kind:
|
|
RollTable.KIND_CHOICE:
|
|
box.add_child(section("Question type"))
|
|
box.add_child(segmented(CHOICE_LABELS, RollTable.CHOICES.find(_choice), func(i: int) -> void:
|
|
_choice = RollTable.CHOICES[i]
|
|
_refresh()
|
|
))
|
|
_choice_note = note("")
|
|
box.add_child(_choice_note)
|
|
_prompt = LineEdit.new()
|
|
_prompt.text = table.prompt
|
|
_prompt.placeholder_text = "Which way out? You have {@gold} gold."
|
|
style_line_edit(_prompt)
|
|
_prompt.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
box.add_child(field("Question (BBCode, {@var} works)", _prompt))
|
|
_save_as = LineEdit.new()
|
|
_save_as.text = table.save_as
|
|
_save_as.placeholder_text = "@name to keep, or a name for this roll"
|
|
style_line_edit(_save_as)
|
|
_save_as.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
box.add_child(field("Save the answer as (optional)", _save_as))
|
|
var mm := HBoxContainer.new()
|
|
mm.add_theme_constant_override("separation", 12)
|
|
_min = LineEdit.new()
|
|
_min.text = table.min_expr
|
|
style_line_edit(_min)
|
|
_min.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
_max = LineEdit.new()
|
|
_max.text = table.max_expr
|
|
style_line_edit(_max)
|
|
_max.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
mm.add_child(field("Lowest", _min))
|
|
mm.add_child(field("Highest", _max))
|
|
for c in mm.get_children():
|
|
(c as Control).size_flags_horizontal = SIZE_EXPAND_FILL
|
|
_minmax_row = mm
|
|
box.add_child(mm)
|
|
_build_options(box)
|
|
RollTable.KIND_LOOP:
|
|
box.add_child(section("Repeat"))
|
|
box.add_child(segmented(LOOP_LABELS, RollTable.LOOPS.find(_loop_mode), func(i: int) -> void:
|
|
_loop_mode = RollTable.LOOPS[i]
|
|
_refresh()
|
|
))
|
|
_loop_expr = LineEdit.new()
|
|
_loop_expr.text = table.loop_expr
|
|
style_line_edit(_loop_expr)
|
|
_loop_expr.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
box.add_child(field("How many times / condition", _loop_expr))
|
|
_loop_note = note("")
|
|
box.add_child(_loop_note)
|
|
RollTable.KIND_VARIABLE:
|
|
_var_name = LineEdit.new()
|
|
_var_name.text = table.var_name
|
|
_var_name.placeholder_text = "hp"
|
|
style_line_edit(_var_name)
|
|
_var_name.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
box.add_child(field("Variable name (used as @name)", _var_name))
|
|
box.add_child(section("Type"))
|
|
box.add_child(segmented(["Number", "Text", "List"], RollTable.VAR_TYPES.find(_var_type), func(i: int) -> void:
|
|
_var_type = RollTable.VAR_TYPES[i]
|
|
_refresh()
|
|
))
|
|
_initial = LineEdit.new()
|
|
_initial.text = table.initial
|
|
_initial.placeholder_text = "10, 2d6, or a word"
|
|
style_line_edit(_initial)
|
|
_initial.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
box.add_child(field("Starting value", _initial))
|
|
box.add_child(note("reset @name, and Reset in the Variables tab, put it back to this."))
|
|
RollTable.KIND_SHEET:
|
|
_template = TextEdit.new()
|
|
_template.text = table.entries[0].text if not table.entries.is_empty() else ""
|
|
_template.placeholder_text = "[b]{@name}[/b]\nHP {@hp} · Gold {@gold}\nSkills: {@skill_*}"
|
|
_template.custom_minimum_size.y = 120
|
|
_template.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
|
|
style_text_edit(_template)
|
|
_template.text_changed.connect(_refresh)
|
|
box.add_child(field("Template (BBCode with {@var}, {@prefix_*} and {= expr})", _template))
|
|
_template_preview = RichTextLabel.new()
|
|
_template_preview.bbcode_enabled = true
|
|
_template_preview.fit_content = true
|
|
_template_preview.scroll_active = false
|
|
var pbox := PanelContainer.new()
|
|
pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7]))
|
|
pbox.add_child(_template_preview)
|
|
box.add_child(pbox)
|
|
RollTable.KIND_ROUTER:
|
|
box.add_child(section("Cases (if / else if / otherwise)"))
|
|
box.add_child(note("Checked top to bottom when the chain arrives; the first true case is chosen, and its effects, text and pipes run like a rolled result. An empty condition is Otherwise: it always matches, so keep it last. Add, remove and reorder cases on the card."))
|
|
for i in table.entries.size():
|
|
var e := table.entries[i]
|
|
var le := LineEdit.new()
|
|
le.text = e.when
|
|
le.placeholder_text = "Otherwise (always)"
|
|
style_line_edit(le)
|
|
le.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
_cases.append(le)
|
|
var label := Formatter.strip_tags(e.text).strip_edges()
|
|
box.add_child(field("Case %d%s" % [i + 1, (" · " + label) if label != "" else ""], le))
|
|
if table.entries.is_empty():
|
|
box.add_child(note("This router has no cases yet: add some on the card."))
|
|
_case_note = note("", Style.WARN_INK)
|
|
box.add_child(_case_note)
|
|
_:
|
|
box.free() # roll tables have no kind fields
|
|
return
|
|
_kind_problem = note("", Style.DANGER_INK)
|
|
box.add_child(_kind_problem)
|
|
body.add_child(box)
|
|
|
|
|
|
## Pick choices: where the options come from, and a Show only if field per
|
|
## option.
|
|
func _build_options(box: VBoxContainer) -> void:
|
|
var mb := VBoxContainer.new()
|
|
mb.add_theme_constant_override("separation", 6)
|
|
mb.add_child(section("Options"))
|
|
mb.add_child(segmented(OPTION_LABELS, 1 if _options_mode == "vars" else 0, func(i: int) -> void:
|
|
_options_mode = "vars" if i == 1 else "fixed"
|
|
_refresh()
|
|
))
|
|
box.add_child(mb)
|
|
_opt_mode_box = mb
|
|
var ob := VBoxContainer.new()
|
|
ob.add_theme_constant_override("separation", 8)
|
|
_opt_from = LineEdit.new()
|
|
_opt_from.text = table.options_from
|
|
_opt_from.placeholder_text = "@skill_* or @contacts"
|
|
style_line_edit(_opt_from)
|
|
_opt_from.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
ob.add_child(field("Options from (@prefix_* or a @list)", _opt_from))
|
|
_opt_where = LineEdit.new()
|
|
_opt_where.text = table.options_where
|
|
_opt_where.placeholder_text = "option_value >= 1 (optional)"
|
|
style_line_edit(_opt_where)
|
|
_opt_where.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
ob.add_child(field("Only where (optional)", _opt_where))
|
|
_opt_note = note("")
|
|
ob.add_child(_opt_note)
|
|
box.add_child(ob)
|
|
_options_box = ob
|
|
var sb := VBoxContainer.new()
|
|
sb.add_theme_constant_override("separation", 6)
|
|
sb.add_child(section("Show only if"))
|
|
sb.add_child(note("Checked when the card is reached. An option whose condition is false isn't offered, not even to Random. Empty means always."))
|
|
for i in table.entries.size():
|
|
var e := table.entries[i]
|
|
var le := LineEdit.new()
|
|
le.text = e.show_if
|
|
le.placeholder_text = "always"
|
|
style_line_edit(le)
|
|
le.text_changed.connect(func(_t: String) -> void: _refresh())
|
|
_show_if[e.id] = le
|
|
var label := Formatter.strip_tags(e.text).strip_edges()
|
|
var cap := "Chosen (every option from variables)" if (i == 0 and table.is_dynamic()) else "Option %d%s" % [i + (0 if table.is_dynamic() else 1), (" · " + label) if label != "" else ""]
|
|
sb.add_child(field(cap, le))
|
|
box.add_child(sb)
|
|
_show_if_box = sb
|
|
|
|
|
|
func _refresh_kind() -> void:
|
|
var s := settings()
|
|
var problems := kind_problems(table, s)
|
|
if _kind_problem:
|
|
_kind_problem.text = "\n".join(problems)
|
|
_kind_problem.visible = not problems.is_empty()
|
|
match table.kind:
|
|
RollTable.KIND_CHOICE:
|
|
_minmax_row.visible = _choice == "number"
|
|
var msg := ""
|
|
if _choice != table.choice and table.choice == "pick":
|
|
msg = "Only the first option is kept, as the Answer row (its effects and pipes stay)."
|
|
elif _choice != table.choice and _choice == "pick":
|
|
msg = "The Answer row becomes the first option; two more are added."
|
|
elif _choice == "pick" and _options_mode == "vars" and table.is_dynamic():
|
|
msg = "The player picks one of the options from variables or a fixed extra, or Random."
|
|
elif _choice == "pick" and _options_mode == "fixed" and table.is_dynamic():
|
|
msg = "Back to a fixed list: the Chosen row becomes an ordinary option (or goes, if it does nothing)."
|
|
elif _choice == "pick":
|
|
msg = "The player picks one of the card's options, or Random."
|
|
else:
|
|
msg = "The answer goes in {answer}; the Answer row's effects and pipes run after it."
|
|
_choice_note.text = msg
|
|
_mark(_save_as, s["save_as"] == "" or _re(SAVE_PATTERN).search(TemplateKit.probe(s["save_as"])) != null)
|
|
var pick := _choice == "pick"
|
|
_opt_mode_box.visible = pick
|
|
_options_box.visible = pick and _options_mode == "vars"
|
|
_show_if_box.visible = pick and not _show_if.is_empty()
|
|
if pick and _options_mode == "vars":
|
|
_mark(_opt_from, options_from_error(s["options_from"]) == "")
|
|
_mark(_opt_where, when_error(s["options_where"]) == "")
|
|
var desc := RollTable.new()
|
|
desc.options_from = s["options_from"]
|
|
desc.options_where = s["options_where"]
|
|
var how := "One option for %s, labelled with its name and value, after any fixed options. The Chosen row runs for whichever is picked; option, option_label and option_value hold it, e.g. @[option] += 1." % desc.options_description() \
|
|
if options_from_error(s["options_from"]) == "" else "Write @skill_* for each set variable with that prefix, or @contacts for each item of a list."
|
|
if not table.is_dynamic():
|
|
how += " A Chosen row is added first; the options already on the card stay as fixed extras."
|
|
_opt_note.text = how
|
|
elif pick and table.is_dynamic():
|
|
_opt_note.text = ""
|
|
for eid: String in _show_if:
|
|
_mark(_show_if[eid] as LineEdit, when_error((_show_if[eid] as LineEdit).text) == "")
|
|
_mark(_min, Expr.check(TemplateKit.probe(s["min"])) == "" and s["min"] != "")
|
|
_mark(_max, Expr.check(TemplateKit.probe(s["max"])) == "" and s["max"] != "")
|
|
RollTable.KIND_LOOP:
|
|
_loop_note.text = LOOP_NOTES.get(_loop_mode, "")
|
|
_mark(_loop_expr, s["loop_expr"] != "" and Expr.check(TemplateKit.probe(s["loop_expr"])) == "")
|
|
RollTable.KIND_VARIABLE:
|
|
_mark(_var_name, _re(VAR_PATTERN).search(TemplateKit.probe(s["var_name"])) != null)
|
|
_mark(_initial, _initial_error(s["initial"], _var_type) == "")
|
|
RollTable.KIND_SHEET:
|
|
var ctx := Roller.live_context(table_board(), _live_vars())
|
|
_template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \
|
|
else "[color=#69726b]Preview appears here.[/color]"
|
|
RollTable.KIND_ROUTER:
|
|
var cases: Array = s["cases"]
|
|
for i in _cases.size():
|
|
_mark(_cases[i], when_error(str(cases[i])) == "")
|
|
var hint := router_hint(cases)
|
|
_case_note.text = hint
|
|
_case_note.visible = hint != ""
|
|
# The ranged/card-mode sections only apply to roll tables and pick choices.
|
|
var rolls := table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and _choice == "pick")
|
|
_type_box.visible = rolls
|
|
_card_box.visible = rolls
|
|
|
|
|
|
func _mark(le: LineEdit, ok: bool) -> void:
|
|
le.add_theme_color_override("font_color", Style.INK if ok else Style.DANGER_INK)
|
|
|
|
|
|
## The board and variables for the sheet preview, when the dialog sits in Main.
|
|
func table_board() -> TowerBoard:
|
|
var m := get_parent() as Main
|
|
return m.data if m else TowerBoard.new()
|
|
|
|
|
|
func _live_vars() -> Dictionary:
|
|
var m := get_parent() as Main
|
|
return m.persistent_vars if m else {}
|
|
|
|
|
|
func _refresh() -> void:
|
|
if _preview == null:
|
|
return
|
|
var det := _details.text
|
|
_preview.text = Formatter.close_open_tags(det) if det.strip_edges() != "" else "[color=#69726b]Preview appears here.[/color]"
|
|
_dice_row.visible = _ranged
|
|
_deck_block.visible = _card_mode
|
|
var s := settings()
|
|
var dice_ok := not _ranged or dice_ok_text(s["dice"])
|
|
_dice.add_theme_color_override("font_color", Style.INK if dice_ok else Style.WARN_INK)
|
|
var msgs := PackedStringArray()
|
|
if _ranged and not table.is_ranged():
|
|
msgs.append("Each entry gets a range sized by its weight; adjust them on the card.")
|
|
if _ranged and extra_pipe_count(table) > 0:
|
|
msgs.append("A range takes one pipe, so extra pipes on an entry will be dropped.")
|
|
if not _ranged and table.is_ranged():
|
|
msgs.append("Ranges are removed; entries become plain picks.")
|
|
_type_note.text = " ".join(msgs)
|
|
_type_note.visible = not msgs.is_empty()
|
|
var problem := ""
|
|
if not dice_ok:
|
|
problem = "“%s” is not a valid dice expression." % s["dice"]
|
|
elif _type_box == null or _type_box.visible:
|
|
var clone := RollTable.from_dict(table.to_dict())
|
|
apply_settings(clone, s)
|
|
problem = clone.range_problems()
|
|
_problem.text = problem
|
|
_problem.visible = problem != ""
|
|
if _type_box != null:
|
|
_refresh_kind()
|
|
if is_inside_tree():
|
|
_fit()
|
|
|
|
|
|
func _on_apply() -> void:
|
|
var s := settings()
|
|
var r := apply_settings(table, s)
|
|
if not r["ok"]:
|
|
if _kind_problem and not kind_problems(table, s).is_empty():
|
|
_kind_problem.text = r["error"]
|
|
_kind_problem.visible = true
|
|
else:
|
|
_problem.text = r["error"]
|
|
_problem.visible = true
|
|
return
|
|
applied.emit(r)
|
|
close()
|
|
|
|
|
|
## Problems with the kind-specific settings (empty when fine).
|
|
static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
|
|
var out := PackedStringArray()
|
|
match t.kind:
|
|
RollTable.KIND_CHOICE:
|
|
# Template placeholders ({$name}) check as a plain name (TemplateKit.probe).
|
|
var save := TemplateKit.probe(str(s.get("save_as", t.save_as)).strip_edges())
|
|
if save != "" and _re(SAVE_PATTERN).search(save) == null:
|
|
out.append("Save as: use a name like career, or @career to keep it.")
|
|
if str(s.get("choice", t.choice)) == "pick":
|
|
if str(s.get("options_mode", "vars" if t.options_from != "" else "fixed")) == "vars":
|
|
var ferr := options_from_error(str(s.get("options_from", t.options_from)))
|
|
if ferr != "":
|
|
out.append("Options from: " + ferr)
|
|
var werr := when_error(str(s.get("options_where", t.options_where)))
|
|
if werr != "":
|
|
out.append("Only where: " + werr)
|
|
var si: Dictionary = s.get("show_if", {})
|
|
for eid: String in si:
|
|
var serr := when_error(str(si[eid]))
|
|
if serr != "":
|
|
var e := t.find_entry(eid)
|
|
var at := t.entries.find(e) if e != null else -1
|
|
out.append("Show only if (%s): %s" % [("option %d" % (at + 1)) if at >= 0 else eid, serr])
|
|
if str(s.get("choice", t.choice)) == "number":
|
|
for k in [["min", "Lowest"], ["max", "Highest"]]:
|
|
var src := TemplateKit.probe(str(s.get(k[0], "")).strip_edges())
|
|
var err := Expr.check(src) if src != "" else "it's empty"
|
|
if err != "":
|
|
out.append("%s: %s" % [k[1], err])
|
|
RollTable.KIND_LOOP:
|
|
var src := TemplateKit.probe(str(s.get("loop_expr", t.loop_expr)).strip_edges())
|
|
if src == "":
|
|
out.append("The loop needs a count or a condition.")
|
|
elif Expr.check(src) != "":
|
|
out.append("Loop rule: " + Expr.check(src))
|
|
RollTable.KIND_ROUTER:
|
|
var cases: Array = s.get("cases", [])
|
|
for i in cases.size():
|
|
var err := when_error(str(cases[i]))
|
|
if err != "":
|
|
out.append("Case %d: %s" % [i + 1, err])
|
|
RollTable.KIND_VARIABLE:
|
|
var n := TemplateKit.probe(str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@"))
|
|
if _re(VAR_PATTERN).search(n) == null:
|
|
out.append("Variable name: lowercase letters, digits and _ only.")
|
|
var err := _initial_error(str(s.get("initial", t.initial)), str(s.get("var_type", t.var_type)))
|
|
if err != "":
|
|
out.append("Starting value: " + err)
|
|
return out
|
|
|
|
|
|
## "" when a router case condition is usable (empty is Otherwise), else why not.
|
|
static func when_error(src: String) -> String:
|
|
src = TemplateKit.probe(src.strip_edges())
|
|
return Expr.check(src) if src != "" else ""
|
|
|
|
|
|
## "" when an options_from pattern is usable, else why not ("" is refused).
|
|
static func options_from_error(src: String) -> String:
|
|
src = TemplateKit.probe(src.strip_edges())
|
|
if src == "":
|
|
return "write @prefix_* or @list"
|
|
return str(RollTable.parse_options_from(src)["error"])
|
|
|
|
|
|
## A hint about the order of router cases (an Otherwise that isn't last), or "".
|
|
static func router_hint(cases: Array) -> String:
|
|
for i in cases.size():
|
|
if str(cases[i]).strip_edges() == "" and i < cases.size() - 1:
|
|
return "Case %d is Otherwise, so the cases after it can never be chosen. Move it to the end." % (i + 1)
|
|
return ""
|
|
|
|
|
|
static func _initial_error(src: String, type: String) -> String:
|
|
src = TemplateKit.probe(src.strip_edges())
|
|
if src == "":
|
|
return ""
|
|
if type != "number" and RollTable._looks_literal(src):
|
|
return ""
|
|
return Expr.check(src)
|
|
|
|
|
|
static func _re(pattern: String) -> RegEx:
|
|
return RegEx.create_from_string(pattern)
|
|
|
|
|
|
## Dice text for a ranged table: plain dice (2d6) or an expression that uses a
|
|
## variable, dice or a function ("2d6 + dm(@end)", "@terms"). A lone word
|
|
## such as "banana" is not accepted.
|
|
static func dice_ok_text(text: String) -> bool:
|
|
var s := TemplateKit.probe(text.strip_edges())
|
|
if Dice.is_valid_text(s):
|
|
return true
|
|
if s == "" or Expr.check(s) != "":
|
|
return false
|
|
return _re("^[A-Za-z_][A-Za-z0-9_]*$").search(s) == null
|
|
|
|
|
|
## Applies the kind-specific settings. Turning a pick choice into a number or
|
|
## text one keeps only its first entry (as the Answer); the other way, the
|
|
## Answer becomes the first of three options.
|
|
static func _apply_kind(t: RollTable, s: Dictionary) -> void:
|
|
match t.kind:
|
|
RollTable.KIND_CHOICE:
|
|
var c := str(s.get("choice", t.choice))
|
|
if RollTable.CHOICES.has(c) and c != t.choice:
|
|
if c == "pick":
|
|
if not t.entries.is_empty():
|
|
t.entries[0].text = "Option 1"
|
|
for n in range(t.entries.size() + 1, 4):
|
|
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option %d" % n))
|
|
else:
|
|
while t.entries.size() > 1:
|
|
t.entries.remove_at(t.entries.size() - 1)
|
|
if t.entries.is_empty():
|
|
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Answer"))
|
|
t.entries[0].text = "Answer"
|
|
t.entries[0].has_range = false
|
|
t.card_mode = false
|
|
t.choice = c
|
|
t.prompt = str(s.get("prompt", t.prompt))
|
|
t.save_as = str(s.get("save_as", t.save_as)).strip_edges()
|
|
var si: Dictionary = s.get("show_if", {})
|
|
for eid: String in si:
|
|
var se := t.find_entry(eid)
|
|
if se != null:
|
|
se.show_if = str(si[eid]).strip_edges()
|
|
if t.choice != "pick":
|
|
t.options_from = ""
|
|
t.options_where = ""
|
|
elif s.has("options_mode"):
|
|
_apply_options(t, str(s["options_mode"]) == "vars", str(s.get("options_from", "")), str(s.get("options_where", "")))
|
|
if t.choice == "number":
|
|
t.min_expr = str(s.get("min", t.min_expr)).strip_edges()
|
|
t.max_expr = str(s.get("max", t.max_expr)).strip_edges()
|
|
RollTable.KIND_LOOP:
|
|
var m := str(s.get("loop_mode", t.loop_mode))
|
|
if RollTable.LOOPS.has(m):
|
|
t.loop_mode = m
|
|
t.loop_expr = str(s.get("loop_expr", t.loop_expr)).strip_edges()
|
|
RollTable.KIND_VARIABLE:
|
|
t.var_name = str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@")
|
|
var vt := str(s.get("var_type", t.var_type))
|
|
if RollTable.VAR_TYPES.has(vt):
|
|
t.var_type = vt
|
|
t.initial = str(s.get("initial", t.initial)).strip_edges()
|
|
RollTable.KIND_ROUTER:
|
|
var cases: Array = s.get("cases", [])
|
|
for i in mini(cases.size(), t.entries.size()):
|
|
t.entries[i].when = str(cases[i]).strip_edges()
|
|
RollTable.KIND_SHEET:
|
|
if s.has("template"):
|
|
if t.entries.is_empty():
|
|
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), ""))
|
|
t.entries[0].text = str(s["template"])
|
|
|
|
|
|
## Switches a pick card between a fixed list and options from variables.
|
|
## Turning variables on adds a Chosen entry first (untouched default
|
|
## "Option N" entries go; anything else stays as a fixed extra). Turning them
|
|
## off makes the Chosen entry an ordinary option, or drops it if it does
|
|
## nothing (no effects, pipes, details or text of its own).
|
|
static func _apply_options(t: RollTable, on: bool, from: String, where: String) -> void:
|
|
if on:
|
|
if not t.is_dynamic():
|
|
var keep: Array[TableEntry] = []
|
|
for e in t.entries:
|
|
var blank := e.effects.strip_edges() == "" and e.pipes.is_empty() and e.details.strip_edges() == "" \
|
|
and e.show_if.strip_edges() == "" and RegEx.create_from_string("^Option \\d+$").search(e.text.strip_edges()) != null
|
|
if not blank:
|
|
keep.append(e)
|
|
t.entries = keep
|
|
t.entries.insert(0, TableEntry.new(TowerBoard.new_id("e"), Roller.CHOSEN))
|
|
t.options_from = from.strip_edges()
|
|
t.options_where = where.strip_edges()
|
|
return
|
|
if t.is_dynamic() and not t.entries.is_empty():
|
|
var c := t.entries[0]
|
|
var txt := Formatter.strip_tags(c.text).strip_edges()
|
|
if c.effects.strip_edges() == "" and c.pipes.is_empty() and c.details.strip_edges() == "" and (txt == "" or txt == Roller.CHOSEN):
|
|
t.entries.remove_at(0)
|
|
t.options_from = ""
|
|
t.options_where = ""
|
|
if t.entries.is_empty():
|
|
t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Option 1"))
|
|
|
|
|
|
# ---------- Pure editing logic ----------
|
|
|
|
## Wraps text[sel.x:sel.y] in open/close_tag. With an empty range, inserts the
|
|
## pair. Returns {text, caret}: the caret sits inside an inserted pair, or
|
|
## after the closing tag of a wrapped selection.
|
|
static func wrap_text(text: String, sel: Vector2i, open: String, close_tag: String) -> Dictionary:
|
|
var a := clampi(mini(sel.x, sel.y), 0, text.length())
|
|
var b := clampi(maxi(sel.x, sel.y), 0, text.length())
|
|
var out := text.substr(0, a) + open + text.substr(a, b - a) + close_tag + text.substr(b)
|
|
var caret := a + open.length() if a == b else b + open.length() + close_tag.length()
|
|
return {"text": out, "caret": caret}
|
|
|
|
|
|
## "a, b ,, a" -> ["a", "b"].
|
|
static func parse_tags(text: String) -> Array[String]:
|
|
var out: Array[String] = []
|
|
for part in text.split(","):
|
|
var t := part.strip_edges()
|
|
if t != "" and not out.has(t):
|
|
out.append(t)
|
|
return out
|
|
|
|
|
|
## Number of pipes beyond the first, summed over entries (lost when going ranged).
|
|
static func extra_pipe_count(t: RollTable) -> int:
|
|
var n := 0
|
|
for e in t.entries:
|
|
n += maxi(0, e.pipes.size() - 1)
|
|
return n
|
|
|
|
|
|
## Applies a settings Dictionary (name, details, tags, ranged, dice, card_mode,
|
|
## deck_empty) to the table. Returns {ok, error, deck_reset}: on a bad dice
|
|
## expression nothing is changed. deck_reset says the card deck no longer fits
|
|
## (type, dice or card mode changed), so a saved deck should be cleared.
|
|
static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary:
|
|
var problems := kind_problems(t, s)
|
|
if not problems.is_empty():
|
|
return {"ok": false, "error": "\n".join(problems), "deck_reset": false}
|
|
var ranged: bool = s.get("ranged", false)
|
|
# Only roll tables and pick choices can be ranged or dealt as cards.
|
|
var choice := str(s.get("choice", t.choice))
|
|
var rolls := t.kind == RollTable.KIND_ROLL or (t.kind == RollTable.KIND_CHOICE and choice == "pick")
|
|
if not rolls:
|
|
ranged = false
|
|
var dice := str(s.get("dice", t.dice)).strip_edges()
|
|
if ranged and not dice_ok_text(dice):
|
|
return {"ok": false, "error": "“%s” is not a valid dice expression." % dice, "deck_reset": false}
|
|
var was_ranged := t.is_ranged()
|
|
var old_dice := t.dice
|
|
var old_card := t.card_mode
|
|
var new_name := str(s.get("name", t.name)).strip_edges()
|
|
if new_name != "":
|
|
t.name = new_name
|
|
t.details = str(s.get("details", t.details))
|
|
t.tags = parse_tags(str(s.get("tags", "")))
|
|
t.card_mode = bool(s.get("card_mode", t.card_mode)) and rolls
|
|
t.deck_empty = "stop" if str(s.get("deck_empty", t.deck_empty)) == "stop" else "reshuffle"
|
|
if ranged:
|
|
t.dice = dice
|
|
if not was_ranged:
|
|
assign_ranges(t)
|
|
elif was_ranged:
|
|
drop_ranges(t)
|
|
_apply_kind(t, s)
|
|
var deck_reset := was_ranged != ranged or old_card != t.card_mode or (ranged and old_dice != t.dice)
|
|
return {"ok": true, "error": "", "deck_reset": deck_reset}
|
|
|
|
|
|
## Gives entries ranges on the table's dice, sized by weight (at least one
|
|
## value each while there is room). Entries of weight 0 get no range. Each
|
|
## entry keeps only its first pipe, since a range takes one pipe.
|
|
static func assign_ranges(t: RollTable) -> void:
|
|
var d := t.dice_obj()
|
|
var lo := d.min_value()
|
|
var hi := d.max_value()
|
|
var live: Array[TableEntry] = []
|
|
var total := 0
|
|
for e in t.entries:
|
|
e.has_range = false
|
|
if e.weight > 0:
|
|
live.append(e)
|
|
total += e.weight
|
|
while e.pipes.size() > 1:
|
|
e.remove_pipe(e.pipes[e.pipes.size() - 1])
|
|
var span := hi - lo + 1
|
|
var cum := 0
|
|
var prev := lo - 1
|
|
for i in live.size():
|
|
var e := live[i]
|
|
if prev >= hi:
|
|
break
|
|
cum += e.weight
|
|
var end := lo - 1 + roundi(float(span) * cum / total)
|
|
end = mini(end, hi - (live.size() - 1 - i))
|
|
end = clampi(maxi(end, prev + 1), prev + 1, hi)
|
|
if i == live.size() - 1:
|
|
end = hi
|
|
e.has_range = true
|
|
e.range_lo = prev + 1
|
|
e.range_hi = end
|
|
prev = end
|
|
|
|
|
|
static func drop_ranges(t: RollTable) -> void:
|
|
for e in t.entries:
|
|
e.has_range = false
|
|
e.range_lo = 1
|
|
e.range_hi = 1
|