using System.Collections.Generic; using System.Linq; using RimWorld; using UnityEngine; using Verse; using Verse.Sound; namespace BlaxCastes { /// /// 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. /// public class Dialog_ManageCastes : Dialog_ManagePolicies { 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 NoCastes = new List(); private static Texture2D[] medCareIcons; /// The left button went down on the schedule grid and is still held (SchedulePaintAllowed). private static bool schedulePaintStarted; private Vector2 scrollPosition; private float contentHeight = 600f; private readonly WorkCycle workCycle = new WorkCycle(); public Dialog_ManageCastes() : this(null) { } /// Opens with the given caste selected, or with none selected when it is null. 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, workCycle); } /// /// 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. /// 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()); } /// Where the base class draws "Make default": the fourth 32 px button from the right, below title and tip. public static Rect MakeDefaultButtonRect(Rect inRect) => new Rect(inRect.xMax - 32f - 3 * 42f, inRect.y + 74f, 32f, 32f); /// /// "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". /// private static void DoAssignByStatusButton(Rect inRect, WorkCycle cycle) { 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 = AssignByStatus(cycle); Messages.Message("BlaxCastes_AssignByStatusDone".Translate(assigned), MessageTypeDefOf.NeutralEvent, historical: false); }, destructive: true)); } TooltipHandler.TipRegion(button, "BlaxCastes_AssignByStatusTip".Translate(count)); } /// /// The confirmed "Assign by status": CasteManager.AssignByStatus, and the pawns it put into the caste /// of the window's work cycle run join that run's followers (WorkCycle.AddJoined). Returns how many /// were assigned. /// public static int AssignByStatus(WorkCycle cycle) { var assigned = new List(); int count = CasteManager.AssignByStatus(assigned); cycle?.AddJoined(assigned); return count; } /// The confirm text for "Assign by status", naming the pawn count. public static string AssignByStatusConfirmText(int count) => "BlaxCastes_AssignByStatusConfirm".Translate(count.Named("COUNT")); // ---- base class hooks ------------------------------------------------------------------ /// A new caste with the next free id, labelled "Caste N", managing nothing. protected override Caste CreateNewPolicy() => CasteManager.CreateCaste(); protected override List GetPolicies() => Comp?.Castes ?? NoCastes; protected override Caste GetDefaultPolicy() => Comp?.DefaultCaste; protected override void SetDefaultPolicy(Caste policy) => CasteManager.SetDefault(policy); /// Members become casteless and keep their policies; rows pointing at the caste fall back to No caste. 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); } /// Draws every slot from the top of the scroll view; returns the height used. 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; } /// A Tiny label across the width; returns the y below it. 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; } } /// The member count and "Apply to all members", which asks first, naming the count. private static void DoFooter(Rect footer, Caste caste, WorkCycle cycle) { List 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()); } /// The confirm text for "Apply to all members", naming the caste and the member count. public static string ApplyToAllConfirmText(Caste caste, int count) => "BlaxCastes_ApplyToAllConfirm".Translate(caste.label.Named("CASTE"), count.Named("COUNT")); // ---- policy, medical care and loadout rows ------------------------------------------- /// /// One row: label, managed checkbox, dropdown and (for policies) the pencil. Inactive: greyed out, /// with the note as tooltip, and nothing can be changed. /// 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); } /// The loadout row is shown only while Weapons Tab Reborn is active. public static bool ShowsLoadoutRow => WeaponsTab.ModActive; /// The loadout row, greyed out while the setting is off or the mod's API could not be used. 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; } /// The vanilla Assign tab's "Manage ... policies" text for the slot's editor. 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> PolicyMenu(Caste caste, CasteSlot slot) { yield return new Widgets.DropdownMenuElement { 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 { option = new FloatMenuOption(local.label, () => CasteManager.SetSlot(caste, slot, local)), payload = local, }; } } private static IEnumerable> MedCareMenu(Caste caste) { yield return new Widgets.DropdownMenuElement { 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 { option = new FloatMenuOption(care.GetLabel().CapitalizeFirst(), () => CasteManager.SetSlot(caste, CasteSlot.MedCare, care), MedCareIcon(care), Color.white), payload = i, }; } } private static IEnumerable> LoadoutMenu(Caste caste) { yield return new Widgets.DropdownMenuElement { option = new FloatMenuOption("BlaxCastes_Unmanaged".Translate(), () => CasteManager.SetSlot(caste, CasteSlot.Loadout, Caste.Unmanaged)), payload = Caste.Unmanaged, }; foreach (KeyValuePair loadout in WeaponsTab.Loadouts()) { int id = loadout.Key; yield return new Widgets.DropdownMenuElement { option = new FloatMenuOption(loadout.Value, () => CasteManager.SetSlot(caste, CasteSlot.Loadout, id)), payload = id, }; } } /// The same icons the vanilla medical care button uses. Loaded on first draw. private static Texture2D MedCareIcon(MedicalCareCategory care) { if (medCareIcons == null) { medCareIcons = new[] { ContentFinder.Get("UI/Icons/Medical/NoCare", reportFailure: false), ContentFinder.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 ---------------------------------------------------------------------------- /// /// 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. /// 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 names = caste.Schedule ?? ScheduleSlot.Default(); TimeAssignmentDef brush = TimeAssignmentSelector.selectedAssignment; var grid = new Rect(ValueX, y, cellWidth * ScheduleSlot.Hours, HourCellHeight); Event current = Event.current; // The grid ends where the scrollbar starts: only a press that started on the grid paints. bool held = Input.GetMouseButton(0); bool paint = SchedulePaintAllowed(ref schedulePaintStarted, current.type, current.button, Mouse.IsOver(grid), held); 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 (!held) MouseoverSounds.DoRegion(cell); if (!Mouse.IsOver(cell)) continue; Widgets.DrawBox(cell, 2); if (paint && 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; } /// /// Whether the schedule grid paints during this GUI event. Vanilla's Schedule tab paints whenever the /// left button is held over a cell; here the grid ends where the scroll view's scrollbar starts, so a /// drag of the scrollbar that drifts over the grid would paint (and give every member a day the caste /// left alone). So painting needs a press that started on the grid: started is set by a left press, /// to whether it was over the grid, and cleared when the button is up. /// public static bool SchedulePaintAllowed(ref bool started, EventType type, int button, bool overGrid, bool buttonHeld) { if (type == EventType.MouseDown && button == 0) started = overGrid; else if (!buttonHeld || (type == EventType.MouseUp && button == 0)) started = false; return started; } /// /// 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. /// public static float BrushWidthFor(float width) { int brushes = ModsConfig.RoyaltyActive ? 5 : 4; return Mathf.Clamp((width - ValueX) / brushes, MinBrushWidth, MaxBrushWidth); } private static List CopyFromPawnOptions(Caste caste) { var options = new List(); 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; } /// The pawns "Copy from pawn" lists: colonists and slaves of the player that have a schedule, by name. public static List SchedulePawns() { if (Current.Game == null) return new List(); return PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_OfPlayerFaction .Where(p => p.RaceProps != null && p.RaceProps.Humanlike && !p.IsPrisoner && ScheduleSlot.HasTimetable(p)) .OrderBy(p => p.LabelShort) .ToList(); } /// "Copy from pawn": the caste takes the pawn's 24 hours; members follow. Returns how many moved. 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); } /// /// 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. /// public static int PaintHour(Caste caste, int hour, TimeAssignmentDef def) { if (caste == null || def == null || hour < 0 || hour >= ScheduleSlot.Hours) return 0; List names = caste.Schedule?.ToList() ?? ScheduleSlot.Default(); names[hour] = def.defName; return CasteManager.SetSlot(caste, CasteSlot.Schedule, names); } // ---- work priorities --------------------------------------------------------------------- /// /// 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. /// 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 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; } /// The line under the work priorities heading, or null: setting off, a work manager, or manual priorities off. 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; } /// The tooltip of "Start from nothing", naming the work types it keeps (Patient and Bed rest). public static string StartFromNothingTip() { string kept = WorkSlot.SelfCareTypes().Select(t => WorkSlot.TypeLabel(t)).ToCommaList(useAnd: true); return "BlaxCastes_WorkStartFromNothingTip".Translate(kept.Named("KEPT")); } /// One click on a cycle button, with no clicks before it: members that follow the type move. Returns how many moved. public static int CycleWork(Caste caste, WorkTypeDef def, bool forward = true) => new WorkCycle().Click(caste, def, forward); /// /// 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. /// Pawns "Assign by status" puts into the run's caste get the caste's current value, so they join /// the run's followers (AddJoined) instead of ending the run, which would let the next click pick up /// a member set by hand to that value. /// public sealed class WorkCycle { private Caste caste; private string defName; private int? lastValue; private List followers; /// Cycles the type one step and moves the run's followers. Returns how many moved. 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); } /// Ends the run: the next click takes the followers anew. public void End() { caste = null; defName = null; followers = null; } /// /// Pawns that just joined a caste (Assign by status). Those in the run's caste that follow its type /// now, as a fresh assign leaves them, are added to the run's followers. Returns how many were added. /// public int AddJoined(IEnumerable joined) { if (followers == null || caste == null || joined == null) return 0; List following = CasteManager.WorkFollowers(caste, defName); int added = 0; foreach (Pawn pawn in joined) { if (pawn != null && following.Contains(pawn) && !followers.Contains(pawn)) { followers.Add(pawn); added++; } } return added; } } // ---- helpers the rows use; public so the tests can drive them -------------------------- /// The game's policies that fit a slot, in database order. Empty for the other slots. public static IEnumerable PoliciesFor(CasteSlot slot) { Game game = Current.Game; if (game == null) yield break; IEnumerable 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; } } /// /// 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. /// 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; } } /// /// 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. /// 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 ---------------------------------------------------------------- /// /// 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 not in the Assign tab, because the message would point to a button that is not there. /// That is the setting the game started with (CasteColumns.Shown), not a change waiting for a restart. /// public static bool ShowFirstLoadMessage() { if (!CasteColumns.Shown) return false; string text = "BlaxCastes_FirstLoadMessage".Translate(); LongEventHandler.ExecuteWhenFinished(() => Messages.Message(text, MessageTypeDefOf.NeutralEvent)); return true; } } }