TableTower/core/template_library.gd

159 lines
5.1 KiB
GDScript3
Raw Normal View History

class_name TemplateLibrary
extends RefCounted
## Saved templates (see TemplateKit), shared by every collection: one JSON
## file per template in <root>/templates/<slug>.json, plus the read-only
## built-in templates shipped in res://templates/. With an empty root the
## user's templates live in memory only (--sample runs and tests).
const BUILTIN_DIR := "res://templates"
const BUILTIN_PREFIX := "builtin:"
var root: String
var builtin_dir: String
## Messages about files that couldn't be read or written (most recent last).
var errors: PackedStringArray = []
var _memory: Dictionary = {} # id -> template, when root is ""
func _init(p_root: String = "user://", p_builtin_dir: String = BUILTIN_DIR) -> void:
root = p_root
builtin_dir = p_builtin_dir
func templates_dir() -> String:
return root.path_join("templates")
func path_for(id: String) -> String:
return templates_dir().path_join(id + ".json")
static func is_builtin(id: String) -> bool:
return id.begins_with(BUILTIN_PREFIX)
## [{id, name, description, kind, builtin, template}]: the built-in templates
## and the user's, sorted by name.
func list() -> Array[Dictionary]:
var out: Array[Dictionary] = []
for f in _json_files(builtin_dir):
var tpl := _read(builtin_dir.path_join(f))
if not tpl.is_empty():
out.append(_row(BUILTIN_PREFIX + f.get_basename(), tpl, true))
if root == "":
for id: String in _memory:
out.append(_row(id, _memory[id], false))
else:
for f in _json_files(templates_dir()):
var tpl2 := _read(templates_dir().path_join(f))
if not tpl2.is_empty():
out.append(_row(f.get_basename(), tpl2, false))
out.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
return str(a["name"]).naturalnocasecmp_to(str(b["name"])) < 0)
return out
func _row(id: String, tpl: Dictionary, builtin: bool) -> Dictionary:
return {"id": id, "name": str(tpl.get("name", id)), "description": str(tpl.get("description", "")),
"kind": str(tpl.get("kind", "selection")), "builtin": builtin, "template": tpl}
static func _json_files(dir: String) -> PackedStringArray:
var out := PackedStringArray()
if dir == "" or not DirAccess.dir_exists_absolute(dir):
return out
for f in DirAccess.get_files_at(dir):
if f.get_extension() == "json":
out.append(f)
return out
func _read(path: String) -> Dictionary:
var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(path))
var r := TemplateKit.validate(parsed)
if not r["ok"]:
errors.append("Template %s is unreadable: %s" % [path, "; ".join(r["errors"])])
return {}
return r["template"]
## The template with this id, or {}.
func get_template(id: String) -> Dictionary:
if is_builtin(id):
var p := builtin_dir.path_join(id.substr(BUILTIN_PREFIX.length()) + ".json")
return _read(p) if FileAccess.file_exists(p) else {}
if not LibraryStore.is_valid_id(id):
return {}
if root == "":
return (_memory.get(id, {}) as Dictionary).duplicate(true)
return _read(path_for(id)) if FileAccess.file_exists(path_for(id)) else {}
func exists(id: String) -> bool:
if root == "":
return _memory.has(id)
return LibraryStore.is_valid_id(id) and FileAccess.file_exists(path_for(id))
## Saves a new template under a unique slug of its name. Returns the id, or "".
func add(tpl: Dictionary) -> String:
var base := LibraryStore.slugify(str(tpl.get("name", "template")))
var id := base
var n := 2
while exists(id):
id = "%s-%d" % [base, n]
n += 1
return id if _write(id, tpl) else ""
func _write(id: String, tpl: Dictionary) -> bool:
if root == "":
_memory[id] = tpl.duplicate(true)
return true
var err := TowerBoard.write_text_atomic(path_for(id), JSON.stringify(tpl, " ", false))
if err != OK:
errors.append("Couldn't save %s: %s" % [path_for(id), error_string(err)])
return false
return true
## Renames a user template (the file keeps its id). Built-ins can't be renamed.
func rename(id: String, new_name: String) -> bool:
if is_builtin(id) or new_name.strip_edges() == "":
return false
var tpl := get_template(id)
if tpl.is_empty():
return false
tpl["name"] = new_name.strip_edges()
return _write(id, tpl)
## Deletes a user template. Built-ins can't be deleted.
func delete(id: String) -> bool:
if is_builtin(id) or not exists(id):
return false
if root == "":
return _memory.erase(id)
return DirAccess.remove_absolute(path_for(id)) == OK
## The template as file text, for exporting.
func export_text(id: String) -> String:
var tpl := get_template(id)
return JSON.stringify(tpl, " ", false) if not tpl.is_empty() else ""
## Imports template file text as a new user template.
## Returns {"ok", "id", "name", "errors"}.
func import_text(text: String) -> Dictionary:
var json := JSON.new()
if json.parse(text) != OK:
return {"ok": false, "id": "", "name": "", "errors": ["Not valid JSON (line %d): %s" % [json.get_error_line(), json.get_error_message()]]}
var r := TemplateKit.validate(json.data)
if not r["ok"]:
return {"ok": false, "id": "", "name": "", "errors": r["errors"]}
var id := add(r["template"])
if id == "":
return {"ok": false, "id": "", "name": "", "errors": ["Couldn't save the template."]}
return {"ok": true, "id": id, "name": str(r["template"]["name"]), "errors": []}