A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Statecraft.Game.Map.Units;
using Statecraft.Sim;
using UnityEngine.UIElements;
namespace Statecraft.Game.UI
{
/// <summary>The turn report (#1037; the first outside play-test, #1038: "I see the values changing, but I don't really
/// understand what's happening"). When a turn has run, a short panel names each top-bar number that changed, with the
/// change the bar shows (HudModel.From) and its main causes, the sim's own causes in the player's language
/// (StepResult.Why, through HudModel.Causes and CauseText, B1). "See all" opens the Why screen with every cause; Close, Esc or Cancel
/// closes it. Nothing is computed or reworded here, so no rule lives in the UI.
/// <para>While it shows, the root has <see cref="OpenClass"/>: ScreenNav.DisableCovered disables the top bar, the panels
/// and the decision layer under it, as under an End Turn outcome clip, which is drawn over the report (Game.uxml order)
/// and disables it in turn; the report takes the keyboard focus when it is uncovered. A turn the sim refused outright
/// (SimBridge.EndTurn's failure: Session.Last does not move) shows no report; a turn with a refused order does. The
/// session replaced for New Game or a load closes the old game's report. Other bridge changes leave it open (End Turn
/// opens its new report from TurnEnded; answering the ending turn's card keeps it under the end screen).</para></summary>
public sealed class TurnReportPresenter : IDisposable
{
/// <summary>On the "root" element while the report shows.</summary>
public const string OpenClass = "turn-report-open";
public const string ElementName = "turn-report";
/// <summary>The id of the row after the meters' that lists the enemy's orders this turn (#1293).</summary>
public const string EnemyRow = "enemy";
/// <summary>The row after the stocks that lists the arms workshops' Arms and ceiling pauses this turn (#1701 A1).</summary>
public const string WorkshopRow = "workshops";
/// <summary>The row after the workshops' and the operations' that lists the cities the enemy holds this turn (R-CITY-010, #1711).</summary>
public const string HeldRow = "held";
/// <summary>The row of the turn's postponed and lapsed operations (R-ENEMY-007, #2543).</summary>
public const string OperationsRow = "operations";
/// <summary>The units_1948.yaml rows, which name the enemy's units in that row (GameRoot sets them once the map has read
/// them); without a row a unit is named by its id (report.unit).</summary>
public IReadOnlyList<UnitEntry>? Units { get; set; }
/// <summary>Each settlement's Hebrew name (name_he), by id: the map's parse, the same rows Why and the toasts use.</summary>
public IReadOnlyDictionary<string, string>? TownNamesHe { get; set; }
readonly VisualElement hudRoot, report; readonly ScrollView rows; readonly SimBridge bridge; readonly UiText text;
readonly ScreenNav nav; readonly Button close, all;
readonly Action<IReadOnlyList<Rejection>> onTurn;
readonly Action onChanged;
readonly Action<string?> onScreen;
GameSession session; // the session the open report belongs to
readonly EventCallback<NavigationCancelEvent> onCancel;
/// <summary>The turn last reported (or the session's last turn when this was made: a loaded game reports nothing).</summary>
StepResult? seen;
int closedAt = -1;
public TurnReportPresenter(VisualElement root, SimBridge bridge, UiText text, ScreenNav nav)
{
this.bridge = bridge; this.text = text; this.nav = nav;
hudRoot = root.Q("root") ?? root;
report = root.Q<VisualElement>(ElementName);
rows = report.Q<ScrollView>("turn-report-rows");
report.Q<Label>("turn-report-title").text = text["report.title"];
report.Q<Label>("turn-report-intro").text = text["report.intro"];
close = report.Q<Button>("turn-report-close"); close.text = text["report.close"];
all = report.Q<Button>("turn-report-all"); all.text = text["report.all"];
close.clicked += OnClose;
all.clicked += SeeAll;
onCancel = e => { Close(); e.StopPropagation(); };
report.RegisterCallback(onCancel);
// Close takes the focus when the report comes out uncovered; again once styles resolve, as an element shown this
// frame may not take it yet (OutcomePresenter's layer does the same).
ScreenNav.OnUncovered(report, () =>
{
close.Focus();
close.schedule.Execute(() => { if (IsOpen && report.enabledSelf && report.focusController?.focusedElement != close) close.Focus(); });
});
seen = bridge.Session.Last;
onTurn = _ =>
{
// Guarded as a whole, as OutcomePresenter is: nothing here may throw out of TurnEnded, whose later handlers
// include the turn's autosave.
try
{
var last = bridge.Session.Last;
if (last == null || ReferenceEquals(last, seen)) return;
seen = last;
// #2202: it opens when the enemy playback ends (Held). End turn still closes an open screen, as Show does
// without a playback, so the moves play on the open map (#2967 review, S1); a screen opened while they
// play stays (ShowWhenFree waits for it).
if (held) { nav.Close(); wantsShow = true; return; }
wantsShow = false; // this turn's report replaces one that waited for a screen
Show();
}
catch (Exception e) { UnityEngine.Debug.LogException(e); Hide(); }
};
bridge.TurnEnded += onTurn;
// Only a replaced session (New Game, a load: SimBridge.Replace) makes the report stale. Other changes keep it:
// answering the ending turn's card (SimBridge.SeeEndingCard) changes nothing and leaves it under the end screen.
session = bridge.Session;
onChanged = () => { if (ReferenceEquals(bridge.Session, session)) return; session = bridge.Session; wantsShow = false; Hide(); };
bridge.Changed += onChanged;
onScreen = screen => { if (screen == null) ShowWhenFree(); };
nav.Changed += onScreen;
Hide();
}
/// <summary>Raised with the turn being reported when the report opens, and with null when it closes (#1878: the map
/// shows the under-attack look on the hexes the turn attacked for as long as the report is up).</summary>
public event Action<StepResult?>? Showing;
bool held, wantsShow;
/// <summary>#2202: true while End turn's enemy playback runs (EnemyTurnPlayback.Holding; owner, Q1 a: the report waits
/// for it). A turn that ends meanwhile is reported when it turns false; another game drops the wait.</summary>
public bool Held
{
get => held;
set
{
if (held == value) return;
held = value;
ShowWhenFree();
}
}
/// <summary>#2202: true while a turn's report waits to open: for the enemy playback (<see cref="Held"/>), or for a
/// screen the player opened while it played, which the report does not close under them (#2967 review, S3).</summary>
public bool Waiting => wantsShow;
/// <summary>#2202: the session's last turn is reported once nothing holds it (GameRoot's language switch: the rebuilt
/// report takes over a wait the old one had, #2967 review, S2).</summary>
public void Wait()
{
var last = bridge.Session.Last;
if (last == null) return;
seen = last;
wantsShow = true;
ShowWhenFree();
}
void ShowWhenFree()
{
if (held || !wantsShow || nav.Current != null) return;
wantsShow = false;
// #3004: the hold can end inside End turn (End turn again mid-playback, on a turn with no moves to play), after
// the step and before TurnEnded: the report shown here is the new turn's, so TurnEnded finds it reported.
seen = bridge.Session.Last ?? seen;
try { Show(); }
catch (Exception e) { UnityEngine.Debug.LogException(e); Hide(); }
}
/// <summary>True while the report shows.</summary>
public bool IsOpen => hudRoot.ClassListContains(OpenClass);
/// <summary>True in the frame the report closed: GameRoot's Escape poll then leaves the card alone (the same Escape
/// key already closed the report through the Cancel event), as for OutcomePresenter.ClosedThisFrame.</summary>
public bool ClosedThisFrame => closedAt == UnityEngine.Time.frameCount;
/// <summary>One line of the report: the meter's id, its caption with the change the bar shows (and Immigration's
/// arrivals this turn), and its main causes.</summary>
public readonly struct Line
{
public readonly string Meter, Heading; public readonly IReadOnlyList<string> Causes;
public Line(string meter, string heading, IReadOnlyList<string> causes) { Meter = meter; Heading = heading; Causes = causes; }
}
/// <summary>The report's lines for the session's last turn: each top-bar meter whose shown change is not empty, in
/// the bar's order (the meters have different units, so no order by size is given without a rule); then national stocks; under
/// <see cref="WorkshopRow"/>, the arms workshops' lines (#1701); under <see cref="OperationsRow"/>, the postponed and lapsed
/// operations (R-ENEMY-007); under <see cref="HeldRow"/>, the held cities (#1711); under
/// <see cref="EnemyRow"/>, the enemy's orders (#1293).</summary>
public static IReadOnlyList<Line> Lines(SimBridge bridge, UiText text, IReadOnlyList<UnitEntry>? units = null,
IReadOnlyDictionary<string, string>? townNamesHe = null)
{
var m = HudModel.From(bridge, text); var lines = new List<Line>();
foreach (var id in HudModel.MeterIds)
{
if (id == "cohesion" && !m.ShowsCohesion) continue;
var meter = m.For(id);
if (meter.Delta.Length == 0) continue;
var heading = id == "immigration"
? text.Format("report.immigration_line", text["hud.caption.immigration"], meter.Delta, meter.Value)
: text.Format("report.line", text["hud.caption." + id], meter.Delta);
lines.Add(new Line(id, heading, HudModel.Causes(bridge.Session.Last, id, bridge.Content,
w => CauseText.Line(w, bridge.Content, units ?? Array.Empty<UnitEntry>(), text, townNamesHe))));
}
lines.AddRange(StockLines(bridge, text, units, townNamesHe));
var workshops = WorkshopLines(bridge, text, townNamesHe);
if (workshops.Count > 0) lines.Add(new Line(WorkshopRow, text["report.workshops"], workshops));
// R-ENEMY-007 (#2543): a postponed or lapsed operation changes no number either, and the rule says the turn report
// names the units and why, so its lines have their own row, in the sim's order.
var operations = bridge.Session.Last?.Why.Where(w => w.Key == CauseKeys.OperationPostponed || w.Key == CauseKeys.OperationLapsed
|| w.Key == CauseKeys.OperationLapsedSigned || w.Key == CauseKeys.OperationLapsedUnitLost || w.Key == CauseKeys.OperationWaitsForArmistice)
.Select(w => CauseText.Line(w, bridge.Content, units ?? Array.Empty<UnitEntry>(), text, townNamesHe)).ToList();
if (operations != null && operations.Count > 0) lines.Add(new Line(OperationsRow, text["report.operations"], operations));
// R-CITY-010 (#1711): a held city's line changes no number (Delta 0), so HudModel.Causes leaves it out and it has
// its own row; the sim writes it under gdd-0.3 only, in s.Cities' order.
var held = bridge.Session.Last?.Why.Where(w => w.Key == CauseKeys.CityHeld)
.Select(w => CauseText.Line(w, bridge.Content, units ?? Array.Empty<UnitEntry>(), text, townNamesHe)).ToList();
if (held != null && held.Count > 0) lines.Add(new Line(HeldRow, text["report.held"], held));
var enemy = EnemyOrders(bridge, text, units);
if (enemy.Count > 0) lines.Add(new Line(EnemyRow, text["report.enemy"], enemy));
return lines;
}
/// <summary>National stocks, independently of the top bar. Include unchanged stocks; never invent causes
/// for consumption/imports that the sim did not report. Legacy has no national pools.</summary>
public static IReadOnlyList<Line> StockLines(SimBridge bridge, UiText text,
IReadOnlyList<UnitEntry>? units = null, IReadOnlyDictionary<string, string>? townNamesHe = null)
{
var lines = new List<Line>();
if (!bridge.Content.IsGdd) return lines;
foreach (var id in new[] { Pools.FoodTarget, Pools.ArmsTarget })
{
var s = bridge.State; var prev = bridge.Session.Previous;
var stock = StockMeter.From(id == Pools.FoodTarget ? s.Food : s.Arms,
prev == null ? (int?)null : id == Pools.FoodTarget ? prev.Food : prev.Arms,
(key, n) => text.Format(key, n));
var heading = stock.Delta.Length == 0
? text.Format("report.stock_line", text["hud.caption." + id], stock.Value)
: text.Format("report.stock_change", text["hud.caption." + id], stock.Value, stock.Delta);
lines.Add(new Line(id, heading, StockCauses(bridge.Session.Last, id,
w => CauseText.Line(w, bridge.Content, units ?? Array.Empty<UnitEntry>(), text, townNamesHe))));
}
return lines;
}
/// <summary>The same largest-two and stable tie order as the report's indicators, matched to stock targets. The
/// Food shortage's line is informational (delta 0, #2527) but still shows, after the lines that have one.</summary>
public static IReadOnlyList<string> StockCauses(StepResult? turn, string target, Func<Cause, string> line)
{
if (turn == null) return Array.Empty<string>();
var rows = turn.Why.Select((w, i) => (w, i)).Where(x => x.w.Target == target).ToList();
return rows.Where(x => x.w.Delta != 0).OrderByDescending(x => Math.Abs(x.w.Delta)).ThenBy(x => x.i)
.Take(HudModel.MaxCauses)
.Concat(rows.Where(x => x.w.Delta == 0 && x.w.Key == CauseKeys.FoodShortage).OrderBy(x => x.i))
.Select(x => line(x.w)).ToList();
}
/// <summary>#1701 A1 (owner, 2 November 2026: "Yes, in the panel (Recommended)"): the arms workshops that made Arms and
/// those whose next cycle waits at the debt ceiling this turn, as the sim's causes say (CauseKeys.WorkshopArms;
/// CauseKeys.WorkshopPaused with Workshops.DebtCeiling; R-ARMS-006), the city in the player's language. Each city's
/// Arms are one line and its ceiling pauses another, with their count (owner, 2 November 2026: "Combine per city
/// (Recommended)", the option "'Workshops in Tel Aviv (6): +6 Arms'; pauses likewise combined with a count."), in the
/// order each first appears among the sim's causes; a city with one keeps A1's own line ("Workshop in Tel Aviv: +1
/// Arms"). The count is the number of those causes, each 1 Arms; nothing else is computed. A no-worker pause stays on
/// the Why screen. There is no ruleset check here: the sim gives these causes under gdd-0.3 only
/// (ArmsWorkshopTests.Gdd01RunsNoWorkshopCycle), and the report shows what the sim says.</summary>
static IReadOnlyList<string> WorkshopLines(SimBridge bridge, UiText text, IReadOnlyDictionary<string, string>? townNamesHe)
{
var turn = bridge.Session.Last;
if (turn == null) return Array.Empty<string>();
return turn.Why
.Where(w => w.Key == CauseKeys.WorkshopArms || (w.Key == CauseKeys.WorkshopPaused && w.Args.FirstOrDefault() == Workshops.DebtCeiling))
.GroupBy(w => (w.Key, City: w.Target)) // groups come in the order of their first cause
.Select(g =>
{
var made = g.Key.Key == CauseKeys.WorkshopArms;
var city = ContentNames.Settlement(text, bridge.Content, g.Key.City, townNamesHe);
var n = g.Count();
return n == 1 ? text.Format(made ? "report.workshop_arms" : "report.workshop_paused_debt", city)
: text.Format(made ? "report.workshop_arms_n" : "report.workshop_paused_debt_n", city, n);
}).ToList();
}
/// <summary>#1293: every order the enemy AI gave in the last turn, and every attack its units made, a standing one too
/// (#1297), as the sim names it on its cause (Cause.EnemyOrder, R-ENEMY-001), in the sim's order, in the player's
/// language: Message is English only. The unit is named by its row
/// (unit i of a new game is StartingForces[i], R-UNIT-006), in Hebrew by its name_he where it has one.</summary>
static IReadOnlyList<string> EnemyOrders(SimBridge bridge, UiText text, IReadOnlyList<UnitEntry>? units)
{
var turn = bridge.Session.Last;
if (turn == null) return Array.Empty<string>();
string Name(Cause cause, int id)
{
var snapshot = cause.Units.FirstOrDefault(u => u.Id == id);
if (snapshot != null) return UnitNames.Of(snapshot, bridge.Content, units ?? Array.Empty<UnitEntry>(), text);
return text.Format("report.unit", id);
}
// An engagement (#1297) names its enemy attackers, one line each, and gives no line if it names none: its Target is
// a hex, not a unit. An order names its unit, Target. A new attack order that engages the same turn names its unit
// on both causes (#2534): one line per order and unit, not two (#2538 review).
return turn.Why.Where(w => w.EnemyOrder != "")
.SelectMany(w => (w.EnemyOrder == Combat.Attack ? w.EnemyAttackers : new[] { int.Parse(w.Target, CultureInfo.InvariantCulture) })
.Select(id => (cause: w, id)))
.GroupBy(x => (x.cause.EnemyOrder, x.id))
.Select(g => text.Format("report.enemy_" + g.Key.EnemyOrder, Name(g.First().cause, g.Key.id))).ToList();
}
void Show()
{
rows.Clear();
foreach (var line in Lines(bridge, text, Units, TownNamesHe))
{
var row = new VisualElement { name = "turn-report-" + line.Meter };
row.AddToClassList("turn-report-row");
var heading = new Label(line.Heading) { name = "turn-report-heading-" + line.Meter };
heading.AddToClassList("turn-report-heading");
row.Add(heading);
if (line.Causes.Count > 0)
{
// One label a cause, so each takes its own direction (UiDirection): in Hebrew a line with a key (B1) is
// right to left and a line still in English left to right.
var causes = new VisualElement { name = "turn-report-causes-" + line.Meter };
causes.AddToClassList("turn-report-causes");
foreach (var cause in line.Causes)
{
var label = new Label(cause);
label.AddToClassList("turn-report-cause");
causes.Add(label);
}
row.Add(causes);
}
rows.Add(row);
}
if (rows.childCount == 0) { Hide(); return; } // nothing in the bar moved: no report to dismiss
nav.Close();
report.style.display = DisplayStyle.Flex;
hudRoot.AddToClassList(OpenClass);
ScreenNav.DisableCovered(hudRoot); // the report comes out uncovered (or under an outcome clip) and takes the focus then
Showing?.Invoke(seen);
}
void OnClose() => Close();
/// <summary>Closes the report; false when it was not open (GameRoot's Escape chain).</summary>
public bool Close()
{
if (!IsOpen) return false;
Hide();
return true;
}
void Hide()
{
bool wasOpen = IsOpen;
if (wasOpen) closedAt = UnityEngine.Time.frameCount;
report.style.display = DisplayStyle.None;
hudRoot.RemoveFromClassList(OpenClass);
ScreenNav.DisableCovered(hudRoot); // the decision layer comes back: an open card takes the focus (OnUncovered)
if (wasOpen) Showing?.Invoke(null);
}
void SeeAll()
{
Hide();
nav.Open("why");
}
public void Dispose()
{
bridge.Changed -= onChanged;
bridge.TurnEnded -= onTurn;
nav.Changed -= onScreen;
close.clicked -= OnClose;
all.clicked -= SeeAll;
report.UnregisterCallback(onCancel);
ScreenNav.OnUncovered(report, null);
Hide();
}
}
}