TableTower/ui/theme_store.gd

185 lines
6.6 KiB
GDScript3
Raw Normal View History

class_name ThemeStore
extends RefCounted
## Theme sets: the built-ins (BuiltinThemes) plus the user's own, saved as JSON
## in user://themes/ (their pictures and sounds in user://themes/<id>/; see
## docs/THEMES.md). apply() writes a set into Style's tokens; the app then
## rebuilds its UI (Main.restyle) so every control picks the new colours up.
## Where user sets live (a test points this elsewhere).
static var DIR := "user://themes/"
const DEFAULT_ID := "tarot"
const SETTING := "theme"
## Editor rows, in order: [token, label, basic?]. Basic rows show first; the
## rest sit under "More colours".
const TOKENS := [
["ON_BG", "Text on the background", true],
["CARD", "Card face", true],
["INK", "Card text", true],
["MUTED", "Card secondary text", true],
["THREAD", "Threads", true],
["ACCENT", "Highlight (lit and selected)", true],
["TRIM", "Trim and headings", true],
["GLOW", "Magic sparkles", true],
["SELECTED", "Selected card outline", true],
["CARD_HEAD", "Card header", true],
["BG", "Background (flat)", false],
["BG_DEEP", "Background shadow", false],
["BG_HOVER", "Background buttons, hover", false],
["PANEL", "Panels (flat)", false],
["ON_BG_MUTED", "Secondary text on the background", false],
["CARD_SOFT", "Boxes on cards", false],
["CARD_HOVER", "Card buttons, hover", false],
["CARD_SHADE", "Card shading", false],
["FAINT", "Faint text", false],
["RULE", "Lines on cards", false],
["DASH", "Dashed outlines", false],
["HOVER_ROW", "Result row, hover", false],
["STRIPE", "Striped rows", false],
["TRIM_DARK", "Trim, dark", false],
["THREAD_DARK", "Threads, dark edge", false],
["ACCENT_DARK", "Highlight, dark", false],
["LIT", "Lit result", false],
["FLICK", "Rolling flicker", false],
["PULSE", "Thread pulse", false],
["DANGER", "Danger", false],
["DANGER_INK", "Danger text", false],
["BAD_INK_ON_BG", "Problem text on the background", false],
["WARN_BG", "Warning box", false],
["WARN_INK", "Warning text", false],
["OK_INK", "Success outlet", false],
["NO_INK", "Failure outlet", false],
["REF_INK", "Table link text", false],
["REF_BG", "Table link box", false],
["REF_INK_ON_BG", "Table link on the background", false],
["VALUE_INK", "Value text", false],
["VALUE_INK_ON_BG", "Value text on the background", false],
["VALUE_BG", "Value box", false],
["VALUE_BORDER", "Value box border", false],
]
const PATTERNS := [["none", "None"], ["dots", "Dots"], ["stars", "Stars"]]
const LOGOS := [["fortune_teller", "Morgan (fortune teller)"], ["mascot", "The theme's own mascot"], ["tower", "Tower"], ["none", "None"]]
const CARD_FRAMES := [["ornate", "Beaded"], ["art", "The theme's own frame"], ["plain", "Plain"]]
## The open spread, handed across the scene reload that applies a theme.
static var carry_board: TowerBoard = null
## The active set (also kept here so --sample runs, which don't save, keep it).
static var current: Dictionary = {}
static var _fallback: Dictionary = {}
## Every set: built-ins first, then the user's, by name.
static func all() -> Array[Dictionary]:
var out: Array[Dictionary] = BuiltinThemes.all()
var mine: Array[Dictionary] = []
var d := DirAccess.open(DIR)
if d:
for f in d.get_files():
if f.ends_with(".json"):
var t: Variant = JSON.parse_string(FileAccess.get_file_as_string(DIR + f))
if t is Dictionary:
t["builtin"] = false
mine.append(t)
mine.sort_custom(func(a: Dictionary, b: Dictionary) -> bool: return str(a.get("name", "")).naturalnocasecmp_to(str(b.get("name", ""))) < 0)
out.append_array(mine)
return out
static func find(id: String) -> Dictionary:
for t in all():
if str(t.get("id", "")) == id:
return t
return BuiltinThemes.TAROT
## Saves a user set and returns its id. Built-in ids can't be overwritten:
## saving one makes a copy.
static func save(t: Dictionary) -> String:
var out := t.duplicate(true)
var id := str(out.get("id", ""))
# A copy of a built-in theme uses the built-in's files: name them in full.
if bool(t.get("builtin", false)) or _is_builtin(id):
out = ThemeAssets.pin_paths(out, ThemeAssets.folder(t))
if id == "" or bool(out.get("builtin", false)) or _is_builtin(id):
id = _new_id(str(out.get("name", "My theme")))
out["id"] = id
out.erase("builtin")
DirAccess.make_dir_recursive_absolute(DIR)
var f := FileAccess.open(DIR + id + ".json", FileAccess.WRITE)
if f:
f.store_string(JSON.stringify(out, "\t"))
return id
static func delete(id: String) -> void:
if not _is_builtin(id):
DirAccess.remove_absolute(DIR + id + ".json")
## Writes a set into Style. Tokens the set doesn't list get the fallback value,
## so switching sets never leaves colours behind.
static func apply(t: Dictionary) -> void:
var sc: Script = Style
if _fallback.is_empty():
for row: Array in TOKENS:
_fallback[row[0]] = sc.get(row[0])
var colors: Dictionary = t.get("colors", {})
for row: Array in TOKENS:
var tok: String = row[0]
sc.set(tok, Color.from_string(str(colors[tok]), _fallback[tok]) if colors.has(tok) else _fallback[tok])
if not colors.has("CARD_HEAD"):
# Darker than the card face, so card text stays readable in every theme.
Style.CARD_HEAD = Style.CARD.lerp(Style.CARD_SHADE, 0.85)
Style.BG_FILL = t.get("background", {})
Style.PANEL_FILL = t.get("panel", {})
Style.PATTERN = str(t.get("pattern", "dots"))
Style.LOGO = str(t.get("logo", "none"))
Style.CARD_FRAME = str(t.get("card_frame", "plain"))
Style.set_fonts(str(t.get("font_body", "")), str(t.get("font_display", "")))
current = t
ThemeAssets.clear_cache()
FrameSet.active = FrameSet.for_theme(t)
ThreadStrip.active = ThreadStrip.for_theme(t)
## Applies a set, remembers it, and rebuilds the app's UI around the open spread.
static func use(m: Main, t: Dictionary) -> void:
apply(t)
if m.state:
m.state.set_setting(SETTING, str(t.get("id", DEFAULT_ID)))
m.state.save()
m._save_now()
carry_board = m.data
if m.screens:
m.screens.keep_for_reload()
m.get_tree().reload_current_scene.call_deferred()
## Every token's colour for a set (its own, else the fallback), as "#hex".
static func resolved_colors(t: Dictionary) -> Dictionary:
var colors: Dictionary = t.get("colors", {})
var out := {}
for row: Array in TOKENS:
var fb: Color = _fallback.get(row[0], (Style as Script).get(row[0]))
out[row[0]] = str(colors[row[0]]) if colors.has(row[0]) else "#" + fb.to_html(true)
return out
static func _is_builtin(id: String) -> bool:
for t in BuiltinThemes.all():
if t["id"] == id:
return true
return false
static func _new_id(name: String) -> String:
var base := name.to_lower().replace(" ", "-").validate_filename()
if base == "":
base = "theme"
var id := base
var n := 2
while _is_builtin(id) or FileAccess.file_exists(DIR + id + ".json"):
id = "%s-%d" % [base, n]
n += 1
return id