Files
linuxdistro-roguelite/Assets/Scripts/UI/TerminalTheme.cs
T
2026-10-27 11:35:32 +01:00

222 lines
12 KiB
C#

using System.Collections.Generic;
using KernelPanic.Data;
using UnityEngine;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
/// <summary>Shared presentation only: tokens, viewport classes, distro identity and motion.</summary>
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<StyleSheet>("KernelTheme");
if (sheet != null) root.styleSheets.Add(sheet);
StyleSheet readability = Resources.Load<StyleSheet>("Readability");
if (readability != null) root.styleSheets.Add(readability);
root.RegisterCallback<GeometryChangedEvent>(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<FocusInEvent>(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<AttachToPanelEvent>(_ => Subscribe());
root.RegisterCallback<DetachFromPanelEvent>(_ =>
{
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<Button>().Where(button => button.text == text && button.enabledInHierarchy).First();
replacement ??= region.Query<Button>().Where(button => button.enabledInHierarchy).First();
if (replacement != null) replacement.Focus();
else { region.focusable = true; region.Focus(); }
});
}
public static void ConstrainModalFocus(VisualElement overlay)
{
// Tab produces a NavigationMoveEvent in both editor and runtime panels.
// Handling KeyDown as well would move focus twice for a single key.
overlay.RegisterCallback<NavigationMoveEvent>(evt =>
{
if (evt.direction != NavigationMoveEvent.Direction.Next && evt.direction != NavigationMoveEvent.Direction.Previous) return;
var controls = new List<VisualElement>();
overlay.Query<VisualElement>().ForEach(element =>
{
if (!element.focusable || !element.enabledInHierarchy || !element.visible || element.tabIndex < 0) return;
if (element is not Button && element is not Toggle && element is not TextField && element is not DropdownField) return;
for (var p = element; p != overlay; p = p.parent)
if (p == null || p.resolvedStyle.display == DisplayStyle.None) return;
controls.Add(element);
});
if (controls.Count == 0) return;
var focused = overlay.focusController.focusedElement as VisualElement;
int index = controls.FindIndex(control => control == focused || control.Contains(focused));
overlay.panel.focusController.IgnoreEvent(evt);
evt.StopImmediatePropagation();
controls[(index + (evt.direction == NavigationMoveEvent.Direction.Previous ? -1 : 1) + controls.Count) % controls.Count].Focus();
}, TrickleDown.TrickleDown);
}
// UI Toolkit's editor tooltip window is not available in standalone players.
// Use the same tooltip strings for pointer and keyboard inspection at runtime.
private static void AttachHints(VisualElement root)
{
var hint = new ScrollView(ScrollViewMode.Vertical) { focusable = false };
hint.AddToClassList("runtime-hint");
hint.style.display = DisplayStyle.None;
hint.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
hint.verticalScrollerVisibility = ScrollerVisibility.Auto;
hint.contentContainer.focusable = false;
hint.contentViewport.focusable = false;
foreach (var control in new VisualElement[] { hint.verticalScroller, hint.verticalScroller.slider,
hint.verticalScroller.lowButton, hint.verticalScroller.highButton })
control.focusable = false;
var body = new Label { pickingMode = PickingMode.Ignore, enableRichText = false, name = "RuntimeHintText" };
body.style.whiteSpace = WhiteSpace.Normal;
body.style.flexShrink = 0;
hint.Add(body);
VisualElement owner = null;
IVisualElementScheduledItem pending = null;
IVisualElementScheduledItem pendingHide = null;
IVisualElementScheduledItem refresh = null;
bool InsideHint(VisualElement element) => element == hint || (element != null && hint.Contains(element));
void Hide()
{
pending?.Pause();
pendingHide?.Pause();
refresh?.Pause();
owner = null;
hint.style.display = DisplayStyle.None;
}
void RefreshVisible()
{
if (owner?.panel == null || owner.resolvedStyle.display == DisplayStyle.None || string.IsNullOrWhiteSpace(owner.tooltip))
{ Hide(); return; }
body.text = owner.tooltip;
float width = Mathf.Max(1, Mathf.Min(380, root.layout.width - 24));
float heightLimit = Mathf.Max(1, root.layout.height - 24);
// Reserve the vertical scrollbar in the measurement so long descriptions wrap
// inside the viewport instead of growing the popup beyond the window edge.
float measured = body.MeasureTextSize(body.text, Mathf.Max(1, width - 44),
VisualElement.MeasureMode.Exactly, 0, VisualElement.MeasureMode.Undefined).y;
float height = Mathf.Min(heightLimit, Mathf.Max(44, measured + 24));
hint.style.width = width;
hint.style.maxWidth = width;
hint.style.height = height;
hint.style.maxHeight = heightLimit;
Vector2 point = root.WorldToLocal(owner.worldBound.min);
hint.style.left = Mathf.Clamp(point.x, 12, Mathf.Max(12, root.layout.width - width - 12));
hint.style.top = Mathf.Clamp(point.y - height - 8, 12, Mathf.Max(12, root.layout.height - height - 12));
}
void Inspect(VisualElement element)
{
pendingHide?.Pause();
if (InsideHint(element)) return;
while (element != null && element != root && string.IsNullOrWhiteSpace(element.tooltip)) element = element.parent;
if (element == null || element == root)
{
// Allow the pointer to cross the small gap from the inspected item to its popup.
pendingHide = root.schedule.Execute(Hide).StartingIn(180);
return;
}
if (owner == element) return;
Hide();
owner = element;
pending = root.schedule.Execute(() =>
{
if (owner?.panel == null || owner.resolvedStyle.display == DisplayStyle.None) { Hide(); return; }
if (hint.parent == null) root.Add(hint);
hint.BringToFront();
hint.style.display = DisplayStyle.Flex;
hint.scrollOffset = Vector2.zero;
RefreshVisible();
refresh ??= root.schedule.Execute(RefreshVisible).Every(100);
refresh.Resume();
}).StartingIn(450);
}
root.RegisterCallback<PointerOverEvent>(evt => Inspect(evt.target as VisualElement));
root.RegisterCallback<FocusInEvent>(evt => Inspect(evt.target as VisualElement));
root.RegisterCallback<PointerLeaveEvent>(_ => Hide());
root.RegisterCallback<FocusOutEvent>(_ => Hide());
root.RegisterCallback<PointerDownEvent>(evt => { if (!InsideHint(evt.target as VisualElement)) Hide(); }, TrickleDown.TrickleDown);
root.RegisterCallback<WheelEvent>(evt => { if (!InsideHint(evt.target as VisualElement)) Hide(); }, TrickleDown.TrickleDown);
root.RegisterCallback<KeyDownEvent>(evt =>
{
var focused = root.focusController?.focusedElement as VisualElement;
if (owner != null && hint.style.display.value != DisplayStyle.None &&
(focused == owner || (focused != null && owner.Contains(focused))) &&
(evt.keyCode == KeyCode.PageDown || evt.keyCode == KeyCode.PageUp))
{
float direction = evt.keyCode == KeyCode.PageDown ? 1 : -1;
hint.scrollOffset = new Vector2(0, Mathf.Clamp(hint.scrollOffset.y + direction * hint.contentViewport.layout.height * 0.8f,
0, hint.verticalScroller.highValue));
evt.StopImmediatePropagation();
return;
}
Hide();
}, TrickleDown.TrickleDown);
root.RegisterCallback<DetachFromPanelEvent>(_ => Hide());
}
public static void SetDistro(VisualElement root, DistroDefinition distro)
{
foreach (string id in new[] { "arch", "ubuntu", "fedora", "mint", "gentoo", "nixos" })
root.EnableInClassList("distro-" + id, distro != null && distro.Id == id);
}
}
}