-
-
Notifications
You must be signed in to change notification settings - Fork 407
Commands rework - Brigadier backend #8111
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Pesekjak
wants to merge
14
commits into
SkriptLang:dev/feature
Choose a base branch
from
Pesekjak:feature/command-rework
base: dev/feature
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
d4c9326
added support for single entry data to be included multiple times wit…
Pesekjak f5c7e1b
added test for entry data being included multiple times within a sing…
Pesekjak af6bcbc
added missing constructors
Pesekjak 5aca0a2
made list returned by EntryContainer#getAll unmodifiable
Pesekjak dd48da8
fixed incorrect package name in the test
Pesekjak 65a1f0f
added initial implementation
Pesekjak 3cc007e
switch to custom command sender API,
Pesekjak 8c6a820
changed the registration process for argument types
Pesekjak ab43e0d
added support for unnamed arguments,
Pesekjak 47e6466
removed generic param for native brigadier node from skript command n…
Pesekjak a623e9a
added support for literal groups as arguments
Pesekjak b453668
fixed triggers being loaded multiple times for command arguments comp…
Pesekjak 279d612
implemented the initial support for argument suggestions
Pesekjak 58f3cef
finished the implementation of suggestions, small improvements
Pesekjak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
43 changes: 43 additions & 0 deletions
43
src/main/java/ch/njol/skript/command/brigadier/BrigadierCommandEvent.java
Pesekjak marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package ch.njol.skript.command.brigadier; | ||
|
||
import ch.njol.skript.command.CommandEvent; | ||
import com.mojang.brigadier.context.CommandContext; | ||
import org.bukkit.command.CommandSender; | ||
import org.bukkit.event.HandlerList; | ||
import org.jetbrains.annotations.NotNull; | ||
|
||
/** | ||
* Event for executing brigadier commands. | ||
*/ | ||
public class BrigadierCommandEvent extends CommandEvent { | ||
|
||
private final CommandContext<CommandSender> context; | ||
|
||
public BrigadierCommandEvent(CommandContext<CommandSender> context) { | ||
super(context.getSource(), context.getRootNode().getName(), | ||
context.getNodes().stream() | ||
.map(arg -> arg.getRange().get(context.getInput())) | ||
.toArray(String[]::new)); | ||
this.context = context; | ||
} | ||
|
||
/** | ||
* @return command execution context | ||
*/ | ||
public CommandContext<CommandSender> getContext() { | ||
return context; | ||
} | ||
|
||
// Bukkit stuff | ||
private final static HandlerList handlers = new HandlerList(); | ||
|
||
@Override | ||
public @NotNull HandlerList getHandlers() { | ||
return handlers; | ||
} | ||
|
||
public static HandlerList getHandlerList() { | ||
return handlers; | ||
} | ||
|
||
} |
191 changes: 191 additions & 0 deletions
191
src/main/java/ch/njol/skript/command/brigadier/BrigadierCommandHandler.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,191 @@ | ||
package ch.njol.skript.command.brigadier; | ||
|
||
import ch.njol.skript.Skript; | ||
import com.destroystokyo.paper.event.brigadier.AsyncPlayerSendCommandsEvent; | ||
import com.google.common.base.Preconditions; | ||
import com.mojang.brigadier.CommandDispatcher; | ||
import com.mojang.brigadier.builder.ArgumentBuilder; | ||
import com.mojang.brigadier.builder.LiteralArgumentBuilder; | ||
import com.mojang.brigadier.builder.RequiredArgumentBuilder; | ||
import com.mojang.brigadier.exceptions.CommandSyntaxException; | ||
import com.mojang.brigadier.tree.ArgumentCommandNode; | ||
import com.mojang.brigadier.tree.CommandNode; | ||
import com.mojang.brigadier.tree.LiteralCommandNode; | ||
import com.mojang.brigadier.tree.RootCommandNode; | ||
import io.papermc.paper.command.brigadier.CommandSourceStack; | ||
import org.bukkit.Bukkit; | ||
import org.bukkit.command.BlockCommandSender; | ||
import org.bukkit.command.Command; | ||
import org.bukkit.command.CommandSender; | ||
import org.bukkit.command.ConsoleCommandSender; | ||
import org.bukkit.entity.Entity; | ||
import org.bukkit.entity.Player; | ||
import org.bukkit.event.EventHandler; | ||
import org.bukkit.event.Listener; | ||
import org.jetbrains.annotations.NotNull; | ||
import org.jetbrains.annotations.Nullable; | ||
import org.jetbrains.annotations.Unmodifiable; | ||
import org.jetbrains.annotations.UnmodifiableView; | ||
import org.skriptlang.skript.brigadier.RootSkriptCommandNode; | ||
import org.skriptlang.skript.lang.command.CommandHandler; | ||
import org.skriptlang.skript.lang.command.CommandSourceType; | ||
|
||
import java.lang.reflect.Field; | ||
import java.util.ArrayList; | ||
import java.util.Collections; | ||
import java.util.Map; | ||
import java.util.Set; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
import java.util.function.Consumer; | ||
|
||
public class BrigadierCommandHandler implements CommandHandler<CommandSender>, Listener { | ||
|
||
private final Map<String, RootSkriptCommandNode<CommandSender>> commands = new ConcurrentHashMap<>(); | ||
private @Nullable CommandDispatcher<CommandSender> dispatcher; | ||
|
||
@Override | ||
public synchronized boolean registerCommand(RootSkriptCommandNode<CommandSender> command) { | ||
if (commands.containsKey(command.getLiteral())) { | ||
Skript.error("Command " + command.getLiteral() + " is already registered"); | ||
return false; | ||
} | ||
commands.put(command.getLiteral(), command); | ||
// TODO proper registration with aliases and help page | ||
Bukkit.getCommandMap().getKnownCommands().put(command.getLiteral(), new WrappedBrigadierCommand(command)); | ||
dispatcher = null; // reset dispatcher | ||
Bukkit.getScheduler().runTaskLater(Skript.getInstance(), PaperCommandUtils::syncCommands, 1); | ||
return true; | ||
} | ||
|
||
@Override | ||
public synchronized boolean unregisterCommand(RootSkriptCommandNode<CommandSender> command) { | ||
boolean result = commands.remove(command.getLiteral(), command); | ||
if (!result) return false; | ||
Bukkit.getCommandMap().getKnownCommands().remove(command.getLiteral()); | ||
dispatcher = null; // reset dispatcher | ||
Bukkit.getScheduler().runTaskLater(Skript.getInstance(), PaperCommandUtils::syncCommands, 1); | ||
return true; | ||
} | ||
|
||
@Override | ||
public @Nullable RootSkriptCommandNode<CommandSender> getCommand(String label) { | ||
return commands.get(label); | ||
} | ||
|
||
@Override | ||
public @UnmodifiableView Map<String, RootSkriptCommandNode<CommandSender>> getAllCommands() { | ||
return Collections.unmodifiableMap(commands); | ||
} | ||
|
||
@Override | ||
public boolean dispatchCommand(CommandSender source, String input) { | ||
if (dispatcher == null) { | ||
dispatcher = new CommandDispatcher<>(); | ||
commands.values().forEach(cmd -> dispatcher.register(cmd.flatToBuilder())); | ||
} | ||
|
||
// TODO | ||
// if the command does not exist return false | ||
// send error message to source similar to vanilla | ||
try { | ||
dispatcher.execute(input, source); | ||
} catch (CommandSyntaxException exception) { | ||
Skript.getInstance().getSLF4JLogger().info("Command syntax error", exception); | ||
} | ||
return true; | ||
} | ||
|
||
@Override | ||
public @Unmodifiable Set<CommandSourceType> supportedTypes() { | ||
return Set.of( | ||
CommandSourceType.typed(Player.class, "player", "the player", "players", "the players"), | ||
CommandSourceType.typed(ConsoleCommandSender.class, "console", "the console", "server", "the server"), | ||
CommandSourceType.typed(BlockCommandSender.class, "block", "blocks"), | ||
CommandSourceType.typed(Entity.class, "entity", "entities") | ||
); | ||
} | ||
|
||
private static final @Nullable Field NODE_CHILDREN_FIELD; | ||
|
||
static { | ||
Field nodeChildrenField = null; | ||
try { | ||
nodeChildrenField = CommandNode.class.getDeclaredField("children"); | ||
nodeChildrenField.setAccessible(true); | ||
} catch (Exception exception) { | ||
if (Skript.debug()) | ||
throw Skript.exception(exception, "Failed to access the command node children field"); | ||
} | ||
NODE_CHILDREN_FIELD = nodeChildrenField; | ||
} | ||
|
||
@EventHandler | ||
@SuppressWarnings("UnstableApiUsage") | ||
public void onAsyncPlayerSendCommands(AsyncPlayerSendCommandsEvent<@NotNull CommandSourceStack> event) { | ||
if (!event.isAsynchronous() && event.hasFiredAsync()) | ||
return; | ||
RootCommandNode<CommandSourceStack> rootNode = event.getCommandNode(); | ||
Consumer<CommandNode<CommandSourceStack>> bukkitNodeRemover = node -> {}; | ||
try { | ||
Preconditions.checkNotNull(NODE_CHILDREN_FIELD); | ||
//noinspection unchecked | ||
Map<String, CommandNode<CommandSourceStack>> children = (Map<String, CommandNode<CommandSourceStack>>) | ||
NODE_CHILDREN_FIELD.get(rootNode); | ||
bukkitNodeRemover = node -> children.remove(node.getName()); | ||
} catch (Exception exception) { | ||
if (Skript.debug()) | ||
throw Skript.exception(exception, "Failed to access the node children field"); | ||
} | ||
|
||
for (RootSkriptCommandNode<CommandSender> node : commands.values()) { | ||
CommandNode<CommandSourceStack> paperCompatible = convertToClientsidePaper(node.flat()); | ||
bukkitNodeRemover.accept(paperCompatible); | ||
rootNode.addChild(paperCompatible); | ||
} | ||
} | ||
|
||
// TODO suggestions | ||
|
||
/** | ||
* Converts given command node to a node that can be safely sent to the client. | ||
* | ||
* @param node node to convert | ||
* @return node that can be sent to the client | ||
*/ | ||
// TODO convert paper argument types to NMS argument types | ||
// TODO filter out commands with requirements player does not meet (mirrors vanilla behaviour) | ||
private CommandNode<CommandSourceStack> convertToClientsidePaper(CommandNode<CommandSender> node) { | ||
ArgumentBuilder<CommandSourceStack, ?> builder; | ||
if (node instanceof LiteralCommandNode<CommandSender> lcn) { | ||
builder = LiteralArgumentBuilder.literal(lcn.getLiteral()); | ||
} else if (node instanceof ArgumentCommandNode<?,?> acn) { | ||
builder = RequiredArgumentBuilder.argument(acn.getName(), acn.getType()); | ||
} else { | ||
throw new IllegalArgumentException("Unsupported node implementation; only native Brigadier nodes " | ||
+ "are supported"); | ||
} | ||
if (node.getRequirement() != null) | ||
builder.requires(stack -> node.getRequirement().test(new WrappedCommandSourceStack(stack))); | ||
if (node.getRedirect() != null) | ||
builder.forward(convertToClientsidePaper(node.getRedirect()), ctx -> Collections.emptyList(), node.isFork()); | ||
if (node.getCommand() != null) | ||
builder.executes(ctx -> com.mojang.brigadier.Command.SINGLE_SUCCESS); | ||
node.getChildren().forEach(child -> builder.then(convertToClientsidePaper(child))); | ||
return builder.build(); | ||
} | ||
|
||
private class WrappedBrigadierCommand extends Command { | ||
|
||
protected WrappedBrigadierCommand(RootSkriptCommandNode<CommandSender> node) { | ||
super(node.getName(), node.getDescription() != null ? node.getDescription() : "", | ||
"" /* TODO usage */, new ArrayList<>(node.getAliases())); | ||
} | ||
|
||
@Override | ||
public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String @NotNull [] args) { | ||
return BrigadierCommandHandler.this.dispatchCommand(sender, getName() + " " + String.join(" ", args)); | ||
} | ||
|
||
} | ||
|
||
} |
23 changes: 23 additions & 0 deletions
23
src/main/java/ch/njol/skript/command/brigadier/BrigadierModule.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
package ch.njol.skript.command.brigadier; | ||
|
||
import ch.njol.skript.Skript; | ||
import org.skriptlang.skript.addon.AddonModule; | ||
import org.skriptlang.skript.addon.SkriptAddon; | ||
|
||
import java.io.IOException; | ||
|
||
/** | ||
* Module for Brigadier commands. | ||
*/ | ||
public class BrigadierModule implements AddonModule { | ||
|
||
@Override | ||
public void load(SkriptAddon addon) { | ||
try { | ||
Skript.getAddonInstance().loadClasses("ch.njol.skript.command.brigadier"); | ||
} catch (IOException e) { | ||
throw new RuntimeException(e); | ||
} | ||
} | ||
|
||
} |
57 changes: 57 additions & 0 deletions
57
src/main/java/ch/njol/skript/command/brigadier/BrigadierSuggestionsEvent.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package ch.njol.skript.command.brigadier; | ||
|
||
import com.mojang.brigadier.context.CommandContext; | ||
import org.bukkit.command.CommandSender; | ||
import org.bukkit.event.HandlerList; | ||
import org.jetbrains.annotations.NotNull; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
|
||
/** | ||
* Event for retrieving command suggestions (tab completions). | ||
*/ | ||
public class BrigadierSuggestionsEvent extends BrigadierCommandEvent { | ||
|
||
private final List<String> suggestions = new ArrayList<>(); | ||
|
||
public BrigadierSuggestionsEvent(CommandContext<CommandSender> context) { | ||
super(context); | ||
} | ||
|
||
/** | ||
* @return suggestions | ||
*/ | ||
public String[] getSuggestions() { | ||
return suggestions.toArray(String[]::new); | ||
} | ||
|
||
/** | ||
* @param suggestions new suggestions | ||
*/ | ||
public void setSuggestions(List<String> suggestions) { | ||
this.suggestions.clear(); | ||
if (suggestions != null) | ||
this.suggestions.addAll(suggestions); | ||
} | ||
|
||
/** | ||
* @param suggestions new suggestions | ||
*/ | ||
public void setSuggestions(String... suggestions) { | ||
setSuggestions(List.of(suggestions)); | ||
} | ||
|
||
// Bukkit stuff | ||
private final static HandlerList handlers = new HandlerList(); | ||
|
||
@Override | ||
public @NotNull HandlerList getHandlers() { | ||
return handlers; | ||
} | ||
|
||
public static HandlerList getHandlerList() { | ||
return handlers; | ||
} | ||
|
||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.