using System; using System.Collections.Generic; using System.IO; using System.Linq; using Verse; namespace BlaxDefaults { /// What DefaultsFile.Load found. public sealed class LoadResult { public List Entries = new List(); /// The file the entries came from (main or .bak), null when none loaded. public string LoadedFrom; /// Full paths of the broken copies made by this load (Defaults.broken-<timestamp>.xml and the like). public List BrokenCopies = new List(); /// No file loaded and every file that existed failed (each was renamed to a broken copy): the library starts empty. public bool BothFailed; /// Entries of the loaded file whose class this version doesn't have; written back on every write. public List Unknown = new List(); /// The loaded file's formatVersion; 0 when nothing loaded. public int FormatVersion; /// /// Defaults files still in place that nothing was read from: the read was skipped (the game was saving or /// loading), failed with an exception, or a broken file could not be renamed. DefaultsLibrary reads /// again once and moves what is still unread aside before its first write. /// public List Unread = new List(); /// Where DefaultsLibrary moved the unread files before its first write (Defaults.unread-<timestamp>.xml). public List UnreadCopies = new List(); /// The file came from a newer version of Blax Defaults: this version reads it but never writes it. public bool FromNewerVersion => FormatVersion > DefaultsLibrary.FormatVersion; } /// /// The defaults in memory, one entry per kind, global and shared by every save. Read once at startup from /// DefaultsFile; every Set or Forget writes the whole file through DefaultsFile.Write. Get returns the /// live entry: never edit it in place, edit a Clone() and Set that. Nothing here touches a save. /// /// Two guards keep the file safe when the startup load could not use it. A file left unread in place /// (LoadResult.Unread: the game was saving or loading, an exception, a broken file that could not be /// renamed) is read again once, on the first use with the Scribe free; whatever is still unread then is /// moved aside (Defaults.unread-<timestamp>.xml) before the first write, so the write's rotation into /// .bak can't drop it. A file of a newer format version is read but never written, since this version /// would drop the fields that version added. /// public static class DefaultsLibrary { /// /// The defaults file format. Bump it whenever a release adds a kind of entry (a DefaultsEntry subclass) /// or a field to one: an older version then reads the file, keeps the entries it can't load, and never /// writes the file, so it can't drop what the newer version saved. /// public const int FormatVersion = 1; private static readonly Dictionary entries = new Dictionary(StringComparer.Ordinal); /// The startup load left a file unread in place: read it again on the next use. private static bool retryPending; private static bool warnedNewer; /// Raised after an entry is set or forgotten (not after a test restore). public static event Action Changed; /// True once the startup load ran, whatever it found. public static bool LoadedAtStartup { get; private set; } /// /// The last load's result (the startup load, or its retry): broken and unread copies, whether both files /// failed, the entries of a newer version (for the settings page and the next write). /// public static LoadResult LastLoad { get; private set; } = new LoadResult(); /// False when the last write failed or was refused; the file then still holds the previous content. public static bool LastWriteOk { get; private set; } = true; /// True while the read the startup load skipped is still to be retried. public static bool RetryPending => retryPending; /// The loaded file came from a newer version: Set and Forget work in memory, the file is never written. public static bool ReadOnly => LastLoad.FromNewerVersion; /// Every entry, ordered by key. public static List All { get { EnsureLoaded(); return entries.Values.OrderBy(e => e.key, StringComparer.Ordinal).ToList(); } } public static int Count { get { EnsureLoaded(); return entries.Count; } } public static bool Has(string key) { EnsureLoaded(); return key != null && entries.ContainsKey(key); } public static DefaultsEntry Get(string key) { EnsureLoaded(); return key != null && entries.TryGetValue(key, out DefaultsEntry e) ? e : null; } public static T Get(string key) where T : DefaultsEntry => Get(key) as T; /// Entries whose key starts with this prefix, ordered by key. public static List WithPrefix(string prefix) { EnsureLoaded(); return entries.Values.Where(e => e.key.StartsWith(prefix, StringComparison.Ordinal)).OrderBy(e => e.key, StringComparer.Ordinal).ToList(); } /// Adds or replaces the entry with its key and writes the file. Returns whether the write succeeded. public static bool Set(DefaultsEntry entry) { if (entry == null || entry.key.NullOrEmpty()) throw new ArgumentException("A defaults entry needs a key."); EnsureLoaded(); entries[entry.key] = entry; return WriteAndNotify(); } /// Adds or replaces several entries and writes the file once. Returns whether the write succeeded. public static bool SetMany(IEnumerable batch) { List list = batch?.ToList() ?? new List(); if (list.Any(e => e == null || e.key.NullOrEmpty())) throw new ArgumentException("A defaults entry needs a key."); EnsureLoaded(); foreach (DefaultsEntry e in list) entries[e.key] = e; return WriteAndNotify(); } /// Removes the entry and writes the file. False when there was no such entry. public static bool Forget(string key) { EnsureLoaded(); if (key == null || !entries.Remove(key)) return false; WriteAndNotify(); return true; } /// Reads the file into memory. Called once from BlaxDefaultsStartup; writes nothing. public static void LoadAtStartup() { Install(DefaultsFile.Load() ?? new LoadResult(), retry: true); LoadedAtStartup = true; } /// Clones of every entry, for a test to restore later. public static List Snapshot() { EnsureLoaded(); return entries.Values.Select(e => e.Clone()).ToList(); } /// Puts a snapshot back in memory without writing the file. Tests only. public static void RestoreForTests(List snapshot) => Replace(snapshot); /// Replaces the whole library in memory without writing the file. For DefaultsFile tests that reload. public static void ReplaceInMemory(IEnumerable loaded) => Replace(loaded); /// /// Tests only: puts a load result in place as the startup load does (its entries in memory, LastLoad, /// and with retry a pending read of its unread files), without touching the files. /// public static void InstallLoadForTests(LoadResult result, bool retry) { Install(result ?? new LoadResult(), retry); warnedNewer = false; } private static void Install(LoadResult r, bool retry) { LastLoad = r; Replace(r.Entries); retryPending = retry && r.LoadedFrom == null && r.Unread.Count > 0; } /// /// The retry of a startup read that left a file unread: once, on the first use with the Scribe free. /// Entries set meanwhile (in memory only: a write needs the Scribe free too) win over the file's. /// private static void EnsureLoaded() { if (!retryPending || Scribe.mode != LoadSaveMode.Inactive) return; retryPending = false; List meanwhile = entries.Values.ToList(); LoadResult r; try { r = DefaultsFile.Load() ?? new LoadResult(); } catch (Exception e) { Log.Error("[Blax Defaults] Reading the defaults file again failed: " + e); return; } Install(r, retry: false); foreach (DefaultsEntry e in meanwhile) entries[e.key] = e; if (r.LoadedFrom != null) Log.Message("[Blax Defaults] The defaults file was read on a second try: " + r.Entries.Count + " defaults from " + r.LoadedFrom + "."); } private static void Replace(IEnumerable loaded) { entries.Clear(); if (loaded == null) return; foreach (DefaultsEntry e in loaded) { if (e != null && !e.key.NullOrEmpty()) entries[e.key] = e; } } private static bool WriteAndNotify() { bool ok; try { ok = Write(); } catch (Exception e) { Log.Error("[Blax Defaults] Writing the defaults file failed: " + e); ok = false; } LastWriteOk = ok; try { Changed?.Invoke(); } catch (Exception e) { Log.Error("[Blax Defaults] A listener of DefaultsLibrary.Changed failed: " + e); } return ok; } /// /// The file write behind both guards: refused for a newer version's file; unread files moved aside /// first; the entries of a newer version written back, except those whose key the library has now. /// private static bool Write() { if (ReadOnly) { if (!warnedNewer) { warnedNewer = true; Log.Warning("[Blax Defaults] The defaults file was made by a newer version of Blax Defaults (format " + LastLoad.FormatVersion + "), so this version does not write it. Your change works until you quit."); } return false; } if (!SetAsideUnread()) return false; List all = All; var keys = new HashSet(all.Select(e => e.key), StringComparer.Ordinal); List unknown = LastLoad.Unknown.Where(u => u.Key == null || !keys.Contains(u.Key)).ToList(); return DefaultsFile.Write(all, unknown); } /// /// Moves every file the load left unread aside before the first write. False when one could not be /// moved (one error): then nothing is written, so that file is never rotated away. /// private static bool SetAsideUnread() { List unread = LastLoad.Unread; if (unread.Count == 0) return true; // DefaultsFile.Write refuses while the game saves or loads; the files move on the write that happens. if (Scribe.mode != LoadSaveMode.Inactive) return true; foreach (string path in unread.ToList()) { if (File.Exists(path)) { string copy = DefaultsFile.SetAsideUnread(path); if (copy == null) return false; LastLoad.UnreadCopies.Add(copy); } unread.Remove(path); } return true; } } }