forked from CodeCrafter47/BungeeTabListPlus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractTabOverlayHandler.java
More file actions
2501 lines (2243 loc) · 119 KB
/
Copy pathAbstractTabOverlayHandler.java
File metadata and controls
2501 lines (2243 loc) · 119 KB
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2025 proferabg
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package codecrafter47.bungeetablistplus.handler;
import codecrafter47.bungeetablistplus.protocol.PacketHandler;
import codecrafter47.bungeetablistplus.protocol.PacketListenerResult;
import codecrafter47.bungeetablistplus.protocol.Team;
import codecrafter47.bungeetablistplus.util.BitSet;
import codecrafter47.bungeetablistplus.util.ConcurrentBitSet;
import codecrafter47.bungeetablistplus.util.Property119Handler;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.velocitypowered.api.network.ProtocolVersion;
import com.velocitypowered.proxy.protocol.MinecraftPacket;
import com.velocitypowered.proxy.protocol.packet.HeaderAndFooterPacket;
import com.velocitypowered.proxy.protocol.packet.LegacyPlayerListItemPacket;
import com.velocitypowered.proxy.protocol.packet.chat.ComponentHolder;
import de.codecrafter47.taboverlay.Icon;
import de.codecrafter47.taboverlay.ProfileProperty;
import de.codecrafter47.taboverlay.config.misc.ChatFormat;
import de.codecrafter47.taboverlay.config.misc.Unchecked;
import de.codecrafter47.taboverlay.handler.*;
import it.unimi.dsi.fastutil.objects.*;
import lombok.*;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.velocitypowered.proxy.protocol.packet.LegacyPlayerListItemPacket.ADD_PLAYER;
import static com.velocitypowered.proxy.protocol.packet.LegacyPlayerListItemPacket.REMOVE_PLAYER;
import static com.velocitypowered.proxy.protocol.packet.LegacyPlayerListItemPacket.UPDATE_DISPLAY_NAME;
import static com.velocitypowered.proxy.protocol.packet.LegacyPlayerListItemPacket.UPDATE_GAMEMODE;
import static com.velocitypowered.proxy.protocol.packet.LegacyPlayerListItemPacket.UPDATE_LATENCY;
public abstract class AbstractTabOverlayHandler implements PacketHandler, TabOverlayHandler {
// some options
private static final boolean OPTION_ENABLE_CUSTOM_SLOT_USERNAME_COLLISION_CHECK = true;
private static final boolean OPTION_ENABLE_CUSTOM_SLOT_UUID_COLLISION_CHECK = true;
private static final boolean OPTION_ENABLE_CONSISTENCY_CHECKS = true;
private static ComponentHolder EMPTY_COMPONENT;
protected static final String[][] EMPTY_PROPERTIES_ARRAY = new String[0][];
private static final ImmutableMap<RectangularTabOverlay.Dimension, BitSet> DIMENSION_TO_USED_SLOTS;
private static final BitSet[] SIZE_TO_USED_SLOTS;
private static final UUID[] CUSTOM_SLOT_UUID_STEVE;
private static final UUID[] CUSTOM_SLOT_UUID_ALEX;
private static final UUID[] CUSTOM_SLOT_UUID_SPACER;
private static final Set<UUID> CUSTOM_SLOT_UUIDS;
private static final String[] CUSTOM_SLOT_USERNAME;
private static final String[] CUSTOM_SLOT_USERNAME_SMILEYS;
private static final Set<String> CUSTOM_SLOT_USERNAMES;
private static final String[] CUSTOM_SLOT_TEAMNAME;
private static final Set<String> CUSTOM_SLOT_TEAMNAMES;
private static final Set<String> blockedTeams = new HashSet<>();
static {
// build the dimension to used slots map (for the rectangular tab overlay)
val builder = ImmutableMap.<RectangularTabOverlay.Dimension, BitSet>builder();
for (int columns = 1; columns <= 4; columns++) {
for (int rows = 0; rows <= 20; rows++) {
if (columns != 1 && rows != 0 && columns * rows <= (columns - 1) * 20)
continue;
BitSet usedSlots = new BitSet(80);
for (int column = 0; column < columns; column++) {
for (int row = 0; row < rows; row++) {
usedSlots.set(index(column, row));
}
}
builder.put(new RectangularTabOverlay.Dimension(columns, rows), usedSlots);
}
}
DIMENSION_TO_USED_SLOTS = builder.build();
// build the size to used slots map (for the simple tab overlay)
SIZE_TO_USED_SLOTS = new BitSet[81];
for (int size = 0; size <= 80; size++) {
BitSet usedSlots = new BitSet(80);
usedSlots.set(0, size);
SIZE_TO_USED_SLOTS[size] = usedSlots;
}
// generate random uuids for our custom slots
CUSTOM_SLOT_UUID_ALEX = new UUID[80];
CUSTOM_SLOT_UUID_STEVE = new UUID[80];
CUSTOM_SLOT_UUID_SPACER = new UUID[17];
UUID base = UUID.randomUUID();
long msb = base.getMostSignificantBits();
long lsb = base.getLeastSignificantBits();
lsb ^= base.hashCode();
for (int i = 0; i < 80; i++) {
CUSTOM_SLOT_UUID_STEVE[i] = new UUID(msb, lsb ^ (2 * i));
CUSTOM_SLOT_UUID_ALEX[i] = new UUID(msb, lsb ^ (2 * i + 1));
}
for (int i = 0; i < 17; i++) {
CUSTOM_SLOT_UUID_SPACER[i] = new UUID(msb, lsb ^ (160 + i));
}
if (OPTION_ENABLE_CUSTOM_SLOT_UUID_COLLISION_CHECK) {
CUSTOM_SLOT_UUIDS = ImmutableSet.<UUID>builder()
.add(CUSTOM_SLOT_UUID_ALEX)
.add(CUSTOM_SLOT_UUID_STEVE)
.add(CUSTOM_SLOT_UUID_SPACER).build();
} else {
CUSTOM_SLOT_UUIDS = null;
}
// generate usernames for custom slots
int unique = ThreadLocalRandom.current().nextInt();
CUSTOM_SLOT_USERNAME = new String[81];
for (int i = 0; i < 81; i++) {
CUSTOM_SLOT_USERNAME[i] = String.format("~BTLP%08x %02d", unique, i);
}
if (OPTION_ENABLE_CUSTOM_SLOT_USERNAME_COLLISION_CHECK) {
CUSTOM_SLOT_USERNAMES = ImmutableSet.copyOf(CUSTOM_SLOT_USERNAME);
} else {
CUSTOM_SLOT_USERNAMES = null;
}
CUSTOM_SLOT_USERNAME_SMILEYS = new String[80];
String emojis = "\u263a\u2639\u2620\u2763\u2764\u270c\u261d\u270d\u2618\u2615\u2668\u2693\u2708\u231b\u231a\u2600\u2b50\u2601\u2602\u2614\u26a1\u2744\u2603\u2604\u2660\u2665\u2666\u2663\u265f\u260e\u2328\u2709\u270f\u2712\u2702\u2692\u2694\u2699\u2696\u2697\u26b0\u26b1\u267f\u26a0\u2622\u2623\u2640\u2642\u267e\u267b\u269c\u303d\u2733\u2734\u2747\u203c\u2b1c\u2b1b\u25fc\u25fb\u25aa\u25ab\u2049\u26ab\u26aa\u3030\u00a9\u00ae\u2122\u2139\u24c2\u3297\u2716\u2714\u2611\u2695\u2b06\u2197\u27a1\u2198\u2b07\u2199\u3299\u2b05\u2196\u2195\u2194\u21a9\u21aa\u2934\u2935\u269b\u2721\u2638\u262f\u271d\u2626\u262a\u262e\u2648\u2649\u264a\u264b\u264c\u264d\u264e\u264f\u2650\u2651\u2652\u2653\u25b6\u25c0\u23cf";
for (int i = 0; i < 80; i++) {
CUSTOM_SLOT_USERNAME_SMILEYS[i] = String.format("" + emojis.charAt(i), unique, i);
}
// generate teams for custom slots
CUSTOM_SLOT_TEAMNAME = new String[81];
for (int i = 0; i < 81; i++) {
CUSTOM_SLOT_TEAMNAME[i] = String.format(" BTLP%08x %02d", unique, i);
}
CUSTOM_SLOT_TEAMNAMES = ImmutableSet.copyOf(CUSTOM_SLOT_TEAMNAME);
}
protected final Logger logger;
private final Executor eventLoopExecutor;
private final UUID viewerUuid;
private final Object2ObjectMap<UUID, PlayerListEntry> serverPlayerList = new Object2ObjectOpenHashMap<>();
protected final Set<String> serverTabListPlayers = new ObjectOpenHashSet<>();
@Nullable
protected Component serverHeader = null;
@Nullable
protected Component serverFooter = null;
protected final Object2ObjectMap<String, TeamEntry> serverTeams = new Object2ObjectOpenHashMap<>();
protected final Object2ObjectMap<String, String> playerToTeamMap = new Object2ObjectOpenHashMap<>();
private final Queue<AbstractContentOperationModeHandler<?>> nextActiveContentHandlerQueue = new ConcurrentLinkedQueue<>();
private final Queue<AbstractHeaderFooterOperationModeHandler<?>> nextActiveHeaderFooterHandlerQueue = new ConcurrentLinkedQueue<>();
private AbstractContentOperationModeHandler<?> activeContentHandler;
private AbstractHeaderFooterOperationModeHandler<?> activeHeaderFooterHandler;
private boolean hasCreatedCustomTeams = false;
private final AtomicBoolean updateScheduledFlag = new AtomicBoolean(false);
private final Runnable updateTask = this::update;
private final boolean is18;
private boolean is13OrLater;
private boolean is119OrLater;
private boolean is1203OrLater;
protected boolean active;
public AbstractTabOverlayHandler(Logger logger, Executor eventLoopExecutor, UUID viewerUuid, boolean is18, boolean is13OrLater, boolean is119OrLater, boolean is1203OrLater) {
this.logger = logger;
this.eventLoopExecutor = eventLoopExecutor;
this.viewerUuid = viewerUuid;
this.is18 = is18;
this.is13OrLater = is13OrLater;
this.is119OrLater = is119OrLater;
this.is1203OrLater = is1203OrLater;
this.activeContentHandler = new PassThroughContentHandler();
this.activeHeaderFooterHandler = new PassThroughHeaderFooterHandler();
EMPTY_COMPONENT = new ComponentHolder(is13OrLater ? (is1203OrLater ? ProtocolVersion.MINECRAFT_1_20_3 : ProtocolVersion.MINECRAFT_1_13) : ProtocolVersion.MINECRAFT_1_12_2, Component.empty());
}
protected abstract void sendPacket(MinecraftPacket packet);
protected abstract ProtocolVersion getProtocol();
@Override
public PacketListenerResult onPlayerListPacket(LegacyPlayerListItemPacket packet) {
switch (packet.getAction()) {
case ADD_PLAYER:
for (LegacyPlayerListItemPacket.Item item : packet.getItems()) {
if (OPTION_ENABLE_CUSTOM_SLOT_UUID_COLLISION_CHECK) {
if (CUSTOM_SLOT_UUIDS.contains(item.getUuid())) {
throw new AssertionError("UUID collision " + item.getUuid());
}
}
if (OPTION_ENABLE_CUSTOM_SLOT_USERNAME_COLLISION_CHECK) {
if (CUSTOM_SLOT_USERNAMES.contains(item.getName())) {
throw new AssertionError("Username collision" + item.getName());
}
}
PlayerListEntry old = serverPlayerList.put(item.getUuid(), new PlayerListEntry(item));
if (old != null) {
serverTabListPlayers.remove(old.getUsername());
}
serverTabListPlayers.add(item.getName());
}
break;
case UPDATE_GAMEMODE:
for (LegacyPlayerListItemPacket.Item item : packet.getItems()) {
PlayerListEntry playerListEntry = serverPlayerList.get(item.getUuid());
if (playerListEntry != null) {
playerListEntry.setGamemode(item.getGameMode());
}
}
break;
case UPDATE_LATENCY:
for (LegacyPlayerListItemPacket.Item item : packet.getItems()) {
PlayerListEntry playerListEntry = serverPlayerList.get(item.getUuid());
if (playerListEntry != null) {
playerListEntry.setPing(item.getLatency());
}
}
break;
case UPDATE_DISPLAY_NAME:
for (LegacyPlayerListItemPacket.Item item : packet.getItems()) {
PlayerListEntry playerListEntry = serverPlayerList.get(item.getUuid());
if (playerListEntry != null) {
playerListEntry.setDisplayName(item.getDisplayName());
}
}
break;
case REMOVE_PLAYER:
for (LegacyPlayerListItemPacket.Item item : packet.getItems()) {
PlayerListEntry removed = serverPlayerList.remove(item.getUuid());
if (removed != null) {
serverTabListPlayers.remove(removed.getUsername());
}
}
break;
}
try {
return this.activeContentHandler.onPlayerListPacket(packet);
} catch (Throwable th) {
logger.log(Level.SEVERE, "Unexpected error", th);
// try recover
enterContentOperationMode(ContentOperationMode.PASS_TROUGH);
return PacketListenerResult.PASS;
}
}
@Override
public PacketListenerResult onTeamPacket(Team packet) {
if (packet.getPlayers() != null) {
boolean block = false;
for (String player : packet.getPlayers()) {
if (player.isEmpty()) {
block = true;
break;
}
}
if (block) {
if (!blockedTeams.contains(packet.getName())) {
logger.warning("Blocking Team Packet for Team " + packet.getName() + ", as it is incompatible with BungeeTabListPlus.");
blockedTeams.add(packet.getName());
}
return PacketListenerResult.CANCEL;
}
}
try {
this.activeContentHandler.onTeamPacketPreprocess(packet);
} catch (Throwable th) {
logger.log(Level.SEVERE, "Unexpected error", th);
// try recover
enterContentOperationMode(ContentOperationMode.PASS_TROUGH);
}
if (packet.getMode() == 1) {
TeamEntry team = serverTeams.remove(packet.getName());
if (team != null) {
for (String player : team.getPlayers()) {
playerToTeamMap.remove(player, packet.getName());
}
}
} else {
// Create or get old team
TeamEntry teamEntry;
if (packet.getMode() == 0) {
teamEntry = new TeamEntry();
serverTeams.put(packet.getName(), teamEntry);
} else {
teamEntry = serverTeams.get(packet.getName());
}
if (teamEntry != null) {
if (packet.getMode() == 0 || packet.getMode() == 2) {
teamEntry.setDisplayName(packet.getDisplayName());
teamEntry.setPrefix(packet.getPrefix());
teamEntry.setSuffix(packet.getSuffix());
teamEntry.setFriendlyFire(packet.getFriendlyFire());
teamEntry.setNameTagVisibility(packet.getNameTagVisibility());
teamEntry.setCollisionRule(packet.getCollisionRule());
teamEntry.setColor(packet.getColor());
}
if (packet.getPlayers() != null) {
for (String s : packet.getPlayers()) {
if (packet.getMode() == 0 || packet.getMode() == 3) {
if (playerToTeamMap.containsKey(s)) {
TeamEntry previousTeam = serverTeams.get(playerToTeamMap.get(s));
// previousTeam shouldn't be null (that's inconsistent with playerToTeamMap, but apparently it happens)
if (previousTeam != null) {
previousTeam.removePlayer(s);
}
}
teamEntry.addPlayer(s);
playerToTeamMap.put(s, packet.getName());
} else {
teamEntry.removePlayer(s);
playerToTeamMap.remove(s, packet.getName());
}
}
}
}
}
try {
return this.activeContentHandler.onTeamPacket(packet);
} catch (Throwable th) {
logger.log(Level.SEVERE, "Unexpected error", th);
// try recover
enterContentOperationMode(ContentOperationMode.PASS_TROUGH);
return PacketListenerResult.PASS;
}
}
@Override
public PacketListenerResult onPlayerListHeaderFooterPacket(HeaderAndFooterPacket packet) {
PacketListenerResult result = PacketListenerResult.PASS;
try {
result = this.activeHeaderFooterHandler.onPlayerListHeaderFooterPacket(packet);
if (result == PacketListenerResult.MODIFIED) {
throw new AssertionError("PacketListenerResult.MODIFIED must not be used");
}
} catch (Throwable th) {
logger.log(Level.SEVERE, "Unexpected error", th);
// try recover
enterHeaderAndFooterOperationMode(HeaderAndFooterOperationMode.PASS_TROUGH);
}
this.serverHeader = packet.getHeader() != null ? packet.getHeader().getComponent() : Component.empty();
this.serverFooter = packet.getFooter() != null ? packet.getFooter().getComponent() : Component.empty();
return result;
}
@Override
public void onServerSwitch(boolean is13OrLater) {
this.is13OrLater = is13OrLater;
if (!active) {
active = true;
update();
} else {
serverTeams.clear();
playerToTeamMap.clear();
if (isUsingAltRespawn()) {
hasCreatedCustomTeams = false;
}
try {
this.activeContentHandler.onServerSwitch();
} catch (Throwable th) {
logger.log(Level.SEVERE, "Unexpected error", th);
// try recover
enterContentOperationMode(ContentOperationMode.PASS_TROUGH);
}
try {
this.activeHeaderFooterHandler.onServerSwitch();
} catch (Throwable th) {
logger.log(Level.SEVERE, "Unexpected error", th);
// try recover
enterContentOperationMode(ContentOperationMode.PASS_TROUGH);
}
if (!serverPlayerList.isEmpty()) {
List<LegacyPlayerListItemPacket.Item> items = new ArrayList<>();
for(UUID uuid : serverPlayerList.keySet()){
LegacyPlayerListItemPacket.Item item = new LegacyPlayerListItemPacket.Item(uuid);
items.add(item);
}
LegacyPlayerListItemPacket packet = new LegacyPlayerListItemPacket(REMOVE_PLAYER, items);
sendPacket(packet);
}
serverPlayerList.clear();
if (serverHeader != null) {
serverHeader = Component.empty();
}
if (serverFooter != null) {
serverFooter = Component.empty();
}
serverTabListPlayers.clear();
}
}
protected boolean isUsingAltRespawn() {
return false;
}
@Override
public <R> R enterContentOperationMode(ContentOperationMode<R> operationMode) {
AbstractContentOperationModeHandler<?> handler;
if (operationMode == ContentOperationMode.PASS_TROUGH) {
handler = new PassThroughContentHandler();
} else if (operationMode == ContentOperationMode.SIMPLE) {
handler = new SimpleOperationModeHandler();
} else if (operationMode == ContentOperationMode.RECTANGULAR) {
handler = new RectangularSizeHandler();
} else {
throw new UnsupportedOperationException();
}
nextActiveContentHandlerQueue.add(handler);
scheduleUpdate();
return Unchecked.cast(handler.getTabOverlay());
}
@Override
public <R> R enterHeaderAndFooterOperationMode(HeaderAndFooterOperationMode<R> operationMode) {
AbstractHeaderFooterOperationModeHandler<?> handler;
if (operationMode == HeaderAndFooterOperationMode.PASS_TROUGH) {
handler = new PassThroughHeaderFooterHandler();
} else if (operationMode == HeaderAndFooterOperationMode.CUSTOM) {
handler = new CustomHeaderAndFooterOperationModeHandler();
} else {
throw new UnsupportedOperationException(Objects.toString(operationMode));
}
nextActiveHeaderFooterHandlerQueue.add(handler);
scheduleUpdate();
return Unchecked.cast(handler.getTabOverlay());
}
private void scheduleUpdate() {
if (this.updateScheduledFlag.compareAndSet(false, true)) {
try {
eventLoopExecutor.execute(updateTask);
} catch (RejectedExecutionException ignored) {
}
}
}
private void update() {
if (!active) {
return;
}
updateScheduledFlag.set(false);
// update content handler
AbstractContentOperationModeHandler<?> contentHandler;
while (null != (contentHandler = nextActiveContentHandlerQueue.poll())) {
this.activeContentHandler.invalidate();
contentHandler.onActivated(this.activeContentHandler);
this.activeContentHandler = contentHandler;
}
this.activeContentHandler.update();
// update header and footer handler
AbstractHeaderFooterOperationModeHandler<?> heaerFooterHandler;
while (null != (heaerFooterHandler = nextActiveHeaderFooterHandlerQueue.poll())) {
this.activeHeaderFooterHandler.invalidate();
heaerFooterHandler.onActivated(this.activeHeaderFooterHandler);
this.activeHeaderFooterHandler = heaerFooterHandler;
}
this.activeHeaderFooterHandler.update();
}
private abstract class AbstractContentOperationModeHandler<T extends AbstractContentTabOverlay> extends OperationModeHandler<T> {
/**
* Called when the player receives a {@link LegacyPlayerListItemPacket} packet.
* <p>
* This method is called after this {@link AbstractTabOverlayHandler} has updated the {@code serverPlayerList}.
*/
abstract PacketListenerResult onPlayerListPacket(LegacyPlayerListItemPacket packet);
/**
* Called when the player receives a {@link Team} packet.
* <p>
* This method is called before this {@link AbstractTabOverlayHandler} executes its own logic to update the
* server team info.
*/
abstract void onTeamPacketPreprocess(Team packet);
/**
* Called when the player receives a {@link Team} packet.
* <p>
* This method is called after this {@link AbstractTabOverlayHandler} executes its own logic to update the
* server team info.
*/
abstract PacketListenerResult onTeamPacket(Team packet);
/**
* Called when the player switches the server.
* <p>
* This method is called before this {@link AbstractTabOverlayHandler} executes its own logic to clear the
* server player list info.
*/
abstract void onServerSwitch();
abstract void update();
final void invalidate() {
getTabOverlay().invalidate();
onDeactivated();
}
/**
* Called when this {@link OperationModeHandler} is deactivated.
* <p>
* This method must put the client player list in the state expected by {@link #onActivated(AbstractContentOperationModeHandler)}. It must
* especially remove all custom entries and players must be part of the correct teams.
*/
abstract void onDeactivated();
/**
* Called when this {@link OperationModeHandler} becomes the active one.
* <p>
* State of the player list when this method is called:
* - there are no custom entries on the client
* - all entries from {@link #serverPlayerList} are known to the client, but the client may know the wrong displayname, gamemode and ping
* - player list header/ footer may be wrong
* <p>
* Additional information about the state of the player list may be obtained from the previous handler
*
* @param previous previous handler
*/
abstract void onActivated(AbstractContentOperationModeHandler<?> previous);
}
private abstract class AbstractHeaderFooterOperationModeHandler<T extends AbstractHeaderFooterTabOverlay> extends OperationModeHandler<T> {
/**
* Called when the player receives a {@link HeaderAndFooterPacket} packet.
* <p>
* This method is called before this {@link AbstractTabOverlayHandler} executes its own logic to update the
* server player list info.
*/
abstract PacketListenerResult onPlayerListHeaderFooterPacket(HeaderAndFooterPacket packet);
/**
* Called when the player switches the server.
* <p>
* This method is called before this {@link AbstractTabOverlayHandler} executes its own logic to clear the
* server player list info.
*/
abstract void onServerSwitch();
abstract void update();
final void invalidate() {
getTabOverlay().invalidate();
onDeactivated();
}
/**
* Called when this {@link OperationModeHandler} is deactivated.
* <p>
* This method must put the client player list in the state expected by {@link #onActivated(AbstractHeaderFooterOperationModeHandler)}. It must
* especially remove all custom entries and players must be part of the correct teams.
*/
abstract void onDeactivated();
/**
* Called when this {@link OperationModeHandler} becomes the active one.
* <p>
* State of the player list when this method is called:
* - there are no custom entries on the client
* - all entries from {@link #serverPlayerList} are known to the client, but the client may know the wrong displayname, gamemode and ping
* - player list header/ footer may be wrong
* <p>
* Additional information about the state of the player list may be obtained from the previous handler
*
* @param previous previous handler
*/
abstract void onActivated(AbstractHeaderFooterOperationModeHandler<?> previous);
}
private abstract static class AbstractContentTabOverlay implements TabOverlayHandle {
private boolean valid = true;
@Override
public boolean isValid() {
return valid;
}
final void invalidate() {
valid = false;
}
}
private abstract static class AbstractHeaderFooterTabOverlay implements TabOverlayHandle {
private boolean valid = true;
@Override
public boolean isValid() {
return valid;
}
final void invalidate() {
valid = false;
}
}
private final class PassThroughContentHandler extends AbstractContentOperationModeHandler<PassThroughContentTabOverlay> {
@Override
protected PassThroughContentTabOverlay createTabOverlay() {
return new PassThroughContentTabOverlay();
}
@Override
PacketListenerResult onPlayerListPacket(LegacyPlayerListItemPacket packet) {
return PacketListenerResult.PASS;
}
@Override
void onTeamPacketPreprocess(Team packet) {
// nothing to do
}
@Override
PacketListenerResult onTeamPacket(Team packet) {
return PacketListenerResult.PASS;
}
@Override
void onServerSwitch() {
sendPacket(HeaderAndFooterPacket.create(Component.empty(), Component.empty(), getProtocol()));
}
@Override
void update() {
// nothing to do
}
@Override
void onDeactivated() {
// nothing to do
}
@Override
void onActivated(AbstractContentOperationModeHandler<?> previous) {
if (previous instanceof PassThroughContentHandler) {
// we're lucky, nothing to do
return;
}
// fix player list entries
if (!serverPlayerList.isEmpty()) {
// restore player ping
LegacyPlayerListItemPacket packet;
List<LegacyPlayerListItemPacket.Item> items = new ArrayList<>(serverPlayerList.size());
for (PlayerListEntry entry : serverPlayerList.values()) {
LegacyPlayerListItemPacket.Item item = new LegacyPlayerListItemPacket.Item(entry.getUuid());
item.setLatency(entry.getPing());
items.add(item);
}
packet = new LegacyPlayerListItemPacket(UPDATE_LATENCY, items);
sendPacket(packet);
// restore player gamemode
items.clear();
for (PlayerListEntry entry : serverPlayerList.values()) {
LegacyPlayerListItemPacket.Item item = new LegacyPlayerListItemPacket.Item(entry.getUuid());
item.setGameMode(entry.getGamemode());
items.add(item);
}
packet = new LegacyPlayerListItemPacket(UPDATE_GAMEMODE, items);
sendPacket(packet);
// restore player display name
items.clear();
for (PlayerListEntry entry : serverPlayerList.values()) {
LegacyPlayerListItemPacket.Item item = new LegacyPlayerListItemPacket.Item(entry.getUuid());
item.setDisplayName(entry.getDisplayName());
items.add(item);
}
packet = new LegacyPlayerListItemPacket(UPDATE_DISPLAY_NAME, items);
sendPacket(packet);
}
}
}
private final class PassThroughContentTabOverlay extends AbstractContentTabOverlay {
}
private final class PassThroughHeaderFooterHandler extends AbstractHeaderFooterOperationModeHandler<PassThroughHeaderFooterTabOverlay> {
@Override
protected PassThroughHeaderFooterTabOverlay createTabOverlay() {
return new PassThroughHeaderFooterTabOverlay();
}
@Override
PacketListenerResult onPlayerListHeaderFooterPacket(HeaderAndFooterPacket packet) {
return PacketListenerResult.PASS;
}
@Override
void onServerSwitch() {
sendPacket(HeaderAndFooterPacket.create(Component.empty(), Component.empty(), getProtocol()));
}
@Override
void update() {
// nothing to do
}
@Override
void onDeactivated() {
// nothing to do
}
@Override
void onActivated(AbstractHeaderFooterOperationModeHandler<?> previous) {
if (previous instanceof PassThroughHeaderFooterHandler) {
// we're lucky, nothing to do
return;
}
// fix header/ footer
sendPacket(HeaderAndFooterPacket.create(serverHeader != null ? serverHeader : Component.empty(), serverFooter != null ? serverFooter : Component.empty(), getProtocol()));
}
}
private final class PassThroughHeaderFooterTabOverlay extends AbstractHeaderFooterTabOverlay {
}
private abstract class CustomContentTabOverlayHandler<T extends CustomContentTabOverlay> extends AbstractContentOperationModeHandler<T> {
boolean viewerIsSpectator = false;
final ObjectSet<UUID> freePlayers;
@Nonnull
BitSet usedSlots;
BitSet dirtySlots;
int highestUsedSlotIndex;
private boolean using80Slots;
private int usedSlotsCount;
final SlotState[] slotState;
/**
* Uuid of the player list entry used for the slot.
*/
final UUID[] slotUuid;
/**
* Username of the player list entry used for the slot.
*/
final String[] slotUsername;
/**
* Player uuid mapped to the slot it is used for
*/
final Object2IntMap<UUID> playerUuidToSlotMap;
/**
* Player username mapped to the slot it is used for
*/
final Object2IntMap<String> playerUsernameToSlotMap;
boolean canShrink = false;
private final List<LegacyPlayerListItemPacket.Item> itemQueueAddPlayer;
private final List<LegacyPlayerListItemPacket.Item> itemQueueRemovePlayer;
private final List<LegacyPlayerListItemPacket.Item> itemQueueUpdateDisplayName;
private final List<LegacyPlayerListItemPacket.Item> itemQueueUpdatePing;
private final boolean experimentalTabCompleteFixForTabSize80 = isExperimentalTabCompleteFixForTabSize80();
private final boolean experimentalTabCompleteSmileys = isExperimentalTabCompleteSmileys();
private CustomContentTabOverlayHandler() {
this.dirtySlots = new BitSet(80);
this.usedSlots = SIZE_TO_USED_SLOTS[0];
this.usedSlotsCount = 0;
this.using80Slots = false;
this.slotState = new SlotState[80];
Arrays.fill(this.slotState, SlotState.UNUSED);
this.slotUuid = new UUID[80];
this.slotUsername = new String[80];
this.highestUsedSlotIndex = -1;
this.freePlayers = new ObjectOpenHashSet<>();
this.playerUuidToSlotMap = new Object2IntOpenHashMap<>();
this.playerUuidToSlotMap.defaultReturnValue(-1);
this.playerUsernameToSlotMap = new Object2IntOpenHashMap<>();
this.playerUsernameToSlotMap.defaultReturnValue(-1);
this.itemQueueAddPlayer = new ArrayList<>(80);
this.itemQueueRemovePlayer = new ArrayList<>(80);
this.itemQueueUpdateDisplayName = new ArrayList<>(80);
this.itemQueueUpdatePing = new ArrayList<>(80);
}
@Override
PacketListenerResult onPlayerListPacket(LegacyPlayerListItemPacket packet) {
int action = packet.getAction();
if (using80Slots && action == UPDATE_GAMEMODE) {
return PacketListenerResult.PASS;
}
// check whether viewer gamemode changed
boolean viewerGamemodeChanged = false;
T tabOverlay = getTabOverlay();
if (action == ADD_PLAYER || action == UPDATE_GAMEMODE || action == REMOVE_PLAYER) {
PlayerListEntry entry = serverPlayerList.get(viewerUuid);
boolean viewerIsSpectator = entry != null && entry.getGamemode() == 3;
if (this.viewerIsSpectator != viewerIsSpectator) {
this.viewerIsSpectator = viewerIsSpectator;
if (!using80Slots) {
if (highestUsedSlotIndex >= 0) {
dirtySlots.set(highestUsedSlotIndex);
}
if (viewerIsSpectator) {
// mark player slot as dirty
int i = playerUuidToSlotMap.getInt(viewerUuid);
if (i >= 0) {
dirtySlots.set(i);
}
} else {
// mark slots with player uuid as dirty
if (action == UPDATE_GAMEMODE) {
// if action is ADD_PLAYER slots are marked dirty below, so only do it here if action is UPDATE_GAMEMODE
for (int slot = 0; slot < 80; slot++) {
UUID uuid = tabOverlay.uuid[slot];
if (viewerUuid.equals(uuid)) {
dirtySlots.set(slot);
}
}
}
}
}
viewerGamemodeChanged = true;
}
}
PacketListenerResult result;
boolean needUpdate = !using80Slots && viewerGamemodeChanged;
switch (action) {
case ADD_PLAYER:
List<LegacyPlayerListItemPacket.Item> items = packet.getItems();
if (!using80Slots) {
for (LegacyPlayerListItemPacket.Item item : items) {
if (!viewerUuid.equals(item.getUuid())) {
item.setGameMode(0);
}
}
for (LegacyPlayerListItemPacket.Item item : items) {
UUID uuid = item.getUuid();
int index = playerUuidToSlotMap.getInt(uuid);
if (index == -1) {
freePlayers.add(uuid);
needUpdate = true;
} else if (!item.getName().equals(slotUsername[index])) {
dirtySlots.set(index);
needUpdate = true;
} else {
item.setDisplayName(tabOverlay.text[index]);
item.setLatency(tabOverlay.ping[index]);
tabOverlay.dirtyFlagsText.clear(index);
tabOverlay.dirtyFlagsPing.clear(index);
}
}
// mark slot to use for player as dirty
// a new player joining the server shouldn't happen too frequently, so we can accept
// the cost of searching all 80 slots
if (!freePlayers.isEmpty()) {
for (int slot = 0; slot < 80; slot++) {
UUID uuid = tabOverlay.uuid[slot];
if (uuid != null && freePlayers.contains(uuid)) {
dirtySlots.set(slot);
}
}
}
// request size update if tab list too small
if (usedSlotsCount < serverPlayerList.size()) {
tabOverlay.dirtyFlagSize = true;
}
} else {
for (LegacyPlayerListItemPacket.Item item : packet.getItems()) {
if (!playerToTeamMap.containsKey(item.getName())) {
sendPacket(createPacketTeamAddPlayers(CUSTOM_SLOT_TEAMNAME[80], new String[]{item.getName()}));
}
}
}
if (needUpdate) {
sendPacket(packet);
result = PacketListenerResult.CANCEL;
} else {
result = PacketListenerResult.MODIFIED;
}
break;
case UPDATE_GAMEMODE:
if (viewerGamemodeChanged) {
items = packet.getItems();
for (LegacyPlayerListItemPacket.Item item : items) {
if (!viewerUuid.equals(item.getUuid())) {
item.setGameMode(0);
}
}
sendPacket(packet);
}
result = PacketListenerResult.CANCEL;
break;
case UPDATE_LATENCY:
result = PacketListenerResult.CANCEL;
break;
case UPDATE_DISPLAY_NAME:
result = PacketListenerResult.CANCEL;
break;
case REMOVE_PLAYER:
if (!using80Slots) {
items = packet.getItems();
for (LegacyPlayerListItemPacket.Item item : items) {
int index = playerUuidToSlotMap.removeInt(item.getUuid());
if (index == -1) {
if (OPTION_ENABLE_CONSISTENCY_CHECKS) {
if (serverPlayerList.containsKey(item.getUuid())) {
logger.severe("Inconsistent data: player in serverPlayerList but not in playerUuidToSlotMap");
}
}
} else {
// Switch slot 'index' from player to custom mode - restoring player teams
// 1. remove player from team
if (item.getUuid().version() != 2) { // hack for Citizens compatibility
sendPacket(createPacketTeamRemovePlayers(CUSTOM_SLOT_TEAMNAME[index], new String[]{slotUsername[index]}));
playerUsernameToSlotMap.removeInt(slotUsername[index]);
String playerTeamName;
if ((playerTeamName = playerToTeamMap.get(slotUsername[index])) != null) {
// 2. add player to correct team
sendPacket(createPacketTeamAddPlayers(playerTeamName, new String[]{slotUsername[index]}));
// 3. reset custom slot team
sendPacket(createPacketTeamUpdate(CUSTOM_SLOT_TEAMNAME[index], EMPTY_COMPONENT, EMPTY_COMPONENT, EMPTY_COMPONENT, Team.NameTagVisibility.ALWAYS, Team.CollisionRule.ALWAYS, is13OrLater ? 21 : 0, (byte) 1));
}
}
// 4. create new custom slot
tabOverlay.dirtyFlagsIcon.clear(index);
tabOverlay.dirtyFlagsText.clear(index);
tabOverlay.dirtyFlagsPing.clear(index);
Icon icon = tabOverlay.icon[index];
UUID customSlotUuid;
if (icon.isAlex()) {
customSlotUuid = CUSTOM_SLOT_UUID_ALEX[index];
} else {
customSlotUuid = CUSTOM_SLOT_UUID_STEVE[index];
}
slotState[index] = SlotState.CUSTOM;
slotUuid[index] = customSlotUuid;
LegacyPlayerListItemPacket.Item item1 = new LegacyPlayerListItemPacket.Item(customSlotUuid);
item1.setName(slotUsername[index] = getCustomSlotUsername(index));
Property119Handler.setProperties(item1, toPropertiesArray(icon.getTextureProperty()));
item1.setDisplayName(tabOverlay.text[index]);
item1.setLatency(tabOverlay.ping[index]);
item1.setGameMode(0);
LegacyPlayerListItemPacket packet1 = new LegacyPlayerListItemPacket(ADD_PLAYER, List.of(item1));
sendPacket(packet1);
if (is18) {
packet1 = new LegacyPlayerListItemPacket(UPDATE_DISPLAY_NAME, List.of(item1));
sendPacket(packet1);
}
}