Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ lines. Details live in the docs and the linked issue.

### Added

- Add a Convert Legacy Theme menu item that creates a semantic theme copy ([#238](https://github.com/Ambiguous-Interactive/DxTerminal/issues/238)).
- 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)).
Expand Down
43 changes: 43 additions & 0 deletions Editor/CustomEditors/TerminalThemeAssetEditor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
{
using System;
using System.Collections.Generic;
using System.IO;
using Themes;
using UnityEditor;
using UnityEngine;
Expand All @@ -10,6 +11,8 @@
[CanEditMultipleObjects]
internal sealed class TerminalThemeAssetEditor : UnityEditor.Editor
{
private const string ConvertMenu = "Assets/DxTerminal/Convert Legacy Theme";

private static readonly GUIContent RolesLabel = new("Color roles");
private static readonly string[] LegacyExclusions = { TerminalThemeAsset.SemanticFlagPropertyName, TerminalThemeAsset.RolesPropertyName };

Expand All @@ -21,6 +24,46 @@ private static void CreateAsset()
ProjectWindowUtil.CreateAsset(TerminalThemeAsset.CreateSemantic(), "NewTerminalTheme.asset");
}

[MenuItem(ConvertMenu, true)]
private static bool CanConvertLegacyTheme()
{
return Selection.objects.Length == 1
&& Selection.activeObject is TerminalThemeAsset asset
&& asset != null
&& !asset.UsesSemanticRoles
&& AssetDatabase.IsMainAsset(asset);
}

[MenuItem(ConvertMenu)]
private static void ConvertLegacyTheme()
{
if (!CanConvertLegacyTheme())
{
return;
}

TerminalThemeAsset source = (TerminalThemeAsset)Selection.activeObject;
string sourcePath = AssetDatabase.GetAssetPath(source);
// Installed packages can be read-only. Put copies in the project's Assets folder.
string folder = sourcePath.StartsWith("Assets/", StringComparison.Ordinal) ? sourcePath[..sourcePath.LastIndexOf('/')] : "Assets";
string stem = $"{folder}/{Path.GetFileNameWithoutExtension(sourcePath)} Semantic";
string assetPath = stem + ".asset";
for (int suffix = 1; !IsAvailable(assetPath) || !IsAvailable(Path.ChangeExtension(assetPath, ".uss")); ++suffix)
{
assetPath = FormattableString.Invariant($"{stem} {suffix}.asset");
}

TerminalThemeAsset converted = source.CreateSemanticCopy();
converted.name = Path.GetFileNameWithoutExtension(assetPath);
AssetDatabase.CreateAsset(converted, assetPath);
Selection.activeObject = converted;
}

private static bool IsAvailable(string path)
{
return !File.Exists(path) && string.Equals(path, AssetDatabase.GenerateUniqueAssetPath(path), StringComparison.Ordinal);
}

public override void OnInspectorGUI()
{
TerminalThemeAsset asset = (TerminalThemeAsset)target;
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,10 @@ require the package's `BaseStyles.uss` on the panel settings; without it the bar
## Themes and Settings Assets

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.
below 4.5:1 or outline below 3:1 across black, mid gray, and white game backdrops.

Select a legacy theme asset and choose `Assets > DxTerminal > Convert Legacy Theme`. The new asset uses your input and log colors where widgets share a role. Roles that have no
legacy color use Dx Dark defaults. Review the contrast warnings in the new asset's Inspector.

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`.
Expand Down
21 changes: 21 additions & 0 deletions Runtime/CommandTerminal/Themes/TerminalThemeAsset.cs
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,27 @@ internal IReadOnlyDictionary<string, Color> ReadRoleColors()
return _roles.ReadColors();
}

internal TerminalThemeAsset CreateSemanticCopy()
{
// Input and log colors take priority where several widgets share one role.
TerminalThemeAsset converted = CreateSemantic();
converted._roles = new TerminalThemeRoles(
surface: _terminalBg,
surfaceRaised: _buttonBg,
hover: _buttonHoverBg,
input: _inputFieldBg,
ink: _inputTextColor,
inkBody: _textMessage,
inkMuted: _textShell,
accent: _caretColor,
accentSoft: _textInputEcho,
selection: _buttonSelectedBg,
warning: _textWarning,
errorText: _textError
);
return converted;
}

private void AppendSemanticColors(StringBuilder builder)
{
IReadOnlyDictionary<string, Color> roles = ReadRoleColors();
Expand Down
31 changes: 31 additions & 0 deletions Runtime/CommandTerminal/Themes/TerminalThemeRoles.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,37 @@ internal sealed class TerminalThemeRoles
[SerializeField]
private Color _synChoice = new(194f / 255f, 245f / 255f, 216f / 255f);

internal TerminalThemeRoles() { }

internal TerminalThemeRoles(
Color surface,
Color surfaceRaised,
Color hover,
Color input,
Color ink,
Color inkBody,
Color inkMuted,
Color accent,
Color accentSoft,
Color selection,
Color warning,
Color errorText
)
{
_surface = surface;
_surfaceRaised = surfaceRaised;
_hover = hover;
_input = input;
_ink = ink;
_inkBody = inkBody;
_inkMuted = inkMuted;
_accent = accent;
_accentSoft = accentSoft;
_selection = selection;
_warning = warning;
_errorText = errorText;
}

private static Color Quantize(Color color)
{
return new Color(
Expand Down
134 changes: 134 additions & 0 deletions Tests/Editor/TerminalThemeConversionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
namespace WallstopStudios.DxCommandTerminal.Tests.Editor
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Themes;
using UnityEngine;
#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEngine.UIElements;
#endif

public sealed class TerminalThemeConversionTests
{
#if UNITY_EDITOR
[Test]
public void AssetsMenuConvertsAndImportsACopyWithoutReplacingExistingFiles()
{
string folder = $"Assets/DxTerminalThemeTest-{Guid.NewGuid():N}";
UnityEngine.Object[] previousSelection = Selection.objects;
AssetDatabase.CreateFolder("Assets", Path.GetFileName(folder));
try
{
string originalPath = folder + "/Legacy.asset";
string originalSheetPath = Path.ChangeExtension(originalPath, ".uss");
TerminalThemeAsset source = ScriptableObject.CreateInstance<TerminalThemeAsset>();
source.name = "Legacy";
using (SerializedObject serialized = new(source))
{
serialized.FindProperty("_textError").colorValue = new Color(31f / 255f, 63f / 255f, 127f / 255f, 0.45f);
serialized.ApplyModifiedPropertiesWithoutUndo();
}

AssetDatabase.CreateAsset(source, originalPath);
byte[] originalAsset = File.ReadAllBytes(originalPath);
string originalSheet = File.ReadAllText(originalSheetPath);
string occupiedSheetPath = folder + "/Legacy Semantic.uss";
const string handWritten = ".custom-theme { color: red; }";
File.WriteAllText(occupiedSheetPath, handWritten);
AssetDatabase.ImportAsset(occupiedSheetPath, ImportAssetOptions.ForceSynchronousImport);
string occupiedAssetPath = folder + "/Legacy Semantic 1.asset";
AssetDatabase.CreateAsset(ScriptableObject.CreateInstance<TerminalThemePack>(), occupiedAssetPath);
string occupiedAssetGuid = AssetDatabase.AssetPathToGUID(occupiedAssetPath);

Selection.activeObject = source;
Assert.That(EditorApplication.ExecuteMenuItem("Assets/DxTerminal/Convert Legacy Theme"), Is.True);

string convertedPath = AssetDatabase.GetAssetPath(Selection.activeObject);
Assert.That(convertedPath, Is.EqualTo(folder + "/Legacy Semantic 2.asset"));
AssetDatabase.ImportAsset(convertedPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);
TerminalThemeAsset converted = AssetDatabase.LoadAssetAtPath<TerminalThemeAsset>(convertedPath);
Assert.That(converted != null, Is.True);
Assert.That(converted.UsesSemanticRoles, Is.True);

string convertedSheetPath = Path.ChangeExtension(convertedPath, ".uss");
string convertedSheet = File.ReadAllText(convertedSheetPath);
Assert.That(convertedSheet, Is.EqualTo(converted.BuildUss()));
Assert.That(convertedSheet, Does.Contain(".legacy-semantic-2-theme"));
Assert.That(convertedSheet, Does.Contain("--dxt-error-text: rgba(31, 63, 127, 0.45);"));
Assert.That(AssetDatabase.LoadAssetAtPath<StyleSheet>(convertedSheetPath) != null, Is.True);
Assert.That(source.UsesSemanticRoles, Is.False);
Assert.That(File.ReadAllBytes(originalPath), Is.EqualTo(originalAsset));
Assert.That(File.ReadAllText(originalSheetPath), Is.EqualTo(originalSheet));
Assert.That(File.ReadAllText(occupiedSheetPath), Is.EqualTo(handWritten));
Assert.That(AssetDatabase.AssetPathToGUID(occupiedAssetPath), Is.EqualTo(occupiedAssetGuid));
Assert.That(AssetDatabase.LoadAssetAtPath<TerminalThemePack>(occupiedAssetPath) != null, Is.True);
}
finally
{
Selection.objects = previousSelection;
AssetDatabase.DeleteAsset(folder);
}
}
#endif

[Test]
public void LegacyColorsFeedSemanticRolesAndNewRolesKeepTheirDefaults()
{
TerminalThemeAsset source = ScriptableObject.CreateInstance<TerminalThemeAsset>();
TerminalThemeAsset defaults = TerminalThemeAsset.CreateSemantic();
TerminalThemeAsset converted = source.CreateSemanticCopy();
try
{
string legacyUss = source.BuildUss();
IReadOnlyDictionary<string, Color> roles = converted.ReadRoleColors();
Dictionary<string, string> legacyVariables = new(StringComparer.Ordinal)
{
["surface"] = "terminal-bg",
["surface-raised"] = "button-bg",
["input"] = "input-field-bg",
["selection"] = "button-selected-bg",
["hover"] = "button-hover-bg",
["ink"] = "input-text-color",
["ink-body"] = "text-message",
["ink-muted"] = "text-shell",
["accent"] = "caret-color",
["accent-soft"] = "text-input-echo",
["warning"] = "text-warning",
["error-text"] = "text-error",
};
string convertedUss = converted.BuildUss();
IReadOnlyDictionary<string, Color> defaultColors = defaults.ReadRoleColors();
Assert.That(roles.Keys, Is.EquivalentTo(defaultColors.Keys));
foreach (KeyValuePair<string, Color> role in roles)
{
if (legacyVariables.TryGetValue(role.Key, out string variable))
{
Match originalColor = Regex.Match(legacyUss, $"--{variable}: (rgba[^;]+);");
Assert.That(originalColor.Success, Is.True, variable);
Assert.That(convertedUss, Does.Contain($"--dxt-{role.Key}: {originalColor.Groups[1].Value};"), role.Key);
}
else
{
Assert.That(role.Value, Is.EqualTo(defaultColors[role.Key]), role.Key);
}
}

Assert.That(converted.UsesSemanticRoles, Is.True);
Assert.That(source.UsesSemanticRoles, Is.False);
Assert.That(source.BuildUss(), Is.EqualTo(legacyUss));
}
finally
{
#if UNITY_EDITOR
UnityEngine.Object.DestroyImmediate(converted);
UnityEngine.Object.DestroyImmediate(defaults);
UnityEngine.Object.DestroyImmediate(source);
#endif
}
}
}
}
11 changes: 11 additions & 0 deletions Tests/Editor/TerminalThemeConversionTests.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading