-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
LegacyComponentSerializerImpl.java
569 lines (497 loc) · 20.2 KB
/
LegacyComponentSerializerImpl.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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/*
* This file is part of adventure, licensed under the MIT License.
*
* Copyright (c) 2017-2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.text.serializer.legacy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.format.TextFormat;
import net.kyori.adventure.text.flattener.ComponentFlattener;
import net.kyori.adventure.text.flattener.FlattenerListener;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import static java.util.Objects.requireNonNull;
final class LegacyComponentSerializerImpl implements LegacyComponentSerializer {
static final Pattern DEFAULT_URL_PATTERN = Pattern.compile("(?:(https?)://)?([-\\w_.]+\\.\\w{2,})(/\\S*)?");
static final Pattern URL_SCHEME_PATTERN = Pattern.compile("^[a-z][a-z0-9+\\-.]*:");
private static final TextDecoration[] DECORATIONS = TextDecoration.values();
private static final char LEGACY_BUNGEE_HEX_CHAR = 'x';
private static final List<TextFormat> FORMATS;
private static final String LEGACY_CHARS;
static {
// Enumeration order may change - manually
final Map<TextFormat, String> formats = new LinkedHashMap<>(16 + 5 + 1); // colours + decorations + reset
formats.put(NamedTextColor.BLACK, "0");
formats.put(NamedTextColor.DARK_BLUE, "1");
formats.put(NamedTextColor.DARK_GREEN, "2");
formats.put(NamedTextColor.DARK_AQUA, "3");
formats.put(NamedTextColor.DARK_RED, "4");
formats.put(NamedTextColor.DARK_PURPLE, "5");
formats.put(NamedTextColor.GOLD, "6");
formats.put(NamedTextColor.GRAY, "7");
formats.put(NamedTextColor.DARK_GRAY, "8");
formats.put(NamedTextColor.BLUE, "9");
formats.put(NamedTextColor.GREEN, "a");
formats.put(NamedTextColor.AQUA, "b");
formats.put(NamedTextColor.RED, "c");
formats.put(NamedTextColor.LIGHT_PURPLE, "d");
formats.put(NamedTextColor.YELLOW, "e");
formats.put(NamedTextColor.WHITE, "f");
formats.put(TextDecoration.OBFUSCATED, "k");
formats.put(TextDecoration.BOLD, "l");
formats.put(TextDecoration.STRIKETHROUGH, "m");
formats.put(TextDecoration.UNDERLINED, "n");
formats.put(TextDecoration.ITALIC, "o");
formats.put(Reset.INSTANCE, "r");
FORMATS = Collections.unmodifiableList(new ArrayList<>(formats.keySet()));
LEGACY_CHARS = String.join("", formats.values());
// assert same length
if(FORMATS.size() != LEGACY_CHARS.length()) {
throw new IllegalStateException("FORMATS length differs from LEGACY_CHARS length");
}
}
static final LegacyComponentSerializer SECTION_SERIALIZER = new LegacyComponentSerializerImpl(SECTION_CHAR, HEX_CHAR, null, false, false, ComponentFlattener.basic());
static final LegacyComponentSerializer AMPERSAND_SERIALIZER = new LegacyComponentSerializerImpl(AMPERSAND_CHAR, HEX_CHAR, null, false, false, ComponentFlattener.basic());
private final char character;
private final char hexCharacter;
private final @Nullable TextReplacementConfig urlReplacementConfig;
private final boolean hexColours;
private final boolean useTerriblyStupidHexFormat; // (╯°□°)╯︵ ┻━┻
private final ComponentFlattener flattener;
LegacyComponentSerializerImpl(final char character, final char hexCharacter, final @Nullable TextReplacementConfig urlReplacementConfig, final boolean hexColours, final boolean useTerriblyStupidHexFormat, final ComponentFlattener flattener) {
this.character = character;
this.hexCharacter = hexCharacter;
this.urlReplacementConfig = urlReplacementConfig;
this.hexColours = hexColours;
this.useTerriblyStupidHexFormat = useTerriblyStupidHexFormat;
this.flattener = flattener;
}
private @Nullable FormatCodeType determineFormatType(final char legacy, final String input, final int pos) {
if(pos >= 14) {
// The BungeeCord RGB color format uses a repeating sequence of RGB values, each character formatted
// as their own color format string, and to make things interesting, all the colors are also valid
// Mojang colors. To differentiate this, we do a lookback check for &x (or equivalent) for its position
// in the string if it is indeed a BungeeCord-style RGB color.
final int expectedCharacterPosition = pos - 14;
final int expectedIndicatorPosition = pos - 13;
if(input.charAt(expectedCharacterPosition) == this.character && input.charAt(expectedIndicatorPosition) == LEGACY_BUNGEE_HEX_CHAR) {
return FormatCodeType.BUNGEECORD_UNUSUAL_HEX;
}
}
if(legacy == this.hexCharacter && input.length() - pos >= 6) {
return FormatCodeType.KYORI_HEX;
} else if(LEGACY_CHARS.indexOf(legacy) != -1) {
return FormatCodeType.MOJANG_LEGACY;
}
return null;
}
static @Nullable LegacyFormat legacyFormat(final char character) {
final int index = LEGACY_CHARS.indexOf(character);
if(index != -1) {
final TextFormat format = FORMATS.get(index);
if(format instanceof NamedTextColor) {
return new LegacyFormat((NamedTextColor) format);
} else if(format instanceof TextDecoration) {
return new LegacyFormat((TextDecoration) format);
} else if(format instanceof Reset) {
return LegacyFormat.RESET;
}
}
return null;
}
private @Nullable DecodedFormat decodeTextFormat(final char legacy, final String input, final int pos) {
final FormatCodeType foundFormat = this.determineFormatType(legacy, input, pos);
if(foundFormat == null) {
return null;
}
if(foundFormat == FormatCodeType.KYORI_HEX) {
final @Nullable TextColor parsed = tryParseHexColor(input.substring(pos, pos + 6));
if(parsed != null) {
return new DecodedFormat(foundFormat, parsed);
}
} else if(foundFormat == FormatCodeType.MOJANG_LEGACY) {
return new DecodedFormat(foundFormat, FORMATS.get(LEGACY_CHARS.indexOf(legacy)));
} else if(foundFormat == FormatCodeType.BUNGEECORD_UNUSUAL_HEX) {
final StringBuilder foundHex = new StringBuilder(6);
for(int i = pos - 1; i >= pos - 11; i -= 2) {
foundHex.append(input.charAt(i));
}
final @Nullable TextColor parsed = tryParseHexColor(foundHex.reverse().toString());
if(parsed != null) {
return new DecodedFormat(foundFormat, parsed);
}
}
return null;
}
private static @Nullable TextColor tryParseHexColor(final String hexDigits) {
try {
final int color = Integer.parseInt(hexDigits, 16);
return TextColor.color(color);
} catch(final NumberFormatException ex) {
return null;
}
}
private static boolean isHexTextColor(final TextFormat format) {
return format instanceof TextColor && !(format instanceof NamedTextColor);
}
private String toLegacyCode(TextFormat format) {
if(isHexTextColor(format)) {
final TextColor color = (TextColor) format;
if(this.hexColours) {
final String hex = String.format("%06x", color.value());
if(this.useTerriblyStupidHexFormat) {
// ah yes, wonderful. A 14 digit long completely unreadable string.
final StringBuilder legacy = new StringBuilder(String.valueOf(LEGACY_BUNGEE_HEX_CHAR));
for(final char character : hex.toCharArray()) {
legacy.append(this.character).append(character);
}
return legacy.toString();
} else {
// this is a bit nicer, hey?
return this.hexCharacter + hex;
}
} else {
// if we are not using hex colours, then convert the hex colour
// to the "nearest" possible named/standard text colour
format = NamedTextColor.nearestTo(color);
}
}
final int index = FORMATS.indexOf(format);
return Character.toString(LEGACY_CHARS.charAt(index));
}
private TextComponent extractUrl(final TextComponent component) {
if(this.urlReplacementConfig == null) return component;
final Component newComponent = component.replaceText(this.urlReplacementConfig);
if(newComponent instanceof TextComponent) return (TextComponent) newComponent;
return TextComponent.ofChildren(newComponent);
}
@Override
public @NonNull TextComponent deserialize(final @NonNull String input) {
int next = input.lastIndexOf(this.character, input.length() - 2);
if(next == -1) {
return this.extractUrl(Component.text(input));
}
final List<TextComponent> parts = new ArrayList<>();
TextComponent.Builder current = null;
boolean reset = false;
int pos = input.length();
do {
final DecodedFormat decoded = this.decodeTextFormat(input.charAt(next + 1), input, next + 2);
if(decoded != null) {
final int from = next + (decoded.encodedFormat == FormatCodeType.KYORI_HEX ? 8 : 2);
if(from != pos) {
if(current != null) {
if(reset) {
parts.add(current.build());
reset = false;
current = Component.text();
} else {
current = Component.text().append(current.build());
}
} else {
current = Component.text();
}
current.content(input.substring(from, pos));
} else if(current == null) {
current = Component.text();
}
if(!reset) {
reset = applyFormat(current, decoded.format);
}
if(decoded.encodedFormat == FormatCodeType.BUNGEECORD_UNUSUAL_HEX) {
// BungeeCord hex characters are a repeating set of characters, all of which are also valid
// legacy Mojang chat colors. Subtract the number of characters in the format, and only then
// skip ahead.
next -= 12;
}
pos = next;
}
next = input.lastIndexOf(this.character, next - 1);
} while(next != -1);
if(current != null) {
parts.add(current.build());
}
final String remaining = pos > 0 ? input.substring(0, pos) : "";
if(parts.size() == 1 && remaining.isEmpty()) {
return this.extractUrl(parts.get(0));
} else {
Collections.reverse(parts);
return this.extractUrl(Component.text().content(remaining).append(parts).build());
}
}
@Override
public @NonNull String serialize(final @NonNull Component component) {
final Cereal state = new Cereal();
this.flattener.flatten(component, state);
return state.toString();
}
private static boolean applyFormat(final TextComponent.@NonNull Builder builder, final @NonNull TextFormat format) {
if(format instanceof TextColor) {
builder.colorIfAbsent((TextColor) format);
return true;
} else if(format instanceof TextDecoration) {
builder.decoration((TextDecoration) format, TextDecoration.State.TRUE);
return false;
} else if(format instanceof Reset) {
return true;
}
throw new IllegalArgumentException(String.format("unknown format '%s'", format.getClass()));
}
@Override
public @NonNull Builder toBuilder() {
return new BuilderImpl(this);
}
private enum Reset implements TextFormat {
INSTANCE
}
// Are you hungry?
private final class Cereal implements FlattenerListener {
private final StringBuilder sb = new StringBuilder();
private final StyleState style = new StyleState();
private @Nullable TextFormat lastWritten;
private StyleState[] styles = new StyleState[8];
private int head = -1;
@Override
public void pushStyle(final @NonNull Style pushed) {
final int idx = ++this.head;
if(idx >= this.styles.length) {
this.styles = Arrays.copyOf(this.styles, this.styles.length * 2);
}
StyleState state = this.styles[idx];
if(state == null) {
this.styles[idx] = state = new StyleState();
}
if(idx > 0) {
// https://github.com/KyoriPowered/adventure/issues/287
// https://github.com/KyoriPowered/adventure/pull/299
state.set(this.styles[idx - 1]);
} else {
state.clear();
}
state.apply(pushed);
}
@Override
public void component(final @NonNull String text) {
if(!text.isEmpty()) {
if(this.head < 0) throw new IllegalStateException("No style has been pushed!");
this.styles[this.head].applyFormat();
this.sb.append(text);
}
}
@Override
public void popStyle(final @NonNull Style style) {
if(this.head-- < 0) {
throw new IllegalStateException("Tried to pop beyond what was pushed!");
}
}
void append(final @NonNull TextFormat format) {
if(this.lastWritten != format) {
this.sb.append(LegacyComponentSerializerImpl.this.character).append(LegacyComponentSerializerImpl.this.toLegacyCode(format));
}
this.lastWritten = format;
}
@Override
public String toString() {
return this.sb.toString();
}
private final class StyleState {
private @Nullable TextColor color;
private final Set<TextDecoration> decorations;
private boolean needsReset;
StyleState() {
this.decorations = EnumSet.noneOf(TextDecoration.class);
}
void set(final @NonNull StyleState that) {
this.color = that.color;
this.decorations.clear();
this.decorations.addAll(that.decorations);
}
public void clear() {
this.color = null;
this.decorations.clear();
}
void apply(final @NonNull Style component) {
final TextColor color = component.color();
if(color != null) {
this.color = color;
}
for(int i = 0, length = DECORATIONS.length; i < length; i++) {
final TextDecoration decoration = DECORATIONS[i];
switch(component.decoration(decoration)) {
case TRUE:
this.decorations.add(decoration);
break;
case FALSE:
if(this.decorations.remove(decoration)) {
this.needsReset = true;
}
break;
}
}
}
void applyFormat() {
final boolean colorChanged = this.color != Cereal.this.style.color;
if(this.needsReset) {
if(!colorChanged) {
Cereal.this.append(Reset.INSTANCE);
}
this.needsReset = false;
}
// If color changes, we need to do a full reset.
// Additionally, if the last thing to be appended was a reset then we need to re-apply everything.
if(colorChanged || Cereal.this.lastWritten == Reset.INSTANCE) {
this.applyFullFormat();
return;
}
// Does current have any decorations we don't have?
// Since there is no way to undo decorations, we need to reset these cases
if(!this.decorations.containsAll(Cereal.this.style.decorations)) {
this.applyFullFormat();
return;
}
// Apply new decorations
for(final TextDecoration decoration : this.decorations) {
if(Cereal.this.style.decorations.add(decoration)) {
Cereal.this.append(decoration);
}
}
}
private void applyFullFormat() {
if(this.color != null) {
Cereal.this.append(this.color);
} else {
Cereal.this.append(Reset.INSTANCE);
}
Cereal.this.style.color = this.color;
for(final TextDecoration decoration : this.decorations) {
Cereal.this.append(decoration);
}
Cereal.this.style.decorations.clear();
Cereal.this.style.decorations.addAll(this.decorations);
}
}
}
static final class BuilderImpl implements Builder {
private char character = LegacyComponentSerializer.SECTION_CHAR;
private char hexCharacter = LegacyComponentSerializer.HEX_CHAR;
private TextReplacementConfig urlReplacementConfig = null;
private boolean hexColours = false;
private boolean useTerriblyStupidHexFormat = false;
private ComponentFlattener flattener = ComponentFlattener.basic();
BuilderImpl() {
}
BuilderImpl(final @NonNull LegacyComponentSerializerImpl serializer) {
this.character = serializer.character;
this.hexCharacter = serializer.hexCharacter;
this.urlReplacementConfig = serializer.urlReplacementConfig;
this.hexColours = serializer.hexColours;
this.useTerriblyStupidHexFormat = serializer.useTerriblyStupidHexFormat;
}
@Override
public @NonNull Builder character(final char legacyCharacter) {
this.character = legacyCharacter;
return this;
}
@Override
public @NonNull Builder hexCharacter(final char legacyHexCharacter) {
this.hexCharacter = legacyHexCharacter;
return this;
}
@Override
public @NonNull Builder extractUrls() {
return this.extractUrls(DEFAULT_URL_PATTERN, null);
}
@Override
public @NonNull Builder extractUrls(final @NonNull Pattern pattern) {
return this.extractUrls(pattern, null);
}
@Override
public @NonNull Builder extractUrls(final @Nullable Style style) {
return this.extractUrls(DEFAULT_URL_PATTERN, style);
}
@Override
public @NonNull Builder extractUrls(final @NonNull Pattern pattern, final @Nullable Style style) {
requireNonNull(pattern, "pattern");
this.urlReplacementConfig = TextReplacementConfig.builder()
.match(pattern)
.replacement(url -> {
String clickUrl = url.content();
if(!URL_SCHEME_PATTERN.matcher(clickUrl).find()) {
clickUrl = "http://" + clickUrl;
}
return (style == null ? url : url.style(style)).clickEvent(ClickEvent.openUrl(clickUrl));
})
.build();
return this;
}
@Override
public @NonNull Builder hexColors() {
this.hexColours = true;
return this;
}
@Override
public @NonNull Builder useUnusualXRepeatedCharacterHexFormat() {
this.useTerriblyStupidHexFormat = true; // :(
return this;
}
@Override
public @NonNull Builder flattener(final @NonNull ComponentFlattener flattener) {
this.flattener = requireNonNull(flattener, "flattener");
return this;
}
@Override
public @NonNull LegacyComponentSerializer build() {
return new LegacyComponentSerializerImpl(this.character, this.hexCharacter, this.urlReplacementConfig, this.hexColours, this.useTerriblyStupidHexFormat, this.flattener);
}
}
enum FormatCodeType {
MOJANG_LEGACY,
KYORI_HEX,
BUNGEECORD_UNUSUAL_HEX;
}
static final class DecodedFormat {
final FormatCodeType encodedFormat;
final TextFormat format;
private DecodedFormat(final FormatCodeType encodedFormat, final TextFormat format) {
if(format == null) {
throw new IllegalStateException("No format found");
}
this.encodedFormat = encodedFormat;
this.format = format;
}
}
}