diff --git a/.llm/skills/terminal-theming/SKILL.md b/.llm/skills/terminal-theming/SKILL.md index 5d878613..085c01a2 100644 --- a/.llm/skills/terminal-theming/SKILL.md +++ b/.llm/skills/terminal-theming/SKILL.md @@ -9,19 +9,22 @@ metadata: ## Asset model -| Asset | Class | Role | -| ----------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -| Theme pack | `TerminalThemePack` (`Runtime/CommandTerminal/Themes/`) | Named set of UI Toolkit style values (colors, sizes) applied to `TerminalUI` | -| Font pack | `TerminalFontPack` (`Runtime/CommandTerminal/Themes/`) | Bundle of `FontAsset`s selectable per terminal | -| Theme asset | `TerminalThemeAsset` (`Runtime/CommandTerminal/Themes/`) | Authoring-only SO whose 19 color fields auto-generate a sibling `.uss` via `TerminalThemeAssetPostProcessor` (Editor) | -| Stylesheets | `Styles/*.uss`, `Styles/*.tss` | Base USS (`BaseStyles.uss`), theme settings TSS chain | -| Persistence | `TerminalThemeConfiguration(s)`, `TerminalThemePersister` | Saved/serialized theme selections and per-theme overrides | +| Asset | Class | Role | +| ----------- | --------------------------------------------------------- | ---------------------------------------------------------------------------- | +| Theme pack | `TerminalThemePack` (`Runtime/CommandTerminal/Themes/`) | Named set of UI Toolkit style values (colors, sizes) applied to `TerminalUI` | +| Font pack | `TerminalFontPack` (`Runtime/CommandTerminal/Themes/`) | Bundle of `FontAsset`s selectable per terminal | +| Theme asset | `TerminalThemeAsset` (`Runtime/CommandTerminal/Themes/`) | Authoring asset that generates a sibling `.uss` on import | +| Stylesheets | `Styles/*.uss`, `Styles/*.tss` | Base USS (`BaseStyles.uss`), theme settings TSS chain | +| Persistence | `TerminalThemeConfiguration(s)`, `TerminalThemePersister` | Saved/serialized theme selections and per-theme overrides | Built-in packs ship as ScriptableObject assets under `Packs/Themes/` and `Packs/Fonts/`. ## Theme assets (generated sheets) -`TerminalThemeAsset` colors -> sibling `.uss` written by `TerminalThemeAssetPostProcessor` on every import. Contracts enforced there: +New theme assets start with the 20 Dx Dark roles. The Inspector checks the serialized colors against the same contrast pairs as the shipped-theme gate. Generated USS includes +widget aliases for theme pack discovery. Old assets still generate their original widget colors. + +`TerminalThemeAssetPostProcessor` writes `.uss` on import: - Generated sheets carry the `TerminalThemeAsset.GeneratedMarkerPrefix` first-line stamp; only marker-carrying files are overwritten or deleted. A hand-written sheet sharing the asset's name is preserved with a warning. diff --git a/CHANGELOG.md b/CHANGELOG.md index 013b1259..35dcbebe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ lines. Details live in the docs and the linked issue. ### Added +- Add semantic color roles and contrast checks to new theme assets ([#238](https://github.com/Ambiguous-Interactive/DxTerminal/issues/238)). - Add a selection outline to Dx theme palette results and completion hints ([#238](https://github.com/Ambiguous-Interactive/DxTerminal/issues/238)). - Add the Dx theme pack with Dx Dark, Dx Paper, and Phosphor ([#238](https://github.com/Ambiguous-Interactive/DxTerminal/issues/238)). - Add serialized PlayerInput action names and custom-map routing through C# events ([#245](https://github.com/Ambiguous-Interactive/DxTerminal/issues/245)). diff --git a/Editor/CustomEditors/TerminalThemeAssetEditor.cs b/Editor/CustomEditors/TerminalThemeAssetEditor.cs new file mode 100644 index 00000000..aaaa8cbe --- /dev/null +++ b/Editor/CustomEditors/TerminalThemeAssetEditor.cs @@ -0,0 +1,84 @@ +namespace WallstopStudios.DxCommandTerminal.Editor.CustomEditors +{ + using System; + using System.Collections.Generic; + using Themes; + using UnityEditor; + using UnityEngine; + + [CustomEditor(typeof(TerminalThemeAsset))] + [CanEditMultipleObjects] + internal sealed class TerminalThemeAssetEditor : UnityEditor.Editor + { + private static readonly GUIContent RolesLabel = new("Color roles"); + private static readonly string[] LegacyExclusions = { TerminalThemeAsset.SemanticFlagPropertyName, TerminalThemeAsset.RolesPropertyName }; + + private List _contrastWarnings; + + [MenuItem("Assets/Create/Wallstop Studios/DxTerminal/Theme Asset", false, 1_111_124)] + private static void CreateAsset() + { + ProjectWindowUtil.CreateAsset(TerminalThemeAsset.CreateSemantic(), "NewTerminalTheme.asset"); + } + + public override void OnInspectorGUI() + { + TerminalThemeAsset asset = (TerminalThemeAsset)target; + bool valuesUpdated = serializedObject.UpdateIfRequiredOrScript(); + SerializedProperty mode = serializedObject.FindProperty(TerminalThemeAsset.SemanticFlagPropertyName); + if (mode.hasMultipleDifferentValues) + { + EditorGUILayout.HelpBox("Select themes that use the same color fields.", MessageType.Info); + return; + } + + if (!asset.UsesSemanticRoles) + { + _contrastWarnings = null; + DrawPropertiesExcluding(serializedObject, LegacyExclusions); + serializedObject.ApplyModifiedProperties(); + return; + } + + SerializedProperty roles = serializedObject.FindProperty(TerminalThemeAsset.RolesPropertyName); + EditorGUILayout.PropertyField(roles, RolesLabel, true); + bool valuesEdited = serializedObject.ApplyModifiedProperties(); + if (serializedObject.isEditingMultipleObjects) + { + EditorGUILayout.HelpBox("Select one theme to check its contrast.", MessageType.Info); + return; + } + + if (_contrastWarnings == null || valuesUpdated || valuesEdited) + { + UpdateContrastWarnings(asset.ReadRoleColors()); + } + + foreach (string warning in _contrastWarnings) + { + EditorGUILayout.HelpBox(warning, MessageType.Warning); + } + + if (_contrastWarnings.Count == 0) + { + EditorGUILayout.HelpBox("Contrast passes on black, mid gray, and white backdrops.", MessageType.Info); + } + } + + private void UpdateContrastWarnings(IReadOnlyDictionary colors) + { + _contrastWarnings ??= new List(); + _contrastWarnings.Clear(); + Color surface = colors["surface"]; + foreach ((string foreground, string background, double minimum) in ThemeContrast.Pairs) + { + Color? layer = string.Equals(background, "surface", StringComparison.Ordinal) ? null : colors[background]; + (double ratio, string backdrop) = ThemeContrast.Measure(colors[foreground], surface, layer); + if (ratio < minimum) + { + _contrastWarnings.Add($"{foreground} on {background} over {backdrop} gives {ratio:F2}:1. Minimum is {minimum:F1}:1."); + } + } + } + } +} diff --git a/Editor/CustomEditors/TerminalThemeAssetEditor.cs.meta b/Editor/CustomEditors/TerminalThemeAssetEditor.cs.meta new file mode 100644 index 00000000..e6d058c1 --- /dev/null +++ b/Editor/CustomEditors/TerminalThemeAssetEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fa5980d9a2ef4c358246870a0a2216d0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/README.md b/README.md index a1c45a45..c30777f9 100644 --- a/README.md +++ b/README.md @@ -163,12 +163,11 @@ require the package's `BaseStyles.uss` on the panel settings; without it the bar ## Themes and Settings Assets -Create a theme without hand-writing USS: `Assets > Create > Wallstop Studios > DxTerminal > Theme Asset` makes a `TerminalThemeAsset` with color pickers for the 19 custom -properties a terminal theme sheet needs. The Editor automatically writes a sibling `.uss` named after the asset and keeps it in sync when you recolor or rename it (a rename -generates a fresh sheet file — Unity references assets by path-derived identity, so like renaming any stylesheet, packs using the old file need the new sheet re-assigned); drag -that sheet into a `TerminalThemePack`'s Themes list and it behaves exactly like the shipped sheets — `set-theme ` (or the palette) picks it up. Hand-written `.uss` themes -remain fully supported. Prefer asset names without "theme" in the middle (`DarkTheme`, `Neon Nights`); names like `Cool Theme 2` still work but their `set-theme` shorthand becomes -ambiguous — the full class name always resolves. +Choose `Assets > Create > Wallstop Studios > DxTerminal > Theme Asset` to start with Dx Dark colors. Edit the semantic roles in the Inspector. The contrast check reports any text +below 4.5:1 or outline below 3:1 across black, mid gray, and white game backdrops. Existing theme assets still use their widget color fields. + +The Editor writes a sibling `.uss` and keeps it in sync. Add the sheet to a `TerminalThemePack` to make it available to `set-theme`. If you rename the asset, reassign the new sheet +in the pack. Hand-written `.uss` themes also work. Use the full class name if the `set-theme` shorthand is ambiguous, such as for `Cool Theme 2`. To share one configuration across terminals, `Assets > Create > Wallstop Studios > DxTerminal > Terminal Settings` makes a `TerminalSettings` asset. Assign it to a `TerminalUI` or `CommandPaletteUI` and its values (buffer sizes, input caret, caret blink rate, button text, hint mode, history dedup, ignored log types, disabled commands, Unity log forwarding, diff --git a/Runtime/CommandTerminal/Themes/TerminalThemeAsset.cs b/Runtime/CommandTerminal/Themes/TerminalThemeAsset.cs index 348aa1b0..ce5b43a6 100644 --- a/Runtime/CommandTerminal/Themes/TerminalThemeAsset.cs +++ b/Runtime/CommandTerminal/Themes/TerminalThemeAsset.cs @@ -1,21 +1,13 @@ namespace WallstopStudios.DxCommandTerminal.Themes { using System; + using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using Helper; using UnityEngine; - /* - Authoring-only theme asset (issue #72, option A): one asset per theme - with color fields for the 19 custom properties every terminal theme - sheet must define. An Editor postprocessor auto-writes the sibling - .uss file on every asset change; the generated sheet drops into a - TerminalThemePack like any hand-written one and is never read back by - this asset, so runtime behavior and shipped packs are unchanged. - */ - [CreateAssetMenu(menuName = "Wallstop Studios/DxTerminal/Theme Asset", fileName = "NewTerminalTheme", order = 1_111_124)] public sealed class TerminalThemeAsset : ScriptableObject { /* @@ -24,6 +16,31 @@ public sealed class TerminalThemeAsset : ScriptableObject hand-written sheets are never clobbered. */ internal const string GeneratedMarkerPrefix = "/* Generated by TerminalThemeAsset"; + internal const string SemanticFlagPropertyName = nameof(_useSemanticRoles); + internal const string RolesPropertyName = nameof(_roles); + + private static readonly (string Widget, string Role)[] WidgetColors = + { + ("terminal-bg", "surface"), + ("button-bg", "surface-raised"), + ("input-field-bg", "input"), + ("button-selected-bg", "selection"), + ("button-hover-bg", "hover"), + ("scroll-bg", "surface"), + ("scroll-color", "ink-muted"), + ("scroll-inverse-bg", "ink-muted"), + ("scroll-active-bg", "ink-body"), + ("button-text", "ink-body"), + ("button-selected-text", "ink"), + ("button-hover-text", "ink"), + ("input-text-color", "ink"), + ("text-message", "ink-body"), + ("text-warning", "warning"), + ("text-input-echo", "accent-soft"), + ("text-shell", "ink-muted"), + ("text-error", "error-text"), + ("caret-color", "accent"), + }; /* The CSS class the generated sheet targets, derived from the asset @@ -44,6 +61,18 @@ public string CssClassName } } + internal bool UsesSemanticRoles + { + get { return _useSemanticRoles; } + } + + // Missing in legacy assets, which must keep generating their original colors. + [SerializeField] + private bool _useSemanticRoles; + + [SerializeField] + private TerminalThemeRoles _roles = new(); + [Header("Backgrounds")] [SerializeField] [Tooltip("Terminal window background")] @@ -123,6 +152,13 @@ public string CssClassName [Tooltip("Input caret color")] private Color _caretColor = new(0.949f, 0.949f, 0.9686f, 1f); + internal static TerminalThemeAsset CreateSemantic() + { + TerminalThemeAsset asset = CreateInstance(); + asset._useSemanticRoles = true; + return asset; + } + /* Reads without an exists-check: the file can vanish between a check and the read, so the read is the check. Expected failures @@ -260,6 +296,41 @@ public string BuildUss() */ builder.Append(GeneratedMarkerPrefix).Append(" from '").Append(SafeDisplayName()).Append(".asset' - hand edits are overwritten on the next change. */\n"); builder.Append('.').Append(cssClass).Append(" {\n"); + if (_useSemanticRoles) + { + AppendSemanticColors(builder); + } + else + { + AppendLegacyColors(builder); + } + + builder.Append("}\n"); + return builder.ToString(); + } + + internal IReadOnlyDictionary ReadRoleColors() + { + return _roles.ReadColors(); + } + + private void AppendSemanticColors(StringBuilder builder) + { + IReadOnlyDictionary roles = ReadRoleColors(); + foreach (KeyValuePair role in roles) + { + AppendToken(builder, "--dxt-" + role.Key, role.Value); + } + + builder.Append('\n'); + foreach ((string widget, string role) in WidgetColors) + { + AppendToken(builder, "--" + widget, roles[role]); + } + } + + private void AppendLegacyColors(StringBuilder builder) + { builder.Append(" /* Backgrounds */\n"); AppendToken(builder, "--terminal-bg", _terminalBg); AppendToken(builder, "--button-bg", _buttonBg); @@ -284,8 +355,6 @@ public string BuildUss() builder.Append(" /* Other UI Elements */\n"); AppendToken(builder, "--scroll-color", _scrollColor); AppendToken(builder, "--caret-color", _caretColor); - builder.Append("}\n"); - return builder.ToString(); } private string SafeDisplayName() diff --git a/Runtime/CommandTerminal/Themes/TerminalThemeRoles.cs b/Runtime/CommandTerminal/Themes/TerminalThemeRoles.cs new file mode 100644 index 00000000..057c4a92 --- /dev/null +++ b/Runtime/CommandTerminal/Themes/TerminalThemeRoles.cs @@ -0,0 +1,107 @@ +namespace WallstopStudios.DxCommandTerminal.Themes +{ + using System; + using System.Collections.Generic; + using UnityEngine; + + [Serializable] + internal sealed class TerminalThemeRoles + { + [SerializeField] + private Color _surface = new(13f / 255f, 17f / 255f, 23f / 255f, 0.94f); + + [SerializeField] + private Color _surfaceRaised = new(22f / 255f, 28f / 255f, 37f / 255f); + + [SerializeField] + private Color _hover = new(29f / 255f, 37f / 255f, 48f / 255f); + + [SerializeField] + private Color _input = new(10f / 255f, 14f / 255f, 19f / 255f); + + [SerializeField] + private Color _line = new(35f / 255f, 44f / 255f, 56f / 255f); + + [SerializeField] + private Color _ink = new(230f / 255f, 237f / 255f, 243f / 255f); + + [SerializeField] + private Color _inkBody = new(201f / 255f, 210f / 255f, 220f / 255f); + + [SerializeField] + private Color _inkMuted = new(154f / 255f, 163f / 255f, 175f / 255f); + + [SerializeField] + private Color _accent = new(92f / 255f, 214f / 255f, 143f / 255f); + + [SerializeField] + private Color _accentSoft = new(184f / 255f, 242f / 255f, 207f / 255f); + + [SerializeField] + private Color _onAccent = new(13f / 255f, 17f / 255f, 23f / 255f); + + [SerializeField] + private Color _selection = new(18f / 255f, 48f / 255f, 31f / 255f); + + [SerializeField] + private Color _selectionLine = new(52f / 255f, 126f / 255f, 82f / 255f); + + [SerializeField] + private Color _warning = new(244f / 255f, 168f / 255f, 54f / 255f); + + [SerializeField] + private Color _error = new(236f / 255f, 70f / 255f, 97f / 255f); + + [SerializeField] + private Color _errorLine = new(180f / 255f, 68f / 255f, 90f / 255f); + + [SerializeField] + private Color _errorText = new(255f / 255f, 122f / 255f, 142f / 255f); + + [SerializeField] + private Color _synNumber = new(108f / 255f, 182f / 255f, 255f / 255f); + + [SerializeField] + private Color _synString = new(250f / 255f, 192f / 255f, 98f / 255f); + + [SerializeField] + private Color _synChoice = new(194f / 255f, 245f / 255f, 216f / 255f); + + private static Color Quantize(Color color) + { + return new Color( + Mathf.RoundToInt(Mathf.Clamp01(color.r) * 255f) / 255f, + Mathf.RoundToInt(Mathf.Clamp01(color.g) * 255f) / 255f, + Mathf.RoundToInt(Mathf.Clamp01(color.b) * 255f) / 255f, + (float)Math.Round(Mathf.Clamp01(color.a), 3) + ); + } + + internal IReadOnlyDictionary ReadColors() + { + return new SortedDictionary(StringComparer.Ordinal) + { + ["surface"] = Quantize(_surface), + ["surface-raised"] = Quantize(_surfaceRaised), + ["hover"] = Quantize(_hover), + ["input"] = Quantize(_input), + ["line"] = Quantize(_line), + ["ink"] = Quantize(_ink), + ["ink-body"] = Quantize(_inkBody), + ["ink-muted"] = Quantize(_inkMuted), + ["accent"] = Quantize(_accent), + ["accent-soft"] = Quantize(_accentSoft), + ["on-accent"] = Quantize(_onAccent), + ["selection"] = Quantize(_selection), + ["selection-line"] = Quantize(_selectionLine), + ["warning"] = Quantize(_warning), + ["error"] = Quantize(_error), + ["error-line"] = Quantize(_errorLine), + ["error-text"] = Quantize(_errorText), + ["syn-number"] = Quantize(_synNumber), + ["syn-string"] = Quantize(_synString), + ["syn-choice"] = Quantize(_synChoice), + }; + } + } +} diff --git a/Runtime/CommandTerminal/Themes/TerminalThemeRoles.cs.meta b/Runtime/CommandTerminal/Themes/TerminalThemeRoles.cs.meta new file mode 100644 index 00000000..25eb5ed5 --- /dev/null +++ b/Runtime/CommandTerminal/Themes/TerminalThemeRoles.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0908cd5028504a509a1d833a188bb788 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/CommandTerminal/Themes/ThemeContrast.cs b/Runtime/CommandTerminal/Themes/ThemeContrast.cs new file mode 100644 index 00000000..17d4d387 --- /dev/null +++ b/Runtime/CommandTerminal/Themes/ThemeContrast.cs @@ -0,0 +1,95 @@ +namespace WallstopStudios.DxCommandTerminal.Themes +{ + using System; + using System.Collections.Generic; + using UnityEngine; + + internal static class ThemeContrast + { + private const double TextMinimum = 4.5; + private const double OutlineMinimum = 3.0; + + internal static readonly IReadOnlyList<(string Foreground, string Background, double Minimum)> Pairs = Array.AsReadOnly( + new (string, string, double)[] + { + ("ink", "surface", TextMinimum), + ("ink", "input", TextMinimum), + ("ink", "selection", TextMinimum), + ("ink", "hover", TextMinimum), + ("ink-body", "surface", TextMinimum), + ("ink-body", "surface-raised", TextMinimum), + ("ink-muted", "surface", TextMinimum), + ("ink-muted", "input", TextMinimum), + ("accent", "input", TextMinimum), + ("accent-soft", "surface", TextMinimum), + ("accent-soft", "selection", TextMinimum), + ("on-accent", "accent", TextMinimum), + ("warning", "surface", TextMinimum), + ("warning", "surface-raised", TextMinimum), + ("error-text", "surface", TextMinimum), + ("error-text", "surface-raised", TextMinimum), + ("error-text", "input", TextMinimum), + ("syn-number", "surface", TextMinimum), + ("syn-number", "input", TextMinimum), + ("syn-string", "surface", TextMinimum), + ("syn-string", "input", TextMinimum), + ("syn-choice", "surface", TextMinimum), + ("syn-choice", "input", TextMinimum), + ("error", "surface", OutlineMinimum), + ("error", "surface-raised", OutlineMinimum), + ("accent", "surface", OutlineMinimum), + ("selection-line", "surface", OutlineMinimum), + ("error-line", "surface", OutlineMinimum), + ("error-line", "input", OutlineMinimum), + } + ); + + private static readonly (string Name, Color Color)[] Backdrops = + { + ("black", Color.black), + ("mid gray", new Color(128f / 255f, 128f / 255f, 128f / 255f)), + ("white", Color.white), + }; + + internal static (double Ratio, string Backdrop) Measure(Color foreground, Color surface, Color? backdropLayer) + { + double worstRatio = double.PositiveInfinity; + string worstBackdrop = string.Empty; + foreach ((string name, Color game) in Backdrops) + { + Color baseColor = Over(surface, game); + Color background = backdropLayer is Color layer ? Over(layer, baseColor) : baseColor; + double front = Luminance(Over(foreground, background)); + double back = Luminance(background); + double ratio = (Math.Max(front, back) + 0.05) / (Math.Min(front, back) + 0.05); + if (ratio < worstRatio) + { + worstRatio = ratio; + worstBackdrop = name; + } + } + + return (worstRatio, worstBackdrop); + } + + private static Color Over(Color foreground, Color opaqueBackground) + { + float remaining = 1f - foreground.a; + return new Color( + foreground.r * foreground.a + opaqueBackground.r * remaining, + foreground.g * foreground.a + opaqueBackground.g * remaining, + foreground.b * foreground.a + opaqueBackground.b * remaining + ); + } + + private static double Luminance(Color color) + { + return 0.2126 * Linearize(color.r) + 0.7152 * Linearize(color.g) + 0.0722 * Linearize(color.b); + } + + private static double Linearize(double channel) + { + return channel <= 0.04045 ? channel / 12.92 : Math.Pow((channel + 0.055) / 1.055, 2.4); + } + } +} diff --git a/Runtime/CommandTerminal/Themes/ThemeContrast.cs.meta b/Runtime/CommandTerminal/Themes/ThemeContrast.cs.meta new file mode 100644 index 00000000..0f7b52d5 --- /dev/null +++ b/Runtime/CommandTerminal/Themes/ThemeContrast.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 838f3c64b1ca4b76b38bed983dcc302a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/Editor/ThemeContrastTests.cs b/Tests/Editor/ThemeContrastTests.cs index da473c77..fa674164 100644 --- a/Tests/Editor/ThemeContrastTests.cs +++ b/Tests/Editor/ThemeContrastTests.cs @@ -7,6 +7,7 @@ using System.Text.RegularExpressions; using NUnit.Framework; using Themes; + using UnityEngine; #if UNITY_EDITOR using UnityEditor; using PackageInfo = UnityEditor.PackageManager.PackageInfo; @@ -15,47 +16,11 @@ public sealed class ThemeContrastTests { - private const double TextMinimum = 4.5; - private const double OutlineMinimum = 3.0; - private const string PackageRoot = "Packages/com.wallstop-studios.dxcommandterminal/"; private const string ThemeSheet = "Styles/Themes/DxThemes.uss"; private static readonly string[] ThemeClasses = { "dx-dark-theme", "dx-paper-theme", "phosphor-theme" }; private static readonly Lazy>> Themes = new(LoadThemes); - private static readonly (string Foreground, string Background, double Minimum)[] Pairs = - { - ("ink", "surface", TextMinimum), - ("ink", "input", TextMinimum), - ("ink", "selection", TextMinimum), - ("ink", "hover", TextMinimum), - ("ink-body", "surface", TextMinimum), - ("ink-body", "surface-raised", TextMinimum), - ("ink-muted", "surface", TextMinimum), - ("ink-muted", "input", TextMinimum), - ("accent", "input", TextMinimum), - ("accent-soft", "surface", TextMinimum), - ("accent-soft", "selection", TextMinimum), - ("on-accent", "accent", TextMinimum), - ("warning", "surface", TextMinimum), - ("warning", "surface-raised", TextMinimum), - ("error-text", "surface", TextMinimum), - ("error-text", "surface-raised", TextMinimum), - ("error-text", "input", TextMinimum), - ("syn-number", "surface", TextMinimum), - ("syn-number", "input", TextMinimum), - ("syn-string", "surface", TextMinimum), - ("syn-string", "input", TextMinimum), - ("syn-choice", "surface", TextMinimum), - ("syn-choice", "input", TextMinimum), - ("error", "surface", OutlineMinimum), - ("error", "surface-raised", OutlineMinimum), - ("accent", "surface", OutlineMinimum), - ("selection-line", "surface", OutlineMinimum), - ("error-line", "surface", OutlineMinimum), - ("error-line", "input", OutlineMinimum), - }; - private static readonly (string Name, Rgb Color)[] Backdrops = { ("black", new Rgb(0x000000)), ("mid gray", new Rgb(0x808080)), ("white", new Rgb(0xFFFFFF)) }; private static readonly (string Mode, double[,] Matrix)[] VisionModels = @@ -108,6 +73,13 @@ private static Dictionary> LoadThemes() using StreamReader reader = new(typeof(ThemeContrastTests).Assembly.GetManifestResourceStream(ThemeSheet)); string sheet = reader.ReadToEnd(); #endif + Dictionary> themes = ParseThemes(sheet); + Assert.That(themes.Keys, Is.EquivalentTo(ThemeClasses)); + return themes; + } + + private static Dictionary> ParseThemes(string sheet) + { sheet = Regex.Replace(sheet, @"/\*[\s\S]*?\*/", string.Empty); Dictionary> themes = new(StringComparer.Ordinal); foreach (Match block in Regex.Matches(sheet, @"^\.([a-z-]+)\s*\{([^}]*)\}", RegexOptions.Multiline)) @@ -142,7 +114,6 @@ private static Dictionary> LoadThemes() themes.Add(themeClass, roles); } - Assert.That(themes.Keys, Is.EquivalentTo(ThemeClasses)); return themes; } @@ -150,20 +121,13 @@ private static IEnumerable ContrastCases() { foreach (string theme in ThemeClasses) { - foreach ((string foreground, string background, double minimum) in Pairs) + foreach ((string foreground, string background, double minimum) in ThemeContrast.Pairs) { yield return new TestCaseData(theme, foreground, background, minimum); } } } - private static double Contrast(Rgb foreground, Rgb background) - { - double text = foreground.RelativeLuminance(); - double back = background.RelativeLuminance(); - return (Math.Max(text, back) + 0.05) / (Math.Min(text, back) + 0.05); - } - private static double Apca(Rgb foreground, Rgb background) { double text = foreground.ApcaLuminance(); @@ -186,8 +150,8 @@ private static double Apca(Rgb foreground, Rgb background) private static (double Ratio, string Result) MeasureContrast(string theme, string foregroundRole, string backgroundRole) { Dictionary colors = Themes.Value[theme]; - double worstRatio = double.PositiveInfinity; - string worstBackdrop = string.Empty; + Color? layer = string.Equals(backgroundRole, "surface", StringComparison.Ordinal) ? null : colors["dxt-" + backgroundRole].ToColor(); + (double worstRatio, string worstBackdrop) = ThemeContrast.Measure(colors["dxt-" + foregroundRole].ToColor(), colors["dxt-surface"].ToColor(), layer); double weakestLc = double.PositiveInfinity; string weakestBackdrop = string.Empty; foreach ((string backdrop, Rgb game) in Backdrops) @@ -195,13 +159,6 @@ private static (double Ratio, string Result) MeasureContrast(string theme, strin Rgb surface = colors["dxt-surface"].Over(game); Rgb background = string.Equals(backgroundRole, "surface", StringComparison.Ordinal) ? surface : colors["dxt-" + backgroundRole].Over(surface); Rgb foreground = colors["dxt-" + foregroundRole].Over(background); - double ratio = Contrast(foreground, background); - if (ratio < worstRatio) - { - worstRatio = ratio; - worstBackdrop = backdrop; - } - double lc = Apca(foreground, background); if (Math.Abs(lc) < Math.Abs(weakestLc)) { @@ -217,6 +174,34 @@ private static (double Ratio, string Result) MeasureContrast(string theme, strin return (worstRatio, result); } + [Test] + public void NewThemeAssetGeneratesEveryDxDarkColor() + { + TerminalThemeAsset asset = TerminalThemeAsset.CreateSemantic(); + try + { + asset.name = "sample"; + Dictionary roles = ParseThemes(asset.BuildUss())["sample-theme"]; + Assert.That(roles, Is.EquivalentTo(Themes.Value["dx-dark-theme"])); + } + finally + { +#if UNITY_EDITOR + UnityEngine.Object.DestroyImmediate(asset); +#endif + } + } + + [Test] + public void ContrastRejectsTextThatOnlyPassesOnDarkBackdrops() + { + Color surface = new(13f / 255f, 17f / 255f, 23f / 255f, 0.94f); + Color error = new(236f / 255f, 70f / 255f, 97f / 255f); + (double ratio, string backdrop) = ThemeContrast.Measure(error, surface, null); + Assert.That(backdrop, Is.EqualTo("white")); + Assert.That(ratio, Is.EqualTo(4.41).Within(0.01)); + } + [TestCaseSource(nameof(ContrastCases))] public void RolesMeetContrastMinimum(string theme, string foregroundRole, string backgroundRole, double minimum) { @@ -374,9 +359,9 @@ public double OkLabDistance(Rgb other, double[,] matrix) return 100 * Math.Sqrt(deltaL * deltaL + deltaA * deltaA + deltaB * deltaB); } - public double RelativeLuminance() + public Color ToColor() { - return 0.2126 * Linearize(_red) + 0.7152 * Linearize(_green) + 0.0722 * Linearize(_blue); + return new Color((float)_red, (float)_green, (float)_blue, (float)_alpha); } public double ApcaLuminance() diff --git a/Tests/Runtime/TerminalThemeAssetTests.cs b/Tests/Runtime/TerminalThemeAssetTests.cs index a22dad68..6d5f20fa 100644 --- a/Tests/Runtime/TerminalThemeAssetTests.cs +++ b/Tests/Runtime/TerminalThemeAssetTests.cs @@ -144,9 +144,9 @@ public void ColorsFormatAsUssRgbaValues() StringAssert.Contains("--text-error: rgba(255, 69, 58, 1);", uss); } - private TerminalThemeAsset CreateAsset(string name) + private TerminalThemeAsset CreateAsset(string name, bool semantic = false) { - TerminalThemeAsset asset = ScriptableObject.CreateInstance(); + TerminalThemeAsset asset = semantic ? TerminalThemeAsset.CreateSemantic() : ScriptableObject.CreateInstance(); asset.name = name; _createdAssets.Add(asset); return asset; @@ -176,6 +176,27 @@ .uss must appear without any manual step. Assert.AreEqual(asset.BuildUss(), File.ReadAllText(sheetPath), "Editing the asset rewrites the sheet"); } + [Test] + public void EditingASemanticAssetUpdatesItsImportedSheet() + { + CreateTempFolder(); + + const string assetPath = TempFolder + "/ProbeTheme.asset"; + const string sheetPath = TempFolder + "/ProbeTheme.uss"; + AssetDatabase.CreateAsset(CreateAsset("ProbeTheme", semantic: true), assetPath); + string originalGuid = AssetDatabase.AssetPathToGUID(sheetPath); + TerminalThemeAsset asset = AssetDatabase.LoadAssetAtPath(assetPath); + Assert.That(asset.UsesSemanticRoles, Is.True); + + SetColor(asset, TerminalThemeAsset.RolesPropertyName + "._errorText", Color.magenta); + string uss = File.ReadAllText(sheetPath); + Assert.That(uss, Does.Contain("--dxt-error-text: rgba(255, 0, 255, 1);")); + Assert.That(uss, Does.Contain("--text-error: rgba(255, 0, 255, 1);")); + Assert.That(AssetDatabase.LoadAssetAtPath(sheetPath) != null, Is.True); + Assert.That(originalGuid, Is.Not.Empty); + Assert.That(AssetDatabase.AssetPathToGUID(sheetPath), Is.EqualTo(originalGuid)); + } + [Test] public void DeletingTheAssetRemovesItsGeneratedSheet() {