1111 */
1212public class Colors {
1313
14- private static final Pattern PATTERN = Pattern . compile ( "<#([A-Fa-f0-9]){6}>" ) ;
15- private static boolean supportHex ;
14+ private static final char COLOR_PREFIX = '&' ;
15+ private static Replacer replacer ;
1616
17- static {
18- try {
19- Class .forName ("net.md_5.bungee.api.ChatColor" )
20- .getDeclaredMethod ("of" , String .class );
21- supportHex = true ;
22- } catch (Throwable t ){
23- supportHex = false ;
17+ /**
18+ * Initialize util. Do not call this method manually
19+ * @param replaceRgb Replace RGB tags
20+ */
21+ public static void init (boolean replaceRgb ) {
22+ if (isSupportRgb () && replaceRgb ) {
23+ replacer = new RgbReplacer ();
24+ } else {
25+ replacer = new SimpleReplacer ();
2426 }
2527 }
2628
@@ -30,20 +32,7 @@ public class Colors {
3032 * @return String with replaced colors
3133 */
3234 public static String of (String line ) {
33- if (supportHex ) {
34- Matcher matcher = PATTERN .matcher (line );
35-
36- while (matcher .find ()) {
37- net .md_5 .bungee .api .ChatColor hexColor = net .md_5 .bungee .api .ChatColor .of (matcher .group ()
38- .substring (1 , matcher .group ().length () - 1 ));
39- String before = line .substring (0 , matcher .start ());
40- String after = line .substring (matcher .end ());
41- line = before + hexColor + after ;
42- matcher = PATTERN .matcher (line );
43- }
44- }
45-
46- return ChatColor .translateAlternateColorCodes ('&' , line );
35+ return replacer .replace (line );
4736 }
4837
4938 /**
@@ -71,4 +60,48 @@ public static String[] ofArr(String[] array){
7160 return array ;
7261 }
7362
63+ private static boolean isSupportRgb () {
64+ try {
65+ Class .forName ("net.md_5.bungee.api.ChatColor" )
66+ .getDeclaredMethod ("of" , String .class );
67+ return true ;
68+ } catch (Throwable t ) {
69+ return false ;
70+ }
71+ }
72+
73+ private interface Replacer {
74+ String replace (String input );
75+ }
76+
77+ private static class SimpleReplacer implements Replacer {
78+
79+ @ Override
80+ public String replace (String input ) {
81+ return ChatColor .translateAlternateColorCodes (COLOR_PREFIX , input );
82+ }
83+ }
84+
85+ private static class RgbReplacer implements Replacer {
86+
87+ private static final Pattern PATTERN = Pattern .compile ("<#([A-Fa-f0-9]){6}>" );
88+
89+ @ Override
90+ public String replace (String input ) {
91+ Matcher matcher = PATTERN .matcher (input );
92+
93+ while (matcher .find ()) {
94+ String group = matcher .group ();
95+ net .md_5 .bungee .api .ChatColor hexColor = net .md_5 .bungee .api .ChatColor .of (group
96+ .substring (1 , group .length () - 1 ));
97+ String before = input .substring (0 , matcher .start ());
98+ String after = input .substring (matcher .end ());
99+ input = before + hexColor + after ;
100+ matcher = PATTERN .matcher (input );
101+ }
102+
103+ return ChatColor .translateAlternateColorCodes (COLOR_PREFIX , input );
104+ }
105+ }
106+
74107}
0 commit comments