TableTower/core/formatter.gd

260 lines
9.4 KiB
GDScript3
Raw Permalink Normal View History

class_name Formatter
extends RefCounted
## BBCode helpers for Godot 4 RichTextLabel text: closing open tags, removing
## tags for plain-text spots, export without internal markers, and the allowed-tag
## filter for imported files.
##
## A "tag" here is only a tag Godot's RichTextLabel recognizes (see KNOWN_TAGS).
## Anything else in brackets, such as [x] or [optional], is ordinary text: Godot
## shows it as typed, and every function here leaves it alone.
##
## Internal markers (added by TextExpander, never typed by users) are url tags
## whose parameter starts with one of INTERNAL_META_PREFIXES, for example
## [url=table:loot]…[/url] or [url=missing:Gems]⚠ Gems[/url].
## Every tag name Godot 4's RichTextLabel parses.
const KNOWN_TAGS: Array[String] = [
"b", "i", "u", "s", "code", "char", "p", "center", "left", "right", "fill",
"indent", "url", "hint", "img", "font", "font_size", "opentype_features", "otf",
"lang", "dropcap", "color", "bgcolor", "fgcolor", "outline_size", "outline_color",
"table", "cell", "ul", "ol", "lb", "rb", "br", "hr", "lrm", "rlm", "lre", "rle",
"lro", "rlo", "pdf", "alm", "lri", "rli", "fsi", "pdi", "zwj", "zwnj", "wj", "shy",
"wave", "tornado", "shake", "fade", "rainbow", "pulse",
# The app's own effects (ui/text_effects).
"sparkle", "shimmer", "flash",
]
## Tags that stand alone and never take a closing tag.
const STANDALONE_TAGS: Array[String] = [
"lb", "rb", "br", "hr", "char", "lrm", "rlm", "lre", "rle", "lro", "rlo", "pdf",
"alm", "lri", "rli", "fsi", "pdi", "zwj", "zwnj", "wj", "shy",
]
## Tags kept by sanitize_import(). Godot lists have no item tag: inside [ul]/[ol]
## each line is one item.
const IMPORT_ALLOWED_TAGS: Array[String] = [
"b", "i", "u", "s", "code", "color", "font_size", "ul", "ol",
"center", "left", "right", "fill", "indent", "lb", "rb",
]
## url parameters with these prefixes are TextExpander's internal markers.
## "lore:" is a link to a Lore Entry (SheetLoreLinks): it means nothing outside the app.
const INTERNAL_META_PREFIXES: Array[String] = ["table:", "var:", "missing:", "unset:", "deep:", "error:", "lore:"]
## Matches one tag: [name], [/name], [name=param] or [name key=value ...].
## Parameters may contain quoted strings, so [url={"a":1}] is one tag.
const _TAG_PATTERN := "\\[(/?)([a-z_]+)((?:=|\\s)(?:\"[^\"\\n]*\"|[^\\[\\]\"\\n])*)?\\]"
static var _tag_re: RegEx = null
static var _param_res: Dictionary = {}
## Splits text into tokens, in order. Each token is a Dictionary:
## kind: "text" | "open" | "close" | "single"
## raw: String (the exact source text of the token)
## name: String (tag name, "" for text)
## param: String (everything after the name, such as "=red" or " bullet=*", "" if none)
static func tokenize(text: String) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var pos: int = 0
for m: RegExMatch in _tag_regex().search_all(text):
var name: String = m.get_string(2)
if not KNOWN_TAGS.has(name):
continue
var closing: bool = m.get_string(1) == "/"
var param: String = m.get_string(3)
if closing and param != "":
continue
if m.get_start() > pos:
out.append(_text_token(text.substr(pos, m.get_start() - pos)))
var kind: String = "close" if closing else ("single" if STANDALONE_TAGS.has(name) else "open")
out.append({"kind": kind, "raw": m.get_string(), "name": name, "param": param})
pos = m.get_end()
if pos < text.length():
out.append(_text_token(text.substr(pos)))
return out
## Returns the known tag that starts exactly at `pos`, as a token Dictionary
## (see tokenize), or an empty Dictionary when there is none.
static func tag_at(text: String, pos: int) -> Dictionary:
var m: RegExMatch = _tag_regex().search(text, pos)
if m == null or m.get_start() != pos:
return {}
var name: String = m.get_string(2)
if not KNOWN_TAGS.has(name):
return {}
var closing: bool = m.get_string(1) == "/"
if closing and m.get_string(3) != "":
return {}
var kind: String = "close" if closing else ("single" if STANDALONE_TAGS.has(name) else "open")
return {"kind": kind, "raw": m.get_string(), "name": name, "param": m.get_string(3)}
## Closes every tag left open at the end of `text`, so one entry's formatting
## can't spill into the rest of a result. A closing tag that skips over inner open
## tags ([b][i]x[/b]) first closes the inner ones. A closing tag with no matching
## open tag is escaped ([lb]/b]) so it can't close an outer tag from another entry.
static func close_open_tags(text: String) -> String:
var out: String = ""
var stack: Array[String] = []
for t: Dictionary in tokenize(text):
var kind: String = t["kind"]
var name: String = t["name"]
if kind == "open":
stack.append(name)
out += t["raw"]
elif kind == "close":
var at: int = stack.rfind(name)
if at < 0:
out += "[lb]" + (t["raw"] as String).substr(1)
continue
while stack.size() - 1 > at:
out += "[/%s]" % stack.pop_back()
stack.pop_back()
out += t["raw"]
else:
out += t["raw"]
while not stack.is_empty():
out += "[/%s]" % stack.pop_back()
return out
## Plain text for window titles, search, autocomplete and "Copy as text".
## Removes every known tag, turns [lb]/[rb] into brackets, [br] into a newline and
## [char=XXXX] into its character, drops [img] paths, and keeps unknown bracket
## text such as [x]. Internal markers become readable: a missing-table marker
## reads "⚠ Gems (missing table)", an unset variable "{hero?}".
static func strip_tags(text: String) -> String:
var out: String = ""
var urls: Array[String] = []
var in_img: int = 0
for t: Dictionary in tokenize(text):
var kind: String = t["kind"]
var name: String = t["name"]
if kind == "text":
if in_img == 0:
out += t["raw"]
elif kind == "single":
match name:
"lb": out += "["
"rb": out += "]"
"br": out += "\n"
"char":
var code: String = (t["param"] as String).trim_prefix("=").strip_edges()
if code.is_valid_hex_number():
out += String.chr(code.hex_to_int())
elif name == "img":
in_img = maxi(0, in_img + (1 if kind == "open" else -1))
elif name == "url":
if kind == "open":
urls.append(_meta_of(t["param"]))
elif not urls.is_empty():
if (urls.pop_back() as String).begins_with("missing:"):
out += " (missing table)"
return out
## Formatted text for "Copy as BBCode": keeps the user's formatting but removes
## the internal [url=table:/var:/missing:/unset:/deep:] wrappers (keeping the text
## inside them).
static func to_export_bbcode(text: String) -> String:
var out: String = ""
var urls: Array[bool] = []
for t: Dictionary in tokenize(text):
if t["name"] == "url":
if t["kind"] == "open":
var internal: bool = is_internal_meta(_meta_of(t["param"]))
urls.append(internal)
if internal:
continue
elif not urls.is_empty() and urls.pop_back():
continue
out += t["raw"]
return out
## Cleans text from an imported file. Only IMPORT_ALLOWED_TAGS survive, and only
## with harmless parameters ([color=red], [color=#ff0000], [font_size=20],
## [ul bullet=*], [ol type=a]). Every other tag is removed but its text is kept,
## except [img]…[/img], whose content (a path) is removed too. This means imported
## text can't load files, open links or forge internal markers. Unknown bracket
## text like [x] is kept. Open tags are closed at the end.
static func sanitize_import(text: String) -> String:
var out: String = ""
var in_img: int = 0
var kept: Array[String] = []
for t: Dictionary in tokenize(text):
var kind: String = t["kind"]
var name: String = t["name"]
if name == "img" and kind != "text":
in_img = maxi(0, in_img + (1 if kind == "open" else -1))
continue
if in_img > 0:
continue
if kind == "text":
out += t["raw"]
elif not IMPORT_ALLOWED_TAGS.has(name):
continue
elif kind == "close":
# Keep a closing tag only if its opening tag was kept.
var at: int = kept.rfind(name)
if at >= 0:
kept.remove_at(at)
out += t["raw"]
elif kind == "single" or _param_ok(name, t["param"]):
if kind == "open":
kept.append(name)
out += t["raw"]
return close_open_tags(out)
## Makes text show literally, so a real tag such as [b] is displayed as typed.
## Every "[" becomes "[lb]", which also stops [[references]] from expanding.
static func escape_literal(text: String) -> String:
return text.replace("[", "[lb]")
## True when a url parameter is one of TextExpander's internal markers.
static func is_internal_meta(meta: String) -> bool:
for p in INTERNAL_META_PREFIXES:
if meta.begins_with(p):
return true
return false
static func _meta_of(param: String) -> String:
var m: String = param.trim_prefix("=").strip_edges()
if m.length() >= 2 and m.begins_with("\"") and m.ends_with("\""):
m = m.substr(1, m.length() - 2)
return m
static func _param_ok(name: String, param: String) -> bool:
if param == "":
return name != "color" and name != "font_size"
var pattern: String = ""
match name:
"color": pattern = "^=(#[0-9A-Fa-f]{3,8}|[A-Za-z_]+)$"
"font_size": pattern = "^=\\d{1,3}$"
"ul": pattern = "^ bullet=[^\\[\\]\\s]{1,4}$"
"ol": pattern = "^ type=[1aAiI]$"
"indent": pattern = "^=\\d{1,2}$"
_: return false
if not _param_res.has(pattern):
var re := RegEx.new()
re.compile(pattern)
_param_res[pattern] = re
return (_param_res[pattern] as RegEx).search(param) != null
static func _tag_regex() -> RegEx:
if _tag_re == null:
_tag_re = RegEx.new()
_tag_re.compile(_TAG_PATTERN)
return _tag_re
static func _text_token(s: String) -> Dictionary:
return {"kind": "text", "raw": s, "name": "", "param": ""}