using System;
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxSlaves
{
///
/// Counts time as a slave of the player's colony, per pawn, in ticks. This is deliberately not a RecordDef:
/// Pawn_RecordsTracker saves records as a list ordered by def index (DefMap), and def indices follow the
/// load order, so any RecordDef added by this mod would shift the records of every mod loaded after it
/// when Blax Slaves is added to or removed from a running save. Here the counter lives in its own save
/// node, keyed by pawn reference: adding the mod starts at zero, removing it drops only this node.
///
/// Every CountInterval ticks it adds the whole interval to each living colony slave on any map (pawns in
/// containers, transporters on the ground and cryptosleep included), in a caravan, in a travelling
/// transporter or aboard a gravship in flight: the set PawnsFinder already keeps for colony slaves.
///
public class GameComponent_TimeAsSlave : GameComponent
{
private Dictionary ticks = new Dictionary();
private List keysWorkingList;
private List valuesWorkingList;
private readonly HashSet counted = new HashSet();
private readonly List purgeList = new List();
public GameComponent_TimeAsSlave(Game game)
{
}
public static GameComponent_TimeAsSlave Instance => Current.Game?.GetComponent();
/// Pawns with a counter: colony slaves now or earlier. Read-only, for tests and other mods.
public IReadOnlyCollection TrackedPawns => ticks.Keys;
public int TicksOf(Pawn pawn) => pawn != null && ticks.TryGetValue(pawn, out int t) ? t : 0;
public override void GameComponentTick()
{
if (Find.TickManager.TicksGame % TimeAsSlave.CountInterval == 0)
Count(TimeAsSlave.CountInterval);
}
private void Count(int interval)
{
List slaves = PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_SlavesOfColony;
counted.Clear();
for (int i = 0; i < slaves.Count; i++)
{
Pawn pawn = slaves[i];
// The finder joins several lists; never count one pawn twice in a pass.
if (pawn == null || pawn.Dead || !counted.Add(pawn))
continue;
ticks.TryGetValue(pawn, out int t);
ticks[pawn] = t + interval;
}
counted.Clear();
}
///
/// Drops the counters of destroyed pawns (discarded ones included). They are saved nowhere, so their
/// references could not be loaded back. Dead slaves keep theirs while their corpse or world pawn exists.
/// Runs before every save and after every load; returns how many it dropped.
///
public int Purge()
{
purgeList.Clear();
foreach (KeyValuePair entry in ticks)
{
if (entry.Key == null || entry.Key.Destroyed)
purgeList.Add(entry.Key);
}
for (int i = 0; i < purgeList.Count; i++)
ticks.Remove(purgeList[i]);
int dropped = purgeList.Count;
purgeList.Clear();
return dropped;
}
public override void ExposeData()
{
if (Scribe.mode == LoadSaveMode.Saving)
Purge();
// A reference that can't be resolved on load (a pawn lost without being destroyed) comes back as a
// null key. BuildDictionary skips null keys; logNullErrors: false keeps that out of the error log.
Scribe_Collections.Look(ref ticks, "ticks", LookMode.Reference, LookMode.Value,
ref keysWorkingList, ref valuesWorkingList, logNullErrors: false);
if (Scribe.mode == LoadSaveMode.PostLoadInit)
{
if (ticks == null)
ticks = new Dictionary();
Purge();
}
}
}
public static class TimeAsSlave
{
public const string LineId = "blax.slaves.timeAsSlave";
/// Ticks between two counting passes (GenTicks.TickRareInterval); each pass adds the whole interval.
public const int CountInterval = 250;
/// Ticks this pawn has spent as a slave of the colony since Blax Slaves was installed.
public static int Ticks(Pawn pawn) => GameComponent_TimeAsSlave.Instance?.TicksOf(pawn) ?? 0;
/// "Enslaved for 23 days (tracked since install)", formatted like the Records tab.
public static string Label(Pawn pawn) =>
"BlaxSlaves_TimeAsSlaveLine".Translate(Ticks(pawn).ToStringTicksToPeriod());
/// The Records tab row: label, value as vanilla formats time records, and tooltip.
public static string RecordLabel => "BlaxSlaves_TimeAsSlaveRecord".Translate().CapitalizeFirst();
public static string RecordValue(Pawn pawn) => Ticks(pawn).ToStringTicksToPeriod();
public static string RecordTooltip => "BlaxSlaves_TimeAsSlaveRecordDesc".Translate();
// The counter always counts; the setting only hides the line.
internal static readonly SlaveTabLine Line = new SlaveTabLine(
LineId,
Label,
tooltip: _ => "BlaxSlaves_TimeAsSlaveLineTip".Translate(),
visible: _ => BlaxSlavesMod.Settings == null || BlaxSlavesMod.Settings.showTimeInSlaveTab);
}
///
/// Adds "Time as a slave" at the end of the Records tab's time column, where a RecordDef row would sit,
/// laid out like vanilla's private DrawRecord (8 px indent, value in the right 45 percent, highlight and
/// tooltip on hover). DrawTimeRecords draws inside the card's scroll view and returns the column height,
/// which DrawRecordsCard turns into the scroll height, so the postfix draws right under the last row and
/// adds its own height to the result. Shown for every pawn, like vanilla's time records.
///
[HarmonyPatch(typeof(RecordsCardUtility), "DrawTimeRecords")]
public static class Patch_RecordsCardTimeAsSlave
{
private const float Indent = 8f;
private const float ValueShare = 0.45f;
public static void Postfix(Rect leftRect, Pawn pawn, ref float __result)
{
if (pawn == null)
return;
try
{
__result += DrawRow(leftRect, __result, pawn);
}
catch (Exception e)
{
Log.ErrorOnce("[Blax Slaves] Records tab row failed: " + e, 0x6B1A61);
}
}
private static float DrawRow(Rect column, float curY, Pawn pawn)
{
float width = column.width - Indent;
float valueWidth = width * ValueShare;
string value = TimeAsSlave.RecordValue(pawn);
var row = new Rect(column.x + Indent, column.y + curY, width, Text.CalcHeight(value, valueWidth));
bool over = Mouse.IsOver(row);
if (over)
Widgets.DrawHighlight(row);
Rect labelRect = row;
labelRect.width -= valueWidth;
Widgets.Label(labelRect, TimeAsSlave.RecordLabel);
Rect valueRect = row;
valueRect.x = labelRect.xMax;
valueRect.width = valueWidth;
Widgets.Label(valueRect, value);
if (over)
TooltipHandler.TipRegion(row, new TipSignal(TimeAsSlave.RecordTooltip, 0x6B1A62));
return row.height;
}
}
///
/// One extra line in the slave tab, drawn under "Slave price". Shown for colony slaves only unless
/// prisonersToo is set, because vanilla draws the slave price in the prisoner tab as well.
///
public sealed class SlaveTabLine
{
public readonly string id;
public readonly Func label;
public readonly Func tooltip;
public readonly Func visible;
public readonly bool prisonersToo;
public SlaveTabLine(string id, Func label, Func tooltip = null,
Func visible = null, bool prisonersToo = false)
{
this.id = id;
this.label = label;
this.tooltip = tooltip;
this.visible = visible;
this.prisonersToo = prisonersToo;
}
}
///
/// The one place that adds lines to the slave tab (time as a slave now; appraised value, persuasion,
/// loyalty and indenture term in later releases). Add a line once at startup; Add replaces a line with
/// the same id, so registering twice never doubles it. Each line runs in its own try/catch, so a broken
/// line logs once and the rest of the tab still draws.
///
public static class SlaveTabLines
{
private static readonly List lines = new List { TimeAsSlave.Line };
public static IReadOnlyList All => lines;
public static void Add(SlaveTabLine line)
{
if (line?.id == null || line.label == null)
return;
int i = lines.FindIndex(l => l.id == line.id);
if (i >= 0)
lines[i] = line;
else
lines.Add(line);
}
public static bool Remove(string id) => lines.RemoveAll(l => l.id == id) > 0;
public static bool Shows(SlaveTabLine line, Pawn pawn)
{
if (line == null || pawn?.guest == null)
return false;
bool colonySlave = pawn.guest.IsSlave && pawn.Faction != null && pawn.Faction.IsPlayer;
bool colonyPrisoner = pawn.guest.IsPrisoner && pawn.guest.HostFaction != null && pawn.guest.HostFaction.IsPlayer;
if (!colonySlave && !(line.prisonersToo && colonyPrisoner))
return false;
return line.visible == null || line.visible(pawn);
}
/// The labels the tab would show for this pawn, in order. Needs no GUI, so tests can read it.
public static List LabelsFor(Pawn pawn)
{
var result = new List();
foreach (SlaveTabLine line in lines)
{
try
{
if (!Shows(line, pawn))
continue;
string label = line.label(pawn);
if (!label.NullOrEmpty())
result.Add(label);
}
catch (Exception e)
{
LogOnce(line, e);
}
}
return result;
}
internal static void Draw(Listing_Standard listing, Pawn pawn)
{
if (listing == null || pawn == null)
return;
for (int i = 0; i < lines.Count; i++)
{
SlaveTabLine line = lines[i];
try
{
if (!Shows(line, pawn))
continue;
string label = line.label(pawn);
if (label.NullOrEmpty())
continue;
// Listing_Standard.Label measures the wrapped height, and ITab_Pawn_Visitor.FillTab sizes
// the tab from listing.CurHeight afterwards, so a long translation grows the tab instead
// of being cut off.
Rect rect = listing.Label(label);
if (line.tooltip != null && Mouse.IsOver(rect))
{
Widgets.DrawHighlight(rect);
string tip = line.tooltip(pawn);
if (!tip.NullOrEmpty())
TooltipHandler.TipRegion(rect, tip);
}
}
catch (Exception e)
{
LogOnce(line, e);
}
}
}
private static void LogOnce(SlaveTabLine line, Exception e) =>
Log.ErrorOnce("[Blax Slaves] Slave tab line " + line?.id + " failed: " + e, 0x6B1A60 ^ (line?.id?.GetHashCode() ?? 0));
}
///
/// Draws the extra slave tab lines right after vanilla's "Slave price". DoSlavePriceListing is private
/// and also runs in the prisoner tab; SlaveTabLines decides per line who sees it.
///
[HarmonyPatch(typeof(ITab_Pawn_Visitor), "DoSlavePriceListing")]
public static class Patch_SlaveTabLines
{
private static Func selPawn;
private static bool bound;
public static void Postfix(ITab_Pawn_Visitor __instance, Listing_Standard listing)
{
SlaveTabLines.Draw(listing, PawnOf(__instance));
}
///
/// The pawn the tab shows. ITab.SelPawn is protected (and virtual), so it is bound once by
/// reflection; if that ever fails, the single selected thing is what vanilla's getter returns.
///
public static Pawn PawnOf(ITab tab)
{
if (!bound)
{
bound = true;
try
{
MethodInfo getter = AccessTools.PropertyGetter(typeof(ITab), "SelPawn");
if (getter != null)
selPawn = AccessTools.MethodDelegate>(getter);
}
catch (Exception e)
{
Log.Warning("[Blax Slaves] ITab.SelPawn not found, the slave tab uses the selection instead: " + e.Message);
selPawn = null;
}
}
if (tab != null && selPawn != null)
return selPawn(tab);
return Find.Selector?.SingleSelectedThing as Pawn;
}
}
}