use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.
the class SpongeParameterizedCommand method complete.
@Override
public List<CommandCompletion> complete(@NonNull final CommandCause cause, final ArgumentReader.@NonNull Mutable arguments) {
final SpongeCommandDispatcher dispatcher = this.getCachedDispatcher();
final String input = arguments.remaining();
final ParseResults<CommandSourceStack> parseResults = dispatcher.parse((StringReader) arguments, (CommandSourceStack) cause);
final Suggestions suggestions = dispatcher.getCompletionSuggestions(parseResults).join();
return suggestions.getList().stream().map(SpongeCommandCompletion::from).collect(Collectors.toList());
}
use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.
the class BrigadierCommandRegistrar method registerInternal.
private Tuple<CommandMapping, LiteralCommandNode<CommandSourceStack>> registerInternal(final CommandRegistrar<?> registrar, @Nullable final PluginContainer container, final LiteralCommandNode<CommandSourceStack> namespacedCommand, final String[] secondaryAliases, final boolean allowDuplicates) {
// Brig technically allows them...
// Get the builder and the first literal.
final String requestedAlias = namespacedCommand.getLiteral();
final Optional<CommandMapping> existingMapping = this.manager.commandMapping(requestedAlias);
if (allowDuplicates && existingMapping.isPresent()) {
// then we just let it go, the requirements will be of the old node.
this.dispatcher.register(namespacedCommand);
return Tuple.of(existingMapping.get(), namespacedCommand);
}
// This will throw an error if there is an issue.
final CommandMapping mapping = this.manager.registerNamespacedAlias(registrar, container, namespacedCommand, secondaryAliases);
// Let the registration happen.
this.dispatcher.register(namespacedCommand);
// Redirect aliases
for (final String alias : mapping.allAliases()) {
if (!alias.equals(namespacedCommand.getLiteral())) {
final LiteralArgumentBuilder<CommandSourceStack> redirecting = LiteralArgumentBuilder.<CommandSourceStack>literal(alias).executes(namespacedCommand.getCommand()).requires(namespacedCommand.getRequirement());
if (namespacedCommand.getRedirect() == null) {
redirecting.redirect(namespacedCommand);
} else {
// send it directly to the namespaced command's target.
redirecting.forward(namespacedCommand.getRedirect(), namespacedCommand.getRedirectModifier(), namespacedCommand.isFork());
}
this.dispatcher.register(redirecting.build());
}
}
return Tuple.of(mapping, namespacedCommand);
}
use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.
the class SpongeRegistryLoaders method valueParameter.
@SuppressWarnings("ConstantConditions")
public static RegistryLoader<ValueParameter<?>> valueParameter() {
return RegistryLoader.of(l -> {
l.add(ResourceKeyedValueParameters.BIG_DECIMAL, SpongeBigDecimalValueParameter::new);
l.add(ResourceKeyedValueParameters.BIG_INTEGER, SpongeBigIntegerValueParameter::new);
l.add(ResourceKeyedValueParameters.BLOCK_STATE, k -> ClientNativeArgumentParser.createConverter(k, BlockStateArgument.block(), (reader, cause, state) -> (BlockState) state.getState()));
l.add(ResourceKeyedValueParameters.BOOLEAN, k -> ClientNativeArgumentParser.createIdentity(k, BoolArgumentType.bool()));
l.add(ResourceKeyedValueParameters.COLOR, SpongeColorValueParameter::new);
l.add(ResourceKeyedValueParameters.DATA_CONTAINER, SpongeDataContainerValueParameter::new);
l.add(ResourceKeyedValueParameters.DATE_TIME, SpongeDateTimeValueParameter::new);
l.add(ResourceKeyedValueParameters.DOUBLE, k -> ClientNativeArgumentParser.createIdentity(k, DoubleArgumentType.doubleArg()));
l.add(ResourceKeyedValueParameters.DURATION, SpongeDurationValueParameter::new);
l.add(ResourceKeyedValueParameters.ENTITY, k -> ClientNativeArgumentParser.createConverter(k, EntityArgument.entity(), (reader, cause, selector) -> (Entity) selector.findSingleEntity((CommandSourceStack) cause)));
l.add(ResourceKeyedValueParameters.GAME_PROFILE, SpongeGameProfileValueParameter::new);
l.add(ResourceKeyedValueParameters.INTEGER, k -> ClientNativeArgumentParser.createIdentity(k, IntegerArgumentType.integer()));
l.add(ResourceKeyedValueParameters.IP, SpongeIPAddressValueParameter::new);
l.add(ResourceKeyedValueParameters.ITEM_STACK_SNAPSHOT, k -> ClientNativeArgumentParser.createConverter(k, ItemArgument.item(), (reader, cause, converter) -> new SpongeItemStackSnapshot((ItemStack) (Object) converter.createItemStack(1, true))));
l.add(ResourceKeyedValueParameters.LOCATION, SpongeServerLocationValueParameter::new);
l.add(ResourceKeyedValueParameters.LONG, k -> ClientNativeArgumentParser.createIdentity(k, LongArgumentType.longArg()));
l.add(ResourceKeyedValueParameters.MANY_ENTITIES, k -> ClientNativeArgumentParser.createConverter(k, EntityArgument.entities(), (reader, cause, selector) -> selector.findEntities((CommandSourceStack) cause).stream().map(x -> (Entity) x).collect(Collectors.toList())));
l.add(ResourceKeyedValueParameters.MANY_GAME_PROFILES, k -> ClientNativeArgumentParser.createConverter(k, GameProfileArgument.gameProfile(), (reader, cause, converter) -> converter.getNames((CommandSourceStack) cause)));
l.add(ResourceKeyedValueParameters.MANY_PLAYERS, k -> ClientNativeArgumentParser.createConverter(k, EntityArgument.players(), (reader, cause, selector) -> selector.findPlayers((CommandSourceStack) cause)));
l.add(ResourceKeyedValueParameters.NONE, SpongeNoneValueParameter::new);
l.add(ResourceKeyedValueParameters.OPERATOR, SpongeOperatorValueParameter::new);
l.add(ResourceKeyedValueParameters.PLAYER, k -> ClientNativeArgumentParser.createConverter(k, EntityArgument.player(), (reader, cause, selector) -> (Player) selector.findSinglePlayer((CommandSourceStack) cause)));
l.add(ResourceKeyedValueParameters.PLUGIN, SpongePluginContainerValueParameter::new);
l.add(ResourceKeyedValueParameters.REMAINING_JOINED_STRINGS, k -> ClientNativeArgumentParser.createIdentity(k, StringArgumentType.greedyString()));
l.add(ResourceKeyedValueParameters.RESOURCE_KEY, k -> ClientNativeArgumentParser.createConverter(k, ResourceLocationArgument.id(), (reader, cause, resourceLocation) -> (ResourceKey) (Object) resourceLocation));
l.add(ResourceKeyedValueParameters.ROTATION, k -> ClientNativeArgumentParser.createConverter(k, RotationArgument.rotation(), (reader, cause, coords) -> {
final Vec2 rotation = coords.getRotation((CommandSourceStack) cause);
return new Vector3d(rotation.x, rotation.y, 0);
}));
l.add(ResourceKeyedValueParameters.STRING, k -> ClientNativeArgumentParser.createIdentity(k, StringArgumentType.string()));
l.add(ResourceKeyedValueParameters.TARGET_BLOCK, SpongeTargetBlockValueParameter::new);
l.add(ResourceKeyedValueParameters.TARGET_ENTITY, k -> new SpongeTargetEntityValueParameter(k, false));
l.add(ResourceKeyedValueParameters.TARGET_PLAYER, k -> new SpongeTargetEntityValueParameter(k, true));
l.add(ResourceKeyedValueParameters.TEXT_FORMATTING_CODE, k -> ClientNativeArgumentParser.createConverter(k, StringArgumentType.string(), (reader, cause, result) -> LegacyComponentSerializer.legacyAmpersand().deserialize(result)));
l.add(ResourceKeyedValueParameters.TEXT_FORMATTING_CODE_ALL, k -> ClientNativeArgumentParser.createConverter(k, StringArgumentType.greedyString(), (reader, cause, result) -> LegacyComponentSerializer.legacyAmpersand().deserialize(result)));
l.add(ResourceKeyedValueParameters.TEXT_JSON, k -> ClientNativeArgumentParser.createConverter(k, ComponentArgument.textComponent(), (reader, cause, result) -> SpongeAdventure.asAdventure(result)));
l.add(ResourceKeyedValueParameters.TEXT_JSON_ALL, k -> ClientNativeArgumentParser.createConverter(k, StringArgumentType.greedyString(), (reader, cause, result) -> GsonComponentSerializer.gson().deserialize(result)));
l.add(ResourceKeyedValueParameters.URL, k -> ClientNativeArgumentParser.createConverter(k, StringArgumentType.string(), (reader, cause, input) -> {
try {
return new URL(input);
} catch (final MalformedURLException ex) {
throw new SimpleCommandExceptionType(new TextComponent("Could not parse " + input + " as a URL")).createWithContext(reader);
}
}));
l.add(ResourceKeyedValueParameters.USER, SpongeUserValueParameter::new);
l.add(ResourceKeyedValueParameters.UUID, k -> ClientNativeArgumentParser.createIdentity(k, UuidArgument.uuid()));
l.add(ResourceKeyedValueParameters.VECTOR2D, k -> ClientNativeArgumentParser.createConverter(k, Vec2Argument.vec2(), (reader, cause, result) -> {
final net.minecraft.world.phys.Vec3 r = result.getPosition((CommandSourceStack) cause);
return new Vector2d(r.x, r.z);
}));
l.add(ResourceKeyedValueParameters.VECTOR3D, k -> ClientNativeArgumentParser.createConverter(k, Vec3Argument.vec3(false), (reader, cause, result) -> VecHelper.toVector3d(result.getPosition((CommandSourceStack) cause))));
l.add(ResourceKeyedValueParameters.WORLD, k -> ClientNativeArgumentParser.createConverter(k, DimensionArgument.dimension(), (reader, cause, result) -> Sponge.server().worldManager().world((ResourceKey) (Object) result).orElseThrow(() -> DimensionArgumentAccessor.accessor$ERROR_INVALID_VALUE().createWithContext(reader, result))));
});
}
use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.
the class CommandSourceStackMixin method impl$updateCauseOnWithWorld.
/*
* A note on why we're doing this with the cause manually.
*
* When the object is first constructed, we get the cause from the stack manager. However, as the command processor
* works through the nodes, this entire source may get replaced. We want to keep some of the changes in sync,
* but the original cause may have gone by the time the source changes. Really, this command source is the analogue
* of our Cause, NOT our CauseStackManager, so we just need to do `Cause.with(...)` along with their select `with*(...)`
* methods.
*/
@Inject(method = "withLevel", at = @At("RETURN"))
private void impl$updateCauseOnWithWorld(final ServerLevel serverWorld, final CallbackInfoReturnable<CommandSourceStack> cir) {
if (cir.getReturnValue() != (Object) this) {
final ServerLocation location = this.impl$cause.context().get(EventContextKeys.LOCATION).map(x -> ServerLocation.of((org.spongepowered.api.world.server.ServerWorld) serverWorld, x.position())).orElseGet(() -> ServerLocation.of((org.spongepowered.api.world.server.ServerWorld) serverWorld, VecHelper.toVector3d(cir.getReturnValue().getPosition())));
((CommandSourceStackBridge) cir.getReturnValue()).bridge$setCause(this.impl$applyToCause(EventContextKeys.LOCATION, location));
}
}
use of net.minecraft.commands.CommandSourceStack in project MinecraftForge by MinecraftForge.
the class ClientCommandTest method init.
private void init(RegisterClientCommandsEvent event) {
event.getDispatcher().register(Commands.literal("clientcommandtest").then(Commands.literal("rawsuggest").then(Commands.argument("block", ResourceLocationArgument.id()).suggests((c, b) -> SharedSuggestionProvider.suggestResource(ForgeRegistries.BLOCKS.getKeys(), b)).executes(this::testCommand))).then(Commands.literal("registeredsuggest").then(Commands.argument("block", ResourceLocationArgument.id()).suggests(SuggestionProviders.AVAILABLE_BIOMES).executes(this::testCommand))).then(Commands.literal("server").executes((context) -> {
context.getSource().getServer();
context.getSource().sendSuccess(new TextComponent("Successfully called getServer should have errored"), false);
return 1;
})).then(Commands.literal("level").executes((context) -> {
context.getSource().getLevel();
context.getSource().sendSuccess(new TextComponent("Successfully called getLevel should have errored"), false);
return 1;
})).then(Commands.literal("get_objective").then(Commands.argument("objective", ObjectiveArgument.objective()).executes((context) -> {
context.getSource().sendSuccess(new TextComponent("Regular: ").append(ObjectiveArgument.getObjective(context, "objective").getFormattedDisplayName()), false);
return 1;
}))).then(Commands.literal("get_advancement").then(Commands.argument("advancement", ResourceLocationArgument.id()).executes((context) -> {
context.getSource().sendSuccess(ResourceLocationArgument.getAdvancement(context, "advancement").getChatComponent(), false);
return 1;
}))).then(Commands.literal("get_recipe").then(Commands.argument("recipe", ResourceLocationArgument.id()).executes((context) -> {
context.getSource().sendSuccess(ResourceLocationArgument.getRecipe(context, "recipe").getResultItem().getDisplayName(), false);
return 1;
}))).then(Commands.literal("get_team").then(Commands.argument("team", TeamArgument.team()).executes((context) -> {
context.getSource().sendSuccess(TeamArgument.getTeam(context, "team").getFormattedDisplayName(), false);
return 1;
}))).then(Commands.literal("get_loaded_blockpos").then(Commands.argument("blockpos", BlockPosArgument.blockPos()).executes((context) -> {
context.getSource().sendSuccess(new TextComponent(BlockPosArgument.getLoadedBlockPos(context, "blockpos").toString()), false);
return 1;
}))).then(Commands.literal("requires").requires((source) -> false).executes((context) -> {
context.getSource().sendSuccess(new TextComponent("Executed command"), false);
return 1;
})));
// Used for testing that client command redirects can only be used with client commands
LiteralArgumentBuilder<CommandSourceStack> fork = Commands.literal("clientcommandfork");
fork.fork(event.getDispatcher().getRoot(), (context) -> List.of(context.getSource(), context.getSource())).executes((context) -> {
context.getSource().sendSuccess(new TextComponent("Executing forked command"), false);
return 1;
});
event.getDispatcher().register(fork);
}
Aggregations