rimworld-blax-laws/Source/BlaxLaws/UI/MainTabWindow_Laws.cs

530 lines
24 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// The Laws tab (MainButtonDef BlaxLaws_Laws; design: "Lawbook tab"). Two tabs:
/// - Lawbook: one line per row with Action (icon, category and label; a click opens the act picker),
/// Option (drug binges only), Stage, Severity, Punishment, Days, On, the overlap icon and delete.
/// Each dropdown offers only what fits the row's action and stage. "Add law" opens the act picker,
/// "Starter lawbook" adds the suggested rows. An empty book shows one line.
/// - Cases: newest first, who, what, stage, when, punishment and status, a button to jump to the pawn
/// and, for a held case, "Arrest now".
/// Below the Lawbook: the current map's court place (CourtPlaceUi), with "Pick court place" and "Clear".
/// The logic lives in LawbookUi and CaseLog; every write goes through Lawbook. Only the lines in view
/// are drawn.
/// </summary>
public class MainTabWindow_Laws : MainTabWindow
{
private enum Page
{
Lawbook,
Cases,
}
private const float RowHeight = 30f;
private const float HeaderHeight = 26f;
private const float ButtonHeight = 32f;
private const float Gap = 6f;
private const float IconSize = 24f;
private const float ScrollBar = 16f;
// Lawbook columns; Action takes what is left.
private const float OptionWidth = 130f;
private const float StageWidth = 90f;
private const float SeverityWidth = 100f;
private const float PunishmentWidth = 150f;
private const float DaysWidth = 56f;
private const float OnWidth = 36f;
private const float SmallIcon = 24f;
// Cases columns; What takes what is left.
private const float WhoWidth = 150f;
private const float CaseStageWidth = 80f;
private const float WhenWidth = 110f;
private const float CasePunishmentWidth = 140f;
private const float StatusWidth = 190f;
private const float CaseButtonsWidth = 180f;
private static Page page = Page.Lawbook;
private static bool showClosed = true;
private static readonly Color SeriousColor = new Color(1f, 0.82f, 0.45f);
private Vector2 lawScroll;
private Vector2 caseScroll;
// The Cases tab's rows, refilled in place on every GUI event (CaseLog.FillRows).
private readonly List<LawCase> caseRows = new List<LawCase>();
private struct DaysBuffer
{
public int value;
public string text;
}
private readonly Dictionary<int, DaysBuffer> dayBuffers = new Dictionary<int, DaysBuffer>();
private readonly List<TabRecord> tabs = new List<TabRecord>();
public override Vector2 RequestedTabSize => new Vector2(1010f, 640f);
public override void PreOpen()
{
base.PreOpen();
dayBuffers.Clear();
}
public override void DoWindowContents(Rect inRect)
{
Rect body = inRect;
body.yMin += TabDrawer.TabHeight;
tabs.Clear();
tabs.Add(new TabRecord("BlaxLaws_TabLawbook".Translate(), () => page = Page.Lawbook, page == Page.Lawbook));
tabs.Add(new TabRecord("BlaxLaws_TabCases".Translate(), () => page = Page.Cases, page == Page.Cases));
Widgets.DrawMenuSection(body);
TabDrawer.DrawTabs(body, tabs);
body = body.ContractedBy(10f);
try
{
if (page == Page.Lawbook)
DoLawbook(body);
else
DoCases(body);
}
catch (Exception e)
{
LawsLog.Once("Laws tab", e);
}
finally
{
Text.Anchor = TextAnchor.UpperLeft;
Text.Font = GameFont.Small;
GUI.color = Color.white;
}
}
// ---- Lawbook ---------------------------------------------------------------------------
private void DoLawbook(Rect rect)
{
// The court place strip sits at the bottom, drawn before the empty-book return so "Clear" works
// with an empty book.
if (Find.CurrentMap != null)
{
Rect court = new Rect(rect.x, rect.yMax - ButtonHeight, rect.width, ButtonHeight);
try
{
DrawCourtPlace(court, Find.CurrentMap);
}
catch (Exception e)
{
LawsLog.Once("Laws tab, court place", e);
}
rect.yMax = court.y - Gap;
Widgets.DrawLineHorizontal(rect.x, rect.yMax, rect.width);
rect.yMax -= Gap;
}
Rect buttons = new Rect(rect.x, rect.y, rect.width, ButtonHeight);
Rect add = new Rect(buttons.x, buttons.y, 160f, ButtonHeight);
if (Widgets.ButtonText(add, "BlaxLaws_AddLaw".Translate()))
Find.WindowStack.Add(Dialog_PickAct.ForNewRow());
TooltipHandler.TipRegion(add, "BlaxLaws_AddLawTip".Translate());
Rect starter = new Rect(add.xMax + Gap, buttons.y, 180f, ButtonHeight);
if (Widgets.ButtonText(starter, "BlaxLaws_StarterLawbook".Translate()))
LawbookUi.PressStarter();
TooltipHandler.TipRegion(starter, "BlaxLaws_StarterLawbookTip".Translate());
if (!BlaxLawsMod.S.enforceLaws)
{
Rect off = new Rect(starter.xMax + Gap * 2, buttons.y, buttons.xMax - starter.xMax - Gap * 2, ButtonHeight);
using (new TextBlock(GameFont.Small, TextAnchor.MiddleRight, ColorLibrary.RedReadable))
Widgets.Label(off, "BlaxLaws_EnforceOff".Translate());
}
IReadOnlyList<Law> laws = Lawbook.Laws;
Rect list = new Rect(rect.x, buttons.yMax + Gap, rect.width, rect.yMax - buttons.yMax - Gap);
if (laws.Count == 0)
{
using (new TextBlock(GameFont.Small, TextAnchor.UpperLeft, ColoredText.SubtleGrayColor))
Widgets.Label(list, "BlaxLaws_EmptyBook".Translate());
return;
}
Rect header = new Rect(list.x, list.y, list.width - ScrollBar, HeaderHeight);
DrawLawHeader(header);
Rect outRect = new Rect(list.x, header.yMax, list.width, list.yMax - header.yMax);
Rect viewRect = new Rect(0f, 0f, outRect.width - ScrollBar, laws.Count * RowHeight);
ScrollToFocus(laws, outRect.height);
Widgets.BeginScrollView(outRect, ref lawScroll, viewRect);
try
{
int first = Mathf.Max(0, Mathf.FloorToInt(lawScroll.y / RowHeight));
int last = Mathf.Min(laws.Count - 1, Mathf.CeilToInt((lawScroll.y + outRect.height) / RowHeight));
for (int i = first; i <= last && i < laws.Count; i++)
{
Rect r = new Rect(0f, i * RowHeight, viewRect.width, RowHeight);
try
{
DrawLaw(r, laws[i], i);
}
catch (Exception e)
{
LawsLog.Once("Lawbook row", e);
}
}
}
finally
{
Widgets.EndScrollView();
}
}
private const float CourtHeaderWidth = 110f;
private const float PickWidth = 170f;
private const float ClearWidth = 80f;
private const float ShowWidth = 70f;
/// <summary>"Court place:", the place and its room, Show, Pick court place and Clear.</summary>
private static void DrawCourtPlace(Rect r, Map map)
{
float right = r.xMax;
if (CourtPlaceUi.CanClear(map))
{
Rect clear = new Rect(right - ClearWidth, r.y, ClearWidth, r.height);
if (Widgets.ButtonText(clear, "BlaxLaws_ClearCourtPlace".Translate()))
HookGuard.Run("Clear court place", () => CourtPlace.Clear(map));
TooltipHandler.TipRegion(clear, "BlaxLaws_ClearCourtPlaceTip".Translate());
right = clear.x - Gap;
}
Rect pick = new Rect(right - PickWidth, r.y, PickWidth, r.height);
if (Widgets.ButtonText(pick, "BlaxLaws_PickCourtPlace".Translate()))
HookGuard.Run("Pick court place", CourtPlaceUi.BeginPick);
TooltipHandler.TipRegion(pick, "BlaxLaws_PickCourtPlaceTip".Translate());
right = pick.x - Gap;
if (CourtPlaceUi.CanJump(map))
{
Rect show = new Rect(right - ShowWidth, r.y, ShowWidth, r.height);
if (Widgets.ButtonText(show, "BlaxLaws_JumpTo".Translate()))
HookGuard.Run("Jump to court place", () => CourtPlaceUi.JumpTo(map));
right = show.x - Gap;
}
Rect header = new Rect(r.x, r.y, CourtHeaderWidth, r.height);
using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft, ColoredText.SubtleGrayColor))
Widgets.Label(header, "BlaxLaws_CourtPlaceHeader".Translate());
Rect line = new Rect(header.xMax + Gap, r.y, right - header.xMax - Gap * 2, r.height);
string text = CourtPlaceUi.Line(map);
using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft, Color.white))
Widgets.Label(line, text.Truncate(line.width));
TooltipHandler.TipRegion(new Rect(r.x, r.y, line.xMax - r.x, r.height), () => text + "\n\n" + "BlaxLaws_CourtPlaceTip".Translate().ToString(), 7351);
}
private void ScrollToFocus(IReadOnlyList<Law> laws, float height)
{
if (!LawbookUi.ScrollPending)
return;
LawbookUi.ScrollPending = false;
page = Page.Lawbook;
for (int i = 0; i < laws.Count; i++)
{
if (laws[i].id != LawbookUi.FocusLawId)
continue;
float top = i * RowHeight;
if (top < lawScroll.y || top + RowHeight > lawScroll.y + height)
lawScroll.y = Mathf.Max(0f, top - height / 2f);
return;
}
}
private static void Columns(Rect r, out Rect action, out Rect option, out Rect stage, out Rect severity, out Rect punishment,
out Rect days, out Rect on, out Rect overlap, out Rect delete)
{
float x = r.xMax;
delete = new Rect(x - SmallIcon, r.y, SmallIcon, r.height);
x = delete.x - Gap;
overlap = new Rect(x - SmallIcon, r.y, SmallIcon, r.height);
x = overlap.x - Gap;
on = new Rect(x - OnWidth, r.y, OnWidth, r.height);
x = on.x - Gap;
days = new Rect(x - DaysWidth, r.y, DaysWidth, r.height);
x = days.x - Gap;
punishment = new Rect(x - PunishmentWidth, r.y, PunishmentWidth, r.height);
x = punishment.x - Gap;
severity = new Rect(x - SeverityWidth, r.y, SeverityWidth, r.height);
x = severity.x - Gap;
stage = new Rect(x - StageWidth, r.y, StageWidth, r.height);
x = stage.x - Gap;
option = new Rect(x - OptionWidth, r.y, OptionWidth, r.height);
x = option.x - Gap;
action = new Rect(r.x, r.y, x - r.x, r.height);
}
private static void DrawLawHeader(Rect r)
{
Columns(r, out Rect action, out Rect option, out Rect stage, out Rect severity, out Rect punishment, out Rect days, out Rect on, out _, out _);
using (new TextBlock(GameFont.Small, TextAnchor.LowerLeft, ColoredText.SubtleGrayColor))
{
HeaderLabel(action, "BlaxLaws_ColAction", null);
HeaderLabel(option, "BlaxLaws_ColOption", "BlaxLaws_ColOptionTip");
HeaderLabel(stage, "BlaxLaws_ColStage", "BlaxLaws_ColStageTip");
HeaderLabel(severity, "BlaxLaws_ColSeverity", "BlaxLaws_ColSeverityTip");
HeaderLabel(punishment, "BlaxLaws_ColPunishment", null);
HeaderLabel(days, "BlaxLaws_ColDays", "BlaxLaws_ColDaysTip");
HeaderLabel(on, "BlaxLaws_ColOn", "BlaxLaws_ColOnTip");
}
Widgets.DrawLineHorizontal(r.x, r.yMax - 1f, r.width);
}
private static void HeaderLabel(Rect r, string key, string tipKey)
{
Widgets.Label(r, key.Translate());
if (tipKey != null)
TooltipHandler.TipRegion(r, tipKey.Translate());
}
private void DrawLaw(Rect r, Law law, int index)
{
if (index % 2 == 1)
Widgets.DrawLightHighlight(r);
if (law.id == LawbookUi.FocusLawId && Time.realtimeSinceStartup < LawbookUi.FocusUntil)
Widgets.DrawHighlightSelected(r);
Columns(r, out Rect action, out Rect option, out Rect stage, out Rect severity, out Rect punishment, out Rect days, out Rect on,
out Rect overlap, out Rect delete);
ActEntry entry = law.Entry;
Color rowColor = law.enabled ? Color.white : Color.gray;
// Action: icon, category and label; a click opens the picker.
Widgets.DrawHighlightIfMouseover(action);
float x = action.x + 2f;
if (entry != null && ActIcons.HasIcon(entry))
{
ActIcons.Draw(new Rect(x, action.y + (action.height - IconSize) / 2f, IconSize, IconSize), entry);
x += IconSize + 4f;
}
Rect label = new Rect(x, action.y, action.xMax - x, action.height);
string text = LawbookUi.ActionLabel(law);
string missing = law.MissingText;
using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft, missing != null ? ColoredText.SubtleGrayColor : rowColor))
Widgets.Label(label, (missing != null ? text + " (" + missing + ")" : text).Truncate(label.width));
TooltipHandler.TipRegion(action, () => LawbookUi.ActionTooltip(law), law.id * 31 + 1);
if (Widgets.ButtonInvisible(action))
Find.WindowStack.Add(Dialog_PickAct.ForRow(law));
// Option, drug binges only.
if (LawbookUi.HasOption(law))
Dropdown(option, law, LawbookUi.OptionChoices, DrugOptions.Label(law.option));
Dropdown(stage, law, LawbookUi.StageChoices, LawLabels.Stage(law.stage));
Dropdown(severity, law, LawbookUi.SeverityChoices, LawLabels.Severity(law.severity));
Dropdown(punishment, law, LawbookUi.PunishmentChoices, LawbookUi.PunishmentLabel(law));
// Days: a 1 to 50 field for punishments with days, "-" otherwise.
if (LawbookUi.UsesDays(law))
{
// The buffer belongs to the value it was typed for; a change from elsewhere (Severity moving
// untouched days) starts a fresh one, so stale text never writes the old number back.
string buffer = null;
if (dayBuffers.TryGetValue(law.id, out DaysBuffer kept) && kept.value == law.days)
buffer = kept.text;
int value = law.days;
Rect field = days.ContractedBy(0f, 3f);
Widgets.TextFieldNumeric(field, ref value, ref buffer, Lawbook.MinDays, Lawbook.MaxDays);
if (value != law.days && value >= Lawbook.MinDays && value <= Lawbook.MaxDays)
Lawbook.SetDays(law, value);
dayBuffers[law.id] = new DaysBuffer { value = law.days, text = buffer };
}
else
{
using (new TextBlock(GameFont.Small, TextAnchor.MiddleCenter, ColoredText.SubtleGrayColor))
Widgets.Label(days, "BlaxLaws_NoDays".Translate());
}
// On.
bool enabled = law.enabled;
Widgets.Checkbox(new Vector2(on.x + (on.width - 24f) / 2f, on.y + (on.height - 24f) / 2f), ref enabled);
if (enabled != law.enabled)
Lawbook.SetEnabled(law, enabled);
TooltipHandler.TipRegion(on, "BlaxLaws_ColOnTip".Translate());
// Overlap icon.
IReadOnlyList<Law> overlaps = ActOverlaps.Of(law);
if (overlaps.Count > 0)
{
Rect icon = new Rect(overlap.x, overlap.y + (overlap.height - SmallIcon) / 2f, SmallIcon, SmallIcon);
GUI.DrawTexture(icon, LawsTex.Overlap);
TooltipHandler.TipRegion(icon, () => OverlapTip(overlaps), law.id * 31 + 2);
}
// Delete, asking first when the row has open cases.
Rect del = new Rect(delete.x, delete.y + (delete.height - SmallIcon) / 2f, SmallIcon, SmallIcon);
if (Widgets.ButtonImage(del, TexButton.Delete, Color.white, GenUI.SubtleMouseoverColor, true, "BlaxLaws_DeleteLaw".Translate()))
LawbookUi.RequestDelete(law);
}
private static string OverlapTip(IReadOnlyList<Law> overlaps)
{
var lines = new List<string>();
foreach (Law o in overlaps)
lines.Add(" - " + LawbookUi.ActionLabel(o) + " (" + LawLabels.Stage(o.stage) + ")");
return "BlaxLaws_OverlapTip".Translate(string.Join("\n", lines));
}
private static void Dropdown(Rect rect, Law law, Func<Law, List<RowChoice>> choices, string label)
{
Rect button = rect.ContractedBy(0f, 2f);
Widgets.Dropdown(button, law, l => (object)null, l => Elements(choices(l)), label.Truncate(button.width - 16f));
}
private static IEnumerable<Widgets.DropdownMenuElement<object>> Elements(List<RowChoice> choices)
{
foreach (RowChoice c in choices)
{
string label = c.action == null && !c.reason.NullOrEmpty() ? c.label + " (" + c.reason + ")" : c.label;
yield return new Widgets.DropdownMenuElement<object>
{
option = new FloatMenuOption(label, c.action),
payload = c.payload,
};
}
}
// ---- Cases -----------------------------------------------------------------------------
private void DoCases(Rect rect)
{
Rect top = new Rect(rect.x, rect.y, rect.width, ButtonHeight);
Rect closed = new Rect(top.x, top.y + 4f, 240f, 24f);
Widgets.CheckboxLabeled(closed, "BlaxLaws_ShowClosed".Translate(), ref showClosed);
CaseLog.FillRows(caseRows, showClosed);
List<LawCase> cases = caseRows;
Rect list = new Rect(rect.x, top.yMax + Gap, rect.width, rect.yMax - top.yMax - Gap);
if (cases.Count == 0)
{
using (new TextBlock(GameFont.Small, TextAnchor.UpperLeft, ColoredText.SubtleGrayColor))
Widgets.Label(list, "BlaxLaws_NoCases".Translate());
return;
}
Rect header = new Rect(list.x, list.y, list.width - ScrollBar, HeaderHeight);
CaseColumns(header, out Rect who, out Rect what, out Rect stage, out Rect when, out Rect punishment, out Rect status, out _);
using (new TextBlock(GameFont.Small, TextAnchor.LowerLeft, ColoredText.SubtleGrayColor))
{
Widgets.Label(who, "BlaxLaws_ColWho".Translate());
Widgets.Label(what, "BlaxLaws_ColWhat".Translate());
Widgets.Label(stage, "BlaxLaws_ColStage".Translate());
Widgets.Label(when, "BlaxLaws_ColWhen".Translate());
Widgets.Label(punishment, "BlaxLaws_ColPunishment".Translate());
Widgets.Label(status, "BlaxLaws_ColStatus".Translate());
}
Widgets.DrawLineHorizontal(header.x, header.yMax - 1f, header.width);
Rect outRect = new Rect(list.x, header.yMax, list.width, list.yMax - header.yMax);
Rect viewRect = new Rect(0f, 0f, outRect.width - ScrollBar, cases.Count * RowHeight);
Widgets.BeginScrollView(outRect, ref caseScroll, viewRect);
try
{
int first = Mathf.Max(0, Mathf.FloorToInt(caseScroll.y / RowHeight));
int last = Mathf.Min(cases.Count - 1, Mathf.CeilToInt((caseScroll.y + outRect.height) / RowHeight));
for (int i = first; i <= last; i++)
{
try
{
DrawCase(new Rect(0f, i * RowHeight, viewRect.width, RowHeight), cases[i], i);
}
catch (Exception e)
{
LawsLog.Once("Cases row", e);
}
}
}
finally
{
Widgets.EndScrollView();
}
}
private static void CaseColumns(Rect r, out Rect who, out Rect what, out Rect stage, out Rect when, out Rect punishment, out Rect status, out Rect buttons)
{
float x = r.xMax;
buttons = new Rect(x - CaseButtonsWidth, r.y, CaseButtonsWidth, r.height);
x = buttons.x - Gap;
status = new Rect(x - StatusWidth, r.y, StatusWidth, r.height);
x = status.x - Gap;
punishment = new Rect(x - CasePunishmentWidth, r.y, CasePunishmentWidth, r.height);
x = punishment.x - Gap;
when = new Rect(x - WhenWidth, r.y, WhenWidth, r.height);
x = when.x - Gap;
stage = new Rect(x - CaseStageWidth, r.y, CaseStageWidth, r.height);
x = stage.x - Gap;
who = new Rect(r.x, r.y, WhoWidth, r.height);
what = new Rect(who.xMax + Gap, r.y, x - who.xMax - Gap, r.height);
}
private static void DrawCase(Rect r, LawCase c, int index)
{
if (index % 2 == 1)
Widgets.DrawLightHighlight(r);
Widgets.DrawHighlightIfMouseover(r);
CaseColumns(r, out Rect who, out Rect what, out Rect stage, out Rect when, out Rect punishment, out Rect status, out Rect buttons);
Color color = c.IsClosed ? ColoredText.SubtleGrayColor : SeverityColor(c.severity);
using (new TextBlock(GameFont.Small, TextAnchor.MiddleLeft, color))
{
Cell(who, CaseLog.Who(c));
Cell(what, CaseLog.What(c));
Cell(stage, CaseLog.Stage(c));
Cell(when, CaseLog.When(c));
Cell(punishment, CaseLog.Punishment(c));
Cell(status, CaseLog.Status(c));
}
TooltipHandler.TipRegion(new Rect(r.x, r.y, buttons.x - r.x, r.height), () => CaseTip(c), c.id * 31 + 3);
float bx = buttons.xMax;
if (CaseLog.CanJump(c))
{
Rect jump = new Rect(bx - 70f, r.y + 3f, 70f, r.height - 6f);
if (Widgets.ButtonText(jump, "BlaxLaws_JumpTo".Translate()))
CaseLog.JumpTo(c);
TooltipHandler.TipRegion(jump, "BlaxLaws_JumpToTip".Translate(c.OffenderLabel));
bx = jump.x - Gap;
}
if (CaseLog.CanArrestNow(c))
{
Rect arrest = new Rect(bx - 100f, r.y + 3f, 100f, r.height - 6f);
if (Widgets.ButtonText(arrest, "BlaxLaws_ArrestNow".Translate()))
CaseLog.ArrestNow(c);
TooltipHandler.TipRegion(arrest, () => "BlaxLaws_ArrestNowTip".Translate(CaseLog.HoldReason(c.offender)), c.id * 31 + 4);
}
}
private static void Cell(Rect r, string text)
{
Widgets.Label(r, (text ?? "").Truncate(r.width));
}
private static string CaseTip(LawCase c)
{
var lines = new List<string>
{
CaseLog.Who(c),
CaseLog.What(c),
LawLabels.Severity(c.severity) + ", " + CaseLog.Stage(c),
CaseLog.Punishment(c),
CaseLog.Status(c),
};
return string.Join("\n", lines);
}
private static Color SeverityColor(LawSeverity s)
{
switch (s)
{
case LawSeverity.Grave: return ColorLibrary.RedReadable;
case LawSeverity.Serious: return SeriousColor;
default: return Color.white;
}
}
}
}