rimworld-blax-defaults/Source/BlaxDefaults/DefaultsLibrary.cs

308 lines
13 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Verse;
namespace BlaxDefaults
{
/// <summary>What DefaultsFile.Load found.</summary>
public sealed class LoadResult
{
public List<DefaultsEntry> Entries = new List<DefaultsEntry>();
/// <summary>The file the entries came from (main or .bak), null when none loaded.</summary>
public string LoadedFrom;
/// <summary>Full paths of the broken copies made by this load (Defaults.broken-&lt;timestamp&gt;.xml and the like).</summary>
public List<string> BrokenCopies = new List<string>();
/// <summary>No file loaded and every file that existed failed (each was renamed to a broken copy): the library starts empty.</summary>
public bool BothFailed;
/// <summary>Entries of the loaded file whose class this version doesn't have; written back on every write.</summary>
public List<UnknownEntry> Unknown = new List<UnknownEntry>();
/// <summary>The loaded file's formatVersion; 0 when nothing loaded.</summary>
public int FormatVersion;
/// <summary>
/// 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.
/// </summary>
public List<string> Unread = new List<string>();
/// <summary>Where DefaultsLibrary moved the unread files before its first write (Defaults.unread-&lt;timestamp&gt;.xml).</summary>
public List<string> UnreadCopies = new List<string>();
/// <summary>The file came from a newer version of Blax Defaults: this version reads it but never writes it.</summary>
public bool FromNewerVersion => FormatVersion > DefaultsLibrary.FormatVersion;
}
/// <summary>
/// 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-&lt;timestamp&gt;.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.
/// </summary>
public static class DefaultsLibrary
{
/// <summary>
/// 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.
/// </summary>
public const int FormatVersion = 1;
private static readonly Dictionary<string, DefaultsEntry> entries = new Dictionary<string, DefaultsEntry>(StringComparer.Ordinal);
/// <summary>The startup load left a file unread in place: read it again on the next use.</summary>
private static bool retryPending;
private static bool warnedNewer;
/// <summary>Raised after an entry is set or forgotten (not after a test restore).</summary>
public static event Action Changed;
/// <summary>True once the startup load ran, whatever it found.</summary>
public static bool LoadedAtStartup { get; private set; }
/// <summary>
/// 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).
/// </summary>
public static LoadResult LastLoad { get; private set; } = new LoadResult();
/// <summary>False when the last write failed or was refused; the file then still holds the previous content.</summary>
public static bool LastWriteOk { get; private set; } = true;
/// <summary>True while the read the startup load skipped is still to be retried.</summary>
public static bool RetryPending => retryPending;
/// <summary>The loaded file came from a newer version: Set and Forget work in memory, the file is never written.</summary>
public static bool ReadOnly => LastLoad.FromNewerVersion;
/// <summary>Every entry, ordered by key.</summary>
public static List<DefaultsEntry> 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<T>(string key) where T : DefaultsEntry => Get(key) as T;
/// <summary>Entries whose key starts with this prefix, ordered by key.</summary>
public static List<DefaultsEntry> WithPrefix(string prefix)
{
EnsureLoaded();
return entries.Values.Where(e => e.key.StartsWith(prefix, StringComparison.Ordinal)).OrderBy(e => e.key, StringComparer.Ordinal).ToList();
}
/// <summary>Adds or replaces the entry with its key and writes the file. Returns whether the write succeeded.</summary>
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();
}
/// <summary>Adds or replaces several entries and writes the file once. Returns whether the write succeeded.</summary>
public static bool SetMany(IEnumerable<DefaultsEntry> batch)
{
List<DefaultsEntry> list = batch?.ToList() ?? new List<DefaultsEntry>();
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();
}
/// <summary>Removes the entry and writes the file. False when there was no such entry.</summary>
public static bool Forget(string key)
{
EnsureLoaded();
if (key == null || !entries.Remove(key))
return false;
WriteAndNotify();
return true;
}
/// <summary>Reads the file into memory. Called once from BlaxDefaultsStartup; writes nothing.</summary>
public static void LoadAtStartup()
{
Install(DefaultsFile.Load() ?? new LoadResult(), retry: true);
LoadedAtStartup = true;
}
/// <summary>Clones of every entry, for a test to restore later.</summary>
public static List<DefaultsEntry> Snapshot()
{
EnsureLoaded();
return entries.Values.Select(e => e.Clone()).ToList();
}
/// <summary>Puts a snapshot back in memory without writing the file. Tests only.</summary>
public static void RestoreForTests(List<DefaultsEntry> snapshot) => Replace(snapshot);
/// <summary>Replaces the whole library in memory without writing the file. For DefaultsFile tests that reload.</summary>
public static void ReplaceInMemory(IEnumerable<DefaultsEntry> loaded) => Replace(loaded);
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
private static void EnsureLoaded()
{
if (!retryPending || Scribe.mode != LoadSaveMode.Inactive)
return;
retryPending = false;
List<DefaultsEntry> 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<DefaultsEntry> 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;
}
/// <summary>
/// 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.
/// </summary>
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<DefaultsEntry> all = All;
var keys = new HashSet<string>(all.Select(e => e.key), StringComparer.Ordinal);
List<UnknownEntry> unknown = LastLoad.Unknown.Where(u => u.Key == null || !keys.Contains(u.Key)).ToList();
return DefaultsFile.Write(all, unknown);
}
/// <summary>
/// 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.
/// </summary>
private static bool SetAsideUnread()
{
List<string> 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;
}
}
}