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 HUD keeps clear of the phone's notch and home indicator (#1013)

agamrafaeli-instinct412824b10924
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2483a6563..b596ab673 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,14 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
## [Unreleased]
+### Fixed
+- On a notched phone the HUD and the panels keep clear of the notch and the home indicator: the root is padded by
+ the browser's `env(safe-area-inset-*)` values (the camera's top inset and the map labels follow as before), and it
+ follows the insets even when the root bounds do not change, as a same-size landscape flip moves the notch with no
+ geometry event (a per-frame poll); desktops and notch-free phones are unchanged.
+ With a side inset, raised meter captions reflow into the existing two-row bar when their measured widths no longer
+ fit; Security's level wraps with its caption, and the 12 px text floor is preserved.
+
### Added
- An opt-in Civilization-style hex-tile map (`?hex-tiles`, desktop `-hex-tiles`; `?hex-tiles=tel_aviv_crop` for the
Tel Aviv crop): one-file hex prototypes (towns, orchards, fields, forests, hills), units as their own layer, painted
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 41ec247b7..52a2d7724 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -332,6 +332,7 @@ namespace Statecraft.Game.UI
pointer.HexClicked += onHex;
var camRig = rig = cameraController.GetComponent<CameraRig>();
Own(new TopBarInset(root, camRig)); // the map is framed below the top bar
+ Own(new SafeAreaFit(root)); // the HUD keeps clear of the phone's notch
var mini = minimap = Own(new MinimapPresenter(root, map.Hexes, text));
var labelCamera = cameraController.GetComponent<Camera>();
labels = Own(new MapLabelsPresenter(root, map, labelCamera, null,
diff --git a/unity/Assets/Scripts/UI/HudPresenter.cs b/unity/Assets/Scripts/UI/HudPresenter.cs
index 9639ac6c7..4d306337d 100644
--- a/unity/Assets/Scripts/UI/HudPresenter.cs
+++ b/unity/Assets/Scripts/UI/HudPresenter.cs
@@ -91,7 +91,7 @@ namespace Statecraft.Game.UI
/// owner's second answer, 15 October 2026). The plate keeps its width; the turn and the date take a line each, and the
/// plate grows.</summary>
readonly List<Label> plateText;
- readonly VisualElement? dateRow;
+ readonly VisualElement? dateRow, captionRow;
/// <summary>The plate's padding while the floor raises its text (the stylesheet's is 2 px top and bottom, 10-12 at the
/// sides): PlateSidePx at both sides keeps every line at least 0 px from the 18 px corner zones (TopBarTests), each the
/// corner scrolls' reach (about 14 px in) plus 4, and PlateEdgePx at the top and bottom keeps it inside the frame's
@@ -101,6 +101,7 @@ namespace Statecraft.Game.UI
readonly VisualElement turnBox;
readonly IVisualElementScheduledItem floorCheck;
float smallTextSize = SmallTextPx;
+ bool captionFitWrap;
/// <summary>The left icon column (promo 03): the screens' buttons (ScreenNav.Screens).</summary>
public const string RailName = "left-column";
@@ -164,6 +165,7 @@ namespace Statecraft.Game.UI
barItems = bar.Children().ToList();
foreach (var k in barItems) k.RegisterCallback<GeometryChangedEvent>(OnRowGeometry); // a row grows inside the fixed bar
dateRow = bar.Q<VisualElement>(className: "date-row");
+ captionRow = bar.Q(className: "meter-caption-row");
plateText = dateRow?.Query<Label>().ToList() ?? new List<Label>();
dateRow?.parent?.RegisterCallback<GeometryChangedEvent>(OnPlateGeometry); // a wider raised plate needs room in the bar
ApplyTextFloor();
@@ -179,6 +181,7 @@ namespace Statecraft.Game.UI
railTips?.Dispose(); barTips?.Dispose(); meterTip?.Dispose();
floorCheck.Pause();
foreach (var l in smallText) { l.style.fontSize = StyleKeyword.Null; l.style.whiteSpace = StyleKeyword.Null; l.style.maxWidth = StyleKeyword.Null; }
+ if (captionRow != null) captionRow.style.flexWrap = StyleKeyword.Null;
turnBox.style.width = StyleKeyword.Null; turnBox.style.minWidth = StyleKeyword.Null;
foreach (var k in barItems) k.UnregisterCallback<GeometryChangedEvent>(OnRowGeometry);
foreach (var e in underBar) e.style.marginTop = StyleKeyword.Null;
@@ -201,7 +204,11 @@ namespace Statecraft.Game.UI
// plate's width does not depend on the tier, so this settles in one pass.
void OnPlateGeometry(GeometryChangedEvent e) { if (smallTextSize > SmallTextPx && e.oldRect.width != e.newRect.width) SetCompact(bar.layout.width); }
- void OnMeterGeometry(GeometryChangedEvent e) => UpdateRoomy();
+ void OnMeterGeometry(GeometryChangedEvent e)
+ {
+ UpdateRoomy();
+ if (smallTextSize > SmallTextPx && bar.ClassListContains(CompactClass)) SetCompact(bar.layout.width);
+ }
// The rows' height does not depend on the bar's (RowsHeight), so this settles in one pass.
void OnRowGeometry(GeometryChangedEvent e) => PlaceUnderBar();
@@ -296,8 +303,10 @@ namespace Statecraft.Game.UI
l.style.fontSize = raised ? new StyleLength(smallTextSize) : new StyleLength(StyleKeyword.Null);
if (l.name == "attention") continue;
l.style.whiteSpace = oneLine ? new StyleEnum<WhiteSpace>(WhiteSpace.NoWrap) : new StyleEnum<WhiteSpace>(StyleKeyword.Null);
- l.style.maxWidth = oneLine ? new StyleLength(StyleKeyword.None) : new StyleLength(StyleKeyword.Null);
+ l.style.maxWidth = oneLine || captionFitWrap ? new StyleLength(StyleKeyword.None) : new StyleLength(StyleKeyword.Null);
}
+ if (captionRow != null) captionRow.style.flexWrap = captionFitWrap
+ ? new StyleEnum<Wrap>(Wrap.Wrap) : new StyleEnum<Wrap>(StyleKeyword.Null);
foreach (var l in plateText)
{
l.style.fontSize = raised ? new StyleLength(smallTextSize) : new StyleLength(StyleKeyword.Null);
@@ -373,6 +382,40 @@ namespace Statecraft.Game.UI
static float DevicePixelRatio() => 1f;
#endif
+ // Compact raised captions need their intrinsic group width, not the shrunken meter-body allocation.
+ // Security and its level share a row; the fit-triggered two-row tier lets that group wrap.
+ bool CaptionsNeedAnotherRow(float width)
+ {
+ float Sides(VisualElement e)
+ {
+ var s = e.resolvedStyle;
+ return s.paddingLeft + s.paddingRight + s.borderLeftWidth + s.borderRightWidth;
+ }
+ float Margins(VisualElement e) => e.resolvedStyle.marginLeft + e.resolvedStyle.marginRight;
+ float needed = Sides(bar);
+ foreach (var child in bar.Children().Where(e => e.resolvedStyle.position == Position.Relative && e.resolvedStyle.display != DisplayStyle.None))
+ {
+ if (child.name != "meters") { needed += child.layout.width + Margins(child); continue; }
+ needed += Sides(child) + Margins(child);
+ foreach (var meter in meters.Where(e => e.resolvedStyle.display != DisplayStyle.None))
+ {
+ float captions = 0f;
+ foreach (var label in meter.Query<Label>(className: "meter-name").ToList().Where(l => !string.IsNullOrEmpty(l.text)))
+ {
+ float font = label.resolvedStyle.fontSize;
+ if (!(font > 0f)) return false; // wait for the first settled geometry
+ captions += label.MeasureTextSize(label.text, 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined).x
+ * smallTextSize / font + Sides(label) + Margins(label);
+ }
+ var body = meter.Q(className: "meter-body");
+ if (body == null) return false; // a reduced tree has no complete caption-fit budget
+ needed += UnityEngine.Mathf.Max(meter.resolvedStyle.minWidth.value,
+ captions + Sides(body) + Margins(body) + Sides(meter)) + Margins(meter);
+ }
+ }
+ return needed > width;
+ }
+
void SetCompact(float width)
{
if (!(width > 0)) return; // NaN before layout: wait for it
@@ -380,7 +423,8 @@ namespace Statecraft.Game.UI
var tierWidth = raised ? width - FloorGrowth() : width; // the owner's text floor needs room (#624)
bar.EnableInClassList(CompactClass, tierWidth < CompactBelowPx);
hudRoot.EnableInClassList(NarrowClass, tierWidth < NarrowBelowPx || raised && smallTextSize > OneRowSmallMaxPx);
- hudRoot.EnableInClassList(TwoRowClass, width < TwoRowBelowPx);
+ captionFitWrap = raised && width >= TwoRowBelowPx && bar.ClassListContains(CompactClass) && CaptionsNeedAnotherRow(width);
+ hudRoot.EnableInClassList(TwoRowClass, width < TwoRowBelowPx || captionFitWrap);
hudRoot.EnableInClassList(ThreeRowClass, width < ThreeRowBelowPx);
StyleSmallText(raised);
PlaceUnderBar();
diff --git a/unity/Assets/Scripts/UI/SafeArea.jslib b/unity/Assets/Scripts/UI/SafeArea.jslib
new file mode 100644
index 000000000..1a656b9ca
--- /dev/null
+++ b/unity/Assets/Scripts/UI/SafeArea.jslib
@@ -0,0 +1,21 @@
+// The browser's safe-area insets in CSS pixels (the notch, the home indicator), for SafeAreaFit: a probe element reads
+// the env(safe-area-inset-*) values, which iOS Safari and Chrome on Android expose; everywhere else they are 0, so the
+// UI is padded only where hardware eats the screen. Writes top, right, bottom, left. The HEAPF32 indexing assumes
+// wasm32 pointers (Unity 6000.3's WebGL target), as WheelInput.jslib.
+mergeInto(LibraryManager.library, {
+ StatecraftSafeAreaInsets: function (out) {
+ var v = [0, 0, 0, 0];
+ if (typeof document !== "undefined" && document.body) {
+ var probe = document.createElement("div");
+ probe.style.cssText = "position:fixed;visibility:hidden;pointer-events:none;" +
+ "padding-top:env(safe-area-inset-top,0px);padding-right:env(safe-area-inset-right,0px);" +
+ "padding-bottom:env(safe-area-inset-bottom,0px);padding-left:env(safe-area-inset-left,0px);";
+ document.body.appendChild(probe);
+ var cs = getComputedStyle(probe);
+ v = [parseFloat(cs.paddingTop) || 0, parseFloat(cs.paddingRight) || 0,
+ parseFloat(cs.paddingBottom) || 0, parseFloat(cs.paddingLeft) || 0];
+ document.body.removeChild(probe);
+ }
+ for (var i = 0; i < 4; i++) HEAPF32[(out >> 2) + i] = v[i];
+ },
+});
diff --git a/unity/Assets/Scripts/UI/SafeArea.jslib.meta b/unity/Assets/Scripts/UI/SafeArea.jslib.meta
new file mode 100644
index 000000000..901343c51
--- /dev/null
+++ b/unity/Assets/Scripts/UI/SafeArea.jslib.meta
@@ -0,0 +1,32 @@
+fileFormatVersion: 2
+guid: 9dcd8894fe1c22a256b797de5cf7ad65
+PluginImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ iconMap: {}
+ executionOrder: {}
+ defineConstraints: []
+ isPreloaded: 0
+ isOverridable: 0
+ isExplicitlyReferenced: 0
+ validateReferences: 1
+ platformData:
+ - first:
+ Any:
+ second:
+ enabled: 0
+ settings: {}
+ - first:
+ Editor: Editor
+ second:
+ enabled: 0
+ settings:
+ DefaultValueInitialized: true
+ - first:
+ WebGL: WebGL
+ second:
+ enabled: 1
+ settings: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Scripts/UI/SafeAreaFit.cs b/unity/Assets/Scripts/UI/SafeAreaFit.cs
new file mode 100644
index 000000000..581c758f7
--- /dev/null
+++ b/unity/Assets/Scripts/UI/SafeAreaFit.cs
@@ -0,0 +1,84 @@
+#nullable enable
+using UnityEngine;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>Keeps the HUD and the panels inside the phone's safe area: on a notched phone the top bar otherwise sits
+ /// under the notch and the bottom buttons under the home indicator (mobile audit). Pads the root by the safe area's
+ /// insets, in panel px, and lets the layout do the rest: every panel is positioned from the root's edges, the taller
+ /// top bar flows into the camera's inset through TopBarInset as before, and the map labels re-place from their
+ /// layer's moved origin (MapLabelsPresenter.Refresh measures container.worldBound). A desktop or a notch-free phone
+ /// has no insets, so nothing changes there.</summary>
+ public sealed class SafeAreaFit : System.IDisposable
+ {
+ readonly VisualElement root;
+ readonly System.Func<(float l, float r, float t, float b)>? readInsets; // tests feed the insets; production reads the platform
+ IVisualElementScheduledItem? poll;
+ float appliedL = -1f, appliedR, appliedT, appliedB; // an impossible start: the first Update always writes
+
+ public SafeAreaFit(VisualElement root) : this(root, null) { }
+
+ internal SafeAreaFit(VisualElement root, System.Func<(float l, float r, float t, float b)>? readInsets)
+ {
+ this.root = root;
+ this.readInsets = readInsets;
+ root.RegisterCallback<GeometryChangedEvent>(OnGeometry); // a rotation usually moves the notch with the bounds
+ // ...but not always: two landscapes of the same dimensions swap the notch side with the root bounds
+ // unchanged and no event fires, so poll every frame; Apply writes only on a change.
+ poll = root.schedule.Execute(Update).Every(0);
+ Update();
+ }
+
+ void OnGeometry(GeometryChangedEvent e) => Update();
+
+ public void Update()
+ {
+ if (readInsets != null) { var v = readInsets(); Apply(v.l, v.r, v.t, v.b); return; }
+ var panel = root.panel;
+ if (panel == null) return;
+ float scale = panel.scaledPixelsPerPoint;
+#if UNITY_WEBGL && !UNITY_EDITOR
+ // The browser's env(safe-area-inset-*) values come in CSS px (SafeArea.jslib); the canvas is drawn in device
+ // pixels, so a CSS px is devicePixelRatio device px (HudPresenter's text floor divides by the same ratio).
+ var css = new float[4];
+ StatecraftSafeAreaInsets(css);
+ float dpr = StatecraftDevicePixelRatio();
+ Apply(Panel(css[3], dpr, scale), Panel(css[1], dpr, scale), Panel(css[0], dpr, scale), Panel(css[2], dpr, scale));
+#else
+ // Screen.safeArea's margins in device px; the editor and desktops get the whole screen, so all four are 0.
+ var safe = Screen.safeArea;
+ Apply(PanelPx(safe.xMin, scale), PanelPx(Screen.width - safe.xMax, scale),
+ PanelPx(Screen.height - safe.yMax, scale), PanelPx(safe.yMin, scale));
+#endif
+ }
+
+ /// <summary>Pads the root by the insets, in panel px. Idempotent (the same insets write once); Dispose resets.
+ /// The seam SafeAreaTests pins, so the padding writes and the reset cannot silently go.</summary>
+ internal void Apply(float l, float r, float t, float b)
+ {
+ if (l == appliedL && r == appliedR && t == appliedT && b == appliedB) return;
+ appliedL = l; appliedR = r; appliedT = t; appliedB = b;
+ root.style.paddingLeft = l; root.style.paddingRight = r;
+ root.style.paddingTop = t; root.style.paddingBottom = b;
+ }
+
+ /// <summary>cssPx in panel px: dpr device px per CSS px (the canvas's scale), scale device px per panel px.</summary>
+ public static int Panel(float cssPx, float dpr, float scale) => scale > 0f ? Mathf.RoundToInt(cssPx * dpr / scale) : 0;
+ /// <summary>devicePx in panel px at scale device px per panel px.</summary>
+ public static int PanelPx(float devicePx, float scale) => scale > 0f ? Mathf.RoundToInt(devicePx / scale) : 0;
+
+ public void Dispose()
+ {
+ poll?.Pause(); poll = null;
+ root.UnregisterCallback<GeometryChangedEvent>(OnGeometry);
+ root.style.paddingLeft = StyleKeyword.Null; root.style.paddingRight = StyleKeyword.Null;
+ root.style.paddingTop = StyleKeyword.Null; root.style.paddingBottom = StyleKeyword.Null;
+ }
+
+#if UNITY_WEBGL && !UNITY_EDITOR
+ [System.Runtime.InteropServices.DllImport("__Internal")] static extern void StatecraftSafeAreaInsets(float[] insets);
+ [System.Runtime.InteropServices.DllImport("__Internal")] static extern float StatecraftDevicePixelRatio();
+#endif
+ }
+}
diff --git a/unity/Assets/Scripts/UI/SafeAreaFit.cs.meta b/unity/Assets/Scripts/UI/SafeAreaFit.cs.meta
new file mode 100644
index 000000000..a51d9e21c
--- /dev/null
+++ b/unity/Assets/Scripts/UI/SafeAreaFit.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: aeda362c86e7692241ec1631b0c0fb1f
diff --git a/unity/Assets/Tests/EditMode/SafeAreaTests.cs b/unity/Assets/Tests/EditMode/SafeAreaTests.cs
new file mode 100644
index 000000000..9e330042d
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/SafeAreaTests.cs
@@ -0,0 +1,101 @@
+using System.Collections;
+using NUnit.Framework;
+using Statecraft.Game.UI;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.TestTools;
+using UnityEngine.UIElements;
+
+public class SafeAreaTests
+{
+ [Test]
+ public void CssPixelsBecomePanelPixelsAtTheDevicesRatioAndScale()
+ {
+ // a 47 px iPhone notch at 3x, the panel scaled 1.5 device px per panel px: exactly 94 panel px (no .5 boundary)
+ Assert.AreEqual(94, SafeAreaFit.Panel(47f, 3f, 1.5f));
+ Assert.AreEqual(0, SafeAreaFit.Panel(0f, 3f, 1.5f), "no inset, no padding");
+ Assert.AreEqual(0, SafeAreaFit.Panel(47f, 3f, 0f), "no scale yet, no padding");
+ }
+
+ [Test]
+ public void DevicePixelsBecomePanelPixelsOverTheScale()
+ {
+ Assert.AreEqual(40, SafeAreaFit.PanelPx(48f, 1.2f));
+ Assert.AreEqual(0, SafeAreaFit.PanelPx(48f, 0f), "no scale yet, no padding");
+ }
+
+ /// <summary>The padding itself: Apply writes it, the layout follows (the top bar clears the notch), and Dispose
+ /// puts it back. Red without the writes in Apply, and red without the reset in Dispose.</summary>
+ [UnityTest]
+ public IEnumerator TheRootIsPaddedAndDisposePutsItBack()
+ {
+ using var ui = new UiTestKit();
+ var insets = (l: 0f, r: 0f, t: 0f, b: 0f);
+ using var fit = new SafeAreaFit(ui.Root, () => insets);
+ // Let the first layout settle, then keep the reader consistent with the synthetic insets under test.
+ // The production poll remains active; it must not replace this fixture's padding with editor screen margins.
+ for (int i = 0; i < 20 && float.IsNaN(ui.Root.resolvedStyle.width); i++) yield return null;
+ yield return null; yield return null;
+ insets = (10f, 20f, 47f, 34f);
+ fit.Apply(insets.l, insets.r, insets.t, insets.b);
+ // What Apply wrote, exactly; the resolved padding snaps to the panel's pixel grid (47 -> 46.29 at this scale).
+ Assert.AreEqual(47f, ui.Root.style.paddingTop.value.value, 1e-3f, "the notch's inset pads the root");
+ Assert.AreEqual(34f, ui.Root.style.paddingBottom.value.value, 1e-3f, "the home indicator's inset");
+ Assert.AreEqual(10f, ui.Root.style.paddingLeft.value.value, 1e-3f);
+ Assert.AreEqual(20f, ui.Root.style.paddingRight.value.value, 1e-3f);
+ for (int i = 0; i < 10 && ui.Root.resolvedStyle.paddingTop < 45f; i++)
+ {
+ EditorApplication.QueuePlayerLoopUpdate();
+ yield return null;
+ }
+ Assert.AreEqual(47f, ui.Root.resolvedStyle.paddingTop, 1f, "the layout follows, snapped to the pixel grid");
+ Assert.AreEqual(34f, ui.Root.resolvedStyle.paddingBottom, 1f);
+ Assert.GreaterOrEqual(ui.Q<VisualElement>("top-bar").worldBound.yMin, 47f - 1f, "the top bar moves down out of the notch");
+ fit.Dispose();
+ Assert.AreEqual(StyleKeyword.Null, ui.Root.style.paddingTop.keyword, "Dispose resets the style");
+ Assert.AreEqual(StyleKeyword.Null, ui.Root.style.paddingLeft.keyword);
+ for (int i = 0; i < 10 && ui.Root.resolvedStyle.paddingTop > 0f; i++)
+ {
+ EditorApplication.QueuePlayerLoopUpdate();
+ yield return null;
+ }
+ Assert.AreEqual(0f, ui.Root.resolvedStyle.paddingTop, 1f, "Dispose resets the padding");
+ }
+
+ /// <summary>The review probe: two landscapes of the same dimensions swap the notch side with the root bounds
+ /// unchanged, so no GeometryChangedEvent fires. The per-frame poll still moves the padding: settle on the left,
+ /// flip to the right, and the padding follows without the test calling Update/Apply itself.</summary>
+ [UnityTest]
+ public IEnumerator InsetChangesArePickedUpWhenTheBoundsDoNotChange()
+ {
+ using var ui = new UiTestKit();
+ var insets = (l: 47f, r: 0f, t: 0f, b: 0f);
+ int reads = 0;
+ using var fit = new SafeAreaFit(ui.Root, () => { reads++; return insets; });
+ for (int i = 0; i < 20 && float.IsNaN(ui.Root.resolvedStyle.width); i++) yield return null;
+ yield return null; yield return null;
+ Assert.AreEqual(47f, ui.Root.style.paddingLeft.value.value, 1e-3f, "settled: the left inset pads the left");
+ var bounds = ui.Root.layout;
+ insets = (0f, 47f, 0f, 0f); // the notch moved to the right edge; the bounds did not change
+ // A quiet EditMode runtime panel needs player-loop requests to service scheduled callbacks.
+ for (int i = 0; i < 30; i++)
+ {
+ EditorApplication.QueuePlayerLoopUpdate();
+ yield return null;
+ }
+ Assert.AreEqual(bounds, ui.Root.layout, "the root bounds did not change");
+ Assert.AreEqual(47f, ui.Root.style.paddingRight.value.value, 1e-3f, "the poll moved the padding to the right");
+ Assert.AreEqual(0f, ui.Root.style.paddingLeft.value.value, 1e-3f, "and cleared the left");
+ fit.Dispose();
+ int stoppedReads = reads;
+ insets = (12f, 34f, 56f, 78f);
+ for (int i = 0; i < 10; i++)
+ {
+ EditorApplication.QueuePlayerLoopUpdate();
+ yield return null;
+ }
+ Assert.AreEqual(stoppedReads, reads, "Dispose stops polling the reader");
+ Assert.AreEqual(StyleKeyword.Null, ui.Root.style.paddingLeft.keyword);
+ Assert.AreEqual(StyleKeyword.Null, ui.Root.style.paddingRight.keyword);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/SafeAreaTests.cs.meta b/unity/Assets/Tests/EditMode/SafeAreaTests.cs.meta
new file mode 100644
index 000000000..f84bc4c5e
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/SafeAreaTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: d08053a410e95bde5f0075ddc1e7473c
diff --git a/unity/Assets/Tests/EditMode/TopBarTests.cs b/unity/Assets/Tests/EditMode/TopBarTests.cs
index 979d3111c..6cdceb546 100644
--- a/unity/Assets/Tests/EditMode/TopBarTests.cs
+++ b/unity/Assets/Tests/EditMode/TopBarTests.cs
@@ -57,7 +57,7 @@ public class TopBarTests
/// score in the plate. <paramref name="widest"/> false keeps the turn-1 values. <paramref name="collapsed"/> (with
/// <paramref name="withEvent"/>) hides the open card to its "Decision waiting" button, as Hide does.</summary>
static IEnumerator Rendered(int w, int h, bool hebrew, System.Action<VisualElement, UiText> check, bool widest = true, bool withEvent = false,
- bool collapsed = false)
+ bool collapsed = false, System.Func<VisualElement, IEnumerator>? afterRender = null)
{
var text = hebrew ? He : En;
var rt = new RenderTexture(w, h, 0);
@@ -110,12 +110,129 @@ public class TopBarTests
for (int i = 0; i < 8; i++) yield return null;
Assert.AreEqual(DisplayStyle.Flex, score.resolvedStyle.display, "precondition: the score shows, so its room is checked");
check(root, text);
+ if (afterRender != null) yield return afterRender(root);
}
finally
{
- card?.Dispose(); dir?.Dispose(); hud?.Dispose();
- Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
+ card?.Dispose(); dir?.Dispose();
+ try
+ {
+ var captionRow = root.Q(className: "meter-caption-row");
+ var beforeDispose = captionRow == null ? new StyleEnum<Wrap>(StyleKeyword.Null) : captionRow.style.flexWrap;
+ hud?.Dispose();
+ if (afterRender != null)
+ {
+ Assert.IsNotNull(captionRow, "the real Game.uxml has its Security caption row");
+ if (!hebrew) Assert.AreEqual(Wrap.Wrap, beforeDispose.value,
+ "precondition: inline wrapping is still active immediately before HUD Dispose");
+ Assert.AreEqual(StyleKeyword.Null, captionRow!.style.flexWrap.keyword,
+ "HUD Dispose clears its inline Security caption-row wrapping");
+ }
+ }
+ finally { Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt); }
+ }
+ }
+
+
+ [UnityTest]
+ public IEnumerator LandscapeSafeInsetsKeepCaptionInkDisjoint()
+ {
+ var problems = new List<string>();
+ foreach (bool he in new[] { false, true })
+ foreach (bool widest in new[] { false, true })
+ yield return Rendered(844, 390, he, (root, text) => { }, widest: widest,
+ afterRender: root => CaptionInsetPhases(root, he, widest, problems));
+ Assert.IsEmpty(problems, string.Join("\n", problems));
+ }
+
+ static IEnumerator CaptionInsetPhases(VisualElement root, bool he, bool widest, List<string> problems)
+ {
+ var css = (l: 0f, r: 0f);
+ int reads = 0;
+ using var fit = new SafeAreaFit(root, () =>
+ {
+ reads++;
+ float scale = root.panel.scaledPixelsPerPoint;
+ return (SafeAreaFit.Panel(css.l, 1f, scale), SafeAreaFit.Panel(css.r, 1f, scale), 0f, 0f);
+ });
+ Rect viewport = default, startingBar = default;
+ string startingClasses = "";
+ var bar = root.Q("top-bar");
+ var inner = root.Q("root");
+ string Classes() => string.Join(",", inner.GetClasses().OrderBy(c => c)) + "/" + string.Join(",", bar.GetClasses().OrderBy(c => c));
+ foreach (var phase in new (string name, float l, float r)[]
+ { ("zero", 0f, 0f), ("left47", 47f, 0f), ("right47", 0f, 47f), ("restored", 0f, 0f) })
+ {
+ css = (phase.l, phase.r);
+ int previousReads = reads;
+ string settledClasses = "";
+ float settledHeight = 0f;
+ for (int i = 0; i < 40; i++)
+ {
+ EditorApplication.QueuePlayerLoopUpdate(); yield return null;
+ if (i == 29) { settledClasses = Classes(); settledHeight = bar.layout.height; }
+ if (i >= 30)
+ {
+ Assert.AreEqual(settledClasses, Classes(), phase.name + ": final ten frames keep the settled tiers");
+ Assert.AreEqual(settledHeight, bar.layout.height, 1e-3f, phase.name + ": final ten frames keep the settled bar height");
+ }
+ }
+ Assert.Greater(reads, previousReads, "the actual scheduled reader must run");
+ float scale = root.panel.scaledPixelsPerPoint;
+ Assert.AreEqual(844f, root.worldBound.width * scale, 2f);
+ Assert.AreEqual(390f, root.worldBound.height * scale, 2f);
+ Assert.AreEqual(SafeAreaFit.Panel(css.l, 1f, scale), root.resolvedStyle.paddingLeft, 2f);
+ Assert.AreEqual(SafeAreaFit.Panel(css.r, 1f, scale), root.resolvedStyle.paddingRight, 2f);
+ if (phase.name == "zero") { viewport = root.worldBound; startingBar = bar.worldBound; startingClasses = Classes(); }
+ else Assert.AreEqual(viewport, root.worldBound, "stable viewport throughout side-inset changes");
+ if (phase.name == "restored")
+ {
+ Assert.AreEqual(startingClasses, Classes(), "removing the inset restores the original tiers");
+ Assert.AreEqual(startingBar, bar.worldBound, "removing the inset restores original bar bounds");
+ }
+ string at = $"{(he ? "he" : "en")} widest={widest} {phase.name}";
+ var labels = root.Q("top-bar").Query<Label>(className: "meter-name").ToList()
+ .Where(l => Shown(l) && !string.IsNullOrEmpty(l.text)).ToList();
+ Assert.AreEqual(8, labels.Count, "seven captions and Security level must be exercised");
+ var ink = new List<(Label label, Rect bounds)>();
+ foreach (var l in labels)
+ {
+ float fontCss = l.resolvedStyle.fontSize * scale;
+ if (fontCss < 11.95f) problems.Add($"{at}: '{l.text}' below12px floor: {fontCss}");
+ var box = l.contentRect;
+ var natural = l.MeasureTextSize(l.text, 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined);
+ bool wrap = l.resolvedStyle.whiteSpace == WhiteSpace.Normal;
+ var measured = wrap ? l.MeasureTextSize(l.text, box.width, VisualElement.MeasureMode.Exactly, 0, VisualElement.MeasureMode.Undefined) : natural;
+ float width = wrap ? Mathf.Min(natural.x, box.width) : natural.x;
+ float x = box.x;
+ var align = l.resolvedStyle.unityTextAlign;
+ if (align == TextAnchor.UpperRight || align == TextAnchor.MiddleRight || align == TextAnchor.LowerRight) x += box.width - width;
+ else if (align == TextAnchor.UpperCenter || align == TextAnchor.MiddleCenter || align == TextAnchor.LowerCenter) x += (box.width - width) / 2f;
+ var origin = l.LocalToWorld(new Vector2(x, box.y));
+ var r = new Rect(origin.x, origin.y, width, measured.y);
+ ink.Add((l, r));
+ foreach (var word in l.text.Split(' '))
+ if (wrap && l.MeasureTextSize(word, 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined).x > box.width + 1f / scale)
+ problems.Add($"{at}: '{word}' would break inside a word");
+ if (!Inside(r, root.Q("top-bar").worldBound, 1f / scale)) problems.Add($"{at}: '{l.text}' leaves usable bar");
+ TestContext.WriteLine($"CAPTIONINK {at} '{l.text}' bounds={r} box={l.worldBound} fontCSS={fontCss}");
+ }
+ for (int i = 0; i < ink.Count; i++)
+ for (int j = i + 1; j < ink.Count; j++)
+ {
+ var a = ink[i].bounds; var b = ink[j].bounds;
+ float x = Mathf.Min(a.xMax, b.xMax) - Mathf.Max(a.xMin, b.xMin);
+ float y = Mathf.Min(a.yMax, b.yMax) - Mathf.Max(a.yMin, b.yMin);
+ if (x * scale > 0.5f && y * scale > 0.5f)
+ problems.Add($"{at}: '{ink[i].label.text}' overlaps '{ink[j].label.text}' by{x * scale}CSSpx");
+ }
}
+ // Leave the real EN fit-triggered wrapping active so the fixture's Dispose assertion is not vacuous.
+ css = (47f, 0f);
+ for (int i = 0; i < 40; i++) { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }
+ if (!he)
+ Assert.AreEqual(Wrap.Wrap, root.Q(className: "meter-caption-row").style.flexWrap.value,
+ "precondition: real scheduled left inset activated inline caption-row wrapping before Dispose");
}
/// <summary>A label's text fits its box: on one line, or wrapped within its height (InfoPanelLayoutTests).</summary>