TableTower/ui/choice_dialog.gd
RobinFiredrake 82d67eb64f Size audit: split ChoiceDialog and TableCard into helpers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 19:56:20 -06:00

356 lines
11 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.
##
## Options from variables (docs/LOGIC.md §2a) come after the fixed ones, with
## their value as a badge on the right; their preview is the Chosen entry's.
##
## Previews read rules in plain words (effects "Luck −1", pipe conditions
## "only if Luck is 2 or more", option sources) unless Main's rules view is
## Text (RulesView.plain); `plain` can also be set directly.
##
## 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"
## 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 = {}
## Rules in plain words in the previews (from Main when it has a rules view).
var plain := true
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: ChoicePreview
var chrome: ChoiceChrome
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)
preview = ChoicePreview.new(self)
chrome = ChoiceChrome.new(self)
_build()
chrome.build()
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 := ChoiceOptionRow.build(self, 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 spread, 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)"
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()
var m := get_parent() as Main
if board == null and m:
board = m.data
vars = m.persistent_vars
if m:
plain = RulesView.plain(m)
RulesView.watch(m, _on_rules_view_changed)
preview.refresh()
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()
func _on_rules_view_changed(_v: Variant = null) -> void:
var m := get_parent() as Main
if m:
plain = RulesView.plain(m)
preview.shown_for = -2
preview.refresh()
## 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()
preview.hide()
mouse_filter = Control.MOUSE_FILTER_IGNORE
pill.show()
chrome.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()
preview.refresh()
## 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()
chrome.place_pill()
_toast_timer.start()
func _process(_delta: float) -> void:
if minimized:
chrome.place_pill()
elif preview_panel.visible:
preview.place()
# ---------- Preview ----------
## The preview content for option `k` (see ChoicePreview), or null.
func preview_for_option(k: int) -> Control:
return preview.preview_for_option(k)