using System; using System.Collections.Generic; using RimWorld; using UnityEngine; using Verse; namespace BlaxDefaults { /// One value of "Every new bill", one row of the settings section, in page order. public enum BillField { RepeatMode, RepeatCount, TargetCount, PauseWhenSatisfied, UnpauseWhenYouHave, IngredientSearchRadius, AllowedSkillRange, StoreMode, IncludeEquipped, IncludeTainted, HpRange, QualityRange, } /// /// The "Every new bill" values on the settings page, drawn under the section's billDefaults toggle by /// SettingsPage. Work package "bills" (design.md: "Values for every new bill", players get). Each value has /// a "game's default" state and only values the player changes are set: repeat mode (do X times, do until /// you have X, do forever), the count (1), the target (10), pause when satisfied (off) and resume at (5), /// ingredient radius (unlimited), allowed skill range (0 to 20), where products go (best stockpile or drop /// on floor), count equipped (off), count tainted (off), and the hit points and quality ranges for counting. /// Edits go to a clone of the saved BillValues (or a new one under DefaultsKeys.EveryBill) and are stored /// with DefaultsLibrary.Set; when no value is set any more, the entry is forgotten. /// /// Each row: the label, then either the game's value in grey and a "Change" button, or the editor and a /// "Game's default" button. Edits made while the mouse button is held (sliders, ranges) are kept in /// memory and stored once on release, so a drag writes the file once. /// public static class BillValuesSection { private const float RowHeight = 30f; private const float RangeRowHeight = 32f; private const float ButtonWidth = 140f; private const float LabelWidthPct = 0.34f; // The vanilla radius slider (Dialog_BillConfig): 3 to 100, and 100 means unlimited (999). private const float RadiusMin = 3f; private const float RadiusSliderMax = 100f; private const float RadiusUnlimited = 999f; private const int SkillRangeId = 0x4BD5B1; private const int HpRangeId = 0x4BD5B2; private const int QualityRangeId = 0x4BD5B3; private static readonly Color Grey = new Color(0.65f, 0.65f, 0.65f); /// The game's values, as a new BillValues holds them. private static readonly BillValues Game = new BillValues(); /// Every value, in page order. public static readonly BillField[] Fields = (BillField[])Enum.GetValues(typeof(BillField)); // Edits of a drag in progress, stored on mouse release. private static BillValues pending; // The saved values the rows showed last frame; another value means the library changed elsewhere. private static string shownFingerprint; private static readonly Dictionary buffers = new Dictionary(); public static void Draw(Listing_Standard l) { string savedPrint = BillDefaults.Values?.Fingerprint() ?? ""; if (pending == null && savedPrint != shownFingerprint) buffers.Clear(); BillValues v = Working(); string before = v.Fingerprint(); GreyLabel(l, "BlaxDefaults_Bills_Intro".Translate()); if (!BlaxDefaultsMod.BillsOn) GreyLabel(l, "BlaxDefaults_Bills_Off".Translate()); ModeRow(l, v, BillField.RepeatMode); if (v.repeatMode == "TargetCount") GreyLabel(l, "BlaxDefaults_Bills_TargetNote".Translate()); CountRow(l, v, BillField.RepeatCount, min: 1); CountRow(l, v, BillField.TargetCount, min: 1); BoolRow(l, v, BillField.PauseWhenSatisfied); CountRow(l, v, BillField.UnpauseWhenYouHave, min: 0); if (v.setTargetCount && v.setUnpauseWhenYouHave && v.unpauseWhenYouHave >= v.targetCount) { // As the vanilla bill window does: resume below the target, or the bill never pauses. v.unpauseWhenYouHave = Mathf.Max(0, v.targetCount - 1); buffers.Remove(BillField.UnpauseWhenYouHave); } if (PauseNeverStarts(v)) GreyLabel(l, "BlaxDefaults_Bills_ResumeNote".Translate()); RadiusRow(l, v); RangeRow(l, v, BillField.AllowedSkillRange); ModeRow(l, v, BillField.StoreMode); BoolRow(l, v, BillField.IncludeEquipped); BoolRow(l, v, BillField.IncludeTainted); RangeRow(l, v, BillField.HpRange); RangeRow(l, v, BillField.QualityRange); if (v.AnySet && l.ButtonText("BlaxDefaults_Bills_ResetAll".Translate())) { Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("BlaxDefaults_Bills_ResetAllConfirm".Translate(), () => ForgetAll(), destructive: true)); } if (v.Fingerprint() != before) pending = v; if (pending != null && !Input.GetMouseButton(0)) { BillValues p = pending; pending = null; Store(p); } shownFingerprint = BillDefaults.Values?.Fingerprint() ?? ""; } // ---- the logic behind the rows (tested without drawing) ------------------------------------------- /// A copy to edit: the edits of a drag in progress, else a clone of the saved values, else new values under bill:*. public static BillValues Working() => (pending ?? BillDefaults.Values)?.CloneValues() ?? new BillValues(DefaultsKeys.EveryBill); /// /// Stores an edited copy under bill:*: DefaultsLibrary.Set when a value is set and something changed, /// DefaultsLibrary.Forget when no value is set any more. Pass a copy (Working), never the live entry. /// Returns false when the file write failed. /// public static bool Store(BillValues edited) { if (edited == null) return false; edited.key = DefaultsKeys.EveryBill; BillValues saved = BillDefaults.Values; if (!edited.AnySet) return saved == null || DefaultsLibrary.Forget(DefaultsKeys.EveryBill); if (saved != null && saved.Fingerprint() == edited.Fingerprint()) return true; return DefaultsLibrary.Set(edited); } /// Changes a copy of the current values and stores it (Store). For menu choices and tests. public static bool Edit(Action change) { BillValues v = Working(); change(v); pending = null; buffers.Clear(); return Store(v); } /// Forgets every value: new bills start with the game's values again. public static void ForgetAll() { pending = null; buffers.Clear(); DefaultsLibrary.Forget(DefaultsKeys.EveryBill); } /// True when the value is set, false when it follows the game's default. public static bool IsSet(BillValues v, BillField f) { switch (f) { case BillField.RepeatMode: return v.repeatMode != null; case BillField.RepeatCount: return v.setRepeatCount; case BillField.TargetCount: return v.setTargetCount; case BillField.PauseWhenSatisfied: return v.setPauseWhenSatisfied; case BillField.UnpauseWhenYouHave: return v.setUnpauseWhenYouHave; case BillField.IngredientSearchRadius: return v.setIngredientSearchRadius; case BillField.AllowedSkillRange: return v.setAllowedSkillRange; case BillField.StoreMode: return v.storeMode != null; case BillField.IncludeEquipped: return v.setIncludeEquipped; case BillField.IncludeTainted: return v.setIncludeTainted; case BillField.HpRange: return v.setHpRange; case BillField.QualityRange: return v.setQualityRange; default: return false; } } /// Sets the value, starting from the game's value ("Change" before the player edits it). public static void Change(BillValues v, BillField f) => Put(v, f, set: true); /// Back to the game's default: the value is unset and holds the game's value again. public static void Clear(BillValues v, BillField f) => Put(v, f, set: false); private static void Put(BillValues v, BillField f, bool set) { switch (f) { case BillField.RepeatMode: v.repeatMode = set ? BillDefaults.RepeatModeNames[0] : null; break; case BillField.RepeatCount: v.setRepeatCount = set; v.repeatCount = Game.repeatCount; break; case BillField.TargetCount: v.setTargetCount = set; v.targetCount = Game.targetCount; break; case BillField.PauseWhenSatisfied: v.setPauseWhenSatisfied = set; v.pauseWhenSatisfied = Game.pauseWhenSatisfied; break; case BillField.UnpauseWhenYouHave: v.setUnpauseWhenYouHave = set; v.unpauseWhenYouHave = Game.unpauseWhenYouHave; break; case BillField.IngredientSearchRadius: v.setIngredientSearchRadius = set; v.ingredientSearchRadius = Game.ingredientSearchRadius; break; case BillField.AllowedSkillRange: v.setAllowedSkillRange = set; v.allowedSkillRange = Game.allowedSkillRange; break; case BillField.StoreMode: v.storeMode = set ? BillDefaults.StoreModeNames[0] : null; break; case BillField.IncludeEquipped: v.setIncludeEquipped = set; v.includeEquipped = Game.includeEquipped; break; case BillField.IncludeTainted: v.setIncludeTainted = set; v.includeTainted = Game.includeTainted; break; case BillField.HpRange: v.setHpRange = set; v.hpRange = Game.hpRange; break; case BillField.QualityRange: v.setQualityRange = set; v.qualityRange = Game.qualityRange; break; } } /// Pause when satisfied is set on, but resume at (set or the game's 5) is not below the target, so bills never pause. public static bool PauseNeverStarts(BillValues v) => v.setPauseWhenSatisfied && v.pauseWhenSatisfied && (v.setUnpauseWhenYouHave ? v.unpauseWhenYouHave : Game.unpauseWhenYouHave) >= (v.setTargetCount ? v.targetCount : Game.targetCount); // ---- rows ------------------------------------------------------------------------------------------- /// /// The label, the game's value or the editor, and the button that switches between them. Returns the /// editor's rect, or a zero rect when the value follows the game's default. A Change button with /// onChange set calls it instead of setting the value. /// private static Rect Row(Listing_Standard l, BillValues v, BillField f, float height, Action onChange = null) { Rect row = l.GetRect(height); string tip = TipKey(f); if (tip != null) TooltipHandler.TipRegion(row, tip.Translate()); Rect labelRect = row.LeftPart(LabelWidthPct); Rect button = row.RightPartPixels(ButtonWidth); var editor = new Rect(labelRect.xMax + 8f, row.y, button.x - labelRect.xMax - 16f, row.height); Text.Anchor = TextAnchor.MiddleLeft; Widgets.Label(labelRect, LabelKey(f).Translate()); bool set = IsSet(v, f); if (!set) { GUI.color = Grey; Widgets.Label(editor, "BlaxDefaults_Bills_GameDefault".Translate(GameValueText(f))); GUI.color = Color.white; } Text.Anchor = TextAnchor.UpperLeft; if (set) { if (Widgets.ButtonText(button, "BlaxDefaults_Bills_UseGameDefault".Translate())) { Clear(v, f); buffers.Remove(f); } } else if (Widgets.ButtonText(button, "BlaxDefaults_Bills_Change".Translate())) { if (onChange != null) { onChange(); } else { Change(v, f); buffers.Remove(f); } } l.Gap(l.verticalSpacing); return IsSet(v, f) ? editor : Rect.zero; } private static void ModeRow(Listing_Standard l, BillValues v, BillField f) { Rect editor = Row(l, v, f, RowHeight, onChange: () => ModeMenu(f)); if (editor.width > 0f && Widgets.ButtonText(editor, ModeLabel(f, f == BillField.RepeatMode ? v.repeatMode : v.storeMode))) ModeMenu(f); } private static void ModeMenu(BillField f) { var options = new List(); foreach (string name in f == BillField.RepeatMode ? BillDefaults.RepeatModeNames : BillDefaults.StoreModeNames) { string chosen = name; options.Add(new FloatMenuOption(ModeLabel(f, chosen), () => Edit(x => { if (f == BillField.RepeatMode) x.repeatMode = chosen; else x.storeMode = chosen; }))); } Find.WindowStack.Add(new FloatMenu(options)); } private static void CountRow(Listing_Standard l, BillValues v, BillField f, int min) { Rect editor = Row(l, v, f, RowHeight); if (editor.width <= 0f) return; int value = f == BillField.RepeatCount ? v.repeatCount : f == BillField.TargetCount ? v.targetCount : v.unpauseWhenYouHave; buffers.TryGetValue(f, out string buffer); Widgets.IntEntry(editor, ref value, ref buffer); if (value < min) { value = min; buffer = value.ToString(); } buffers[f] = buffer; if (f == BillField.RepeatCount) v.repeatCount = value; else if (f == BillField.TargetCount) v.targetCount = value; else v.unpauseWhenYouHave = value; } private static void BoolRow(Listing_Standard l, BillValues v, BillField f) { // Change turns the value on: off is already the game's default for all three. Rect editor = Row(l, v, f, RowHeight, onChange: () => { Change(v, f); SetBool(v, f, true); }); if (editor.width <= 0f) return; bool on = GetBool(v, f); Widgets.CheckboxLabeled(editor, OnOff(on), ref on, placeCheckboxNearText: true); SetBool(v, f, on); } private static void RadiusRow(Listing_Standard l, BillValues v) { Rect editor = Row(l, v, BillField.IngredientSearchRadius, RowHeight); if (editor.width <= 0f) return; Rect slider = editor.LeftPart(0.7f); Rect value = editor.RightPart(0.28f); float shown = Mathf.Min(v.ingredientSearchRadius, RadiusSliderMax); float now = Widgets.HorizontalSlider(slider, shown, RadiusMin, RadiusSliderMax, middleAlignment: true, roundTo: 1f); if (now != shown) v.ingredientSearchRadius = now >= RadiusSliderMax ? RadiusUnlimited : now; Text.Anchor = TextAnchor.MiddleLeft; Widgets.Label(value, RadiusText(v.ingredientSearchRadius)); Text.Anchor = TextAnchor.UpperLeft; } private static void RangeRow(Listing_Standard l, BillValues v, BillField f) { Rect editor = Row(l, v, f, RangeRowHeight); if (editor.width <= 0f) return; switch (f) { case BillField.AllowedSkillRange: Widgets.IntRange(editor, SkillRangeId, ref v.allowedSkillRange, 0, 20); break; case BillField.HpRange: Widgets.FloatRange(editor, HpRangeId, ref v.hpRange, 0f, 1f, null, ToStringStyle.PercentZero); // As the vanilla bill window rounds it. v.hpRange.min = Mathf.Round(v.hpRange.min * 100f) / 100f; v.hpRange.max = Mathf.Round(v.hpRange.max * 100f) / 100f; break; case BillField.QualityRange: Widgets.QualityRange(editor, QualityRangeId, ref v.qualityRange); break; } } private static void GreyLabel(Listing_Standard l, string text) { GUI.color = Grey; l.Label(text); GUI.color = Color.white; } // ---- texts ------------------------------------------------------------------------------------------ private static string LabelKey(BillField f) => "BlaxDefaults_Bills_" + f; private static string TipKey(BillField f) { switch (f) { case BillField.RepeatCount: return "BlaxDefaults_Bills_RepeatCountTip"; case BillField.TargetCount: case BillField.PauseWhenSatisfied: case BillField.UnpauseWhenYouHave: case BillField.IncludeEquipped: case BillField.IncludeTainted: case BillField.HpRange: case BillField.QualityRange: return "BlaxDefaults_Bills_TargetOnlyTip"; default: return null; } } /// What a new bill has when the value follows the game's default. private static string GameValueText(BillField f) { switch (f) { case BillField.RepeatMode: return ModeLabel(f, BillDefaults.RepeatModeNames[0]); case BillField.RepeatCount: return Game.repeatCount.ToString(); case BillField.TargetCount: return Game.targetCount.ToString(); case BillField.PauseWhenSatisfied: return OnOff(Game.pauseWhenSatisfied); case BillField.UnpauseWhenYouHave: return Game.unpauseWhenYouHave.ToString(); case BillField.IngredientSearchRadius: return RadiusText(Game.ingredientSearchRadius); case BillField.AllowedSkillRange: return "BlaxDefaults_Bills_Range".Translate(Game.allowedSkillRange.min, Game.allowedSkillRange.max); case BillField.StoreMode: return ModeLabel(f, BillDefaults.StoreModeNames[0]); case BillField.IncludeEquipped: return OnOff(Game.includeEquipped); case BillField.IncludeTainted: return OnOff(Game.includeTainted); case BillField.HpRange: return "BlaxDefaults_Bills_Range".Translate(Game.hpRange.min.ToStringPercent(), Game.hpRange.max.ToStringPercent()); case BillField.QualityRange: return "BlaxDefaults_Bills_AnyQuality".Translate(); default: return ""; } } /// The vanilla label of a repeat or store mode ("Do until you have X", "Drop on floor"), or the saved name. private static string ModeLabel(BillField f, string name) { Def def = f == BillField.RepeatMode ? BillDefaults.ResolveRepeatMode(name) : (Def)BillDefaults.ResolveStoreMode(name); return def != null ? def.LabelCap.Resolve() : name; } private static string RadiusText(float radius) => radius >= RadiusUnlimited ? "BlaxDefaults_Bills_Unlimited".Translate().Resolve() : radius.ToString("F0"); private static string OnOff(bool on) => (on ? "BlaxDefaults_Bills_ValueOn" : "BlaxDefaults_Bills_ValueOff").Translate(); private static bool GetBool(BillValues v, BillField f) => f == BillField.PauseWhenSatisfied ? v.pauseWhenSatisfied : f == BillField.IncludeEquipped ? v.includeEquipped : v.includeTainted; private static void SetBool(BillValues v, BillField f, bool on) { if (f == BillField.PauseWhenSatisfied) v.pauseWhenSatisfied = on; else if (f == BillField.IncludeEquipped) v.includeEquipped = on; else v.includeTainted = on; } } }