TableTower/ui/choice_dialog.gd
RobinFiredrake 14a0b6e6a4 Keep long sheets from widening the tray; show sheets filled in in previews
The tray's sheet headline now wraps at a fixed width and scrolls past
220 px, so a long character sheet can't stretch the window (which also
threw off Fit on big boards). Option previews in the choice pop-up show
a sheet card rendered with current values instead of its raw template
and a meaningless 100%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 17:11:19 -06:00

630 lines
20 KiB
GDScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class_name ChoiceDialog
extends ModalCard
## The pop-up a choice card opens mid-roll (docs/LOGIC.md §2, §8): the card's
## question and either its options (pick), a number field (number) or a text
## field (text), with Cancel.
##
## Keys: 1–9 pick an option, R picks Random, Enter confirms, Esc cancels,
## M or Tab (Ctrl+M inside a text field) minimizes or restores. Arrow keys
## move between options.
##
## Minimize hides the dialog and its dim so the board can be looked at and
## used; a pill at the bottom centre ("Question waiting") brings it back
## exactly as it was. While it waits, Main refuses to start another roll or
## switch to Build (see nudge()).
##
## Hovering or focusing an option shows a preview panel beside the card: the
## option's details and effects, and a TablePreview for every table it pipes
## to or mentions. Number and text questions preview where the Answer leads.
##
## The answer arrives through `reply.done`, a signal on a separate object so
## the waiting roll never hangs: closing or freeing the dialog in any way
## (Esc, the window closing, a new roll replacing this one) answers null,
## which is Cancel.
## Holds the answer signal. It outlives the dialog, so an awaiting roll
## resumes even when the dialog is freed.
class Reply extends RefCounted:
signal done(value: Variant)
var finished := false
func finish(value: Variant) -> void:
if finished:
return
finished = true
done.emit(value)
var request: Dictionary
var reply := Reply.new()
var kind := "pick"
const PREVIEW_WIDTH := 350.0
## The board the question belongs to, for previews. Found from the parent Main
## when not set; without one the dialog simply shows no preview.
var board: TowerBoard
## Board variables, so previews can show sheets filled in.
var vars: Dictionary = {}
var minimized := false
var preview_panel: PanelContainer
var pill: PanelContainer
var toast_panel: PanelContainer
var _center: Control
var _dim: ColorRect
var _preview_box: VBoxContainer
var _preview_for := -2
var _hover := -1
var _prev_focus: Control
var _toast_timer: Timer
var _spin: SpinBox
var _text: LineEdit
var _options: Array[Control] = []
var _range_note: Label
var _typed := false
func _init(p_request: Dictionary = {}) -> void:
request = p_request
kind = str(request.get("kind", "pick"))
var title := Formatter.strip_tags(str(request.get("title", ""))).strip_edges()
super._init(title if title != "" else "A question", 500.0)
# A stray click on the board behind shouldn't throw the answer away.
close_on_backdrop = false
# A lighter dim, so the steps that led here stay readable behind the card.
_dim = get_child(0) as ColorRect
_center = get_child(1) as Control
if _dim:
_dim.color = Color(0, 0, 0, 0.32)
_build()
_build_chrome()
func _build() -> void:
var prompt := str(request.get("prompt", "")).strip_edges()
if prompt != "":
var p := RichText.label(RichText.decorate(prompt), 18, Style.INK, false)
p.size_flags_horizontal = SIZE_EXPAND_FILL
body.add_child(p)
match kind:
"number":
_build_number()
"text":
_build_text()
_:
_build_pick()
func _build_pick() -> void:
var list := VBoxContainer.new()
list.add_theme_constant_override("separation", 6)
body.add_child(list)
var opts: Array = request.get("options", [])
for k in opts.size():
var o: Dictionary = opts[k]
var row := _option_row(k, o)
list.add_child(row)
_options.append(row)
var hint := note("Press 1–%d to choose, R for Random, M to look at the board, Esc to cancel." % mini(9, maxi(1, opts.size())))
hint.add_theme_font_size_override("font_size", 13)
body.add_child(hint)
add_button("Cancel", "plain", func() -> void: answer(null))
var r := add_button("Random", "primary", func() -> void: answer(-1))
r.tooltip_text = "Roll this card normally instead of choosing (R)"
## One option: number key, text and details as a subtitle; the whole row is a
## button.
func _option_row(k: int, o: Dictionary) -> Control:
var b := Button.new()
b.focus_mode = Control.FOCUS_ALL
b.size_flags_horizontal = SIZE_EXPAND_FILL
var m := [14, 8, 14, 9]
var n := Style.bordered(Style.box(Color.WHITE, 9, m), 1, Style.RULE)
var h := Style.bordered(Style.box(Style.LIT, 9, m), 1, Style.BRASS_DARK)
Style.skin_button(b, n, h, h, Style.INK)
b.add_theme_stylebox_override("focus", Style.focus_ring(9))
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 12)
row.mouse_filter = MOUSE_FILTER_IGNORE
row.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
row.offset_left = 14
row.offset_right = -14
row.offset_top = 8
row.offset_bottom = -9
var key := Style.make_label(str(k + 1) if k < 9 else "", Style.display(), 20, Style.COPPER)
key.custom_minimum_size = Vector2(16, 0)
key.size_flags_vertical = SIZE_SHRINK_CENTER
key.mouse_filter = MOUSE_FILTER_IGNORE
row.add_child(key)
var col := VBoxContainer.new()
col.add_theme_constant_override("separation", 1)
col.size_flags_horizontal = SIZE_EXPAND_FILL
col.mouse_filter = MOUSE_FILTER_IGNORE
row.add_child(col)
var text := RichText.label(RichText.decorate(str(o.get("text", ""))), 17, Style.INK, false, true, true)
text.mouse_filter = MOUSE_FILTER_IGNORE
col.add_child(text)
var det := Formatter.strip_tags(str(o.get("details", ""))).strip_edges()
if det != "":
var sub := Style.make_label(det, Style.body(), 13, Style.MUTED)
sub.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
sub.max_lines_visible = 2
sub.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
sub.mouse_filter = MOUSE_FILTER_IGNORE
col.add_child(sub)
b.tooltip_text = det
b.add_child(row)
# Buttons don't size to their children, so follow the row's height.
var fit := func() -> void: b.custom_minimum_size.y = row.get_combined_minimum_size().y + 17.0
row.minimum_size_changed.connect(fit)
fit.call_deferred()
var index := int(o.get("index", k))
b.pressed.connect(func() -> void: answer(index))
b.mouse_entered.connect(func() -> void: _set_hover(k))
b.mouse_exited.connect(func() -> void:
if _hover == k:
_set_hover(-1)
)
b.focus_entered.connect(_refresh_preview)
b.focus_exited.connect(_refresh_preview.call_deferred)
return b
func _build_number() -> void:
var lo := int(request.get("min", 0))
var hi := maxi(lo, int(request.get("max", 99)))
var def: Variant = request.get("default", lo)
_spin = SpinBox.new()
_spin.min_value = lo
_spin.max_value = hi
_spin.step = 1
_spin.rounded = true
_spin.value = clampi(int(def) if (def is int or def is float) else lo, lo, hi)
_spin.custom_minimum_size = Vector2(150, 46)
_spin.size_flags_horizontal = SIZE_SHRINK_BEGIN
var le := _spin.get_line_edit()
style_line_edit(le)
le.add_theme_font_override("font", Style.body_bold())
le.add_theme_font_size_override("font_size", 22)
le.add_theme_color_override("font_selected_color", Style.INK)
_spin.add_theme_color_override("up_icon_modulate", Style.MUTED)
_spin.add_theme_color_override("down_icon_modulate", Style.MUTED)
# Typed text is applied on confirm; the arrows (or code) set the value directly.
le.text_changed.connect(func(_t: String) -> void: _typed = true)
_spin.value_changed.connect(func(_v: float) -> void: _typed = false)
le.text_submitted.connect(func(_t: String) -> void: _confirm())
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 12)
row.add_child(_spin)
_range_note = note("A whole number from %d to %d." % [lo, hi])
_range_note.size_flags_vertical = SIZE_SHRINK_CENTER
row.add_child(_range_note)
body.add_child(row)
add_button("Cancel", "plain", func() -> void: answer(null))
add_button("OK", "primary", _confirm)
func _build_text() -> void:
_text = LineEdit.new()
_text.placeholder_text = "Type your answer"
_text.text = str(request.get("default", ""))
style_line_edit(_text)
_text.add_theme_font_size_override("font_size", 18)
_text.text_submitted.connect(func(_t: String) -> void: _confirm())
body.add_child(_text)
add_button("Cancel", "plain", func() -> void: answer(null))
add_button("OK", "primary", _confirm)
func _ready() -> void:
super._ready()
if board == null:
var m := get_parent() as Main
if m:
board = m.data
vars = m.persistent_vars
_refresh_preview()
if _spin:
_spin.get_line_edit().grab_focus()
_spin.get_line_edit().select_all()
elif _text:
_text.grab_focus()
elif not _options.is_empty():
_options[0].grab_focus()
# Screenshot flags: --choice-focus=<n> focuses option n, --choice-minimized.
for a in OS.get_cmdline_user_args():
if a.begins_with("--choice-focus="):
var n := a.get_slice("=", 1).to_int()
if n >= 0 and n < _options.size():
_options[n].grab_focus()
elif a == "--choice-minimized":
minimize.call_deferred()
## Enter on the number or text field, or OK.
func _confirm() -> void:
if _spin:
if _typed:
_spin.apply()
answer(int(_spin.value))
elif _text:
answer(_text.text)
## Gives the answer (null = Cancel) and closes. Only the first answer counts.
func answer(value: Variant) -> void:
reply.finish(value)
if is_inside_tree() and not is_queued_for_deletion():
super.close()
## Esc and every other way of closing answer Cancel.
func close() -> void:
answer(null)
func _input(event: InputEvent) -> void:
if not is_inside_tree():
return
var k := event as InputEventKey
if k and k.pressed and not k.echo and _is_minimize_key(k):
get_viewport().set_input_as_handled()
toggle_minimized()
return
if minimized:
return
if k and k.pressed and not k.echo and kind == "pick":
var code := k.keycode
if code >= KEY_1 and code <= KEY_9:
var i := code - KEY_1
if i < _options.size():
get_viewport().set_input_as_handled()
_options[i].emit_signal("pressed")
return
if code >= KEY_KP_1 and code <= KEY_KP_9:
var j := code - KEY_KP_1
if j < _options.size():
get_viewport().set_input_as_handled()
_options[j].emit_signal("pressed")
return
if code == KEY_R:
get_viewport().set_input_as_handled()
answer(-1)
return
super._input(event)
func _notification(what: int) -> void:
# Freed or taken off the screen without an answer: the roll gets Cancel.
if what == NOTIFICATION_EXIT_TREE or what == NOTIFICATION_PREDELETE:
reply.finish(null)
# ---------- Minimize ----------
func _is_minimize_key(k: InputEventKey) -> bool:
var code := k.keycode
if code != KEY_M and code != KEY_TAB:
return false
if k.alt_pressed or (code == KEY_TAB and (k.ctrl_pressed or k.meta_pressed)):
return false
if k.ctrl_pressed or k.meta_pressed:
return code == KEY_M
if k.shift_pressed and code == KEY_M:
return false
# Plain keys type into text fields, so they only count outside of them.
var f := get_viewport().gui_get_focus_owner()
return not (f is LineEdit or f is TextEdit)
func toggle_minimized() -> void:
if minimized:
restore()
else:
minimize()
## Hides the dialog (answers stay as typed) and shows the pill.
func minimize() -> void:
if minimized or not is_inside_tree():
return
minimized = true
var f := get_viewport().gui_get_focus_owner()
_prev_focus = f if f != null and card.is_ancestor_of(f) else null
if f != null:
f.release_focus()
_center.hide()
if _dim:
_dim.hide()
_hide_preview()
mouse_filter = Control.MOUSE_FILTER_IGNORE
pill.show()
_place_pill()
## Brings the dialog back exactly as it was.
func restore() -> void:
if not minimized:
return
minimized = false
pill.hide()
toast_panel.hide()
mouse_filter = Control.MOUSE_FILTER_STOP
_center.show()
if _dim:
_dim.show()
_fit.call_deferred()
if is_instance_valid(_prev_focus) and _prev_focus.is_visible_in_tree():
_prev_focus.grab_focus()
elif _spin:
_spin.get_line_edit().grab_focus()
elif _text:
_text.grab_focus()
elif not _options.is_empty():
_options[0].grab_focus()
_refresh_preview()
## Tells the player a question is waiting (they tried to start a roll or enter
## Build): a toast above the pill with a Show button. Does nothing when the
## dialog is already on screen.
func nudge(message: String = "Answer the waiting question first") -> void:
if not minimized:
return
(toast_panel.get_meta("label") as Label).text = message
toast_panel.show()
toast_panel.reset_size()
_place_pill()
_toast_timer.start()
func _build_chrome() -> void:
preview_panel = PanelContainer.new()
preview_panel.mouse_filter = Control.MOUSE_FILTER_IGNORE
preview_panel.clip_contents = true
var sb := Style.box(Style.CARD, 10, [14, 11, 14, 12])
sb.border_width_top = 3
sb.border_color = Style.COPPER
sb.shadow_color = Color(0, 0, 0, 0.4)
sb.shadow_size = 16
sb.shadow_offset = Vector2(0, 6)
preview_panel.add_theme_stylebox_override("panel", sb)
_preview_box = VBoxContainer.new()
_preview_box.add_theme_constant_override("separation", 8)
_preview_box.mouse_filter = Control.MOUSE_FILTER_IGNORE
preview_panel.add_child(_preview_box)
preview_panel.hide()
add_child(preview_panel)
var min_btn := add_button("Minimize", "plain", minimize)
min_btn.tooltip_text = "Hide this question to look at the board (M or Tab)"
footer.move_child(min_btn, 0)
var spacer := Control.new()
spacer.size_flags_horizontal = Control.SIZE_EXPAND_FILL
footer.add_child(spacer)
footer.move_child(spacer, 1)
pill = _bar_panel()
var row := pill.get_child(0) as HBoxContainer
var lbl := Style.make_label("Question waiting: " + title_label.text + " ·", Style.body_bold(), 15, Style.INK)
lbl.size_flags_vertical = Control.SIZE_SHRINK_CENTER
row.add_child(lbl)
var show_btn := make_button("Show", "primary")
show_btn.add_theme_font_size_override("font_size", 14)
show_btn.pressed.connect(restore)
show_btn.tooltip_text = "Bring the question back (M)"
row.add_child(show_btn)
var x := make_button("Cancel", "plain")
x.add_theme_font_size_override("font_size", 14)
x.tooltip_text = "Cancel the question and stop this roll"
x.pressed.connect(func() -> void: answer(null))
row.add_child(x)
pill.hide()
add_child(pill)
toast_panel = _bar_panel()
var trow := toast_panel.get_child(0) as HBoxContainer
var tl := Style.make_label("", Style.body(), 15, Style.INK)
trow.add_child(tl)
toast_panel.set_meta("label", tl)
var ts := make_button("Show", "primary")
ts.add_theme_font_size_override("font_size", 14)
ts.pressed.connect(restore)
trow.add_child(ts)
toast_panel.hide()
add_child(toast_panel)
_toast_timer = Timer.new()
_toast_timer.one_shot = true
_toast_timer.wait_time = 4.0
_toast_timer.timeout.connect(func() -> void: toast_panel.hide())
add_child(_toast_timer)
func _bar_panel() -> PanelContainer:
var p := PanelContainer.new()
var sb := Style.bordered(Style.box(Style.CARD, 12, [14, 7, 8, 7]), 1, Style.DASH)
sb.border_width_top = 3
sb.border_color = Style.COPPER
sb.shadow_color = Color(0, 0, 0, 0.4)
sb.shadow_size = 14
sb.shadow_offset = Vector2(0, 5)
p.add_theme_stylebox_override("panel", sb)
p.mouse_filter = Control.MOUSE_FILTER_STOP
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 10)
p.add_child(row)
return p
## Bottom centre, above the result tray; the toast sits just above it.
func _place_pill() -> void:
if not minimized:
return
pill.reset_size()
var bottom := size.y - 14.0
var m := get_parent() as Main
if m and m.tray and m.tray.is_inside_tree():
bottom = m.tray.get_global_rect().position.y - get_global_rect().position.y - 12.0
pill.position = Vector2(maxf(8.0, (size.x - pill.size.x) / 2.0), bottom - pill.size.y)
if toast_panel.visible:
toast_panel.reset_size()
toast_panel.position = Vector2(maxf(8.0, (size.x - toast_panel.size.x) / 2.0), pill.position.y - toast_panel.size.y - 8.0)
func _process(_delta: float) -> void:
if minimized:
_place_pill()
elif preview_panel.visible:
_place_preview()
# ---------- Preview ----------
func _set_hover(k: int) -> void:
_hover = k
_refresh_preview()
## Shows the preview for the hovered option, else the focused one, else (for
## number and text questions) where the Answer leads.
func _refresh_preview() -> void:
if minimized or preview_panel == null or not is_inside_tree():
return
var idx := -1
if kind == "pick":
idx = _hover
if idx < 0:
for k in _options.size():
if _options[k].has_focus():
idx = k
break
else:
idx = 0
if idx == _preview_for:
return
_preview_for = idx
for c in _preview_box.get_children():
_preview_box.remove_child(c)
c.queue_free()
var content := preview_for_option(idx) if idx >= 0 else null
if content == null:
preview_panel.hide()
return
_preview_box.add_child(content)
preview_panel.show()
_place_preview()
func _hide_preview() -> void:
_preview_for = -2
if preview_panel:
preview_panel.hide()
## The entry behind option `k` (a position in the request's options; for
## number and text questions, the single Answer entry), or null.
func _entry_for(k: int) -> TableEntry:
if board == null:
return null
var t := board.get_table(str(request.get("table_id", "")))
if t == null:
return null
var index := k
if kind == "pick":
var opts: Array = request.get("options", [])
if k < 0 or k >= opts.size():
return null
index = int((opts[k] as Dictionary).get("index", k))
return t.entries[index] if index >= 0 and index < t.entries.size() else null
## The preview content for option `k` as a Control, or null when there is
## nothing to say. It holds the option's details and effects, then a
## TablePreview for each table it pipes to (with its count) and each table
## its text mentions with [[Table]].
func preview_for_option(k: int) -> Control:
var e := _entry_for(k)
if e == null:
return null
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 8)
box.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.custom_minimum_size.x = PREVIEW_WIDTH - 28.0
var heading := section(("Option %d" % (k + 1)) if kind == "pick" else "After you answer")
heading.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.add_child(heading)
var any := false
var det := e.details.strip_edges()
if det != "":
any = true
var d := RichText.label(RichText.decorate(det), 14, Style.INK, false)
d.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.add_child(d)
var fx := Effects.split(e.effects)
if not fx.is_empty():
any = true
box.add_child(_rule())
box.add_child(section("Effects"))
for st in fx:
var l := Style.make_label(st, Style.body_bold(), 13, RichText.VAR_INK)
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
l.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.add_child(l)
var shown: Array[String] = []
for tid in e.pipes:
shown.append(tid)
any = true
box.add_child(_rule())
box.add_child(TablePreview.build(board, tid, {"count": e.count_text(tid), "vars": vars}))
var mentioned: Array[String] = []
for name in TextExpander.references(e.text, func(n: String) -> String: return Roller.resolve(board, n)):
var rid := Roller.resolve(board, name)
if rid != "" and not shown.has(rid) and not mentioned.has(rid):
mentioned.append(rid)
if not mentioned.is_empty():
any = true
box.add_child(_rule())
box.add_child(section("Mentioned in the text"))
for rid in mentioned:
box.add_child(TablePreview.build(board, rid, {"vars": vars}))
if not any:
box.free()
return null
return box
func _rule() -> Control:
var r := ColorRect.new()
r.color = Style.RULE
r.custom_minimum_size.y = 1
r.mouse_filter = Control.MOUSE_FILTER_IGNORE
return r
## Beside the card (right if there is room, else left), top-aligned with it
## and kept on screen. It never overlaps the card, so it never covers options.
func _place_preview() -> void:
if not preview_panel.visible:
return
var view := size
var cr := card.get_global_rect()
var gap := 18.0
var right := view.x - cr.end.x - gap - 10.0
var left := cr.position.x - gap - 10.0
var w := PREVIEW_WIDTH
var x: float
if right >= w or right >= left:
w = clampf(right, 180.0, PREVIEW_WIDTH)
x = cr.end.x + gap
else:
w = clampf(left, 180.0, PREVIEW_WIDTH)
x = cr.position.x - gap - w
preview_panel.custom_minimum_size.x = w
preview_panel.size = Vector2(w, 0)
var h := preview_panel.get_combined_minimum_size().y
var top := clampf(cr.position.y, 10.0, maxf(10.0, view.y - 10.0 - h))
h = minf(h, view.y - top - 10.0)
preview_panel.position = Vector2(x, top)
preview_panel.size = Vector2(w, h)