aboutsummaryrefslogtreecommitdiffhomepage
path: root/patches/unapplied/server/0167-AsyncTabCompleteEvent.patch
blob: b8617c18e5f0f3a7a5d4936bc51be5715b9239b8 (plain)
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
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Jason Penilla <11360596+jpenilla@users.noreply.github.com>
Date: Sun, 26 Nov 2017 13:19:58 -0500
Subject: [PATCH] AsyncTabCompleteEvent

Let plugins be able to control tab completion of commands and chat async.

This will be useful for frameworks like ACF so we can define async safe completion handlers,
and avoid going to main for tab completions.

Especially useful if you need to query a database in order to obtain the results for tab
completion, such as offline players.

Also adds isCommand and getLocation to the sync TabCompleteEvent

Co-authored-by: Aikar <aikar@aikar.co>

diff --git a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
index 6e2957e31ad4be418bcd475b2e3a4e56b5be591e..b5abb0d433322224ccbbed8755fb3ebf77b5a36c 100644
--- a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
@@ -688,12 +688,16 @@ public class ServerGamePacketListenerImpl extends ServerCommonPacketListenerImpl
 
     }
 
+    // Paper start
+    private static final java.util.concurrent.ExecutorService TAB_COMPLETE_EXECUTOR = java.util.concurrent.Executors.newFixedThreadPool(4,
+        new com.google.common.util.concurrent.ThreadFactoryBuilder().setDaemon(true).setNameFormat("Async Tab Complete Thread - #%d").setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(net.minecraft.server.MinecraftServer.LOGGER)).build());
+    // Paper end
     @Override
     public void handleCustomCommandSuggestions(ServerboundCommandSuggestionPacket packet) {
-        PacketUtils.ensureRunningOnSameThread(packet, this, this.player.serverLevel());
+        // PacketUtils.ensureRunningOnSameThread(packet, this, this.player.serverLevel()); // Paper - run this async
         // CraftBukkit start
         if (this.chatSpamTickCount.addAndGet(1) > 500 && !this.server.getPlayerList().isOp(this.player.getGameProfile())) {
-            this.disconnect(Component.translatable("disconnect.spam"));
+            server.scheduleOnMain(() -> this.disconnect(Component.translatable("disconnect.spam", new Object[0]))); // Paper
             return;
         }
         // Paper start
@@ -704,18 +708,45 @@ public class ServerGamePacketListenerImpl extends ServerCommonPacketListenerImpl
         }
         // Paper end
         // CraftBukkit end
+        // Paper start - async tab completion
+        TAB_COMPLETE_EXECUTOR.execute(() -> {
         StringReader stringreader = new StringReader(packet.getCommand());
 
         if (stringreader.canRead() && stringreader.peek() == '/') {
             stringreader.skip();
         }
-
-        ParseResults<CommandSourceStack> parseresults = this.server.getCommands().getDispatcher().parse(stringreader, this.player.createCommandSourceStack());
-
-        this.server.getCommands().getDispatcher().getCompletionSuggestions(parseresults).thenAccept((suggestions) -> {
-            if (suggestions.isEmpty()) return; // CraftBukkit - don't send through empty suggestions - prevents [<args>] from showing for plugins with nothing more to offer
-            this.send(new ClientboundCommandSuggestionsPacket(packet.getId(), suggestions));
+            final String command = packet.getCommand();
+            final com.destroystokyo.paper.event.server.AsyncTabCompleteEvent event = new com.destroystokyo.paper.event.server.AsyncTabCompleteEvent(this.getCraftPlayer(), command, true, null);
+            event.callEvent();
+            final java.util.List<com.destroystokyo.paper.event.server.AsyncTabCompleteEvent.Completion> completions = event.isCancelled() ? com.google.common.collect.ImmutableList.of() : event.completions();
+            // If the event isn't handled, we can assume that we have no completions, and so we'll ask the server
+            if (!event.isHandled()) {
+                if (!event.isCancelled()) {
+
+                    this.server.scheduleOnMain(() -> { // This needs to be on main
+                        ParseResults<CommandSourceStack> parseresults = this.server.getCommands().getDispatcher().parse(stringreader, this.player.createCommandSourceStack());
+
+                        this.server.getCommands().getDispatcher().getCompletionSuggestions(parseresults).thenAccept((suggestions) -> {
+                            if (suggestions.isEmpty()) return; // CraftBukkit - don't send through empty suggestions - prevents [<args>] from showing for plugins with nothing more to offer
+                            this.connection.send(new ClientboundCommandSuggestionsPacket(packet.getId(), suggestions));
+                        });
+                    });
+                }
+            } else if (!completions.isEmpty()) {
+                final com.mojang.brigadier.suggestion.SuggestionsBuilder builder0 = new com.mojang.brigadier.suggestion.SuggestionsBuilder(command, stringreader.getTotalLength());
+                final com.mojang.brigadier.suggestion.SuggestionsBuilder builder = builder0.createOffset(builder0.getInput().lastIndexOf(' ') + 1);
+                completions.forEach(completion -> {
+                    final Integer intSuggestion = com.google.common.primitives.Ints.tryParse(completion.suggestion());
+                    if (intSuggestion != null) {
+                        builder.suggest(intSuggestion, PaperAdventure.asVanilla(completion.tooltip()));
+                    } else {
+                        builder.suggest(completion.suggestion(), PaperAdventure.asVanilla(completion.tooltip()));
+                    }
+                });
+                player.connection.send(new ClientboundCommandSuggestionsPacket(packet.getId(), builder.buildFuture().join()));
+            }
         });
+        // Paper end - async tab completion
     }
 
     @Override
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
index 6b9675a1170f9e536432826e52b3cb3fa5195272..3ceebd86f44d1997201c34559d1b63004a973282 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
@@ -2195,7 +2195,7 @@ public final class CraftServer implements Server {
             offers = this.tabCompleteChat(player, message);
         }
 
-        TabCompleteEvent tabEvent = new TabCompleteEvent(player, message, offers);
+        TabCompleteEvent tabEvent = new TabCompleteEvent(player, message, offers, message.startsWith("/") || forceCommand, pos != null ? io.papermc.paper.util.MCUtil.toLocation(((CraftWorld) player.getWorld()).getHandle(), BlockPos.containing(pos)) : null); // Paper
         this.getPluginManager().callEvent(tabEvent);
 
         return tabEvent.isCancelled() ? Collections.EMPTY_LIST : tabEvent.getCompletions();
diff --git a/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java b/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java
index d24acf28f5ed023acc550bcf877e4b9800ec8c9f..8f82041f0482df22a6a9ea38d50d56228131775d 100644
--- a/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java
+++ b/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java
@@ -28,6 +28,61 @@ public class ConsoleCommandCompleter implements Completer {
     public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
         final CraftServer server = this.server.server;
         final String buffer = line.line();
+        // Async Tab Complete
+        final com.destroystokyo.paper.event.server.AsyncTabCompleteEvent event =
+            new com.destroystokyo.paper.event.server.AsyncTabCompleteEvent(server.getConsoleSender(), buffer, true, null);
+        event.callEvent();
+        final List<com.destroystokyo.paper.event.server.AsyncTabCompleteEvent.Completion> completions = event.isCancelled() ? com.google.common.collect.ImmutableList.of() : event.completions();
+
+        if (event.isCancelled() || event.isHandled()) {
+            // Still fire sync event with the provided completions, if someone is listening
+            if (!event.isCancelled() && TabCompleteEvent.getHandlerList().getRegisteredListeners().length > 0) {
+                List<com.destroystokyo.paper.event.server.AsyncTabCompleteEvent.Completion> finalCompletions = new java.util.ArrayList<>(completions);
+                Waitable<List<String>> syncCompletions = new Waitable<List<String>>() {
+                    @Override
+                    protected List<String> evaluate() {
+                        org.bukkit.event.server.TabCompleteEvent syncEvent = new org.bukkit.event.server.TabCompleteEvent(server.getConsoleSender(), buffer,
+                            finalCompletions.stream()
+                                .map(com.destroystokyo.paper.event.server.AsyncTabCompleteEvent.Completion::suggestion)
+                                .collect(java.util.stream.Collectors.toList()));
+                        return syncEvent.callEvent() ? syncEvent.getCompletions() : com.google.common.collect.ImmutableList.of();
+                    }
+                };
+                server.getServer().processQueue.add(syncCompletions);
+                try {
+                    final List<String> legacyCompletions = syncCompletions.get();
+                    completions.removeIf(it -> !legacyCompletions.contains(it.suggestion())); // remove any suggestions that were removed
+                    // add any new suggestions
+                    for (final String completion : legacyCompletions) {
+                        if (notNewSuggestion(completions, completion)) {
+                            continue;
+                        }
+                        completions.add(com.destroystokyo.paper.event.server.AsyncTabCompleteEvent.Completion.completion(completion));
+                    }
+                } catch (InterruptedException | ExecutionException e1) {
+                    e1.printStackTrace();
+                }
+            }
+
+            if (!completions.isEmpty()) {
+                for (final com.destroystokyo.paper.event.server.AsyncTabCompleteEvent.Completion completion : completions) {
+                    if (completion.suggestion().isEmpty()) {
+                        continue;
+                    }
+                    candidates.add(new Candidate(
+                        completion.suggestion(),
+                        completion.suggestion(),
+                        null,
+                        io.papermc.paper.adventure.PaperAdventure.PLAIN.serializeOr(completion.tooltip(), null),
+                        null,
+                        null,
+                        false
+                    ));
+                }
+            }
+            return;
+        }
+
         // Paper end
         Waitable<List<String>> waitable = new Waitable<List<String>>() {
             @Override
@@ -73,4 +128,15 @@ public class ConsoleCommandCompleter implements Completer {
             Thread.currentThread().interrupt();
         }
     }
+
+    // Paper start
+    private boolean notNewSuggestion(final List<com.destroystokyo.paper.event.server.AsyncTabCompleteEvent.Completion> completions, final String completion) {
+        for (final com.destroystokyo.paper.event.server.AsyncTabCompleteEvent.Completion it : completions) {
+            if (it.suggestion().equals(completion)) {
+                return true;
+            }
+        }
+        return false;
+    }
+    // Paper end
 }