class_name TextExpander extends RefCounted ## Expands inline table references and variables in entry text. ## ## Syntax (expanded strictly left to right, so a chain variable must be saved ## before it's used): ## [[Table]] roll on Table and insert the result ## [[Table -> var]] ...and save it as chain variable "var" ## [[Table -> @var]] ...and save it as persistent variable "@var" ## [[3x Gems]] roll 3 times, joined with ", " ## [[1d4 Coins]] roll 1d4 for the count (NdM, NdM+K, NdM-K) ## {var} {@var} insert a saved value (numbers without ".0") ## {@var|Table} use the saved value, else roll on Table, save, insert ## {@skill_*} every set variable with that prefix, sorted: ## "Gun Combat 1, Pilot 0" ## {= expr} a computed value (see Expr), e.g. {= dm(@str)} ## ## Inserted pieces are wrapped in internal url tags so the UI can show hover ## pop-ups through RichTextLabel's meta_hover_started signal: ## [url=table:][/url] one roll on a table ## [url=var:][/url] a variable ("@town" for persistent ones) ## [url=missing:]⚠ [/url] a table that doesn't exist ## [url=unset:]{?}[/url] a variable that isn't set ## [url=deep:]⚠ chain too deep[/url] the depth limit was reached ## [url=error:expr]⚠ [/url] a {= expr} that couldn't be worked out ## {@prefix_*} lists and {= expr} values are inserted as plain text. ## ## BBCode is untouched: known tags (including ones with parameters such as ## [url={"a":1}]) are copied as-is, and ordinary bracket text like [x] stays text. ## A reference's name can't contain "[" or "]", so "[[b]x[/b]]" is not one. ## Use [lb] to write a literal "[[". ## ## expand() is the plain form. expand_async() is the coroutine form the roller ## uses, so that a reference into a choice card can wait for the player. ## render() shows text live (sheet cards, prompts) without rolling anything. ## Upper limit for [[Nx Table]] and [[NdM Table]] counts. const MAX_REPEAT := 100 const DEEP_TEXT := "⚠ chain too deep" const _VAR_PATTERN := "\\{(@?[A-Za-z_][A-Za-z0-9_]*)(?:\\|([^{}\\[\\]\\n]+))?\\}" const _LIST_PATTERN := "\\{@([A-Za-z0-9_]*)\\*\\}" const _COUNT_PATTERN := "^(?:(\\d+)\\s*[x×]|(\\d*)[dD](\\d+)(?:\\s*([+-])\\s*(\\d+))?)\\s+(\\S.*)$" const _SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$" static var _res: Dictionary = {} ## Expands `text` and returns: ## text: String the expanded BBCode, with open tags closed at the end ## children: Array the result nodes rolled inline, in order (one per roll, ## so [[3x Gems]] adds three) ## References roll through ctx.roll_table (or roll_table_async when it's set ## and never has to wait). static func expand(text: String, ctx: RollContext) -> Dictionary: var r: Variant = Callable(TextExpander, "expand_async").call(text, ctx) if r is Dictionary: return r push_warning("TextExpander.expand had to wait for a prompt; use expand_async.") return {"text": "", "children": []} ## Shows text live, without rolling: variables, {@prefix_*} lists and {= expr} ## are filled in, and a [[reference]] reads as the table's name (in a table: ## marker) instead of a roll. For sheet cards, prompts and previews. static func render(text: String, ctx: RollContext) -> String: var r: Variant = Callable(TextExpander, "expand_async").call(text, ctx, true) return str((r as Dictionary)["text"]) if r is Dictionary else "" ## Coroutine form of expand(). With `live`, nothing is rolled (see render()). static func expand_async(text: String, ctx: RollContext, live: bool = false) -> Dictionary: var out: String = "" var children: Array = [] var i: int = 0 var n: int = text.length() while i < n: var c: String = text[i] if c == "[": if i + 1 < n and text[i + 1] == "[": var ref: Dictionary = _ref_at(text, i) if not ref.is_empty(): if live: out += _live_ref(ref, ctx) else: out += await _expand_ref(ref, ctx, children) i = ref["end"] continue out += c i += 1 continue var tag: Dictionary = Formatter.tag_at(text, i) if not tag.is_empty(): out += tag["raw"] i += (tag["raw"] as String).length() continue elif c == "{": if i + 1 < n and text[i + 1] == "=": var close := _expr_end(text, i + 2) if close >= 0: out += _expand_expr(text.substr(i + 2, close - i - 2), ctx) i = close + 1 continue var lm: RegExMatch = _re(_LIST_PATTERN).search(text, i) if lm != null and lm.get_start() == i: out += Formatter.close_open_tags(ctx.list_text(lm.get_string(1))) i = lm.get_end() continue var m: RegExMatch = _re(_VAR_PATTERN).search(text, i) if m != null and m.get_start() == i: if live: out += _live_var(m.get_string(1), ctx) else: out += await _expand_var(m.get_string(1), m.get_string(2).strip_edges(), ctx, children) i = m.get_end() continue out += c i += 1 return {"text": Formatter.close_open_tags(out), "children": children} ## Index of the "}" closing a {= expr} that starts at `from`, outside quotes; ## -1 if there isn't one on the same line. static func _expr_end(text: String, from: int) -> int: var quote := "" for k in range(from, text.length()): var c := text[k] if quote != "": if c == quote: quote = "" elif c == "\"" or c == "'": quote = c elif c == "\n": return -1 elif c == "}": return k return -1 static func _expand_expr(src: String, ctx: RollContext) -> String: var r := Expr.evaluate(src.strip_edges(), ctx) if r["error"] != "": return error_marker(str(r["error"])) return Formatter.close_open_tags(Expr.format_value(r["value"])) ## The marker for a {= expr} that failed. static func error_marker(message: String) -> String: return "[url=error:expr]⚠ %s[/url]" % Formatter.escape_literal(message) static func _live_ref(ref: Dictionary, ctx: RollContext) -> String: var name: String = ref["name"] var id: String = ctx.resolve(name) if id == "": var count: Dictionary = _parse_count(name) if not count.is_empty(): name = count["name"] id = ctx.resolve(name) if id == "": return missing_marker(name) var shown := name if ctx.board != null and ctx.board.get_table(id) != null: shown = ctx.board.get_table(id).name return "[url=table:%s]%s[/url]" % [id, Formatter.close_open_tags(shown)] static func _live_var(name: String, ctx: RollContext) -> String: var value: Variant = ctx.lookup(name) if value != null: return "[url=var:%s]%s[/url]" % [name, Formatter.close_open_tags(str(value))] return unset_marker(name) ## Names of the tables referenced in `text`, without rolling, in order of first ## appearance and without duplicates. Covers [[...]] references (minus any count ## prefix and "-> var" part) and the table in {@var|Table}. With a resolver ## (func(name) -> id), a name like "3x Gems" that is itself a table name is kept ## whole, the same way expand() decides. static func references(text: String, resolve: Callable = Callable()) -> Array[String]: var out: Array[String] = [] var i: int = 0 var n: int = text.length() while i < n: var c: String = text[i] var name: String = "" if c == "[" and i + 1 < n and text[i + 1] == "[": var ref: Dictionary = _ref_at(text, i) if not ref.is_empty(): var whole: String = ref["name"] name = whole var count: Dictionary = _parse_count(whole) if not count.is_empty(): var whole_ok: bool = resolve.is_valid() and str(resolve.call(whole)) != "" if not whole_ok: name = count["name"] i = ref["end"] elif c == "[": var tag: Dictionary = Formatter.tag_at(text, i) if not tag.is_empty(): i += (tag["raw"] as String).length() continue elif c == "{": var m: RegExMatch = _re(_VAR_PATTERN).search(text, i) if m != null and m.get_start() == i: name = m.get_string(2).strip_edges() i = m.get_end() if name != "": if not out.has(name): out.append(name) continue i += 1 return out ## The marker for a reference to a table that doesn't exist. static func missing_marker(name: String) -> String: return "[url=missing:%s]⚠ %s[/url]" % [name, name] ## The marker for a variable that hasn't been saved. `name` includes any "@". static func unset_marker(name: String) -> String: return "[url=unset:%s]{%s?}[/url]" % [name, name] ## The marker for a reference past the depth limit. The roller can use it as the ## summary of a node it stopped for depth. static func deep_marker(table_id: String) -> String: return "[url=deep:%s]%s[/url]" % [table_id, DEEP_TEXT] ## Rolls an NdM+K expression ("1d4", "d6", "2d6+1", "3d8-2") with `rng`. ## Returns -1 when the expression isn't valid. static func roll_dice(expr: String, rng: RandomNumberGenerator) -> int: var m: RegExMatch = _re("^\\s*(\\d*)[dD](\\d+)\\s*(?:([+-])\\s*(\\d+))?\\s*$").search(expr) if m == null: return -1 return _roll_parts(m.get_string(1), m.get_string(2), m.get_string(3), m.get_string(4), rng) static func _roll_parts(num: String, sides: String, op: String, mod: String, rng: RandomNumberGenerator) -> int: var dice: int = int(num) if num != "" else 1 var faces: int = int(sides) if faces < 1 or dice > MAX_REPEAT: return -1 var total: int = 0 for _k in dice: total += rng.randi_range(1, faces) if mod != "": total += int(mod) if op == "+" else -int(mod) return total ## Parses "[[...]]" at `pos`. Returns {name, save, end} or {} if it isn't a ## valid reference (no closing "]]", empty, or containing "[", "]" or a newline). static func _ref_at(text: String, pos: int) -> Dictionary: var close: int = text.find("]]", pos + 2) if close < 0: return {} var body: String = text.substr(pos + 2, close - pos - 2) if body.strip_edges() == "" or body.contains("[") or body.contains("]") or body.contains("\n"): return {} var name: String = body var save_as: String = "" var arrow: int = body.rfind("->") if arrow >= 0: var target: String = body.substr(arrow + 2).strip_edges() if _re(_SAVE_PATTERN).search(target) != null: save_as = target name = body.substr(0, arrow) name = name.strip_edges() if name == "": return {} return {"name": name, "save": save_as, "end": close + 2} ## Splits "3x Gems" / "1d4+1 Coins" into {kind: "times"|"dice", ...parts, name}. static func _parse_count(name: String) -> Dictionary: var m: RegExMatch = _re(_COUNT_PATTERN).search(name) if m == null: return {} if m.get_string(1) != "": return {"kind": "times", "times": int(m.get_string(1)), "name": m.get_string(6).strip_edges()} return { "kind": "dice", "num": m.get_string(2), "sides": m.get_string(3), "sign": m.get_string(4), "mod": m.get_string(5), "name": m.get_string(6).strip_edges(), } static func _expand_ref(ref: Dictionary, ctx: RollContext, children: Array) -> String: var name: String = ref["name"] var times: int = 1 var id: String = ctx.resolve(name) if id == "": var count: Dictionary = _parse_count(name) if not count.is_empty(): name = count["name"] id = ctx.resolve(name) if count["kind"] == "times": times = count["times"] else: times = _roll_parts(count["num"], count["sides"], count["sign"], count["mod"], ctx.rng) times = clampi(times, 0, MAX_REPEAT) if id == "": return missing_marker(name) var pieces: PackedStringArray = [] var plain: PackedStringArray = [] for _k in times: if ctx.halted != "": break var piece: Dictionary = await _roll_one(id, ctx, children) pieces.append(piece["text"]) plain.append(piece["value"]) var save_as: String = ref["save"] if save_as != "" and ctx.halted == "": ctx.save(save_as, ", ".join(plain), id) return ", ".join(pieces) static func _expand_var(name: String, table: String, ctx: RollContext, children: Array) -> String: var value: Variant = ctx.lookup(name) if value != null: return "[url=var:%s]%s[/url]" % [name, Formatter.close_open_tags(str(value))] if table == "": return unset_marker(name) var id: String = ctx.resolve(table) if id == "": return missing_marker(table) if ctx.halted != "": return unset_marker(name) var piece: Dictionary = await _roll_one(id, ctx, children) if not piece["rolled"]: return piece["text"] ctx.save(name, piece["value"], id) return "[url=var:%s]%s[/url]" % [name, piece["value"]] ## One roll on a resolved table. Returns {text (wrapped for display), value ## (export BBCode, for saving), rolled (false for depth/missing markers)}. static func _roll_one(id: String, ctx: RollContext, children: Array) -> Dictionary: if ctx.depth > ctx.max_depth: var deep: String = deep_marker(id) return {"text": deep, "value": DEEP_TEXT, "rolled": false} var node: Dictionary = await ctx.roll_async(id) if node.is_empty(): var missing: String = missing_marker(id) return {"text": missing, "value": "", "rolled": false} children.append(node) var summary: String = Formatter.close_open_tags(str(node.get("summary", ""))) var value: String = Formatter.to_export_bbcode(summary) if node.has("answer"): value = Expr.format_value(node["answer"]) return { "text": "[url=table:%s]%s[/url]" % [id, summary], "value": value, "rolled": true, } static func _re(pattern: String) -> RegEx: if not _res.has(pattern): var re := RegEx.new() re.compile(pattern) _res[pattern] = re return _res[pattern]