Search in sources :

Example 1 with CommandSourceStack

use of net.minecraft.commands.CommandSourceStack in project MinecraftForge by MinecraftForge.

the class DimensionsCommand method register.

static ArgumentBuilder<CommandSourceStack, ?> register() {
    return Commands.literal("dimensions").requires(// permission
    cs -> cs.hasPermission(0)).executes(ctx -> {
        ctx.getSource().sendSuccess(new TranslatableComponent("commands.forge.dimensions.list"), true);
        final Registry<DimensionType> reg = ctx.getSource().registryAccess().registryOrThrow(Registry.DIMENSION_TYPE_REGISTRY);
        Map<ResourceLocation, List<ResourceLocation>> types = new HashMap<>();
        for (ServerLevel dim : ctx.getSource().getServer().getAllLevels()) {
            types.computeIfAbsent(reg.getKey(dim.dimensionType()), k -> new ArrayList<>()).add(dim.dimension().location());
        }
        types.keySet().stream().sorted().forEach(key -> {
            ctx.getSource().sendSuccess(new TextComponent(key + ": " + types.get(key).stream().map(ResourceLocation::toString).sorted().collect(Collectors.joining(", "))), false);
        });
        return 0;
    });
}
Also used : ResourceLocation(net.minecraft.resources.ResourceLocation) CommandSourceStack(net.minecraft.commands.CommandSourceStack) Commands(net.minecraft.commands.Commands) HashMap(java.util.HashMap) DimensionType(net.minecraft.world.level.dimension.DimensionType) ServerLevel(net.minecraft.server.level.ServerLevel) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Registry(net.minecraft.core.Registry) TextComponent(net.minecraft.network.chat.TextComponent) List(java.util.List) Map(java.util.Map) TranslatableComponent(net.minecraft.network.chat.TranslatableComponent) ArgumentBuilder(com.mojang.brigadier.builder.ArgumentBuilder) TextComponent(net.minecraft.network.chat.TextComponent) DimensionType(net.minecraft.world.level.dimension.DimensionType) ServerLevel(net.minecraft.server.level.ServerLevel) TranslatableComponent(net.minecraft.network.chat.TranslatableComponent) HashMap(java.util.HashMap) ResourceLocation(net.minecraft.resources.ResourceLocation) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with CommandSourceStack

use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.

the class SpongeCommandDispatcher method getCompletionSuggestions.

@Override
public CompletableFuture<Suggestions> getCompletionSuggestions(final ParseResults<CommandSourceStack> parse, final int cursor) {
    final CommandContextBuilder<CommandSourceStack> context = parse.getContext();
    // Sponge Start - redirect if this actually represents a non-Brig command
    final CommandContextBuilder<CommandSourceStack> child = context.getLastChild();
    if (child instanceof SpongeCommandContextBuilder) {
        final SpongeCommandContextBuilder spongeChild = (SpongeCommandContextBuilder) child;
        if (((SpongeCommandContextBuilder) child).representsNonBrigCommand()) {
            // special handling!
            final String rawCommand = parse.getReader().getString();
            final String[] command = spongeChild.nonBrigCommand();
            // we know this will exist.
            final CommandMapping mapping = this.commandManager.commandMapping(command[0]).get();
            return CommandUtil.createSuggestionsForRawCommand(rawCommand, spongeChild.nonBrigCommand(), spongeChild.cause(), mapping).buildFuture();
        }
    }
    // Sponge End
    final SuggestionContext<CommandSourceStack> nodeBeforeCursor = context.findSuggestionContext(cursor);
    final CommandNode<CommandSourceStack> parent = nodeBeforeCursor.parent;
    final int start = Math.min(nodeBeforeCursor.startPos, cursor);
    final String fullInput = parse.getReader().getString();
    final String truncatedInput = fullInput.substring(0, cursor);
    // Sponge Start: the collection might be different.
    final Collection<CommandNode<CommandSourceStack>> children;
    if (parent instanceof SpongeNode) {
        children = ((SpongeNode) parent).getChildrenForSuggestions();
    } else {
        children = parent.getChildren();
    }
    // @SuppressWarnings("unchecked") final CompletableFuture<Suggestions>[] futures = new CompletableFuture[parent.getChildren().size()];
    @SuppressWarnings("unchecked") final CompletableFuture<Suggestions>[] futures = new CompletableFuture[children.size()];
    // Sponge End
    int i = 0;
    for (final CommandNode<CommandSourceStack> node : children) {
        // Sponge: parent.getChildren() -> children
        CompletableFuture<Suggestions> future = Suggestions.empty();
        try {
            future = node.listSuggestions(context.build(truncatedInput), new SuggestionsBuilder(truncatedInput, start));
        } catch (final CommandSyntaxException ignored) {
        }
        futures[i++] = future;
    }
    // See https://github.com/Mojang/brigadier/pull/81
    return CompletableFuture.allOf(futures).handle((voidResult, exception) -> {
        final List<Suggestions> suggestions = new ArrayList<>();
        for (final CompletableFuture<Suggestions> future : futures) {
            if (!future.isCompletedExceptionally()) {
                suggestions.add(future.join());
            }
        }
        return Suggestions.merge(fullInput, suggestions);
    });
// Sponge End
}
Also used : LiteralCommandNode(com.mojang.brigadier.tree.LiteralCommandNode) DummyCommandNode(org.spongepowered.common.command.brigadier.tree.DummyCommandNode) SpongeRootCommandNode(org.spongepowered.common.command.brigadier.tree.SpongeRootCommandNode) RootCommandNode(com.mojang.brigadier.tree.RootCommandNode) SpongeArgumentCommandNode(org.spongepowered.common.command.brigadier.tree.SpongeArgumentCommandNode) CommandNode(com.mojang.brigadier.tree.CommandNode) ArrayList(java.util.ArrayList) CommandSourceStack(net.minecraft.commands.CommandSourceStack) SpongeCommandContextBuilder(org.spongepowered.common.command.brigadier.context.SpongeCommandContextBuilder) Suggestions(com.mojang.brigadier.suggestion.Suggestions) CompletableFuture(java.util.concurrent.CompletableFuture) CommandMapping(org.spongepowered.api.command.manager.CommandMapping) SpongeNode(org.spongepowered.common.command.brigadier.tree.SpongeNode) SuggestionsBuilder(com.mojang.brigadier.suggestion.SuggestionsBuilder) SpongeCommandSyntaxException(org.spongepowered.common.command.exception.SpongeCommandSyntaxException) CommandSyntaxException(com.mojang.brigadier.exceptions.CommandSyntaxException)

Example 3 with CommandSourceStack

use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.

the class SpongeCommandContextBuilder method findSuggestionContext.

@Override
public SuggestionContext<CommandSourceStack> findSuggestionContext(final int cursor) {
    if (this.transaction != null && !this.transaction.isEmpty()) {
        return this.transaction.peek().getCopyBuilder().findSuggestionContext(cursor);
    }
    // where appropriate. There is one change marked below.
    if (this.getRange().getStart() <= cursor) {
        if (this.getRange().getEnd() < cursor) {
            if (this.getChild() != null) {
                return this.getChild().findSuggestionContext(cursor);
            } else if (!this.getNodes().isEmpty()) {
                final ParsedCommandNode<CommandSourceStack> last = this.getNodes().get(this.getNodes().size() - 1);
                return new SuggestionContext<>(last.getNode(), last.getRange().getEnd() + 1);
            } else {
                return new SuggestionContext<>(this.getRootNode(), this.getRange().getStart());
            }
        } else {
            CommandNode<CommandSourceStack> prev = this.getRootNode();
            for (final ParsedCommandNode<CommandSourceStack> node : this.getNodes()) {
                final StringRange nodeRange = node.getRange();
                // Sponge Start
                if (SpongeCommandContextBuilder.checkNodeCannotBeEmpty(node.getNode(), nodeRange)) {
                    // Sponge End
                    if (nodeRange.getStart() <= cursor && cursor <= nodeRange.getEnd()) {
                        return new SuggestionContext<>(prev, nodeRange.getStart());
                    }
                // Sponge Start: End if
                }
                // Sponge End
                prev = node.getNode();
            }
            if (prev == null) {
                throw new IllegalStateException("Can't find node before cursor");
            }
            return new SuggestionContext<>(prev, this.getRange().getStart());
        }
    }
    throw new IllegalStateException("Can't find node before cursor");
}
Also used : SuggestionContext(com.mojang.brigadier.context.SuggestionContext) ParsedCommandNode(com.mojang.brigadier.context.ParsedCommandNode) CommandSourceStack(net.minecraft.commands.CommandSourceStack) StringRange(com.mojang.brigadier.context.StringRange)

Example 4 with CommandSourceStack

use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.

the class SpongeParameterTranslator method createFlags.

@SuppressWarnings({ "unchecked", "rawtypes" })
private void createFlags(final LiteralCommandNode<CommandSourceStack> node, final List<Flag> flags, @Nullable final SpongeCommandExecutorWrapper wrapper) {
    final Collection<CommandNode<CommandSourceStack>> nodesToAddChildrenTo = new ArrayList<>();
    for (final Flag flag : flags) {
        // first create the literal.
        final Iterator<String> aliasIterator = flag.aliases().iterator();
        final LiteralArgumentBuilder<CommandSourceStack> flagLiteral = LiteralArgumentBuilder.literal(aliasIterator.next());
        flagLiteral.requires((Predicate) flag.requirement());
        final Collection<? extends CommandNode<CommandSourceStack>> toBeRedirected;
        final SpongeFlagLiteralCommandNode flagNode = new SpongeFlagLiteralCommandNode(flagLiteral, flag);
        if (flag.associatedParameter().isPresent()) {
            toBeRedirected = this.createAndAttachNode(Collections.singleton(flagNode), Collections.singletonList(flag.associatedParameter().get()), wrapper, node.getCommand() != null, false);
        } else {
            toBeRedirected = Collections.singletonList(flagNode);
        }
        for (final CommandNode<CommandSourceStack> candidate : toBeRedirected) {
            if (candidate instanceof SpongeNode && ((SpongeNode) candidate).canForceRedirect()) {
                ((SpongeNode) candidate).forceRedirect(node);
            } else {
                nodesToAddChildrenTo.add(candidate);
            }
        }
        node.addChild(flagNode);
        while (aliasIterator.hasNext()) {
            final LiteralArgumentBuilder<CommandSourceStack> nextFlag = LiteralArgumentBuilder.<CommandSourceStack>literal(aliasIterator.next()).executes(flagNode.getCommand());
            if (flagNode.getRedirect() != null) {
                nextFlag.redirect(flagNode.getRedirect());
            } else {
                nextFlag.redirect(flagNode);
            }
            node.addChild(new SpongeFlagLiteralCommandNode(nextFlag, flag));
        }
    }
    if (!nodesToAddChildrenTo.isEmpty()) {
        for (final CommandNode<CommandSourceStack> target : node.getChildren()) {
            if (!target.getChildren().isEmpty() && target instanceof SpongeFlagLiteralCommandNode) {
                nodesToAddChildrenTo.forEach(x -> x.addChild(((SpongeFlagLiteralCommandNode) target).cloneWithRedirectToThis()));
            } else {
                nodesToAddChildrenTo.forEach(x -> x.addChild(target));
            }
        }
    }
}
Also used : LiteralCommandNode(com.mojang.brigadier.tree.LiteralCommandNode) SpongeFlagLiteralCommandNode(org.spongepowered.common.command.brigadier.tree.SpongeFlagLiteralCommandNode) SpongeLiteralCommandNode(org.spongepowered.common.command.brigadier.tree.SpongeLiteralCommandNode) CommandNode(com.mojang.brigadier.tree.CommandNode) SpongeFlagLiteralCommandNode(org.spongepowered.common.command.brigadier.tree.SpongeFlagLiteralCommandNode) ArrayList(java.util.ArrayList) SpongeNode(org.spongepowered.common.command.brigadier.tree.SpongeNode) Flag(org.spongepowered.api.command.parameter.managed.Flag) CommandSourceStack(net.minecraft.commands.CommandSourceStack)

Example 5 with CommandSourceStack

use of net.minecraft.commands.CommandSourceStack in project SpongeCommon by SpongePowered.

the class DifficultyCommandMixin method setDifficulty.

// @formatter:on
/**
 * @author Zidane
 * @reason Only apply difficulty for the world the command was ran in (as in Sponge, all worlds have difficulties)
 */
@Overwrite
public static int setDifficulty(CommandSourceStack source, Difficulty difficulty) throws CommandSyntaxException {
    if (source.getLevel().getDifficulty() == difficulty) {
        throw DifficultyCommandMixin.ERROR_ALREADY_DIFFICULT.create(difficulty.getKey());
    } else {
        final LevelData levelData = source.getLevel().getLevelData();
        ((ServerWorldProperties) levelData).setDifficulty((org.spongepowered.api.world.difficulty.Difficulty) (Object) difficulty);
        source.getLevel().setSpawnSettings(((MinecraftServerAccessor) SpongeCommon.server()).invoker$isSpawningMonsters(), SpongeCommon.server().isSpawningAnimals());
        source.getLevel().getPlayers(p -> true).forEach(p -> p.connection.send(new ClientboundChangeDifficultyPacket(levelData.getDifficulty(), levelData.isDifficultyLocked())));
        source.sendSuccess(new TranslatableComponent("commands.difficulty.success", difficulty.getDisplayName()), true);
        return 0;
    }
}
Also used : CommandSourceStack(net.minecraft.commands.CommandSourceStack) MinecraftServerAccessor(org.spongepowered.common.accessor.server.MinecraftServerAccessor) Overwrite(org.spongepowered.asm.mixin.Overwrite) SpongeCommon(org.spongepowered.common.SpongeCommon) Final(org.spongepowered.asm.mixin.Final) ServerWorldProperties(org.spongepowered.api.world.server.storage.ServerWorldProperties) LevelData(net.minecraft.world.level.storage.LevelData) Mixin(org.spongepowered.asm.mixin.Mixin) DynamicCommandExceptionType(com.mojang.brigadier.exceptions.DynamicCommandExceptionType) Shadow(org.spongepowered.asm.mixin.Shadow) ClientboundChangeDifficultyPacket(net.minecraft.network.protocol.game.ClientboundChangeDifficultyPacket) DifficultyCommand(net.minecraft.server.commands.DifficultyCommand) CommandSyntaxException(com.mojang.brigadier.exceptions.CommandSyntaxException) Difficulty(net.minecraft.world.Difficulty) TranslatableComponent(net.minecraft.network.chat.TranslatableComponent) ServerWorldProperties(org.spongepowered.api.world.server.storage.ServerWorldProperties) TranslatableComponent(net.minecraft.network.chat.TranslatableComponent) ClientboundChangeDifficultyPacket(net.minecraft.network.protocol.game.ClientboundChangeDifficultyPacket) LevelData(net.minecraft.world.level.storage.LevelData) Overwrite(org.spongepowered.asm.mixin.Overwrite)

Aggregations

CommandSourceStack (net.minecraft.commands.CommandSourceStack)22 CommandNode (com.mojang.brigadier.tree.CommandNode)6 ArrayList (java.util.ArrayList)6 CommandSyntaxException (com.mojang.brigadier.exceptions.CommandSyntaxException)5 LiteralCommandNode (com.mojang.brigadier.tree.LiteralCommandNode)5 Map (java.util.Map)5 TextComponent (net.minecraft.network.chat.TextComponent)5 Suggestions (com.mojang.brigadier.suggestion.Suggestions)4 HashMap (java.util.HashMap)4 List (java.util.List)4 ServerLevel (net.minecraft.server.level.ServerLevel)4 ResultConsumer (com.mojang.brigadier.ResultConsumer)3 StringReader (com.mojang.brigadier.StringReader)3 CommandContext (com.mojang.brigadier.context.CommandContext)3 Collectors (java.util.stream.Collectors)3 CommandSource (net.minecraft.commands.CommandSource)3 Component (net.minecraft.network.chat.Component)3 Vec2 (net.minecraft.world.phys.Vec2)3 CauseStackManager (org.spongepowered.api.event.CauseStackManager)3 EventContextKeys (org.spongepowered.api.event.EventContextKeys)3