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

248 lines
11 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxDefaults
{
/// <summary>
/// "New shelves start empty at Normal". Work package "setup" (design.md: "Quick setup: new shelves start
/// empty"). The list holds StorageKinds.CoveredDefs(). A kind is ticked when its thingClass is
/// Building_Storage or a subclass, building.isHopper is false, and its parent filter allows things from at
/// least two top-level item categories (children of ThingCategoryDefOf.Root; each allowed def counts under
/// the top-level category its first thingCategories entry leads to; defs without one don't count). Kinds
/// that already have a default are marked and start unticked. Confirming saves EmptyTemplate per ticked kind.
/// </summary>
public static class QuickSetup
{
public sealed class Candidate
{
public ThingDef Def;
public bool Ticked;
public bool HasDefault;
/// <summary>
/// UntickedReason(Def), worked out once when the list is built (the rule scans every storable def,
/// too slow for every row on every GUI event); null when the preselection ticks the kind.
/// </summary>
public string UntickedReason;
}
/// <summary>Every covered def with its preselection, in def order.</summary>
public static List<Candidate> Candidates()
{
var list = new List<Candidate>();
foreach (ThingDef def in StorageKinds.CoveredDefs())
{
bool has = DefaultsLibrary.Has(DefaultsKeys.ForStorage(def));
string reason;
bool preselect;
try
{
reason = UntickedReason(def);
preselect = reason == null;
}
catch (Exception e)
{
// A modded def with odd storage settings stays unticked instead of breaking the list.
HookGuard.Report("QuickSetup.Preselect", e);
reason = null;
preselect = false;
}
list.Add(new Candidate { Def = def, HasDefault = has, UntickedReason = reason, Ticked = preselect && !has });
}
return list;
}
/// <summary>The preselection rule above, ignoring whether a default exists.</summary>
public static bool Preselect(ThingDef def) => UntickedReason(def) == null;
/// <summary>
/// Why the preselection leaves the def unticked, as a keyed string; null when it ticks it. Ignores
/// whether a default exists.
/// </summary>
public static string UntickedReason(ThingDef def)
{
if (def?.building == null || def.thingClass == null || !typeof(Building_Storage).IsAssignableFrom(def.thingClass))
return "BlaxDefaults_QuickSetupReasonNotShelf";
// An empty hopper starves the nutrient paste dispenser (BuildingProperties.isHopper).
if (def.building.isHopper)
return "BlaxDefaults_QuickSetupReasonHopper";
if (TopLevelCategoryCount(StorageKinds.ParentFilterFor(def)) < 2)
return "BlaxDefaults_QuickSetupReasonOneCategory";
return null;
}
/// <summary>How many top-level item categories the filter allows things from.</summary>
public static int TopLevelCategoryCount(ThingFilter parentFilter)
{
var tops = new HashSet<ThingCategoryDef>();
foreach (ThingDef def in StorageKinds.StorableDefs(parentFilter))
{
ThingCategoryDef top = TopLevelCategoryOf(def);
if (top != null)
tops.Add(top);
}
return tops.Count;
}
/// <summary>
/// The child of ThingCategoryDefOf.Root that the def's first thingCategories entry leads to, or null when
/// the def has no category or its first one isn't under Root.
/// </summary>
public static ThingCategoryDef TopLevelCategoryOf(ThingDef def)
{
ThingCategoryDef root = ThingCategoryDefOf.Root;
ThingCategoryDef cat = def?.thingCategories?.FirstOrDefault();
// The depth limit only guards against a modded category loop.
for (int depth = 0; cat != null && depth < 64; depth++)
{
if (cat.parent == root)
return cat;
cat = cat.parent;
}
return null;
}
/// <summary>
/// Normal, allows nothing, refuses every storable def the def's parent filter allows, unlisted = Refuse,
/// so items a mod adds later are refused too. Not saved.
/// </summary>
public static StorageTemplate EmptyTemplate(ThingDef def)
{
var t = new StorageTemplate(DefaultsKeys.ForStorage(def))
{
Priority = StoragePriority.Normal,
unlisted = UnlistedRule.Refuse,
};
foreach (ThingDef d in StorageKinds.StorableDefs(StorageKinds.ParentFilterFor(def)))
t.refused.Add(d.defName);
return t;
}
/// <summary>
/// Saves EmptyTemplate for each def, replacing any default it has. Returns how many were saved (put in
/// the library with one file write; DefaultsLibrary.LastWriteOk tells whether it succeeded).
/// </summary>
public static int Apply(IEnumerable<ThingDef> ticked)
{
if (ticked == null)
return 0;
List<DefaultsEntry> templates = ticked.Where(d => d != null).Distinct().Select(d => (DefaultsEntry)EmptyTemplate(d)).ToList();
if (templates.Count > 0)
DefaultsLibrary.SetMany(templates);
return templates.Count;
}
/// <summary>
/// The settings page button that opens Dialog_QuickSetup, under the Storage buildings section. Its
/// tooltip says that [FSF] No Default Shelf Storage does the same thing while that mod is active.
/// </summary>
public static void DrawButton(Listing_Standard l)
{
Rect rect = l.GetRect(30f);
if (Widgets.ButtonText(rect, "BlaxDefaults_QuickSetupButton".Translate()))
Find.WindowStack.Add(new Dialog_QuickSetup());
TooltipHandler.TipRegion(rect, ButtonTooltip());
l.Gap(l.verticalSpacing);
}
/// <summary>The button's tooltip, with the [FSF] No Default Shelf Storage note while that mod is active.</summary>
public static string ButtonTooltip()
{
string tip = "BlaxDefaults_QuickSetupTip".Translate();
if (OverlapWarnings.IsActive(OverlapWarnings.FsfNoDefaultShelfStorage))
tip += "\n\n" + "BlaxDefaults_QuickSetupTipFsf".Translate();
return tip;
}
}
/// <summary>The quick setup list: a checkbox per QuickSetup.Candidate, Confirm and Cancel. Work package "setup".</summary>
public class Dialog_QuickSetup : Window
{
public readonly List<QuickSetup.Candidate> Candidates;
private const float RowHeight = 28f;
private const float ButtonHeight = 38f;
private Vector2 scroll;
public Dialog_QuickSetup()
{
Candidates = QuickSetup.Candidates();
doCloseX = true;
forcePause = true;
absorbInputAroundWindow = true;
}
public override Vector2 InitialSize => new Vector2(480f, 600f);
/// <summary>Saves the empty default for every ticked kind. Returns how many were saved.</summary>
public int Confirm()
{
int saved = QuickSetup.Apply(Candidates.Where(c => c.Ticked).Select(c => c.Def));
if (saved > 0)
Messages.Message("BlaxDefaults_QuickSetupSaved".Translate(saved), MessageTypeDefOf.TaskCompletion, historical: false);
return saved;
}
public override void DoWindowContents(Rect inRect)
{
float y = inRect.y;
Text.Font = GameFont.Medium;
Widgets.Label(new Rect(inRect.x, y, inRect.width - 30f, 35f), "BlaxDefaults_QuickSetupTitle".Translate());
y += 40f;
Text.Font = GameFont.Small;
string intro = "BlaxDefaults_QuickSetupIntro".Translate();
float introHeight = Text.CalcHeight(intro, inRect.width);
Widgets.Label(new Rect(inRect.x, y, inRect.width, introHeight), intro);
y += introHeight + 10f;
var outRect = new Rect(inRect.x, y, inRect.width, inRect.yMax - y - ButtonHeight - 10f);
if (Candidates.Count == 0)
{
Widgets.Label(outRect, "BlaxDefaults_QuickSetupNone".Translate());
}
else
{
var viewRect = new Rect(0f, 0f, outRect.width - 16f, Candidates.Count * RowHeight);
Widgets.BeginScrollView(outRect, ref scroll, viewRect);
for (int i = 0; i < Candidates.Count; i++)
DrawRow(new Rect(0f, i * RowHeight, viewRect.width, RowHeight), Candidates[i], i);
Widgets.EndScrollView();
}
float buttonWidth = (inRect.width - 10f) / 2f;
var confirmRect = new Rect(inRect.x, inRect.yMax - ButtonHeight, buttonWidth, ButtonHeight);
var cancelRect = new Rect(confirmRect.xMax + 10f, confirmRect.y, buttonWidth, ButtonHeight);
if (Widgets.ButtonText(confirmRect, "Confirm".Translate()))
{
Confirm();
Close();
}
if (Widgets.ButtonText(cancelRect, "CancelButton".Translate()))
Close();
}
private static void DrawRow(Rect rect, QuickSetup.Candidate c, int index)
{
if (index % 2 == 1)
Widgets.DrawLightHighlight(rect);
string label = c.Def.LabelCap;
if (c.Def.modContentPack != null && !c.Def.modContentPack.IsOfficialMod)
label += " " + ("(" + c.Def.modContentPack.Name + ")").Colorize(ColoredText.SubtleGrayColor);
if (c.HasDefault)
label += " " + ("(" + "BlaxDefaults_QuickSetupHasDefault".Translate() + ")").Colorize(ColoredText.SubtleGrayColor);
Widgets.CheckboxLabeled(rect.ContractedBy(2f, 0f), label, ref c.Ticked);
string reason = c.UntickedReason;
string tip = reason == null ? null : (string)reason.Translate();
if (c.HasDefault)
tip = (tip == null ? "" : tip + "\n\n") + "BlaxDefaults_QuickSetupReasonHasDefault".Translate();
if (tip != null)
TooltipHandler.TipRegion(rect, tip);
}
}
}