|
1 | 1 | using CommunityToolkit.WinUI.Helpers;
|
2 | 2 | using System;
|
| 3 | +using System.Globalization; |
3 | 4 | using Windows.UI;
|
4 | 5 |
|
5 | 6 | namespace Files.App.Helpers
|
6 | 7 | {
|
7 | 8 | internal static class ColorHelpers
|
8 | 9 | {
|
| 10 | + private const int COLOR_LENGTH = 7; |
| 11 | + private const int COLOR_LENGTH_INCLUDING_ALPHA = 9; |
| 12 | + |
| 13 | + private static readonly Color unknownTagColor = Color.FromArgb(255, 0x9E, 0xA3, 0xA1); |
| 14 | + |
9 | 15 | /// <summary>
|
10 | 16 | /// Converts Hex to Windows.UI.Color.
|
11 | 17 | /// </summary>
|
12 |
| - public static Color FromHex(string colorHex) |
| 18 | + public static Color FromHex(string? colorHex) |
13 | 19 | {
|
| 20 | + // If Hex string is invalid, return Unknown Tag's color |
| 21 | + if ( |
| 22 | + string.IsNullOrWhiteSpace(colorHex) || |
| 23 | + (colorHex.Length != COLOR_LENGTH && colorHex.Length != COLOR_LENGTH_INCLUDING_ALPHA) |
| 24 | + ) |
| 25 | + return unknownTagColor; |
| 26 | + |
14 | 27 | colorHex = colorHex.Replace("#", string.Empty);
|
15 | 28 |
|
16 | 29 | var alphaOffset = colorHex.Length == 8 ? 2 : 0;
|
17 | 30 |
|
18 |
| - var a = alphaOffset == 2 ? (byte)Convert.ToUInt32(colorHex.Substring(0, 2), 16) : (byte)255; |
19 |
| - var r = (byte)Convert.ToUInt32(colorHex.Substring(alphaOffset, 2), 16); |
20 |
| - var g = (byte)Convert.ToUInt32(colorHex.Substring(alphaOffset + 2, 2), 16); |
21 |
| - var b = (byte)Convert.ToUInt32(colorHex.Substring(alphaOffset + 4, 2), 16); |
| 31 | + var a = (byte)255; |
| 32 | + var alphaValid = alphaOffset == 0 || byte.TryParse(colorHex.AsSpan(0, 2), NumberStyles.HexNumber, null, out a); |
| 33 | + |
| 34 | + if ( |
| 35 | + alphaValid && |
| 36 | + byte.TryParse(colorHex.AsSpan(alphaOffset, 2), NumberStyles.HexNumber, null, out byte r) && |
| 37 | + byte.TryParse(colorHex.AsSpan(alphaOffset + 2, 2), NumberStyles.HexNumber, null, out byte g) && |
| 38 | + byte.TryParse(colorHex.AsSpan(alphaOffset + 4, 2), NumberStyles.HexNumber, null, out byte b) |
| 39 | + ) |
| 40 | + return Color.FromArgb(a, r, g, b); |
22 | 41 |
|
23 |
| - return Color.FromArgb(a, r, g, b); |
| 42 | + return unknownTagColor; |
24 | 43 | }
|
25 | 44 |
|
26 | 45 | /// <summary>
|
27 | 46 | /// Converts Uint to Windows.UI.Color.
|
28 | 47 | /// </summary>
|
29 | 48 | public static Color FromUint(this uint value)
|
30 | 49 | {
|
31 |
| - return Windows.UI.Color.FromArgb((byte)((value >> 24) & 0xFF), |
| 50 | + return Color.FromArgb((byte)((value >> 24) & 0xFF), |
32 | 51 | (byte)((value >> 16) & 0xFF),
|
33 | 52 | (byte)((value >> 8) & 0xFF),
|
34 | 53 | (byte)(value & 0xFF));
|
|
0 commit comments