diff --git a/src/main/java/com/laytonsmith/PureUtilities/TermColors.java b/src/main/java/com/laytonsmith/PureUtilities/TermColors.java index 0854e02e9..a7ac898b7 100644 --- a/src/main/java/com/laytonsmith/PureUtilities/TermColors.java +++ b/src/main/java/com/laytonsmith/PureUtilities/TermColors.java @@ -155,6 +155,13 @@ public static void cls() { @TermColor public static String RESET = special("reset"); + private static final byte[] RGB2ANSI_TABLE = { + 0, 4, 4, 4, 2, 8, 12, 12, 2, 2, 6, 6, 10, 10, 10, 14, + 1, 5, 4, 4, 8, 8, 12, 12, 2, 2, 6, 7, 10, 10, 10, 14, + 1, 9, 5, 12, 1, 9, 5, 12, 11, 7, 7, 7, 10, 10, 14, 14, + 1, 9, 5, 13, 1, 9, 5, 13, 3, 3, 7, 13, 11, 11, 11, 15 + }; + private static final Map DEFAULTS = new HashMap(); private static List fields = null; @@ -285,6 +292,25 @@ private static String color(Color c, boolean bright, boolean foreground, boolean return "\033[" + (resetCurrent ? "0;" : "") + color + ";" + (bright ? "1" : "22") + "m"; } + /** + * Converts a RGB color to its (perceptually) closest equivalent. + * @param hex A 6-characters wide hexadecimal-formatted string containing the RRGGBB pattern. + * @return The ANSI string representing such color; {@code null} if an invalid pattern was passed to {@code hex}. + */ + public static String fromRGB(String hex) { + String ret = null; + if(hex.matches("(?i)^[a-z0-9]{6}$")) { + int hexValue = Integer.parseInt(hex, 16); + byte code = RGB2ANSI_TABLE[ + 16 * Math.round(((hexValue >> 16) & 0xFF) / (float) 0x55) + + 4 * Math.round(((hexValue >> 8) & 0xFF) / (float) 0x55) + + Math.round((hexValue & 0xFF) / (float) 0x55) + ]; + ret = "\033[" + (30 + (code & 7)) + ";" + ((code & 0x8) != 0 ? "1" : "22") + "m"; + } + return ret; + } + public static void p(CharSequence c) { StreamUtils.GetSystemOut().print(c); StreamUtils.GetSystemOut().flush(); diff --git a/src/main/java/com/laytonsmith/core/Static.java b/src/main/java/com/laytonsmith/core/Static.java index 7320baddd..41e38f897 100644 --- a/src/main/java/com/laytonsmith/core/Static.java +++ b/src/main/java/com/laytonsmith/core/Static.java @@ -1181,6 +1181,11 @@ public static String MCToANSIColors(String mes) { if(mes == null) { return null; } + if(mes.length() > 13) { + mes = Pattern.compile("(?i)§x(§[0-9A-F]){6}").matcher(mes).replaceAll(match -> { + return TermColors.fromRGB(match.group(0).substring(2).replaceAll("§", "")); + }); + } return mes .replaceAll("§0", TermColors.BLACK) .replaceAll("§1", TermColors.BLUE) @@ -1203,9 +1208,7 @@ public static String MCToANSIColors(String mes) { .replaceAll("§m", TermColors.STRIKE) .replaceAll("§n", TermColors.UNDERLINE) .replaceAll("§o", TermColors.ITALIC) - .replaceAll("§r", TermColors.RESET) - .replaceAll("(?i)§x(§[a-f0-9]){6}", ""); - + .replaceAll("§r", TermColors.RESET); } public static MCCommandSender GetInjectedPlayer(String name) {