416 lines
20 KiB
C#
416 lines
20 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Globalization;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using RimWorld;
|
|
using UnityEngine;
|
|
using Verse;
|
|
|
|
namespace BlaxDefaults
|
|
{
|
|
/// <summary>
|
|
/// Mod settings > Blax Defaults. Work package "page" (design.md: "Defaults library and settings page",
|
|
/// players get / how / settings; "DLC support" for disabled rows).
|
|
///
|
|
/// Order on the page (inside a scroll view): the master toggle "enabled"; a status line (entry count, names
|
|
/// from inactive mods); the red BrokenFilesLine when the startup load found broken files; then one section
|
|
/// per category, each with its toggle: Stockpiles (stockpileDefaults, one row per stockpile entry),
|
|
/// Storage buildings (storageDefaults, one row per storage entry, then QuickSetup.DrawButton), Every new
|
|
/// bill (billDefaults, then BillValuesSection.Draw); last OverlapWarnings.DrawSettings. Each storage row
|
|
/// shows RowSummary with Edit (Dialog_EditStorageTemplate) and Forget (asks first). A row whose kind
|
|
/// needs a DLC that is off is drawn disabled with DisabledReason; a row whose kind is not loaded for
|
|
/// another reason (a removed mod) shows its inactive names and can't be edited. It all works from the
|
|
/// main menu: nothing here needs a running game.
|
|
/// </summary>
|
|
public static class SettingsPage
|
|
{
|
|
private const float ButtonWidth = 90f;
|
|
private const float ButtonHeight = 28f;
|
|
private const float RowPad = 4f;
|
|
|
|
private static Vector2 scrollPosition;
|
|
private static float viewHeight = 900f;
|
|
|
|
/// <summary>
|
|
/// What the page shows for one entry, cached by entry reference. Library entries are never edited in
|
|
/// place (DefaultsLibrary.Get hands out the live entry; changes go through a clone and Set), so a cached
|
|
/// row stays right until its entry is replaced. Saves resolving every name of every template each frame.
|
|
/// </summary>
|
|
private sealed class RowInfo
|
|
{
|
|
public string Summary;
|
|
public string Disabled;
|
|
public int Inactive;
|
|
public bool Editable;
|
|
public string Tip;
|
|
}
|
|
|
|
private static readonly Dictionary<DefaultsEntry, RowInfo> rowCache = new Dictionary<DefaultsEntry, RowInfo>();
|
|
|
|
/// <summary>Called by BlaxDefaultsMod.DoSettingsWindowContents.</summary>
|
|
public static void Draw(Rect inRect)
|
|
{
|
|
BlaxDefaultsSettings s = BlaxDefaultsMod.Settings;
|
|
if (s == null)
|
|
return;
|
|
PruneCache();
|
|
|
|
var view = new Rect(0f, 0f, inRect.width - 16f, Mathf.Max(viewHeight, inRect.height));
|
|
Widgets.BeginScrollView(inRect, ref scrollPosition, view);
|
|
var l = new Listing_Standard { maxOneColumn = true };
|
|
l.Begin(view);
|
|
try
|
|
{
|
|
DrawContents(l, s);
|
|
}
|
|
finally
|
|
{
|
|
viewHeight = l.CurHeight + 12f;
|
|
l.End();
|
|
Widgets.EndScrollView();
|
|
Text.Font = GameFont.Small;
|
|
GUI.color = Color.white;
|
|
}
|
|
}
|
|
|
|
private static void DrawContents(Listing_Standard l, BlaxDefaultsSettings s)
|
|
{
|
|
l.CheckboxLabeled("BlaxDefaults_PageEnabled".Translate(), ref s.enabled, "BlaxDefaults_PageEnabledTip".Translate());
|
|
|
|
List<DefaultsEntry> all = DefaultsLibrary.All;
|
|
int inactive = all.Sum(e => Info(e).Inactive);
|
|
l.Label(StatusLine(all.Count, inactive), -1f, (TipSignal)"BlaxDefaults_PageStatusTip".Translate(DefaultsFile.FilePath).Resolve());
|
|
|
|
string broken = BrokenFilesLine();
|
|
if (broken != null)
|
|
{
|
|
using (new TextBlock(ColorLibrary.RedReadable))
|
|
l.Label(broken);
|
|
}
|
|
|
|
// Stockpiles
|
|
SectionHeader(l, "BlaxDefaults_PageSectionStockpiles".Translate());
|
|
l.CheckboxLabeled("BlaxDefaults_PageStockpilesToggle".Translate(), ref s.stockpileDefaults, "BlaxDefaults_PageStockpilesToggleTip".Translate());
|
|
DrawRows(l, StockpileEntries(), "BlaxDefaults_PageStockpilesNone");
|
|
|
|
// Storage buildings
|
|
SectionHeader(l, "BlaxDefaults_PageSectionStorage".Translate());
|
|
l.CheckboxLabeled("BlaxDefaults_PageStorageToggle".Translate(), ref s.storageDefaults, "BlaxDefaults_PageStorageToggleTip".Translate());
|
|
DrawRows(l, StorageBuildingEntries(), "BlaxDefaults_PageStorageNone");
|
|
Guarded("QuickSetup.DrawButton", () => QuickSetup.DrawButton(l));
|
|
|
|
// Every new bill
|
|
SectionHeader(l, "BlaxDefaults_PageSectionBills".Translate());
|
|
l.CheckboxLabeled("BlaxDefaults_PageBillsToggle".Translate(), ref s.billDefaults, "BlaxDefaults_PageBillsToggleTip".Translate());
|
|
Guarded("BillValuesSection.Draw", () => BillValuesSection.Draw(l));
|
|
|
|
l.GapLine();
|
|
Guarded("OverlapWarnings.DrawSettings", () => OverlapWarnings.DrawSettings(l));
|
|
}
|
|
|
|
/// <summary>Another package's part of the page: a failure there logs once and leaves the rest of the page drawn.</summary>
|
|
private static void Guarded(string what, Action draw)
|
|
{
|
|
try
|
|
{
|
|
draw();
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
HookGuard.Report("SettingsPage " + what, e);
|
|
}
|
|
finally
|
|
{
|
|
Text.Font = GameFont.Small;
|
|
Text.Anchor = TextAnchor.UpperLeft;
|
|
GUI.color = Color.white;
|
|
}
|
|
}
|
|
|
|
private static void SectionHeader(Listing_Standard l, string title)
|
|
{
|
|
l.GapLine();
|
|
Text.Font = GameFont.Medium;
|
|
l.Label(title);
|
|
Text.Font = GameFont.Small;
|
|
}
|
|
|
|
private static void DrawRows(Listing_Standard l, List<DefaultsEntry> entries, string noneKey)
|
|
{
|
|
if (entries.Count == 0)
|
|
{
|
|
using (new TextBlock(Color.gray))
|
|
l.Label(noneKey.Translate());
|
|
return;
|
|
}
|
|
foreach (DefaultsEntry entry in entries)
|
|
DrawRow(l, entry, Info(entry));
|
|
}
|
|
|
|
private static void DrawRow(Listing_Standard l, DefaultsEntry entry, RowInfo info)
|
|
{
|
|
float textWidth = l.ColumnWidth - 2f * ButtonWidth - 3f * 6f;
|
|
string note = info.Disabled ?? (info.Inactive > 0 ? InactiveText(info.Inactive) : null);
|
|
float textHeight = Text.CalcHeight(info.Summary, textWidth) + (note != null ? Text.CalcHeight(note, textWidth) : 0f);
|
|
float height = Mathf.Max(ButtonHeight + 2f * RowPad, textHeight + 2f * RowPad);
|
|
Rect row = l.GetRect(height);
|
|
Widgets.DrawHighlightIfMouseover(row);
|
|
|
|
var textRect = new Rect(row.x + 6f, row.y + RowPad, textWidth, height - 2f * RowPad);
|
|
using (new TextBlock(info.Disabled != null ? Color.gray : Color.white))
|
|
{
|
|
float summaryHeight = Text.CalcHeight(info.Summary, textWidth);
|
|
Widgets.Label(new Rect(textRect.x, textRect.y, textWidth, summaryHeight), info.Summary);
|
|
if (note != null)
|
|
{
|
|
using (new TextBlock(info.Disabled != null ? ColorLibrary.RedReadable : ColorLibrary.Gold))
|
|
Widgets.Label(new Rect(textRect.x, textRect.y + summaryHeight, textWidth, textRect.height - summaryHeight), note);
|
|
}
|
|
}
|
|
if (!info.Tip.NullOrEmpty())
|
|
TooltipHandler.TipRegion(textRect, info.Tip);
|
|
|
|
float buttonY = row.y + (height - ButtonHeight) / 2f;
|
|
var forgetRect = new Rect(row.xMax - ButtonWidth, buttonY, ButtonWidth, ButtonHeight);
|
|
var editRect = new Rect(forgetRect.x - 6f - ButtonWidth, buttonY, ButtonWidth, ButtonHeight);
|
|
if (Widgets.ButtonText(editRect, "BlaxDefaults_PageEdit".Translate(), active: info.Editable) && info.Editable)
|
|
OpenEditor(entry);
|
|
if (!info.Editable)
|
|
{
|
|
string why = info.Disabled != null
|
|
? "BlaxDefaults_PageEditNeedsDlc".Translate(info.Disabled).Resolve()
|
|
: "BlaxDefaults_PageEditKindMissing".Translate().Resolve();
|
|
TooltipHandler.TipRegion(editRect, why);
|
|
}
|
|
if (Widgets.ButtonText(forgetRect, "BlaxDefaults_PageForget".Translate()))
|
|
ConfirmForget(entry);
|
|
l.Gap(2f);
|
|
}
|
|
|
|
private static void OpenEditor(DefaultsEntry entry)
|
|
{
|
|
StorageKind kind = StorageKinds.ForKey(entry?.key);
|
|
if (kind == null || !(entry is StorageTemplate template))
|
|
return;
|
|
Find.WindowStack.Add(new Dialog_EditStorageTemplate(kind, template.CloneTemplate()));
|
|
}
|
|
|
|
private static RowInfo Info(DefaultsEntry entry)
|
|
{
|
|
if (rowCache.TryGetValue(entry, out RowInfo info))
|
|
return info;
|
|
info = new RowInfo
|
|
{
|
|
Summary = RowSummary(entry),
|
|
Disabled = DisabledReason(entry),
|
|
Inactive = InactiveNameCount(entry),
|
|
Editable = entry is StorageTemplate && StorageKinds.ForKey(entry.key) != null,
|
|
Tip = RowTip(entry),
|
|
};
|
|
rowCache[entry] = info;
|
|
return info;
|
|
}
|
|
|
|
/// <summary>Drops cached rows of entries that left the library (forgotten or replaced).</summary>
|
|
private static void PruneCache()
|
|
{
|
|
if (rowCache.Count == 0)
|
|
return;
|
|
var live = new HashSet<DefaultsEntry>(DefaultsLibrary.All);
|
|
foreach (DefaultsEntry e in rowCache.Keys.Where(e => !live.Contains(e)).ToList())
|
|
rowCache.Remove(e);
|
|
}
|
|
|
|
private static string RowTip(DefaultsEntry entry)
|
|
{
|
|
var parts = new List<string>();
|
|
if (entry is StorageTemplate t)
|
|
parts.Add("BlaxDefaults_PageRowUnlistedTip".Translate(t.unlisted.Label()).Resolve());
|
|
if (DisabledReason(entry) == null)
|
|
{
|
|
List<string> names = entry.UnresolvedNames().ToList();
|
|
if (KindMissing(entry))
|
|
names.Insert(0, DefaultsKeys.NameOf(entry.key));
|
|
if (names.Count > 0)
|
|
{
|
|
string shown = string.Join(", ", names.Take(12)) + (names.Count > 12 ? ", ..." : "");
|
|
parts.Add("BlaxDefaults_PageInactiveNamesTip".Translate(shown).Resolve());
|
|
}
|
|
}
|
|
return parts.Count == 0 ? null : string.Join("\n\n", parts);
|
|
}
|
|
|
|
/// <summary>
|
|
/// What a row says: "Shelf: Normal, allows 14 of 1,903 items, refuses unlisted items". Counts only names
|
|
/// that resolve; the unlisted part is left out for UnlistedRule.Game.
|
|
/// </summary>
|
|
public static string RowSummary(DefaultsEntry entry)
|
|
{
|
|
if (entry == null)
|
|
return null;
|
|
if (!(entry is StorageTemplate t))
|
|
return KindLabel(entry);
|
|
int allows = t.allowed.Count(n => DefDatabase<ThingDef>.GetNamedSilentFail(n) != null);
|
|
int total = allows + t.refused.Count(n => DefDatabase<ThingDef>.GetNamedSilentFail(n) != null);
|
|
string text = "BlaxDefaults_PageRowSummary".Translate(KindLabel(entry), t.Priority.Label().CapitalizeFirst(),
|
|
FormatCount(allows), FormatCount(total)).Resolve();
|
|
switch (t.unlisted)
|
|
{
|
|
case UnlistedRule.Refuse:
|
|
return "BlaxDefaults_PageRowRefusesUnlisted".Translate(text).Resolve();
|
|
case UnlistedRule.Allow:
|
|
return "BlaxDefaults_PageRowAllowsUnlisted".Translate(text).Resolve();
|
|
default:
|
|
return text;
|
|
}
|
|
}
|
|
|
|
/// <summary>The row label for an entry's kind: "Shelf", "Stockpile", or the key's name when the kind is not loaded.</summary>
|
|
public static string KindLabel(DefaultsEntry entry)
|
|
{
|
|
if (entry?.key == null)
|
|
return null;
|
|
if (entry.key == DefaultsKeys.EveryBill)
|
|
return "BlaxDefaults_PageSectionBills".Translate();
|
|
StorageKind kind = StorageKinds.ForKey(entry.key);
|
|
string label = kind?.Label;
|
|
return label.NullOrEmpty() ? DefaultsKeys.NameOf(entry.key) : label.CapitalizeFirst();
|
|
}
|
|
|
|
/// <summary>
|
|
/// "Needs Biotech" (or its DLC) when the entry's kind is a def that a DLC which is off would add, such as
|
|
/// storage:GrowthVat without Biotech; null otherwise. Such an entry is drawn disabled and its names are
|
|
/// not counted as inactive.
|
|
/// </summary>
|
|
public static string DisabledReason(DefaultsEntry entry)
|
|
{
|
|
if (entry == null || !DefaultsKeys.IsStorage(entry.key))
|
|
return null;
|
|
string defName = DefaultsKeys.NameOf(entry.key);
|
|
if (DefDatabase<ThingDef>.GetNamedSilentFail(defName) != null)
|
|
return null;
|
|
string dlc = DlcSupport.MissingDlcOfThing(defName);
|
|
return dlc == null ? null : DlcSupport.NeedsLabel(dlc);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Names in the entry from inactive mods or DLCs that are off; 0 for an entry drawn disabled. A stockpile
|
|
/// or storage kind that is not loaded and waits for no DLC (a removed mod) counts as one more name
|
|
/// (design.md, "DLC support").
|
|
/// </summary>
|
|
public static int InactiveNameCount(DefaultsEntry entry)
|
|
{
|
|
if (entry == null || DisabledReason(entry) != null)
|
|
return 0;
|
|
return entry.UnresolvedNames().Count() + (KindMissing(entry) ? 1 : 0);
|
|
}
|
|
|
|
/// <summary>A stockpile or storage key whose kind is not loaded now.</summary>
|
|
private static bool KindMissing(DefaultsEntry entry) =>
|
|
(DefaultsKeys.IsStorage(entry.key) || DefaultsKeys.IsStockpile(entry.key)) && StorageKinds.ForKey(entry.key) == null;
|
|
|
|
/// <summary>"3 defaults. 2 names from mods that are not active." The status line under the master toggle.</summary>
|
|
public static string StatusLine()
|
|
{
|
|
List<DefaultsEntry> all = DefaultsLibrary.All;
|
|
return StatusLine(all.Count, all.Sum(InactiveNameCount));
|
|
}
|
|
|
|
private static string StatusLine(int count, int inactive)
|
|
{
|
|
string text;
|
|
if (count == 0)
|
|
text = "BlaxDefaults_PageStatusNone".Translate();
|
|
else if (count == 1)
|
|
text = "BlaxDefaults_PageStatusOne".Translate();
|
|
else
|
|
text = "BlaxDefaults_PageStatusMany".Translate(FormatCount(count));
|
|
return inactive > 0 ? text + " " + InactiveText(inactive) : text;
|
|
}
|
|
|
|
private static string InactiveText(int inactive) =>
|
|
inactive == 1
|
|
? "BlaxDefaults_PageInactiveOne".Translate().Resolve()
|
|
: "BlaxDefaults_PageInactiveMany".Translate(FormatCount(inactive)).Resolve();
|
|
|
|
/// <summary>The red lines about the defaults file the last load found (broken, unread, newer), else null.</summary>
|
|
public static string BrokenFilesLine() => BrokenFilesLine(DefaultsLibrary.LastLoad);
|
|
|
|
/// <summary>
|
|
/// The red lines for this load result, one per line, null when the load was clean: a file of a newer
|
|
/// version (read, never written); a file left unread, or where it was moved before the first write; the
|
|
/// broken copies and their folder. "The defaults file and its backup" only when there are two broken
|
|
/// copies: a lone broken file without a backup gets the one-file line.
|
|
/// </summary>
|
|
public static string BrokenFilesLine(LoadResult load)
|
|
{
|
|
if (load == null)
|
|
return null;
|
|
var lines = new List<string>();
|
|
if (load.FromNewerVersion)
|
|
lines.Add("BlaxDefaults_PageNewerFile".Translate().Resolve());
|
|
|
|
List<string> unread = load.Unread?.Where(p => !p.NullOrEmpty()).ToList() ?? new List<string>();
|
|
if (unread.Count > 0)
|
|
lines.Add("BlaxDefaults_PageUnread".Translate(Path.GetDirectoryName(unread[0])).Resolve());
|
|
List<string> unreadCopies = load.UnreadCopies?.Where(p => !p.NullOrEmpty()).ToList() ?? new List<string>();
|
|
if (unreadCopies.Count > 0)
|
|
lines.Add("BlaxDefaults_PageUnreadKept".Translate(Path.GetDirectoryName(unreadCopies[0]), string.Join(", ", unreadCopies.Select(Path.GetFileName))).Resolve());
|
|
|
|
List<string> copies = load.BrokenCopies?.Where(p => !p.NullOrEmpty()).ToList() ?? new List<string>();
|
|
if (copies.Count > 0)
|
|
{
|
|
string folder = Path.GetDirectoryName(copies[0]);
|
|
string names = string.Join(", ", copies.Select(Path.GetFileName));
|
|
if (load.BothFailed && copies.Count >= 2)
|
|
lines.Add("BlaxDefaults_PageBrokenBoth".Translate(folder, names).Resolve());
|
|
else if (!load.LoadedFrom.NullOrEmpty())
|
|
lines.Add("BlaxDefaults_PageBrokenRecovered".Translate(folder, names, Path.GetFileName(load.LoadedFrom)).Resolve());
|
|
else
|
|
lines.Add("BlaxDefaults_PageBrokenEmpty".Translate(folder, names).Resolve());
|
|
}
|
|
return lines.Count == 0 ? null : string.Join("\n", lines);
|
|
}
|
|
|
|
/// <summary>Forget with the confirmation dialog ("Forget the default for new shelves?").</summary>
|
|
public static void ConfirmForget(DefaultsEntry entry)
|
|
{
|
|
if (entry?.key == null)
|
|
return;
|
|
string key = entry.key;
|
|
StorageKind kind = StorageKinds.ForKey(key);
|
|
string what = kind != null ? kind.LabelPlural : KindLabel(entry);
|
|
Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(
|
|
"BlaxDefaults_PageForgetConfirm".Translate(what),
|
|
() => DefaultsLibrary.Forget(key),
|
|
destructive: true));
|
|
}
|
|
|
|
/// <summary>The storage entries (stockpile: and storage: keys) in the order the page lists them.</summary>
|
|
public static List<DefaultsEntry> StorageEntries()
|
|
{
|
|
List<DefaultsEntry> list = StockpileEntries();
|
|
list.AddRange(StorageBuildingEntries());
|
|
return list;
|
|
}
|
|
|
|
/// <summary>Stockpile entries: the vanilla stockpile, the dumping stockpile, then modded types by key.</summary>
|
|
public static List<DefaultsEntry> StockpileEntries() =>
|
|
DefaultsLibrary.WithPrefix(DefaultsKeys.StockpilePrefix)
|
|
.OrderBy(e => e.key == DefaultsKeys.Stockpile ? 0 : e.key == DefaultsKeys.Dumping ? 1 : 2)
|
|
.ThenBy(e => e.key, StringComparer.Ordinal)
|
|
.ToList();
|
|
|
|
/// <summary>Storage building entries, by their row label.</summary>
|
|
public static List<DefaultsEntry> StorageBuildingEntries() =>
|
|
DefaultsLibrary.WithPrefix(DefaultsKeys.StoragePrefix)
|
|
.OrderBy(e => KindLabel(e), StringComparer.OrdinalIgnoreCase)
|
|
.ThenBy(e => e.key, StringComparer.Ordinal)
|
|
.ToList();
|
|
|
|
/// <summary>"1,903": the count with a thousands separator, as in the design's example row.</summary>
|
|
private static string FormatCount(int n) => n.ToString("N0", CultureInfo.InvariantCulture);
|
|
}
|
|
}
|