Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More graceful handling of undefined named colors #383

Merged
merged 2 commits into from
Dec 17, 2023
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
50 changes: 40 additions & 10 deletions commonItems.UnitTests/Colors/ColorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,21 @@ public void ColorCanBeInitializedWithHsvaComponents() {
Assert.Equal(0.5, testColor.V, decimalPlaces);
}

[Theory]
[InlineData(0, 0, 0)]
[InlineData(255, 0, 0)]
[InlineData(0, 255, 0)]
[InlineData(0, 0, 255)]
[InlineData(255, 255, 255)]
[InlineData(128, 128, 128)]
public void ColorCanBeConstructedFromSystemDrawingColor(int r, int g, int b) {
var systemDrawingColor = System.Drawing.Color.FromArgb(r, g, b);
var color = new Color(systemDrawingColor);
Assert.Equal(r, color.R);
Assert.Equal(g, color.G);
Assert.Equal(b, color.B);
}

[Fact]
public void HsvConversion_GreyHasZeroHue() {
var testColor = new Color(128, 128, 128);
Expand Down Expand Up @@ -469,13 +484,6 @@ public void ColorCanBeInitializedFromQuotedStreamWithName() {
Assert.Equal(0.5, color.V, decimalPlaces);
}

[Fact]
public void ColorInitializingRequiresCachedColorWhenUsingName() {
var colorFactory = new ColorFactory();
var reader = new BufferedReader("= dark_moderate_cyan");
Assert.Throws<ArgumentException>(() => colorFactory.GetColor(reader));
}

[Fact]
public void ColorCanBeCachedFromStream() {
var colorFactory = new ColorFactory();
Expand All @@ -499,7 +507,7 @@ public void ColorCanBeInitializedWithName() {
var colorFactory = new ColorFactory();
colorFactory.AddNamedColor("dark_moderate_cyan", new Color(64, 128, 128));

var color = colorFactory.GetColor("dark_moderate_cyan");
var color = colorFactory.GetColorByName("dark_moderate_cyan");

Assert.Equal(64, color.R);
Assert.Equal(128, color.G);
Expand All @@ -510,6 +518,28 @@ public void ColorCanBeInitializedWithName() {
Assert.Equal(0.5, color.V, decimalPlaces);
}

[Theory]
[InlineData("white", "white")]
[InlineData("ck2_purple", "purple")]
[InlineData("purple", "purple")]
[InlineData("green_light", "green")]
[InlineData("yellow_light", "yellow")]
[InlineData("gray", "gray")]
[InlineData("grey", "gray")] // the classic
[InlineData("red_green_blue", "red")] // first matching word is used
[InlineData("snow_white", "snow")]
[InlineData("random_bullshit", "black")] // black is the final fallback
public void ColorCanBeReturnedEvenForUncachedName(string colorName, string expectedReturnedColorName) {
var colorFactory = new ColorFactory();

var color = colorFactory.GetColorByName(colorName);
var expectedColor = System.Drawing.Color.FromName(expectedReturnedColorName);

Assert.Equal(expectedColor.R, color.R);
Assert.Equal(expectedColor.G, color.G);
Assert.Equal(expectedColor.B, color.B);
}

private class Foo : Parser {
public Foo(BufferedReader reader) {
RegisterKeyword("color", colorReader => color = new ColorFactory().GetColor(colorReader));
Expand Down Expand Up @@ -668,7 +698,7 @@ public void ColorPaletteCanBeAlteredByStream() {
var reader2 = new BufferedReader("= hex { FFD700 }");
colorFactory.AddNamedColor("gold", reader2);

var gold = colorFactory.GetColor("gold");
var gold = colorFactory.GetColorByName("gold");

Assert.Equal(255, gold.R);
Assert.Equal(215, gold.G);
Expand All @@ -685,7 +715,7 @@ public void ColorPaletteCanBeAlteredDirectly() {
colorFactory.AddNamedColor("gold", new Color(255, 0, 0));
colorFactory.AddNamedColor("gold", new Color(255, 215, 0));

var gold = colorFactory.GetColor("gold");
var gold = colorFactory.GetColorByName("gold");

Assert.Equal(255, gold.R);
Assert.Equal(215, gold.G);
Expand Down
7 changes: 7 additions & 0 deletions commonItems/Colors/Color.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ public Color(double h, double s, double v) {
public Color(double h, double s, double v, double alpha) : this(h, s, v) {
A = alpha;
}

public Color(System.Drawing.Color color) {
RgbComponents[0] = color.R;
RgbComponents[1] = color.G;
RgbComponents[2] = color.B;
DeriveHsvFromRgb();
}

public override bool Equals(object? obj) {
return obj is Color color && RgbComponents.SequenceEqual(color.RgbComponents);
Expand Down
55 changes: 49 additions & 6 deletions commonItems/Colors/ColorFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,7 @@ public Color GetColor(BufferedReader reader) {
}
default: {
if (CommonRegexes.Catchall.IsMatch(token)) {
if (NamedColors.TryGetValue(token, out var value)) {
return value;
}
throw new ArgumentException($"{token} was not a cached color");
return GetColorByName(token);
}

foreach (var ch in token.ToCharArray().Reverse()) {
Expand All @@ -124,11 +121,57 @@ public Color GetColor(BufferedReader reader) {
}
}

public Color GetColor(string colorName) {
private static System.Drawing.Color? GetSystemDrawingColorByName(string colorName) {
try {
var color = System.Drawing.Color.FromName(colorName);
if (!color.IsKnownColor) {
return null;
}
if (color == System.Drawing.Color.Empty) {
return null;
}

return color;
} catch {
return null;
}
}

public Color GetColorByName(string colorName) {
if (NamedColors.TryGetValue(colorName, out var value)) {
return value;
}
throw new ArgumentException($"{colorName} was not a cached color");

Logger.Warn($"{colorName} was not a cached color");

// Try to find a color that matches the name.
var systemDrawingColor = GetSystemDrawingColorByName(colorName);
if (systemDrawingColor is not null) {
var color = new Color(systemDrawingColor.Value);
NamedColors[colorName] = color;
return color;
}

// Split the color name into words and try to find a color that matches each word.
foreach (string word in colorName.Split('_')) {
string wordToUse = word;
if (wordToUse == "grey") {
wordToUse = "gray";
}

var colorFromWord = GetSystemDrawingColorByName(wordToUse);
if (colorFromWord is null) {
continue;
}

var color = new Color(colorFromWord.Value);
NamedColors[colorName] = color;
return color;
}

// If all else fails, return black.
Logger.Warn($"No matching fallback color found for {colorName}, using black");
return new Color(System.Drawing.Color.Black);
}

public void AddNamedColor(string name, Color color) {
Expand Down
2 changes: 1 addition & 1 deletion commonItems/commonItems.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<GeneratePackageOnBuild>False</GeneratePackageOnBuild>
<PackageId>PGCG.$(AssemblyName)</PackageId>
<Version>9.2.0</Version>
<Version>10.0.0</Version>
<Authors>PGCG</Authors>
<PackageProjectUrl>https://github.com/ParadoxGameConverters/commonItems.NET</PackageProjectUrl>
<RepositoryUrl>https://github.com/ParadoxGameConverters/commonItems.NET</RepositoryUrl>
Expand Down
Loading