using System.Collections.Generic; using KernelPanic.Data; using UnityEngine; using UnityEngine.UIElements; namespace KernelPanic.UI { /// Shared presentation only: tokens, viewport classes, distro identity and motion. internal static class TerminalTheme { public static void Attach(VisualElement root) { if (root.ClassListContains("kernel-ui")) return; root.AddToClassList("kernel-ui"); var font = TerminalFontResolver.Resolve(null); if (font != null) root.style.unityFontDefinition = new StyleFontDefinition(font); StyleSheet sheet = Resources.Load("KernelTheme"); if (sheet != null) root.styleSheets.Add(sheet); StyleSheet readability = Resources.Load("Readability"); if (readability != null) root.styleSheets.Add(readability); root.RegisterCallback(evt => { root.EnableInClassList("compact", evt.newRect.width < 1100); root.EnableInClassList("narrow", evt.newRect.width < 760); root.EnableInClassList("short-screen", evt.newRect.height < 760); }); AttachPreferences(root); root.RegisterCallback(evt => { if (evt.target is not VisualElement control) return; // Reveal keyboard focus in each enclosing scroll area, not just the innermost list. for (var parent = control.parent; parent != null; parent = parent.parent) // Scrollbars and the viewport belong to the scroll view, but not its scrollable content. if (parent is ScrollView scroll && control != scroll.contentContainer && scroll.contentContainer.Contains(control)) scroll.ScrollTo(control); }); AttachHints(root); } private static void AttachPreferences(VisualElement root) { bool listening = false; void Apply() { root.EnableInClassList("reduced-motion", UIPreferences.ReducedMotion); root.EnableInClassList("text-large", UIPreferences.TextSize == UITextSize.Large); root.EnableInClassList("density-comfortable", UIPreferences.Density == UILayoutDensity.Comfortable); } void Subscribe() { if (!listening) UIPreferences.Changed += Apply; listening = true; Apply(); } root.RegisterCallback(_ => Subscribe()); root.RegisterCallback(_ => { if (listening) UIPreferences.Changed -= Apply; listening = false; }); Apply(); if (root.panel != null) Subscribe(); } public static void PreserveFocus(VisualElement region) { var focused = region?.focusController?.focusedElement as VisualElement; if (focused == null || !region.Contains(focused)) return; string name = focused.name; string text = (focused as Button)?.text; region.schedule.Execute(() => { if (focused.panel != null) return; VisualElement replacement = string.IsNullOrEmpty(name) ? null : region.Q(name); if (replacement == null && !string.IsNullOrEmpty(text)) replacement = region.Query