rimworld-blax-castes/Source/BlaxCastes/Dialog_ManageCastes.cs

726 lines
36 KiB
C#
Raw Normal View History

using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.Sound;
namespace BlaxCastes
{
/// <summary>
/// The caste manager, built on the vanilla policy manager: the base class draws the caste list and
/// handles new, duplicate, rename, delete (with its confirm) and make default. The right side scrolls:
/// one row per policy slot (a managed checkbox, a dropdown and a pencil that opens the vanilla policy
/// editor), the weapon loadout row while Weapons Tab Reborn is active, the schedule (a 24-hour grid
/// painted like the vanilla Schedule tab, with the vanilla time assignment selector as the brush) and
/// the work priorities (a cycle button per work type). Below the scroll area sit the member count and
/// "Apply to all members"; "Assign by status" sits left of the close button. Both ask first.
/// Every change goes through CasteManager, so member sync and the delete rules always apply.
/// The base layout changed in 1.6, so DoContentsRect only draws inside the rect it is given.
/// </summary>
public class Dialog_ManageCastes : Dialog_ManagePolicies<Caste>
{
private const float RowHeight = 32f;
private const float RowGap = 6f;
private const float SlotLabelWidth = 110f;
private const float IconSize = 24f;
private const float Gap = 8f;
private const float AssignByStatusWidth = 200f;
private const float CreateButtonWidth = 180f;
private const float FooterHeight = 30f;
private const float ScrollBarWidth = 16f;
private const float ValueX = SlotLabelWidth + IconSize + Gap;
private const float SmallButtonHeight = 26f;
private const float MinBrushWidth = 64f;
private const float MaxBrushWidth = 96f;
private const float BrushHeight = 28f;
private const float HourLabelHeight = 16f;
private const float HourCellHeight = 24f;
private const int WorkColumns = 3;
private const float WorkRowHeight = 26f;
private const float WorkButtonWidth = 44f;
private static readonly List<Caste> NoCastes = new List<Caste>();
private static Texture2D[] medCareIcons;
private Vector2 scrollPosition;
private float contentHeight = 600f;
private readonly WorkCycle workCycle = new WorkCycle();
public Dialog_ManageCastes() : this(null)
{
}
/// <summary>Opens with the given caste selected, or with none selected when it is null.</summary>
public Dialog_ManageCastes(Caste caste) : base(caste)
{
}
protected override string TitleKey => "BlaxCastes_ManageCastesTitle";
protected override string TipKey => "BlaxCastes_ManageCastesTip";
public override Vector2 InitialSize => new Vector2(860f, 700f);
private static GameComponent_BlaxCastes Comp => GameComponent_BlaxCastes.Instance;
public override void DoWindowContents(Rect inRect)
{
GameComponent_BlaxCastes comp = Comp;
// A policy deleted in a vanilla editor opened from here must not stay in a caste slot.
CasteManager.CheckSlots(comp);
if (SelectedPolicy != null && (comp == null || !comp.HasCaste(SelectedPolicy)))
SelectedPolicy = null;
base.DoWindowContents(inRect);
DoMakeDefaultTip(inRect);
DoAssignByStatusButton(inRect);
}
/// <summary>
/// The base class gives "Make default" the vanilla tooltip about new colonists. Over the same
/// button, that tip is cleared and replaced by one about Default caste rows.
/// </summary>
private void DoMakeDefaultTip(Rect inRect)
{
if (SelectedPolicy == null || GetDefaultPolicy() == SelectedPolicy)
return;
Rect button = MakeDefaultButtonRect(inRect);
if (!Mouse.IsOver(button))
return;
TooltipHandler.ClearTooltipsFrom(button);
TooltipHandler.TipRegion(button, "BlaxCastes_MakeDefaultTip".Translate());
}
/// <summary>Where the base class draws "Make default": the fourth 32 px button from the right, below title and tip.</summary>
public static Rect MakeDefaultButtonRect(Rect inRect) => new Rect(inRect.xMax - 32f - 3 * 42f, inRect.y + 74f, 32f, 32f);
/// <summary>
/// "Assign by status", left of the close button. Shown only while there are pawns without a caste
/// record whose status row gives them a caste. It replaces those pawns' own policies with their
/// caste's, which cannot be undone, so it asks first, like "Apply to all members".
/// </summary>
private static void DoAssignByStatusButton(Rect inRect)
{
if (Comp == null)
return;
int count = CasteManager.PawnsToAssignByStatus().Count;
if (count == 0)
return;
var button = new Rect(inRect.x, inRect.yMax - CloseButSize.y, AssignByStatusWidth, CloseButSize.y);
if (Widgets.ButtonText(button, "BlaxCastes_AssignByStatus".Translate(count)))
{
Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(AssignByStatusConfirmText(count), () =>
{
int assigned = CasteManager.AssignByStatus();
Messages.Message("BlaxCastes_AssignByStatusDone".Translate(assigned), MessageTypeDefOf.NeutralEvent, historical: false);
}, destructive: true));
}
TooltipHandler.TipRegion(button, "BlaxCastes_AssignByStatusTip".Translate(count));
}
/// <summary>The confirm text for "Assign by status", naming the pawn count.</summary>
public static string AssignByStatusConfirmText(int count) =>
"BlaxCastes_AssignByStatusConfirm".Translate(count.Named("COUNT"));
// ---- base class hooks ------------------------------------------------------------------
/// <summary>A new caste with the next free id, labelled "Caste N", managing nothing.</summary>
protected override Caste CreateNewPolicy() => CasteManager.CreateCaste();
protected override List<Caste> GetPolicies() => Comp?.Castes ?? NoCastes;
protected override Caste GetDefaultPolicy() => Comp?.DefaultCaste;
protected override void SetDefaultPolicy(Caste policy) => CasteManager.SetDefault(policy);
/// <summary>Members become casteless and keep their policies; rows pointing at the caste fall back to No caste.</summary>
protected override AcceptanceReport TryDeletePolicy(Caste policy)
{
if (CasteManager.DeleteCaste(policy))
return AcceptanceReport.WasAccepted;
return "BlaxCastes_DeleteFailed".Translate(policy?.label ?? "");
}
protected override void DoContentsRect(Rect rect)
{
Caste caste = SelectedPolicy;
if (caste == null)
return;
var footer = new Rect(rect.x, rect.yMax - FooterHeight, rect.width, FooterHeight);
var outRect = new Rect(rect.x, rect.y, rect.width, footer.y - Gap - rect.y);
var viewRect = new Rect(0f, 0f, outRect.width - ScrollBarWidth, Mathf.Max(contentHeight, outRect.height));
Widgets.BeginScrollView(outRect, ref scrollPosition, viewRect);
contentHeight = DoSlots(viewRect.width, caste, workCycle);
Widgets.EndScrollView();
DoFooter(footer, caste, workCycle);
}
/// <summary>Draws every slot from the top of the scroll view; returns the height used.</summary>
private static float DoSlots(float width, Caste caste, WorkCycle cycle)
{
float y = 0f;
foreach (CasteSlot slot in CasteUtility.PolicySlots)
{
DoSlotRow(new Rect(0f, y, width, RowHeight), caste, slot, active: true, note: null);
y += RowHeight + RowGap;
}
if (!caste.IsManaged(CasteSlot.Apparel) && StarterCastes.CanCreateSlaveOutfit)
{
var create = new Rect(ValueX, y, CreateButtonWidth, FooterHeight - 4f);
if (Widgets.ButtonText(create, "BlaxCastes_CreateSlaveOutfit".Translate()))
{
ApparelPolicy outfit = StarterCastes.CreateSlaveOutfit();
if (outfit != null)
CasteManager.SetSlot(caste, CasteSlot.Apparel, outfit);
}
TooltipHandler.TipRegion(create, "BlaxCastes_CreateSlaveOutfitTip".Translate());
y += FooterHeight + 2f;
}
if (StarterCastes.IsSlaveOutfit(caste.ApparelPolicy))
y = DoNote(width, y, "BlaxCastes_SlaveOutfitCold".Translate(), ColorLibrary.Gold);
if (ShowsLoadoutRow)
y = DoLoadoutRow(width, y, caste);
y += Gap;
y = DoSchedule(width, y, caste);
y += Gap * 2f;
y = DoWork(width, y, caste, cycle);
y += Gap * 2f;
y = DoNote(width, y, "BlaxCastes_ManagerHint".Translate(), Color.gray);
return y;
}
/// <summary>A Tiny label across the width; returns the y below it.</summary>
private static float DoNote(float width, float y, string text, Color color)
{
using (new TextBlock(GameFont.Tiny, color))
{
float h = Text.CalcHeight(text, width);
Widgets.Label(new Rect(0f, y, width, h), text);
return y + h + 4f;
}
}
/// <summary>The member count and "Apply to all members", which asks first, naming the count.</summary>
private static void DoFooter(Rect footer, Caste caste, WorkCycle cycle)
{
List<Pawn> members = CasteManager.LiveMembers(caste);
const float buttonWidth = 180f;
var button = new Rect(footer.xMax - buttonWidth, footer.y, buttonWidth, footer.height);
var label = new Rect(footer.x, footer.y, button.x - footer.x - Gap, footer.height);
using (new TextBlock(TextAnchor.MiddleLeft))
Widgets.Label(label, "BlaxCastes_MemberCount".Translate(members.Count));
if (members.Count == 0 || !caste.AnyManaged())
return;
if (Widgets.ButtonText(button, "BlaxCastes_ApplyToAll".Translate()))
{
Caste local = caste;
Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(
ApplyToAllConfirmText(local, members.Count),
() =>
{
CasteManager.ApplyToAll(local);
cycle.End(); // every member follows again, so the next click takes the followers anew
},
destructive: true));
}
TooltipHandler.TipRegion(button, "BlaxCastes_ApplyToAllTip".Translate());
}
/// <summary>The confirm text for "Apply to all members", naming the caste and the member count.</summary>
public static string ApplyToAllConfirmText(Caste caste, int count) =>
"BlaxCastes_ApplyToAllConfirm".Translate(caste.label.Named("CASTE"), count.Named("COUNT"));
// ---- policy, medical care and loadout rows -------------------------------------------
/// <summary>
/// One row: label, managed checkbox, dropdown and (for policies) the pencil. Inactive: greyed out,
/// with the note as tooltip, and nothing can be changed.
/// </summary>
private static void DoSlotRow(Rect row, Caste caste, CasteSlot slot, bool active, string note)
{
float iconY = row.y + (row.height - IconSize) / 2f;
Rect labelRect = new Rect(row.x, row.y, SlotLabelWidth, row.height);
Rect checkRect = new Rect(labelRect.xMax, iconY, IconSize, IconSize);
Rect pencilRect = new Rect(row.xMax - IconSize, iconY, IconSize, IconSize);
Rect dropRect = new Rect(checkRect.xMax + Gap, row.y + 2f, 0f, row.height - 4f);
dropRect.xMax = pencilRect.x - Gap;
if (Mouse.IsOver(row))
Widgets.DrawHighlight(row);
using (new TextBlock(TextAnchor.MiddleLeft, active ? Color.white : Color.gray))
Widgets.Label(labelRect, CasteUtility.SlotLabel(slot).Truncate(labelRect.width));
bool managed = caste.IsManaged(slot);
bool wasManaged = managed;
Widgets.Checkbox(checkRect.x, checkRect.y, ref managed, IconSize, disabled: !active);
TooltipHandler.TipRegion(checkRect, "BlaxCastes_ManagedTip".Translate());
if (active && managed != wasManaged)
SetManaged(caste, slot, managed);
string valueLabel = CasteUtility.ValueLabel(slot, caste.GetSlot(slot)).CapitalizeFirst();
if (!active)
{
using (new TextBlock(TextAnchor.MiddleLeft, Color.gray))
Widgets.Label(dropRect, valueLabel.Truncate(dropRect.width));
if (!note.NullOrEmpty())
TooltipHandler.TipRegion(row, note);
return;
}
switch (slot)
{
case CasteSlot.MedCare:
Widgets.Dropdown(dropRect, caste, c => c.MedCare, c => MedCareMenu(c), valueLabel.Truncate(dropRect.width));
return;
case CasteSlot.Loadout:
Widgets.Dropdown(dropRect, caste, c => c.LoadoutId, c => LoadoutMenu(c), valueLabel.Truncate(dropRect.width));
TooltipHandler.TipRegion(row, "BlaxCastes_LoadoutTip".Translate());
return;
}
Widgets.Dropdown(dropRect, caste, c => c.GetSlot(slot) as Policy, c => PolicyMenu(c, slot), valueLabel.Truncate(dropRect.width));
if (Widgets.ButtonImage(pencilRect, TexButton.Rename, tooltip: EditorTip(slot)))
OpenPolicyEditor(slot, caste.GetSlot(slot) as Policy);
}
/// <summary>The loadout row is shown only while Weapons Tab Reborn is active.</summary>
public static bool ShowsLoadoutRow => WeaponsTab.ModActive;
/// <summary>The loadout row, greyed out while the setting is off or the mod's API could not be used.</summary>
private static float DoLoadoutRow(float width, float y, Caste caste)
{
string note = null;
if (!WeaponsTab.Available)
note = "BlaxCastes_LoadoutUnavailable".Translate();
else if (!WeaponsTab.SettingOn)
note = "BlaxCastes_LoadoutSettingOff".Translate();
DoSlotRow(new Rect(0f, y, width, RowHeight), caste, CasteSlot.Loadout, note == null, note);
y += RowHeight + RowGap;
if (note != null)
y = DoNote(width, y, note, Color.gray);
return y;
}
/// <summary>The vanilla Assign tab's "Manage ... policies" text for the slot's editor.</summary>
private static string EditorTip(CasteSlot slot)
{
switch (slot)
{
case CasteSlot.Apparel: return "ManageApparelPolicies".Translate();
case CasteSlot.Food: return "ManageFoodPolicies".Translate();
case CasteSlot.Drug: return "ManageDrugPolicies".Translate();
case CasteSlot.Reading: return "ManageReadingPolicies".Translate();
default: return null;
}
}
private static IEnumerable<Widgets.DropdownMenuElement<Policy>> PolicyMenu(Caste caste, CasteSlot slot)
{
yield return new Widgets.DropdownMenuElement<Policy>
{
option = new FloatMenuOption("BlaxCastes_Unmanaged".Translate(), () => CasteManager.SetSlot(caste, slot, null)),
payload = null,
};
foreach (Policy policy in PoliciesFor(slot))
{
Policy local = policy;
yield return new Widgets.DropdownMenuElement<Policy>
{
option = new FloatMenuOption(local.label, () => CasteManager.SetSlot(caste, slot, local)),
payload = local,
};
}
}
private static IEnumerable<Widgets.DropdownMenuElement<int>> MedCareMenu(Caste caste)
{
yield return new Widgets.DropdownMenuElement<int>
{
option = new FloatMenuOption("BlaxCastes_Unmanaged".Translate(), () => CasteManager.SetSlot(caste, CasteSlot.MedCare, null)),
payload = Caste.Unmanaged,
};
for (int i = (int)MedicalCareCategory.NoCare; i <= (int)MedicalCareCategory.Best; i++)
{
var care = (MedicalCareCategory)i;
yield return new Widgets.DropdownMenuElement<int>
{
option = new FloatMenuOption(care.GetLabel().CapitalizeFirst(), () => CasteManager.SetSlot(caste, CasteSlot.MedCare, care), MedCareIcon(care), Color.white),
payload = i,
};
}
}
private static IEnumerable<Widgets.DropdownMenuElement<int>> LoadoutMenu(Caste caste)
{
yield return new Widgets.DropdownMenuElement<int>
{
option = new FloatMenuOption("BlaxCastes_Unmanaged".Translate(), () => CasteManager.SetSlot(caste, CasteSlot.Loadout, Caste.Unmanaged)),
payload = Caste.Unmanaged,
};
foreach (KeyValuePair<int, string> loadout in WeaponsTab.Loadouts())
{
int id = loadout.Key;
yield return new Widgets.DropdownMenuElement<int>
{
option = new FloatMenuOption(loadout.Value, () => CasteManager.SetSlot(caste, CasteSlot.Loadout, id)),
payload = id,
};
}
}
/// <summary>The same icons the vanilla medical care button uses. Loaded on first draw.</summary>
private static Texture2D MedCareIcon(MedicalCareCategory care)
{
if (medCareIcons == null)
{
medCareIcons = new[]
{
ContentFinder<Texture2D>.Get("UI/Icons/Medical/NoCare", reportFailure: false),
ContentFinder<Texture2D>.Get("UI/Icons/Medical/NoMeds", reportFailure: false),
ThingDefOf.MedicineHerbal?.uiIcon,
ThingDefOf.MedicineIndustrial?.uiIcon,
ThingDefOf.MedicineUltratech?.uiIcon,
};
}
int i = (int)care;
return i >= 0 && i < medCareIcons.Length ? medCareIcons[i] : null;
}
private static void OpenPolicyEditor(CasteSlot slot, Policy policy)
{
switch (slot)
{
case CasteSlot.Apparel:
Find.WindowStack.Add(new Dialog_ManageApparelPolicies(policy as ApparelPolicy));
break;
case CasteSlot.Food:
Find.WindowStack.Add(new Dialog_ManageFoodPolicies(policy as FoodPolicy));
break;
case CasteSlot.Drug:
Find.WindowStack.Add(new Dialog_ManageDrugPolicies(policy as DrugPolicy));
break;
case CasteSlot.Reading:
Find.WindowStack.Add(new Dialog_ManageReadingPolicies(policy as ReadingPolicy));
break;
}
}
// ---- schedule ----------------------------------------------------------------------------
/// <summary>
/// The schedule: the vanilla time assignment selector picks the brush; click or drag over the 24
/// cells to paint, the way the vanilla Schedule tab works. While the caste leaves the schedule
/// alone, the cells show the game's starting schedule faded, and painting one starts from it.
/// </summary>
private static float DoSchedule(float width, float y, Caste caste)
{
bool managed = caste.IsManaged(CasteSlot.Schedule);
using (new TextBlock(TextAnchor.MiddleLeft))
Widgets.Label(new Rect(0f, y, SlotLabelWidth, BrushHeight), CasteUtility.SlotLabel(CasteSlot.Schedule));
// The vanilla selector draws one row of brushes in the top half of its rect, each half as wide as the rect.
float brushWidth = BrushWidthFor(width);
TimeAssignmentSelector.DrawTimeAssignmentSelectorGrid(new Rect(ValueX, y, brushWidth * 2f, BrushHeight * 2f + 2f));
y += BrushHeight + 4f;
float cellWidth = (width - ValueX) / ScheduleSlot.Hours;
using (new TextBlock(GameFont.Tiny, TextAnchor.LowerCenter))
{
for (int hour = 0; hour < ScheduleSlot.Hours; hour++)
Widgets.Label(new Rect(ValueX + hour * cellWidth, y, cellWidth, HourLabelHeight), hour.ToString());
}
y += HourLabelHeight;
IReadOnlyList<string> names = caste.Schedule ?? ScheduleSlot.Default();
bool mouseDown = Input.GetMouseButton(0);
TimeAssignmentDef brush = TimeAssignmentSelector.selectedAssignment;
var grid = new Rect(ValueX, y, cellWidth * ScheduleSlot.Hours, HourCellHeight);
for (int hour = 0; hour < ScheduleSlot.Hours; hour++)
{
Rect cell = new Rect(ValueX + hour * cellWidth, y, cellWidth, HourCellHeight).ContractedBy(1f);
TimeAssignmentDef def = ScheduleSlot.Resolve(names[hour]);
GUI.color = managed ? Color.white : new Color(1f, 1f, 1f, 0.35f);
GUI.DrawTexture(cell, def.ColorTexture);
GUI.color = Color.white;
if (!mouseDown)
MouseoverSounds.DoRegion(cell);
if (!Mouse.IsOver(cell))
continue;
Widgets.DrawBox(cell, 2);
if (mouseDown && brush != null && (def != brush || !managed))
{
PaintHour(caste, hour, brush);
SoundDefOf.Designate_DragStandard_Changed_NoCam.PlayOneShotOnCamera();
}
}
TooltipHandler.TipRegion(grid, managed ? "BlaxCastes_ScheduleTip".Translate() : "BlaxCastes_ScheduleUnmanagedTip".Translate());
y += HourCellHeight + 4f;
var copy = new Rect(ValueX, y, 150f, SmallButtonHeight);
if (Widgets.ButtonText(copy, "BlaxCastes_ScheduleCopyFromPawn".Translate()))
Find.WindowStack.Add(new FloatMenu(CopyFromPawnOptions(caste)));
TooltipHandler.TipRegion(copy, "BlaxCastes_ScheduleCopyFromPawnTip".Translate());
var leave = new Rect(copy.xMax + Gap, y, 120f, SmallButtonHeight);
if (Widgets.ButtonText(leave, "BlaxCastes_Unmanaged".Translate(), active: managed) && managed)
CasteManager.SetSlot(caste, CasteSlot.Schedule, null);
TooltipHandler.TipRegion(leave, "BlaxCastes_ScheduleLeaveAloneTip".Translate());
return y + SmallButtonHeight;
}
/// <summary>
/// The width of one schedule brush: the row's width shared by the brushes (four, five with Royalty),
/// between 64 and 96 px. The vanilla Schedule tab gives each about 92 px; 64 is too narrow for
/// "Recreation" in the Small font.
/// </summary>
public static float BrushWidthFor(float width)
{
int brushes = ModsConfig.RoyaltyActive ? 5 : 4;
return Mathf.Clamp((width - ValueX) / brushes, MinBrushWidth, MaxBrushWidth);
}
private static List<FloatMenuOption> CopyFromPawnOptions(Caste caste)
{
var options = new List<FloatMenuOption>();
foreach (Pawn pawn in SchedulePawns())
{
Pawn local = pawn;
options.Add(new FloatMenuOption(local.LabelShortCap, () => CopyScheduleFrom(caste, local)));
}
if (options.Count == 0)
options.Add(new FloatMenuOption("BlaxCastes_ScheduleNoPawns".Translate(), null));
return options;
}
/// <summary>The pawns "Copy from pawn" lists: colonists and slaves of the player that have a schedule, by name.</summary>
public static List<Pawn> SchedulePawns()
{
if (Current.Game == null)
return new List<Pawn>();
return PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_OfPlayerFaction
.Where(p => p.RaceProps != null && p.RaceProps.Humanlike && !p.IsPrisoner && ScheduleSlot.HasTimetable(p))
.OrderBy(p => p.LabelShort)
.ToList();
}
/// <summary>"Copy from pawn": the caste takes the pawn's 24 hours; members follow. Returns how many moved.</summary>
public static int CopyScheduleFrom(Caste caste, Pawn pawn)
{
string[] names = ScheduleSlot.Of(pawn);
return caste == null || names == null ? 0 : CasteManager.SetSlot(caste, CasteSlot.Schedule, names);
}
/// <summary>
/// Paints one hour. A caste that left the schedule alone starts from the game's starting schedule.
/// Members follow, hour by hour. Returns how many moved.
/// </summary>
public static int PaintHour(Caste caste, int hour, TimeAssignmentDef def)
{
if (caste == null || def == null || hour < 0 || hour >= ScheduleSlot.Hours)
return 0;
List<string> names = caste.Schedule?.ToList() ?? ScheduleSlot.Default();
names[hour] = def.defName;
return CasteManager.SetSlot(caste, CasteSlot.Schedule, names);
}
// ---- work priorities ---------------------------------------------------------------------
/// <summary>
/// The work priorities: "Start from nothing" and a cycle button per work type (leave alone, 1, 2,
/// 3, 4, off). Greyed out with a note while the setting is off or an automatic work manager is active.
/// </summary>
private static float DoWork(float width, float y, Caste caste, WorkCycle cycle)
{
bool active = WorkSlot.Active;
using (new TextBlock(TextAnchor.MiddleLeft, active ? Color.white : Color.gray))
Widgets.Label(new Rect(0f, y, SlotLabelWidth, RowHeight - 4f), CasteUtility.SlotLabel(CasteSlot.Work));
var startRect = new Rect(ValueX, y + 2f, Mathf.Min(260f, width - ValueX), IconSize);
bool start = caste.WorkStartFromNothing;
bool wasStart = start;
Widgets.CheckboxLabeled(startRect, "BlaxCastes_WorkStartFromNothing".Translate(), ref start, disabled: !active, placeCheckboxNearText: true);
if (active && start != wasStart)
CasteManager.SetWorkStartFromNothing(caste, start);
TooltipHandler.TipRegion(startRect, () => StartFromNothingTip(), 0x5F3A21);
y += RowHeight - 2f;
string note = WorkNote();
if (note != null)
y = DoNote(width, y, note, active ? Color.gray : ColorLibrary.Gold);
List<WorkTypeDef> types = WorkSlot.Types();
float columnWidth = width / WorkColumns;
for (int i = 0; i < types.Count; i++)
{
WorkTypeDef def = types[i];
var cell = new Rect((i % WorkColumns) * columnWidth, y + (i / WorkColumns) * WorkRowHeight, columnWidth - Gap, WorkRowHeight - 2f);
var button = new Rect(cell.xMax - WorkButtonWidth, cell.y, WorkButtonWidth, cell.height);
var label = new Rect(cell.x + 4f, cell.y, button.x - cell.x - 6f, cell.height);
int? priority = caste.WorkPriorityOf(def.defName);
if (Mouse.IsOver(cell))
Widgets.DrawHighlight(cell);
using (new TextBlock(TextAnchor.MiddleLeft, active && priority != null ? Color.white : Color.gray))
Widgets.Label(label, WorkSlot.TypeLabel(def).Truncate(label.width));
if (active)
{
if (Widgets.ButtonText(button, WorkSlot.PriorityLabel(priority)))
cycle.Click(caste, def);
}
else
{
using (new TextBlock(TextAnchor.MiddleCenter, Color.gray))
Widgets.Label(button, WorkSlot.PriorityLabel(priority));
}
if (Mouse.IsOver(cell))
{
WorkTypeDef local = def;
TooltipHandler.TipRegion(cell, () => "BlaxCastes_WorkTypeTip".Translate(
(local.gerundLabel ?? local.label).CapitalizeFirst().Named("WORK"), (local.description ?? "").Named("DESC")), local.index ^ 0x3A71C4);
}
}
int rows = (types.Count + WorkColumns - 1) / WorkColumns;
return y + rows * WorkRowHeight;
}
/// <summary>The line under the work priorities heading, or null: setting off, a work manager, or manual priorities off.</summary>
public static string WorkNote()
{
if (!WorkSlot.SettingOn)
return "BlaxCastes_WorkSettingOff".Translate();
string manager = WorkSlot.ActiveManager();
if (manager != null)
return "BlaxCastes_WorkManagerActive".Translate(manager);
if (!WorkSlot.ManualPriorities)
return "BlaxCastes_WorkManualOff".Translate();
return null;
}
/// <summary>The tooltip of "Start from nothing", naming the work types it keeps (Patient and Bed rest).</summary>
public static string StartFromNothingTip()
{
string kept = WorkSlot.SelfCareTypes().Select(t => WorkSlot.TypeLabel(t)).ToCommaList(useAnd: true);
return "BlaxCastes_WorkStartFromNothingTip".Translate(kept.Named("KEPT"));
}
/// <summary>One click on a cycle button, with no clicks before it: members that follow the type move. Returns how many moved.</summary>
public static int CycleWork(Caste caste, WorkTypeDef def, bool forward = true) => new WorkCycle().Click(caste, def, forward);
/// <summary>
/// A run of clicks on one work type's cycle button (leave alone, 1, 2, 3, 4, off, leave alone). The
/// members that follow the type are taken before the first click, and every click of the run moves
/// only them. Stepping 3, 4, off, leave alone, 1 to reach 1 therefore never picks up a pawn set to 4
/// or off by hand on the way. A click on another type or caste, a change to the type from anywhere
/// else, "Apply to all members" or closing the window starts a new run. Each window has its own.
/// </summary>
public sealed class WorkCycle
{
private Caste caste;
private string defName;
private int? lastValue;
private List<Pawn> followers;
/// <summary>Cycles the type one step and moves the run's followers. Returns how many moved.</summary>
public int Click(Caste target, WorkTypeDef def, bool forward = true)
{
if (target == null || def == null)
return 0;
int? current = target.WorkPriorityOf(def.defName);
if (followers == null || caste != target || defName != def.defName || lastValue != current)
{
caste = target;
defName = def.defName;
followers = CasteManager.WorkFollowers(target, def.defName);
}
int? next = forward ? WorkSlot.Next(current) : WorkSlot.Previous(current);
lastValue = next;
return CasteManager.SetWorkPriority(target, def.defName, next, followers);
}
/// <summary>Ends the run: the next click takes the followers anew.</summary>
public void End()
{
caste = null;
defName = null;
followers = null;
}
}
// ---- helpers the rows use; public so the tests can drive them --------------------------
/// <summary>The game's policies that fit a slot, in database order. Empty for the other slots.</summary>
public static IEnumerable<Policy> PoliciesFor(CasteSlot slot)
{
Game game = Current.Game;
if (game == null)
yield break;
IEnumerable<Policy> source;
switch (slot)
{
case CasteSlot.Apparel: source = game.outfitDatabase?.AllOutfits; break;
case CasteSlot.Food: source = game.foodRestrictionDatabase?.AllFoodRestrictions; break;
case CasteSlot.Drug: source = game.drugPolicyDatabase?.AllPolicies; break;
case CasteSlot.Reading: source = game.readingPolicyDatabase?.AllReadingPolicies; break;
default: source = null; break;
}
if (source == null)
yield break;
foreach (Policy p in source)
{
if (p != null)
yield return p;
}
}
/// <summary>
/// What ticking the managed box sets: the database's default policy, the colonist default medical
/// care, the game's starting schedule or Weapons Tab Reborn's default loadout. Null when no game is
/// loaded, and for work priorities, which are set type by type.
/// </summary>
public static object DefaultValue(CasteSlot slot)
{
Game game = Current.Game;
if (game == null)
return null;
switch (slot)
{
case CasteSlot.Apparel: return game.outfitDatabase?.DefaultOutfit();
case CasteSlot.Food: return game.foodRestrictionDatabase?.DefaultFoodRestriction();
case CasteSlot.Drug: return game.drugPolicyDatabase?.DefaultDrugPolicy();
case CasteSlot.Reading: return game.readingPolicyDatabase?.DefaultReadingPolicy();
case CasteSlot.MedCare: return (int)(game.playSettings?.defaultCareForColonist ?? MedicalCareCategory.Best);
case CasteSlot.Schedule: return ScheduleSlot.Default();
case CasteSlot.Loadout: return WeaponsTab.DefaultLoadoutId();
default: return null;
}
}
/// <summary>
/// The managed checkbox. Ticking a slot sets the default value (members follow, see
/// CasteManager.SetSlot); unticking leaves every pawn as it is. Returns how many members moved.
/// </summary>
public static int SetManaged(Caste caste, CasteSlot slot, bool managed)
{
if (caste == null || caste.IsManaged(slot) == managed)
return 0;
if (!managed)
return CasteManager.SetSlot(caste, slot, null);
object value = DefaultValue(slot);
return value == null ? 0 : CasteManager.SetSlot(caste, slot, value);
}
// ---- first-load message ----------------------------------------------------------------
/// <summary>
/// Posts the message that points to Assign > Manage castes. The game component calls this once
/// per save and stores the result. Returns false (try again on the next load) while the Caste
/// column is turned off, because the message would point to a button that is not there.
/// </summary>
public static bool ShowFirstLoadMessage()
{
if (BlaxCastesMod.Settings != null && !BlaxCastesMod.Settings.showAssignColumn)
return false;
string text = "BlaxCastes_FirstLoadMessage".Translate();
LongEventHandler.ExecuteWhenFinished(() => Messages.Message(text, MessageTypeDefOf.NeutralEvent));
return true;
}
}
}