using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Meta;
using KernelPanic.Run;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.UIElements;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace KernelPanic.UI
{
internal static class TerminalFontResolver
{
private static readonly string[] PreferredMonospaceFontFamilies =
{
"Consolas",
"Cascadia Mono",
"Menlo",
"Monaco",
"DejaVu Sans Mono",
"Liberation Mono",
"Ubuntu Mono",
"Courier New"
};
private static FontAsset _runtimeMonospaceFont;
private static bool _warnedMissingFont;
public static FontAsset Resolve(FontAsset configuredFont)
{
if (configuredFont != null)
{
return configuredFont;
}
if (_runtimeMonospaceFont != null)
{
return _runtimeMonospaceFont;
}
Font dynamicFont = Font.CreateDynamicFontFromOSFont(PreferredMonospaceFontFamilies, 16);
if (dynamicFont == null)
{
if (!_warnedMissingFont)
{
Debug.LogWarning("No monospace OS font found; terminal UI will use Unity's default font.");
_warnedMissingFont = true;
}
return null;
}
_runtimeMonospaceFont = FontAsset.CreateFontAsset(dynamicFont);
return _runtimeMonospaceFont;
}
}
///
/// Binds the main menu terminal UI document and routes command activation between panels.
///
[RequireComponent(typeof(UIDocument))]
public sealed class MainMenuController : MonoBehaviour
{
private const string HiddenClassName = "hidden";
private const string SelectedClassName = "selected";
private const string CursorOnClassName = "cursor-on";
private const string ModalOpenClassName = "modal-open";
private const int ModalTransitionMs = 160;
private const string SharedScrollbarStyleResourcePath = "TerminalScrollbars";
private const string SharedRarityStyleResourcePath = "RarityPresentation";
private const float BootIntroSeconds = 1.5f;
private static bool _bootIntroPlayed;
// Static fields don't reset between Play sessions when the Editor's "Reload Domain"
// option is disabled. RuntimeInitializeOnLoadMethod runs once per player/Play-mode
// startup regardless of that setting, so this keeps bootIntroPlayed session-scoped.
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
private static void ResetSessionState()
{
_bootIntroPlayed = false;
}
[SerializeField] private FontAsset monospaceFont;
[SerializeField] private string motdBody = "unstable userspace detected; keep a rollback shell open.";
[SerializeField] private DistroDatabase distroDatabase;
[SerializeField] private CardDatabase cardDatabase;
[SerializeField] private PackageDatabase packageDatabase;
[SerializeField] private LanguageDeckDatabase languageDeckDatabase;
[SerializeField] private FeaturedUnitPanel featuredUnitPanel = new();
[SerializeField] private CollectionScreenController collectionScreen = new();
[SerializeField] private StarterSelectionController starterSelection = new();
[SerializeField] private GachaScreenController gachaScreen = new();
private readonly List _commandEntries = new();
private readonly List _packageRows = new();
private readonly List _loadoutRows = new();
private readonly List _selectedRunLanguages = new();
private readonly Dictionary> _draftLanguagesByDistro = new(StringComparer.OrdinalIgnoreCase);
private readonly List _screenHistory = new();
private UIDocument _document;
private VisualElement _root;
private VisualElement _shellRoot;
private VisualElement _bootIntroPanel;
private VisualElement _mainMenuPanel;
private VisualElement _collectionPanel;
private VisualElement _runSetupPanel;
private VisualElement _gachaPanel;
private VisualElement _settingsPanel;
private VisualElement _runArchivePanel;
private VisualElement _eventBanner;
private VisualElement _backgroundLogLayer;
private ScrollView _runSetupList;
private VisualElement _runSetupDetail;
private ScrollView _runSetupPackageScroll;
private Label _appIdLabel;
private Label _entropyLabel;
private Label _pullTokensLabel;
private Label _titleCursorLabel;
private Label _promptCursorLabel;
private Label _bootIntroLogLabel;
private Label _motdBodyLabel;
private VisualElement _motdBlock;
private Button _rootCreditsToEntropyButton;
private VisualElement _rootCreditExchangeModal;
private Label _rootCreditExchangeBalanceLabel;
private Label _rootCreditExchangePreviewLabel;
private Label _rootCreditExchangeMessageLabel;
private TextField _rootCreditExchangeInput;
private Button _rootCreditExchangeMinusHundredButton;
private Button _rootCreditExchangeMinusOneButton;
private Button _rootCreditExchangeNoneButton;
private Button _rootCreditExchangePlusOneButton;
private Button _rootCreditExchangePlusHundredButton;
private Button _rootCreditExchangeMaxButton;
private Button _rootCreditExchangeConfirmButton;
private Button _rootCreditExchangeCancelButton;
private Button _rootCreditExchangeCloseButton;
private Button _collectionUnitsButton;
private Button _collectionLanguagesButton;
private Button _collectionPackagesButton;
private readonly ScreenFrameController _runSetupFrame = new();
private readonly ScreenFrameController _collectionFrame = new();
private readonly ScreenFrameController _gachaFrame = new();
private readonly ScreenFrameController _settingsFrame = new();
private readonly ScreenFrameController _runArchiveFrame = new();
private SaveService _saveService;
private SaveData _saveData;
private bool _runLaunchPending;
private bool _saveLoadFailed;
private bool _saveWriteFailed;
private bool _loadingMetaState;
private VisualElement _saveRecoveryOverlay;
private VisualElement _runHistoryOverlay;
private VisualElement _dailyQuestOverlay;
private bool _dailyQuestReturnToPrompt;
private VisualElement _dailyQuestPreviousFocus;
private bool _dailyQuestOpenedWithPointer;
private EntropyWallet _wallet;
private GachaService _gachaService;
private PlayerCollection _playerCollection;
private CardLoadout _cardLoadout;
private PackageLoadout _packageLoadout;
private BackgroundLogRingBuffer _backgroundLog;
private IEventBannerSource _eventBannerSource;
private int _selectedCommandIndex;
private int _selectedPackageIndex;
private string _runSetupNotice;
private string _runSeedText = string.Empty;
private CollectionTopTab _collectionTab;
private float _bootIntroElapsed;
private int _bootIntroCharacterCount;
private bool _cursorVisible;
private bool _suppressNextClick;
private bool _warnedUnresolvedSaveId;
private bool _rootCreditExchangeOpen;
private IVisualElementScheduledItem _rootCreditExchangeOpenSchedule;
private IVisualElementScheduledItem _rootCreditExchangeHideSchedule;
private string _bootIntroCopy;
private Action _rootCreditExchangeMinusHundredClicked;
private Action _rootCreditExchangeMinusOneClicked;
private Action _rootCreditExchangePlusOneClicked;
private Action _rootCreditExchangePlusHundredClicked;
private IVisualElementScheduledItem _blinkSchedule;
private IVisualElementScheduledItem _bootIntroSchedule;
private IVisualElementScheduledItem _dailyQuestSchedule;
private TerminalCommandLine _commandLine;
private MenuScreen _activeScreen = MenuScreen.Main;
public void Initialize(EntropyWallet initializedWallet)
{
_wallet = initializedWallet ?? new EntropyWallet();
RefreshCurrencyReadouts();
}
private void Awake()
{
_document = GetComponent();
ComposeMetaServices();
BindElements();
LoadSharedStyles();
BindCommandEntries();
TerminalTheme.Attach(_root);
_commandLine = new TerminalCommandLine(_root, ActivateCommand, () => _activeScreen == MenuScreen.Main && !starterSelection.IsActive && !_rootCreditExchangeOpen && _runHistoryOverlay == null && _dailyQuestOverlay == null && !CheckpointModalOpen && !_runLaunchPending && !PersistenceBlocked);
BindPreferences();
RegisterCommandEntryCallbacks();
BindScreenFrames();
starterSelection.Bind(_root, distroDatabase, HandleStarterConfirmed);
FontAsset resolvedFont = ResolveMonospaceFont();
featuredUnitPanel.Bind(_root, resolvedFont, GetBestWaveForUnit, OpenFeaturedUnitDetail);
collectionScreen.Bind(_root, resolvedFont, languageDeckDatabase, cardDatabase, _playerCollection, GetMergesBalance, UpgradeCollectionUnit, packageDatabase, _packageLoadout, SaveCurrentState, () => _saveData, UpgradeCollectionPackage, ScrapCollectionPackage);
gachaScreen.Bind(_root, distroDatabase, packageDatabase, resolvedFont, _gachaService, _playerCollection, _wallet, ResolvePulledDistros, ClaimStandardFiveStarSelector, HandleMetaStateChanged, OpenRootCreditExchange, StartGachaPullCutscene);
LoadMetaState();
_playerCollection.Changed += HandleMetaStateChanged;
_gachaService.Changed += HandleMetaStateChanged;
ApplyOptionalFont(resolvedFont);
}
private void BindPreferences()
{
TerminalTheme.ConstrainModalFocus(_root.Q("RootCreditExchangeModal"));
Toggle motion = _root.Q("ReducedMotionToggle");
motion.SetValueWithoutNotify(UIPreferences.ReducedMotion);
motion.text = UIPreferences.ReducedMotion ? "[ true ]" : "[ false ]";
motion.RegisterValueChangedCallback(evt =>
{
UIPreferences.ReducedMotion = evt.newValue;
UIPreferences.Save();
motion.text = evt.newValue ? "[ true ]" : "[ false ]";
_root.EnableInClassList("reduced-motion", evt.newValue);
_shellRoot.EnableInClassList("reduced-motion", evt.newValue);
if (evt.newValue && !_bootIntroPanel.ClassListContains(HiddenClassName)) CompleteBootIntro();
StartAmbientSchedules();
});
Button textSize = _root.Q