Search in sources :

Example 1 with CommandCause

use of org.spongepowered.api.command.CommandCause in project SpongeCommon by SpongePowered.

the class SpongeTargetEntityValueParameter method parseValue.

@Override
@NonNull
public Optional<? extends Entity> parseValue(@NonNull final CommandCause cause, final ArgumentReader.@NonNull Mutable reader) throws ArgumentParseException {
    final Object root = cause.cause().root();
    if (root instanceof Living) {
        final Living living = (Living) root;
        final Optional<RayTraceResult<@NonNull Entity>> rayTraceResult = RayTrace.entity().sourceEyePosition(living).direction(living.headDirection()).limit(30).continueWhileBlock(RayTrace.onlyAir()).select(this.isPlayerOnly ? entity -> entity instanceof Player : entity -> true).continueWhileEntity(// if we hit an entity first, it obscures a player.
        r -> false).execute();
        if (rayTraceResult.isPresent()) {
            return rayTraceResult.map(RayTraceResult::selectedObject);
        }
        throw reader.createException(Component.text("The cause root is not looking at a entity!"));
    }
    throw reader.createException(Component.text("The cause root must be a Living!"));
}
Also used : NonNull(org.checkerframework.checker.nullness.qual.NonNull) ArgumentReader(org.spongepowered.api.command.parameter.ArgumentReader) Entity(org.spongepowered.api.entity.Entity) CommandCause(org.spongepowered.api.command.CommandCause) Component(net.kyori.adventure.text.Component) ArgumentParseException(org.spongepowered.api.command.exception.ArgumentParseException) ResourceKey(org.spongepowered.api.ResourceKey) CommandContext(org.spongepowered.api.command.parameter.CommandContext) ResourceKeyedZeroAdvanceValueParameter(org.spongepowered.common.command.brigadier.argument.ResourceKeyedZeroAdvanceValueParameter) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) RayTrace(org.spongepowered.api.util.blockray.RayTrace) Living(org.spongepowered.api.entity.living.Living) RayTraceResult(org.spongepowered.api.util.blockray.RayTraceResult) Player(org.spongepowered.api.entity.living.player.Player) Living(org.spongepowered.api.entity.living.Living) NonNull(org.checkerframework.checker.nullness.qual.NonNull) RayTraceResult(org.spongepowered.api.util.blockray.RayTraceResult) NonNull(org.checkerframework.checker.nullness.qual.NonNull)

Example 2 with CommandCause

use of org.spongepowered.api.command.CommandCause in project SpongeCommon by SpongePowered.

the class SpongeParameterizedCommandBuilder method build.

@Override
public Command.@NonNull Parameterized build() {
    if (this.subcommands.isEmpty()) {
        Preconditions.checkState(this.commandExecutor != null, "Either a subcommand or an executor must exist!");
    } else {
        Preconditions.checkState(!(!this.parameters.isEmpty() && this.commandExecutor == null), "An executor must exist if you set parameters!");
    }
    final Predicate<CommandCause> requirements = this.executionRequirements == null ? cause -> true : this.executionRequirements;
    final List<Parameter.Subcommand> subcommands = this.subcommands.entrySet().stream().map(x -> new SpongeSubcommandParameterBuilder().aliases(x.getValue()).subcommand(x.getKey()).build()).collect(Collectors.toList());
    // build the node.
    return new SpongeParameterizedCommand(subcommands, ImmutableList.copyOf(this.parameters), this.shortDescription, this.extendedDescription, requirements, this.commandExecutor, this.flags, this.isTerminal);
}
Also used : NonNull(org.checkerframework.checker.nullness.qual.NonNull) Command(org.spongepowered.api.command.Command) Predicate(java.util.function.Predicate) Flag(org.spongepowered.api.command.parameter.managed.Flag) Set(java.util.Set) HashMap(java.util.HashMap) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) CommandCause(org.spongepowered.api.command.CommandCause) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Parameter(org.spongepowered.api.command.parameter.Parameter) Component(net.kyori.adventure.text.Component) Map(java.util.Map) CommandExecutor(org.spongepowered.api.command.CommandExecutor) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) SpongeSubcommandParameterBuilder(org.spongepowered.common.command.parameter.subcommand.SpongeSubcommandParameterBuilder) Nullable(org.checkerframework.checker.nullness.qual.Nullable) CommandCause(org.spongepowered.api.command.CommandCause) SpongeSubcommandParameterBuilder(org.spongepowered.common.command.parameter.subcommand.SpongeSubcommandParameterBuilder)

Example 3 with CommandCause

use of org.spongepowered.api.command.CommandCause in project SpongeCommon by SpongePowered.

the class ServerGamePacketListenerImplMixin method impl$getSuggestionsFromNonBrigCommand.

@Inject(method = "handleCustomCommandSuggestions", at = @At(value = "NEW", target = "com/mojang/brigadier/StringReader", remap = false), cancellable = true)
private void impl$getSuggestionsFromNonBrigCommand(final ServerboundCommandSuggestionPacket packet, final CallbackInfo ci) {
    final String rawCommand = packet.getCommand();
    final String[] command = CommandUtil.extractCommandString(rawCommand);
    final CommandCause cause = CommandCause.create();
    final SpongeCommandManager manager = SpongeCommandManager.get(this.server);
    if (!rawCommand.contains(" ")) {
        final SuggestionsBuilder builder = new SuggestionsBuilder(command[0], 0);
        if (command[0].isEmpty()) {
            manager.getAliasesForCause(cause).forEach(builder::suggest);
        } else {
            manager.getAliasesThatStartWithForCause(cause, command[0]).forEach(builder::suggest);
        }
        this.connection.send(new ClientboundCommandSuggestionsPacket(packet.getId(), builder.build()));
        ci.cancel();
    } else {
        final Optional<CommandMapping> mappingOptional = manager.commandMapping(command[0].toLowerCase(Locale.ROOT)).filter(x -> !(x.registrar() instanceof BrigadierBasedRegistrar));
        if (mappingOptional.isPresent()) {
            final CommandMapping mapping = mappingOptional.get();
            if (mapping.registrar().canExecute(cause, mapping)) {
                final SuggestionsBuilder builder = CommandUtil.createSuggestionsForRawCommand(rawCommand, command, cause, mapping);
                this.connection.send(new ClientboundCommandSuggestionsPacket(packet.getId(), builder.build()));
            } else {
                this.connection.send(new ClientboundCommandSuggestionsPacket(packet.getId(), Suggestions.empty().join()));
            }
            ci.cancel();
        }
    }
}
Also used : CommandMapping(org.spongepowered.api.command.manager.CommandMapping) SpongeCommandManager(org.spongepowered.common.command.manager.SpongeCommandManager) CommandCause(org.spongepowered.api.command.CommandCause) SuggestionsBuilder(com.mojang.brigadier.suggestion.SuggestionsBuilder) ClientboundCommandSuggestionsPacket(net.minecraft.network.protocol.game.ClientboundCommandSuggestionsPacket) BrigadierBasedRegistrar(org.spongepowered.common.command.registrar.BrigadierBasedRegistrar) Inject(org.spongepowered.asm.mixin.injection.Inject)

Example 4 with CommandCause

use of org.spongepowered.api.command.CommandCause in project SpongeCommon by SpongePowered.

the class SpongeCommandCauseFactory method create.

@Override
@NonNull
public CommandCause create() {
    try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) {
        final Cause cause = frame.currentCause();
        final CommandSource iCommandSource = cause.first(CommandSource.class).orElseGet(() -> SpongeCommon.game().systemSubject());
        final CommandSourceStack commandSource;
        if (iCommandSource instanceof CommandSourceProviderBridge) {
            // We know about this one so we can create it using the factory method on the source.
            commandSource = ((CommandSourceProviderBridge) iCommandSource).bridge$getCommandSource(cause);
        } else {
            // try to create a command cause from the given ICommandSource, but as Mojang did not see fit to
            // put any identifying characteristics on the object, we have to go it alone...
            final EventContext context = cause.context();
            @Nullable final Locatable locatable = iCommandSource instanceof Locatable ? (Locatable) iCommandSource : null;
            final Component displayName;
            if (iCommandSource instanceof Entity) {
                displayName = ((Entity) iCommandSource).get(Keys.DISPLAY_NAME).map(SpongeAdventure::asVanilla).orElseGet(() -> new TextComponent(iCommandSource instanceof Nameable ? ((Nameable) iCommandSource).name() : iCommandSource.getClass().getSimpleName()));
            } else {
                displayName = new TextComponent(iCommandSource instanceof Nameable ? ((Nameable) iCommandSource).name() : iCommandSource.getClass().getSimpleName());
            }
            final String name = displayName.getString();
            commandSource = new CommandSourceStack(iCommandSource, context.get(EventContextKeys.LOCATION).map(x -> VecHelper.toVanillaVector3d(x.position())).orElseGet(() -> locatable == null ? Vec3.ZERO : VecHelper.toVanillaVector3d(locatable.location().position())), context.get(EventContextKeys.ROTATION).map(rot -> new Vec2((float) rot.x(), (float) rot.y())).orElse(Vec2.ZERO), context.get(EventContextKeys.LOCATION).map(x -> (ServerLevel) x.world()).orElseGet(() -> locatable == null ? SpongeCommon.server().getLevel(Level.OVERWORLD) : (ServerLevel) locatable.serverLocation().world()), 4, name, displayName, SpongeCommon.server(), iCommandSource instanceof Entity ? (net.minecraft.world.entity.Entity) iCommandSource : null);
        }
        // We don't want the command source to have altered the cause here (unless there is the special case of the
        // server), so we reset it back to what it was (in the ctor of CommandSource, it will add the current source
        // to the cause - that's for if the source is created elsewhere, not here)
        ((CommandSourceStackBridge) commandSource).bridge$setCause(frame.currentCause());
        return (CommandCause) commandSource;
    }
}
Also used : TextComponent(net.minecraft.network.chat.TextComponent) NonNull(org.checkerframework.checker.nullness.qual.NonNull) EventContextKeys(org.spongepowered.api.event.EventContextKeys) CommandSourceStack(net.minecraft.commands.CommandSourceStack) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) CommandSourceProviderBridge(org.spongepowered.common.bridge.commands.CommandSourceProviderBridge) ServerLevel(net.minecraft.server.level.ServerLevel) EventContext(org.spongepowered.api.event.EventContext) Locatable(org.spongepowered.api.world.Locatable) CommandSourceStackBridge(org.spongepowered.common.bridge.commands.CommandSourceStackBridge) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Nameable(org.spongepowered.api.util.Nameable) Nullable(org.checkerframework.checker.nullness.qual.Nullable) Component(net.minecraft.network.chat.Component) SpongeCommon(org.spongepowered.common.SpongeCommon) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) Entity(org.spongepowered.api.entity.Entity) Cause(org.spongepowered.api.event.Cause) CommandCause(org.spongepowered.api.command.CommandCause) TextComponent(net.minecraft.network.chat.TextComponent) Keys(org.spongepowered.api.data.Keys) Vec2(net.minecraft.world.phys.Vec2) Vec3(net.minecraft.world.phys.Vec3) VecHelper(org.spongepowered.common.util.VecHelper) CommandSource(net.minecraft.commands.CommandSource) Level(net.minecraft.world.level.Level) Entity(org.spongepowered.api.entity.Entity) ServerLevel(net.minecraft.server.level.ServerLevel) CommandSourceStackBridge(org.spongepowered.common.bridge.commands.CommandSourceStackBridge) CommandSource(net.minecraft.commands.CommandSource) CommandCause(org.spongepowered.api.command.CommandCause) CommandSourceStack(net.minecraft.commands.CommandSourceStack) EventContext(org.spongepowered.api.event.EventContext) Nameable(org.spongepowered.api.util.Nameable) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Vec2(net.minecraft.world.phys.Vec2) Cause(org.spongepowered.api.event.Cause) CommandCause(org.spongepowered.api.command.CommandCause) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) CommandSourceProviderBridge(org.spongepowered.common.bridge.commands.CommandSourceProviderBridge) Component(net.minecraft.network.chat.Component) TextComponent(net.minecraft.network.chat.TextComponent) Nullable(org.checkerframework.checker.nullness.qual.Nullable) Locatable(org.spongepowered.api.world.Locatable) NonNull(org.checkerframework.checker.nullness.qual.NonNull)

Example 5 with CommandCause

use of org.spongepowered.api.command.CommandCause in project SpongeCommon by SpongePowered.

the class SpongeCommandManager method prettyPrintThrowableError.

private void prettyPrintThrowableError(final Throwable thr, final String commandNoArgs, final String args, final CommandCause cause) {
    final String commandString;
    if (args != null && !args.isEmpty()) {
        commandString = commandNoArgs + " " + args;
    } else {
        commandString = commandNoArgs;
    }
    final SpongeCommandMapping mapping = this.commandMappings.get(commandNoArgs.toLowerCase());
    final PrettyPrinter prettyPrinter = new PrettyPrinter(100).add("Unexpected error occurred while executing command '%s'", commandString).centre().hr().addWrapped("While trying to run '%s', an error occurred that the command processor was not expecting. " + "This usually indicates an error in the plugin that owns this command. Report this error " + "to the plugin developer first - this is usually not a Sponge error.", commandString).hr().add().add("Command: %s", commandString).add("Owning Plugin: %s", mapping.plugin().map(x -> x.metadata().id()).orElse("unknown")).add("Owning Registrar: %s", mapping.registrar().getClass().getName()).add().add("Exception Details: ");
    if (thr instanceof SpongeCommandSyntaxException) {
        // we know the inner exception was wrapped by us.
        prettyPrinter.add(thr.getCause());
    } else {
        prettyPrinter.add(thr);
    }
    prettyPrinter.add().add("CommandCause details: ").addWrapped(cause.cause().toString()).log(SpongeCommon.logger(), Level.ERROR);
}
Also used : LiteralCommandNode(com.mojang.brigadier.tree.LiteralCommandNode) Object2BooleanMap(it.unimi.dsi.fastutil.objects.Object2BooleanMap) SpongeCommandDispatcher(org.spongepowered.common.command.brigadier.dispatcher.SpongeCommandDispatcher) Arrays(java.util.Arrays) Game(org.spongepowered.api.Game) Inject(com.google.inject.Inject) Level(org.apache.logging.log4j.Level) CommandFailedRegistrationException(org.spongepowered.api.command.manager.CommandFailedRegistrationException) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) CommandPhaseContext(org.spongepowered.common.event.tracking.phase.general.CommandPhaseContext) MinecraftServer(net.minecraft.server.MinecraftServer) HashMultimap(com.google.common.collect.HashMultimap) Locale(java.util.Locale) Map(java.util.Map) RootCommandTreeNode(org.spongepowered.common.command.registrar.tree.builder.RootCommandTreeNode) TransactionalCaptureSupplier(org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier) Subject(org.spongepowered.api.service.permission.Subject) Object2BooleanOpenHashMap(it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap) PrintWriter(java.io.PrintWriter) SpongeCommandCompletion(org.spongepowered.common.command.SpongeCommandCompletion) ImmutableSet(com.google.common.collect.ImmutableSet) CommandCompletion(org.spongepowered.api.command.CommandCompletion) Collection(java.util.Collection) Launch(org.spongepowered.common.launch.Launch) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) SpongeCommandResult(org.spongepowered.common.command.result.SpongeCommandResult) TypeToken(io.leangen.geantyref.TypeToken) Collectors(java.util.stream.Collectors) LiteralArgumentBuilder(com.mojang.brigadier.builder.LiteralArgumentBuilder) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) SpongeParameterizedCommandRegistrar(org.spongepowered.common.command.registrar.SpongeParameterizedCommandRegistrar) Player(net.minecraft.world.entity.player.Player) Objects(java.util.Objects) ExecuteCommandEvent(org.spongepowered.api.event.command.ExecuteCommandEvent) List(java.util.List) PhaseContext(org.spongepowered.common.event.tracking.PhaseContext) Optional(java.util.Optional) HoverEvent(net.kyori.adventure.text.event.HoverEvent) CommandManager(org.spongepowered.api.command.manager.CommandManager) SpongePaginationService(org.spongepowered.common.service.game.pagination.SpongePaginationService) CommandRegistrar(org.spongepowered.api.command.registrar.CommandRegistrar) NonNull(org.checkerframework.checker.nullness.qual.NonNull) EventContextKeys(org.spongepowered.api.event.EventContextKeys) ComponentMessageThrowable(net.kyori.adventure.util.ComponentMessageThrowable) SharedSuggestionProvider(net.minecraft.commands.SharedSuggestionProvider) CommandSourceStack(net.minecraft.commands.CommandSourceStack) Constants(org.spongepowered.common.util.Constants) Command(com.mojang.brigadier.Command) CommandsBridge(org.spongepowered.common.bridge.commands.CommandsBridge) PrettyPrinter(org.spongepowered.common.util.PrettyPrinter) HashMap(java.util.HashMap) BrigadierCommandRegistrar(org.spongepowered.common.command.registrar.BrigadierCommandRegistrar) Multimap(com.google.common.collect.Multimap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) SpongeCommand(org.spongepowered.common.command.sponge.SpongeCommand) Component(net.kyori.adventure.text.Component) CallbackCommand(org.spongepowered.common.adventure.CallbackCommand) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Nullable(org.checkerframework.checker.nullness.qual.Nullable) GeneralPhase(org.spongepowered.common.event.tracking.phase.general.GeneralPhase) CommandResult(org.spongepowered.api.command.CommandResult) SpongeCommandSyntaxException(org.spongepowered.common.command.exception.SpongeCommandSyntaxException) RegisterCommandEventImpl(org.spongepowered.common.event.lifecycle.RegisterCommandEventImpl) Parameterized(org.spongepowered.api.command.Command.Parameterized) Identity(net.kyori.adventure.identity.Identity) CommandTreeNode(org.spongepowered.api.command.registrar.tree.CommandTreeNode) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) StringWriter(java.io.StringWriter) CommandRegistrarType(org.spongepowered.api.command.registrar.CommandRegistrarType) SpongeCommon(org.spongepowered.common.SpongeCommon) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) PaginationService(org.spongepowered.api.service.pagination.PaginationService) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) Cause(org.spongepowered.api.event.Cause) CommandCause(org.spongepowered.api.command.CommandCause) CommandMapping(org.spongepowered.api.command.manager.CommandMapping) Provider(com.google.inject.Provider) PluginContainer(org.spongepowered.plugin.PluginContainer) Audience(net.kyori.adventure.audience.Audience) SpongeConfigs(org.spongepowered.common.applaunch.config.core.SpongeConfigs) CommandNode(com.mojang.brigadier.tree.CommandNode) GenericTypeReflector(io.leangen.geantyref.GenericTypeReflector) CommandSyntaxException(com.mojang.brigadier.exceptions.CommandSyntaxException) Collections(java.util.Collections) CommandException(org.spongepowered.api.command.exception.CommandException) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) PrettyPrinter(org.spongepowered.common.util.PrettyPrinter) SpongeCommandSyntaxException(org.spongepowered.common.command.exception.SpongeCommandSyntaxException)

Aggregations

CommandCause (org.spongepowered.api.command.CommandCause)8 NonNull (org.checkerframework.checker.nullness.qual.NonNull)6 Optional (java.util.Optional)4 Component (net.kyori.adventure.text.Component)4 Nullable (org.checkerframework.checker.nullness.qual.Nullable)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 CauseStackManager (org.spongepowered.api.event.CauseStackManager)3 Preconditions (com.google.common.base.Preconditions)2 ImmutableList (com.google.common.collect.ImmutableList)2 CommandNode (com.mojang.brigadier.tree.CommandNode)2 Collections (java.util.Collections)2 Objects (java.util.Objects)2 CommandSourceStack (net.minecraft.commands.CommandSourceStack)2 SharedSuggestionProvider (net.minecraft.commands.SharedSuggestionProvider)2 CommandCompletion (org.spongepowered.api.command.CommandCompletion)2 Cause (org.spongepowered.api.event.Cause)2 EventContextKeys (org.spongepowered.api.event.EventContextKeys)2 SpongeCommon (org.spongepowered.common.SpongeCommon)2 SpongeAdventure (org.spongepowered.common.adventure.SpongeAdventure)2