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!"));
}
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);
}
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();
}
}
}
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;
}
}
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);
}
Aggregations