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.

21.5 KB
Raw Blame
#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Statecraft.Game.Map;
using Statecraft.Sim;
using UnityEngine;
using UnityEngine.UIElements;

namespace Statecraft.Game.UI
{
    /// <summary>The Settings screen (#40), opened from the left column's gear like the other screens (ScreenNav). Its options:
    /// the graphics quality (GraphicsQuality: Auto / High / Low), the sound effects volume (GameAudio, #39), the start menu's music
    /// volume (MenuMusic, #39), the UI's language (#1036),
    /// the UI scale (100% / 125% / 150%), the tilt-shift blur, the WebGL companion (#1119, its row only where a page shows it) and a Community row whose "Star on GitHub" opens the repository
    /// (#1168, ExternalLink). The blur option turns it off and on: applied at once (TiltShift.Enabled, what the "tiltshift"
    /// toggle sets) and kept in the SettingsStore, so it holds after a reload. A stored "off" only ever turns the blur off, so ?notiltshift still boots without it. The
    /// button says what is set ("On" / "Off"), not only a colour: the player's choice (Enabled), not the web tier's
    /// automatic fallback's tilt-shift step (TiltShift.FallbackOff), which it never changes.</summary>
    public sealed class SettingsPresenter : IDisposable
    {
        public const string TiltShiftKey = "tiltshift", QualityKey = "quality", LanguageKey = "lang", UiScaleKey = "uiscale", SoundKey = "sfx", MusicKey = "music", CompanionKey = "companion", EnemyMovesKey = "enemymoves", SelectedClass = "settings-choice-selected";
        /// <summary>The owner's UI scales (#40, 18 Oct 2026), in percent; the first is the default.</summary>
        public static readonly int[] UiScales = { 100, 125, 150 };
        /// <summary>The owner's ruling on #1011 (19 Oct 2026): Settings offers only the UI scales verified to fit, and 100% always,
        /// as the fallback. A scale above 100% is verified on the window shapes (width / height, narrowest to widest) where
        /// the layout suites pass with the panel at that scale: UiLayoutTests, InfoPanelLayoutTests, TopBarScoreLayoutTests,
        /// HebrewUiTests, LeftColumnTests, PromoScreensTests and TopBarTests, with the turn report (TurnReportTests) and the
        /// encyclopedia (EncyclopediaScreenTests) as the owner ruled on #2219. Since #1853 they pass at 125% and at 150% (#40,
        /// 2 Nov 2026), and the screens, the event card, the info panel, the turn report and the encyclopedia all run in
        /// English and Hebrew at both ends of the range, 360x800 and 2560x1080 (the budget rows' own test runs 1920 and 390
        /// wide), so both scales are verified on the shapes between them. A layout change that breaks a suite at a scale narrows or removes its entry.
        /// Tests enter shapes here to drive the rule and put the table back.</summary>
        public static readonly Dictionary<int, (float narrowest, float widest)> VerifiedShapes = new Dictionary<int, (float, float)>
        {
            [125] = (360f / 800f, 2560f / 1080f),
            [150] = (360f / 800f, 2560f / 1080f),
        };
        /// <summary>The sound effects' volume steps (#39): the stored word and GameAudio's volume. With no stored choice, "high".</summary>
        public static readonly (string level, float volume)[] SoundLevels = { ("off", 0f), ("low", 0.35f), ("high", 1f) };
        /// <summary>The Music row's step with no stored choice (owner, #2297, 2 Nov 2026: "Low by default (Recommended)").</summary>
        public const string MusicDefault = "low";
        readonly SettingsStore? store; readonly UiText text; readonly VisualElement root, screen; readonly Button tiltShift;
        readonly (Button button, GraphicsQuality.Choice choice, Action pick)[] quality;
        readonly LanguageButtons languages;
        readonly (Button button, string level, Action pick)[] sound;
        readonly (Button button, string level, Action pick)[] musicLevels;
        readonly MenuMusic? music;
        string musicLevel;
        readonly AdvisorSettings? advisors;
        readonly (Button button, string level, Action pick)[] helpLevels;
        readonly GameAudio? audio;
        string soundLevel;
        readonly PanelSettings? panel; readonly Vector2Int reference; int uiScale = UiScales[0], chosen = UiScales[0];
        readonly (Button button, int percent, Action pick)[] scales;
        readonly Action unbindStar, unbindQuit;
        readonly Button quit;
        /// <summary>True between Quit's first press, which asks, and its second, which quits (#2188).</summary>
        bool quitAsked;
        readonly Button companionSwitch;
        readonly (Func<bool> on, Action<bool> set)? companion;
        readonly Button enemyMoves;
        readonly Action<bool>? setEnemyMoves;
        bool enemyMovesOn;

        /// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Task 7): whether End turn plays the
        /// enemy's moves on the map (EnemyTurnPlayback). On unless the player turned it off (the stored "off").</summary>
        public static bool EnemyMovesOn(SettingsStore? store) => store?.Read(EnemyMovesKey) != "off";

        /// <param name="store">Where the choice is kept; null keeps nothing (the option still works until the page closes).</param>
        /// <param name="switchLanguage">Puts the UI in the language pressed (GameRoot builds the screens again); null changes
        /// nothing but the stored choice, read at the next start.</param>
        /// <param name="panel">The UI's panel, which the UI scale scales; null leaves the scale alone.</param>
        /// <param name="advisors">The live advisor settings; null hides its row.</param>
        /// <param name="audio">The sound effects the volume applies to; null keeps only the choice.</param>
        /// <param name="companion">The WebGL companion (#1119, WebCompanion): whether it runs, and what turns it on or off at
        /// once; null (no page to show it in) hides its row.</param>
        /// <param name="music">The start menu's music the Music volume applies to; null keeps only the choice.</param>
        /// <param name="enemyMoves">Told the enemy-moves switch's new value at once (#2202: off skips a playback that plays);
        /// null keeps only the choice, read at the next End turn.</param>
        public SettingsPresenter(VisualElement root, UiText text, SettingsStore? store, Action<string>? switchLanguage = null, PanelSettings? panel = null, GameAudio? audio = null, AdvisorSettings? advisors = null,
            (Func<bool> on, Action<bool> set)? companion = null, MenuMusic? music = null, Action<bool>? enemyMoves = null)
        {
            this.store = store; this.text = text; this.root = root; this.audio = audio; this.advisors = advisors; this.companion = companion; this.music = music;
            screen = root.Q<VisualElement>("screen-settings");
            screen.Q<Label>("settings-screen-title").text = text["settings.title"];
            screen.Q<Label>("settings-tiltshift-label").text = text["settings.tiltshift"];
            tiltShift = screen.Q<Button>("settings-tiltshift");
            if (store?.Read(TiltShiftKey) == "off") TiltShift.Enabled = false;
            tiltShift.clicked += Flip;
            screen.Q<Label>("settings-enemymoves-label").text = text["settings.enemymoves"];
            this.enemyMoves = screen.Q<Button>("settings-enemymoves");
            setEnemyMoves = enemyMoves;
            enemyMovesOn = EnemyMovesOn(store);
            this.enemyMoves.clicked += FlipEnemyMoves;
            // Graphics quality (#40): three buttons, the one that is set marked. A stored choice is applied at start unless
            // an instrument flag must see the tier's own look (GraphicsQuality.AtStart); Auto at start changes nothing.
            screen.Q<Label>("settings-quality-label").text = text["settings.quality"];
            var choices = new[] { GraphicsQuality.Choice.Auto, GraphicsQuality.Choice.High, GraphicsQuality.Choice.Low };
            quality = Array.ConvertAll(choices, c =>
            {
                var key = GraphicsQuality.Format(c);
                var b = screen.Q<Button>("settings-quality-" + key);
                b.text = text["settings.quality." + key];
                Action pick = () => Pick(c);
                b.clicked += pick;
                return (b, c, pick);
            });
            var start = GraphicsQuality.AtStart(store?.Read(QualityKey), Application.absoluteURL, Environment.GetCommandLineArgs(),
                Application.platform == RuntimePlatform.WebGLPlayer);
            if (start != GraphicsQuality.Current) GraphicsQuality.Apply(start);
            // The UI's language (#1036): the same buttons as the start screen's (LanguageButtons), the one in use marked.
            screen.Q<Label>("settings-language-label").text = text["settings.language"];
            languages = new LanguageButtons(screen, "settings-language-", text["ui.lang"], store, switchLanguage);
            // Sound effects (#39): three volume steps, the one that is set marked, applied to GameAudio at once and kept.
            screen.Q<Label>("settings-sound-label").text = text["settings.sound"];
            var storedSound = store?.Read(SoundKey);
            soundLevel = Array.Exists(SoundLevels, l => l.level == storedSound) ? storedSound! : "high";
            ApplySound();
            sound = Array.ConvertAll(SoundLevels, l =>
            {
                var b = screen.Q<Button>("settings-sound-" + l.level);
                b.text = text["settings.sound." + l.level];
                Action pick = () => PickSound(l.level);
                b.clicked += pick;
                return (b, l.level, pick);
            });
            // Music (#39, MenuMusic): the same three steps as the sound effects, kept apart from them. With no stored choice,
            // "low", the owner's ruling on #2297 (2 Nov 2026): "Low by default (Recommended)", "35% volume: the theme sits
            // under the menu".
            screen.Q<Label>("settings-music-label").text = text["settings.music"];
            var storedMusic = store?.Read(MusicKey);
            musicLevel = Array.Exists(SoundLevels, l => l.level == storedMusic) ? storedMusic! : MusicDefault;
            ApplyMusic();
            musicLevels = Array.ConvertAll(SoundLevels, l =>
            {
                var b = screen.Q<Button>("settings-music-" + l.level);
                b.text = text["settings.music." + l.level];
                Action pick = () => PickMusic(l.level);
                b.clicked += pick;
                return (b, l.level, pick);
            });
            // The help level is presentation-only and read live by the advisor queue (spec6).
            var helpLabel = screen.Q<Label>("settings-advisors-label");
            helpLabel.text = text["settings.advisors"];
            if (advisors == null) helpLabel.parent.style.display = DisplayStyle.None;
            helpLevels = Array.ConvertAll(AdvisorSettings.Levels, level =>
            {
                var b = screen.Q<Button>("settings-advisors-" + level);
                b.text = text["settings.advisors." + level];
                Action pick = () => { advisors?.SetLevel(level); Show(); };
                b.clicked += pick;
                return (b, level, pick);
            });
            // UI scale (#40): the panel scales with the screen from its 1920x1080 reference (ScaleWithScreenSize); dividing the
            // reference by the choice multiplies that scale by it, whatever the window. The whole UI is one panel. Dispose
            // puts the reference back: in the editor the panel is a project asset, and a choice must not stay in it.
            this.panel = panel;
            reference = panel != null ? panel.referenceResolution : default;
            screen.Q<Label>("settings-uiscale-label").text = text["settings.uiscale"];
            scales = Array.ConvertAll(UiScales, percent =>
            {
                var b = screen.Q<Button>("settings-uiscale-" + percent);
                b.text = PlayerText.Percent(Level(percent));
                Action pick = () => PickScale(percent);
                b.clicked += pick;
                return (b, percent, pick);
            });
            var storedScale = store?.Read(UiScaleKey);
            int startScale = Array.Find(UiScales, p => p.ToString(CultureInfo.InvariantCulture) == storedScale);   // 0 when the file names none of them
            chosen = startScale > 0 ? startScale : UiScales[0];
            ApplyScale(Fits(chosen) ? chosen : UiScales[0]);
            // The fit depends on the window's shape, which a resize changes: the offer and the applied scale follow the
            // root's geometry (as TopBarInset does). The file keeps the choice, so a shape that holds it again gets it back.
            root.RegisterCallback<GeometryChangedEvent>(OnGeometry);
            // The WebGL companion (#1119): off unless the player turns it on here or the address asks for it (WebCompanion.On).
            // Unavailable for now (WebCompanion.Available, owner 2 Nov 2026): GameRoot passes no switch, so the row stays hidden.
            screen.Q<Label>("settings-companion-label").text = text["settings.companion"];
            companionSwitch = screen.Q<Button>("settings-companion");
            if (companion == null) companionSwitch.parent.style.display = DisplayStyle.None;
            else companionSwitch.parent.style.display = StyleKeyword.Null;   // GameRoot reuses the tree an earlier Begin hid it in
            companionSwitch.clicked += FlipCompanion;
            // Community (#1168): Star on GitHub opens the repository in a new tab.
            screen.Q<Label>("settings-community-label").text = text["settings.community"];
            var star = screen.Q<Button>("settings-star");
            star.text = text["community.star"];
            unbindStar = ExternalLink.Bind(star, ExternalLink.Repository);
            // Quit (#2153: desktop players only) asks first (#2188, the owner: "Ask to confirm (Recommended)"): the first
            // press puts the question in the button's place and the second quits, the two presses New game uses
            // (NewGamePresenter). Opening Settings again withdraws the question.
            quit = screen.Q<Button>("settings-quit");
            quit.text = text["ui.quit"];
            unbindQuit = QuitButton.Bind(quit, QuitButton.Platform(), PressQuit, screen.Q("settings-quit-row"));
            ScreenNav.OnOpened(screen, () => { WithdrawQuit(); Show(); });   // a dev toggle may have changed it while the screen was shut
            Show();
        }

        public void Dispose()
        {
            tiltShift.clicked -= Flip;
            enemyMoves.clicked -= FlipEnemyMoves;
            companionSwitch.clicked -= FlipCompanion;
            foreach (var (b, _, pick) in quality) b.clicked -= pick;
            languages.Dispose();
            foreach (var (b, _, pick) in sound) b.clicked -= pick;
            foreach (var (b, _, pick) in musicLevels) b.clicked -= pick;
            foreach (var (b, _, pick) in scales) b.clicked -= pick;
            foreach (var (b, _, pick) in helpLevels) b.clicked -= pick;
            unbindStar();
            unbindQuit();
            root.UnregisterCallback<GeometryChangedEvent>(OnGeometry);
            if (panel != null) panel.referenceResolution = reference;
            if (screen.userData is Action) screen.userData = null;
        }

        void PressQuit()
        {
            if (!quitAsked) { quitAsked = true; quit.text = text["ui.quit_confirm"]; return; }
            WithdrawQuit();
            QuitButton.Quitter();
        }

        void WithdrawQuit() { quitAsked = false; quit.text = text["ui.quit"]; }

        void FlipCompanion()
        {
            if (companion is not { } c) return;
            bool on = !c.on();
            c.set(on);
            Show();
            try { store?.Write(CompanionKey, on ? "on" : "off"); }
            catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
            {
                Debug.LogWarning($"Settings: could not keep the companion choice ({e.Message}); it holds until the page is closed");
            }
        }

        void FlipEnemyMoves()
        {
            enemyMovesOn = !enemyMovesOn;
            Show();
            setEnemyMoves?.Invoke(enemyMovesOn);
            try { store?.Write(EnemyMovesKey, enemyMovesOn ? "on" : "off"); }
            catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
            {
                Debug.LogWarning($"Settings: could not keep the enemy-moves choice ({e.Message}); it holds until the page is closed");
            }
        }

        void Flip()
        {
            TiltShift.Enabled = !TiltShift.Enabled;
            Show();
            try { store?.Write(TiltShiftKey, TiltShift.Enabled ? "on" : "off"); }
            catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
            {
                Debug.LogWarning($"Settings: could not keep the tilt-shift choice ({e.Message}); it holds until the page is closed");
            }
        }

        void Pick(GraphicsQuality.Choice c)
        {
            if (c == GraphicsQuality.Current) return;   // pressing Automatic again must not undo the fallback's step down
            GraphicsQuality.Apply(c);
            Show();
            try { store?.Write(QualityKey, GraphicsQuality.Format(GraphicsQuality.Current)); }
            catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
            {
                Debug.LogWarning($"Settings: could not keep the quality choice ({e.Message}); it holds until the page is closed");
            }
        }

        void PickSound(string level)
        {
            soundLevel = level;
            ApplySound();
            Show();
            try { store?.Write(SoundKey, level); }
            catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
            {
                Debug.LogWarning($"Settings: could not keep the sound choice ({e.Message}); it holds until the page is closed");
            }
        }

        void ApplySound()
        {
            if (audio != null) audio.Volume = Array.Find(SoundLevels, l => l.level == soundLevel).volume;
        }

        void PickMusic(string level)
        {
            musicLevel = level;
            ApplyMusic();
            Show();
            try { store?.Write(MusicKey, level); }
            catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
            {
                Debug.LogWarning($"Settings: could not keep the music choice ({e.Message}); it holds until the page is closed");
            }
        }

        void ApplyMusic()
        {
            if (music != null) music.Volume = Array.Find(SoundLevels, l => l.level == musicLevel).volume;
        }

        void PickScale(int percent)
        {
            chosen = percent;
            ApplyScale(percent);
            Show();
            try { store?.Write(UiScaleKey, percent.ToString(CultureInfo.InvariantCulture)); }
            catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
            {
                Debug.LogWarning($"Settings: could not keep the UI scale ({e.Message}); it holds until the page is closed");
            }
        }

        /// <summary>A UI scale's level (1.25 for 125%): the stored values and the buttons' names are whole percents.</summary>
        static double Level(int percent) => percent / 100.0;

        /// <summary>Whether the scale is verified to fit this window (VerifiedShapes); 100% always is. Before the first
        /// layout the shape is unknown and a verified scale counts: nothing is drawn yet, and OnGeometry checks again.</summary>
        bool Fits(int percent)
        {
            if (percent == UiScales[0]) return true;
            if (!VerifiedShapes.TryGetValue(percent, out var shapes)) return false;
            float shape = root.layout.width / root.layout.height;
            // A tolerance on both ends (#2219 review): the root's layout is in panel units after scaling, so a window exactly
            // at an end of the range can come out a last bit outside it.
            return !(shape > 0) || (shape >= shapes.narrowest - 1e-4f && shape <= shapes.widest + 1e-4f);
        }

        void OnGeometry(GeometryChangedEvent e)
        {
            var fit = Fits(chosen) ? chosen : UiScales[0];
            if (fit != uiScale) ApplyScale(fit);
            Show();
        }

        void ApplyScale(int percent)
        {
            uiScale = percent;
            var level = Level(percent);
            if (panel != null)
                panel.referenceResolution = new Vector2Int(Mathf.RoundToInt((float)(reference.x / level)), Mathf.RoundToInt((float)(reference.y / level)));
        }

        void Show()
        {
            tiltShift.text = text[TiltShift.Enabled ? "settings.on" : "settings.off"];
            enemyMoves.text = text[enemyMovesOn ? "settings.on" : "settings.off"];
            companionSwitch.text = text[companion?.on() == true ? "settings.on" : "settings.off"];
            foreach (var (b, c, _) in quality) b.EnableInClassList(SelectedClass, c == GraphicsQuality.Current);
            languages.Mark();
            foreach (var (b, l, _) in sound) b.EnableInClassList(SelectedClass, l == soundLevel);
            foreach (var (b, l, _) in musicLevels) b.EnableInClassList(SelectedClass, l == musicLevel);
            foreach (var (b, level, _) in helpLevels) b.EnableInClassList(SelectedClass, level == advisors?.Level);
            foreach (var (b, p, _) in scales)
            {
                b.EnableInClassList(SelectedClass, p == uiScale);
                b.style.display = Fits(p) ? DisplayStyle.Flex : DisplayStyle.None;
            }
        }
    }
}