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

280 lines
13 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HarmonyLib;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxDefaults
{
/// <summary>A mod that sets the same defaults: its package id, name and a keyed string naming what it sets.</summary>
public sealed class OverlapMod
{
public readonly string PackageId;
public readonly string Name;
public readonly string WhatKey;
public OverlapMod(string packageId, string name, string whatKey)
{
PackageId = packageId;
Name = name;
WhatKey = whatKey;
}
public string What => WhatKey.Translate();
public override string ToString() => PackageId;
}
/// <summary>
/// Names active mods that set the same defaults. Work package "setup" (design.md: "Overlap warnings").
/// Detection only, through Compat.IsActive; no patches against those mods. 1.0 detects for storage
/// 1trickPwnyta's Defaults (defaults.1trickPwnyta), the unofficial Defaults 1.7 repack, Set my Defaults,
/// [FSF] No Default Shelf Storage, [FSF] FrozenSnowFox Tweaks and Default Normal Empty Storage, and for the
/// bill values Better Workbench Management, Default Ingredient Radius, Default Bill Ingredient Radius and
/// Default Until X. Dismissed ids live in BlaxDefaultsSettings.dismissedOverlaps, never in a save.
///
/// Package ids, each read from the mod's own About/About.xml in its public source repository, with its
/// About/PublishedFileId.txt matching the Workshop item (checked 2026-11-29):
/// - 1trickPwnyta's Defaults (Workshop 3285178686, Experimental 3522445452): github.com/1trickPwnyta/DefaultsMod,
/// branches master and experimental (the same id on both; Castes' Compat also read branch 1.7).
/// - Set my Defaults (3737034968): github.com/jb-rimworld/set-my-defaults, branch main.
/// - [FSF] No Default Shelf Storage (945085502): github.com/FrozenSnowFox/FSF_No_Default_Shelf_Storage, branch main.
/// - [FSF] FrozenSnowFox Tweaks (2893432492): github.com/FrozenSnowFox/FSF_FrozenSnowFox_Tweaks, branch main.
/// - Better Workbench Management (935982361): github.com/Falconne/ImprovedWorkbenches, branch master,
/// mod-structure/About/About.xml.
/// - Default Ingredient Radius (2909706985): github.com/emipa606/DefaultIngredientRadius, branch main.
/// - Default Bill Ingredient Radius (3789671048): github.com/benpbmith/DefaultBillIngredientRadius, branch main.
/// Not listed yet, because no public About.xml could be read; add each once its id is read from the mod files:
/// - the unofficial Defaults 1.7 repack (3836680679): its Workshop description says its packageId differs
/// from the original's, without naming it (what: BlaxDefaults_OverlapWhatDefaults).
/// - Default Normal Empty Storage (3779351608): no public source; Nexus mod 758 (BlaxDefaults_OverlapWhatEmptyStorage).
/// - Default Until X (3554414830): no public source (BlaxDefaults_OverlapWhatRepeat).
/// None of these mods is installed on the test machine, so detection is tested with a simulated id.
/// </summary>
public static class OverlapWarnings
{
public const string Defaults1trickPwnyta = "defaults.1trickPwnyta";
public const string SetMyDefaults = "juliusberger.workbenchbilldefaults";
public const string FsfNoDefaultShelfStorage = "FrozenSnowFox.NoDefaultShelfStorage";
public const string FsfTweaks = "FrozenSnowFox.FrozenSnowFoxTweaks";
public const string BetterWorkbenchManagement = "falconne.BWM";
public const string DefaultIngredientRadius = "Mlie.DefaultIngredientRadius";
public const string DefaultBillIngredientRadius = "pkthxbai.defaultbillingredientradius";
/// <summary>Every overlapping mod Defaults knows, in the order the page lists them: storage, then bills.</summary>
public static readonly OverlapMod[] Mods =
{
new OverlapMod(Defaults1trickPwnyta, "1trickPwnyta's Defaults", "BlaxDefaults_OverlapWhatDefaults"),
new OverlapMod(SetMyDefaults, "Set my Defaults", "BlaxDefaults_OverlapWhatDefaults"),
new OverlapMod(FsfNoDefaultShelfStorage, "[FSF] No Default Shelf Storage", "BlaxDefaults_OverlapWhatFsfShelves"),
new OverlapMod(FsfTweaks, "[FSF] FrozenSnowFox Tweaks", "BlaxDefaults_OverlapWhatFsfTweaks"),
new OverlapMod(BetterWorkbenchManagement, "Better Workbench Management", "BlaxDefaults_OverlapWhatStoreMode"),
new OverlapMod(DefaultIngredientRadius, "Default Ingredient Radius", "BlaxDefaults_OverlapWhatRadius"),
new OverlapMod(DefaultBillIngredientRadius, "Default Bill Ingredient Radius", "BlaxDefaults_OverlapWhatRadius"),
};
/// <summary>Package ids treated as active on top of the real mod list. For tests only.</summary>
public static readonly HashSet<string> SimulatedActive = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// The mod list can't change without a restart, so the real detection runs once.
private static List<OverlapMod> detected;
private static bool shownThisSession;
/// <summary>The overlapping mods that are active (real or simulated), in list order.</summary>
public static List<OverlapMod> Active()
{
detected ??= Mods.Where(m => Compat.IsActive(m.PackageId)).ToList();
if (SimulatedActive.Count == 0)
return new List<OverlapMod>(detected);
return Mods.Where(m => detected.Contains(m) || SimulatedActive.Contains(m.PackageId)).ToList();
}
/// <summary>True when the mod with this package id is active, real or simulated.</summary>
public static bool IsActive(string packageId) =>
!packageId.NullOrEmpty() && (SimulatedActive.Contains(packageId) || Compat.IsActive(packageId));
/// <summary>True when the player chose "Don't remind me" for this package id.</summary>
public static bool IsDismissed(string packageId)
{
List<string> dismissed = BlaxDefaultsMod.Settings?.dismissedOverlaps;
return dismissed != null && dismissed.Any(id => string.Equals(id, packageId, StringComparison.OrdinalIgnoreCase));
}
private static bool WarningsOn => BlaxDefaultsMod.Settings == null || BlaxDefaultsMod.Settings.warnOverlaps;
/// <summary>
/// The settings page text naming each active mod and what it sets; null when none or warnOverlaps is off.
/// Names dismissed mods too: "Don't remind me" only stops the window on load.
/// </summary>
public static string SettingsText()
{
if (!WarningsOn)
return null;
List<OverlapMod> active = Active();
if (active.Count == 0)
return null;
var sb = new StringBuilder();
sb.Append("BlaxDefaults_OverlapSettingsIntro".Translate());
foreach (OverlapMod mod in active)
sb.Append("\n- " + "BlaxDefaults_OverlapLine".Translate(mod.Name.Named("MOD"), mod.What.Named("WHAT")));
sb.Append("\n" + "BlaxDefaults_OverlapAdvice".Translate());
return sb.ToString();
}
/// <summary>The message text for these mods, or null for none.</summary>
public static string MessageText(List<OverlapMod> mods)
{
if (mods == null || mods.Count == 0)
return null;
string names = mods.Select(m => m.Name).ToCommaList(useAnd: true);
return "BlaxDefaults_OverlapMessage".Translate(names.Named("MODS"));
}
/// <summary>The warnOverlaps checkbox and SettingsText, on the settings page.</summary>
public static void DrawSettings(Listing_Standard l)
{
BlaxDefaultsSettings s = BlaxDefaultsMod.Settings;
if (s == null)
return;
l.CheckboxLabeled("BlaxDefaults_WarnOverlaps".Translate(), ref s.warnOverlaps, "BlaxDefaults_WarnOverlapsTip".Translate());
string text = SettingsText();
if (text != null)
l.Label(text);
}
/// <summary>
/// On the first game loaded in a session: one window listing the active mods not yet dismissed, with
/// "Don't remind me" per mod. Returns the mods it named (empty after the first call of a session). A
/// plain message has no buttons, so it is a small window (Dialog_OverlapWarnings).
/// </summary>
public static List<OverlapMod> ShowOncePerSession()
{
var named = new List<OverlapMod>();
if (shownThisSession)
return named;
shownThisSession = true;
if (!WarningsOn)
return named;
foreach (OverlapMod mod in Active())
{
if (!IsDismissed(mod.PackageId))
named.Add(mod);
}
if (named.Count == 0)
return named;
var mods = new List<OverlapMod>(named);
// FinalizeInit runs inside the loading event; the window opens when it is done.
LongEventHandler.ExecuteWhenFinished(() => Find.WindowStack?.Add(new Dialog_OverlapWarnings(mods)));
return named;
}
/// <summary>"Don't remind me": adds the id to dismissedOverlaps and writes the mod settings.</summary>
public static void Dismiss(string packageId)
{
BlaxDefaultsSettings s = BlaxDefaultsMod.Settings;
if (s == null || packageId.NullOrEmpty())
return;
s.dismissedOverlaps ??= new List<string>();
if (!IsDismissed(packageId))
s.dismissedOverlaps.Add(packageId);
try
{
s.Write();
}
catch (Exception e)
{
Log.Warning("[Blax Defaults] Writing the mod settings failed: " + e.Message);
}
}
/// <summary>Lets ShowOncePerSession show again. Tests only.</summary>
public static void ResetSessionForTests()
{
shownThisSession = false;
}
}
/// <summary>
/// The window on the first game loaded in a session: which active mods set the same defaults, each with
/// what it sets and "Don't remind me". Work package "setup".
/// </summary>
public class Dialog_OverlapWarnings : Window
{
public readonly List<OverlapMod> Mods;
private readonly HashSet<string> dismissedHere = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private const float RowHeight = 56f;
private const float ButtonWidth = 150f;
private Vector2 scroll;
public Dialog_OverlapWarnings(List<OverlapMod> mods)
{
Mods = mods ?? new List<OverlapMod>();
doCloseX = true;
doCloseButton = true;
forcePause = true;
absorbInputAroundWindow = true;
}
public override Vector2 InitialSize => new Vector2(560f, Mathf.Min(680f, 230f + Mods.Count * RowHeight));
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_OverlapTitle".Translate());
y += 40f;
Text.Font = GameFont.Small;
string message = OverlapWarnings.MessageText(Mods) ?? "";
float messageHeight = Text.CalcHeight(message, inRect.width);
Widgets.Label(new Rect(inRect.x, y, inRect.width, messageHeight), message);
y += messageHeight + 10f;
var outRect = new Rect(inRect.x, y, inRect.width, inRect.yMax - y - CloseButSize.y - 10f);
var viewRect = new Rect(0f, 0f, outRect.width - 16f, Mods.Count * RowHeight);
Widgets.BeginScrollView(outRect, ref scroll, viewRect);
for (int i = 0; i < Mods.Count; i++)
DrawRow(new Rect(0f, i * RowHeight, viewRect.width, RowHeight - 6f), Mods[i]);
Widgets.EndScrollView();
}
private void DrawRow(Rect row, OverlapMod mod)
{
var textRect = new Rect(row.x, row.y, row.width - ButtonWidth - 10f, row.height);
Widgets.Label(textRect, mod.Name + "\n" + mod.What.Colorize(ColoredText.SubtleGrayColor));
var buttonRect = new Rect(row.xMax - ButtonWidth, row.y + (row.height - 30f) / 2f, ButtonWidth, 30f);
if (dismissedHere.Contains(mod.PackageId))
{
Text.Anchor = TextAnchor.MiddleCenter;
Widgets.Label(buttonRect, "BlaxDefaults_OverlapDismissed".Translate());
Text.Anchor = TextAnchor.UpperLeft;
}
else if (Widgets.ButtonText(buttonRect, "BlaxDefaults_OverlapDontRemind".Translate()))
{
OverlapWarnings.Dismiss(mod.PackageId);
dismissedHere.Add(mod.PackageId);
}
}
}
[HarmonyPatch(typeof(Game), nameof(Game.FinalizeInit))]
public static class Patch_Game_FinalizeInit
{
public static void Postfix()
{
try
{
OverlapWarnings.ShowOncePerSession();
}
catch (Exception e)
{
HookGuard.Report("Game.FinalizeInit", e);
}
}
}
}