Move patches to unapplied

This commit is contained in:
Nassim Jahnke
2024-12-12 12:22:12 +01:00
parent ff75689b08
commit 45ddf764d9
821 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,23 @@
--- a/net/minecraft/commands/CommandSource.java
+++ b/net/minecraft/commands/CommandSource.java
@@ -22,6 +22,13 @@
public boolean shouldInformAdmins() {
return false;
}
+
+ // CraftBukkit start
+ @Override
+ public org.bukkit.command.CommandSender getBukkitSender(CommandSourceStack wrapper) {
+ return io.papermc.paper.brigadier.NullCommandSender.INSTANCE; // Paper - expose a no-op CommandSender
+ }
+ // CraftBukkit end
};
void sendSystemMessage(Component message);
@@ -35,4 +42,6 @@
default boolean alwaysAccepts() {
return false;
}
+
+ org.bukkit.command.CommandSender getBukkitSender(CommandSourceStack wrapper); // CraftBukkit
}

View File

@@ -0,0 +1,114 @@
--- a/net/minecraft/commands/CommandSourceStack.java
+++ b/net/minecraft/commands/CommandSourceStack.java
@@ -45,9 +45,9 @@
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
+import com.mojang.brigadier.tree.CommandNode; // CraftBukkit
-public class CommandSourceStack implements ExecutionCommandSource<CommandSourceStack>, SharedSuggestionProvider {
-
+public class CommandSourceStack implements ExecutionCommandSource<CommandSourceStack>, SharedSuggestionProvider, io.papermc.paper.command.brigadier.PaperCommandSourceStack { // Paper - Brigadier API
public static final SimpleCommandExceptionType ERROR_NOT_PLAYER = new SimpleCommandExceptionType(Component.translatable("permissions.requires.player"));
public static final SimpleCommandExceptionType ERROR_NOT_ENTITY = new SimpleCommandExceptionType(Component.translatable("permissions.requires.entity"));
public final CommandSource source;
@@ -65,6 +65,8 @@
private final Vec2 rotation;
private final CommandSigningContext signingContext;
private final TaskChainer chatMessageChainer;
+ public java.util.Map<Thread, CommandNode> currentCommand = new java.util.concurrent.ConcurrentHashMap<>(); // CraftBukkit // Paper - Thread Safe Vanilla Command permission checking
+ public boolean bypassSelectorPermissions = false; // Paper - add bypass for selector permissions
public CommandSourceStack(CommandSource output, Vec3 pos, Vec2 rot, ServerLevel world, int level, String name, Component displayName, MinecraftServer server, @Nullable Entity entity) {
this(output, pos, rot, world, level, name, displayName, server, entity, false, CommandResultCallback.EMPTY, EntityAnchorArgument.Anchor.FEET, CommandSigningContext.ANONYMOUS, TaskChainer.immediate(server));
@@ -171,8 +173,43 @@
@Override
public boolean hasPermission(int level) {
+ // CraftBukkit start
+ // Paper start - Thread Safe Vanilla Command permission checking
+ CommandNode currentCommand = this.currentCommand.get(Thread.currentThread());
+ if (currentCommand != null) {
+ return this.hasPermission(level, org.bukkit.craftbukkit.command.VanillaCommandWrapper.getPermission(currentCommand));
+ // Paper end - Thread Safe Vanilla Command permission checking
+ }
+ // CraftBukkit end
+
return this.permissionLevel >= level;
+ }
+
+ // Paper start - Fix permission levels for command blocks
+ private boolean forceRespectPermissionLevel() {
+ return this.source == CommandSource.NULL || (this.source instanceof final net.minecraft.world.level.BaseCommandBlock commandBlock && commandBlock.getLevel().paperConfig().commandBlocks.forceFollowPermLevel);
+ }
+ // Paper end - Fix permission levels for command blocks
+
+ // CraftBukkit start
+ public boolean hasPermission(int i, String bukkitPermission) {
+ // Paper start - Fix permission levels for command blocks
+ final java.util.function.BooleanSupplier hasBukkitPerm = () -> this.source == CommandSource.NULL /*treat NULL as having all bukkit perms*/ || this.getBukkitSender().hasPermission(bukkitPermission); // lazily check bukkit perms to the benefit of custom permission setups
+ // if the server is null, we must check the vanilla perm level system
+ // if ignoreVanillaPermissions is true, we can skip vanilla perms and just run the bukkit perm check
+ //noinspection ConstantValue
+ if (this.getServer() == null || !this.getServer().server.ignoreVanillaPermissions) { // server & level are null for command function loading
+ final boolean hasPermLevel = this.permissionLevel >= i;
+ if (this.forceRespectPermissionLevel()) { // NULL CommandSource and command blocks (if setting is enabled) should always pass the vanilla perm check
+ return hasPermLevel && hasBukkitPerm.getAsBoolean();
+ } else { // otherwise check vanilla perm first then bukkit perm, matching upstream behavior
+ return hasPermLevel || hasBukkitPerm.getAsBoolean();
+ }
+ }
+ return hasBukkitPerm.getAsBoolean();
+ // Paper end - Fix permission levels for command blocks
}
+ // CraftBukkit end
public Vec3 getPosition() {
return this.worldPosition;
@@ -302,21 +339,26 @@
while (iterator.hasNext()) {
ServerPlayer entityplayer = (ServerPlayer) iterator.next();
- if (entityplayer.commandSource() != this.source && this.server.getPlayerList().isOp(entityplayer.getGameProfile())) {
+ if (entityplayer.commandSource() != this.source && entityplayer.getBukkitEntity().hasPermission("minecraft.admin.command_feedback")) { // CraftBukkit
entityplayer.sendSystemMessage(ichatmutablecomponent);
}
}
}
- if (this.source != this.server && this.server.getGameRules().getBoolean(GameRules.RULE_LOGADMINCOMMANDS)) {
+ if (this.source != this.server && this.server.getGameRules().getBoolean(GameRules.RULE_LOGADMINCOMMANDS) && !org.spigotmc.SpigotConfig.silentCommandBlocks) { // Spigot
this.server.sendSystemMessage(ichatmutablecomponent);
}
}
public void sendFailure(Component message) {
+ // Paper start - Add UnknownCommandEvent
+ this.sendFailure(message, true);
+ }
+ public void sendFailure(Component message, boolean withStyle) {
+ // Paper end - Add UnknownCommandEvent
if (this.source.acceptsFailure() && !this.silent) {
- this.source.sendSystemMessage(Component.empty().append(message).withStyle(ChatFormatting.RED));
+ this.source.sendSystemMessage(withStyle ? Component.empty().append(message).withStyle(ChatFormatting.RED) : message); // Paper - Add UnknownCommandEvent
}
}
@@ -400,4 +442,16 @@
public boolean isSilent() {
return this.silent;
}
+
+ // Paper start
+ @Override
+ public CommandSourceStack getHandle() {
+ return this;
+ }
+ // Paper end
+ // CraftBukkit start
+ public org.bukkit.command.CommandSender getBukkitSender() {
+ return this.source.getBukkitSender(this);
+ }
+ // CraftBukkit end
}

View File

@@ -0,0 +1,372 @@
--- a/net/minecraft/commands/Commands.java
+++ b/net/minecraft/commands/Commands.java
@@ -138,6 +138,14 @@
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.level.GameRules;
import org.slf4j.Logger;
+
+// CraftBukkit start
+import com.google.common.base.Joiner;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import org.bukkit.event.player.PlayerCommandSendEvent;
+import org.bukkit.event.server.ServerCommandEvent;
+// CraftBukkit end
public class Commands {
@@ -151,6 +159,7 @@
private final com.mojang.brigadier.CommandDispatcher<CommandSourceStack> dispatcher = new com.mojang.brigadier.CommandDispatcher();
public Commands(Commands.CommandSelection environment, CommandBuildContext commandRegistryAccess) {
+ // Paper
AdvancementCommands.register(this.dispatcher);
AttributeCommand.register(this.dispatcher, commandRegistryAccess);
ExecuteCommand.register(this.dispatcher, commandRegistryAccess);
@@ -250,8 +259,33 @@
if (environment.includeIntegrated) {
PublishCommand.register(this.dispatcher);
+ }
+
+ // Paper start - Vanilla command permission fixes
+ for (final CommandNode<CommandSourceStack> node : this.dispatcher.getRoot().getChildren()) {
+ if (node.getRequirement() == com.mojang.brigadier.builder.ArgumentBuilder.<CommandSourceStack>defaultRequirement()) {
+ node.requirement = stack -> stack.source == CommandSource.NULL || stack.getBukkitSender().hasPermission(org.bukkit.craftbukkit.command.VanillaCommandWrapper.getPermission(node));
+ }
}
+ // Paper end - Vanilla command permission fixes
+ // Paper start - Brigadier Command API
+ // Create legacy minecraft namespace commands
+ for (final CommandNode<CommandSourceStack> node : new java.util.ArrayList<>(this.dispatcher.getRoot().getChildren())) {
+ // The brigadier dispatcher is not able to resolve nested redirects.
+ // E.g. registering the alias minecraft:tp cannot redirect to tp, as tp itself redirects to teleport.
+ // Instead, target the first none redirecting node.
+ CommandNode<CommandSourceStack> flattenedAliasTarget = node;
+ while (flattenedAliasTarget.getRedirect() != null) flattenedAliasTarget = flattenedAliasTarget.getRedirect();
+ this.dispatcher.register(
+ com.mojang.brigadier.builder.LiteralArgumentBuilder.<CommandSourceStack>literal("minecraft:" + node.getName())
+ .executes(flattenedAliasTarget.getCommand())
+ .requires(flattenedAliasTarget.getRequirement())
+ .redirect(flattenedAliasTarget)
+ );
+ }
+ // Paper end - Brigadier Command API
+ // Paper - remove public constructor, no longer needed
this.dispatcher.setConsumer(ExecutionCommandSource.resultConsumer());
}
@@ -262,30 +296,72 @@
return new ParseResults(commandcontextbuilder1, parseResults.getReader(), parseResults.getExceptions());
}
+ // CraftBukkit start
+ public void dispatchServerCommand(CommandSourceStack sender, String command) {
+ Joiner joiner = Joiner.on(" ");
+ if (command.startsWith("/")) {
+ command = command.substring(1);
+ }
+
+ ServerCommandEvent event = new ServerCommandEvent(sender.getBukkitSender(), command);
+ org.bukkit.Bukkit.getPluginManager().callEvent(event);
+ if (event.isCancelled()) {
+ return;
+ }
+ command = event.getCommand();
+
+ String[] args = command.split(" ");
+ if (args.length == 0) return; // Paper - empty commands shall not be dispatched
+
+ // Paper - Fix permission levels for command blocks
+
+ // Handle vanilla commands; // Paper - handled in CommandNode/CommandDispatcher
+
+ String newCommand = joiner.join(args);
+ this.performPrefixedCommand(sender, newCommand, newCommand);
+ }
+ // CraftBukkit end
+
public void performPrefixedCommand(CommandSourceStack source, String command) {
- command = command.startsWith("/") ? command.substring(1) : command;
- this.performCommand(this.dispatcher.parse(command, source), command);
+ // CraftBukkit start
+ this.performPrefixedCommand(source, command, command);
+ }
+
+ public void performPrefixedCommand(CommandSourceStack commandlistenerwrapper, String s, String label) {
+ s = s.startsWith("/") ? s.substring(1) : s;
+ this.performCommand(this.dispatcher.parse(s, commandlistenerwrapper), s, label);
+ // CraftBukkit end
}
public void performCommand(ParseResults<CommandSourceStack> parseResults, String command) {
- CommandSourceStack commandlistenerwrapper = (CommandSourceStack) parseResults.getContext().getSource();
+ this.performCommand(parseResults, command, command);
+ }
+ public void performCommand(ParseResults<CommandSourceStack> parseresults, String s, String label) { // CraftBukkit
+ // Paper start
+ this.performCommand(parseresults, s, label, false);
+ }
+ public void performCommand(ParseResults<CommandSourceStack> parseresults, String s, String label, boolean throwCommandError) {
+ // Paper end
+ CommandSourceStack commandlistenerwrapper = (CommandSourceStack) parseresults.getContext().getSource();
+
Profiler.get().push(() -> {
- return "/" + command;
+ return "/" + s;
});
- ContextChain<CommandSourceStack> contextchain = Commands.finishParsing(parseResults, command, commandlistenerwrapper);
+ ContextChain contextchain = this.finishParsing(parseresults, s, commandlistenerwrapper, label); // CraftBukkit // Paper - Add UnknownCommandEvent
try {
if (contextchain != null) {
Commands.executeCommandInContext(commandlistenerwrapper, (executioncontext) -> {
- ExecutionContext.queueInitialCommandExecution(executioncontext, command, contextchain, commandlistenerwrapper, CommandResultCallback.EMPTY);
+ ExecutionContext.queueInitialCommandExecution(executioncontext, s, contextchain, commandlistenerwrapper, CommandResultCallback.EMPTY);
});
}
} catch (Exception exception) {
+ if (throwCommandError) throw exception;
MutableComponent ichatmutablecomponent = Component.literal(exception.getMessage() == null ? exception.getClass().getName() : exception.getMessage());
- if (Commands.LOGGER.isDebugEnabled()) {
- Commands.LOGGER.error("Command exception: /{}", command, exception);
+ Commands.LOGGER.error("Command exception: /{}", s, exception); // Paper - always show execution exception in console log
+ if (commandlistenerwrapper.getServer().isDebugging() || Commands.LOGGER.isDebugEnabled()) { // Paper - Debugging
StackTraceElement[] astacktraceelement = exception.getStackTrace();
for (int i = 0; i < Math.min(astacktraceelement.length, 3); ++i) {
@@ -298,7 +374,7 @@
}));
if (SharedConstants.IS_RUNNING_IN_IDE) {
commandlistenerwrapper.sendFailure(Component.literal(Util.describeError(exception)));
- Commands.LOGGER.error("'/{}' threw an exception", command, exception);
+ Commands.LOGGER.error("'/{}' threw an exception", s, exception);
}
} finally {
Profiler.get().pop();
@@ -307,18 +383,22 @@
}
@Nullable
- private static ContextChain<CommandSourceStack> finishParsing(ParseResults<CommandSourceStack> parseResults, String command, CommandSourceStack source) {
+ private ContextChain<CommandSourceStack> finishParsing(ParseResults<CommandSourceStack> parseresults, String s, CommandSourceStack commandlistenerwrapper, String label) { // CraftBukkit // Paper - Add UnknownCommandEvent
try {
- Commands.validateParseResults(parseResults);
- return (ContextChain) ContextChain.tryFlatten(parseResults.getContext().build(command)).orElseThrow(() -> {
- return CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().createWithContext(parseResults.getReader());
+ Commands.validateParseResults(parseresults);
+ return (ContextChain) ContextChain.tryFlatten(parseresults.getContext().build(s)).orElseThrow(() -> {
+ return CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().createWithContext(parseresults.getReader());
});
} catch (CommandSyntaxException commandsyntaxexception) {
- source.sendFailure(ComponentUtils.fromMessage(commandsyntaxexception.getRawMessage()));
+ // Paper start - Add UnknownCommandEvent
+ final net.kyori.adventure.text.TextComponent.Builder builder = net.kyori.adventure.text.Component.text();
+ // commandlistenerwrapper.sendFailure(ComponentUtils.fromMessage(commandsyntaxexception.getRawMessage()));
+ builder.color(net.kyori.adventure.text.format.NamedTextColor.RED).append(io.papermc.paper.brigadier.PaperBrigadier.componentFromMessage(commandsyntaxexception.getRawMessage()));
+ // Paper end - Add UnknownCommandEvent
if (commandsyntaxexception.getInput() != null && commandsyntaxexception.getCursor() >= 0) {
int i = Math.min(commandsyntaxexception.getInput().length(), commandsyntaxexception.getCursor());
MutableComponent ichatmutablecomponent = Component.empty().withStyle(ChatFormatting.GRAY).withStyle((chatmodifier) -> {
- return chatmodifier.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/" + command));
+ return chatmodifier.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/" + label)); // CraftBukkit // Paper
});
if (i > 10) {
@@ -333,8 +413,18 @@
}
ichatmutablecomponent.append((Component) Component.translatable("command.context.here").withStyle(ChatFormatting.RED, ChatFormatting.ITALIC));
- source.sendFailure(ichatmutablecomponent);
+ // Paper start - Add UnknownCommandEvent
+ // commandlistenerwrapper.sendFailure(ichatmutablecomponent);
+ builder
+ .append(net.kyori.adventure.text.Component.newline())
+ .append(io.papermc.paper.adventure.PaperAdventure.asAdventure(ichatmutablecomponent));
}
+ org.bukkit.event.command.UnknownCommandEvent event = new org.bukkit.event.command.UnknownCommandEvent(commandlistenerwrapper.getBukkitSender(), s, org.spigotmc.SpigotConfig.unknownCommandMessage.isEmpty() ? null : builder.build());
+ org.bukkit.Bukkit.getServer().getPluginManager().callEvent(event);
+ if (event.message() != null) {
+ commandlistenerwrapper.sendFailure(io.papermc.paper.adventure.PaperAdventure.asVanilla(event.message()), false);
+ // Paper end - Add UnknownCommandEvent
+ }
return null;
}
@@ -368,7 +458,7 @@
executioncontext1.close();
} finally {
- Commands.CURRENT_EXECUTION_CONTEXT.set((Object) null);
+ Commands.CURRENT_EXECUTION_CONTEXT.set(null); // CraftBukkit - decompile error
}
} else {
callback.accept(executioncontext);
@@ -377,30 +467,133 @@
}
public void sendCommands(ServerPlayer player) {
- Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> map = Maps.newHashMap();
+ // Paper start - Send empty commands if tab completion is disabled
+ if (org.spigotmc.SpigotConfig.tabComplete < 0) {
+ player.connection.send(new ClientboundCommandsPacket(new RootCommandNode<>()));
+ return;
+ }
+ // Paper end - Send empty commands if tab completion is disabled
+ // CraftBukkit start
+ // Register Vanilla commands into builtRoot as before
+ // Paper start - Perf: Async command map building
+ // Copy root children to avoid concurrent modification during building
+ final Collection<CommandNode<CommandSourceStack>> commandNodes = new java.util.ArrayList<>(this.dispatcher.getRoot().getChildren());
+ COMMAND_SENDING_POOL.execute(() -> this.sendAsync(player, commandNodes));
+ }
+
+ // Fixed pool, but with discard policy
+ public static final java.util.concurrent.ExecutorService COMMAND_SENDING_POOL = new java.util.concurrent.ThreadPoolExecutor(
+ 2, 2, 0, java.util.concurrent.TimeUnit.MILLISECONDS,
+ new java.util.concurrent.LinkedBlockingQueue<>(),
+ new com.google.common.util.concurrent.ThreadFactoryBuilder()
+ .setNameFormat("Paper Async Command Builder Thread Pool - %1$d")
+ .setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(net.minecraft.server.MinecraftServer.LOGGER))
+ .build(),
+ new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy()
+ );
+
+ private void sendAsync(ServerPlayer player, Collection<CommandNode<CommandSourceStack>> dispatcherRootChildren) {
+ // Paper end - Perf: Async command map building
+ Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> map = Maps.newIdentityHashMap(); // Use identity to prevent aliasing issues
+ // Paper - brigadier API removes the need to fill the map twice
RootCommandNode<SharedSuggestionProvider> rootcommandnode = new RootCommandNode();
map.put(this.dispatcher.getRoot(), rootcommandnode);
- this.fillUsableCommands(this.dispatcher.getRoot(), rootcommandnode, player.createCommandSourceStack(), map);
+ this.fillUsableCommands(dispatcherRootChildren, rootcommandnode, player.createCommandSourceStack(), map); // Paper - Perf: Async command map building; pass copy of children
+
+ Collection<String> bukkit = new LinkedHashSet<>();
+ for (CommandNode node : rootcommandnode.getChildren()) {
+ bukkit.add(node.getName());
+ }
+ // Paper start - Perf: Async command map building
+ new com.destroystokyo.paper.event.brigadier.AsyncPlayerSendCommandsEvent<CommandSourceStack>(player.getBukkitEntity(), (RootCommandNode) rootcommandnode, false).callEvent(); // Paper - Brigadier API
+ net.minecraft.server.MinecraftServer.getServer().execute(() -> {
+ runSync(player, bukkit, rootcommandnode);
+ });
+ }
+
+ private void runSync(ServerPlayer player, Collection<String> bukkit, RootCommandNode<SharedSuggestionProvider> rootcommandnode) {
+ // Paper end - Perf: Async command map building
+ new com.destroystokyo.paper.event.brigadier.AsyncPlayerSendCommandsEvent<CommandSourceStack>(player.getBukkitEntity(), (RootCommandNode) rootcommandnode, true).callEvent(); // Paper - Brigadier API
+ PlayerCommandSendEvent event = new PlayerCommandSendEvent(player.getBukkitEntity(), new LinkedHashSet<>(bukkit));
+ event.getPlayer().getServer().getPluginManager().callEvent(event);
+
+ // Remove labels that were removed during the event
+ for (String orig : bukkit) {
+ if (!event.getCommands().contains(orig)) {
+ rootcommandnode.removeCommand(orig);
+ }
+ }
+ // CraftBukkit end
player.connection.send(new ClientboundCommandsPacket(rootcommandnode));
}
- private void fillUsableCommands(CommandNode<CommandSourceStack> tree, CommandNode<SharedSuggestionProvider> result, CommandSourceStack source, Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> resultNodes) {
- Iterator iterator = tree.getChildren().iterator();
+ // Paper start - Perf: Async command map building; pass copy of children
+ private void fillUsableCommands(Collection<CommandNode<CommandSourceStack>> children, CommandNode<SharedSuggestionProvider> result, CommandSourceStack source, Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> resultNodes) {
+ resultNodes.keySet().removeIf((node) -> !org.spigotmc.SpigotConfig.sendNamespaced && node.getName().contains( ":" )); // Paper - Remove namedspaced from result nodes to prevent redirect trimming ~ see comment below
+ Iterator iterator = children.iterator();
+ // Paper end - Perf: Async command map building
while (iterator.hasNext()) {
CommandNode<CommandSourceStack> commandnode2 = (CommandNode) iterator.next();
+ // Paper start - Brigadier API
+ if (commandnode2.clientNode != null) {
+ commandnode2 = commandnode2.clientNode;
+ }
+ // Paper end - Brigadier API
+ if ( !org.spigotmc.SpigotConfig.sendNamespaced && commandnode2.getName().contains( ":" ) ) continue; // Spigot
if (commandnode2.canUse(source)) {
- ArgumentBuilder<SharedSuggestionProvider, ?> argumentbuilder = commandnode2.createBuilder();
+ ArgumentBuilder argumentbuilder = commandnode2.createBuilder(); // CraftBukkit - decompile error
+ // Paper start
+ /*
+ Because of how commands can be yeeted right left and center due to bad bukkit practices
+ we need to be able to ensure that ALL commands are registered (even redirects).
+ What this will do is IF the redirect seems to be "dead" it will create a builder and essentially populate (flatten)
+ all the children from the dead redirect to the node.
+
+ So, if minecraft:msg redirects to msg but the original msg node has been overriden minecraft:msg will now act as msg and will explicilty inherit its children.
+
+ The only way to fix this is to either:
+ - Send EVERYTHING flattened, don't use redirects
+ - Don't allow command nodes to be deleted
+ - Do this :)
+ */
+
+ // Is there an invalid command redirect?
+ if (argumentbuilder.getRedirect() != null && (CommandNode) resultNodes.get(argumentbuilder.getRedirect()) == null) {
+ // Create the argument builder with the same values as the specified node, but with a different literal and populated children
+
+ CommandNode<CommandSourceStack> redirect = argumentbuilder.getRedirect();
+ // Diff copied from LiteralCommand#createBuilder
+ final com.mojang.brigadier.builder.LiteralArgumentBuilder<CommandSourceStack> builder = com.mojang.brigadier.builder.LiteralArgumentBuilder.literal(commandnode2.getName());
+ builder.requires(redirect.getRequirement());
+ // builder.forward(redirect.getRedirect(), redirect.getRedirectModifier(), redirect.isFork()); We don't want to migrate the forward, since it's invalid.
+ if (redirect.getCommand() != null) {
+ builder.executes(redirect.getCommand());
+ }
+ // Diff copied from LiteralCommand#createBuilder
+ for (CommandNode<CommandSourceStack> child : redirect.getChildren()) {
+ builder.then(child);
+ }
+
+ argumentbuilder = builder;
+ }
+ // Paper end
+
argumentbuilder.requires((icompletionprovider) -> {
return true;
});
if (argumentbuilder.getCommand() != null) {
- argumentbuilder.executes((commandcontext) -> {
- return 0;
+ // Paper start - fix suggestions due to falsely equal nodes
+ argumentbuilder.executes(new com.mojang.brigadier.Command<io.papermc.paper.command.brigadier.CommandSourceStack>() {
+ @Override
+ public int run(com.mojang.brigadier.context.CommandContext<io.papermc.paper.command.brigadier.CommandSourceStack> commandContext) throws CommandSyntaxException {
+ return 0;
+ }
});
+ // Paper end
}
if (argumentbuilder instanceof RequiredArgumentBuilder) {
@@ -415,12 +608,12 @@
argumentbuilder.redirect((CommandNode) resultNodes.get(argumentbuilder.getRedirect()));
}
- CommandNode<SharedSuggestionProvider> commandnode3 = argumentbuilder.build();
+ CommandNode commandnode3 = argumentbuilder.build(); // CraftBukkit - decompile error
resultNodes.put(commandnode2, commandnode3);
result.addChild(commandnode3);
if (!commandnode2.getChildren().isEmpty()) {
- this.fillUsableCommands(commandnode2, commandnode3, source, resultNodes);
+ this.fillUsableCommands(commandnode2.getChildren(), commandnode3, source, resultNodes); // Paper - Perf: Async command map building; pass children directly
}
}
}
@@ -481,7 +674,7 @@
}
private <T> HolderLookup.RegistryLookup.Delegate<T> createLookup(final HolderLookup.RegistryLookup<T> original) {
- return new HolderLookup.RegistryLookup.Delegate<T>(this) {
+ return new HolderLookup.RegistryLookup.Delegate<T>() { // CraftBukkit - decompile error
@Override
public HolderLookup.RegistryLookup<T> parent() {
return original;

View File

@@ -0,0 +1,52 @@
--- a/net/minecraft/commands/arguments/EntityArgument.java
+++ b/net/minecraft/commands/arguments/EntityArgument.java
@@ -102,21 +102,27 @@
}
private EntitySelector parse(StringReader reader, boolean allowAtSelectors) throws CommandSyntaxException {
+ // CraftBukkit start
+ return this.parse(reader, allowAtSelectors, false);
+ }
+
+ public EntitySelector parse(StringReader stringreader, boolean flag, boolean overridePermissions) throws CommandSyntaxException {
+ // CraftBukkit end
boolean flag1 = false;
- EntitySelectorParser argumentparserselector = new EntitySelectorParser(reader, allowAtSelectors);
- EntitySelector entityselector = argumentparserselector.parse();
+ EntitySelectorParser argumentparserselector = new EntitySelectorParser(stringreader, flag);
+ EntitySelector entityselector = argumentparserselector.parse(overridePermissions); // CraftBukkit
if (entityselector.getMaxResults() > 1 && this.single) {
if (this.playersOnly) {
- reader.setCursor(0);
- throw EntityArgument.ERROR_NOT_SINGLE_PLAYER.createWithContext(reader);
+ stringreader.setCursor(0);
+ throw EntityArgument.ERROR_NOT_SINGLE_PLAYER.createWithContext(stringreader);
} else {
- reader.setCursor(0);
- throw EntityArgument.ERROR_NOT_SINGLE_ENTITY.createWithContext(reader);
+ stringreader.setCursor(0);
+ throw EntityArgument.ERROR_NOT_SINGLE_ENTITY.createWithContext(stringreader);
}
} else if (entityselector.includesEntities() && this.playersOnly && !entityselector.isSelfSelector()) {
- reader.setCursor(0);
- throw EntityArgument.ERROR_ONLY_PLAYERS_ALLOWED.createWithContext(reader);
+ stringreader.setCursor(0);
+ throw EntityArgument.ERROR_ONLY_PLAYERS_ALLOWED.createWithContext(stringreader);
} else {
return entityselector;
}
@@ -129,7 +135,12 @@
StringReader stringreader = new StringReader(suggestionsbuilder.getInput());
stringreader.setCursor(suggestionsbuilder.getStart());
- EntitySelectorParser argumentparserselector = new EntitySelectorParser(stringreader, EntitySelectorParser.allowSelectors(icompletionprovider));
+ // Paper start - Fix EntityArgument permissions
+ final boolean permission = object instanceof CommandSourceStack stack
+ ? stack.bypassSelectorPermissions || stack.hasPermission(2, "minecraft.command.selector")
+ : icompletionprovider.hasPermission(2);
+ EntitySelectorParser argumentparserselector = new EntitySelectorParser(stringreader, permission);
+ // Paper end - Fix EntityArgument permissions
try {
argumentparserselector.parse();

View File

@@ -0,0 +1,41 @@
--- a/net/minecraft/commands/arguments/MessageArgument.java
+++ b/net/minecraft/commands/arguments/MessageArgument.java
@@ -40,6 +40,11 @@
public static void resolveChatMessage(CommandContext<CommandSourceStack> context, String name, Consumer<PlayerChatMessage> callback) throws CommandSyntaxException {
MessageArgument.Message message = context.getArgument(name, MessageArgument.Message.class);
+ // Paper start
+ resolveChatMessage(message, context, name, callback);
+ }
+ public static void resolveChatMessage(MessageArgument.Message message, CommandContext<CommandSourceStack> context, String name, Consumer<PlayerChatMessage> callback) throws CommandSyntaxException {
+ // Paper end
CommandSourceStack commandSourceStack = context.getSource();
Component component = message.resolveComponent(commandSourceStack);
CommandSigningContext commandSigningContext = commandSourceStack.getSigningContext();
@@ -54,17 +59,21 @@
private static void resolveSignedMessage(Consumer<PlayerChatMessage> callback, CommandSourceStack source, PlayerChatMessage message) {
MinecraftServer minecraftServer = source.getServer();
CompletableFuture<FilteredText> completableFuture = filterPlainText(source, message);
- Component component = minecraftServer.getChatDecorator().decorate(source.getPlayer(), message.decoratedContent());
- source.getChatMessageChainer().append(completableFuture, filtered -> {
- PlayerChatMessage playerChatMessage2 = message.withUnsignedContent(component).filter(filtered.mask());
+ // Paper start - support asynchronous chat decoration
+ CompletableFuture<Component> componentFuture = minecraftServer.getChatDecorator().decorate(source.getPlayer(), source, message.decoratedContent());
+ source.getChatMessageChainer().append(CompletableFuture.allOf(completableFuture, componentFuture), filtered -> {
+ PlayerChatMessage playerChatMessage2 = message.withUnsignedContent(componentFuture.join()).filter(completableFuture.join().mask());
+ // Paper end - support asynchronous chat decoration
callback.accept(playerChatMessage2);
});
}
private static void resolveDisguisedMessage(Consumer<PlayerChatMessage> callback, CommandSourceStack source, PlayerChatMessage message) {
ChatDecorator chatDecorator = source.getServer().getChatDecorator();
- Component component = chatDecorator.decorate(source.getPlayer(), message.decoratedContent());
- callback.accept(message.withUnsignedContent(component));
+ // Paper start - support asynchronous chat decoration
+ CompletableFuture<Component> componentFuture = chatDecorator.decorate(source.getPlayer(), source, message.decoratedContent());
+ source.getChatMessageChainer().append(componentFuture, (result) -> callback.accept(message.withUnsignedContent(result)));
+ // Paper end - support asynchronous chat decoration
}
private static CompletableFuture<FilteredText> filterPlainText(CommandSourceStack source, PlayerChatMessage message) {

View File

@@ -0,0 +1,38 @@
--- a/net/minecraft/commands/arguments/blocks/BlockStateParser.java
+++ b/net/minecraft/commands/arguments/blocks/BlockStateParser.java
@@ -67,7 +67,7 @@
private final StringReader reader;
private final boolean forTesting;
private final boolean allowNbt;
- private final Map<Property<?>, Comparable<?>> properties = Maps.newHashMap();
+ private final Map<Property<?>, Comparable<?>> properties = Maps.newLinkedHashMap(); // CraftBukkit - stable
private final Map<String, String> vagueProperties = Maps.newHashMap();
private ResourceLocation id = ResourceLocation.withDefaultNamespace("");
@Nullable
@@ -275,7 +275,7 @@
Iterator iterator = property.getPossibleValues().iterator();
while (iterator.hasNext()) {
- T t0 = (Comparable) iterator.next();
+ T t0 = (T) iterator.next(); // CraftBukkit - decompile error
if (t0 instanceof Integer integer) {
builder.suggest(integer);
@@ -545,7 +545,7 @@
Optional<T> optional = property.getValue(value);
if (optional.isPresent()) {
- this.state = (BlockState) this.state.setValue(property, (Comparable) optional.get());
+ this.state = (BlockState) this.state.setValue(property, (T) optional.get()); // CraftBukkit - decompile error
this.properties.put(property, (Comparable) optional.get());
} else {
this.reader.setCursor(cursor);
@@ -581,7 +581,7 @@
private static <T extends Comparable<T>> void appendProperty(StringBuilder builder, Property<T> property, Comparable<?> value) {
builder.append(property.getName());
builder.append('=');
- builder.append(property.getName(value));
+ builder.append(property.getName((T) value)); // CraftBukkit - decompile error
}
public static record BlockResult(BlockState blockState, Map<Property<?>, Comparable<?>> properties, @Nullable CompoundTag nbt) {

View File

@@ -0,0 +1,10 @@
--- a/net/minecraft/commands/arguments/item/ItemInput.java
+++ b/net/minecraft/commands/arguments/item/ItemInput.java
@@ -78,6 +78,6 @@
}
private String getItemName() {
- return this.item.unwrapKey().map(ResourceKey::location).orElseGet(() -> "unknown[" + this.item + "]").toString();
+ return this.item.unwrapKey().<Object>map(ResourceKey::location).orElseGet(() -> "unknown[" + this.item + "]").toString(); // Paper - decompile fix
}
}

View File

@@ -0,0 +1,11 @@
--- a/net/minecraft/commands/arguments/selector/EntitySelector.java
+++ b/net/minecraft/commands/arguments/selector/EntitySelector.java
@@ -93,7 +93,7 @@
}
private void checkPermissions(CommandSourceStack source) throws CommandSyntaxException {
- if (this.usesSelector && !source.hasPermission(2)) {
+ if (!source.bypassSelectorPermissions && (this.usesSelector && !source.hasPermission(2, "minecraft.command.selector"))) { // CraftBukkit // Paper - add bypass for selector perms
throw EntityArgument.ERROR_SELECTORS_NOT_ALLOWED.create();
}
}

View File

@@ -0,0 +1,55 @@
--- a/net/minecraft/commands/arguments/selector/EntitySelectorParser.java
+++ b/net/minecraft/commands/arguments/selector/EntitySelectorParser.java
@@ -133,7 +133,7 @@
boolean flag;
if (source instanceof SharedSuggestionProvider icompletionprovider) {
- if (icompletionprovider.hasPermission(2)) {
+ if (source instanceof net.minecraft.commands.CommandSourceStack stack ? stack.bypassSelectorPermissions || stack.hasPermission(2, "minecraft.command.selector") : icompletionprovider.hasPermission(2)) { // Paper - Fix EntityArgument permissions
flag = true;
return flag;
}
@@ -158,7 +158,7 @@
axisalignedbb = this.createAabb(this.deltaX == null ? 0.0D : this.deltaX, this.deltaY == null ? 0.0D : this.deltaY, this.deltaZ == null ? 0.0D : this.deltaZ);
}
- Function function;
+ Function<Vec3, Vec3> function; // CraftBukkit - decompile error
if (this.x == null && this.y == null && this.z == null) {
function = (vec3d) -> {
@@ -215,8 +215,10 @@
};
}
- protected void parseSelector() throws CommandSyntaxException {
- this.usesSelectors = true;
+ // CraftBukkit start
+ protected void parseSelector(boolean overridePermissions) throws CommandSyntaxException {
+ this.usesSelectors = !overridePermissions;
+ // CraftBukkit end
this.suggestions = this::suggestSelector;
if (!this.reader.canRead()) {
throw EntitySelectorParser.ERROR_MISSING_SELECTOR_TYPE.createWithContext(this.reader);
@@ -505,6 +507,12 @@
}
public EntitySelector parse() throws CommandSyntaxException {
+ // CraftBukkit start
+ return this.parse(false);
+ }
+
+ public EntitySelector parse(boolean overridePermissions) throws CommandSyntaxException {
+ // CraftBukkit end
this.startPosition = this.reader.getCursor();
this.suggestions = this::suggestNameOrSelector;
if (this.reader.canRead() && this.reader.peek() == '@') {
@@ -513,7 +521,7 @@
}
this.reader.skip();
- this.parseSelector();
+ this.parseSelector(overridePermissions); // CraftBukkit
} else {
this.parseNameOrUUID();
}

View File

@@ -0,0 +1,11 @@
--- a/net/minecraft/commands/arguments/selector/SelectorPattern.java
+++ b/net/minecraft/commands/arguments/selector/SelectorPattern.java
@@ -13,7 +13,7 @@
EntitySelectorParser entitySelectorParser = new EntitySelectorParser(new StringReader(selector), true);
return DataResult.success(new SelectorPattern(selector, entitySelectorParser.parse()));
} catch (CommandSyntaxException var2) {
- return DataResult.error(() -> "Invalid selector component: " + selector + ": " + var2.getMessage());
+ return DataResult.error(() -> "Invalid selector component"); // Paper - limit selector error message
}
}