diff --git a/ui/board_view.gd b/ui/board_view.gd index 245f35f..828891f 100644 --- a/ui/board_view.gd +++ b/ui/board_view.gd @@ -106,7 +106,7 @@ func _gui_input(ev: InputEvent) -> void: if mb.button_index == MOUSE_BUTTON_LEFT and main.mode == Main.Mode.BUILD: var key := pipes.pipe_at(world_mouse(), 11.0) if key != "": - main.remove_pipe(key) + main.open_pipe_options(key, mb.global_position) accept_event() return _panning = true diff --git a/ui/details_popup.gd b/ui/details_popup.gd new file mode 100644 index 0000000..3b92fce --- /dev/null +++ b/ui/details_popup.gd @@ -0,0 +1,217 @@ +class_name DetailsPopup +extends PanelContainer +## The hover pop-up for table and entry details, result chips and the +## [[references]] / {variables} inside rendered text. +## +## It ignores the mouse, so it never blocks clicks, stays inside the window, +## and hides itself as soon as the control that opened it is no longer hovered. + +const WIDTH := 300.0 +const DELAY := 0.28 +const OFFSET := Vector2(14, 20) + +var main: Main +var _owner_ctrl: Control +var _title: Label +var _sub: Label +var _body: RichTextLabel +var _wait := 0.0 +var _pending := false + + +func setup(p_main: Main) -> void: + main = p_main + mouse_filter = MOUSE_FILTER_IGNORE + z_index = 100 + top_level = true + var sb := Style.box(Style.CARD, 9, [13, 10, 13, 11]) + sb.border_width_top = 3 + sb.border_color = Style.COPPER + sb.shadow_color = Color(0, 0, 0, 0.35) + sb.shadow_size = 14 + sb.shadow_offset = Vector2(0, 6) + add_theme_stylebox_override("panel", sb) + var v := VBoxContainer.new() + v.add_theme_constant_override("separation", 3) + v.mouse_filter = MOUSE_FILTER_IGNORE + add_child(v) + _title = Style.make_label("", Style.display(), 18, Style.INK) + _title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + _title.custom_minimum_size = Vector2(WIDTH, 0) + _title.mouse_filter = MOUSE_FILTER_IGNORE + v.add_child(_title) + _sub = Style.make_label("", Style.body(), 12, Style.MUTED) + _sub.mouse_filter = MOUSE_FILTER_IGNORE + v.add_child(_sub) + _body = RichText.label("", 14, Style.INK, false) + _body.custom_minimum_size = Vector2(WIDTH, 0) + _body.mouse_filter = MOUSE_FILTER_IGNORE + v.add_child(_body) + hide() + + +## Shows the pop-up for `owner` after a short delay. Empty parts are hidden. +func show_for(owner: Control, title: String, body: String, sub: String = "") -> void: + if owner == null: + return + if not owner.has_meta("_details_hooked"): + owner.set_meta("_details_hooked", true) + owner.mouse_exited.connect(_on_owner_exited.bind(owner)) + _owner_ctrl = owner + _title.text = title + _title.visible = title != "" + _sub.text = sub + _sub.visible = sub != "" + _body.text = body + _body.visible = body != "" + _wait = DELAY if not visible else 0.0 + _pending = true + if visible: + _place() + + +## Hides the pop-up if `owner` opened it (or always, when owner is null). +func hide_for(owner: Control = null) -> void: + if owner == null or owner == _owner_ctrl: + _pending = false + _owner_ctrl = null + hide() + + +func _on_owner_exited(owner: Control) -> void: + hide_for(owner) + + +## Shows the prepared pop-up at a fixed spot until hide_for() (screenshots). +func pin(at: Vector2) -> void: + _owner_ctrl = null + _pending = false + show() + reset_size() + global_position = at + + +func _process(delta: float) -> void: + if _owner_ctrl == null: + return + # The owner may be rebuilt away (a card re-rendering) without a mouse_exited. + if not is_instance_valid(_owner_ctrl) or not _owner_ctrl.is_visible_in_tree(): + hide_for() + return + if _pending: + _wait -= delta + if _wait <= 0.0: + _pending = false + show() + _place() + elif visible: + _place() + + +func _place() -> void: + reset_size() + var view := get_viewport_rect().size + var p := get_global_mouse_position() + OFFSET + if p.x + size.x > view.x - 8.0: + p.x = view.x - size.x - 8.0 + if p.y + size.y > view.y - 8.0: + p.y = get_global_mouse_position().y - size.y - 12.0 + global_position = Vector2(maxf(8.0, p.x), maxf(8.0, p.y)) + + +# ---------- Content ---------- + +func show_table(owner: Control, tid: String, only_if_details: bool = false) -> void: + var t := main.data.get_table(tid) if main.data else null + if t == null: + return + if only_if_details and t.details.strip_edges() == "": + return + show_for(owner, Formatter.strip_tags(t.name), t.details, table_summary(t)) + + +func show_entry(owner: Control, tid: String, eid: String) -> void: + var t := main.data.get_table(tid) + var e := t.find_entry(eid) if t else null + if e == null or e.details.strip_edges() == "": + return + var shown := main.lit_text(tid, eid) + if shown == "": + shown = RichText.preview(e.text, main.data) + show_for(owner, _short(Formatter.strip_tags(shown)), e.details, Formatter.strip_tags(t.name)) + + +## Plain one-line title, cut down to a readable length. +static func _short(s: String) -> String: + s = s.strip_edges().replace("\n", " ") + while s.contains(" "): + s = s.replace(" ", " ") + return s if s.length() <= 90 else s.substr(0, 88).strip_edges() + "…" + + +## A result chip: the entry's details, else the table's. +func show_step(owner: Control, step: Dictionary) -> void: + var t := main.data.get_table(str(step.get("table_id", ""))) + if t == null: + return + var e := t.find_entry(str(step.get("entry_id", ""))) + var body := e.details if e and e.details.strip_edges() != "" else t.details + if body.strip_edges() == "": + return + var title := _short(Formatter.strip_tags(str(step.get("text", "")))) if e and e.details.strip_edges() != "" else Formatter.strip_tags(t.name) + show_for(owner, title, body, Formatter.strip_tags(t.name) if e and e.details.strip_edges() != "" else table_summary(t)) + + +## True when a result chip has something to show. +func step_has_details(step: Dictionary) -> bool: + var t := main.data.get_table(str(step.get("table_id", ""))) + if t == null: + return false + var e := t.find_entry(str(step.get("entry_id", ""))) + return t.details.strip_edges() != "" or (e != null and e.details.strip_edges() != "") + + +## A [url] meta inside rendered text (see TextExpander's marker formats). +func show_meta(owner: Control, meta: String) -> void: + var kind := meta.get_slice(":", 0) + var arg := meta.substr(kind.length() + 1) + match kind: + "table": + show_table(owner, arg) + "var": + _show_var(owner, arg) + "missing": + show_for(owner, "Missing table", "There's no table called [b]%s[/b]. Check the spelling, or add a table with that name." % RichText.plain(arg)) + "unset": + show_for(owner, "{%s} isn't set" % arg, "Nothing has saved this variable yet. Save it earlier in the roll with [lb][lb]Table -> %s]] or a pipe's [i]Save as[/i]." % RichText.plain(arg)) + "deep": + show_for(owner, "Chain too deep", "The roll stopped after %d levels so a loop can't run forever." % Roller.MAX_DEPTH) + + +func _show_var(owner: Control, name: String) -> void: + var persistent := name.begins_with("@") + var value: Variant = null + var source := "" + if persistent: + var v: Variant = main.persistent_vars.get(name.substr(1)) + if v is Dictionary: + value = str(v.get("value", "")) + source = str(v.get("source", "")) + else: + value = (main.current.get("chain_vars", {}) as Dictionary).get(name) + var sub := "Saved for this collection" if persistent else "Saved for this roll" + var st := main.data.get_table(source) if source != "" else null + if st: + sub += " · from %s" % Formatter.strip_tags(st.name) + var body := str(value) if value != null else "[i]Not set[/i]" + show_for(owner, "{%s}" % name, body, sub) + + +## "d100 · 6 ranges · 4 / 6 cards left" +func table_summary(t: RollTable) -> String: + var parts := PackedStringArray([t.dice_label()]) + parts.append("%d %s" % [t.entries.size(), "ranges" if t.is_ranged() else "results"]) + if t.card_mode: + var left := main.cards_left(t.id) + parts.append("%d / %d cards left" % [left.x, left.y]) + return " · ".join(parts) diff --git a/ui/details_popup.gd.uid b/ui/details_popup.gd.uid new file mode 100644 index 0000000..ac831bd --- /dev/null +++ b/ui/details_popup.gd.uid @@ -0,0 +1 @@ +uid://btqlxvnbjdgt0 diff --git a/ui/main.gd b/ui/main.gd index 4cbaaf2..7d68251 100644 --- a/ui/main.gd +++ b/ui/main.gd @@ -9,7 +9,7 @@ const HISTORY_SIZE := 6 const SAVE_DELAY := 0.6 const HINTS := { Mode.PLAY: "Click a die to roll. Results flow down the pipes.", - Mode.BUILD: "Type to edit. Drag from a ● to another table to lay a pipe. Click a pipe to remove it.", + Mode.BUILD: "Type to edit. Drag from a ● to another table to lay a pipe. Click a pipe for its options.", } var data: TowerBoard @@ -43,6 +43,15 @@ var _save_timer: Timer var _undo_snapshot := "" var _saving_enabled := true +# Local state for the current collection (see load_local_state). Kept in memory +# and written to `state` when there is one (saving disabled: memory only). +var decks: Dictionary = {} # table id -> DeckState +var persistent_vars: Dictionary = {} # name without "@" -> {"value", "source"} +var lit_texts: Dictionary = {} # "tid:eid" -> expanded BBCode from the last roll +var _details_popup: DetailsPopup +var _pipe_popover: PipePopover +var _ref_cache: Dictionary = {} # entry text -> Array[String] of referenced table ids + func _ready() -> void: rng.randomize() @@ -328,6 +337,7 @@ func set_mode(m: Mode) -> void: func mark_dirty() -> void: if _saving_enabled: _save_timer.start() + _ref_cache.clear() _update_collapse_all() @@ -397,7 +407,7 @@ func add_entry(tid: String) -> void: for x in t.entries: hi = maxi(hi, x.range_hi) e.has_range = true - e.range_lo = mini(t.die_size(), hi + 1) + e.range_lo = clampi(hi + 1, t.min_value(), t.die_size()) e.range_hi = e.range_lo e.text = "New range" t.entries.append(e) @@ -424,6 +434,7 @@ func delete_table(tid: String) -> void: return var snap := _snapshot() data.remove_table(tid) + forget_table_state(tid) var card := card_for(tid) cards.erase(tid) card.queue_free() @@ -519,12 +530,15 @@ func start_roll(tid: String) -> void: for c in cards.values(): (c as TableCard).set_rolling(false) (c as TableCard).clear_flick() - var tree := Roller.roll(data, tid, rng) + var ctx := Roller.new_context(data, rng, persistent_vars, decks) + var tree := Roller.roll(data, tid, rng, 0, decks, ctx) lit_entries.clear() lit_pipes.clear() + lit_texts.clear() _refresh_lit() - current = {"root": tid, "root_name": t.name, "time": Time.get_unix_time_from_system(), - "steps": [], "all": Roller.flatten(tree, []), "done": false} + current = {"collection": data.id, "root": tid, "root_name": t.name, "time": Time.get_unix_time_from_system(), + "steps": [], "all": Roller.flatten(tree, []), "done": false, "chain_vars": ctx.chain_vars.duplicate()} + _store_roll(ctx) tray.render() await _play_node(tree, my) if my == _token: @@ -533,7 +547,7 @@ func start_roll(tid: String) -> void: tray.render() -func _play_node(n: Dictionary, my: int) -> void: +func _play_node(n: Dictionary, my: int, depth: int = 0) -> void: if my != _token or n.is_empty(): return var t: RollTable = n["table"] @@ -546,7 +560,7 @@ func _play_node(n: Dictionary, my: int) -> void: if card == null: break if t.collapsed: - card.set_more_text("Rolling… %s" % t.fmt(rng.randi_range(1, t.die_size()))) + card.set_more_text("Rolling… %s" % t.fmt(rng.randi_range(t.min_value(), maxi(t.min_value(), t.die_size())))) else: card.flick_random() await get_tree().create_timer((40.0 + k * 16.0) / 1000.0).timeout @@ -558,17 +572,19 @@ func _play_node(n: Dictionary, my: int) -> void: card.set_rolling(false) if not stopped: var e: TableEntry = n["entry"] - lit_entries[Roller.entry_key(t.id, e.id)] = true + var ek := Roller.entry_key(t.id, e.id) + lit_entries[ek] = true + lit_texts[ek] = str(n.get("summary", e.text)) _refresh_lit() if card: card.reveal(e.id) - (current["steps"] as Array).append(Roller.step_of(n)) + (current["steps"] as Array).append(Roller.step_of(n, depth)) tray.render() for c in n["children"]: - var key := Roller.pipe_key(t.id, (n["entry"] as TableEntry).id, (c["table"] as RollTable).id) + var key := Roller.link_key(t.id, (n["entry"] as TableEntry).id, c) lit_pipes[key] = true await _pulse(key, my) - await _play_node(c, my) + await _play_node(c, my, depth + 1) func _pulse(key: String, my: int) -> void: @@ -584,6 +600,7 @@ func _pulse(key: String, my: int) -> void: board.pipes.pulse_key = "" +## Moves the current roll to the Earlier list (it's already in the saved history). func _archive_current() -> void: if current.is_empty() or current.get("archived", false): return @@ -595,29 +612,49 @@ func _archive_current() -> void: history.resize(HISTORY_SIZE) -## A game already under way: a couple of earlier rolls, and a current roll that -## runs through the d100 travel table into the collapsed trinket table. +## Opens the session: the collection's saved history, decks and variables. With +## no saved history (a fresh start, or --sample / --screenshot), it seeds a game +## already under way: a couple of earlier rolls, saved variables for the +## Variables tab, and a current roll that runs through the d100 travel table +## into the collapsed trinket table. func _seed_session() -> void: + load_local_state() + if not current.is_empty(): + _light_steps(current.get("all", [])) + _refresh_lit() + tray.render() + return var now := Time.get_unix_time_from_system() + # Seeded rolls draw from scratch decks so they don't use up real cards. + var scratch := {} for seed_roll in [["monsters", 9], ["loot", 4]]: if data.get_table(seed_roll[0]): - var tree := Roller.roll(data, seed_roll[0], rng) + var tree := Roller.roll(data, seed_roll[0], rng, 0, scratch) var steps := Roller.flatten(tree, []) - history.push_front({"root": seed_roll[0], "root_name": data.get_table(seed_roll[0]).name, + history.push_front({"collection": data.id, "root": seed_roll[0], "root_name": data.get_table(seed_roll[0]).name, "time": now - seed_roll[1] * 60, "steps": steps, "all": steps, "archived": true}) + # A quest-style chain earlier in the session saved who guides the party and + # the day's weather, so {@guide} and {@weather} have values. + if persistent_vars.is_empty(): + var ctx := Roller.new_context(data, rng, persistent_vars, scratch) + for pair in [["@guide", "names"], ["@weather", "weather"]]: + if data.get_table(pair[1]): + var n := Roller.roll(data, pair[1], rng, 0, scratch, ctx) + if not n.is_empty() and not n.has("stop"): + ctx.save(pair[0], Formatter.to_export_bbcode(str(n["summary"])), pair[1]) var start := "wilderness" if data.get_table("wilderness") else (data.tables[0].id if not data.tables.is_empty() else "") if start == "": tray.render() return - var best := Roller.roll(data, start, rng) + var best := Roller.roll(data, start, rng, 0, scratch) for i in 400: if Roller.reaches(best, "trinkets"): break - best = Roller.roll(data, start, rng) + best = Roller.roll(data, start, rng, 0, scratch) var all := Roller.flatten(best, []) - current = {"root": start, "root_name": data.get_table(start).name, "time": now - 60, - "steps": all, "all": all, "done": true} - Roller.collect_lit(best, lit_entries, lit_pipes) + current = {"collection": data.id, "root": start, "root_name": data.get_table(start).name, "time": now - 60, + "steps": all, "all": all, "done": true, "chain_vars": {}} + Roller.collect_lit(best, lit_entries, lit_pipes, lit_texts) _refresh_lit() tray.render() @@ -625,6 +662,8 @@ func _seed_session() -> void: # ---------- Command line (used for screenshots and checks) ---------- # godot --path . -- --screenshot=/tmp/shot.png [--build] [--expand-all] [--collapse-all] # [--roll=] [--shot-delay=] +# [--board=] (with --sample/--screenshot only: show that board instead) +# [--tray=variables] [--hover=,] [--details=
] [--pipe=] [--edit-details=
] func _arg_value(args: PackedStringArray, name: String) -> String: for a in args: @@ -634,6 +673,9 @@ func _arg_value(args: PackedStringArray, name: String) -> String: func _run_cli(args: PackedStringArray) -> void: + var board_file := _arg_value(args, "--board") + if board_file != "" and not _saving_enabled: + await _load_board_file(board_file) if args.has("--build"): set_mode(Mode.BUILD) if args.has("--expand-all"): @@ -643,6 +685,7 @@ func _run_cli(args: PackedStringArray) -> void: var roll := _arg_value(args, "--roll") if roll != "": start_roll(roll) + _run_cli_extras(args) var shot := _arg_value(args, "--screenshot") if shot == "": return @@ -652,3 +695,296 @@ func _run_cli(args: PackedStringArray) -> void: img.save_png(shot) print("Saved screenshot to ", shot) get_tree().quit() + + +# ---------- Local state: decks, persistent variables, history ---------- +# Everything here is keyed by the current collection id (data.id). With saving +# disabled (--sample / --screenshot) `state` is null and it all stays in memory. + +## Loads the current collection's decks, persistent variables and roll history. +## Call it again after switching `data` to another collection (then rebuild the +## cards and call tray.render()). +func load_local_state() -> void: + decks = {} + persistent_vars = {} + history.clear() + current = {} + lit_entries.clear() + lit_pipes.clear() + lit_texts.clear() + _ref_cache.clear() + if state == null or data == null: + return + persistent_vars = state.get_variables(data.id) + for t in data.tables: + var d := state.get_deck(data.id, t.id) + if not d.is_empty(): + decks[t.id] = DeckState.from_dict(d) + var recs := state.get_history(data.id) + for i in recs.size(): + var rec: Dictionary = recs[i] + if not (rec.get("steps") is Array): + continue + rec["all"] = rec["steps"] + rec["done"] = true + if current.is_empty(): + current = rec + elif history.size() < HISTORY_SIZE: + rec["archived"] = true + history.append(rec) + + +## Lights the entries and pipes of a roll from its saved steps. +func _light_steps(steps: Array) -> void: + var stack: Array = [] + for s: Dictionary in steps: + var d := int(s.get("depth", 0)) + stack.resize(d) + stack.append(s) + if s.get("stop", false) or not s.has("entry_id"): + continue + var tid := str(s.get("table_id", "")) + var ek := Roller.entry_key(tid, str(s["entry_id"])) + lit_entries[ek] = true + lit_texts[ek] = str(s.get("text", "")) + if d > 0 and stack[d - 1] is Dictionary and (stack[d - 1] as Dictionary).has("entry_id"): + var p: Dictionary = stack[d - 1] + var ptid := str(p.get("table_id", "")) + var peid := str(p["entry_id"]) + lit_pipes[Roller.ref_key(ptid, peid, tid) if s.get("inline", false) else Roller.pipe_key(ptid, peid, tid)] = true + + +## After a roll: saves the decks, any changed persistent variables and the +## history record. +func _store_roll(ctx: RollContext) -> void: + if state == null: + return + _store_decks() + if ctx.persistent_changed: + _store_variables() + state.add_history({"collection": data.id, "root": current["root"], "root_name": current["root_name"], + "time": current["time"], "steps": current["all"], "chain_vars": current.get("chain_vars", {})}) + state.save() + + +func _store_decks() -> void: + if state == null: + return + for tid: String in decks: + state.set_deck(data.id, tid, (decks[tid] as DeckState).to_dict()) + + +func _store_variables() -> void: + if state == null: + return + state.clear_variables(data.id) + for n: String in persistent_vars: + var v: Variant = persistent_vars[n] + if v is Dictionary: + state.set_variable(data.id, n, str(v.get("value", "")), str(v.get("source", ""))) + else: + state.set_variable(data.id, n, str(v)) + + +## A deleted table's deck and the variables it set are forgotten. +func forget_table_state(tid: String) -> void: + decks.erase(tid) + for n in persistent_vars.keys(): + var v: Variant = persistent_vars[n] + if v is Dictionary and str(v.get("source", "")) == tid: + persistent_vars.erase(n) + if state: + state.forget_table(data.id, tid) + state.save() + if tray: + tray.render() + + +## Vector2i(cards left, total) for a card-mode table. +func cards_left(tid: String) -> Vector2i: + var t := data.get_table(tid) + if t == null: + return Vector2i.ZERO + var deck: DeckState = decks.get(tid) + return deck.cards_left(t) if deck else DeckState.new().cards_left(t) + + +func reshuffle_table(tid: String) -> void: + var t := data.get_table(tid) + if t == null: + return + decks.erase(tid) + if state: + state.clear_deck(data.id, tid) + state.save() + var card := card_for(tid) + if card: + card.update_deck() + toast("Reshuffled %s" % Formatter.strip_tags(t.name)) + + +## The expanded text an entry showed in the last roll, or "" if it isn't lit. +func lit_text(tid: String, eid: String) -> String: + return str(lit_texts.get(Roller.entry_key(tid, eid), "")) + + +## Ids of the tables an entry's text references (cached until the next edit). +func ref_targets_for(e: TableEntry) -> Array[String]: + if not _ref_cache.has(e.text): + _ref_cache[e.text] = Roller.ref_targets(data, e.text) + return _ref_cache[e.text] + + +# ---------- Variables ---------- + +func set_variable(name: String, value: String) -> void: + var old: Variant = persistent_vars.get(name) + var source := str(old.get("source", "")) if old is Dictionary else "" + persistent_vars[name] = {"value": value, "source": source} + _store_variables() + if state: + state.save() + tray.render() + + +func clear_variable(name: String) -> void: + if not persistent_vars.erase(name): + return + _store_variables() + if state: + state.save() + tray.render() + toast("Cleared {@%s}" % name) + + +## Rolls the variable's source table again and saves the new result. +func reroll_variable(name: String) -> void: + var v: Variant = persistent_vars.get(name) + var source := str(v.get("source", "")) if v is Dictionary else "" + var t := data.get_table(source) + if t == null: + toast("{@%s} has no table to re-roll from" % name) + return + var ctx := Roller.new_context(data, rng, persistent_vars, decks) + var n := Roller.roll(data, source, rng, 0, decks, ctx) + if n.is_empty() or n.has("stop"): + toast("Couldn't re-roll {@%s}: %s" % [name, Formatter.strip_tags(str(n.get("summary", "no result")))]) + return + var value := Formatter.to_export_bbcode(str(n["summary"])) + persistent_vars[name] = {"value": value, "source": source} + _store_decks() + _store_variables() + if state: + state.save() + _refresh_lit() + tray.render() + toast("{@%s} is now %s" % [name, Formatter.strip_tags(value)]) + + +# ---------- Copy ---------- + +## Copies the current result: ResultTray.COPY_TEXT, COPY_BBCODE or COPY_DETAILS. +func copy_current(kind: int) -> void: + if current.is_empty(): + return + var text := result_text(current.get("all", []), kind) + DisplayServer.clipboard_set(text) + toast(["Copied as text", "Copied as BBCode", "Copied with details"][clampi(kind, 0, 2)]) + + +## One line per table rolled, indented by depth. Inline rolls are already part +## of their parent's text, so they don't get lines of their own. +func result_text(steps: Array, kind: int) -> String: + var lines := PackedStringArray() + for s: Dictionary in steps: + if s.get("inline", false): + continue + var indent := " ".repeat(int(s.get("depth", 0))) + var tname := str(s.get("table", "")) + var text := str(s.get("text", "")) + if kind == ResultTray.COPY_BBCODE: + lines.append(indent + "[b]%s:[/b] %s" % [Formatter.to_export_bbcode(tname), Formatter.to_export_bbcode(text)]) + else: + lines.append(indent + "%s: %s" % [Formatter.strip_tags(tname), Formatter.strip_tags(text)]) + if kind == ResultTray.COPY_DETAILS: + var t := data.get_table(str(s.get("table_id", ""))) + var e := t.find_entry(str(s.get("entry_id", ""))) if t else null + if e and e.details.strip_edges() != "": + var pad := indent + " " + lines.append(pad + Formatter.strip_tags(e.details).strip_edges().replace("\n", "\n" + pad)) + return "\n".join(lines) + + +# ---------- Pop-ups ---------- + +## The shared hover pop-up for details. +func details() -> DetailsPopup: + if _details_popup == null: + _details_popup = DetailsPopup.new() + add_child(_details_popup) + _details_popup.setup(self) + return _details_popup + + +## Build mode: the options for a clicked pipe (count, save as, remove). +func open_pipe_options(key: String, at: Vector2) -> void: + if _pipe_popover == null: + _pipe_popover = PipePopover.new() + add_child(_pipe_popover) + _pipe_popover.setup(self) + details().hide_for() + _pipe_popover.open(key, at) + + +## The card's ⚙ button. Main.open_table_settings comes from the app-shell work; +## until it exists this only says so. +func request_table_settings(tid: String) -> void: + if has_method("open_table_settings"): + call("open_table_settings", tid) + else: + toast("Table settings aren't available yet") + + +# ---------- Command line extras ---------- + +## Shows a collection file instead of the sample (screenshots only; nothing is saved). +func _load_board_file(path: String) -> void: + var text := FileAccess.get_file_as_string(path) + if text == "" or not data.load_json(text): + push_warning("Couldn't load board file %s" % path) + return + _rebuild_cards() + _seed_session() + await get_tree().process_frame + await get_tree().process_frame + board.fit() + + +func _run_cli_extras(args: PackedStringArray) -> void: + if _arg_value(args, "--tray") == "variables": + tray.set_side(ResultTray.Side.VARIABLES) + var edit := _arg_value(args, "--edit-details") + var ecard := card_for(edit) + if ecard: + ecard._table_details_open = true + if not ecard.table.entries.is_empty(): + ecard._open_details[ecard.table.entries[0].id] = true + ecard.rebuild() + var pipe := _arg_value(args, "--pipe") + if pipe != "": + open_pipe_options(pipe, Vector2(size.x * 0.45, size.y * 0.3)) + var hover := _arg_value(args, "--hover") + if hover.contains(","): + # Synthetic mouse move, to check hover pop-ups in screenshots. + await get_tree().create_timer(0.3).timeout + var ev := InputEventMouseMotion.new() + ev.position = Vector2(hover.get_slice(",", 0).to_float(), hover.get_slice(",", 1).to_float()) + ev.global_position = ev.position + get_viewport().notification(NOTIFICATION_VP_MOUSE_ENTER) + get_viewport().push_input(ev) + var det := _arg_value(args, "--details") + var card := card_for(det) + if card: + await get_tree().process_frame + details().show_table(card, det) + details().pin(card.get_global_rect().position + Vector2(60, 46)) diff --git a/ui/pipe_layer.gd b/ui/pipe_layer.gd index 8e9ab11..860e6e6 100644 --- a/ui/pipe_layer.gd +++ b/ui/pipe_layer.gd @@ -2,22 +2,30 @@ class_name PipeLayer extends Control ## Draws the copper pipes between cards, lit pipes in brass, and the glowing bead ## that travels down a pipe during a roll. Sits behind the cards. +## +## [[References]] in an entry's text draw as thinner dashed pipes. They come from +## the text, so they can't be clicked or removed here. const SAMPLES := 40 var main: Main var hover_key: String = "" +## The pipe whose options are open in Build mode. +var select_key: String = "" var pulse_key: String = "" var pulse_t: float = 0.0 ## pipe key -> polyline in world coordinates, from the last frame. var _paths: Dictionary = {} +var _label_box: StyleBoxFlat func _init() -> void: mouse_filter = MOUSE_FILTER_IGNORE # Controls only draw inside their own rect, so cover the whole world. size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE) + _label_box = Style.box(Style.CARD, 7, [6, 1, 6, 2]) + Style.bordered(_label_box, 1, Style.COPPER_DARK) func _process(_delta: float) -> void: @@ -37,18 +45,34 @@ static func curve(a: Vector2, b: Vector2) -> PackedVector2Array: func _draw() -> void: _paths.clear() var lit_list: Array = [] + var lit_refs: Array = [] + var labels: Array = [] var build := main.mode == Main.Mode.BUILD for t in main.data.tables: var card := main.card_for(t.id) if card == null: continue for e in t.entries: - for to in e.pipes: + var refs := main.ref_targets_for(e) + if e.pipes.is_empty() and refs.is_empty(): + continue + var a := card.anchor_for(e.id) + if a.is_empty(): + continue + for to in refs: var target := main.card_for(to) if target == null: continue - var a := card.anchor_for(e.id) - if a.is_empty(): + var key := Roller.ref_key(t.id, e.id, to) + var pts := curve(a["pos"], target.inlet_point()) + _paths[key] = pts + if main.lit_pipes.has(key): + lit_refs.append(pts) + else: + _draw_ref(pts, false) + for to in e.pipes: + var target := main.card_for(to) + if target == null: continue var key := Roller.pipe_key(t.id, e.id, to) var pts := curve(a["pos"], target.inlet_point()) @@ -56,15 +80,43 @@ func _draw() -> void: if main.lit_pipes.has(key): lit_list.append(pts) else: - _draw_pipe(pts, false, build and key == hover_key) + _draw_pipe(pts, false, build and (key == hover_key or key == select_key)) + var tag := _pipe_tag(e, to) + if tag != "": + labels.append([pts, tag]) # Lit pipes go on top so the path of the last roll reads clearly. + for pts in lit_refs: + _draw_ref(pts, true) for pts in lit_list: _draw_pipe(pts, true, false) + for l in labels: + _draw_tag(l[0], l[1]) if pulse_key != "" and _paths.has(pulse_key): var p := point_along(_paths[pulse_key], pulse_t) - draw_circle(p, 13.0, Color(Style.BRASS, 0.3)) - draw_circle(p, 9.0, Color(Style.BRASS, 0.5)) - draw_circle(p, 7.0, Style.PULSE) + var r := 0.75 if Roller.is_ref_key(pulse_key) else 1.0 + draw_circle(p, 13.0 * r, Color(Style.BRASS, 0.3)) + draw_circle(p, 9.0 * r, Color(Style.BRASS, 0.5)) + draw_circle(p, 7.0 * r, Style.PULSE) + + +## "×2 → foe" for a pipe with options, or "". +static func _pipe_tag(e: TableEntry, to: String) -> String: + var parts := PackedStringArray() + if e.count_for(to) > 1: + parts.append("×%d" % e.count_for(to)) + if e.save_for(to) != "": + parts.append("→ " + e.save_for(to)) + return " ".join(parts) + + +func _draw_tag(pts: PackedVector2Array, text: String) -> void: + var font := Style.body_bold(true) + var fs := 12 + var w := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x + var mid := point_along(pts, 0.5) + var r := Rect2(mid - Vector2(w / 2.0 + 6.0, 10.0), Vector2(w + 12.0, 19.0)) + draw_style_box(_label_box, r) + draw_string(font, Vector2(r.position.x + 6.0, r.position.y + 14.0), text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.COPPER_DARK) func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void: @@ -73,13 +125,56 @@ func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void: draw_polyline(pts, Style.BRASS_DARK if lit else Style.COPPER_DARK, 11.0, true) var inner := Style.BRASS if lit else Style.COPPER if hovered: - inner = Style.DANGER + inner = Style.COPPER.lightened(0.35) draw_polyline(pts, inner, 6.0, true) draw_set_transform(Vector2(0, -1.5)) draw_polyline(pts, Color(1.0, 0.886, 0.745, 0.4), 1.5, true) draw_set_transform(Vector2.ZERO) +## A reference pipe: thinner, in dashes. +func _draw_ref(pts: PackedVector2Array, lit: bool) -> void: + if lit: + draw_polyline(pts, Color(Style.BRASS, 0.14), 12.0, true) + var dashes := _dashes(pts, 12.0, 7.0) + for d in dashes: + draw_polyline(d, Style.BRASS_DARK if lit else Style.COPPER_DARK, 6.0, true) + for d in dashes: + draw_polyline(d, Style.BRASS if lit else Style.COPPER, 3.0, true) + + +## Splits a polyline into dashes `on` long with gaps `off` long. +static func _dashes(pts: PackedVector2Array, on: float, off: float) -> Array[PackedVector2Array]: + var out: Array[PackedVector2Array] = [] + var cur := PackedVector2Array() + var drawing := true + var left := on + for i in range(1, pts.size()): + var a := pts[i - 1] + var b := pts[i] + var seg := a.distance_to(b) + var pos := 0.0 + if drawing and cur.is_empty(): + cur.append(a) + while seg - pos > left: + pos += left + var p := a.lerp(b, pos / seg) + if drawing: + cur.append(p) + out.append(cur) + cur = PackedVector2Array() + else: + cur = PackedVector2Array([p]) + drawing = not drawing + left = on if drawing else off + left -= seg - pos + if drawing: + cur.append(b) + if drawing and cur.size() > 1: + out.append(cur) + return out + + func path_length(key: String) -> float: if not _paths.has(key): return 0.0 @@ -106,8 +201,11 @@ static func point_along(pts: PackedVector2Array, t: float) -> Vector2: ## The pipe under a world-space point, or "" if none is within `tolerance`. +## Reference pipes come from entry text, so they're never picked. func pipe_at(p: Vector2, tolerance: float) -> String: - for key in _paths: + for key: String in _paths: + if Roller.is_ref_key(key): + continue var pts: PackedVector2Array = _paths[key] for i in range(1, pts.size()): if Geometry2D.get_closest_point_to_segment(p, pts[i - 1], pts[i]).distance_to(p) <= tolerance: diff --git a/ui/pipe_popover.gd b/ui/pipe_popover.gd new file mode 100644 index 0000000..f90e598 --- /dev/null +++ b/ui/pipe_popover.gd @@ -0,0 +1,160 @@ +class_name PipePopover +extends PopupPanel +## Build mode: the options for one pipe, opened by clicking it. How many times +## it rolls, the variable it saves its result as, and Remove. + +const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$" + +var main: Main +var key: String = "" +var _entry: TableEntry +var _to: String = "" +var _title: RichTextLabel +var _count: LineEdit +var _save: LineEdit +var _save_ok: StyleBoxFlat +var _save_bad: StyleBoxFlat +var _re := RegEx.new() + + +func setup(p_main: Main) -> void: + main = p_main + _re.compile(SAVE_PATTERN) + theme = Style.card_theme() + var sb := Style.box(Style.CARD, 9, [14, 11, 14, 12]) + sb.border_width_top = 3 + sb.border_color = Style.COPPER + add_theme_stylebox_override("panel", sb) + popup_hide.connect(func() -> void: + _commit_save() + if main.board: + main.board.pipes.select_key = "" + ) + + var v := VBoxContainer.new() + v.add_theme_constant_override("separation", 9) + add_child(v) + _title = RichText.label("", 15, Style.INK, false) + _title.custom_minimum_size = Vector2(260, 0) + v.add_child(_title) + + var field_ok := Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.RULE) + var field_focus := Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.COPPER) + _save_ok = field_ok + _save_bad = Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.DANGER) + + var count_row := HBoxContainer.new() + count_row.add_theme_constant_override("separation", 6) + v.add_child(count_row) + var cl := Style.make_label("Rolls", Style.body(), 14, Style.MUTED) + cl.custom_minimum_size = Vector2(62, 0) + count_row.add_child(cl) + var minus := _small_button("−") + minus.pressed.connect(func() -> void: _set_count(_entry.count_for(_to) - 1 if _entry else 1)) + count_row.add_child(minus) + _count = LineEdit.new() + _count.custom_minimum_size = Vector2(44, 0) + _count.alignment = HORIZONTAL_ALIGNMENT_CENTER + _count.max_length = 2 + _count.add_theme_stylebox_override("normal", field_ok) + _count.add_theme_stylebox_override("focus", field_focus) + _count.text_submitted.connect(func(s: String) -> void: _set_count(s.to_int())) + _count.focus_exited.connect(func() -> void: _set_count(_count.text.to_int())) + count_row.add_child(_count) + var plus := _small_button("+") + plus.pressed.connect(func() -> void: _set_count(_entry.count_for(_to) + 1 if _entry else 1)) + count_row.add_child(plus) + count_row.add_child(Style.make_label("times", Style.body(), 14, Style.MUTED)) + + var save_row := HBoxContainer.new() + save_row.add_theme_constant_override("separation", 6) + v.add_child(save_row) + var sl := Style.make_label("Save as", Style.body(), 14, Style.MUTED) + sl.custom_minimum_size = Vector2(62, 0) + save_row.add_child(sl) + _save = LineEdit.new() + _save.placeholder_text = "name, or @name to keep" + _save.size_flags_horizontal = Control.SIZE_EXPAND_FILL + _save.add_theme_stylebox_override("normal", field_ok) + _save.add_theme_stylebox_override("focus", field_focus) + _save.text_changed.connect(func(s: String) -> void: + var ok := s.strip_edges() == "" or _re.search(s.strip_edges()) != null + _save.add_theme_stylebox_override("normal", _save_ok if ok else _save_bad) + _save.add_theme_stylebox_override("focus", field_focus if ok else _save_bad) + ) + _save.text_submitted.connect(func(_s: String) -> void: + _commit_save() + hide() + ) + save_row.add_child(_save) + var hint := Style.make_label("{name} lasts one roll; {@name} is kept.", Style.body(), 12, Style.MUTED) + v.add_child(hint) + + var remove := Button.new() + remove.text = "Remove pipe" + remove.add_theme_font_size_override("font_size", 14) + var rn := Style.bordered(Style.box(Color(0, 0, 0, 0), 6, [10, 4, 10, 4]), 1, Style.DASH) + var rh := Style.bordered(Style.box(Style.WARN_BG, 6, [10, 4, 10, 4]), 1, Style.DANGER_INK) + Style.skin_button(remove, rn, rh, rh, Style.DANGER_INK) + remove.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN + remove.pressed.connect(func() -> void: + var k := key + _entry = null + hide() + main.remove_pipe(k) + ) + v.add_child(remove) + + +func _small_button(text: String) -> Button: + var b := Button.new() + b.text = text + b.custom_minimum_size = Vector2(26, 26) + b.add_theme_font_size_override("font_size", 16) + var n := Style.bordered(Style.box(Color(0, 0, 0, 0), 5), 1, Style.RULE) + var h := Style.bordered(Style.box(Style.HOVER_ROW, 5), 1, Style.DASH) + Style.skin_button(b, n, h, h, Style.INK) + return b + + +## Opens for the pipe `pipe_key` near `at` (window coordinates). +func open(pipe_key: String, at: Vector2) -> void: + var from := pipe_key.get_slice(">", 0) + var t := main.data.get_table(from.get_slice(":", 0)) + _to = pipe_key.get_slice(">", 1) + _entry = t.find_entry(from.get_slice(":", 1)) if t else null + if _entry == null: + return + key = pipe_key + var target := main.data.get_table(_to) + _title.text = "%s [color=#%s]→[/color] [b]%s[/b]" % [RichText.preview(_entry.text, main.data), Style.COPPER.to_html(false), RichText.plain(Formatter.strip_tags(target.name)) if target else _to] + _count.text = str(_entry.count_for(_to)) + _save.text = _entry.save_for(_to) + _save.add_theme_stylebox_override("normal", _save_ok) + main.board.pipes.select_key = pipe_key + reset_size() + var view := main.get_viewport_rect().size + var sz := get_contents_minimum_size() + var p := at + Vector2(12, 12) + p.x = clampf(p.x, 8.0, view.x - sz.x - 36.0) + p.y = clampf(p.y, 8.0, view.y - sz.y - 36.0) + popup(Rect2i(Vector2i(p), Vector2i.ZERO)) + + +func _set_count(n: int) -> void: + if _entry == null: + return + _entry.set_pipe_count(_to, n) + _count.text = str(_entry.count_for(_to)) + main.mark_dirty() + + +func _commit_save() -> void: + if _entry == null: + return + var s := _save.text.strip_edges() + if s != "" and _re.search(s) == null: + return + if s != _entry.save_for(_to): + _entry.set_pipe_save(_to, s) + main.mark_dirty() diff --git a/ui/pipe_popover.gd.uid b/ui/pipe_popover.gd.uid new file mode 100644 index 0000000..3048b8d --- /dev/null +++ b/ui/pipe_popover.gd.uid @@ -0,0 +1 @@ +uid://daomwkc7dercc diff --git a/ui/port_layer.gd b/ui/port_layer.gd index 2363379..8842bff 100644 --- a/ui/port_layer.gd +++ b/ui/port_layer.gd @@ -50,7 +50,7 @@ func _draw() -> void: var a := card.anchor_for(e.id) if a.is_empty() or not a["visible"]: continue - var on := not e.pipes.is_empty() + var on := not e.pipes.is_empty() or not main.ref_targets_for(e).is_empty() if not build and not on: continue var pos: Vector2 = a["pos"] diff --git a/ui/result_tray.gd b/ui/result_tray.gd index d13d29e..c210d42 100644 --- a/ui/result_tray.gd +++ b/ui/result_tray.gd @@ -1,15 +1,28 @@ class_name ResultTray extends PanelContainer ## The strip along the bottom: the current roll as a chain of result chips -## joined by brass pipe pieces, and a short list of earlier rolls. +## joined by brass pipe pieces, a Copy menu, and on the right either the +## earlier rolls (default) or the Variables tab. + +enum Side { EARLIER, VARIABLES } + +const COPY_TEXT := 0 +const COPY_BBCODE := 1 +const COPY_DETAILS := 2 var main: Main +var side: int = Side.EARLIER var _title: Label var _again: Button +var _copy: MenuButton var _flow: HFlowContainer var _empty: Label +var _earlier_box: VBoxContainer var _earlier: VBoxContainer var _earlier_empty: Label +var _vars: VariablesPanel +var _tab_earlier: Button +var _tab_vars: Button var _shown_for: Dictionary = {} var _shown_count := 0 @@ -41,6 +54,8 @@ func setup(p_main: Main) -> void: main.start_roll(main.current["root"]) ) head.add_child(_again) + _copy = _make_copy_menu() + head.add_child(_copy) _flow = HFlowContainer.new() _flow.add_theme_constant_override("h_separation", 0) _flow.add_theme_constant_override("v_separation", 8) @@ -50,16 +65,81 @@ func setup(p_main: Main) -> void: _empty = Style.make_label("Click a die on any table to roll.", Style.body(), 16, Style.ON_FELT_MUTED) now.add_child(_empty) - var earlier := VBoxContainer.new() - earlier.add_theme_constant_override("separation", 8) - earlier.custom_minimum_size = Vector2(300, 0) - h.add_child(earlier) - earlier.add_child(Style.make_label("EARLIER", Style.caps(), 12, Style.ON_FELT_MUTED)) + var right := VBoxContainer.new() + right.add_theme_constant_override("separation", 8) + right.custom_minimum_size = Vector2(340, 0) + h.add_child(right) + var tabs := HBoxContainer.new() + tabs.add_theme_constant_override("separation", 14) + right.add_child(tabs) + _tab_earlier = _tab("EARLIER") + _tab_earlier.pressed.connect(func() -> void: set_side(Side.EARLIER)) + tabs.add_child(_tab_earlier) + _tab_vars = _tab("VARIABLES") + _tab_vars.tooltip_text = "Saved variables for this collection" + _tab_vars.pressed.connect(func() -> void: set_side(Side.VARIABLES)) + tabs.add_child(_tab_vars) + + _earlier_box = VBoxContainer.new() + _earlier_box.add_theme_constant_override("separation", 6) + right.add_child(_earlier_box) _earlier = VBoxContainer.new() _earlier.add_theme_constant_override("separation", 6) - earlier.add_child(_earlier) + _earlier_box.add_child(_earlier) _earlier_empty = Style.make_label("Older rolls show here.", Style.body(), 15, Style.ON_FELT_MUTED) - earlier.add_child(_earlier_empty) + _earlier_box.add_child(_earlier_empty) + _vars = VariablesPanel.new() + _vars.setup(main) + right.add_child(_vars) + set_side(Side.EARLIER) + + +func _tab(text: String) -> Button: + var b := Button.new() + b.text = text + b.toggle_mode = true + b.add_theme_font_override("font", Style.caps()) + b.add_theme_font_size_override("font_size", 12) + var n := Style.box(Color(0, 0, 0, 0), 0, [0, 0, 0, 3]) + var on := Style.box(Color(0, 0, 0, 0), 0, [0, 0, 0, 1]) + on.border_width_bottom = 2 + on.border_color = Style.BRASS + Style.skin_button(b, n, n, on, Style.ON_FELT_MUTED, Style.ON_FELT, Style.ON_FELT) + b.add_theme_stylebox_override("focus", Style.box(Color(0, 0, 0, 0))) + return b + + +func set_side(s: int) -> void: + side = s + _tab_earlier.set_pressed_no_signal(s == Side.EARLIER) + _tab_vars.set_pressed_no_signal(s == Side.VARIABLES) + _earlier_box.visible = s == Side.EARLIER + _vars.visible = s == Side.VARIABLES + if s == Side.VARIABLES: + _vars.render() + + +func _make_copy_menu() -> MenuButton: + var m := MenuButton.new() + m.text = "Copy" + m.tooltip_text = "Copy this result" + m.flat = false + var normal := Style.bordered(Style.box(Color(1, 1, 1, 0.04), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16)) + var hover := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16)) + Style.skin_button(m, normal, hover, hover, Style.ON_FELT) + m.add_theme_font_size_override("font_size", 15) + var pm := m.get_popup() + pm.add_item("Copy as text", COPY_TEXT) + pm.add_item("Copy as BBCode", COPY_BBCODE) + pm.add_item("Copy with details", COPY_DETAILS) + pm.add_theme_stylebox_override("panel", Style.bordered(Style.box(Style.CARD, 8, [6, 6, 6, 6]), 1, Style.RULE)) + pm.add_theme_stylebox_override("hover", Style.box(Style.LIT, 5, [8, 4, 8, 4])) + pm.add_theme_color_override("font_color", Style.INK) + pm.add_theme_color_override("font_hover_color", Style.INK) + pm.add_theme_font_override("font", Style.body()) + pm.add_theme_font_size_override("font_size", 15) + pm.id_pressed.connect(func(id: int) -> void: main.copy_current(id)) + return m func render() -> void: @@ -78,16 +158,19 @@ func render() -> void: if current.is_empty(): _title.text = "RESULT" _again.hide() + _copy.hide() else: - var root_name: String = current["root_name"] + var root_name := Formatter.strip_tags(str(current["root_name"])) _title.text = ("Result · %s" % root_name).to_upper() _again.text = "Roll %s again" % root_name _again.visible = main.data.get_table(current["root"]) != null var done: bool = current.get("done", false) + _copy.visible = done for i in steps.size(): + var step: Dictionary = steps[i] if i > 0: - _flow.add_child(_link()) - var chip := _chip(steps[i], done and i == steps.size() - 1) + _flow.add_child(_link(step.get("inline", false))) + var chip := _chip(step, done and i == steps.size() - 1) _flow.add_child(chip) if i >= fresh_from: chip.modulate.a = 0.3 @@ -105,61 +188,81 @@ func render() -> void: time.size_flags_vertical = SIZE_SHRINK_BEGIN row.add_child(time) var texts := PackedStringArray() - for s in rec["steps"]: - texts.append(s["text"]) - var line := RichTextLabel.new() - line.bbcode_enabled = true - line.fit_content = true - line.scroll_active = false - line.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + for s: Dictionary in rec["steps"]: + if not s.get("inline", false): + texts.append(RichText.decorate(str(s["text"]), true)) + var line := RichText.label("[color=#%s]%s:[/color] %s" % [Style.ON_FELT_MUTED.to_html(false), + RichText.plain(Formatter.strip_tags(str(rec["root_name"]))), " → ".join(texts)], 14, Style.ON_FELT, false) line.size_flags_horizontal = SIZE_EXPAND_FILL - line.add_theme_font_override("normal_font", Style.body()) - line.add_theme_font_size_override("normal_font_size", 14) - line.add_theme_color_override("default_color", Style.ON_FELT) - line.text = "[color=#%s]%s:[/color] %s" % [Style.ON_FELT_MUTED.to_html(false), _bb(rec["root_name"]), _bb(" → ".join(texts))] + RichText.hook_hover(line, main) row.add_child(line) _earlier.add_child(row) + var n := main.persistent_vars.size() + _tab_vars.text = "VARIABLES · %d" % n if n > 0 else "VARIABLES" + if side == Side.VARIABLES: + _vars.render() + func _chip(step: Dictionary, last: bool) -> Control: + var inline: bool = step.get("inline", false) var p := PanelContainer.new() - var sb := Style.box(Style.LIT if last else Style.CARD, 9, [12, 7, 12, 8]) + var sb := Style.box(Style.LIT if last else Style.CARD, 9, [10, 5, 10, 6] if inline else [12, 7, 12, 8]) sb.shadow_color = Color(0, 0, 0, 0.25) sb.shadow_size = 1 sb.shadow_offset = Vector2(0, 3) if last: Style.bordered(sb, 2, Style.BRASS) sb.set_expand_margin_all(2) + if inline: + sb.bg_color = sb.bg_color.darkened(0.04) p.add_theme_stylebox_override("panel", sb) + p.size_flags_vertical = SIZE_SHRINK_CENTER + p.mouse_filter = MOUSE_FILTER_PASS var v := VBoxContainer.new() v.add_theme_constant_override("separation", 1) p.add_child(v) var num: String = step["num"] - var caption: String = step["table"] + var caption := Formatter.strip_tags(str(step["table"])) if num != "": - caption += " · rolled %s on d%d" % [num, step["die"]] - v.add_child(Style.make_label(caption, Style.body(), 12, Style.MUTED)) - v.add_child(Style.make_label(step["text"], Style.display(), 20, Style.INK)) + caption += " · rolled %s on %s" % [num, step.get("dice", "d%d" % int(step["die"]))] + if step.get("reshuffled", false): + caption += " · deck reshuffled" + if str(step.get("save_as", "")) != "": + caption += " · saved as {%s}" % step["save_as"] + var has_details := main.details().step_has_details(step) + if has_details: + caption += " " + RichText.INFO_MARK + var cap := Style.make_label(caption, Style.body(), 11 if inline else 12, Style.MUTED) + cap.mouse_filter = MOUSE_FILTER_IGNORE + v.add_child(cap) + var shown := RichText.decorate(str(step["text"])) + var body := RichText.display_label(shown, 16 if inline else 20, Style.DANGER_INK if step.get("stop", false) else Style.INK) + if Formatter.strip_tags(shown).length() > 56: + body.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + body.custom_minimum_size = Vector2(420, 0) + RichText.hook_hover(body, main) + v.add_child(body) + if has_details: + p.mouse_entered.connect(func() -> void: main.details().show_step(p, step)) return p -func _link() -> Control: +func _link(inline: bool = false) -> Control: var link := Panel.new() var sb := Style.box(Style.BRASS) sb.border_width_top = 2 sb.border_width_bottom = 2 sb.border_color = Style.BRASS_DARK + if inline: + sb = Style.box(Color(Style.BRASS, 0.55)) link.add_theme_stylebox_override("panel", sb) - link.custom_minimum_size = Vector2(22, 8) + link.custom_minimum_size = Vector2(16, 4) if inline else Vector2(22, 8) link.size_flags_vertical = SIZE_SHRINK_CENTER link.mouse_filter = MOUSE_FILTER_IGNORE return link -static func _bb(text: String) -> String: - return text.replace("[", "[lb]") - - static func clock(unix: float) -> String: var bias: int = Time.get_time_zone_from_system().get("bias", 0) var d := Time.get_datetime_dict_from_unix_time(int(unix) + bias * 60) diff --git a/ui/rich_text.gd b/ui/rich_text.gd new file mode 100644 index 0000000..52a4556 --- /dev/null +++ b/ui/rich_text.gd @@ -0,0 +1,205 @@ +class_name RichText +extends RefCounted +## BBCode display helpers: RichTextLabels in the app's fonts, a readable preview +## of entry text with [[references]] and {variables}, and colouring for +## TextExpander's internal markers in rolled results. + +## Marker shown after items that have hover details. +const INFO_MARK := "ⓘ" + +const _VAR_PATTERN := "\\{(@?[A-Za-z_][A-Za-z0-9_]*)(?:\\|([^{}\\[\\]\\n]+))?\\}" +const _COUNT_PATTERN := "^(?:(\\d+)\\s*[x×]|(\\d*[dD]\\d+(?:\\s*[+-]\\s*\\d+)?))\\s+(\\S.*)$" + +static var _var_re: RegEx +static var _count_re: RegEx + +## Colours for marker text, on cards (light) and on the felt (dark). +const REF_INK := Color("#1d6656") +const REF_BG := Color("#d6e9e2") +const VAR_INK := Color("#7d5a0c") +const REF_INK_FELT := Color("#9fdcc9") +const VAR_INK_FELT := Color("#f3c450") +const BAD_INK_FELT := Color("#ffb1a3") + + +## A RichTextLabel that sizes itself to its text like a Label. +## `zoomable` picks the card (MSDF) fonts that stay sharp on the zoomed board. +static func label(text: String, font_size: int, color: Color, zoomable: bool, wrap: bool = true, bold: bool = false) -> RichTextLabel: + var l := RichTextLabel.new() + l.bbcode_enabled = true + l.fit_content = true + l.scroll_active = false + l.meta_underlined = false + l.hint_underlined = false + l.shortcut_keys_enabled = false + l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART if wrap else TextServer.AUTOWRAP_OFF + l.mouse_filter = Control.MOUSE_FILTER_PASS + set_fonts(l, font_size, zoomable, bold) + l.add_theme_color_override("default_color", color) + l.text = text + return l + + +## Sets every font slot of a RichTextLabel. `bold` makes the normal text bold +## (used for a lit row). +static func set_fonts(l: RichTextLabel, font_size: int, zoomable: bool, bold: bool = false) -> void: + l.add_theme_font_override("normal_font", Style.body_bold(zoomable) if bold else Style.body(zoomable)) + l.add_theme_font_override("bold_font", Style.body_bold(zoomable)) + l.add_theme_font_override("italics_font", Style.body_italic(zoomable)) + l.add_theme_font_override("bold_italics_font", Style.body_bold(zoomable)) + for slot in ["normal_font_size", "bold_font_size", "italics_font_size", "bold_italics_font_size", "mono_font_size"]: + l.add_theme_font_size_override(slot, font_size) + + +## Same as label() but in the Rokkitt display face (result chips). +static func display_label(text: String, font_size: int, color: Color, zoomable: bool = false) -> RichTextLabel: + var l := label(text, font_size, color, zoomable, false) + var f := Style.display(zoomable) + l.add_theme_font_override("normal_font", f) + l.add_theme_font_override("bold_font", Style.display(zoomable, 900)) + return l + + +## Connects a label's [url] metas to the details pop-up. +static func hook_hover(l: RichTextLabel, main: Main) -> void: + l.meta_hover_started.connect(func(meta: Variant) -> void: + main.details().show_meta(l, str(meta))) + l.meta_hover_ended.connect(func(_meta: Variant) -> void: + main.details().hide_for(l)) + # A click (or a tap, where there's no hover) opens the same pop-up. + l.meta_clicked.connect(func(meta: Variant) -> void: + main.details().show_meta(l, str(meta))) + + +## Small muted ⓘ appended to text that has hover details. +static func info_mark(on_felt: bool = false) -> String: + var c := Style.ON_FELT_MUTED if on_felt else Color("#9a9483") + return " [font_size=12][color=#%s]%s[/color][/font_size]" % [c.to_html(false), INFO_MARK] + + +## Escapes text so it shows exactly as typed. +static func plain(text: String) -> String: + return text.replace("[", "[lb]") + + +## Readable BBCode for an entry's text as written (not rolled): each [[reference]] +## becomes a small teal chip with the table's name, {variables} show in brass, +## and a missing table shows the warning marker. References are wrapped in +## [url=table:id] so hovering them shows the table's details. +static func preview(text: String, board: TowerBoard) -> String: + if not text.contains("[[") and not text.contains("{"): + return text + var out := "" + var i := 0 + var n := text.length() + while i < n: + var c := text[i] + if c == "[" and i + 1 < n and text[i + 1] == "[": + var close := text.find("]]", i + 2) + var body := text.substr(i + 2, close - i - 2) if close >= 0 else "" + if close >= 0 and body.strip_edges() != "" and not body.contains("[") and not body.contains("]") and not body.contains("\n"): + out += _ref_chip(body, board) + i = close + 2 + continue + out += c + i += 1 + continue + if c == "[": + var tag := Formatter.tag_at(text, i) + if not tag.is_empty(): + out += tag["raw"] + i += (tag["raw"] as String).length() + continue + elif c == "{": + var m := _vre().search(text, i) + if m != null and m.get_start() == i: + var vname := m.get_string(1) + var shown := "{%s}" % vname + out += "[url=var:%s][color=#%s]%s[/color][/url]" % [vname, VAR_INK.to_html(false), shown] + var from := m.get_string(2).strip_edges() + if from != "": + var id := Roller.resolve(board, from) + if id == "": + out += " " + _bad(TextExpander.missing_marker(from), false) + i = m.get_end() + continue + out += c + i += 1 + return Formatter.close_open_tags(out) + + +static func _ref_chip(body: String, board: TowerBoard) -> String: + var name := body + var save := "" + var arrow := body.rfind("->") + if arrow >= 0: + save = body.substr(arrow + 2).strip_edges() + name = body.substr(0, arrow) + name = name.strip_edges() + var count := "" + var id := Roller.resolve(board, name) + if id == "": + var m := _cre().search(name) + if m != null: + count = (m.get_string(1) + "×") if m.get_string(1) != "" else (m.get_string(2) + "×") + name = m.get_string(3).strip_edges() + id = Roller.resolve(board, name) + if id == "": + return _bad(TextExpander.missing_marker(name), false) + var t := board.get_table(id) + var label_text := count + plain(Formatter.strip_tags(t.name)) + if save != "": + label_text += " → " + plain(save) + return "[url=table:%s][bgcolor=#%s][color=#%s] %s [/color][/bgcolor][/url]" % [id, REF_BG.to_html(false), REF_INK.to_html(false), label_text] + + +## Colours the internal markers of rolled text: table rolls in teal, variables in +## brass, and missing / unset / too-deep markers in red, so they're visible. +static func decorate(bbcode: String, on_felt: bool = false) -> String: + if not bbcode.contains("[url="): + return bbcode + var out := "" + var open: Array[String] = [] + for t: Dictionary in Formatter.tokenize(bbcode): + if t["name"] == "url": + if t["kind"] == "open": + var meta := (t["param"] as String).trim_prefix("=").strip_edges().trim_prefix("\"").trim_suffix("\"") + var color := _marker_color(meta, on_felt) + out += t["raw"] + if color != "": + out += "[color=#%s]" % color + open.append(color) + continue + elif not open.is_empty(): + if open.pop_back() != "": + out += "[/color]" + out += t["raw"] + return out + + +static func _marker_color(meta: String, on_felt: bool) -> String: + if meta.begins_with("table:"): + return (REF_INK_FELT if on_felt else REF_INK).to_html(false) + if meta.begins_with("var:"): + return (VAR_INK_FELT if on_felt else VAR_INK).to_html(false) + if meta.begins_with("missing:") or meta.begins_with("unset:") or meta.begins_with("deep:"): + return (BAD_INK_FELT if on_felt else Style.DANGER_INK).to_html(false) + return "" + + +static func _bad(marker: String, on_felt: bool) -> String: + return decorate(marker, on_felt) + + +static func _vre() -> RegEx: + if _var_re == null: + _var_re = RegEx.new() + _var_re.compile(_VAR_PATTERN) + return _var_re + + +static func _cre() -> RegEx: + if _count_re == null: + _count_re = RegEx.new() + _count_re.compile(_COUNT_PATTERN) + return _count_re diff --git a/ui/rich_text.gd.uid b/ui/rich_text.gd.uid new file mode 100644 index 0000000..447c824 --- /dev/null +++ b/ui/rich_text.gd.uid @@ -0,0 +1 @@ +uid://cftrtp5fjrga2 diff --git a/ui/table_card.gd b/ui/table_card.gd index 76bd7e8..b6ccb3c 100644 --- a/ui/table_card.gd +++ b/ui/table_card.gd @@ -5,6 +5,8 @@ extends PanelContainer ## mode, the table's shape, or (when collapsed) the lit result changes. const WIDTH := 256.0 +## Build mode has more controls per row, so cards are a little wider there. +const BUILD_WIDTH := 300.0 const LONG_LIST := 12 const LIST_HEIGHT := 432.0 const INLET_Y := 30.0 @@ -34,6 +36,11 @@ var _style_normal: StyleBoxFlat var _style_rolling: StyleBoxFlat var _style_dragging: StyleBoxFlat var _style_drop: StyleBoxFlat +var _deck_row: Control +var _deck_label: Label +## Entry ids whose details editor is open (Build mode). +var _open_details: Dictionary = {} +var _table_details_open := false func setup(p_main: Main, p_table: RollTable) -> void: @@ -80,12 +87,23 @@ func rebuild() -> void: _more_label = null list_scroll = null _flick_id = "" + _deck_row = null + _deck_label = null var build := main.mode == Main.Mode.BUILD + custom_minimum_size = Vector2(card_width(), 0) + _shrink.call_deferred() var ranged := table.is_ranged() var col := _vbox(0) add_child(col) col.add_child(_make_header(build, ranged)) + if build and _table_details_open: + var ted := _details_editor(table.details, "Details for this table (BBCode)", 12.0, + func(s: String) -> void: + table.details = s + main.mark_dirty()) + ted.add_theme_constant_override("margin_top", 8) + col.add_child(ted) var pad := MarginContainer.new() pad.mouse_filter = MOUSE_FILTER_PASS @@ -113,6 +131,11 @@ func rebuild() -> void: continue _list_box.add_child(_make_row(e, i, build, ranged, numw)) _set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL) + if build and _open_details.has(e.id): + _list_box.add_child(_details_editor(e.details, "Details for this result (BBCode)", 12.0 + numw + 4.0, + func(s: String) -> void: + e.details = s + main.mark_dirty())) if table.collapsed: _list_box.add_child(_make_more_row(numw)) @@ -171,7 +194,9 @@ func _make_header(build: bool, ranged: bool) -> Control: header.gui_input.connect(_on_header_input.bind(header)) var row := _hbox(8) - header.add_child(row) + var head_box := _vbox(4) + header.add_child(head_box) + head_box.add_child(row) var chevron := ChevronButton.new() chevron.open = not table.collapsed @@ -180,6 +205,11 @@ func _make_header(build: bool, ranged: bool) -> Control: chevron.pressed.connect(func() -> void: main.toggle_collapse(table.id)) row.add_child(chevron) + header.mouse_entered.connect(func() -> void: + if not _dragging and main.mode == Main.Mode.PLAY: + main.details().show_table(header, table.id, true) + ) + if build: var name_edit := LineEdit.new() name_edit.text = table.name @@ -194,17 +224,42 @@ func _make_header(build: bool, ranged: bool) -> Control: main.mark_dirty() ) row.add_child(name_edit) + var gear := Button.new() + gear.text = "⚙" + gear.tooltip_text = "Table settings" + gear.custom_minimum_size = Vector2(26, 26) + gear.size_flags_vertical = SIZE_SHRINK_CENTER + gear.add_theme_font_size_override("font_size", 16) + Style.skin_button(gear, Style.box(Color(0, 0, 0, 0), 6), Style.box(Color("#e6dfcd"), 6), Style.box(Color("#e6dfcd"), 6), Style.MUTED, Style.INK) + gear.pressed.connect(func() -> void: main.request_table_settings(table.id)) + row.add_child(gear) else: var titles := _vbox(3) titles.size_flags_horizontal = SIZE_EXPAND_FILL titles.size_flags_vertical = SIZE_SHRINK_CENTER - var title := Style.make_label(table.name, Style.display(true), 20, Style.INK) + titles.mouse_filter = MOUSE_FILTER_IGNORE + var title := Style.make_label(Formatter.strip_tags(table.name), Style.display(true), 20, Style.INK) title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART - titles.add_child(title) + if table.details.strip_edges() != "": + # A small ⓘ after the name says hovering shows the table's details. + var name_row := _hbox(4) + name_row.mouse_filter = MOUSE_FILTER_IGNORE + title.size_flags_horizontal = SIZE_EXPAND_FILL + name_row.add_child(title) + var mark := Style.make_label(RichText.INFO_MARK, Style.body(true), 12, Color("#9a9483")) + mark.size_flags_vertical = SIZE_SHRINK_CENTER + name_row.add_child(mark) + titles.add_child(name_row) + else: + titles.add_child(title) if ranged or table.collapsed: var count := "%d %s" % [table.entries.size(), "ranges" if ranged else "results"] - titles.add_child(Style.make_label(count, Style.body(true), 12, Style.MUTED)) + var cl := Style.make_label(count, Style.body(true), 12, Style.MUTED) + cl.mouse_filter = MOUSE_FILTER_IGNORE + titles.add_child(cl) row.add_child(titles) + if table.card_mode: + _deck_row = _make_deck_row() var die := table.die_size() var roll := Button.new() @@ -229,9 +284,46 @@ func _make_header(build: bool, ranged: bool) -> Control: roll.resized.connect(func() -> void: _die_icon.position = Vector2(8, (roll.size.y - 20.0) / 2.0 - 1.0)) roll.pressed.connect(func() -> void: main.start_roll(table.id)) row.add_child(roll) + if _deck_row != null: + head_box.add_child(_deck_row) return header +## Card mode: "4 / 6 left" and a small Reshuffle link under the title. +func _make_deck_row() -> Control: + var h := _hbox(6) + var pad := Control.new() + pad.custom_minimum_size = Vector2(26, 0) + pad.mouse_filter = MOUSE_FILTER_IGNORE + h.add_child(pad) + _deck_label = Style.make_label("", Style.body(true), 12, Style.MUTED) + _deck_label.size_flags_vertical = SIZE_SHRINK_CENTER + _deck_label.mouse_filter = MOUSE_FILTER_IGNORE + h.add_child(_deck_label) + var b := Button.new() + b.text = "↻ Reshuffle" + b.tooltip_text = "Put every card back in the deck" + b.add_theme_font_override("font", Style.body(true)) + b.add_theme_font_size_override("font_size", 12) + b.size_flags_vertical = SIZE_SHRINK_CENTER + var n := Style.box(Color(0, 0, 0, 0), 5, [5, 0, 5, 1]) + var hv := Style.box(Color("#e6dfcd"), 5, [5, 0, 5, 1]) + Style.skin_button(b, n, hv, hv, Style.COPPER, Style.INK) + b.pressed.connect(func() -> void: main.reshuffle_table(table.id)) + h.add_child(b) + update_deck() + return h + + +## Refreshes the cards-left count of a card-mode table. +func update_deck() -> void: + if _deck_label == null or not is_instance_valid(_deck_label): + return + var left := main.cards_left(table.id) + _deck_label.text = "%d / %d left" % [left.x, left.y] + _deck_label.add_theme_color_override("font_color", Style.DANGER_INK if left.x == 0 else Style.MUTED) + + func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float) -> Control: var row := PanelContainer.new() row.mouse_filter = MOUSE_FILTER_PASS @@ -255,8 +347,9 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float num.size_flags_vertical = SIZE_SHRINK_CENTER h.add_child(num) - var text: Label = null + var text: RichTextLabel = null if build: + h.add_theme_constant_override("separation", 4) var edit := LineEdit.new() edit.text = e.text edit.size_flags_horizontal = SIZE_EXPAND_FILL @@ -268,6 +361,30 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float main.mark_dirty() ) h.add_child(edit) + if not ranged: + h.add_child(_weight_edit(e)) + var info := Button.new() + info.text = "i" + info.toggle_mode = true + info.button_pressed = _open_details.has(e.id) + info.tooltip_text = "Details shown when hovering this result" + info.custom_minimum_size = Vector2(22, 22) + info.size_flags_vertical = SIZE_SHRINK_CENTER + info.add_theme_font_override("font", Style.body_bold(true)) + info.add_theme_font_size_override("font_size", 13) + var has := e.details.strip_edges() != "" + var inn := Style.bordered(Style.box(Color(0, 0, 0, 0), 11), 1, Style.COPPER if has else Style.DASH) + var inh := Style.bordered(Style.box(Color("#e6dfcd"), 11), 1, Style.COPPER) + var inp := Style.bordered(Style.box(Style.LIT, 11), 1, Style.COPPER) + Style.skin_button(info, inn, inh, inp, Style.COPPER if has else Style.MUTED, Style.INK) + info.toggled.connect(func(on: bool) -> void: + if on: + _open_details[e.id] = true + else: + _open_details.erase(e.id) + rebuild() + ) + h.add_child(info) var x := Button.new() x.text = "×" x.tooltip_text = "Delete this result" @@ -278,21 +395,87 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float x.pressed.connect(func() -> void: main.delete_entry(table.id, e.id)) h.add_child(x) else: - text = Style.make_label(e.text, Style.body(true), 16, Style.INK) - text.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + text = RichText.label(_row_text(e), 16, Style.INK, true) text.size_flags_horizontal = SIZE_EXPAND_FILL text.size_flags_vertical = SIZE_SHRINK_CENTER + RichText.hook_hover(text, main) h.add_child(text) + row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id)) if ranged: var pct := Style.make_label("%d%%" % roundi(table.chance(e) * 100.0), Style.body(true), 12, Style.MUTED) pct.size_flags_vertical = SIZE_SHRINK_CENTER h.add_child(pct) rows[e.id] = row - _row_parts[e.id] = {"num": num, "text": text} + _row_parts[e.id] = {"num": num, "text": text, "entry": e} return row +## Play-mode text of a row: the last rolled (expanded) text when the row is +## lit, otherwise the entry as written with its references shown readably. +func _row_text(e: TableEntry) -> String: + var rolled := main.lit_text(table.id, e.id) + var s := RichText.decorate(rolled) if rolled != "" else RichText.preview(e.text, main.data) + if e.details.strip_edges() != "": + s += RichText.info_mark() + return s + + +## Weight on a plain table, shown as ×N. Also the number of copies in card mode. +func _weight_edit(e: TableEntry) -> LineEdit: + var edit := LineEdit.new() + edit.text = "×%d" % e.weight + edit.custom_minimum_size = Vector2(34, 0) + edit.alignment = HORIZONTAL_ALIGNMENT_CENTER + edit.max_length = 4 + edit.tooltip_text = "Weight: how likely this result is, relative to the others (0 = never)" + edit.size_flags_vertical = SIZE_SHRINK_CENTER + edit.add_theme_font_override("font", Style.display(true)) + edit.add_theme_font_size_override("font_size", 14) + edit.add_theme_color_override("font_color", Style.MUTED) + var commit := func() -> void: + var digits := "" + for ch in edit.text: + if ch >= "0" and ch <= "9": + digits += ch + var w := clampi(digits.to_int(), 0, 999) if digits != "" else e.weight + edit.text = "×%d" % w + if w != e.weight: + e.weight = w + update_deck() + main.mark_dirty() + edit.text_submitted.connect(func(_t: String) -> void: commit.call()) + edit.focus_exited.connect(commit) + return edit + + +## A multi-line details editor (BBCode), shown under a row or the header. +func _details_editor(initial: String, placeholder: String, left: float, on_change: Callable) -> Control: + var wrap := MarginContainer.new() + wrap.mouse_filter = MOUSE_FILTER_PASS + wrap.add_theme_constant_override("margin_left", int(left)) + wrap.add_theme_constant_override("margin_right", 12) + wrap.add_theme_constant_override("margin_top", 2) + wrap.add_theme_constant_override("margin_bottom", 6) + var te := TextEdit.new() + te.text = initial + te.placeholder_text = placeholder + te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY + te.custom_minimum_size = Vector2(0, 66) + te.scroll_fit_content_height = true + te.add_theme_font_override("font", Style.body(true)) + te.add_theme_font_size_override("font_size", 13) + te.add_theme_color_override("font_color", Style.INK) + te.add_theme_color_override("font_placeholder_color", Style.MUTED) + te.add_theme_color_override("caret_color", Style.INK) + te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55)) + te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.RULE)) + te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.COPPER)) + te.text_changed.connect(func() -> void: on_change.call(te.text)) + wrap.add_child(te) + return wrap + + func _range_edit(e: TableEntry, is_lo: bool) -> LineEdit: var edit := LineEdit.new() edit.text = str(e.range_lo if is_lo else e.range_hi) @@ -305,7 +488,7 @@ func _range_edit(e: TableEntry, is_lo: bool) -> LineEdit: edit.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.RULE)) edit.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.COPPER)) var commit := func() -> void: - var v := clampi(edit.text.to_int(), 1, table.die_size()) + var v := clampi(edit.text.to_int(), table.min_value(), table.die_size()) if is_lo: e.range_lo = v else: @@ -391,11 +574,21 @@ func _make_footer(ranged: bool) -> Control: var add := _footer_button("+ Add range" if ranged else "+ Add result", Style.INK) add.pressed.connect(func() -> void: main.add_entry(table.id)) h.add_child(add) + var det := _footer_button("Details", Style.INK) + det.tooltip_text = "Details shown when hovering the table's name" + if table.details.strip_edges() != "": + det.add_theme_color_override("font_color", Style.COPPER) + det.pressed.connect(func() -> void: + _table_details_open = not _table_details_open + rebuild() + ) + h.add_child(det) var spacer := Control.new() spacer.size_flags_horizontal = SIZE_EXPAND_FILL spacer.mouse_filter = MOUSE_FILTER_IGNORE h.add_child(spacer) - var del := _footer_button("Delete table", Style.DANGER_INK) + var del := _footer_button("Delete", Style.DANGER_INK) + del.tooltip_text = "Delete this table" del.pressed.connect(func() -> void: main.delete_table(table.id)) h.add_child(del) return wrap @@ -432,9 +625,19 @@ func _set_row_state(eid: String, state: RowState) -> void: var num: Label = parts["num"] if num: num.add_theme_color_override("font_color", Style.INK if state == RowState.LIT else Style.MUTED) - var text: Label = parts["text"] + var text: RichTextLabel = parts["text"] if text: - text.add_theme_font_override("font", Style.body_bold(true) if state == RowState.LIT else Style.body(true)) + RichText.set_fonts(text, 16, true, state == RowState.LIT) + + +## Re-renders a Play-mode row's text (it shows the rolled text while lit). +func _update_row_text(eid: String) -> void: + var parts: Dictionary = _row_parts.get(eid, {}) + var text: RichTextLabel = parts.get("text") + if text: + var want := _row_text(parts["entry"]) + if text.text != want: + text.text = want func _apply_style() -> void: @@ -449,7 +652,11 @@ func _apply_style() -> void: func _shrink() -> void: - size = Vector2(WIDTH, 0) + size = Vector2(card_width(), 0) + + +func card_width() -> float: + return BUILD_WIDTH if main.mode == Main.Mode.BUILD else WIDTH func set_rolling(on: bool) -> void: @@ -486,6 +693,7 @@ func set_more_text(text: String) -> void: ## Updates highlights after a roll. Collapsed cards rebuild so the rolled result shows. func refresh_lit() -> void: + update_deck() if table.collapsed: var want: Array = [] for e in table.entries: @@ -497,6 +705,7 @@ func refresh_lit() -> void: _more_label.text = _more_text() return for eid in rows: + _update_row_text(eid) _set_row_state(eid, RowState.LIT if main.is_entry_lit(table.id, eid) else RowState.NORMAL) @@ -510,7 +719,7 @@ func reveal(eid: String) -> void: func hidden_has_pipes() -> bool: for e in table.entries: - if not rows.has(e.id) and not e.pipes.is_empty(): + if not rows.has(e.id) and (not e.pipes.is_empty() or not main.ref_targets_for(e).is_empty()): return true return false @@ -554,6 +763,7 @@ func _on_header_input(ev: InputEvent, header: Control) -> void: var mb := ev as InputEventMouseButton if mb and mb.button_index == MOUSE_BUTTON_LEFT: if mb.pressed: + main.details().hide_for() _dragging = true _drag_offset = main.board.world_mouse() - position get_parent().move_child(self, -1) diff --git a/ui/variables_panel.gd b/ui/variables_panel.gd new file mode 100644 index 0000000..7b296d8 --- /dev/null +++ b/ui/variables_panel.gd @@ -0,0 +1,113 @@ +class_name VariablesPanel +extends VBoxContainer +## The Variables tab of the result tray: the collection's persistent variables +## ({@name}), each editable, re-rollable from the table that set it, or +## clearable, and below them the last roll's chain variables (read only). + +const HEIGHT := 132.0 + +var main: Main +var _list: VBoxContainer +var _field: StyleBoxFlat +var _field_focus: StyleBoxFlat + + +func setup(p_main: Main) -> void: + main = p_main + add_theme_constant_override("separation", 0) + _field = Style.bordered(Style.box(Color(1, 1, 1, 0.05), 6, [8, 3, 8, 3]), 1, Color(1, 1, 1, 0.12)) + _field_focus = Style.bordered(Style.box(Color(1, 1, 1, 0.1), 6, [8, 3, 8, 3]), 1, Style.BRASS) + var scroll := ScrollContainer.new() + scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED + scroll.custom_minimum_size = Vector2(0, HEIGHT) + add_child(scroll) + _list = VBoxContainer.new() + _list.add_theme_constant_override("separation", 5) + _list.size_flags_horizontal = SIZE_EXPAND_FILL + scroll.add_child(_list) + + +func render() -> void: + for c in _list.get_children(): + _list.remove_child(c) + c.queue_free() + var names: Array = main.persistent_vars.keys() + names.sort_custom(func(a: Variant, b: Variant) -> bool: return str(a).naturalnocasecmp_to(str(b)) < 0) + if names.is_empty(): + var empty := RichText.label("No saved variables yet. A pipe that saves as [color=#%s]@name[/color], or [lb][lb]Table -> @name]] in a result, keeps its value here." % Style.BRASS.to_html(false), + 14, Style.ON_FELT_MUTED, false) + _list.add_child(empty) + for n in names: + _list.add_child(_var_row(str(n))) + + var chain: Dictionary = main.current.get("chain_vars", {}) + if not chain.is_empty(): + var head := Style.make_label("THIS ROLL", Style.caps(), 11, Style.ON_FELT_MUTED) + head.add_theme_constant_override("line_spacing", 0) + var gap := Control.new() + gap.custom_minimum_size = Vector2(0, 4) + _list.add_child(gap) + _list.add_child(head) + var keys: Array = chain.keys() + keys.sort() + for k in keys: + var line := RichText.label("[color=#%s]{%s}[/color] %s" % [RichText.VAR_INK_FELT.to_html(false), k, str(chain[k])], + 14, Style.ON_FELT, false) + _list.add_child(line) + + +func _var_row(name: String) -> Control: + var v: Dictionary = main.persistent_vars[name] if main.persistent_vars[name] is Dictionary else {"value": str(main.persistent_vars[name])} + var row := HBoxContainer.new() + row.add_theme_constant_override("separation", 6) + var label := Style.make_label("@" + name, Style.body_bold(), 14, RichText.VAR_INK_FELT) + label.custom_minimum_size = Vector2(84, 0) + label.clip_text = true + label.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS + label.tooltip_text = "{@%s}" % name + label.size_flags_vertical = SIZE_SHRINK_CENTER + row.add_child(label) + + var edit := LineEdit.new() + edit.text = str(v.get("value", "")) + edit.size_flags_horizontal = SIZE_EXPAND_FILL + edit.custom_minimum_size = Vector2(60, 0) + edit.add_theme_font_size_override("font_size", 14) + edit.add_theme_color_override("font_color", Style.ON_FELT) + edit.add_theme_color_override("caret_color", Style.ON_FELT) + edit.add_theme_color_override("selection_color", Color(Style.BRASS, 0.4)) + edit.add_theme_stylebox_override("normal", _field) + edit.add_theme_stylebox_override("focus", _field_focus) + edit.tooltip_text = "Edit the value (BBCode ok); Enter to save" + var commit := func() -> void: + if main.persistent_vars.has(name) and edit.text != str((main.persistent_vars[name] as Dictionary).get("value", "")): + main.set_variable(name, edit.text) + edit.text_submitted.connect(func(_t: String) -> void: + commit.call() + edit.release_focus()) + edit.focus_exited.connect(commit) + row.add_child(edit) + + var source := str(v.get("source", "")) + var st := main.data.get_table(source) if source != "" else null + var again := _icon_button("↻", "Re-roll from %s" % Formatter.strip_tags(st.name) if st else "No table to re-roll from") + again.disabled = st == null + again.pressed.connect(func() -> void: main.reroll_variable(name)) + row.add_child(again) + var clear := _icon_button("×", "Clear {@%s}" % name) + clear.pressed.connect(func() -> void: main.clear_variable(name)) + row.add_child(clear) + return row + + +func _icon_button(text: String, tip: String) -> Button: + var b := Button.new() + b.text = text + b.tooltip_text = tip + b.custom_minimum_size = Vector2(28, 26) + b.add_theme_font_size_override("font_size", 16) + var n := Style.bordered(Style.box(Color(1, 1, 1, 0.04), 6), 1, Color(1, 1, 1, 0.12)) + var h := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 6), 1, Color(1, 1, 1, 0.2)) + Style.skin_button(b, n, h, h, Style.ON_FELT_MUTED, Style.ON_FELT) + b.add_theme_color_override("font_disabled_color", Color(Style.ON_FELT_MUTED, 0.35)) + return b diff --git a/ui/variables_panel.gd.uid b/ui/variables_panel.gd.uid new file mode 100644 index 0000000..a2da7dc --- /dev/null +++ b/ui/variables_panel.gd.uid @@ -0,0 +1 @@ +uid://dgpghyp3ajb61