Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

UI: the promo's Cabinet and Defence screens, with narrow-window and Escape fixes (refs #199) (#239)

Eyal Golanc992e440670f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 65d72d27f..ab441b516 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -93,6 +93,22 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
Narrower windows get a compact top bar, and windows narrower than about square get a taller one that puts each change
under its value. Keyboard focus has a fill at least 3:1 against the unfocused button, and a mouse click leaves no
focus behind. Presentation only.
+- The Cabinet and Defence screens are laid out as the promo (`promo/final/04`, `08`), wider, over the hex panel (which
+ is hidden while they are open, so its buttons take no focus):
+ - Cabinet: the Prime Minister's card at the side (with every office the PM holds), the legislature as a half circle of
+ seats, coalition and opposition, with the majority line and each party's seats, and a card per office with portrait
+ (or initials), party, and competence and loyalty as bars;
+ - Defence: the Prime Minister, Minister of Defense and Chief of Staff as cards (one per person), the escalation
+ ladder with the ordered level marked, the reserve call-up as a bar with its minimum, and the defence share of the
+ budget.
+
+ Every figure is the sim's; the promo's forces, intelligence and procurement panels are left out because the sim does
+ not model them yet. A hidden screen does no work when the game changes, and an open one updates in place, keeping
+ keyboard focus. Presentation only.
+- The screens fit narrow windows (#210, #211): in the two-row HUD (narrower than about square, such as a phone's 390 px)
+ every screen takes the full width, with the event column and the hex panel hidden under it, and a screen's header
+ wraps. Escape closes the open screen. The Cabinet says a refusal that applies to every candidate (the Prime Minister's
+ or the President's office) once, not under each name (#215).
- The historical AI no longer sends an order the turn's attention cannot cover (the rule the UI's order queue applies),
so the sim never has to refuse one; the golden playthroughs are unchanged.
- The browser build downloads a smaller heightmap: `heightmap.r16z` (4.1 MB, packed losslessly: row deltas in byte
diff --git a/unity/Assets/Scripts/UI/CabinetPresenter.cs b/unity/Assets/Scripts/UI/CabinetPresenter.cs
index 9d2e36d75..60527903d 100644
--- a/unity/Assets/Scripts/UI/CabinetPresenter.cs
+++ b/unity/Assets/Scripts/UI/CabinetPresenter.cs
@@ -1,38 +1,76 @@
#nullable enable
+using System.Collections.Generic;
using System.Linq;
using Statecraft.Sim;
+using UnityEngine;
using UnityEngine.UIElements;
namespace Statecraft.Game.UI
{
- /// <summary>The Cabinet screen: the government of the day, its coalition, and every office with its holder (portrait,
- /// party, competence and loyalty). Selecting an office lists every person with Appoint, or the reason they cannot be
- /// appointed (Cabinet.Check). Appointing queues the Appoint order for End Turn.</summary>
+ /// <summary>The Cabinet screen, laid out as promo/final/04: the government of the day and the body it answers to; the
+ /// Prime Minister's card at the side, listing every office the PM holds (each also a button to select it); the
+ /// legislature as a half circle of seats, coalition and opposition, with the majority line, and the coalition's seats,
+ /// the opposition's, the majority, the largest party, coalition stability and each party's seats beside it; and a card
+ /// for every other office held by someone else (portrait, party, competence and loyalty bars). Every number is the
+ /// sim's: legislatures.yaml seats and size, governments.yaml coalition, people.yaml competence and loyalty, GameState
+ /// coalition stability. The two seat colours mark coalition and opposition only (content records no party colours).
+ /// Selecting an office lists every person with Appoint, or the reason they cannot be appointed (Cabinet.Check).
+ /// Appointing queues the Appoint order for End Turn. The screen renders only while it is open (a change while it is
+ /// hidden is caught up when ScreenNav opens it), and it updates its cards in place, so keyboard focus survives.</summary>
public sealed class CabinetPresenter : System.IDisposable
{
+ public const string PrimeMinister = "prime_minister";
+ /// <summary>Portrait boxes in logical pixels (Statecraft.uss .seat / .pm-card .card-portrait).</summary>
+ public static readonly Vector2 CardPortrait = new Vector2(188f, 150f), PmPortrait = new Vector2(286f, 250f);
+ /// <summary>The seat colours: coalition blue and opposition grey, each at least 3:1 against the screen's navy.</summary>
+ public static readonly Color CoalitionColour = new Color32(92, 138, 200, 255), OppositionColour = new Color32(186, 180, 168, 255);
+
readonly VisualElement screen; readonly SimBridge bridge; readonly UiText text; readonly PortraitCatalog? portraits;
+ readonly Button pmCard; readonly System.Action onPm;
+ readonly ScrollView list, candidates; readonly VisualElement pmOffices, chips; readonly Hemicycle hemicycle;
+ readonly Dictionary<string, Button> cards = new Dictionary<string, Button>();
+ List<string> cardOrder = new List<string>(), pmOrder = new List<string>();
+ readonly Dictionary<string, (Button appoint, Label reason)> rows = new Dictionary<string, (Button, Label)>();
+ string? pickFor; string chipsFor = "";
+ bool dirty;
public CabinetPresenter(VisualElement root, SimBridge bridge, UiText text, PortraitCatalog? portraits)
{
screen = root.Q<VisualElement>("screen-cabinet"); this.bridge = bridge; this.text = text; this.portraits = portraits;
- bridge.Changed += Render;
+ pmCard = screen.Q<Button>("seat-" + PrimeMinister);
+ list = screen.Q<ScrollView>("cabinet-seats"); candidates = screen.Q<ScrollView>("cabinet-candidates");
+ pmOffices = screen.Q<VisualElement>("cabinet-pm-offices"); chips = screen.Q<VisualElement>("cabinet-parties");
+ hemicycle = screen.Q<Hemicycle>("cabinet-hemicycle");
+ onPm = () => Select(PrimeMinister);
+ pmCard.clicked += onPm;
+ screen.Q<Label>("cabinet-house-unit").text = text["cabinet.members_unit"];
+ bridge.Changed += OnChanged;
+ ScreenNav.OnOpened(screen, () => { if (dirty) Render(); });
Render();
}
- /// <summary>Unsubscribes from the bridge and removes the rows (the owner calls this when disabled).</summary>
+ /// <summary>Unsubscribes and empties every card, list and the half circle (the owner calls this when disabled).</summary>
public void Dispose()
{
- bridge.Changed -= Render;
- screen.Q<ScrollView>("cabinet-seats")?.Clear();
- screen.Q<ScrollView>("cabinet-candidates")?.Clear();
+ bridge.Changed -= OnChanged;
+ pmCard.clicked -= onPm;
+ if (screen.userData is System.Action) screen.userData = null;
+ list.Clear(); candidates.Clear(); pmOffices.Clear(); chips.Clear(); PersonCard.Clear(pmCard);
+ cards.Clear(); rows.Clear(); cardOrder.Clear(); pmOrder.Clear(); pickFor = null; chipsFor = "";
+ hemicycle.Set(new Hemicycle.Group[0], 0);
screen.Q<VisualElement>("cabinet-pick").style.display = DisplayStyle.None;
}
/// <summary>The office whose candidates are listed, or null.</summary>
public string? Selected { get; private set; }
+ /// <summary>How many times the screen was rendered (a hidden screen is not).</summary>
+ public int Renders { get; private set; }
+
public void Select(string? office) { Selected = office; Render(); }
+ void OnChanged() { if (ScreenNav.IsOpen(screen)) Render(); else dirty = true; }
+
string Describe(Person p)
{
var c = bridge.Content; var party = Offices.PartyOf(c, p, bridge.State.Date);
@@ -40,60 +78,171 @@ namespace Statecraft.Game.UI
return text.Format("cabinet.person", p.Name, partyName, p.Competence, p.Loyalty);
}
+ /// <summary>The legislature's party blocks in drawing order: the coalition's parties, then the opposition's, each by
+ /// seats (most first, then content order), in the coalition or opposition colour. Parties without a seat are left out.</summary>
+ public static IReadOnlyList<Hemicycle.Group> Blocks(Content c, Legislature leg, Government? gov)
+ {
+ var order = c.Parties.Select((p, i) => (p.Id, i)).ToDictionary(x => x.Id, x => x.i);
+ int Order(string id) => order.TryGetValue(id, out var i) ? i : int.MaxValue;
+ var inCoalition = new HashSet<string>(gov?.Coalition ?? new List<string>());
+ var blocks = new List<Hemicycle.Group>();
+ foreach (var coalition in new[] { true, false })
+ foreach (var kv in leg.Seats.Where(kv => kv.Value > 0 && inCoalition.Contains(kv.Key) == coalition)
+ .OrderByDescending(kv => kv.Value).ThenBy(kv => Order(kv.Key)))
+ blocks.Add(new Hemicycle.Group(kv.Key, kv.Value, coalition ? CoalitionColour : OppositionColour, coalition));
+ return blocks;
+ }
+
public void Render()
{
+ dirty = false; Renders++;
var c = bridge.Content; var s = bridge.State;
var gov = Offices.Government(c, s.Date);
+ var leg = Offices.Legislature(c, s.Date);
var (seats, size) = PoliticsSystem.CoalitionSeats(c, s.Date);
screen.Q<Label>("cabinet-government").text = gov?.Name ?? "";
- screen.Q<Label>("cabinet-coalition").text = text.Format("cabinet.coalition", seats, size, PlayerText.Percent(s.CoalitionStability));
- var list = screen.Q<ScrollView>("cabinet-seats");
- list.Clear();
+ screen.Q<Label>("cabinet-legislature").text = leg == null ? "" : text.Format("cabinet.legislature", leg.Body, leg.Size);
+ RenderHouse(c, s, gov, leg, seats, size);
+
var lineup = Cabinet.Lineup(c, s);
if (Selected != null && lineup.All(x => x.Office.Id != Selected)) Selected = null; // that office no longer exists (abolished)
- foreach (var seat in lineup)
+
+ // The Prime Minister's card lists every office the PM holds today (Ben-Gurion was also Minister of Defense);
+ // those offices get no second card, but each stays selectable from a button under the PM card.
+ var pmSeat = lineup.FirstOrDefault(x => x.Office.Id == PrimeMinister);
+ var pm = pmSeat?.Holder;
+ bool HeldByPm(Seat x) => pm != null && x.Office.Id != PrimeMinister && x.Holder?.Id == pm.Id;
+ pmCard.EnableInClassList("seat-selected", Selected == PrimeMinister);
+ if (pmSeat != null)
{
- var office = seat.Office.Id;
- var row = new Button(() => Select(office)) { name = "seat-" + office };
- row.AddToClassList("seat");
- row.EnableInClassList("seat-selected", office == Selected);
- var portrait = new VisualElement();
- portrait.AddToClassList("seat-portrait");
- var tex = portraits?.Get(seat.Holder?.Id);
- if (tex != null) portrait.style.backgroundImage = new StyleBackground(tex);
- portrait.style.display = tex != null ? DisplayStyle.Flex : DisplayStyle.None; // never an invented portrait
- row.Add(portrait);
- var who = seat.Holder == null ? text["cabinet.vacant"] : Describe(seat.Holder) + (seat.Appointed ? text["cabinet.appointed"] : "");
- var label = new Label(text.Format("cabinet.seat", seat.Office.Title, who)) { name = "seat-" + office + "-holder" };
- label.EnableInClassList("appointed", seat.Appointed);
- row.Add(label);
- list.Add(row);
+ var offices = pm == null ? pmSeat.Office.Title
+ : string.Join(text["card.offices_separator"], lineup.Where(x => x.Office.Id == PrimeMinister || HeldByPm(x)).Select(x => x.Office.Title));
+ PersonCard.Fill(pmCard, "seat-" + PrimeMinister, c, s, pm, offices, pmSeat.Appointed, text, portraits, PmPortrait, partyLabel: true);
}
- var pick = screen.Q<VisualElement>("cabinet-pick");
- var candidates = screen.Q<ScrollView>("cabinet-candidates");
- candidates.Clear();
- pick.style.display = Selected == null ? DisplayStyle.None : DisplayStyle.Flex;
- if (Selected != null)
+ var pmHeld = lineup.Where(HeldByPm).ToList();
+ if (!pmHeld.Select(x => x.Office.Id).SequenceEqual(pmOrder))
{
- var office = c.Offices.First(o => o.Id == Selected);
- screen.Q<Label>("cabinet-pick-title").text = text.Format("cabinet.pick", office.Title);
- foreach (var (person, reason) in Cabinet.Candidates(c, s, Selected))
+ pmOffices.Clear();
+ foreach (var seat in pmHeld)
{
- var p = person;
- var row = new VisualElement { name = "cand-" + p.Id };
- row.AddToClassList("candidate");
- var appoint = new Button(() => Appoint(office.Id, p.Id)) { name = "appoint-" + p.Id, text = Describe(p) };
- appoint.SetEnabled(reason == null);
- row.Add(appoint);
- if (reason != null) { var why = new Label(reason) { name = "cand-" + p.Id + "-reason" }; why.AddToClassList("reason"); row.Add(why); }
- candidates.Add(row);
+ var office = seat.Office.Id;
+ var b = new Button(() => Select(office)) { name = "seat-" + office, text = text.Format("cabinet.select_office", seat.Office.Title) };
+ b.AddToClassList("pm-office");
+ pmOffices.Add(b);
}
+ pmOrder = pmHeld.Select(x => x.Office.Id).ToList();
+ }
+ foreach (var b in pmOffices.Children()) b.EnableInClassList("seat-selected", b.name == "seat-" + Selected);
+ pmOffices.style.display = pmHeld.Count > 0 ? DisplayStyle.Flex : DisplayStyle.None;
+
+ var grid = lineup.Where(x => x.Office.Id != PrimeMinister && !HeldByPm(x)).ToList();
+ if (!grid.Select(x => x.Office.Id).SequenceEqual(cardOrder))
+ {
+ list.Clear(); cards.Clear();
+ foreach (var seat in grid)
+ {
+ var office = seat.Office.Id;
+ var card = new Button(() => Select(office)) { name = "seat-" + office };
+ card.AddToClassList("seat");
+ PersonCard.Build(card, "seat-" + office, text);
+ cards[office] = card;
+ list.Add(card);
+ }
+ cardOrder = grid.Select(x => x.Office.Id).ToList();
+ }
+ foreach (var seat in grid)
+ {
+ var card = cards[seat.Office.Id];
+ card.EnableInClassList("seat-selected", seat.Office.Id == Selected);
+ card.EnableInClassList("seat-vacant", seat.Holder == null);
+ PersonCard.Fill(card, "seat-" + seat.Office.Id, c, s, seat.Holder, seat.Office.Title, seat.Appointed, text, portraits, CardPortrait);
}
+
+ RenderPick(c, s);
var queued = bridge.Queued.OfType<Appoint>().Select(a =>
text.Format("cabinet.queued", c.People.First(p => p.Id == a.Person).Name, c.Offices.First(o => o.Id == a.Office).Title));
screen.Q<Label>("cabinet-status").text = string.Join("\n", queued);
}
+ /// <summary>The candidate list for the selected office: rows are made when the office changes and updated in place.</summary>
+ void RenderPick(Content c, GameState s)
+ {
+ var pick = screen.Q<VisualElement>("cabinet-pick");
+ pick.style.display = Selected == null ? DisplayStyle.None : DisplayStyle.Flex;
+ if (Selected != pickFor)
+ {
+ candidates.Clear(); rows.Clear();
+ pickFor = Selected;
+ if (Selected != null)
+ foreach (var person in c.People)
+ {
+ var p = person; var office = Selected;
+ var row = new VisualElement { name = "cand-" + p.Id };
+ row.AddToClassList("candidate");
+ var appoint = new Button(() => Appoint(office, p.Id)) { name = "appoint-" + p.Id };
+ row.Add(appoint);
+ var why = new Label { name = "cand-" + p.Id + "-reason" };
+ why.AddToClassList("reason");
+ row.Add(why);
+ candidates.Add(row);
+ rows[p.Id] = (appoint, why);
+ }
+ }
+ if (Selected == null) return;
+ screen.Q<Label>("cabinet-pick-title").text = text.Format("cabinet.pick", c.Offices.First(o => o.Id == Selected).Title);
+ var list = Cabinet.Candidates(c, s, Selected);
+ // A refusal about the office itself (the Prime Minister's or the President's, an abolished one) is the same for
+ // everyone: it is said once under the heading, not under every name (#215).
+ var shared = list.Count > 0 && list.All(x => x.reason != null && x.reason == list[0].reason) ? list[0].reason : null;
+ var common = screen.Q<Label>("cabinet-pick-reason");
+ common.text = shared ?? "";
+ common.style.display = shared == null ? DisplayStyle.None : DisplayStyle.Flex;
+ foreach (var (person, reason) in list)
+ {
+ if (!rows.TryGetValue(person.Id, out var r)) continue;
+ r.appoint.text = Describe(person);
+ r.appoint.SetEnabled(reason == null);
+ r.reason.text = shared == null ? reason ?? "" : "";
+ r.reason.style.display = reason == null || shared != null ? DisplayStyle.None : DisplayStyle.Flex;
+ }
+ }
+
+ /// <summary>The half circle of seats and its legend; the party list is remade only when the body or government changes.</summary>
+ void RenderHouse(Content c, GameState s, Government? gov, Legislature? leg, int seats, int size)
+ {
+ screen.Q<VisualElement>("cabinet-house").style.display = leg == null ? DisplayStyle.None : DisplayStyle.Flex;
+ screen.Q<Label>("cabinet-coalition").text = text.Format("cabinet.coalition", seats, size, PlayerText.Percent(s.CoalitionStability));
+ screen.Q<UiBar>("cabinet-stability").Value = (float)s.CoalitionStability;
+ if (leg == null) { hemicycle.Set(new Hemicycle.Group[0], 0); chips.Clear(); chipsFor = ""; return; }
+ var blocks = Blocks(c, leg, gov);
+ hemicycle.Set(blocks, leg.Size);
+ screen.Q<Label>("cabinet-house-size").text = leg.Size.ToString(System.Globalization.CultureInfo.InvariantCulture);
+ screen.Q<Label>("cabinet-opposition").text = text.Format("cabinet.opposition", blocks.Where(b => !b.Coalition).Sum(b => b.Seats));
+ screen.Q<Label>("cabinet-majority").text = text.Format("cabinet.majority", hemicycle.Majority);
+ var largest = blocks.OrderByDescending(b => b.Seats).FirstOrDefault();
+ screen.Q<Label>("cabinet-largest").text = largest.Seats > 0 ? text.Format("cabinet.largest", c.Parties.First(p => p.Id == largest.Party).Name, largest.Seats) : "";
+ var key = leg.Id + "/" + (gov?.Id ?? "");
+ if (key == chipsFor) return;
+ chipsFor = key;
+ chips.Clear();
+ foreach (var b in blocks) chips.Add(Chip("party-" + b.Party, b.Colour, text.Format("cabinet.party_seats", c.Parties.First(p => p.Id == b.Party).Name, b.Seats), false));
+ var unrecorded = leg.Size - blocks.Sum(b => b.Seats);
+ if (unrecorded > 0) chips.Add(Chip("party-unrecorded", Color.clear, text.Format("cabinet.party_seats", text["cabinet.unrecorded"], unrecorded), true));
+ }
+
+ static VisualElement Chip(string name, Color colour, string caption, bool hollow)
+ {
+ var chip = new VisualElement { name = name, pickingMode = PickingMode.Ignore };
+ chip.AddToClassList("party-chip");
+ var swatch = new VisualElement { pickingMode = PickingMode.Ignore };
+ swatch.AddToClassList("party-swatch");
+ swatch.EnableInClassList("party-swatch--hollow", hollow);
+ if (!hollow) swatch.style.backgroundColor = colour;
+ chip.Add(swatch);
+ chip.Add(new Label(caption) { name = name + "-label", pickingMode = PickingMode.Ignore });
+ return chip;
+ }
+
void Appoint(string office, string person)
{
// The bridge reports a refusal itself (Refused); the sim re-checks legality when the turn runs.
diff --git a/unity/Assets/Scripts/UI/DefencePresenter.cs b/unity/Assets/Scripts/UI/DefencePresenter.cs
index 1454bde90..beaf6f628 100644
--- a/unity/Assets/Scripts/UI/DefencePresenter.cs
+++ b/unity/Assets/Scripts/UI/DefencePresenter.cs
@@ -6,32 +6,72 @@ using UnityEngine.UIElements;
namespace Statecraft.Game.UI
{
- /// <summary>The Defence screen: the always-on escalation ladder (spec section 3) with the current level and its turn
- /// length, the UN ceasefire clock in full war, security orders to raise or lower the level, and the reserve call-up
- /// with its yearly cost. Orders are queued for End Turn.</summary>
+ /// <summary>The Defence screen, laid out as promo/final/08: the leadership (the Prime Minister, the Minister of Defense
+ /// and the Chief of Staff, each with portrait, party, competence and loyalty), the always-on escalation ladder (spec
+ /// section 3) with the current level, the ordered one and each level's turn length, the UN ceasefire clock in full war,
+ /// security orders to raise or lower the level, the reserve call-up as a bar with the level's minimum marked and its
+ /// yearly cost, and the defence share of the national budget. Orders are queued for End Turn. The promo's forces
+ /// readiness and strength, intelligence and procurement panels are left out: the sim does not model them yet. The call-up
+ /// and the budget share show what the turn will end with (a queued order's value, else today's). The screen renders only
+ /// while it is open (a change while it is hidden is caught up when ScreenNav opens it).</summary>
public sealed class DefencePresenter : IDisposable
{
public const double MobilizationStep = 0.05;
- readonly VisualElement screen; readonly SimBridge bridge; readonly UiText text;
+ /// <summary>The leadership cards, in order, and the budget line that is the defence share.</summary>
+ public static readonly string[] Leaders = { "prime_minister", "defense_minister", "chief_of_staff" };
+ public const string BudgetLine = "defense_minister";
+ /// <summary>The leadership portrait box in logical pixels (Statecraft.uss .leader .card-portrait).</summary>
+ public static readonly UnityEngine.Vector2 LeaderPortrait = new UnityEngine.Vector2(190f, 200f);
+ readonly VisualElement screen; readonly SimBridge bridge; readonly UiText text; readonly PortraitCatalog? portraits;
readonly Button escalate, deEscalate, mobUp, mobDown; readonly Action onEscalate, onDeEscalate, onMobUp, onMobDown;
- public DefencePresenter(VisualElement root, SimBridge bridge, UiText text)
+ public DefencePresenter(VisualElement root, SimBridge bridge, UiText text, PortraitCatalog? portraits = null)
{
- screen = root.Q<VisualElement>("screen-defence"); this.bridge = bridge; this.text = text;
+ screen = root.Q<VisualElement>("screen-defence"); this.bridge = bridge; this.text = text; this.portraits = portraits;
escalate = screen.Q<Button>("escalate"); deEscalate = screen.Q<Button>("de-escalate");
mobUp = screen.Q<Button>("mob-up"); mobDown = screen.Q<Button>("mob-down");
onEscalate = () => Order(+1); onDeEscalate = () => Order(-1);
onMobUp = () => Mobilize(+MobilizationStep); onMobDown = () => Mobilize(-MobilizationStep);
escalate.clicked += onEscalate; deEscalate.clicked += onDeEscalate; mobUp.clicked += onMobUp; mobDown.clicked += onMobDown;
- bridge.Changed += Render;
+ foreach (var (name, key) in Sections) screen.Q<Label>(name).text = text[key].ToUpperInvariant(); // the promo's capitals; a caseless script is unchanged
+ bridge.Changed += OnChanged;
+ ScreenNav.OnOpened(screen, () => { if (dirty) Render(); });
Render();
}
- /// <summary>Unsubscribes from the bridge and the buttons (the owner calls this when disabled).</summary>
+ /// <summary>The section captions and their strings.</summary>
+ static readonly (string name, string key)[] Sections =
+ {
+ ("defence-title-leadership", "defence.section_leadership"), ("defence-title-ladder", "defence.section_ladder"),
+ ("defence-title-callup", "defence.section_callup"), ("defence-title-budget", "defence.section_budget"),
+ };
+
+ bool dirty;
+
+ /// <summary>How many times the screen was rendered (a hidden screen is not).</summary>
+ public int Renders { get; private set; }
+
+ void OnChanged() { if (ScreenNav.IsOpen(screen)) Render(); else dirty = true; }
+
+ /// <summary>Unsubscribes from the bridge and the buttons and empties the leadership cards (the owner calls this when disabled).</summary>
public void Dispose()
{
- bridge.Changed -= Render;
+ bridge.Changed -= OnChanged;
+ if (screen.userData is System.Action) screen.userData = null;
escalate.clicked -= onEscalate; deEscalate.clicked -= onDeEscalate; mobUp.clicked -= onMobUp; mobDown.clicked -= onMobDown;
+ foreach (var office in Leaders) PersonCard.Clear(screen.Q<VisualElement>("lead-" + office));
+ screen.Q<UiBar>("mob-bar").Mark = null;
+ }
+
+ /// <summary>The defence share of spending the turn will end with: a queued budget's, else today's (as the call-up).</summary>
+ public double? ProposedBudgetShare
+ {
+ get
+ {
+ var queued = (bridge.QueuedLike(new AllocateBudget(new System.Collections.Generic.Dictionary<string, double>())) as AllocateBudget)?.Shares;
+ if (queued != null && queued.TryGetValue(BudgetLine, out var q)) return q;
+ return bridge.State.Budget.TryGetValue(BudgetLine, out var today) ? today : (double?)null;
+ }
}
int QueuedDelta => (bridge.QueuedLike(new SecurityOrder(0)) as SecurityOrder)?.Delta ?? 0;
@@ -89,17 +129,35 @@ namespace Statecraft.Game.UI
public void Render()
{
+ dirty = false; Renders++;
var c = bridge.Content; var s = bridge.State;
+ var delta = QueuedDelta;
+ var target = TargetRung;
for (int rung = 1; rung <= 5; rung++)
{
screen.Q<Label>($"rung-{rung}-name").text = text[$"defence.rung{rung}"];
screen.Q<Label>($"rung-{rung}-turn").text = text[TurnKey(SecuritySystem.TurnLengthFor(rung))];
- screen.Q<VisualElement>($"rung-{rung}").EnableInClassList("rung-current", rung == s.Rung);
+ var row = screen.Q<VisualElement>($"rung-{rung}");
+ row.EnableInClassList("rung-current", rung == s.Rung);
+ row.EnableInClassList("rung-target", rung == target && target != s.Rung); // the level an order will move to
}
screen.Q<Label>("defence-command").text = text.Format("defence.command",
Cabinet.Holder(c, s, "defense_minister")?.Name ?? text["cabinet.vacant"], Cabinet.Holder(c, s, "chief_of_staff")?.Name ?? text["cabinet.vacant"]);
- var delta = QueuedDelta;
- var target = TargetRung;
+ // One card per person: a leader who holds several of these offices (Ben-Gurion, Prime Minister and Minister of
+ // Defense) has one card listing them all; a vacancy keeps its own card.
+ var lineup = Cabinet.Lineup(c, s);
+ var seats = Leaders.Select(o => lineup.FirstOrDefault(x => x.Office.Id == o)).ToList();
+ for (int i = 0; i < Leaders.Length; i++)
+ {
+ var card = screen.Q<VisualElement>("lead-" + Leaders[i]);
+ var seat = seats[i];
+ var shownEarlier = seat?.Holder != null && seats.Take(i).Any(x => x?.Holder?.Id == seat.Holder.Id);
+ card.style.display = seat == null || shownEarlier ? DisplayStyle.None : DisplayStyle.Flex;
+ if (seat == null || shownEarlier) continue;
+ var titles = seat.Holder == null ? seat.Office.Title
+ : string.Join("\n", seats.Skip(i).Where(x => x?.Holder?.Id == seat.Holder.Id).Select(x => x!.Office.Title)); // one office a line: the narrow card measured "A · B" as two lines but drew one (a blank line at 1366x768)
+ PersonCard.Fill(card, "lead-" + Leaders[i], c, s, seat.Holder, titles, seat.Appointed, text, portraits, LeaderPortrait);
+ }
var ceasefire = screen.Q<Label>("ceasefire");
if (s.Rung == 5 && target == 5) ceasefire.text = text.Format("defence.ceasefire", s.CeasefireWeeksLeft);
else if (s.Rung == 5) ceasefire.text = text["defence.ceasefire_stops"]; // a lowering is queued
@@ -110,6 +168,12 @@ namespace Statecraft.Game.UI
var floor = SecuritySystem.MinMobilization(c, target);
var proposed = EffectiveAt(ProposedMobilization); // what the call-up will be: the sim raises a lower order to the minimum
screen.Q<Label>("mob-level").text = text.Format("defence.mob", PlayerText.Percent(proposed), target, PlayerText.Percent(floor));
+ screen.Q<Label>("mob-percent").text = PlayerText.Percent(proposed);
+ var bar = screen.Q<UiBar>("mob-bar");
+ bar.Value = (float)proposed; bar.Mark = (float)floor;
+ var share = ProposedBudgetShare;
+ screen.Q<UiBar>("defence-budget-bar").Value = share.HasValue ? (float)share.Value : 0f;
+ screen.Q<Label>("defence-budget-share").text = share.HasValue ? text.Format("defence.budget_share", PlayerText.Percent(share.Value)) : text["defence.budget_none"];
screen.Q<Label>("mob-cost").text = text.Format("defence.mob_cost", PlayerText.Money(c, "treasury", EconomySystem.MobilizationCost(c, proposed)));
screen.Q<Button>("escalate").SetEnabled(target < 5);
screen.Q<Button>("de-escalate").SetEnabled(target > 1);
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 6e2b70c54..3facb7833 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -41,6 +41,7 @@ namespace Statecraft.Game.UI
readonly List<IDisposable> owned = new List<IDisposable>();
MinimapPresenter? minimap;
MapLabelsPresenter? labels;
+ ScreenNav? nav;
CameraRig? rig;
List<(string, int, int, DateTime)>? drawn;
@@ -131,12 +132,12 @@ namespace Statecraft.Game.UI
// The toast first: the autosave (below) must report a failed write after the toast has shown the turn's refusals.
var toast = Own(new ToastPresenter(root, bridge, text));
Own(new HudPresenter(root, bridge, text));
- Own(new ScreenNav(root)); // every screen starts hidden (USS); ScreenNav opens one at a time
+ nav = Own(new ScreenNav(root)); // every screen starts hidden (USS); ScreenNav opens one at a time
Own(new PointerBlur(root)); // a mouse click leaves no focus fill behind (keyboard keeps it)
Own(new NavigationGuard(root)); // the camera keys (WASD, arrows) never move UI focus (B6)
if (DiagLog.Nav) Own(new NavEventLog(root)); // ?navlog: every UI pointer/submit event (playtest 2, P2-4)
var card = Own(new EventCardPresenter(root, bridge, text, portraits));
- Own(new DefencePresenter(root, bridge, text));
+ Own(new DefencePresenter(root, bridge, text, portraits));
Own(new BudgetPresenter(root, bridge, text));
Own(new WhyPresenter(root, bridge, text));
Own(new CabinetPresenter(root, bridge, text, portraits));
@@ -232,7 +233,7 @@ namespace Statecraft.Game.UI
StopAllCoroutines();
for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
owned.Clear();
- minimap = null; labels = null; rig = null; drawn = null; logCamera = false;
+ minimap = null; labels = null; nav = null; rig = null; drawn = null; logCamera = false;
// A ?profile run cut short (a stopped coroutine never reaches its restore line) must not leave the terrain at the
// profile's pixel error (Task 24 review M1). Nothing else changes it, so restoring is always right.
if (map != null && map.Terrain != null) map.Terrain.heightmapPixelError = MapBuilder.TerrainPixelError;
@@ -274,6 +275,9 @@ namespace Statecraft.Game.UI
void Update()
{
+ // Escape closes the open screen even when no element has the keyboard focus (ScreenNav also takes the UI
+ // Cancel event from a focused element; closing twice is harmless).
+ if (UnityEngine.InputSystem.Keyboard.current?.escapeKey.wasPressedThisFrame == true) nav?.Close();
SyncMinimap();
if (!logCamera || rig == null || (rig.Distance == loggedDistance && rig.Yaw == loggedYaw)) return;
loggedDistance = rig.Distance; loggedYaw = rig.Yaw;
diff --git a/unity/Assets/Scripts/UI/Hemicycle.cs b/unity/Assets/Scripts/UI/Hemicycle.cs
new file mode 100644
index 000000000..b0b13810c
--- /dev/null
+++ b/unity/Assets/Scripts/UI/Hemicycle.cs
@@ -0,0 +1,222 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using UnityEngine;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>The legislature as a half circle of seats (promo/final/04), drawn with Painter2D: one dot per seat of the
+ /// body that sits on the date (legislatures.yaml size), coloured by block in the order the presenter gives (the
+ /// coalition's parties first, from the left), with a gold majority line that, row by row, runs between the last seat of
+ /// a majority (more than half the seats, counted from the left) and the next seat, so no dot sits on it. Seats a record
+ /// does not assign to a party are drawn as hollow rings, never given to a party. It takes no clicks.</summary>
+ [UxmlElement]
+ public partial class Hemicycle : VisualElement
+ {
+ /// <summary>One party's block of seats, in drawing order.</summary>
+ public readonly struct Group : IEquatable<Group>
+ {
+ public readonly string Party; public readonly int Seats; public readonly Color Colour; public readonly bool Coalition;
+ public Group(string party, int seats, Color colour, bool coalition) { Party = party; Seats = seats; Colour = colour; Coalition = coalition; }
+ public bool Equals(Group o) => Party == o.Party && Seats == o.Seats && Colour == o.Colour && Coalition == o.Coalition;
+ }
+
+ /// <summary>One seat: its centre on the unit half circle (x in -1..1, y in 0..1, y up), its angle and its row.</summary>
+ public readonly struct SeatPlace
+ {
+ public readonly Vector2 Position; public readonly float Angle; public readonly int Row;
+ public SeatPlace(Vector2 position, float angle, int row) { Position = position; Angle = angle; Row = row; }
+ }
+
+ static readonly Color Gold = new Color32(232, 204, 142, 255), Unrecorded = new Color32(170, 164, 150, 255);
+ /// <summary>Inner radius of the half circle, as a share of the outer.</summary>
+ public const float Inner = 0.42f;
+
+ IReadOnlyList<Group> groups = Array.Empty<Group>();
+ int size;
+ List<SeatPlace> places = new List<SeatPlace>();
+ List<Color?> colours = new List<Color?>();
+ List<Vector2> boundary = new List<Vector2>();
+ float[] cuts = Array.Empty<float>();
+ float dot;
+
+ public Hemicycle()
+ {
+ pickingMode = PickingMode.Ignore;
+ generateVisualContent += Draw;
+ }
+
+ public IReadOnlyList<Group> Groups => groups;
+ /// <summary>The number of seats in the body.</summary>
+ public int Size => size;
+ /// <summary>Seats needed for a majority: more than half.</summary>
+ public int Majority => size / 2 + 1;
+ /// <summary>How many times <see cref="Set"/> changed the picture (an unchanged house is not redrawn).</summary>
+ public int Changes { get; private set; }
+
+ /// <summary>Sets the body's size and its party blocks (their seats may sum to less than the size: the rest are drawn
+ /// unassigned; never more). The same house again changes nothing and is not redrawn.</summary>
+ public void Set(IReadOnlyList<Group> blocks, int bodySize)
+ {
+ if (bodySize < 0) throw new ArgumentOutOfRangeException(nameof(bodySize));
+ if (blocks.Sum(g => g.Seats) > bodySize) throw new ArgumentException("more party seats than the body has", nameof(blocks));
+ if (bodySize == size && blocks.SequenceEqual(groups)) return;
+ groups = blocks.ToList(); size = bodySize;
+ places = Places(size);
+ dot = DotRadius(size);
+ colours = new List<Color?>(size);
+ foreach (var g in groups) for (int i = 0; i < g.Seats; i++) colours.Add(g.Colour);
+ while (colours.Count < size) colours.Add(null);
+ cuts = Cuts(places, Majority, size);
+ boundary = Boundary(cuts, size);
+ Changes++;
+ MarkDirtyRepaint();
+ }
+
+ /// <summary>Each seat's colour from left to right: the blocks in order, then unassigned seats (null).</summary>
+ public IReadOnlyList<Color?> SeatColours() => colours;
+
+ /// <summary>The majority line on the unit half circle, from the inner edge out (see <see cref="Boundary"/>).</summary>
+ public IReadOnlyList<Vector2> MajorityLine => boundary;
+
+ /// <summary>The majority line's angle in each row (radians, inner row first; NaN for an empty row).</summary>
+ public IReadOnlyList<float> MajorityCuts => cuts;
+
+ /// <summary>Rows of seats for a body of <paramref name="seatCount"/>.</summary>
+ public static int Rows(int seatCount) => seatCount <= 12 ? 2 : seatCount <= 40 ? 4 : seatCount <= 90 ? 5 : seatCount <= 160 ? 7 : 9;
+
+ static float Radius(int row, int rows) => rows == 1 ? 1f : Inner + (1f - Inner) * row / (rows - 1);
+
+ /// <summary>Seats per row, inner first: in proportion to each row's length, with at most one row holding an odd
+ /// count (pairs of odd rows give a seat from the inner to the outer one), so at most one seat sits at the top.</summary>
+ public static int[] RowCounts(int seatCount)
+ {
+ int rows = Rows(seatCount);
+ var radii = Enumerable.Range(0, rows).Select(i => Radius(i, rows)).ToArray();
+ var total = radii.Sum();
+ var counts = radii.Select(r => (int)Math.Floor(seatCount * r / total)).ToArray();
+ for (int i = rows - 1, left = seatCount - counts.Sum(); left > 0; i = i == 0 ? rows - 1 : i - 1, left--) counts[i]++; // the rest to the outer rows
+ var odd = Enumerable.Range(0, rows).Where(i => counts[i] % 2 == 1).ToList();
+ for (int k = 0; k + 1 < odd.Count; k += 2) { counts[odd[k]]--; counts[odd[k + 1]]++; }
+ return counts;
+ }
+
+ /// <summary>Every seat, from left to right by angle (and from the inside out within an angle).</summary>
+ public static List<SeatPlace> Places(int seatCount)
+ {
+ var result = new List<SeatPlace>(Math.Max(0, seatCount));
+ if (seatCount <= 0) return result;
+ int rows = Rows(seatCount);
+ var counts = RowCounts(seatCount);
+ var placed = new List<(float angle, int row)>(seatCount);
+ for (int row = 0; row < rows; row++)
+ for (int j = 0; j < counts[row]; j++)
+ placed.Add((counts[row] == 1 ? Mathf.PI / 2 : Mathf.PI * (1f - (float)j / (counts[row] - 1)), row));
+ foreach (var (a, row) in placed.OrderByDescending(p => Math.Round(p.angle, 5)).ThenBy(p => p.row))
+ {
+ var r = Radius(row, rows);
+ // sin(pi) is -9e-8 in float: keep the ends on the base line.
+ result.Add(new SeatPlace(new Vector2(Mathf.Cos(a) * r, Mathf.Max(0f, Mathf.Sin(a)) * r), a, row));
+ }
+ return result;
+ }
+
+ /// <summary>Seat centres on the unit half circle, from left to right (see <see cref="Places"/>).</summary>
+ public static List<Vector2> Layout(int seatCount) => Places(seatCount).Select(p => p.Position).ToList();
+
+ /// <summary>A dot's radius on the unit half circle: under half the gap between rows and between seats in the outer row.</summary>
+ public static float DotRadius(int seatCount)
+ {
+ if (seatCount <= 0) return 0f;
+ int rows = Rows(seatCount);
+ var rowGap = rows == 1 ? 1f : (1f - Inner) / (rows - 1);
+ var outer = RowCounts(seatCount)[rows - 1];
+ var seatGap = outer <= 1 ? 1f : Mathf.PI / (outer - 1);
+ return 0.34f * Mathf.Min(rowGap, seatGap); // leaves room for the majority line and its stroke between dots
+ }
+
+ /// <summary>Where the majority line crosses each row (radians, inner row first; NaN for an empty row): between the
+ /// row's last seat among the first <paramref name="majority"/> (counted from the left) and its next seat; half a
+ /// step outside the row when the whole row is on one side.</summary>
+ public static float[] Cuts(IReadOnlyList<SeatPlace> seats, int majority, int seatCount)
+ {
+ int rows = seatCount <= 0 ? 0 : Rows(seatCount);
+ var cuts = new float[rows];
+ for (int row = 0; row < rows; row++)
+ {
+ var inRow = seats.Select((s, i) => (s, i)).Where(x => x.s.Row == row).ToList(); // left to right
+ if (inRow.Count == 0) { cuts[row] = float.NaN; continue; }
+ var step = inRow.Count > 1 ? Mathf.PI / (inRow.Count - 1) : Mathf.PI;
+ bool anyMajority = inRow.Any(x => x.i < majority), anyRest = inRow.Any(x => x.i >= majority);
+ cuts[row] = !anyMajority ? inRow[0].s.Angle + step / 2 // the whole row is outside the majority
+ : !anyRest ? inRow[inRow.Count - 1].s.Angle - step / 2 // the whole row is inside it
+ : (inRow.Last(x => x.i < majority).s.Angle + inRow.First(x => x.i >= majority).s.Angle) / 2;
+ }
+ return cuts;
+ }
+
+ /// <summary>The majority line through the row cuts: in each row a radial step at its cut, and consecutive rows joined
+ /// along the circle half way between them. Points on the unit half circle, inner edge first.</summary>
+ public static List<Vector2> Boundary(IReadOnlyList<float> cuts, int seatCount)
+ {
+ var line = new List<Vector2>();
+ if (seatCount < 2) return line;
+ int rows = cuts.Count;
+ var gap = rows <= 1 ? 0.5f : (1f - Inner) / (rows - 1);
+ Vector2 At(float angle, float r) => new Vector2(Mathf.Cos(angle) * r, Mathf.Sin(angle) * r);
+ float? previous = null;
+ for (int row = 0; row < rows; row++)
+ {
+ var angle = cuts[row];
+ if (float.IsNaN(angle)) continue;
+ var r = Radius(row, rows);
+ float lo = r - gap / 2, hi = r + gap / 2;
+ if (previous.HasValue) // along the circle between the rows, from the last row's angle to this one's
+ for (int k = 1; k <= 8; k++) line.Add(At(Mathf.Lerp(previous.Value, angle, k / 8f), lo));
+ else line.Add(At(angle, lo));
+ line.Add(At(angle, hi));
+ previous = angle;
+ }
+ return line;
+ }
+
+ /// <summary>The majority line's stroke, in pixels.</summary>
+ public const float LineWidth = 2f;
+
+ /// <summary>The margin round the unit half circle: the dots, and the line's ends half a row gap out.</summary>
+ static float Margin(int seatCount) => Mathf.Max(DotRadius(seatCount), (1f - Inner) / Mathf.Max(1, Rows(seatCount) - 1) / 2f);
+
+ /// <summary>Pixels per unit radius when the house is fitted into a box of <paramref name="box"/> pixels.</summary>
+ public static float ScaleFor(Vector2 box, int seatCount)
+ {
+ var m = Margin(seatCount);
+ return Mathf.Min(box.x / (2f + 2f * m), box.y / (1f + 2f * m));
+ }
+
+ void Draw(MeshGenerationContext mgc)
+ {
+ var box = contentRect;
+ if (size == 0 || !(box.width > 8) || !(box.height > 8)) return;
+ // The unit half circle plus a margin, fitted into the box and sat on its bottom edge.
+ var margin = Margin(size);
+ var scale = ScaleFor(box.size, size);
+ var centre = new Vector2(box.center.x, box.yMax - margin * scale);
+ Vector2 At(Vector2 unit) => centre + new Vector2(unit.x, -unit.y) * scale;
+ var p = mgc.painter2D;
+ for (int i = 0; i < size; i++)
+ {
+ var c = colours[i];
+ p.BeginPath(); p.Arc(At(places[i].Position), dot * scale, Angle.Degrees(0), Angle.Degrees(360)); p.ClosePath();
+ if (c.HasValue) { p.fillColor = c.Value; p.Fill(); }
+ else { p.strokeColor = Unrecorded; p.lineWidth = 1.2f; p.Stroke(); }
+ }
+ if (boundary.Count < 2) return;
+ p.strokeColor = Gold; p.lineWidth = LineWidth; p.lineCap = LineCap.Round; p.lineJoin = LineJoin.Round;
+ p.BeginPath(); p.MoveTo(At(boundary[0]));
+ for (int i = 1; i < boundary.Count; i++) p.LineTo(At(boundary[i]));
+ p.Stroke();
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/Hemicycle.cs.meta b/unity/Assets/Scripts/UI/Hemicycle.cs.meta
new file mode 100644
index 000000000..24924a456
--- /dev/null
+++ b/unity/Assets/Scripts/UI/Hemicycle.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: ffdda698922164ddaba3fab57dfc678a
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/HudPresenter.cs b/unity/Assets/Scripts/UI/HudPresenter.cs
index 378813d21..54a5e92fb 100644
--- a/unity/Assets/Scripts/UI/HudPresenter.cs
+++ b/unity/Assets/Scripts/UI/HudPresenter.cs
@@ -33,6 +33,11 @@ namespace Statecraft.Game.UI
/// below (Statecraft.uss .hud-two-row).</summary>
public const float TwoRowBelowPx = 1500f;
public const string TwoRowClass = "hud-two-row";
+ /// <summary>Below this width (a phone held upright: 390x844 is about 790 logical px) the badge and six meters do not
+ /// fit one row either: the root also gets ThreeRowClass, and the bar takes three rows, the badge, the meters, then the
+ /// screen buttons and End Turn (Statecraft.uss .hud-three-row; #210).</summary>
+ public const float ThreeRowBelowPx = 1100f;
+ public const string ThreeRowClass = "hud-three-row";
/// <summary>On the one-row bar, when the meters leave enough room, the bar gets RoomyClass: promo-sized icons (38 px)
/// and values (25 px) (Statecraft.uss .top-bar--roomy). It turns on only when the measured spare room covers the
/// predicted growth (RoomyGrowth) plus SpareShare, and off when the spare room falls below SpareShare, so it never
@@ -71,7 +76,7 @@ namespace Statecraft.Game.UI
bar.UnregisterCallback<GeometryChangedEvent>(OnBarGeometry);
foreach (var m in meters) m.UnregisterCallback<GeometryChangedEvent>(OnMeterGeometry);
bar.RemoveFromClassList(RoomyClass);
- bar.RemoveFromClassList(CompactClass); hudRoot.RemoveFromClassList(NarrowClass); hudRoot.RemoveFromClassList(TwoRowClass);
+ bar.RemoveFromClassList(CompactClass); hudRoot.RemoveFromClassList(NarrowClass); hudRoot.RemoveFromClassList(TwoRowClass); hudRoot.RemoveFromClassList(ThreeRowClass);
}
// The bar's width does not depend on the class, so this settles in one pass.
@@ -112,6 +117,7 @@ namespace Statecraft.Game.UI
bar.EnableInClassList(CompactClass, width < CompactBelowPx);
hudRoot.EnableInClassList(NarrowClass, width < NarrowBelowPx);
hudRoot.EnableInClassList(TwoRowClass, width < TwoRowBelowPx);
+ hudRoot.EnableInClassList(ThreeRowClass, width < ThreeRowBelowPx);
}
/// <summary>End Turn's hourglass, in the button's left padding (Statecraft.uss .end-turn), painted into the button so it
diff --git a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs b/unity/Assets/Scripts/UI/InfoPanelPresenter.cs
index 422219ce1..1c6054366 100644
--- a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs
+++ b/unity/Assets/Scripts/UI/InfoPanelPresenter.cs
@@ -41,7 +41,15 @@ namespace Statecraft.Game.UI
public (int q, int r)? Selected { get; private set; }
- public void Show(int q, int r) { Selected = (q, r); Render(); }
+ /// <summary>Shows the hex; ignored while a screen covers the panel (a wide screen, or any screen in the two-row HUD),
+ /// so a map click cannot change a panel the player cannot see.</summary>
+ public void Show(int q, int r)
+ {
+ var hud = panel.parent;
+ if (hud != null && (hud.ClassListContains(ScreenNav.WideOpenClass)
+ || (hud.ClassListContains(ScreenNav.ScreenOpenClass) && hud.ClassListContains(HudPresenter.TwoRowClass)))) return; // covered (#210)
+ Selected = (q, r); Render();
+ }
void Build(string action)
{
diff --git a/unity/Assets/Scripts/UI/PersonCard.cs b/unity/Assets/Scripts/UI/PersonCard.cs
new file mode 100644
index 000000000..8a691b975
--- /dev/null
+++ b/unity/Assets/Scripts/UI/PersonCard.cs
@@ -0,0 +1,123 @@
+#nullable enable
+using System.Linq;
+using Statecraft.Sim;
+using UnityEngine;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>A person card in the promo's style (promo/final/04 and 08), shared by the Cabinet and Defence screens: the
+ /// framed portrait (or, with none in the catalog, a plain plate with the initials: never an invented likeness), the
+ /// name, the office, the party, and competence and loyalty as two bars with their values out of 10 (people.yaml). A
+ /// vacant office shows its title and "(vacant)" only. The card's elements are made once and updated in place, so a
+ /// focused card keeps its focus. Element names start with the given prefix (<c>{prefix}-holder</c>, <c>-office</c>,
+ /// <c>-party</c>, <c>-portrait</c>, <c>-initials</c>, <c>-competence</c>, <c>-competence-value</c>, <c>-loyalty</c>,
+ /// <c>-loyalty-value</c>).</summary>
+ public static class PersonCard
+ {
+ public const string PortraitClass = "card-portrait", InitialsClass = "card-initials", NameClass = "card-name",
+ OfficeClass = "card-office", PartyClass = "card-party", StatClass = "card-stat";
+ /// <summary>The scale of competence and loyalty (people.yaml; ContentLoader refuses values outside 0-10).</summary>
+ public const int Scale = 10;
+
+ /// <summary>The person's initials (first letter of the first and last words of the name), for the plate shown when
+ /// there is no portrait.</summary>
+ public static string Initials(string name)
+ {
+ var words = name.Split(new[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
+ if (words.Length == 0) return "";
+ return words.Length == 1 ? words[0].Substring(0, 1) : words[0].Substring(0, 1) + words[words.Length - 1].Substring(0, 1);
+ }
+
+ /// <summary>Makes the card's elements inside <paramref name="card"/> (cleared first), empty.</summary>
+ public static void Build(VisualElement card, string prefix, UiText text)
+ {
+ card.Clear();
+ var plate = Element(prefix + "-plate", "card-plate");
+ plate.Add(Element(prefix + "-portrait", PortraitClass));
+ plate.Add(Text(prefix + "-initials", InitialsClass));
+ card.Add(plate);
+ card.Add(Text(prefix + "-holder", NameClass));
+ card.Add(Text(prefix + "-office", OfficeClass));
+ card.Add(Text(prefix + "-party", PartyClass));
+ card.Add(Stat(prefix + "-competence", text["card.competence"], "ui-bar--competence"));
+ card.Add(Stat(prefix + "-loyalty", text["card.loyalty"], "ui-bar--loyalty"));
+ }
+
+ /// <summary>Fills <paramref name="card"/> in place, building it first if it has not been built with this prefix.
+ /// <paramref name="office"/> is the line under the name; <paramref name="portraitSize"/> is the portrait box in
+ /// logical pixels (Statecraft.uss), used to keep the face in view.</summary>
+ public static void Fill(VisualElement card, string prefix, Content c, GameState s, Person? person, string office, bool appointed,
+ UiText text, PortraitCatalog? portraits, Vector2 portraitSize, bool partyLabel = false)
+ {
+ if (card.Q(prefix + "-plate") == null) Build(card, prefix, text);
+ var portrait = card.Q(prefix + "-portrait");
+ var entry = portraits?.Find(person?.Id);
+ var tex = entry?.image;
+ if (tex != null)
+ {
+ portrait.style.backgroundImage = new StyleBackground(tex);
+ portrait.style.backgroundPositionY = new BackgroundPosition(BackgroundPositionKeyword.Top,
+ new Length(PortraitFraming.PositionYPercent(tex.width, tex.height, portraitSize.x, portraitSize.y, entry!.Value.focusY), LengthUnit.Percent));
+ }
+ else portrait.style.backgroundImage = StyleKeyword.None;
+ portrait.style.display = tex != null ? DisplayStyle.Flex : DisplayStyle.None; // never an invented portrait
+ var initials = card.Q<Label>(prefix + "-initials");
+ initials.text = person == null || tex != null ? "" : Initials(person.Name);
+ initials.style.display = tex == null ? DisplayStyle.Flex : DisplayStyle.None;
+
+ var holder = card.Q<Label>(prefix + "-holder");
+ holder.text = person == null ? text["cabinet.vacant"] : appointed ? text.Format("card.appointed_name", person.Name) : person.Name;
+ holder.EnableInClassList("appointed", appointed);
+ card.Q<Label>(prefix + "-office").text = office;
+
+ var party = card.Q<Label>(prefix + "-party");
+ var shown = person != null ? DisplayStyle.Flex : DisplayStyle.None;
+ party.style.display = shown;
+ card.Q(prefix + "-competence-row").style.display = shown;
+ card.Q(prefix + "-loyalty-row").style.display = shown;
+ if (person == null) return;
+ var partyId = Offices.PartyOf(c, person, s.Date);
+ var partyName = partyId == "" ? text["cabinet.no_party"] : c.Parties.First(x => x.Id == partyId).Name;
+ party.text = partyLabel ? text.Format("card.party", partyName) : partyName;
+ SetStat(card, prefix + "-competence", person.Competence);
+ SetStat(card, prefix + "-loyalty", person.Loyalty);
+ }
+
+ /// <summary>Empties a card (a disposed screen keeps no stale person or texture).</summary>
+ public static void Clear(VisualElement card) => card.Clear();
+
+ static void SetStat(VisualElement card, string name, int value)
+ {
+ card.Q<UiBar>(name).Value = (float)value / Scale;
+ card.Q<Label>(name + "-value").text = value.ToString(System.Globalization.CultureInfo.InvariantCulture);
+ }
+
+ static VisualElement Element(string name, string className)
+ {
+ var e = new VisualElement { name = name, pickingMode = PickingMode.Ignore };
+ e.AddToClassList(className);
+ return e;
+ }
+
+ static Label Text(string name, string className)
+ {
+ var l = new Label { name = name, pickingMode = PickingMode.Ignore };
+ l.AddToClassList(className);
+ return l;
+ }
+
+ static VisualElement Stat(string name, string caption, string modifier)
+ {
+ var row = Element(name + "-row", StatClass);
+ var label = new Label(caption) { pickingMode = PickingMode.Ignore };
+ label.AddToClassList("card-stat-name");
+ row.Add(label);
+ var bar = new UiBar { name = name };
+ bar.AddToClassList(modifier);
+ row.Add(bar);
+ row.Add(Text(name + "-value", "card-stat-value"));
+ return row;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/PersonCard.cs.meta b/unity/Assets/Scripts/UI/PersonCard.cs.meta
new file mode 100644
index 000000000..85c072d38
--- /dev/null
+++ b/unity/Assets/Scripts/UI/PersonCard.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 9536ffa43d3014930a74f78e48974b82
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/ScreenNav.cs b/unity/Assets/Scripts/UI/ScreenNav.cs
index ff9531981..564adb63e 100644
--- a/unity/Assets/Scripts/UI/ScreenNav.cs
+++ b/unity/Assets/Scripts/UI/ScreenNav.cs
@@ -13,12 +13,32 @@ namespace Statecraft.Game.UI
public static readonly string[] Screens = { "cabinet", "budget", "defence", "why" };
/// <summary>The class on the open screen's button (Statecraft.uss lights its ring).</summary>
public const string OpenClass = "nav-open";
+ /// <summary>The class on the "root" element while a wide screen (class <see cref="WideClass"/>: Cabinet, Defence) is
+ /// open: Statecraft.uss hides the info panel it covers, so its buttons take no focus and no clicks.</summary>
+ public const string WideOpenClass = "wide-screen-open", WideClass = "screen-wide";
+ /// <summary>The class on the "root" element while any screen is open: in the two-row (narrow) HUD every screen takes
+ /// the full width, so Statecraft.uss hides the event column and the info panel under it (#210).</summary>
+ public const string ScreenOpenClass = "screen-open";
+
+ /// <summary>Asks to be told, synchronously, whenever <paramref name="screen"/> is opened (a presenter that skips
+ /// rendering while its screen is hidden catches up then).</summary>
+ public static void OnOpened(VisualElement screen, System.Action action) => screen.userData = action;
+
+ /// <summary>True when <paramref name="screen"/> is open (ScreenNav shows it inline; the stylesheet hides it).</summary>
+ public static bool IsOpen(VisualElement screen) =>
+ screen.style.display.keyword == StyleKeyword.Undefined && screen.style.display.value == DisplayStyle.Flex;
readonly VisualElement root;
readonly List<(Button, System.Action)> hooks = new List<(Button, System.Action)>();
+ readonly EventCallback<NavigationCancelEvent> onCancel;
public ScreenNav(VisualElement root)
{
this.root = root;
+ // Escape (the UI map's Cancel, from any focused element or the panel) closes the open screen. NavigationGuard
+ // handles only NavigationMoveEvent, so the two never meet. GameRoot also polls the Escape key for the case where
+ // no element has the focus (CloseOnEscape).
+ onCancel = e => { if (Close()) e.StopPropagation(); };
+ root.RegisterCallback(onCancel, TrickleDown.TrickleDown);
foreach (var s in Screens)
{
var screen = s;
@@ -30,7 +50,22 @@ namespace Statecraft.Game.UI
Open(null);
}
- public void Dispose() { foreach (var (b, h) in hooks) b.clicked -= h; hooks.Clear(); }
+ public void Dispose()
+ {
+ foreach (var (b, h) in hooks) b.clicked -= h;
+ hooks.Clear();
+ root.UnregisterCallback(onCancel, TrickleDown.TrickleDown);
+ var r = root.Q("root") ?? root;
+ r.RemoveFromClassList(WideOpenClass); r.RemoveFromClassList(ScreenOpenClass);
+ }
+
+ /// <summary>Closes the open screen (Escape); false when none was open.</summary>
+ public bool Close()
+ {
+ if (Current == null) return false;
+ Open(null);
+ return true;
+ }
/// <summary>The open screen's name, or null.</summary>
public string? Current { get; private set; }
@@ -44,11 +79,17 @@ namespace Statecraft.Game.UI
public void Open(string? screen)
{
Current = screen;
+ var wide = false;
foreach (var s in Screens)
{
- root.Q<VisualElement>("screen-" + s).style.display = s == screen ? DisplayStyle.Flex : DisplayStyle.None;
+ var element = root.Q<VisualElement>("screen-" + s);
+ element.style.display = s == screen ? DisplayStyle.Flex : DisplayStyle.None;
root.Q<Button>("nav-" + s).EnableInClassList(OpenClass, s == screen); // the open screen's button is lit
+ if (s == screen) wide = element.ClassListContains(WideClass);
}
+ (root.Q("root") ?? root).EnableInClassList(WideOpenClass, wide);
+ (root.Q("root") ?? root).EnableInClassList(ScreenOpenClass, screen != null);
+ if (screen != null) (root.Q<VisualElement>("screen-" + screen).userData as System.Action)?.Invoke();
}
}
}
diff --git a/unity/Assets/Scripts/UI/UiBar.cs b/unity/Assets/Scripts/UI/UiBar.cs
new file mode 100644
index 000000000..bf953779c
--- /dev/null
+++ b/unity/Assets/Scripts/UI/UiBar.cs
@@ -0,0 +1,58 @@
+#nullable enable
+using UnityEngine;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>A thin horizontal meter in the promo's style (promo/final/04 and 08): a dark track with a coloured fill for a
+ /// real 0..1 value (a minister's competence or loyalty out of 10, coalition stability, the reserve call-up, a budget
+ /// share), and an optional tick for a threshold on the same scale (the call-up's minimum). The colour comes from a
+ /// modifier class in Statecraft.uss. It takes no clicks and holds no text: the number beside it is a Label. In UXML:
+ /// <c>&lt;Statecraft.Game.UI.UiBar class="ui-bar--stability" /&gt;</c>.</summary>
+ [UxmlElement]
+ public partial class UiBar : VisualElement
+ {
+ public const string ClassName = "ui-bar", FillClass = "ui-bar-fill", MarkClass = "ui-bar-mark";
+ readonly VisualElement fill, mark;
+ float value;
+ float? markAt;
+
+ public UiBar()
+ {
+ AddToClassList(ClassName);
+ pickingMode = PickingMode.Ignore;
+ fill = new VisualElement { name = "fill", pickingMode = PickingMode.Ignore };
+ fill.AddToClassList(FillClass);
+ Add(fill);
+ mark = new VisualElement { name = "mark", pickingMode = PickingMode.Ignore };
+ mark.AddToClassList(MarkClass);
+ mark.style.display = DisplayStyle.None;
+ Add(mark);
+ Value = 0;
+ }
+
+ static float Clamp(float v) => float.IsNaN(v) ? 0f : Mathf.Clamp01(v);
+
+ /// <summary>The filled share, 0..1 (NaN reads as 0).</summary>
+ public float Value
+ {
+ get => value;
+ set { this.value = Clamp(value); fill.style.width = Length.Percent(this.value * 100f); }
+ }
+
+ /// <summary>A tick at this share of the track (0..1), or null for none.</summary>
+ public float? Mark
+ {
+ get => markAt;
+ set
+ {
+ markAt = value.HasValue ? Clamp(value.Value) : (float?)null;
+ mark.style.display = markAt.HasValue ? DisplayStyle.Flex : DisplayStyle.None;
+ if (markAt.HasValue) mark.style.left = Length.Percent(markAt.Value * 100f);
+ }
+ }
+
+ /// <summary>The fill element (tests read its resolved colour).</summary>
+ public VisualElement Fill => fill;
+ }
+}
diff --git a/unity/Assets/Scripts/UI/UiBar.cs.meta b/unity/Assets/Scripts/UI/UiBar.cs.meta
new file mode 100644
index 000000000..508ba2ff5
--- /dev/null
+++ b/unity/Assets/Scripts/UI/UiBar.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 68a99aef7d6e14b6a83c37a949d8616d
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/CabinetScreenTests.cs b/unity/Assets/Tests/EditMode/CabinetScreenTests.cs
index f158c23ec..50643fa2a 100644
--- a/unity/Assets/Tests/EditMode/CabinetScreenTests.cs
+++ b/unity/Assets/Tests/EditMode/CabinetScreenTests.cs
@@ -14,6 +14,14 @@ public class CabinetScreenTests
static readonly Content C = ContentLoader.Load(Paths.Content);
static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ /// <summary>The UI with the Cabinet screen open, as ScreenNav opens it (a hidden screen does not re-render).</summary>
+ static UiTestKit Shown()
+ {
+ var ui = new UiTestKit();
+ ui.Q<VisualElement>("screen-cabinet").style.display = DisplayStyle.Flex;
+ return ui;
+ }
+
/// <summary>The historical game on 26 February 1950: the First Government, whose next turn ends before it falls.</summary>
static SimBridge In1950()
{
@@ -25,13 +33,20 @@ public class CabinetScreenTests
[Test]
public void TheScreenListsTheGovernmentAndRefusesIllegalAppointmentsWithAReason()
{
- using var ui = new UiTestKit();
+ using var ui = Shown();
var bridge = In1950();
var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
Assert.AreEqual("First Government", ui.Q<Label>("cabinet-government").text);
StringAssert.StartsWith("Coalition: 73 of 120 seats", ui.Q<Label>("cabinet-coalition").text);
StringAssert.IsMatch(@"stability \d+%$", ui.Q<Label>("cabinet-coalition").text); // fix round 1, I2: the unit
- Assert.AreEqual("Minister of Finance: Eliezer Kaplan · Mapai · competence 8, loyalty 9", ui.Q<Label>("seat-finance_minister-holder").text);
+ // The finance card (promo 04): name, office, party, and competence and loyalty as bars with their values out of 10.
+ Assert.AreEqual("Eliezer Kaplan", ui.Q<Label>("seat-finance_minister-holder").text);
+ Assert.AreEqual("Minister of Finance", ui.Q<Label>("seat-finance_minister-office").text);
+ Assert.AreEqual("Mapai", ui.Q<Label>("seat-finance_minister-party").text);
+ Assert.AreEqual("8", ui.Q<Label>("seat-finance_minister-competence-value").text);
+ Assert.AreEqual("9", ui.Q<Label>("seat-finance_minister-loyalty-value").text);
+ Assert.AreEqual(0.8f, ui.Q<UiBar>("seat-finance_minister-competence").Value, 1e-6f);
+ Assert.AreEqual(0.9f, ui.Q<UiBar>("seat-finance_minister-loyalty").Value, 1e-6f);
UiTestKit.Press(ui.Q<Button>("seat-finance_minister"));
Assert.AreEqual("finance_minister", cabinet.Selected);
Assert.IsFalse(ui.Q<Button>("appoint-zisling").enabledSelf);
@@ -42,7 +57,7 @@ public class CabinetScreenTests
[Test]
public void AppointingTakesEffectAtEndTurn()
{
- using var ui = new UiTestKit();
+ using var ui = Shown();
var bridge = In1950();
var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
cabinet.Select("finance_minister");
@@ -57,18 +72,20 @@ public class CabinetScreenTests
[Test]
public void APortraitShowsOnlyWhenTheCatalogHasOne()
{
- using var ui = new UiTestKit();
+ using var ui = Shown();
var bridge = In1950();
var catalog = ScriptableObject.CreateInstance<PortraitCatalog>();
try
{
catalog.entries.Add(new PortraitCatalog.Entry { personId = "kaplan", image = Texture2D.whiteTexture });
new CabinetPresenter(ui.Root, bridge, Text, catalog);
- var kaplan = ui.Q<Button>("seat-finance_minister").Q<VisualElement>(className: "seat-portrait");
+ var kaplan = ui.Q<Button>("seat-finance_minister").Q<VisualElement>(className: PersonCard.PortraitClass);
Assert.AreEqual(Texture2D.whiteTexture, kaplan.style.backgroundImage.value.texture);
Assert.AreEqual(DisplayStyle.Flex, kaplan.style.display.value);
- foreach (var seat in Cabinet.Lineup(C, bridge.State).Where(x => x.Holder != null && x.Holder.Id != "kaplan"))
- Assert.AreEqual(DisplayStyle.None, ui.Q<Button>("seat-" + seat.Office.Id).Q<VisualElement>(className: "seat-portrait").style.display.value, "no invented portrait for " + seat.Office.Id);
+ var pm = Cabinet.Holder(C, bridge.State, "prime_minister")!;
+ // Every card but Kaplan's; the PM's other offices are listed on the PM card, not given cards of their own.
+ foreach (var seat in Cabinet.Lineup(C, bridge.State).Where(x => x.Holder != null && x.Holder.Id != "kaplan" && (x.Holder.Id != pm.Id || x.Office.Id == "prime_minister")))
+ Assert.AreEqual(DisplayStyle.None, ui.Q<Button>("seat-" + seat.Office.Id).Q<VisualElement>(className: PersonCard.PortraitClass).style.display.value, "no invented portrait for " + seat.Office.Id);
}
finally { UnityEngine.Object.DestroyImmediate(catalog); }
}
@@ -76,17 +93,25 @@ public class CabinetScreenTests
[Test]
public void EveryCandidateIsListedAndOnlyCheckDecidesWhoCanBeAppointed()
{
- using var ui = new UiTestKit();
+ using var ui = Shown();
var bridge = In1950();
var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
foreach (var office in new[] { "finance_minister", "chief_of_staff", "president", "prime_minister" })
{
cabinet.Select(office);
- foreach (var (person, reason) in Cabinet.Candidates(C, bridge.State, office))
+ var list = Cabinet.Candidates(C, bridge.State, office);
+ // #215: a refusal shared by every candidate (the office itself) is said once under the heading.
+ var shared = list.All(x => x.reason != null && x.reason == list[0].reason) ? list[0].reason : null;
+ Assert.AreEqual(office == "prime_minister" || office == "president", shared != null, office + ": an office-level refusal");
+ Assert.AreEqual(shared ?? "", ui.Q<Label>("cabinet-pick-reason").text, office);
+ Assert.AreEqual(shared == null ? DisplayStyle.None : DisplayStyle.Flex, ui.Q<Label>("cabinet-pick-reason").style.display.value, office);
+ foreach (var (person, reason) in list)
{
Assert.AreEqual(Cabinet.Check(C, bridge.State, office, person.Id), reason, office + " " + person.Id); // Candidates is Check, row by row
Assert.AreEqual(reason == null, ui.Q<Button>("appoint-" + person.Id).enabledSelf, office + " " + person.Id);
- if (reason != null) Assert.AreEqual(reason, ui.Q<Label>("cand-" + person.Id + "-reason").text);
+ var row = ui.Q<Label>("cand-" + person.Id + "-reason");
+ if (shared != null) Assert.AreEqual(DisplayStyle.None, row.style.display.value, office + " " + person.Id + ": not repeated");
+ else if (reason != null) Assert.AreEqual(reason, row.text);
}
}
}
@@ -94,7 +119,7 @@ public class CabinetScreenTests
[Test]
public void ARefusalAtQueueTimeIsShown()
{
- using var ui = new UiTestKit();
+ using var ui = Shown();
var bridge = In1950();
new ToastPresenter(ui.Root, bridge, Text);
var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
@@ -109,7 +134,7 @@ public class CabinetScreenTests
[Test]
public void SelectingNothingClosesTheListAndADisposedScreenHearsNothing()
{
- using var ui = new UiTestKit();
+ using var ui = Shown();
var bridge = In1950();
var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
cabinet.Select("finance_minister");
@@ -132,7 +157,7 @@ public class CabinetScreenTests
[Test]
public void ANewGovernmentRefreshesTheScreenAndEndsTheAppointment()
{
- using var ui = new UiTestKit();
+ using var ui = Shown();
var bridge = In1950();
var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
cabinet.Select("finance_minister");
@@ -146,7 +171,7 @@ public class CabinetScreenTests
Assert.AreEqual(gov.Name, ui.Q<Label>("cabinet-government").text);
var holder = Cabinet.Holder(C, bridge.State, "finance_minister")!;
Assert.AreNotEqual("golda_meir", holder.Id);
- StringAssert.StartsWith("Minister of Finance: " + holder.Name, ui.Q<Label>("seat-finance_minister-holder").text);
+ Assert.AreEqual(holder.Name, ui.Q<Label>("seat-finance_minister-holder").text);
StringAssert.DoesNotContain("(your appointee)", ui.Q<Label>("seat-finance_minister-holder").text);
Assert.IsTrue(bridge.Session.Last!.Why.Any(w => w.System == "cabinet" && w.Target == "appointments"));
}
@@ -154,7 +179,7 @@ public class CabinetScreenTests
[Test]
public void ReplacingTheSessionRedrawsTheScreen()
{
- using var ui = new UiTestKit();
+ using var ui = Shown();
var bridge = In1950();
new CabinetPresenter(ui.Root, bridge, Text, null);
Assert.AreEqual("First Government", ui.Q<Label>("cabinet-government").text);
@@ -175,13 +200,15 @@ public class CabinetScreenTests
if (vacant == null) g.Step(HistoricalAI.Commands(C, g.State));
}
Assert.IsNotNull(vacant, "the historical game has a vacant seat to test with");
- using var ui = new UiTestKit();
+ using var ui = Shown();
var catalog = ScriptableObject.CreateInstance<PortraitCatalog>();
try
{
new CabinetPresenter(ui.Root, new SimBridge(g, Text), Text, catalog);
- Assert.AreEqual(vacant!.Office.Title + ": (vacant)", ui.Q<Label>("seat-" + vacant.Office.Id + "-holder").text);
- Assert.AreEqual(DisplayStyle.None, ui.Q<Button>("seat-" + vacant.Office.Id).Q<VisualElement>(className: "seat-portrait").style.display.value);
+ Assert.AreEqual("(vacant)", ui.Q<Label>("seat-" + vacant!.Office.Id + "-holder").text);
+ Assert.AreEqual(vacant.Office.Title, ui.Q<Label>("seat-" + vacant.Office.Id + "-office").text);
+ Assert.AreEqual(DisplayStyle.None, ui.Q<Button>("seat-" + vacant.Office.Id).Q<VisualElement>(className: PersonCard.PortraitClass).style.display.value);
+ Assert.AreEqual("", ui.Q<Label>("seat-" + vacant.Office.Id + "-initials").text, "a vacancy has no initials either");
}
finally { UnityEngine.Object.DestroyImmediate(catalog); }
}
@@ -189,7 +216,7 @@ public class CabinetScreenTests
[Test]
public void ASelectedOfficeThatDisappearsIsDeselected()
{
- using var ui = new UiTestKit();
+ using var ui = Shown();
var bridge = In1950();
var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
var ending = C.Offices.Where(o => o.Until.HasValue && o.Until > bridge.State.Date).OrderBy(o => o.Until).First();
@@ -204,7 +231,7 @@ public class CabinetScreenTests
[Test]
public void DisposeHidesThePickPanel()
{
- using var ui = new UiTestKit();
+ using var ui = Shown();
var bridge = In1950();
var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
cabinet.Select("finance_minister");
diff --git a/unity/Assets/Tests/EditMode/DefenceScreenTests.cs b/unity/Assets/Tests/EditMode/DefenceScreenTests.cs
index 8d137d928..031fe687d 100644
--- a/unity/Assets/Tests/EditMode/DefenceScreenTests.cs
+++ b/unity/Assets/Tests/EditMode/DefenceScreenTests.cs
@@ -14,6 +14,7 @@ public class DefenceScreenTests
static (UiTestKit ui, SimBridge bridge, DefencePresenter defence) Open()
{
var ui = new UiTestKit();
+ ui.Q<VisualElement>("screen-defence").style.display = DisplayStyle.Flex; // open, as ScreenNav opens it (a hidden screen does not re-render)
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);
new ToastPresenter(ui.Root, bridge, Text);
return (ui, bridge, new DefencePresenter(ui.Root, bridge, Text));
diff --git a/unity/Assets/Tests/EditMode/HudTests.cs b/unity/Assets/Tests/EditMode/HudTests.cs
index 9f73e63b3..8c2e2e476 100644
--- a/unity/Assets/Tests/EditMode/HudTests.cs
+++ b/unity/Assets/Tests/EditMode/HudTests.cs
@@ -368,6 +368,7 @@ public class HudTests
{
("MinimapPresenter.cs", "Length.Percent(", "the view frame's position and size in percent of the picture (layout, not text)"),
("PortraitFraming.cs", "offset / (h - boxH) * 100f", "a portrait's background-position-y in percent (layout, not text)"),
+ ("UiBar.cs", "Length.Percent(", "a bar's fill width and tick position in percent of its track (layout, not text)"),
("MapShaderGlobals.cs", "RiftHazeTopM = -100f", "a real elevation in metres for the rift haze (shader input, not a displayed number)"),
("SettlementKits.cs", "DefaultHouses = 100f", "the owner's symbolic scale for houses and trees (100x real size), not a displayed number"),
("RouteLayer.cs", "CorridorMarginM = 100f", "a clearance in map metres that kit buildings and trees keep from a route (geometry, not a displayed number)"),
diff --git a/unity/Assets/Tests/EditMode/PromoHudTests.cs b/unity/Assets/Tests/EditMode/PromoHudTests.cs
index f0b661472..5246e530a 100644
--- a/unity/Assets/Tests/EditMode/PromoHudTests.cs
+++ b/unity/Assets/Tests/EditMode/PromoHudTests.cs
@@ -500,8 +500,10 @@ public class PromoHudTests
finally { nav.Dispose(); }
}
- /// <summary>Integration bug B5: in the Cabinet the "Appoint to ..." heading has its own column, clear of the portrait
- /// grid and its scroll bar, and does not wrap a word to a line.</summary>
+ /// <summary>Integration bug B5, for the promo Cabinet (promo-screens): the "Appoint to ..." heading sits in the side
+ /// column under the Prime Minister's card, clear of the portrait grid and its scroll bar and of the candidate list's
+ /// scroll bar, inside the column; with the longest office title it breaks only between words (no word is wider than
+ /// the column) and takes at most two lines.</summary>
[UnityTest]
public IEnumerator TheAppointHeadingHasRoom()
{
@@ -513,13 +515,31 @@ public class PromoHudTests
try
{
nav.Open("cabinet");
- cabinet.Select("health_minister");
- for (int i = 0; i < 5; i++) yield return null;
- var title = ui.Q<Label>("cabinet-pick-title");
- StringAssert.StartsWith("Appoint to ", title.text);
- var seats = ui.Q<ScrollView>("cabinet-seats").worldBound;
- Assert.GreaterOrEqual(title.worldBound.xMin, seats.xMax, $"the heading {title.worldBound} starts inside the portrait grid {seats}");
- Assert.LessOrEqual(title.worldBound.height, title.resolvedStyle.fontSize * 2.2f, $"'{title.text}' wraps to more than one line ({title.worldBound.height:0} px)");
+ var longest = Cabinet.Lineup(C, bridge.State).Select(x => x.Office).OrderByDescending(o => o.Title.Length).First();
+ foreach (var office in new[] { "health_minister", longest.Id })
+ {
+ cabinet.Select(office);
+ for (int i = 0; i < 5; i++) yield return null;
+ var title = ui.Q<Label>("cabinet-pick-title");
+ StringAssert.StartsWith("Appoint to ", title.text);
+ var r = title.worldBound;
+ var side = ui.Q<VisualElement>("cabinet-side").worldBound;
+ var grid = ui.Q<ScrollView>("cabinet-seats");
+ Assert.IsFalse(r.Overlaps(grid.worldBound), $"{office}: the heading {r} overlaps the portrait grid {grid.worldBound}");
+ Assert.IsFalse(r.Overlaps(grid.verticalScroller.worldBound), $"{office}: the heading overlaps the grid's scroll bar");
+ var list = ui.Q<ScrollView>("cabinet-candidates");
+ if (list.verticalScroller.resolvedStyle.display == DisplayStyle.Flex)
+ Assert.IsFalse(r.Overlaps(list.verticalScroller.worldBound), $"{office}: the heading overlaps the candidates' scroll bar");
+ Assert.GreaterOrEqual(r.xMin, side.xMin - 0.5f, $"{office}: the heading leaves the side column");
+ Assert.LessOrEqual(r.xMax, side.xMax + 0.5f, $"{office}: the heading leaves the side column");
+ foreach (var word in title.text.Split(' '))
+ {
+ var w = title.MeasureTextSize(word, 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined).x;
+ Assert.LessOrEqual(w, title.contentRect.width + 0.5f, $"{office}: '{word}' ({w:0} px) is wider than the heading ({title.contentRect.width:0} px) and breaks");
+ }
+ var line = title.MeasureTextSize("A", 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined).y;
+ Assert.LessOrEqual(title.contentRect.height, line * 2f + 1f, $"{office}: '{title.text}' takes more than two lines ({title.contentRect.height:0} px, line {line:0} px)");
+ }
}
finally { cabinet.Dispose(); nav.Dispose(); }
}
diff --git a/unity/Assets/Tests/EditMode/PromoScreensTests.cs b/unity/Assets/Tests/EditMode/PromoScreensTests.cs
new file mode 100644
index 000000000..092b51f4c
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/PromoScreensTests.cs
@@ -0,0 +1,746 @@
+#nullable enable
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.TestTools;
+using UnityEngine.UIElements;
+using Object = UnityEngine.Object;
+
+/// <summary>The Cabinet and Defence screens laid out as promo/final/04 and 08: the half circle of seats, the Prime
+/// Minister's card, the person cards with competence and loyalty bars, the leadership, the ladder, the call-up bar and the
+/// defence budget share. Every figure on them is bound to the sim's data, none is invented, and both screens fit the window
+/// shapes the HUD supports, with the HUD's keyboard focus rules.</summary>
+public class PromoScreensTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+
+ /// <summary>The historical game stepped until <paramref name="date"/> (the opening when it is the start).</summary>
+ static GameSession At(DateTime date)
+ {
+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ for (int t = 0; g.State.Date < date; t++)
+ {
+ if (t >= 400 || g.State.GameOver != null) Assert.Fail($"the historical game did not reach {date:yyyy-MM-dd}");
+ g.Step(HistoricalAI.Commands(C, g.State));
+ }
+ return g;
+ }
+
+ /// <summary>One date in each legislature the content has: the Provisional State Council, the First and the Second Knesset.</summary>
+ static IEnumerable<DateTime> OneDatePerLegislature() => C.Legislatures.Select(l => l.From < C.Rules.Start ? C.Rules.Start : l.From.AddDays(30));
+
+ [Test]
+ public void TheHalfCircleSeatsTheRealLegislatureWithTheCoalitionFirst()
+ {
+ foreach (var date in OneDatePerLegislature())
+ {
+ var g = At(date);
+ using var ui = new UiTestKit();
+ var cabinet = new CabinetPresenter(ui.Root, new SimBridge(g, Text), Text, null);
+ var leg = Offices.Legislature(C, g.State.Date)!;
+ var gov = Offices.Government(C, g.State.Date)!;
+ var where = $"{g.State.Date:yyyy-MM-dd} {leg.Id}";
+ var house = ui.Q<Hemicycle>("cabinet-hemicycle");
+ Assert.AreEqual(leg.Size, house.Size, where);
+ Assert.AreEqual(leg.Size, Hemicycle.Layout(leg.Size).Count, where + ": one dot per seat");
+ Assert.AreEqual(leg.Size / 2 + 1, house.Majority, where);
+ foreach (var kv in leg.Seats.Where(kv => kv.Value > 0))
+ {
+ var block = house.Groups.Single(b => b.Party == kv.Key);
+ Assert.AreEqual(kv.Value, block.Seats, where + " " + kv.Key);
+ Assert.AreEqual(gov.Coalition.Contains(kv.Key), block.Coalition, where + " " + kv.Key);
+ }
+ Assert.AreEqual(leg.Seats.Count(kv => kv.Value > 0), house.Groups.Count, where + ": only parties with seats");
+ var (seats, size) = PoliticsSystem.CoalitionSeats(C, g.State.Date);
+ Assert.AreEqual(seats, house.Groups.Where(b => b.Coalition).Sum(b => b.Seats), where + ": the coalition's seats");
+ // Coalition first: the first <seats> dots from the left are coalition colours, the rest are not.
+ var coalitionColours = new HashSet<Color>(house.Groups.Where(b => b.Coalition).Select(b => b.Colour));
+ var dots = house.SeatColours();
+ for (int i = 0; i < dots.Count; i++)
+ Assert.AreEqual(i < seats, dots[i].HasValue && coalitionColours.Contains(dots[i]!.Value), $"{where}: seat {i}");
+ Assert.AreEqual(size, dots.Count);
+ Assert.AreEqual(leg.Size.ToString(), ui.Q<Label>("cabinet-house-size").text, where);
+ Assert.AreEqual($"Coalition: {seats} of {size} seats · stability {PlayerText.Percent(g.State.CoalitionStability)}", ui.Q<Label>("cabinet-coalition").text, where);
+ Assert.AreEqual($"Opposition: {leg.Seats.Where(kv => !gov.Coalition.Contains(kv.Key)).Sum(kv => kv.Value)} seats", ui.Q<Label>("cabinet-opposition").text, where);
+ Assert.AreEqual($"Majority: {size / 2 + 1} seats", ui.Q<Label>("cabinet-majority").text, where);
+ var top = leg.Seats.OrderByDescending(kv => kv.Value).First();
+ Assert.AreEqual($"Largest party: {C.Parties.First(p => p.Id == top.Key).Name}, {top.Value} seats", ui.Q<Label>("cabinet-largest").text, where);
+ Assert.AreEqual($"Answerable to the {leg.Body} · {leg.Size} members", ui.Q<Label>("cabinet-legislature").text, where);
+ Assert.AreEqual((float)g.State.CoalitionStability, ui.Q<UiBar>("cabinet-stability").Value, 1e-6f, where);
+ foreach (var kv in leg.Seats.Where(kv => kv.Value > 0))
+ Assert.AreEqual($"{C.Parties.First(p => p.Id == kv.Key).Name} {kv.Value}", ui.Q<Label>("party-" + kv.Key + "-label").text, where);
+ cabinet.Dispose();
+ }
+ }
+
+ /// <summary>Review I1: the majority line runs, row by row, between the last seat of a majority and the next, clear of
+ /// every dot, on the 37-seat Provisional State Council (promo 04) and the 120-seat Knesset; the layout keeps dots apart.</summary>
+ [Test]
+ public void TheMajorityLineSeparatesAMajorityFromTheRest()
+ {
+ foreach (var size in new[] { 37, 120, 1, 2, 7, 61 })
+ {
+ var seats = Hemicycle.Layout(size);
+ Assert.AreEqual(size, seats.Count, size + " seats");
+ for (int i = 1; i < seats.Count; i++)
+ Assert.GreaterOrEqual(Mathf.Atan2(seats[i - 1].y, seats[i - 1].x) + 1e-4f, Mathf.Atan2(seats[i].y, seats[i].x), $"{size}: left to right");
+ foreach (var p in seats) Assert.LessOrEqual(p.magnitude, 1.0001f, $"{size}: inside the unit half circle");
+ var r = Hemicycle.DotRadius(size);
+ for (int i = 0; i < seats.Count; i++)
+ for (int j = i + 1; j < seats.Count; j++)
+ Assert.Greater((seats[i] - seats[j]).magnitude, 2 * r, $"{size}: dots {i} and {j} overlap");
+ Assert.LessOrEqual(Hemicycle.RowCounts(size).Count(n => n % 2 == 1), 1, $"{size}: at most one seat at the top");
+ }
+ foreach (var size in new[] { 37, 120, 61, 7 })
+ {
+ var house = new Hemicycle();
+ house.Set(new[] { new Hemicycle.Group("a", size / 2 + 1, Color.blue, true), new Hemicycle.Group("b", size - size / 2 - 1, Color.gray, false) }, size);
+ var line = house.MajorityLine;
+ var places = Hemicycle.Places(size);
+ // The dot plus half the line's 2 px stroke, in unit radii at the shipped box (Statecraft.uss .hemicycle-box, 320 x 168).
+ var dot = Hemicycle.DotRadius(size) + Hemicycle.LineWidth / 2f / Hemicycle.ScaleFor(HemicycleBox - new Vector2(1.5f, 1.5f), size);
+ Assert.Greater(line.Count, 1, size + ": a line");
+ // No dot touches the line: every seat centre is more than a dot's radius from every segment.
+ for (int i = 0; i < size; i++)
+ for (int k = 1; k < line.Count; k++)
+ {
+ var d = SegmentDistance(places[i].Position, line[k - 1], line[k]);
+ Assert.Greater(d, dot, $"{size}: seat {i + 1} is {d:0.000} from the line (dot radius {dot:0.000})");
+ }
+ // In each row, the first Majority seats from the left lie left of the line's step in that row, the rest right.
+ var cuts = house.MajorityCuts;
+ for (int i = 0; i < size; i++)
+ Assert.AreEqual(i < house.Majority, places[i].Angle > cuts[places[i].Row], $"{size}: seat {i + 1} (row {places[i].Row}) is on the wrong side of the line");
+ }
+ var h = new Hemicycle();
+ Assert.Throws<ArgumentException>(() => h.Set(new[] { new Hemicycle.Group("a", 38, Color.blue, true) }, 37), "never more seats than the body has");
+ h.Set(new[] { new Hemicycle.Group("a", 30, Color.blue, true) }, 37);
+ Assert.AreEqual(7, h.SeatColours().Count(c => c == null), "unassigned seats stay unassigned, never given to a party");
+ var changes = h.Changes;
+ h.Set(new[] { new Hemicycle.Group("a", 30, Color.blue, true) }, 37);
+ Assert.AreEqual(changes, h.Changes, "the same house again is not redrawn (review I2)");
+ }
+
+ /// <summary>The half circle's box in logical pixels (Statecraft.uss .hemicycle-box); BothScreensFitEveryWindowShape checks it.</summary>
+ static readonly Vector2 HemicycleBox = new Vector2(320f, 168f);
+
+ static float SegmentDistance(Vector2 p, Vector2 a, Vector2 b)
+ {
+ var ab = b - a; var t = ab.sqrMagnitude == 0 ? 0 : Mathf.Clamp01(Vector2.Dot(p - a, ab) / ab.sqrMagnitude);
+ return (p - (a + t * ab)).magnitude;
+ }
+
+ /// <summary>Each card is its office holder's people.yaml record. The Prime Minister's card lists every office the PM
+ /// holds (Ben-Gurion was also Minister of Defense in 1948); those offices get no second card (review M5) but stay
+ /// selectable from a button under the PM card, so no real office is hidden.</summary>
+ [Test]
+ public void EveryCardShowsItsHoldersRealRecord()
+ {
+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ using var ui = new UiTestKit();
+ var cabinet = new CabinetPresenter(ui.Root, new SimBridge(g, Text), Text, null);
+ var lineup = Cabinet.Lineup(C, g.State);
+ var pm = Cabinet.Holder(C, g.State, "prime_minister")!;
+ foreach (var seat in lineup)
+ {
+ var id = "seat-" + seat.Office.Id;
+ Assert.IsNotNull(ui.Root.Q<Button>(id), id + ": every office can be selected");
+ if (seat.Office.Id != CabinetPresenter.PrimeMinister && seat.Holder?.Id == pm.Id)
+ {
+ Assert.AreEqual(seat.Office.Title, ui.Q<Button>(id).text, id + ": the PM's other office, under the PM card");
+ Assert.IsNull(ui.Q<ScrollView>("cabinet-seats").Q<Button>(id), id + ": no second card for the PM");
+ UiTestKit.Press(ui.Q<Button>(id));
+ Assert.AreEqual(seat.Office.Id, cabinet.Selected, id + ": selectable");
+ continue;
+ }
+ if (seat.Office.Id != CabinetPresenter.PrimeMinister)
+ Assert.AreEqual(seat.Office.Title, ui.Q<Label>(id + "-office").text, id);
+ if (seat.Holder == null)
+ {
+ Assert.AreEqual("(vacant)", ui.Q<Label>(id + "-holder").text, id);
+ Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>(id + "-competence-row").style.display.value, id + ": no bars for a vacancy");
+ continue;
+ }
+ var p = seat.Holder;
+ Assert.AreEqual(p.Name, ui.Q<Label>(id + "-holder").text, id);
+ var party = Offices.PartyOf(C, p, g.State.Date);
+ var partyName = party == "" ? "no party" : C.Parties.First(x => x.Id == party).Name;
+ StringAssert.EndsWith(partyName, ui.Q<Label>(id + "-party").text, id);
+ Assert.AreEqual(p.Competence / 10f, ui.Q<UiBar>(id + "-competence").Value, 1e-6f, id);
+ Assert.AreEqual(p.Loyalty / 10f, ui.Q<UiBar>(id + "-loyalty").Value, 1e-6f, id);
+ Assert.AreEqual(p.Competence.ToString(), ui.Q<Label>(id + "-competence-value").text, id);
+ Assert.AreEqual(p.Loyalty.ToString(), ui.Q<Label>(id + "-loyalty-value").text, id);
+ }
+ var held = lineup.Where(x => x.Holder?.Id == pm.Id).Select(x => x.Office.Title).ToList();
+ Assert.AreEqual(string.Join(" · ", held), ui.Q<Label>("seat-prime_minister-office").text);
+ CollectionAssert.Contains(held, "Minister of Defense", "Ben-Gurion held Defence too");
+ Assert.AreEqual("Party: Mapai", ui.Q<Label>("seat-prime_minister-party").text);
+ Assert.IsNull(ui.Q<ScrollView>("cabinet-seats").Q<Button>("seat-prime_minister"), "the PM is the side card, not a grid card");
+ cabinet.Dispose();
+ // Review M3: a disposed screen keeps no card, chip or seat.
+ Assert.AreEqual(0, ui.Q<ScrollView>("cabinet-seats").contentContainer.childCount);
+ Assert.AreEqual(0, ui.Q<VisualElement>("cabinet-parties").childCount);
+ Assert.AreEqual(0, ui.Q<Button>("seat-prime_minister").childCount);
+ Assert.AreEqual(0, ui.Q<Hemicycle>("cabinet-hemicycle").Size);
+ }
+
+ [Test]
+ public void APersonWithoutAPortraitGetsTheirInitialsNeverAnotherFace()
+ {
+ Assert.AreEqual("DB", PersonCard.Initials("David Ben-Gurion"));
+ Assert.AreEqual("HS", PersonCard.Initials("Haim-Moshe Shapira"));
+ Assert.AreEqual("M", PersonCard.Initials("Mordechai"));
+ Assert.AreEqual("", PersonCard.Initials(""));
+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ using var ui = new UiTestKit();
+ var catalog = ScriptableObject.CreateInstance<PortraitCatalog>();
+ try
+ {
+ catalog.entries.Add(new PortraitCatalog.Entry { personId = "kaplan", image = Texture2D.whiteTexture, focusY = 0.3f });
+ new CabinetPresenter(ui.Root, new SimBridge(g, Text), Text, catalog);
+ new DefencePresenter(ui.Root, new SimBridge(g, Text), Text, catalog);
+ foreach (var card in ui.Root.Query<VisualElement>(className: "card-plate").ToList())
+ {
+ var prefix = card.name.Substring(0, card.name.Length - "-plate".Length);
+ var portrait = ui.Q<VisualElement>(prefix + "-portrait");
+ var initials = ui.Q<Label>(prefix + "-initials");
+ var holder = ui.Q<Label>(prefix + "-holder").text;
+ bool kaplan = holder.StartsWith("Eliezer Kaplan");
+ Assert.AreEqual(kaplan ? DisplayStyle.Flex : DisplayStyle.None, portrait.style.display.value, prefix);
+ Assert.AreEqual(kaplan ? DisplayStyle.None : DisplayStyle.Flex, initials.style.display.value, prefix);
+ if (!kaplan) Assert.AreEqual(holder == "(vacant)" ? "" : PersonCard.Initials(holder), initials.text, prefix);
+ }
+ }
+ finally { Object.DestroyImmediate(catalog); }
+ }
+
+ [Test]
+ public void TheLeadershipIsTheRealCommandAndTheBarsAreTheSims()
+ {
+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ using var ui = new UiTestKit();
+ ui.Q<VisualElement>("screen-defence").style.display = DisplayStyle.Flex;
+ var bridge = new SimBridge(g, Text);
+ new ToastPresenter(ui.Root, bridge, Text);
+ var defence = new DefencePresenter(ui.Root, bridge, Text);
+ // One card per person (review M5): Ben-Gurion's card lists Prime Minister and Minister of Defense; the Chief of Staff has his own.
+ var shown = new List<string>();
+ foreach (var office in DefencePresenter.Leaders)
+ {
+ var holder = Cabinet.Holder(C, g.State, office)!;
+ var card = ui.Q<VisualElement>("lead-" + office);
+ var first = DefencePresenter.Leaders.First(o => Cabinet.Holder(C, g.State, o)?.Id == holder.Id);
+ if (first != office)
+ {
+ Assert.AreEqual(DisplayStyle.None, card.style.display.value, office + ": merged into " + first);
+ StringAssert.Contains(C.Offices.First(o => o.Id == office).Title, ui.Q<Label>("lead-" + first + "-office").text, office);
+ continue;
+ }
+ shown.Add(office);
+ Assert.AreEqual(holder.Name, ui.Q<Label>("lead-" + office + "-holder").text, office);
+ StringAssert.StartsWith(C.Offices.First(o => o.Id == office).Title, ui.Q<Label>("lead-" + office + "-office").text, office);
+ Assert.AreEqual(holder.Competence / 10f, ui.Q<UiBar>("lead-" + office + "-competence").Value, 1e-6f, office);
+ Assert.AreEqual(holder.Loyalty / 10f, ui.Q<UiBar>("lead-" + office + "-loyalty").Value, 1e-6f, office);
+ }
+ CollectionAssert.AreEqual(new[] { "prime_minister", "chief_of_staff" }, shown, "1948: Ben-Gurion once, Dori once");
+ Assert.AreEqual("Prime Minister\nMinister of Defense", ui.Q<Label>("lead-prime_minister-office").text);
+ var bar = ui.Q<UiBar>("mob-bar");
+ Assert.AreEqual((float)g.State.Mobilization, bar.Value, 1e-6f);
+ Assert.AreEqual((float)SecuritySystem.MinMobilization(C, g.State.Rung), bar.Mark!.Value, 1e-6f, "the level's minimum is marked");
+ Assert.AreEqual(PlayerText.Percent(g.State.Mobilization), ui.Q<Label>("mob-percent").text);
+ Assert.AreEqual((float)g.State.Budget[DefencePresenter.BudgetLine], ui.Q<UiBar>("defence-budget-bar").Value, 1e-6f);
+ Assert.AreEqual($"{PlayerText.Percent(g.State.Budget[DefencePresenter.BudgetLine])} of budget spending", ui.Q<Label>("defence-budget-share").text);
+ Assert.AreEqual("LEADERSHIP", ui.Q<Label>("defence-title-leadership").text, "the caption from strings, in capitals");
+ // An order to lower the level: the target rung is marked, and the bar's minimum follows it.
+ ui.Press("de-escalate");
+ Assert.IsTrue(ui.Q<VisualElement>("rung-4").ClassListContains("rung-target"));
+ Assert.IsTrue(ui.Q<VisualElement>("rung-5").ClassListContains("rung-current"));
+ Assert.IsFalse(ui.Q<VisualElement>("rung-5").ClassListContains("rung-target"));
+ Assert.AreEqual((float)SecuritySystem.MinMobilization(C, 4), bar.Mark!.Value, 1e-6f);
+ ui.Press("mob-down");
+ Assert.AreEqual((float)defence.ProposedMobilization, bar.Value, 1e-6f, "the bar shows the ordered call-up");
+ ui.Press("escalate");
+ Assert.IsFalse(ui.Root.Query<VisualElement>(className: "rung-target").ToList().Any(), "no order, no target");
+ // Review M4: a queued budget moves the share as a queued call-up moves the call-up.
+ var shares = new Dictionary<string, double>(g.State.Budget);
+ var other = shares.Keys.First(k => k != DefencePresenter.BudgetLine);
+ shares[DefencePresenter.BudgetLine] -= 0.05; shares[other] += 0.05;
+ Assert.IsNull(bridge.Queue(new AllocateBudget(shares)));
+ Assert.AreEqual((float)shares[DefencePresenter.BudgetLine], ui.Q<UiBar>("defence-budget-bar").Value, 1e-6f);
+ Assert.AreEqual($"{PlayerText.Percent(shares[DefencePresenter.BudgetLine])} of budget spending", ui.Q<Label>("defence-budget-share").text);
+ defence.Dispose();
+ foreach (var office in DefencePresenter.Leaders) Assert.AreEqual(0, ui.Q<VisualElement>("lead-" + office).childCount, office + ": emptied on Dispose");
+ Assert.IsNull(bar.Mark);
+ }
+
+ /// <summary>Review I5: each figure on either screen is bound to its own source. Every text with a digit in it, and every
+ /// bar, must be one this test names, with its exact expected value from the sim: a new number or bar fails until it is
+ /// bound on purpose, so no promo figure (readiness, strength) can slip in.</summary>
+ [Test]
+ public void NoFigureOnEitherScreenIsInvented()
+ {
+ foreach (var date in OneDatePerLegislature())
+ {
+ var g = At(date);
+ var s = g.State;
+ using var ui = new UiTestKit();
+ var bridge = new SimBridge(g, Text);
+ var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
+ var defence = new DefencePresenter(ui.Root, bridge, Text);
+ var where = s.Date.ToString("yyyy-MM-dd");
+ var texts = new Dictionary<string, string>();
+ var bars = new Dictionary<string, float>();
+ var leg = Offices.Legislature(C, s.Date)!;
+ var gov = Offices.Government(C, s.Date);
+ var (seats, size) = PoliticsSystem.CoalitionSeats(C, s.Date);
+ var blocks = CabinetPresenter.Blocks(C, leg, gov);
+ texts["cabinet-coalition"] = $"Coalition: {seats} of {size} seats · stability {PlayerText.Percent(s.CoalitionStability)}";
+ texts["cabinet-opposition"] = $"Opposition: {leg.Seats.Where(kv => gov == null || !gov.Coalition.Contains(kv.Key)).Sum(kv => kv.Value)} seats";
+ texts["cabinet-majority"] = $"Majority: {leg.Size / 2 + 1} seats";
+ var top = leg.Seats.OrderByDescending(kv => kv.Value).First();
+ texts["cabinet-largest"] = $"Largest party: {C.Parties.First(p => p.Id == top.Key).Name}, {top.Value} seats";
+ texts["cabinet-legislature"] = $"Answerable to the {leg.Body} · {leg.Size} members";
+ texts["cabinet-house-size"] = leg.Size.ToString();
+ foreach (var b in blocks) texts["party-" + b.Party + "-label"] = $"{C.Parties.First(p => p.Id == b.Party).Name} {leg.Seats[b.Party]}";
+ bars["cabinet-stability"] = (float)s.CoalitionStability;
+ void Person(string prefix, Person? p)
+ {
+ if (p == null) return;
+ texts[prefix + "-competence-value"] = p.Competence.ToString(); texts[prefix + "-loyalty-value"] = p.Loyalty.ToString();
+ bars[prefix + "-competence"] = p.Competence / 10f; bars[prefix + "-loyalty"] = p.Loyalty / 10f;
+ }
+ foreach (var seat in Cabinet.Lineup(C, s)) Person("seat-" + seat.Office.Id, seat.Holder);
+ foreach (var office in DefencePresenter.Leaders) Person("lead-" + office, Cabinet.Holder(C, s, office));
+ for (int rung = 1; rung <= 5; rung++) texts[$"rung-{rung}-name"] = Text[$"defence.rung{rung}"];
+ var floor = SecuritySystem.MinMobilization(C, s.Rung);
+ var callUp = SecuritySystem.EffectiveMobilization(C, s.Rung, s.Mobilization);
+ texts["mob-percent"] = PlayerText.Percent(callUp);
+ texts["mob-level"] = $"{PlayerText.Percent(callUp)} of reserves called up (level {s.Rung} needs at least {PlayerText.Percent(floor)})";
+ texts["mob-cost"] = $"Costs {PlayerText.Money(C, "treasury", EconomySystem.MobilizationCost(C, callUp))} a year in pay and lost work";
+ texts["mob-down"] = "-5%"; texts["mob-up"] = "+5%"; // the step, DefencePresenter.MobilizationStep
+ Assert.AreEqual(0.05, DefencePresenter.MobilizationStep, 1e-12);
+ texts["ceasefire"] = s.Rung == 5 ? Text.Format("defence.ceasefire", s.CeasefireWeeksLeft) : "";
+ texts["defence-budget-share"] = $"{PlayerText.Percent(s.Budget[DefencePresenter.BudgetLine])} of budget spending";
+ bars["mob-bar"] = (float)callUp; bars["defence-budget-bar"] = (float)s.Budget[DefencePresenter.BudgetLine];
+ foreach (var name in new[] { "screen-cabinet", "screen-defence" })
+ {
+ foreach (var t in ui.Q<VisualElement>(name).Query<TextElement>().ToList().Where(t => t.text.Any(char.IsDigit)))
+ {
+ Assert.IsTrue(texts.ContainsKey(t.name), $"{where}: '{t.text}' in {t.name} is a figure no test binds to the sim");
+ Assert.AreEqual(texts[t.name], t.text, $"{where}: {t.name}");
+ }
+ foreach (var bar in ui.Q<VisualElement>(name).Query<UiBar>().ToList().Where(b => b.resolvedStyle.display != DisplayStyle.None && b.parent.style.display != DisplayStyle.None))
+ {
+ Assert.IsTrue(bars.ContainsKey(bar.name), $"{where}: bar {bar.name} = {bar.Value} is bound to nothing");
+ Assert.AreEqual(bars[bar.name], bar.Value, 1e-6f, $"{where}: bar {bar.name}");
+ }
+ }
+ // No promo figure the sim lacks.
+ var words = string.Join("\n", ui.Q<VisualElement>("screen-defence").Query<TextElement>().ToList().Select(l => l.text));
+ foreach (var missing in new[] { "Readiness", "Strength", "Intelligence", "Procurement", "Stance", "Air Force", "Navy" })
+ StringAssert.DoesNotContain(missing, words, "the sim has no " + missing);
+ cabinet.Dispose(); defence.Dispose();
+ }
+ }
+
+ static float Lum(Color c, Color under)
+ {
+ float Ch(float v, float u) { var x = v * c.a + u * (1 - c.a); return x <= 0.04045f ? x / 12.92f : Mathf.Pow((x + 0.055f) / 1.055f, 2.4f); }
+ return 0.2126f * Ch(c.r, under.r) + 0.7152f * Ch(c.g, under.g) + 0.0722f * Ch(c.b, under.b);
+ }
+
+ static float Contrast(Color a, Color b, Color under) { float x = Lum(a, under), y = Lum(b, under); return (Mathf.Max(x, y) + 0.05f) / (Mathf.Min(x, y) + 0.05f); }
+
+ static readonly Color ScreenNavy = new Color32(11, 18, 32, 255), Deep = new Color32(9, 14, 26, 255);
+
+ /// <summary>Non-text contrast (WCAG 1.4.11): every bar's fill is at least 3:1 against its track, and every party colour
+ /// at least 3:1 against the screen behind the half circle.</summary>
+ [UnityTest]
+ public IEnumerator BarsAndPartyColoursMeetThreeToOne()
+ {
+ using var ui = new UiTestKit();
+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ var bridge = new SimBridge(g, Text);
+ var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
+ var defence = new DefencePresenter(ui.Root, bridge, Text);
+ ui.Q<VisualElement>("root").RemoveFromClassList("loading");
+ new ScreenNav(ui.Root).Open("cabinet");
+ ui.Q<VisualElement>("screen-defence").style.display = DisplayStyle.Flex;
+ for (int i = 0; i < 4; i++) yield return null;
+ try
+ {
+ var seen = new HashSet<string>();
+ foreach (var bar in ui.Root.Query<UiBar>().ToList())
+ {
+ var modifier = bar.GetClasses().FirstOrDefault(c => c.StartsWith("ui-bar--"));
+ Assert.IsNotNull(modifier, bar.name + ": a colour modifier");
+ seen.Add(modifier!);
+ var ratio = Contrast(bar.Fill.resolvedStyle.backgroundColor, bar.resolvedStyle.backgroundColor, ScreenNavy);
+ Assert.GreaterOrEqual(ratio, 3f, $"{bar.name} ({modifier}): fill on track {ratio:0.00}:1");
+ }
+ CollectionAssert.IsSupersetOf(seen, new[] { "ui-bar--competence", "ui-bar--loyalty", "ui-bar--stability", "ui-bar--mobilization", "ui-bar--budget" });
+ foreach (var colour in new[] { CabinetPresenter.CoalitionColour, CabinetPresenter.OppositionColour })
+ Assert.GreaterOrEqual(Contrast(colour, ScreenNavy, ScreenNavy), 3f, $"seat colour {colour}");
+ // Review M2: two flat colours, coalition and opposition; a colour never stands for one party.
+ Assert.AreNotEqual(CabinetPresenter.CoalitionColour, CabinetPresenter.OppositionColour);
+ var house = ui.Q<Hemicycle>("cabinet-hemicycle");
+ CollectionAssert.AreEquivalent(new[] { CabinetPresenter.CoalitionColour, CabinetPresenter.OppositionColour }, house.Groups.Select(b => b.Colour).Distinct());
+ foreach (var b in house.Groups) Assert.AreEqual(b.Coalition ? CabinetPresenter.CoalitionColour : CabinetPresenter.OppositionColour, b.Colour, b.Party);
+ }
+ finally { cabinet.Dispose(); defence.Dispose(); }
+ }
+
+ /// <summary>The HUD's focus rules on the cards (reviews I3, N1): keyboard focus changes a card by at least 3:1 and keeps
+ /// its text at least 4.5:1, and a pointer click leaves no card lit.</summary>
+ [UnityTest]
+ public IEnumerator ACardsFocusIsVisibleAndAClickLeavesItUnlit()
+ {
+ using var ui = new UiTestKit();
+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ var cabinet = new CabinetPresenter(ui.Root, new SimBridge(g, Text), Text, null);
+ var blur = new PointerBlur(ui.Root);
+ ui.Q<VisualElement>("root").RemoveFromClassList("loading");
+ new ScreenNav(ui.Root).Open("cabinet");
+ try
+ {
+ for (int i = 0; i < 4; i++) yield return null;
+ foreach (var name in new[] { "seat-finance_minister", "seat-prime_minister" })
+ {
+ var card = ui.Q<Button>(name);
+ var before = card.resolvedStyle.backgroundColor;
+ card.Focus();
+ for (int i = 0; i < 10 && card.focusController.focusedElement != card; i++) yield return null;
+ yield return null; yield return null;
+ Assert.AreSame(card, card.focusController.focusedElement, name + ": focused");
+ var fill = card.resolvedStyle.backgroundColor;
+ Assert.GreaterOrEqual(Contrast(before, fill, Deep), 3f, name + ": focus changes the card by 3:1");
+ foreach (var label in card.Query<Label>().ToList().Where(l => !string.IsNullOrEmpty(l.text) && l.resolvedStyle.display == DisplayStyle.Flex && l.GetFirstAncestorOfType<VisualElement>()?.ClassListContains("card-plate") != true))
+ Assert.GreaterOrEqual(Contrast(label.resolvedStyle.color, fill, Deep), 4.5f, $"{name}: '{label.text}' on the focus fill");
+ using (var e = ClickEvent.GetPooled()) { e.target = card; card.SendEvent(e); }
+ yield return null; yield return null;
+ Assert.AreNotSame(card, card.focusController.focusedElement, name + ": a click leaves no focus");
+ }
+ }
+ finally { cabinet.Dispose(); blur.Dispose(); }
+ }
+
+ /// <summary>Both screens at the window shapes the HUD supports (16:9 at 1920x1080 and 1366x768, 16:10, 4:3, 5:4, the
+ /// wide-and-short browser, square and narrower): each opens under the top bar, clear of the event column and the
+ /// minimap (over the info panel, which it is drawn above), and nothing on it leaves it or its panel sideways; every
+ /// one-line text fits its box.</summary>
+ [UnityTest]
+ public IEnumerator BothScreensFitEveryWindowShape()
+ {
+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ var problems = new List<string>();
+ foreach (var (w, h) in new[] { (1920, 1080), (1366, 768), (1280, 720), (1440, 900), (1920, 1200), (1024, 768), (1280, 1024), (1531, 784), (1024, 1024), (960, 1080), (800, 1000), (960, 600), (390, 844) })
+ {
+ var rt = new RenderTexture(w, h, 0);
+ var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));
+ ps.targetTexture = rt;
+ var go = new GameObject("ScreensTest");
+ go.SetActive(false);
+ var doc = go.AddComponent<UIDocument>();
+ doc.panelSettings = ps;
+ doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
+ go.SetActive(true);
+ var root = doc.rootVisualElement;
+ var owned = new List<IDisposable>();
+ try
+ {
+ for (int i = 0; i < 20 && !(root.Q("top-bar").worldBound.width > 0); i++) yield return null;
+ root.Q("root").RemoveFromClassList("loading");
+ var bridge = new SimBridge(g, Text);
+ owned.Add(new HudPresenter(root, bridge, Text));
+ owned.Add(new CabinetPresenter(root, bridge, Text, null));
+ owned.Add(new DefencePresenter(root, bridge, Text));
+ var nav = new ScreenNav(root); owned.Add(nav);
+ foreach (var s in new[] { "cabinet", "defence" })
+ {
+ nav.Open(s);
+ for (int i = 0; i < 6; i++) yield return null;
+ var where = $"{w}x{h} {s}";
+ var screen = root.Q("screen-" + s); var sr = screen.worldBound;
+ if (!(sr.width > 300)) { problems.Add($"{where}: the screen is {sr}"); continue; }
+ if (sr.yMin < root.Q("top-bar").worldBound.yMax - 0.5f) problems.Add($"{where}: starts over the top bar");
+ // Clear of the event column, or (two-row HUD, #210) full width with the column hidden.
+ var column = root.Q("right-column");
+ if (column.resolvedStyle.display != DisplayStyle.None && sr.Overlaps(column.worldBound)) problems.Add($"{where}: overlaps the event column {column.worldBound}");
+ var parent = root.Q("root");
+ if (parent.IndexOf(screen) < parent.IndexOf(root.Q("info-panel"))) problems.Add($"{where}: drawn under the info panel");
+ // Everything shown stays inside the screen sideways, and inside its panel (a card, a Defence panel, the house).
+ foreach (var e in screen.Query<VisualElement>().ToList().Where(e => e != screen && e.resolvedStyle.display == DisplayStyle.Flex && e.worldBound.width > 0
+ && !(e is UiFrame) && e.GetFirstAncestorOfType<Scroller>() == null && !(e is Scroller)))
+ {
+ var r = e.worldBound;
+ var clip = e.GetFirstAncestorOfType<ScrollView>();
+ if (clip != null && (r.yMax < clip.contentViewport.worldBound.yMin || r.yMin > clip.contentViewport.worldBound.yMax)) continue; // scrolled out of view
+ if (r.xMin < sr.xMin - 0.5f || r.xMax > sr.xMax + 0.5f) problems.Add($"{where}: {e.name}/{e.GetClasses().FirstOrDefault()} {r} leaves the screen {sr}");
+ var panel = e.parent == null ? null : Ancestor(e);
+ if (panel != null && (r.xMin < panel.worldBound.xMin - 0.5f || r.xMax > panel.worldBound.xMax + 0.5f))
+ problems.Add($"{where}: {e.name}/{e.GetClasses().FirstOrDefault()} {r} leaves {panel.name}/{panel.GetClasses().FirstOrDefault()} {panel.worldBound}");
+ if (e is Label l && !string.IsNullOrEmpty(l.text) && l.resolvedStyle.whiteSpace == WhiteSpace.NoWrap)
+ {
+ var natural = l.MeasureTextSize(l.text, 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined);
+ if (natural.x > l.contentRect.width + 1f) problems.Add($"{where}: '{l.text}' ({natural.x:0} px) is cut to {l.contentRect.width:0} px");
+ }
+ }
+ if (s == "cabinet")
+ {
+ var hemi = root.Q("cabinet-hemicycle");
+ if (hemi.layout.width < HemicycleBox.x - 1.5f || hemi.layout.height < HemicycleBox.y - 1.5f) // pixel snapping at a fractional scale moves it by under 1.5 px
+ problems.Add($"{where}: the half circle is {hemi.layout.size}, not the {HemicycleBox} the line test assumes");
+ var cards = root.Q<ScrollView>("cabinet-seats").Query<Button>(className: "seat").ToList();
+ if (cards.Count < 5) problems.Add($"{where}: {cards.Count} cards");
+ if (!(cards[0].worldBound.yMin < root.Q<ScrollView>("cabinet-seats").contentViewport.worldBound.yMax - 100)) problems.Add($"{where}: no card row in view");
+ }
+ }
+ }
+ finally
+ {
+ for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
+ Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
+ }
+ }
+ Assert.IsEmpty(problems, string.Join("\n", problems.Take(40)));
+ }
+
+ /// <summary>Review I2: a hidden screen does no work on a change (an order, End Turn) and catches up when it is opened;
+ /// an open screen updates its cards in place, so they are the same elements and a focused card or Appoint button keeps
+ /// its focus; an unchanged house is not redrawn.</summary>
+ [UnityTest]
+ public IEnumerator AHiddenScreenDoesNoWorkAndAnOpenOneKeepsFocus()
+ {
+ using var ui = new UiTestKit();
+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);
+ var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
+ var defence = new DefencePresenter(ui.Root, bridge, Text);
+ var nav = new ScreenNav(ui.Root);
+ ui.Q<VisualElement>("root").RemoveFromClassList("loading");
+ try
+ {
+ int cab = cabinet.Renders, def = defence.Renders;
+ bridge.Queue(new SetMobilization(0.9));
+ bridge.EndTurn();
+ Assert.AreEqual(cab, cabinet.Renders, "hidden Cabinet: no render on an order or End Turn");
+ Assert.AreEqual(def, defence.Renders, "hidden Defence: no render");
+ nav.Open("defence");
+ Assert.AreEqual(def + 1, defence.Renders, "opening catches up, once");
+ Assert.AreEqual(PlayerText.Percent(bridge.State.Mobilization), ui.Q<Label>("mob-percent").text, "with today's figures");
+ nav.Open("cabinet");
+ Assert.AreEqual(cab + 1, cabinet.Renders);
+ nav.Open("defence"); nav.Open("cabinet");
+ Assert.AreEqual(cab + 1, cabinet.Renders, "nothing changed: no second render on reopening");
+
+ yield return null; yield return null;
+ var house = ui.Q<Hemicycle>("cabinet-hemicycle");
+ var card = ui.Q<Button>("seat-finance_minister");
+ card.Focus();
+ for (int i = 0; i < 10 && card.focusController.focusedElement != card; i++) yield return null;
+ var changes = house.Changes;
+ Assert.IsNull(bridge.Queue(new SetMobilization(0.85))); // a change while Cabinet is open
+ Assert.AreSame(card, ui.Q<Button>("seat-finance_minister"), "the card is updated in place");
+ Assert.AreSame(card, card.focusController.focusedElement, "and keeps the keyboard focus");
+ Assert.AreEqual(changes, house.Changes, "an unchanged house is not redrawn");
+ bridge.Withdraw(bridge.QueuedLike(new SetMobilization(0))!); // frees the attention for the appointment
+ Assert.AreSame(card, card.focusController.focusedElement, "a withdrawal keeps the focus too");
+ cabinet.Select("finance_minister");
+ var appoint = ui.Q<ScrollView>("cabinet-candidates").Query<Button>().ToList().First(b => b.enabledSelf);
+ appoint.Focus();
+ for (int i = 0; i < 10 && appoint.focusController.focusedElement != appoint; i++) yield return null;
+ UiTestKit.Press(appoint); // Enter on Appoint queues the order
+ Assert.AreEqual(1, bridge.Queued.OfType<Appoint>().Count());
+ Assert.AreSame(appoint, ui.Q<Button>(appoint.name), "the candidate row is updated in place");
+ Assert.AreSame(appoint, appoint.focusController.focusedElement, "Appoint keeps the focus");
+ }
+ finally { nav.Dispose(); cabinet.Dispose(); defence.Dispose(); }
+ }
+
+ /// <summary>The review's idle probe as a test: with Cabinet or Defence open (and with neither), 180 idle frames cause no
+ /// recurring relayout or repaint anywhere on either screen (at most one late settle, in the first 60).</summary>
+ [UnityTest]
+ public IEnumerator AnOpenScreenIsStillWhenIdle()
+ {
+ foreach (var open in new string?[] { null, "cabinet", "defence" })
+ {
+ var rt = new RenderTexture(1920, 1080, 0);
+ var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));
+ ps.targetTexture = rt;
+ var go = new GameObject("ScreensIdle");
+ go.SetActive(false);
+ var doc = go.AddComponent<UIDocument>();
+ doc.panelSettings = ps;
+ doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
+ go.SetActive(true);
+ var root = doc.rootVisualElement;
+ var owned = new List<IDisposable>();
+ try
+ {
+ for (int i = 0; i < 20 && !(root.Q("top-bar").worldBound.width > 0); i++) yield return null;
+ root.Q("root").RemoveFromClassList("loading");
+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);
+ owned.Add(new CabinetPresenter(root, bridge, Text, null));
+ owned.Add(new DefencePresenter(root, bridge, Text));
+ var nav = new ScreenNav(root); owned.Add(nav);
+ nav.Open(open);
+ for (int i = 0; i < 30; i++) yield return null; // settle
+ // Frames with any relayout or repaint. One late settle (a font atlas growing when an earlier test drew new
+ // glyphs re-measures every label once) is allowed; anything recurring, or still happening in the last 120
+ // frames, is a per-frame cost and fails.
+ int frame = 0; var busy = new SortedDictionary<int, List<string>>();
+ void Note(string what) { if (!busy.TryGetValue(frame, out var l)) busy[frame] = l = new List<string>(); l.Add(what); }
+ foreach (var e in new[] { root.Q("screen-cabinet"), root.Q("screen-defence") }.SelectMany(s => s.Query<VisualElement>().ToList()))
+ {
+ var name = e.name;
+ e.RegisterCallback<GeometryChangedEvent>(_ => Note("layout " + name));
+ e.generateVisualContent += _ => Note("paint " + name);
+ }
+ for (frame = 0; frame < 180; frame++) yield return null;
+ string Report() => string.Join("; ", busy.Select(kv => $"frame {kv.Key}: {kv.Value.Count} ({string.Join(", ", kv.Value.Distinct().Take(6))})"));
+ Assert.LessOrEqual(busy.Count, 1, $"open={open ?? "none"}: work in more than one idle frame: {Report()}");
+ Assert.IsFalse(busy.Keys.Any(f => f >= 60), $"open={open ?? "none"}: still working after 60 idle frames: {Report()}");
+ }
+ finally
+ {
+ for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
+ Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
+ }
+ }
+ }
+
+ /// <summary>Escape (the UI Cancel event) closes the open screen, from a focused card or from the panel; with nothing open
+ /// it is left alone. GameRoot also calls Close on the Escape key when nothing has the focus.</summary>
+ [UnityTest]
+ public IEnumerator EscapeClosesTheOpenScreen()
+ {
+ using var ui = new UiTestKit();
+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);
+ var cabinet = new CabinetPresenter(ui.Root, bridge, Text, null);
+ var nav = new ScreenNav(ui.Root);
+ var guard = new NavigationGuard(ui.Root);
+ ui.Q<VisualElement>("root").RemoveFromClassList("loading");
+ try
+ {
+ nav.Open("cabinet");
+ yield return null; yield return null;
+ var card = ui.Q<Button>("seat-finance_minister");
+ card.Focus();
+ for (int i = 0; i < 10 && card.focusController.focusedElement != card; i++) yield return null;
+ using (var e = NavigationCancelEvent.GetPooled()) { e.target = card; card.SendEvent(e); }
+ Assert.IsNull(nav.Current, "Escape on a focused card closes the Cabinet");
+ Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>("screen-cabinet").style.display.value);
+ Assert.IsFalse(ui.Q<Button>("nav-cabinet").ClassListContains(ScreenNav.OpenClass), "its button is unlit");
+ Assert.IsFalse(ui.Q<VisualElement>("root").ClassListContains(ScreenNav.WideOpenClass), "the info panel comes back");
+ nav.Open("defence");
+ using (var e = NavigationCancelEvent.GetPooled()) { e.target = ui.Root; ui.Root.SendEvent(e); }
+ Assert.IsNull(nav.Current, "Escape with nothing focused closes Defence");
+ nav.Open("budget");
+ Assert.IsTrue(nav.Close(), "Close (GameRoot's Escape key) closes Budget");
+ Assert.IsFalse(nav.Close(), "and is a no-op with nothing open");
+ // The camera's arrow keys still never move UI focus (NavigationGuard), with a screen open.
+ nav.Open("cabinet");
+ card = ui.Q<Button>("seat-finance_minister");
+ card.Focus();
+ for (int i = 0; i < 10 && card.focusController.focusedElement != card; i++) yield return null;
+ using (var e = NavigationMoveEvent.GetPooled(NavigationMoveEvent.Direction.Right)) { e.target = card; card.SendEvent(e); }
+ yield return null;
+ Assert.AreSame(card, card.focusController.focusedElement, "an arrow key does not move the focus");
+ Assert.AreEqual("cabinet", nav.Current, "and does not close the screen");
+ }
+ finally { guard.Dispose(); nav.Dispose(); cabinet.Dispose(); }
+ }
+
+ /// <summary>#210: at a phone-shaped 390x844 and at 960x600 every screen is usable: at least 500 logical px wide and
+ /// 300 tall, under the top bar. In the two-row HUD (390x844) a screen takes the full width, the event column and the
+ /// info panel under it are hidden and ignore map clicks, and the toast sits below the screen.</summary>
+ [UnityTest]
+ public IEnumerator EveryScreenIsUsableInANarrowWindow()
+ {
+ var problems = new List<string>();
+ foreach (var (w, h) in new[] { (390, 844), (960, 600) })
+ {
+ var rt = new RenderTexture(w, h, 0);
+ var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));
+ ps.targetTexture = rt;
+ var go = new GameObject("NarrowTest");
+ go.SetActive(false);
+ var doc = go.AddComponent<UIDocument>();
+ doc.panelSettings = ps;
+ doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
+ go.SetActive(true);
+ var root = doc.rootVisualElement;
+ var owned = new List<IDisposable>();
+ try
+ {
+ for (int i = 0; i < 20 && !(root.Q("top-bar").worldBound.width > 0); i++) yield return null;
+ root.Q("root").RemoveFromClassList("loading");
+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);
+ owned.Add(new HudPresenter(root, bridge, Text));
+ owned.Add(new CabinetPresenter(root, bridge, Text, null));
+ owned.Add(new DefencePresenter(root, bridge, Text));
+ owned.Add(new BudgetPresenter(root, bridge, Text));
+ owned.Add(new WhyPresenter(root, bridge, Text));
+ var info = new InfoPanelPresenter(root, bridge, Text, C.SettlementHexes.ToDictionary(x => x.Id, x => x.Id)); owned.Add(info);
+ var nav = new ScreenNav(root); owned.Add(nav);
+ var toast = root.Q<Label>("toast");
+ toast.text = "Not done: Not enough attention (need 4.0, have 2.0)";
+ toast.style.display = DisplayStyle.Flex;
+ for (int i = 0; i < 6; i++) yield return null;
+ bool twoRow = root.Q("root").ClassListContains(HudPresenter.TwoRowClass);
+ if ((w, h) == (390, 844) && !twoRow) problems.Add("390x844 is not the two-row HUD");
+ var bar = root.Q("top-bar").worldBound;
+ foreach (var s in ScreenNav.Screens)
+ {
+ nav.Open(s);
+ for (int i = 0; i < 4; i++) yield return null;
+ var where = $"{w}x{h} {s}";
+ var r = root.Q("screen-" + s).worldBound;
+ if (!(r.width >= 500f && r.height >= 300f)) problems.Add($"{where}: the screen is only {r.width:0} x {r.height:0}");
+ if (r.yMin < bar.yMax - 0.5f) problems.Add($"{where}: starts over the top bar");
+ var t = toast.worldBound;
+ if (t.Overlaps(r)) problems.Add($"{where}: the toast {t} covers the screen {r}");
+ if (twoRow)
+ {
+ var panel = root.panel.visualTree.worldBound;
+ if (r.width < panel.width - 40f) problems.Add($"{where}: not full width ({r.width:0} of {panel.width:0})");
+ foreach (var hidden in new[] { "right-column", "info-panel" })
+ if (root.Q(hidden).resolvedStyle.display != DisplayStyle.None) problems.Add($"{where}: {hidden} shows under the screen");
+ var before = info.Selected;
+ var tlv = C.SettlementHexes.Single(x => x.Id == "tel_aviv");
+ info.Show(tlv.Q, tlv.R);
+ if (info.Selected != before) problems.Add($"{where}: a map click changed the hidden info panel");
+ }
+ else if (r.Overlaps(root.Q("right-column").worldBound)) problems.Add($"{where}: overlaps the event column");
+ }
+ nav.Open(null);
+ for (int i = 0; i < 3; i++) yield return null;
+ foreach (var shown in new[] { "right-column", "info-panel" })
+ if (root.Q(shown).resolvedStyle.display == DisplayStyle.None) problems.Add($"{w}x{h}: {shown} stays hidden after closing");
+ }
+ finally
+ {
+ for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
+ Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
+ }
+ }
+ Assert.IsEmpty(problems, string.Join("\n", problems));
+ }
+
+ /// <summary>The nearest box an element belongs in: a card, a Defence panel or the house.</summary>
+ static VisualElement? Ancestor(VisualElement e)
+ {
+ for (var p = e.parent; p != null; p = p.parent)
+ if (p.ClassListContains("seat") || p.ClassListContains("leader") || p.ClassListContains("defence-panel") || p.ClassListContains("cabinet-house") || p.ClassListContains("cabinet-side"))
+ return p;
+ return null;
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/PromoScreensTests.cs.meta b/unity/Assets/Tests/EditMode/PromoScreensTests.cs.meta
new file mode 100644
index 000000000..6ae0d8a5c
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/PromoScreensTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: a43352e21a7c84d99b64d80fdf74eccf
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/UiLayoutTests.cs b/unity/Assets/Tests/EditMode/UiLayoutTests.cs
index 77a1fd144..700aa1810 100644
--- a/unity/Assets/Tests/EditMode/UiLayoutTests.cs
+++ b/unity/Assets/Tests/EditMode/UiLayoutTests.cs
@@ -41,9 +41,15 @@ public class UiLayoutTests
foreach (var a in Fixed)
foreach (var b in Fixed)
if (string.CompareOrdinal(a, b) < 0) Assert.IsFalse(R(a).Overlaps(R(b)), $"{w}x{h}: {a} {R(a)} overlaps {b} {R(b)}");
+ // A wide screen (Cabinet, Defence: promo 04 and 08) opens over the info panel, drawn above it; no screen
+ // covers the top bar, the event card or the minimap.
foreach (var s in Screens)
foreach (var f in Fixed)
+ {
+ if (f == "info-panel" && root.Q(s).ClassListContains("screen-wide"))
+ continue; // checked below: hidden while the wide screen is open
Assert.IsFalse(R(s).Overlaps(R(f)), $"{w}x{h}: {s} {R(s)} overlaps {f} {R(f)}");
+ }
Assert.LessOrEqual(R("meters").xMax, R("nav").xMin + 0.5f, $"{w}x{h}: the meters run into the screen buttons");
Assert.LessOrEqual(R("top-bar").xMin, root.Q(className: "date-box").worldBound.xMin, $"{w}x{h}: date box starts outside the top bar");
Assert.LessOrEqual(root.Q(className: "date-box").worldBound.xMax, R("meters").xMin + 0.5f, $"{w}x{h}: date box runs into the meters");
@@ -68,6 +74,60 @@ public class UiLayoutTests
}
static readonly Content C = ContentLoader.Load(Paths.Content);
+
+ /// <summary>Review I3: a wide screen (Cabinet, Defence) covers the info panel, so while it is open the panel is hidden:
+ /// it is drawn under the screen, takes no keyboard focus (its build buttons cannot be reached with Tab), and a map
+ /// click does not change it. A narrow screen (Budget) leaves it as it was.</summary>
+ [UnityTest]
+ public IEnumerator AWideScreenHidesTheInfoPanelItCovers()
+ {
+ var rt = new RenderTexture(1920, 1080, 0);
+ var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));
+ ps.targetTexture = rt;
+ var go = new GameObject("WideTest");
+ go.SetActive(false);
+ var doc = go.AddComponent<UIDocument>();
+ doc.panelSettings = ps;
+ doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
+ go.SetActive(true);
+ var root = doc.rootVisualElement;
+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);
+ var info = new InfoPanelPresenter(root, bridge, Text, C.SettlementHexes.ToDictionary(x => x.Id, x => x.Id));
+ var nav = new ScreenNav(root);
+ try
+ {
+ root.Q("root").RemoveFromClassList("loading");
+ var tlv = C.SettlementHexes.Single(x => x.Id == "tel_aviv");
+ info.Show(tlv.Q, tlv.R);
+ for (int i = 0; i < 4; i++) yield return null;
+ var panel = root.Q("info-panel");
+ var build = root.Q<Button>("build-camp");
+ Assert.AreEqual(DisplayStyle.Flex, panel.resolvedStyle.display, "precondition: the panel shows");
+ foreach (var s in new[] { "cabinet", "defence" })
+ {
+ nav.Open(s);
+ for (int i = 0; i < 3; i++) yield return null;
+ Assert.IsTrue(root.Q("screen-" + s).ClassListContains(ScreenNav.WideClass), s);
+ Assert.Greater(root.Q("root").IndexOf(root.Q("screen-" + s)), root.Q("root").IndexOf(panel), $"{s} is drawn above the info panel");
+ Assert.IsTrue(root.Q("screen-" + s).worldBound.Overlaps(panel.worldBound) || panel.resolvedStyle.display == DisplayStyle.None, s);
+ Assert.AreEqual(DisplayStyle.None, panel.resolvedStyle.display, $"{s}: the covered info panel is hidden");
+ Assert.IsFalse(build.canGrabFocus, $"{s}: its build button cannot take the keyboard focus");
+ build.Focus();
+ Assert.AreNotSame(build, build.focusController?.focusedElement, $"{s}: focus does not reach it");
+ info.Show(tlv.Q + 3, tlv.R);
+ Assert.AreEqual((tlv.Q, tlv.R), info.Selected, $"{s}: a map click does not change the hidden panel");
+ }
+ nav.Open("budget");
+ for (int i = 0; i < 3; i++) yield return null;
+ Assert.AreEqual(DisplayStyle.Flex, panel.resolvedStyle.display, "a narrow screen leaves the panel");
+ nav.Open(null);
+ for (int i = 0; i < 3; i++) yield return null;
+ Assert.AreEqual(DisplayStyle.Flex, panel.resolvedStyle.display, "closing brings it back");
+ info.Show(tlv.Q + 3, tlv.R);
+ Assert.AreEqual((tlv.Q + 3, tlv.R), info.Selected, "and map clicks reach it again");
+ }
+ finally { nav.Dispose(); info.Dispose(); Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt); }
+ }
static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
/// <summary>The window sizes a player is likely to have: 16:9, 5:4, the playtest's wide-and-short browser window
@@ -210,7 +270,7 @@ public class UiLayoutTests
g.Step(new Command[0]);
}
var problems = new List<string>();
- foreach (var (w, h) in new[] { (1920, 1080), (1280, 720), (1920, 960), (1600, 757), (1366, 657) })
+ foreach (var (w, h) in new[] { (1920, 1080), (1280, 720), (1920, 960), (1600, 757), (1366, 657), (390, 844), (960, 600) }) // #210: and narrow windows
{
var rt = new RenderTexture(w, h, 0);
var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));
diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxml
index 3078808bc..6cb613e11 100644
--- a/unity/Assets/UI/Game.uxml
+++ b/unity/Assets/UI/Game.uxml
@@ -122,16 +122,44 @@
</ui:VisualElement>
<Statecraft.Game.UI.UiFrame />
</ui:VisualElement>
- <ui:VisualElement name="screen-cabinet" class="panel screen">
- <ui:VisualElement class="screen-header"><ui:Label name="cabinet-government" class="title" /><ui:Label name="cabinet-coalition" class="muted" /></ui:VisualElement>
- <ui:VisualElement class="row grow">
- <ui:ScrollView name="cabinet-seats" class="grow" />
- <ui:VisualElement name="cabinet-pick" class="grow">
- <ui:Label name="cabinet-pick-title" class="meter-name" />
- <ui:ScrollView name="cabinet-candidates" class="grow" />
+ <!-- The Cabinet as promo/final/04 (CabinetPresenter): a wide screen; the Prime Minister's card and the appointment
+ list at the side; the legislature's seats (Hemicycle) with its legend above a grid of person cards. -->
+ <ui:VisualElement name="screen-cabinet" class="panel screen screen-wide">
+ <ui:VisualElement class="screen-header"><ui:Label name="cabinet-government" class="title" /><ui:Label name="cabinet-legislature" class="muted" /></ui:VisualElement>
+ <ui:VisualElement name="cabinet-body" class="row grow">
+ <ui:VisualElement name="cabinet-side" class="cabinet-side">
+ <ui:Button name="seat-prime_minister" class="seat pm-card" />
+ <!-- The other offices the PM holds: listed on the card, selectable here (CabinetPresenter). -->
+ <ui:VisualElement name="cabinet-pm-offices" class="pm-offices" />
+ <ui:VisualElement name="cabinet-pick" class="grow">
+ <ui:Label name="cabinet-pick-title" class="meter-name" />
+ <ui:Label name="cabinet-pick-reason" class="reason" />
+ <ui:ScrollView name="cabinet-candidates" class="grow" />
+ </ui:VisualElement>
+ <ui:Label name="cabinet-status" class="muted" />
+ </ui:VisualElement>
+ <ui:VisualElement name="cabinet-main" class="cabinet-main grow">
+ <ui:VisualElement name="cabinet-house" class="cabinet-house">
+ <ui:VisualElement class="hemicycle-box">
+ <Statecraft.Game.UI.Hemicycle name="cabinet-hemicycle" class="hemicycle" />
+ <ui:VisualElement class="hemicycle-count" picking-mode="Ignore">
+ <ui:Label name="cabinet-house-size" class="house-size" />
+ <ui:Label name="cabinet-house-unit" class="house-unit" />
+ </ui:VisualElement>
+ </ui:VisualElement>
+ <ui:VisualElement class="house-legend">
+ <ui:Label name="cabinet-coalition" class="house-coalition" />
+ <Statecraft.Game.UI.UiBar name="cabinet-stability" class="ui-bar--stability house-stability" />
+ <ui:Label name="cabinet-opposition" class="muted" />
+ <ui:Label name="cabinet-majority" class="muted" />
+ <ui:Label name="cabinet-largest" class="muted" />
+ <ui:VisualElement name="cabinet-parties" class="party-chips" />
+ </ui:VisualElement>
+ <Statecraft.Game.UI.UiFrame shadow="false" corners="false" />
+ </ui:VisualElement>
+ <ui:ScrollView name="cabinet-seats" class="grow" />
</ui:VisualElement>
</ui:VisualElement>
- <ui:Label name="cabinet-status" class="muted" />
<Statecraft.Game.UI.UiFrame />
</ui:VisualElement>
<ui:VisualElement name="screen-budget" class="panel screen">
@@ -146,29 +174,58 @@
</ui:VisualElement>
<Statecraft.Game.UI.UiFrame />
</ui:VisualElement>
- <ui:VisualElement name="screen-defence" class="panel screen">
+ <!-- Defence as promo/final/08 (DefencePresenter): leadership, the escalation ladder and the reserve call-up side by
+ side (wrapping in a narrow window), then the defence share of the budget. Only what the sim models. -->
+ <ui:VisualElement name="screen-defence" class="panel screen screen-wide">
<ui:VisualElement class="screen-header"><ui:Label text="Defence" class="title" /><ui:Label name="defence-command" class="muted" /></ui:VisualElement>
- <ui:Label text="Security level" class="meter-name" />
- <ui:VisualElement name="ladder">
- <ui:VisualElement name="rung-5" class="rung"><ui:Label name="rung-5-name" class="grow" /><ui:Label name="rung-5-turn" class="muted" /></ui:VisualElement>
- <ui:VisualElement name="rung-4" class="rung"><ui:Label name="rung-4-name" class="grow" /><ui:Label name="rung-4-turn" class="muted" /></ui:VisualElement>
- <ui:VisualElement name="rung-3" class="rung"><ui:Label name="rung-3-name" class="grow" /><ui:Label name="rung-3-turn" class="muted" /></ui:VisualElement>
- <ui:VisualElement name="rung-2" class="rung"><ui:Label name="rung-2-name" class="grow" /><ui:Label name="rung-2-turn" class="muted" /></ui:VisualElement>
- <ui:VisualElement name="rung-1" class="rung"><ui:Label name="rung-1-name" class="grow" /><ui:Label name="rung-1-turn" class="muted" /></ui:VisualElement>
- </ui:VisualElement>
- <ui:Label name="ceasefire" class="muted" />
- <ui:VisualElement class="row">
- <ui:Button name="de-escalate" text="Lower the level" />
- <ui:Button name="escalate" text="Raise the level" />
- <ui:Label name="order-pending" class="muted grow" />
- </ui:VisualElement>
- <ui:Label text="Reserve call-up" class="meter-name" />
- <ui:VisualElement class="row">
- <ui:Button name="mob-down" text="-5%" />
- <ui:Label name="mob-level" class="grow" />
- <ui:Button name="mob-up" text="+5%" />
- </ui:VisualElement>
- <ui:Label name="mob-cost" class="muted" />
+ <ui:ScrollView name="defence-body" class="grow">
+ <ui:VisualElement class="defence-row">
+ <ui:VisualElement name="defence-leadership" class="defence-panel defence-leadership">
+ <ui:Label name="defence-title-leadership" class="section-title" />
+ <ui:VisualElement class="leaders">
+ <ui:VisualElement name="lead-prime_minister" class="leader" />
+ <ui:VisualElement name="lead-defense_minister" class="leader" />
+ <ui:VisualElement name="lead-chief_of_staff" class="leader" />
+ </ui:VisualElement>
+ <Statecraft.Game.UI.UiFrame shadow="false" />
+ </ui:VisualElement>
+ <ui:VisualElement name="defence-ladder" class="defence-panel defence-ladder">
+ <ui:Label name="defence-title-ladder" class="section-title" />
+ <ui:VisualElement name="ladder">
+ <ui:VisualElement name="rung-5" class="rung"><ui:Label name="rung-5-name" class="grow rung-name" /><ui:Label name="rung-5-turn" class="muted rung-turn" /></ui:VisualElement>
+ <ui:VisualElement name="rung-4" class="rung"><ui:Label name="rung-4-name" class="grow rung-name" /><ui:Label name="rung-4-turn" class="muted rung-turn" /></ui:VisualElement>
+ <ui:VisualElement name="rung-3" class="rung"><ui:Label name="rung-3-name" class="grow rung-name" /><ui:Label name="rung-3-turn" class="muted rung-turn" /></ui:VisualElement>
+ <ui:VisualElement name="rung-2" class="rung"><ui:Label name="rung-2-name" class="grow rung-name" /><ui:Label name="rung-2-turn" class="muted rung-turn" /></ui:VisualElement>
+ <ui:VisualElement name="rung-1" class="rung"><ui:Label name="rung-1-name" class="grow rung-name" /><ui:Label name="rung-1-turn" class="muted rung-turn" /></ui:VisualElement>
+ </ui:VisualElement>
+ <ui:Label name="ceasefire" class="muted wrap" />
+ <ui:VisualElement class="row">
+ <ui:Button name="de-escalate" text="Lower the level" />
+ <ui:Button name="escalate" text="Raise the level" />
+ </ui:VisualElement>
+ <ui:Label name="order-pending" class="muted" />
+ <Statecraft.Game.UI.UiFrame shadow="false" />
+ </ui:VisualElement>
+ <ui:VisualElement name="defence-callup" class="defence-panel defence-callup">
+ <ui:Label name="defence-title-callup" class="section-title" />
+ <ui:Label name="mob-percent" class="big-figure" />
+ <Statecraft.Game.UI.UiBar name="mob-bar" class="ui-bar--mobilization big-bar" />
+ <ui:Label name="mob-level" class="wrap" />
+ <ui:VisualElement class="row">
+ <ui:Button name="mob-down" text="-5%" />
+ <ui:Button name="mob-up" text="+5%" />
+ </ui:VisualElement>
+ <ui:Label name="mob-cost" class="muted wrap" />
+ <Statecraft.Game.UI.UiFrame shadow="false" />
+ </ui:VisualElement>
+ </ui:VisualElement>
+ <ui:VisualElement name="defence-budget" class="defence-panel defence-budget">
+ <ui:Label name="defence-title-budget" class="section-title budget-title" />
+ <Statecraft.Game.UI.UiBar name="defence-budget-bar" class="ui-bar--budget big-bar grow" />
+ <ui:Label name="defence-budget-share" class="budget-share" />
+ <Statecraft.Game.UI.UiFrame shadow="false" />
+ </ui:VisualElement>
+ </ui:ScrollView>
<Statecraft.Game.UI.UiFrame />
</ui:VisualElement>
<ui:VisualElement name="screen-why" class="panel screen">
diff --git a/unity/Assets/UI/Statecraft.uss b/unity/Assets/UI/Statecraft.uss
index d3b81bab8..e8a41bf09 100644
--- a/unity/Assets/UI/Statecraft.uss
+++ b/unity/Assets/UI/Statecraft.uss
@@ -147,6 +147,11 @@ Button:disabled { color: var(--ink-dim); border-color: rgba(120, 120, 120, 0.4);
.hud-two-row .top-bar { height: 216px; padding-top: 6px; padding-bottom: 4px; flex-wrap: wrap; justify-content: space-between; align-content: space-around; }
.hud-two-row .meters { width: 78%; flex-grow: 1; }
.hud-two-row .right-column, .hud-two-row .screen, .hud-two-row .toast { top: 232px; }
+/* Narrower still (a phone upright; HudPresenter adds hud-three-row with hud-two-row): the badge, the meters and the
+ screen buttons with End Turn take a row each, and the panels move down under the taller bar (#210). */
+.hud-three-row .top-bar { height: 312px; }
+.hud-three-row .meters { width: 100%; }
+.hud-three-row .right-column, .hud-three-row .screen, .hud-three-row .toast { top: 328px; }
.turn-box { width: 150px; flex-shrink: 1; min-width: 150px; align-items: flex-end; }
#attention { font-size: 16px; }
.end-turn {
@@ -205,13 +210,14 @@ Button:disabled { color: var(--ink-dim); border-color: rgba(120, 120, 120, 0.4);
/* Full screens (Cabinet, Budget, Defence, Why) open in the centre, one at a time. */
/* Hidden until ScreenNav opens one (never visible while loading; playtest 2, P2-1). Right edge clear of the 480px column. */
.screen { display: none; position: absolute; left: 552px; right: 512px; top: 112px; bottom: 16px; padding: 18px; background-color: rgb(11, 18, 32); } /* opaque: a reading screen, and the map labels must not show through */
-.screen-header { flex-direction: row; justify-content: space-between; align-items: center; border-bottom-width: 1px; border-color: var(--gold-dim); margin-bottom: 10px; padding-bottom: 4px; }
+.screen-header { flex-direction: column; align-items: stretch; border-bottom-width: 1px; border-color: var(--gold-dim); margin-bottom: 10px; padding-bottom: 4px; }
/* Screen titles and section names in gold, letter-spaced, as the promo's "DEFENSE" and "LEADERSHIP". */
.screen-header > .title { color: var(--gold-light); letter-spacing: 1px; }
+/* The subtitle sits under the title, the screen's full width, and wraps in a narrow window (#211). A column, not a
+ wrapping row: a shrinking, wrapping label in a row re-measured itself every frame (PromoScreensTests idle test). */
+.screen-header > .muted { white-space: normal; }
.screen .meter-name { color: var(--gold); letter-spacing: 2px; font-size: 16px; margin-top: 8px; }
.row { flex-direction: row; align-items: center; }
-.rung { flex-direction: row; padding: 5px 10px; margin: 1px 0; border-left-width: 3px; border-color: rgba(0, 0, 0, 0); }
-.rung-current { border-color: var(--gold); background-color: rgba(196, 160, 92, 0.15); }
.grow { flex-grow: 1; }
/* A growing row inside a screen (the Cabinet's seats and candidates) takes the height that is left and stretches its
lists to it, so a long list scrolls instead of growing out of the screen. */
@@ -235,27 +241,137 @@ Button:disabled { color: var(--ink-dim); border-color: rgba(120, 120, 120, 0.4);
.why-group { -unity-font-definition: url("project://database/Assets/UI/Fonts/EBGaramond-SemiBold.ttf"); color: var(--gold); letter-spacing: 1px; margin-top: 10px; border-bottom-width: 1px; border-color: rgba(196, 160, 92, 0.25); }
.why-line { white-space: normal; padding-left: 12px; }
-/* The candidate column (B5): a fixed share beside the portrait grid, clear of the grid's scroll bar, its heading on one line. */
-#cabinet-pick { flex-grow: 0; flex-shrink: 0; width: 42%; margin-left: 14px; }
-#cabinet-pick-title { white-space: normal; }
-/* The Cabinet as the promo's portrait cards (promo/final/04): the lineup wraps into a grid of cards, each a gold-framed
- portrait over the office and its holder; a long lineup scrolls. */
-#cabinet-seats .unity-scroll-view__content-container { flex-direction: row; flex-wrap: wrap; }
+/* Wide screens (Cabinet and Defence, laid out as promo/final/04 and 08): from the left edge to the event column, over the
+ info panel (an opaque reading screen; the info panel is about a hex, not needed while reading a screen). The event card
+ and the minimap stay in view (UiLayoutTests). */
+.screen-wide { left: 16px; bottom: 100px; }
+/* While a wide screen is open the toast's corner (B7) is under it, so the toast moves to the strip the wide screen leaves
+ free at the bottom, between the window's left edge and the event column: opaque, clear of the screen and the column
+ (PromoHudTests.TheToastIsOpaqueAndClearOfTheScreens). Two lines fit. */
+.wide-screen-open .toast { top: auto; bottom: 16px; left: 16px; right: 512px; width: auto; padding: 6px 12px; }
+/* The info panel under an open wide screen is hidden (ScreenNav sets wide-screen-open): no focus, no clicks, no updates. */
+.wide-screen-open .info-panel { display: none; }
+.section-title {
+ -unity-font-definition: url("project://database/Assets/UI/Fonts/EBGaramond-SemiBold.ttf");
+ color: var(--gold); letter-spacing: 3px; font-size: 17px; margin: 0 0 8px 2px; padding: 0;
+}
+.wrap { white-space: normal; }
+
+/* Bars (UiBar): a dark track and a coloured fill, each fill at least 3:1 against the track (PromoScreensTests). */
+.ui-bar { height: 8px; min-width: 40px; flex-grow: 1; flex-shrink: 1; background-color: rgb(34, 42, 58); border-radius: 2px; overflow: visible; }
+.ui-bar-fill { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 2px; background-color: var(--gold); }
+.ui-bar-mark { position: absolute; top: -4px; bottom: -4px; width: 2px; margin-left: -1px; background-color: var(--ink); }
+.ui-bar--competence .ui-bar-fill { background-color: rgb(86, 164, 204); }
+.ui-bar--loyalty .ui-bar-fill { background-color: rgb(104, 186, 132); }
+.ui-bar--stability .ui-bar-fill { background-color: var(--gold); }
+.ui-bar--mobilization .ui-bar-fill { background-color: rgb(152, 178, 96); }
+.ui-bar--budget .ui-bar-fill { background-color: rgb(152, 178, 96); }
+.big-bar { height: 16px; }
+
+/* Person cards (PersonCard): a framed portrait (or a plate with the initials), then name, office, party and the two bars. */
.seat {
- flex-direction: column; align-items: center; justify-content: flex-start; width: 188px; min-height: 250px;
- padding: 8px 8px 10px 8px; margin: 4px; -unity-text-align: upper-center;
+ flex-direction: column; align-items: stretch; justify-content: flex-start; width: 190px;
+ padding: 0 0 8px 0; margin: 4px; -unity-text-align: upper-center; border-color: rgba(196, 160, 92, 0.6);
}
-.seat > Label { white-space: normal; -unity-text-align: upper-center; font-size: 16px; margin-top: 6px; }
-.seat-portrait {
- width: 112px; height: 140px; flex-shrink: 0; -unity-background-scale-mode: scale-and-crop; background-position-y: top 20%;
- background-color: var(--navy-deep); border-width: 1px; border-color: var(--gold);
+.card-plate { height: 150px; flex-shrink: 0; background-color: var(--navy-raised); border-bottom-width: 1px; border-color: var(--gold-dim); overflow: hidden; }
+.card-portrait { flex-grow: 1; background-size: cover; }
+.card-initials {
+ flex-grow: 1; -unity-text-align: middle-center; font-size: 46px; color: rgba(196, 160, 92, 0.75);
+ -unity-font-definition: url("project://database/Assets/UI/Fonts/EBGaramond-SemiBold.ttf"); letter-spacing: 2px;
+}
+.card-name {
+ -unity-font-definition: url("project://database/Assets/UI/Fonts/EBGaramond-SemiBold.ttf");
+ font-size: 19px; color: var(--ink); -unity-text-align: upper-center; white-space: normal; margin: 6px 6px 0 6px; padding: 0;
}
-.seat-selected { border-color: var(--gold); background-color: var(--navy-raised); }
+.card-office { font-size: 15px; color: var(--ink-dim); -unity-text-align: upper-center; white-space: normal; margin: 0 6px; padding: 0; }
+.card-party { font-size: 15px; color: var(--gold); -unity-text-align: upper-center; white-space: normal; -unity-font-style: italic; margin: 0 6px 4px 6px; padding: 0; }
+.card-stat { flex-direction: row; align-items: center; height: 21px; padding: 0 10px; }
+.card-stat-name { width: 82px; flex-shrink: 0; font-size: 14px; color: var(--ink-dim); -unity-text-align: middle-left; padding: 0; margin: 0; }
+.card-stat-value { width: 24px; flex-shrink: 0; font-size: 16px; color: var(--ink); -unity-text-align: middle-right; padding: 0; margin: 0; }
+.seat-selected { border-color: var(--gold-light); background-color: var(--navy-raised); }
+.seat-vacant .card-name { color: var(--ink-dim); }
.appointed { color: var(--gold); }
+/* A keyboard-focused card takes the warm focus fill (Button:focus); its dim and gold text turn ink to stay legible on it. */
+.seat:focus .card-name, .seat:focus .card-office, .seat:focus .card-party, .seat:focus .card-stat-name, .seat:focus .card-initials { color: var(--ink); }
+
+/* The Cabinet: the Prime Minister's card and the appointment list at the side; the house and the cards in the main column. */
+.cabinet-side { width: 300px; flex-shrink: 0; margin-right: 14px; }
+.cabinet-main { min-width: 0; }
+.pm-card { width: auto; margin: 0 0 8px 0; padding-bottom: 12px; }
+.pm-card .card-plate { height: 250px; }
+.pm-card .card-name { font-size: 27px; color: var(--gold-light); margin-top: 8px; }
+.pm-card .card-office { font-size: 17px; }
+.pm-card .card-party { font-size: 17px; margin-bottom: 8px; }
+.pm-card .card-stat { height: 26px; padding: 0 16px; }
+.pm-card .card-stat-name { font-size: 16px; width: 96px; }
+.pm-card .ui-bar { height: 10px; }
+#cabinet-pick { flex-shrink: 1; min-height: 0; }
+/* The Appoint heading wraps rather than run past the 300 px side column (B5; PromoHudTests.TheAppointHeadingHasRoom). */
+#cabinet-pick-title { white-space: normal; }
+.pm-offices { flex-direction: row; flex-wrap: wrap; margin: -2px 0 8px 0; }
+.pm-office { font-size: 15px; padding: 3px 10px; margin: 0 6px 4px 0; border-color: rgba(196, 160, 92, 0.6); }
+.cabinet-house {
+ flex-direction: row; flex-wrap: wrap; align-items: center; flex-shrink: 0; margin: 0 5px 8px 5px; padding: 10px 14px;
+ background-color: rgba(5, 9, 18, 0.55); border-width: 1px; border-color: var(--gold-dim); border-radius: 2px;
+}
+.hemicycle-box { width: 320px; height: 168px; flex-shrink: 0; margin-right: 18px; }
+.hemicycle { position: absolute; left: 0; top: 0; right: 0; bottom: 0; }
+.hemicycle-count { position: absolute; left: 0; right: 0; bottom: 0; align-items: center; }
+.house-size { -unity-font-definition: url("project://database/Assets/UI/Fonts/EBGaramond-SemiBold.ttf"); font-size: 34px; color: var(--ink); padding: 0; margin: 0; -unity-text-align: lower-center; }
+.house-unit { font-size: 13px; letter-spacing: 2px; color: var(--ink-dim); padding: 0; margin: 0; -unity-text-align: upper-center; }
+.house-legend { flex-grow: 1; flex-shrink: 1; min-width: 260px; }
+.house-coalition { font-size: 20px; color: var(--ink); white-space: normal; }
+.house-stability { flex-grow: 0; height: 8px; margin: 3px 0 6px 0; max-width: 360px; }
+.house-legend > Label { padding-top: 0; padding-bottom: 0; }
+.party-chips { flex-direction: row; flex-wrap: wrap; margin-top: 6px; }
+.party-chip { flex-direction: row; align-items: center; margin: 0 12px 2px 0; }
+.party-chip > Label { font-size: 14px; color: var(--ink-dim); padding: 0; margin: 0; }
+.party-swatch { width: 11px; height: 11px; border-radius: 6px; margin-right: 5px; }
+.party-swatch--hollow { border-width: 1.2px; border-color: var(--ink-dim); }
+#cabinet-seats .unity-scroll-view__content-container { flex-direction: row; flex-wrap: wrap; }
.candidate { flex-direction: column; align-items: stretch; margin-bottom: 4px; }
.candidate > Button { white-space: normal; }
.reason { color: var(--ink-dim); font-size: 16px; white-space: normal; flex-shrink: 1; }
+/* Defence: three panels side by side that wrap in a narrow window, then the budget share. */
+.defence-row { flex-direction: row; flex-wrap: wrap; align-items: stretch; }
+.defence-panel {
+ margin: 6px; padding: 14px 16px; background-color: rgba(5, 9, 18, 0.55);
+ border-width: 1px; border-color: var(--gold-dim); border-radius: 2px;
+}
+.defence-leadership { flex-grow: 3; flex-basis: 560px; }
+.defence-ladder { flex-grow: 2; flex-basis: 380px; }
+.defence-callup { flex-grow: 1; flex-basis: 300px; }
+.leaders { flex-direction: row; flex-wrap: wrap; justify-content: space-around; }
+.leader .card-plate { height: 200px; }
+.leader .card-name { font-size: 20px; }
+.leader {
+ width: 172px; flex-grow: 1; max-width: 230px; margin: 4px; padding-bottom: 8px; background-color: var(--navy-deep);
+ border-width: 1px; border-color: rgba(196, 160, 92, 0.6); border-radius: 2px;
+}
+.rung { flex-direction: row; align-items: center; padding: 8px 10px; margin: 2px 0; border-left-width: 3px; border-color: rgba(0, 0, 0, 0); background-color: rgba(255, 255, 255, 0.03); }
+.rung-name { white-space: normal; font-size: 18px; flex-shrink: 1; min-width: 0; }
+.rung-turn { font-size: 15px; margin-left: 8px; flex-shrink: 0; }
+.rung-current { border-color: var(--gold-light); background-color: rgba(196, 160, 92, 0.20); }
+.rung-current .rung-name { color: var(--gold-light); }
+/* The level an order will move to at End Turn: a dashed-looking ink edge, distinct from the lit current level. */
+.rung-target { border-color: var(--ink); border-left-width: 3px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; }
+.big-figure { -unity-font-definition: url("project://database/Assets/UI/Fonts/EBGaramond-SemiBold.ttf"); font-size: 44px; color: var(--ink); padding: 0; margin: 0 0 4px 0; }
+.defence-callup .big-bar { flex-grow: 0; margin: 4px 0 10px 0; }
+.defence-budget { flex-direction: row; align-items: center; }
+.budget-title { margin: 0 18px 0 0; }
+.budget-share { margin-left: 16px; font-size: 18px; }
+/* A wide screen's header wraps its subtitle under the title when the window is narrow. */
+/* Square and narrower windows: a slimmer side column leaves room for two columns of cards. */
+.hud-two-row .cabinet-side { width: 250px; }
+.hud-two-row .pm-card .card-plate { height: 210px; }
+/* #210: in the two-row (narrow) HUD every screen takes the full width under the bar. While one is open the event column
+ and the info panel under it are hidden (no focus, no clicks), and the toast takes the strip below the screen. */
+.hud-two-row .screen { left: 16px; right: 16px; bottom: 100px; }
+.hud-two-row.screen-open .right-column, .hud-two-row.screen-open .info-panel { display: none; }
+.hud-two-row.screen-open .toast { top: auto; bottom: 16px; left: 16px; right: 16px; width: auto; padding: 6px 12px; }
+.hud-two-row .cabinet-house { justify-content: center; }
+
/* Loading (playtest 2, P2-1): until GameRoot is ready only this line shows; the bar's values, the info panel and the
right-hand column are kept out of sight (visibility, so the layout does not jump when they appear). */
.loading-line { display: none; position: absolute; left: 0; right: 0; top: 45%; -unity-text-align: middle-center; font-size: 28px; color: var(--ink); }
diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yaml
index 63fb2c18a..48499858a 100644
--- a/unity/Assets/UI/strings.en.yaml
+++ b/unity/Assets/UI/strings.en.yaml
@@ -58,13 +58,34 @@ why.situations: "Situations"
why.other: "Other"
why.nothing: "Nothing notable happened this turn."
cabinet.coalition: "Coalition: {0} of {1} seats · stability {2}"
-cabinet.seat: "{0}: {1}"
cabinet.vacant: "(vacant)"
cabinet.person: "{0} · {1} · competence {2}, loyalty {3}"
cabinet.no_party: "no party"
-cabinet.appointed: " (your appointee)"
cabinet.pick: "Appoint to {0}"
cabinet.queued: "Ordered: {0} to {1}, at End Turn"
+# Cabinet (promo 04): the body the government answers to, the half circle's legend and its party chips.
+cabinet.legislature: "Answerable to the {0} · {1} members"
+cabinet.opposition: "Opposition: {0} seats"
+cabinet.majority: "Majority: {0} seats"
+cabinet.largest: "Largest party: {0}, {1} seats"
+cabinet.party_seats: "{0} {1}"
+cabinet.unrecorded: "Not recorded"
+cabinet.members_unit: "members"
+cabinet.select_office: "{0}"
+# Person cards (Cabinet and Defence): the two bars' captions, the PM card's party line, and the joint between offices.
+card.competence: "Competence"
+card.loyalty: "Loyalty"
+card.party: "Party: {0}"
+card.appointed_name: "{0} (your appointee)"
+card.offices_separator: " · "
+# Defence (promo 08): the Ministry of Defense's share of budget spending (the Budget screen's line).
+defence.budget_share: "{0} of budget spending"
+defence.budget_none: "No defence line in the budget"
+# Section captions, in normal case: the screen shows them in capitals, as the promo (a caseless script is unchanged).
+defence.section_leadership: "Leadership"
+defence.section_ladder: "Security level"
+defence.section_callup: "Reserve call-up"
+defence.section_budget: "Defence share of the budget"
info.hint: "Click the map to inspect a hex"
info.off_map: "Off the map"
info.hex: "{0} · elevation {1:N0} m"
diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yaml
index 0ffa35363..cf3c98efd 100644
--- a/unity/Assets/UI/strings.he.yaml
+++ b/unity/Assets/UI/strings.he.yaml
@@ -31,6 +31,12 @@ defence.mob: "{0} מכוחות המילואים גויסו (דרגה {1} דור
defence.mob_cost: "עלות שנתית של {0} בשכר ובאובדן עבודה"
defence.ceasefire_stops: "הספירה להפסקת אש של האו״ם נעצרת אם מורידים את הדרגה"
defence.ceasefire_starts: "הפסקת אש של האו״ם: {0} שבועות מההגעה לדרגה 5"
+defence.budget_share: "{0} מהוצאות התקציב"
+defence.budget_none: "אין בתקציב סעיף ביטחון"
+defence.section_leadership: "הנהגה"
+defence.section_ladder: "דרגת ביטחון"
+defence.section_callup: "גיוס מילואים"
+defence.section_budget: "חלקו של הביטחון בתקציב"
budget.share: "{0}"
budget.office: "{0} ({1})"
budget.vacant: "פנוי"
@@ -57,13 +63,24 @@ why.situations: "מצבים"
why.other: "אחר"
why.nothing: "לא קרה דבר ראוי לציון בתור הזה."
cabinet.coalition: "קואליציה: {0} מתוך {1} מנדטים · יציבות {2}"
-cabinet.seat: "{0}: {1}"
cabinet.vacant: "(פנוי)"
cabinet.person: "{0} · {1} · כשירות {2}, נאמנות {3}"
cabinet.no_party: "ללא מפלגה"
-cabinet.appointed: " (מינוי שלך)"
cabinet.pick: "מינוי לתפקיד {0}"
cabinet.queued: "ניתנה פקודה: {0} לתפקיד {1}, בסיום התור"
+cabinet.legislature: "אחראית בפני {0} · {1} חברים"
+cabinet.opposition: "אופוזיציה: {0} מנדטים"
+cabinet.majority: "רוב: {0} מנדטים"
+cabinet.largest: "המפלגה הגדולה: {0}, {1} מנדטים"
+cabinet.party_seats: "{0} {1}"
+cabinet.unrecorded: "לא תועד"
+cabinet.members_unit: "חברים"
+cabinet.select_office: "{0}"
+card.competence: "כשירות"
+card.loyalty: "נאמנות"
+card.party: "מפלגה: {0}"
+card.appointed_name: "{0} (מינוי שלך)"
+card.offices_separator: " · "
info.hint: "יש ללחוץ על המפה כדי לבדוק משושה"
info.off_map: "מחוץ למפה"
info.hex: "{0} · גובה {1:N0} מ׳"