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

362 lines
14 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxLaws
{
/// <summary>One entry of a lawbook column's dropdown. A null action is a disabled entry; reason says why.</summary>
public sealed class RowChoice
{
public string label;
/// <summary>The value the entry sets: a drug option, a LawStage, a LawSeverity or a PunishmentDef.</summary>
public object payload;
/// <summary>Writes the choice through Lawbook. Null for a disabled entry.</summary>
public Action action;
/// <summary>Why the entry is disabled ("Needs Ideology"), or null.</summary>
public string reason;
/// <summary>The row has this value now.</summary>
public bool selected;
public override string ToString() => label + (selected ? " (selected)" : "") + (action == null ? " (disabled: " + reason + ")" : "");
}
/// <summary>
/// The logic behind the Lawbook tab (design: "Lawbook tab"), kept apart from the drawing so the
/// headless tests drive it: what each column offers, what a pick from the act picker does, the starter
/// button and the delete confirmation. Every write goes through Lawbook. A write Lawbook refuses because
/// the key exists shows the existing row instead (Focus).
/// </summary>
public static class LawbookUi
{
/// <summary>Seconds the tab highlights a row it jumped to.</summary>
public const float FocusSeconds = 2.5f;
/// <summary>The row the tab scrolls to and highlights, or 0.</summary>
public static int FocusLawId { get; private set; }
/// <summary>Real time until which the focused row is highlighted.</summary>
public static float FocusUntil { get; private set; }
/// <summary>Set when Focus asks the tab to scroll; the tab clears it once it scrolled.</summary>
public static bool ScrollPending { get; set; }
/// <summary>Shows the row: the Lawbook tab scrolls to it and highlights it.</summary>
public static void Focus(Law law)
{
if (law == null)
return;
FocusLawId = law.id;
FocusUntil = Time.realtimeSinceStartup + FocusSeconds;
ScrollPending = true;
}
public static void ClearFocus()
{
FocusLawId = 0;
ScrollPending = false;
}
// ---- labels ------------------------------------------------------------------------
/// <summary>"Ate: Wake-up". A row whose entry is missing shows its saved label.</summary>
public static string ActionLabel(Law law)
{
if (law == null)
return "";
return "BlaxLaws_ActionLabel".Translate(CategoryLabel(law.CategoryId), law.Label);
}
/// <summary>The category's label ("Ate"), or its id while the category is unknown.</summary>
public static string CategoryLabel(string categoryId)
{
if (categoryId.NullOrEmpty())
return "?";
ActCategoryDef cat = DefDatabase<ActCategoryDef>.GetNamedSilentFail(categoryId);
return cat != null && !cat.label.NullOrEmpty() ? cat.LabelCap.ToString() : categoryId;
}
/// <summary>The Action cell's tooltip: source mod, what counts, a missing entry's reason.</summary>
public static string ActionTooltip(Law law)
{
if (law == null)
return null;
var parts = new List<string>();
ActEntry e = law.Entry;
parts.Add(ActionLabel(law));
string missing = law.MissingText;
if (missing != null)
parts.Add(missing);
string source = e?.sourceMod ?? law.savedMod;
if (!source.NullOrEmpty())
parts.Add("BlaxLaws_SourceMod".Translate(source));
string what = EntryDescription(e);
if (!what.NullOrEmpty())
parts.Add(what);
parts.Add("BlaxLaws_ActionTip".Translate());
return string.Join("\n\n", parts);
}
/// <summary>What the entry's act is, for tooltips: a special act's row tooltip, else the category's tooltip.</summary>
public static string EntryDescription(ActEntry e)
{
if (e == null)
return null;
return HookGuard.Run("Entry tooltip " + e.key, () =>
{
if (e.def is ActDef act)
return act.Worker.RowTooltip;
ActCategoryDef cat = DefDatabase<ActCategoryDef>.GetNamedSilentFail(e.categoryId);
return cat?.Worker.Tooltip;
}, null);
}
/// <summary>The Days cell: the number when the punishment uses days, else "-".</summary>
public static bool UsesDays(Law law) => law?.PunishmentDef?.usesDays ?? false;
public static string PunishmentLabel(Law law)
{
if (law == null)
return "";
PunishmentDef p = law.PunishmentDef;
return p != null ? p.LabelCap.ToString() : law.punishment ?? "";
}
// ---- column choices ----------------------------------------------------------------
/// <summary>Whether the row has an Option column value: drug binges only.</summary>
public static bool HasOption(Law law) => law?.Entry?.hasDrugOption ?? (law?.option != null);
/// <summary>Any drug, hard drugs, social drugs, then every drug's chemical A to Z.</summary>
public static List<RowChoice> OptionChoices(Law law)
{
var list = new List<RowChoice>();
if (law == null || !HasOption(law))
return list;
var options = new List<string> { DrugOptions.Any, DrugOptions.Hard, DrugOptions.Social };
options.AddRange(ActCatalogue.ChemicalOptions);
string current = DrugOptions.Normalize(law.option);
foreach (string o in options)
{
string option = o;
list.Add(new RowChoice
{
label = DrugOptions.Label(option),
payload = option,
selected = option == current,
action = () => ChangeOption(law, option),
});
}
return list;
}
/// <summary>The stages the entry offers; a missing entry keeps the row's stage only.</summary>
public static List<RowChoice> StageChoices(Law law)
{
var list = new List<RowChoice>();
if (law == null)
return list;
ActEntry e = law.Entry;
IEnumerable<LawStage> stages = e != null ? Lawbook.StagesOf(e) : new[] { law.stage };
foreach (LawStage s in stages)
{
LawStage stage = s;
list.Add(new RowChoice
{
label = LawLabels.Stage(stage),
payload = stage,
selected = stage == law.stage,
action = e == null ? (Action)null : () => ChangeStage(law, stage),
reason = e == null ? law.MissingText : null,
});
}
return list;
}
public static List<RowChoice> SeverityChoices(Law law)
{
var list = new List<RowChoice>();
if (law == null)
return list;
foreach (LawSeverity s in Enum.GetValues(typeof(LawSeverity)))
{
LawSeverity severity = s;
list.Add(new RowChoice
{
label = LawLabels.Severity(severity),
payload = severity,
selected = severity == law.severity,
action = () => Lawbook.SetSeverity(law, severity),
});
}
return list;
}
/// <summary>
/// The punishments that fit the row's entry and stage, in order (Lawbook.PunishmentsFor). A row whose
/// entry is missing keeps its punishment and offers nothing else.
/// </summary>
public static List<RowChoice> PunishmentChoices(Law law)
{
var list = new List<RowChoice>();
if (law == null)
return list;
ActEntry e = law.Entry;
if (e == null)
{
PunishmentDef p = law.PunishmentDef;
list.Add(new RowChoice { label = PunishmentLabel(law), payload = p, selected = true, reason = law.MissingText });
return list;
}
foreach (PunishmentDef p in Lawbook.PunishmentsFor(e, law.stage))
{
PunishmentDef punishment = p;
list.Add(new RowChoice
{
label = punishment.LabelCap,
payload = punishment,
selected = punishment.defName == law.punishment,
action = () => Lawbook.SetPunishment(law, punishment),
});
}
return list;
}
// ---- writes that may be refused ----------------------------------------------------
/// <summary>Sets the option; a refusal shows the row that has the key.</summary>
public static bool ChangeOption(Law law, string option)
{
if (Lawbook.SetOption(law, option, out Law existing))
return true;
Refused(existing);
return false;
}
/// <summary>Sets the stage; a punishment that no longer fits resets to Warn. A refusal shows the existing row.</summary>
public static bool ChangeStage(Law law, LawStage stage)
{
if (Lawbook.SetStage(law, stage, out Law existing))
return true;
Refused(existing);
return false;
}
/// <summary>The act picker's pick for an existing row: SetAction, or the existing row with that key.</summary>
public static bool ChangeAction(Law law, string actKey)
{
if (Lawbook.SetAction(law, actKey, out Law existing))
{
Focus(law);
return true;
}
Refused(existing);
return false;
}
/// <summary>
/// The act picker's pick for "Add law". Adds a row for the entry's first stage that has no row yet
/// (a drug binge with the Any option), so an entry with planning and did it can get both. When every
/// stage has a row, nothing is added and existing is the first stage's row, which the tab shows.
/// Returns the new row, or null.
/// </summary>
public static Law AddFromPicker(string actKey, out Law existing)
{
existing = null;
if (actKey.NullOrEmpty())
return null;
Law row = Lawbook.NewRow(actKey);
ActEntry entry = ActCatalogue.Get(actKey);
IEnumerable<LawStage> stages = entry != null ? Lawbook.StagesOf(entry) : new[] { row.stage };
foreach (LawStage s in stages)
{
Law found = Lawbook.Find(actKey, row.option, s);
if (found != null)
{
existing ??= found;
continue;
}
row.stage = s;
if (!Lawbook.TryAdd(row, out Law refused))
{
existing = refused;
break;
}
existing = null;
Focus(row);
return row;
}
Refused(existing);
return null;
}
/// <summary>Rows already in the book for this act key, any option and stage.</summary>
public static List<Law> RowsOf(string actKey) => Lawbook.Laws.Where(l => l.actKey == actKey).ToList();
/// <summary>"Starter lawbook": adds the missing starter rows and says how many.</summary>
public static int PressStarter()
{
int added = Lawbook.AddStarter();
string text = added > 0 ? "BlaxLaws_StarterAdded".Translate(added) : "BlaxLaws_StarterNone".Translate();
Messages.Message(text, MessageTypeDefOf.SilentInput, historical: false);
return added;
}
/// <summary>The confirmation a delete asks first, naming the open cases it closes; null when it has none.</summary>
public static string DeleteConfirmText(Law law)
{
int open = Lawbook.OpenCaseCount(law);
if (open <= 0)
return null;
string text = "BlaxLaws_DeleteConfirm".Translate(ActionLabel(law), open);
int jailed = JailedCount(law);
if (jailed > 0)
text += "\n\n" + "BlaxLaws_DeleteConfirmJailed".Translate(jailed);
return text;
}
/// <summary>Open cases of the row whose offender serves its sentence: a repeal sets them to Release (PunishmentWorker_Jail.Stop).</summary>
public static int JailedCount(Law law)
{
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (comp == null || law == null)
return 0;
int n = 0;
foreach (LawCase c in comp.Cases)
{
if (!c.IsClosed && c.status == CaseStatus.Jailed && (c.planningLawId == law.id || c.didItLawId == law.id))
n++;
}
return n;
}
/// <summary>Deletes the row, asking first when it has open cases (design: "Bulk changes ask first and name the count").</summary>
public static void RequestDelete(Law law)
{
if (law == null)
return;
string confirm = DeleteConfirmText(law);
if (confirm == null)
{
Lawbook.Delete(law);
return;
}
Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(confirm, () => Lawbook.Delete(law), destructive: true));
}
private static void Refused(Law existing)
{
if (existing == null)
return;
Focus(existing);
Messages.Message("BlaxLaws_RowExists".Translate(ActionLabel(existing), LawLabels.Stage(existing.stage)), MessageTypeDefOf.RejectInput, historical: false);
}
}
}