class_name LibraryStore extends RefCounted ## The saved collections: one JSON file per collection in /collections/. ## The file name is the collection id. Local state (decks, variables, history) ## lives in the paired StateStore and is dropped when a collection is deleted. const LEGACY_NAME := "My Tables" ## Folder that contains collections/. Default user://. var root: String var state: StateStore ## Messages about files that couldn't be read or written (most recent last). var errors: PackedStringArray = [] func _init(p_root: String = "user://", p_state: StateStore = null) -> void: root = p_root state = p_state if p_state else StateStore.new(p_root) func collections_dir() -> String: return root.path_join("collections") func path_for(id: String) -> String: return collections_dir().path_join(id + ".json") ## True for ids that are safe to use as a file name. static func is_valid_id(id: String) -> bool: if id == "": return false for c in id: if not (c in "abcdefghijklmnopqrstuvwxyz0123456789-_"): return false return true ## Lowercase letters, digits and dashes; "collection" if nothing is left. static func slugify(text: String) -> String: var out := "" for c in text.to_lower(): if c in "abcdefghijklmnopqrstuvwxyz0123456789": out += c elif not out.ends_with("-"): out += "-" out = out.trim_prefix("-").trim_suffix("-") return out if out != "" else "collection" func exists(id: String) -> bool: return is_valid_id(id) and FileAccess.file_exists(path_for(id)) ## [{id, name}] sorted by name. Unreadable files are skipped and noted in errors. func list() -> Array[Dictionary]: var out: Array[Dictionary] = [] var dir := DirAccess.open(collections_dir()) if dir == null: return out for fname in dir.get_files(): if fname.get_extension() != "json": continue var id := fname.get_basename() if not is_valid_id(id): continue var b := load_collection(id) if b: out.append({"id": id, "name": b.name}) out.sort_custom(func(a: Dictionary, b: Dictionary) -> bool: return str(a["name"]).naturalnocasecmp_to(str(b["name"])) < 0) return out ## Loads a collection, or returns null (and records why in errors) if it's ## missing or unreadable. The id always comes from the file name. func load_collection(id: String) -> TowerBoard: if not exists(id): return _fail("No collection '%s'." % id) var b := TowerBoard.new() if not b.load_json(FileAccess.get_file_as_string(path_for(id))): return _fail("Collection file %s is unreadable or not a collection." % path_for(id)) b.id = id if b.name == "": b.name = id return b ## Saves a collection under its id. Returns false (and records why) on failure. func save(board: TowerBoard) -> bool: if not is_valid_id(board.id): _fail("Can't save a collection with id '%s'." % board.id) return false var err := TowerBoard.write_text_atomic(path_for(board.id), board.to_json()) if err != OK: _fail("Couldn't save %s: %s" % [path_for(board.id), error_string(err)]) return false return true ## Makes and saves an empty collection with a unique id taken from the name. func create(coll_name: String) -> TowerBoard: var b := TowerBoard.new() b.name = coll_name.strip_edges() if coll_name.strip_edges() != "" else "Untitled" b.id = unique_id(slugify(b.name)) save(b) return b ## Changes the display name only; the id (and so the file and state) stays. func rename(id: String, new_name: String) -> bool: var b := load_collection(id) if b == null or new_name.strip_edges() == "": return false b.name = new_name.strip_edges() return save(b) ## Copies a collection (tables only; local state isn't copied). Returns the copy or null. func duplicate(id: String, new_name: String) -> TowerBoard: var b := load_collection(id) if b == null: return null b.name = new_name.strip_edges() if new_name.strip_edges() != "" else b.name + " copy" b.id = unique_id(slugify(b.name)) return b if save(b) else null ## Deletes the file and the collection's local state. func delete(id: String) -> bool: if not exists(id): return false if DirAccess.remove_absolute(path_for(id)) != OK: _fail("Couldn't delete %s." % path_for(id)) return false state.forget_collection(id) state.save() return true ## base, or base-2, base-3 ... whichever isn't taken. func unique_id(base: String) -> String: var id := base var n := 2 while exists(id): id = "%s-%d" % [base, n] n += 1 return id ## First run: if the old single-board file exists and there are no collections, ## imports it as a collection and renames the old file to board.json.bak. ## Returns the imported collection, or null if nothing was migrated. func migrate_legacy(legacy_path: String = "") -> TowerBoard: if legacy_path == "": legacy_path = root.path_join("board.json") if not FileAccess.file_exists(legacy_path) or not list().is_empty(): return null var b := TowerBoard.load_saved(legacy_path) if b == null: _fail("Old board file %s is unreadable; leaving it alone." % legacy_path) return null b.name = LEGACY_NAME b.id = unique_id(slugify(LEGACY_NAME)) if not save(b): return null DirAccess.remove_absolute(legacy_path + ".bak") if DirAccess.rename_absolute(legacy_path, legacy_path + ".bak") != OK: _fail("Imported %s but couldn't rename it to .bak." % legacy_path) return b func _fail(message: String) -> TowerBoard: errors.append(message) push_warning(message) return null