/
FormattedTextHelper.java
461 lines (445 loc) · 23.9 KB
/
FormattedTextHelper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package com.denizenscript.denizen.utilities;
import com.denizenscript.denizen.nms.NMSHandler;
import com.denizenscript.denizen.nms.NMSVersion;
import com.denizenscript.denizen.objects.EntityTag;
import com.denizenscript.denizen.objects.ItemTag;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.*;
import java.util.List;
public class FormattedTextHelper {
// <--[language]
// @name Denizen Text Formatting
// @group Denizen Magic
// @description
// Denizen provides a variety of special chat format options like "on_hover" and "on_click".
// These options exist within Denizen and do not appear in the historical Minecraft legacy chat format that most plugins and systems read.
// That legacy system has 16 colors (0-9, A-F) and a few toggleable formats (bold, italic, etc). It does not contain anything that needs more than just an on/off.
//
// Modern Minecraft, however, supports a JSON based "raw" message format that can do click events, hover events, full RGB colors, etc.
//
// Denizen therefore has its own internal system that works like the legacy format system, but also supports the new options normally only available as 'raw JSON'.
//
// Because it is entirely processed within Denizen, these options only work within Denizen, when performing actions that support raw JSON input.
// This magic tool exists to let you write messages without having to write the messy JSON.
//
// Be aware that many inputs do not support raw JSON, and as such are limited only the historical Minecraft legacy format.
// Also be aware that click events, hover events, etc. are exclusively limited to the chat bar and the pages of books, as you cannot mouse over anything else.
//
// Also note that RGB colors use a format that Spigot invented, meaning they will work in places that use Spigot's parser OR Denizen's version, but nowhere that uses the vanilla format still.
// -->
public static String escape(String input) {
return input.replace("&", "&").replace(";", "&sc").replace("[", "&lb").replace("]", "&rb").replace(String.valueOf(ChatColor.COLOR_CHAR), "&ss");
}
public static String unescape(String input) {
return input.replace("&sc", ";").replace("&lb", "[").replace("&rb", "]").replace("&ss", String.valueOf(ChatColor.COLOR_CHAR)).replace("&", "&");
}
public static String stringify(BaseComponent[] components) {
StringBuilder builder = new StringBuilder(128 * components.length);
for (BaseComponent component : components) {
builder.append(stringify(component));
}
while (builder.toString().endsWith(RESET)) {
builder.setLength(builder.length() - RESET.length());
}
return builder.toString();
}
public static boolean boolNotNull(Boolean bool) {
return bool != null && bool;
}
public static String stringifyRGBSpigot(String hex) {
while (hex.length() < 6) {
hex = "0" + hex;
}
hex = "x" + hex;
StringBuilder outColor = new StringBuilder();
for (char c : hex.toCharArray()) {
outColor.append(org.bukkit.ChatColor.COLOR_CHAR).append(c);
}
return outColor.toString();
}
public static String stringify(BaseComponent component) {
StringBuilder builder = new StringBuilder(128);
ChatColor color = component.getColorRaw();
if (color != null) {
builder.append(color.toString());
}
if (boolNotNull(component.isBoldRaw())) {
builder.append(ChatColor.BOLD.toString());
}
if (boolNotNull(component.isItalicRaw())) {
builder.append(ChatColor.ITALIC.toString());
}
if (boolNotNull(component.isStrikethroughRaw())) {
builder.append(ChatColor.STRIKETHROUGH.toString());
}
if (boolNotNull(component.isUnderlinedRaw())) {
builder.append(ChatColor.UNDERLINE.toString());
}
if (boolNotNull(component.isObfuscatedRaw())) {
builder.append(ChatColor.MAGIC.toString());
}
boolean hasInsertion = component.getInsertion() != null;
if (hasInsertion) {
builder.append(ChatColor.COLOR_CHAR).append("[insertion=").append(escape(component.getInsertion())).append("]");
}
boolean hasHover = component.getHoverEvent() != null;
if (hasHover) {
HoverEvent hover = component.getHoverEvent();
builder.append(ChatColor.COLOR_CHAR).append("[hover=").append(hover.getAction().name()).append(";").append(escape(NMSHandler.getInstance().stringForHover(hover))).append("]");
}
boolean hasClick = component.getClickEvent() != null;
if (hasClick) {
ClickEvent click = component.getClickEvent();
builder.append(ChatColor.COLOR_CHAR).append("[click=").append(click.getAction().name()).append(";").append(escape(click.getValue())).append("]");
}
if (component instanceof TextComponent) {
builder.append(((TextComponent) component).getText());
}
else if (component instanceof TranslatableComponent) {
builder.append(ChatColor.COLOR_CHAR).append("[translate=").append(escape(((TranslatableComponent) component).getTranslate()));
List<BaseComponent> with = ((TranslatableComponent) component).getWith();
if (with != null) {
for (BaseComponent withComponent : with) {
builder.append(";").append(escape(stringify(withComponent)));
}
}
builder.append("]");
}
else if (component instanceof SelectorComponent) {
builder.append(ChatColor.COLOR_CHAR).append("[selector=").append(escape(((SelectorComponent) component).getSelector())).append("]");
}
else if (component instanceof KeybindComponent) {
builder.append(ChatColor.COLOR_CHAR).append("[keybind=").append(escape(((KeybindComponent) component).getKeybind())).append("]");
}
else if (component instanceof ScoreComponent) {
builder.append(ChatColor.COLOR_CHAR).append("[score=").append(escape(((ScoreComponent) component).getName()))
.append(";").append(escape(((ScoreComponent) component).getObjective()))
.append(";").append(escape(((ScoreComponent) component).getValue())).append("]");
}
List<BaseComponent> after = component.getExtra();
if (after != null) {
for (BaseComponent afterComponent : after) {
builder.append(stringify(afterComponent));
}
}
if (hasClick) {
builder.append(ChatColor.COLOR_CHAR + "[/click]");
}
if (hasHover) {
builder.append(ChatColor.COLOR_CHAR + "[/hover]");
}
if (hasInsertion) {
builder.append(ChatColor.COLOR_CHAR + "[/insertion]");
}
builder.append(RESET);
String output = builder.toString();
while (output.contains(RESET + WHITE)) {
output = output.replace(RESET + WHITE, RESET);
}
while (output.contains(RESET + RESET)) {
output = output.replace(RESET + RESET, RESET);
}
return output;
}
public static final String WHITE = ChatColor.WHITE.toString();
public static final String RESET = ChatColor.RESET.toString();
public static TextComponent copyFormatToNewText(TextComponent last) {
TextComponent toRet = new TextComponent();
toRet.setObfuscated(last.isObfuscatedRaw());
toRet.setBold(last.isBoldRaw());
toRet.setStrikethrough(last.isStrikethroughRaw());
toRet.setUnderlined(last.isUnderlinedRaw());
toRet.setItalic(last.isItalicRaw());
toRet.setColor(last.getColorRaw());
return toRet;
}
public static BaseComponent[] parse(String str) {
return parse(str, true);
}
public static BaseComponent[] parse(String str, boolean cleanBase) {
str = CoreUtilities.clearNBSPs(str);
int firstChar = str.indexOf(ChatColor.COLOR_CHAR);
if (firstChar == -1) {
TextComponent base = new TextComponent();
base.addExtra(new TextComponent(str)); // This is for compat with how Spigot does parsing of plaintext.
return new BaseComponent[] { base };
}
TextComponent root = new TextComponent(str.substring(0, firstChar));
TextComponent base = new TextComponent();
if (cleanBase) {
base.setBold(false);
base.setItalic(false);
base.setStrikethrough(false);
base.setUnderlined(false);
base.setObfuscated(false);
base.setColor(ChatColor.WHITE);
}
root.addExtra(base);
str = str.substring(firstChar);
char[] chars = str.toCharArray();
int started = 0;
TextComponent nextText = new TextComponent();
TextComponent lastText = new TextComponent();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == ChatColor.COLOR_CHAR && i + 1 < chars.length) {
char code = chars[i + 1];
if (code == '[') {
int endBracket = str.indexOf(']', i + 2);
if (endBracket == -1) {
continue;
}
String innards = str.substring(i + 2, endBracket);
List<String> innardParts = CoreUtilities.split(innards, ';');
List<String> innardBase = CoreUtilities.split(innardParts.get(0), '=', 2);
innardParts.remove(0);
String innardType = CoreUtilities.toLowerCase(innardBase.get(0));
if (innardBase.size() == 2) {
nextText.setText(nextText.getText() + str.substring(started, i));
base.addExtra(nextText);
TextComponent doublelasttext = lastText;
lastText = nextText;
nextText = copyFormatToNewText(lastText);
nextText.setText("");
if (innardType.equals("score") && innardParts.size() == 2) {
ScoreComponent component = new ScoreComponent(unescape(innardBase.get(1)), unescape(innardParts.get(0)), unescape(innardParts.get(1)));
lastText.addExtra(component);
}
else if (innardType.equals("keybind")) {
KeybindComponent component = new KeybindComponent();
component.setKeybind(unescape(innardBase.get(1)));
lastText.addExtra(component);
}
else if (innardType.equals("selector")) {
SelectorComponent component = new SelectorComponent(unescape(innardBase.get(1)));
lastText.addExtra(component);
}
else if (innardType.equals("translate")) {
TranslatableComponent component = new TranslatableComponent();
component.setTranslate(unescape(innardBase.get(1)));
for (String extra : innardParts) {
for (BaseComponent subComponent : parse(unescape(extra), false)) {
component.addWith(subComponent);
}
}
lastText.addExtra(component);
}
else if (innardType.equals("click") && innardParts.size() == 1) {
int endIndex = str.indexOf(ChatColor.COLOR_CHAR + "[/click]", i);
int backupEndIndex = str.indexOf(ChatColor.COLOR_CHAR + "[click=", i + 5);
if (backupEndIndex > 0 && backupEndIndex < endIndex) {
endIndex = backupEndIndex;
}
if (endIndex == -1) {
continue;
}
TextComponent clickableText = new TextComponent();
clickableText.setClickEvent(new ClickEvent(ClickEvent.Action.valueOf(innardBase.get(1).toUpperCase()), unescape(innardParts.get(0))));
for (BaseComponent subComponent : parse(str.substring(endBracket + 1, endIndex), false)) {
clickableText.addExtra(subComponent);
}
lastText.addExtra(clickableText);
endBracket = endIndex + "&[/click".length();
}
else if (innardType.equals("hover")) {
int endIndex = str.indexOf(ChatColor.COLOR_CHAR + "[/hover]", i);
int backupEndIndex = str.indexOf(ChatColor.COLOR_CHAR + "[hover=", i + 5);
if (backupEndIndex > 0 && backupEndIndex < endIndex) {
endIndex = backupEndIndex;
}
if (endIndex == -1) {
continue;
}
TextComponent hoverableText = new TextComponent();
HoverEvent.Action action = HoverEvent.Action.valueOf(innardBase.get(1).toUpperCase());
if (NMSHandler.getVersion().isAtLeast(NMSVersion.v1_16)) {
if (HoverFormatHelper.processHoverInput(action, hoverableText, innardParts.get(0))) {
continue;
}
}
else {
BaseComponent[] hoverValue;
if (action == HoverEvent.Action.SHOW_ITEM) {
ItemTag item = ItemTag.valueOf(unescape(innardParts.get(0)), CoreUtilities.noDebugContext);
if (item == null) {
continue;
}
hoverValue = new BaseComponent[] {new TextComponent(NMSHandler.getItemHelper().getRawHoverText(item.getItemStack()))};
}
else if (action == HoverEvent.Action.SHOW_ENTITY) {
EntityTag entity = EntityTag.valueOf(unescape(innardParts.get(0)), CoreUtilities.basicContext);
if (entity == null) {
continue;
}
hoverValue = new BaseComponent[] {new TextComponent(NMSHandler.getEntityHelper().getRawHoverText(entity.getBukkitEntity()))};
}
else {
hoverValue = parse(unescape(innardParts.get(0)), false);
}
hoverableText.setHoverEvent(new HoverEvent(action, hoverValue));
}
for (BaseComponent subComponent : parse(str.substring(endBracket + 1, endIndex), false)) {
hoverableText.addExtra(subComponent);
}
lastText.addExtra(hoverableText);
endBracket = endIndex + "&[/hover".length();
}
else if (innardType.equals("insertion")) {
int endIndex = str.indexOf(ChatColor.COLOR_CHAR + "[/insertion]", i);
int backupEndIndex = str.indexOf(ChatColor.COLOR_CHAR + "[insertion=", i + 5);
if (backupEndIndex > 0 && backupEndIndex < endIndex) {
endIndex = backupEndIndex;
}
if (endIndex == -1) {
continue;
}
TextComponent insertableText = new TextComponent();
insertableText.setInsertion(unescape(innardBase.get(1)));
for (BaseComponent subComponent : parse(str.substring(endBracket + 1, endIndex), false)) {
insertableText.addExtra(subComponent);
}
lastText.addExtra(insertableText);
endBracket = endIndex + "&[/insertion".length();
}
else if (innardType.equals("reset")) {
if (innardBase.get(1).length() == 1) {
char subCode = innardBase.get(1).charAt(0);
if (subCode == 'k' || subCode == 'K') {
nextText.setObfuscated(false);
}
else if (subCode == 'l' || subCode == 'L') {
nextText.setBold(false);
}
else if (subCode == 'm' || subCode == 'M') {
nextText.setStrikethrough(false);
}
else if (subCode == 'n' || subCode == 'N') {
nextText.setUnderlined(false);
}
else if (subCode == 'o' || subCode == 'O') {
nextText.setItalic(false);
}
}
else if (innardBase.get(1).equals("font")) {
nextText.setFont(doublelasttext.getFont());
}
else {
nextText.setColor(doublelasttext.getColor());
}
}
else if (innardType.equals("color")) {
String colorChar = innardBase.get(1);
if (colorChar.length() == 1) {
nextText.setColor(ChatColor.getByChar(colorChar.charAt(0)));
}
else if (colorChar.length() == 7) {
nextText.setColor(ChatColor.of(colorChar));
}
}
else if (innardType.equals("font")) {
nextText.setFont(innardBase.get(1));
}
}
i = endBracket;
started = endBracket + 1;
continue;
}
else if ((code >= '0' && code <= '9') || (code >= 'a' && code <= 'f') || (code >= 'A' && code <= 'F')) {
nextText.setText(nextText.getText() + str.substring(started, i));
if (!nextText.getText().isEmpty()) {
base.addExtra(nextText);
}
nextText = new TextComponent();
nextText.setColor(ChatColor.getByChar(code));
}
else if ((code >= 'k' && code <= 'o') || (code >= 'K' && code <= 'O')) {
nextText.setText(nextText.getText() + str.substring(started, i));
if (!nextText.getText().isEmpty()) {
base.addExtra(nextText);
}
nextText = copyFormatToNewText(nextText);
if (code == 'k' || code == 'K') {
nextText.setObfuscated(true);
}
else if (code == 'l' || code == 'L') {
nextText.setBold(true);
}
else if (code == 'm' || code == 'M') {
nextText.setStrikethrough(true);
}
else if (code == 'n' || code == 'N') {
nextText.setUnderlined(true);
}
else if (code == 'o' || code == 'O') {
nextText.setItalic(true);
}
}
else if (code == 'r' || code == 'R') {
nextText.setText(nextText.getText() + str.substring(started, i));
if (!nextText.getText().isEmpty()) {
base.addExtra(nextText);
}
nextText = new TextComponent();
nextText.setColor(ChatColor.WHITE);
}
else if (code == 'x') {
if (i + 13 >= chars.length) {
continue;
}
StringBuilder color = new StringBuilder(12);
color.append("#");
for (int c = 1; c <= 6; c++) {
if (chars[i + c * 2] != ChatColor.COLOR_CHAR) {
color = null;
break;
}
color.append(chars[i + 1 + c * 2]);
}
if (color == null) {
continue;
}
nextText.setText(nextText.getText() + str.substring(started, i));
if (!nextText.getText().isEmpty()) {
base.addExtra(nextText);
}
nextText = new TextComponent();
nextText.setColor(ChatColor.of(color.toString()));
i += 13;
started = i + 1;
continue;
}
else {
continue;
}
i++;
started = i + 1;
}
else if (i + "https://a.".length() < chars.length && chars[i] == 'h' && chars[i + 1] == 't' && chars[i + 2] == 't' && chars[i + 3] == 'p') {
String subStr = str.substring(i, i + "https://a.".length());
if (subStr.startsWith("https://") || subStr.startsWith("http://")) {
int nextSpace = CoreUtilities.indexOfAny(str, i, ' ', '\t', '\n');
if (nextSpace == -1) {
nextSpace = str.length();
}
String url = str.substring(i, nextSpace);
nextText.setText(nextText.getText() + str.substring(started, i));
base.addExtra(nextText);
lastText = nextText;
nextText = new TextComponent(lastText);
nextText.setText("");
TextComponent clickableText = new TextComponent(url);
clickableText.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
lastText.addExtra(clickableText);
i = nextSpace;
started = nextSpace;
continue;
}
}
}
nextText.setText(nextText.getText() + str.substring(started));
if (!nextText.getText().isEmpty()) {
base.addExtra(nextText);
}
return new BaseComponent[] { cleanBase ? root : base };
}
}