use of org.spongepowered.api.command.spec.CommandSpec in project SpongeCommon by SpongePowered.
the class SpongePaginationService method buildPaginationCommand.
private CommandSpec buildPaginationCommand() {
final ActivePaginationCommandElement paginationElement = new ActivePaginationCommandElement(t("pagination-id"));
CommandSpec next = CommandSpec.builder().description(t("Go to the next page")).executor((src, args) -> {
args.<ActivePagination>getOne("pagination-id").get().nextPage();
return CommandResult.success();
}).build();
CommandSpec prev = CommandSpec.builder().description(t("Go to the previous page")).executor((src, args) -> {
args.<ActivePagination>getOne("pagination-id").get().previousPage();
return CommandResult.success();
}).build();
CommandElement pageArgs = integer(t("page"));
CommandExecutor pageExecutor = (src, args) -> {
args.<ActivePagination>getOne("pagination-id").get().specificPage(args.<Integer>getOne("page").get());
return CommandResult.success();
};
CommandSpec page = CommandSpec.builder().description(t("Go to a specific page")).arguments(pageArgs).executor(pageExecutor).build();
// Fallback to page arguments
ChildCommandElementExecutor childDispatcher = new ChildCommandElementExecutor(pageExecutor);
childDispatcher.register(next, "next", "n");
childDispatcher.register(prev, "prev", "p", "previous");
childDispatcher.register(page, "page");
// https://github.com/SpongePowered/SpongeAPI/issues/1272
return CommandSpec.builder().arguments(paginationElement, firstParsing(childDispatcher, pageArgs)).executor(childDispatcher).description(t("Helper command for paginations occurring")).build();
}
use of org.spongepowered.api.command.spec.CommandSpec in project SpongeCommon by SpongePowered.
the class CooldownTrackerTest method onInit.
@Listener
public void onInit(GameInitializationEvent event) {
final CommandSpec test = CommandSpec.builder().executor((src, args) -> {
if (!(src instanceof Player)) {
throw new CommandException(Text.of(TextColors.RED, "You must be a player to execute this command!"));
}
final Player player = (Player) src;
final CooldownTracker cooldownTracker = player.getCooldownTracker();
final ItemType itemType = player.getItemInHand(HandTypes.MAIN_HAND).orElse(ItemStack.empty()).getType();
if (!cooldownTracker.hasCooldown(itemType)) {
player.sendMessage(Text.of(TextColors.GRAY, "The item type in your hand is not on cooldown!"));
} else {
player.sendMessage(Text.of(TextColors.GRAY, "The cooldown remaining for the item type in your hand is ", TextColors.GOLD, cooldownTracker.getCooldown(itemType).orElse(0), TextColors.GRAY, " tick(s)."));
player.sendMessage(Text.of(TextColors.GRAY, "This item type has ", TextColors.GOLD, new DecimalFormat("#.00").format(cooldownTracker.getFractionRemaining(itemType).orElse(0.0) * 100) + "%", TextColors.GRAY, " of its cooldown remaining."));
}
return CommandResult.success();
}).build();
final CommandSpec set = CommandSpec.builder().executor((src, args) -> {
if (!(src instanceof Player)) {
throw new CommandException(Text.of(TextColors.RED, "You must be a player to execute this command!"));
}
final Player player = (Player) src;
final int cooldown = args.<Integer>getOne("cooldown").orElse(10);
player.getCooldownTracker().setCooldown(player.getItemInHand(HandTypes.MAIN_HAND).orElse(ItemStack.empty()).getType(), cooldown);
player.sendMessage(Text.of(TextColors.GRAY, "You have given the item type in your hand a cooldown of ", TextColors.GOLD, cooldown, TextColors.GRAY, " tick(s)."));
return CommandResult.success();
}).arguments(GenericArguments.integer(Text.of("cooldown"))).build();
final CommandSpec enable = CommandSpec.builder().executor(((src, args) -> {
if (!(src instanceof Player)) {
throw new CommandException(Text.of(TextColors.RED, "You must be a player to execute this command!"));
}
final Player player = (Player) src;
if (!this.enabled.remove(player.getUniqueId())) {
this.enabled.add(player.getUniqueId());
src.sendMessage(Text.of(TextColors.GOLD, "You have enabled the cooldown listeners!"));
} else {
src.sendMessage(Text.of(TextColors.GOLD, "You have disabled the cooldown listeners!"));
}
return CommandResult.success();
})).build();
Sponge.getCommandManager().register(this, CommandSpec.builder().executor(((src, args) -> {
src.sendMessage(Text.of(TextColors.GOLD, "Use cooldown set|test|enable"));
return CommandResult.success();
})).child(test, "test").child(set, "set").child(enable, "enable", "disable").build(), "cooldowns");
}
use of org.spongepowered.api.command.spec.CommandSpec in project SpongeCommon by SpongePowered.
the class InventoryQueryTest method onInitialization.
@Listener
public void onInitialization(GameInitializationEvent e) {
CommandSpec inventoryType = CommandSpec.builder().executor((src, args) -> {
Inventory inventory = getPlayerInventory(src);
Inventory hotbar = inventory.query(QueryOperationTypes.INVENTORY_TYPE.of(Hotbar.class));
src.sendMessage(Text.of("You have ", hotbar.totalItems(), " items in your hotbar."));
return CommandResult.success();
}).build();
CommandSpec itemType = CommandSpec.builder().executor((src, args) -> {
Inventory inventory = getPlayerInventory(src);
Inventory sticks = inventory.query(QueryOperationTypes.ITEM_TYPE.of(ItemTypes.STICK));
src.sendMessage(Text.of("You have ", sticks.totalItems(), " sticks in your inventory."));
return CommandResult.success();
}).build();
CommandSpec itemStackGeneral = CommandSpec.builder().executor((src, args) -> {
Inventory inventory = getPlayerInventory(src);
ItemStack lapis = ItemStack.of(ItemTypes.DYE, 4);
lapis.offer(Keys.DYE_COLOR, DyeColors.BLUE);
Inventory lapisItems = inventory.query(QueryOperationTypes.ITEM_STACK_IGNORE_QUANTITY.of(lapis));
src.sendMessage(Text.of("You have ", lapisItems.totalItems(), " lapis lazuli in your inventory."));
return CommandResult.success();
}).build();
CommandSpec itemStackSpecific = CommandSpec.builder().executor((src, args) -> {
Inventory inventory = getPlayerInventory(src);
ItemStack lapis = ItemStack.of(ItemTypes.DYE, 4);
lapis.offer(Keys.DYE_COLOR, DyeColors.BLUE);
Inventory lapisItems = inventory.query(QueryOperationTypes.ITEM_STACK_EXACT.of(lapis));
src.sendMessage(Text.of("You have ", lapisItems.size(), " stacks of 4 lapis lazuli in your inventory."));
return CommandResult.success();
}).build();
CommandSpec itemStackCustom = CommandSpec.builder().executor((src, args) -> {
Inventory inventory = getPlayerInventory(src);
Inventory evenCountStacks = inventory.query(QueryOperationTypes.ITEM_STACK_CUSTOM.of(x -> x.getQuantity() > 0 && x.getQuantity() % 2 == 0));
src.sendMessage(Text.of("You have ", evenCountStacks.size(), " stacks with an even number of items in your inventory."));
return CommandResult.success();
}).build();
CommandSpec inventoryProperty = CommandSpec.builder().executor((src, args) -> {
Inventory inventory = getPlayerInventory(src);
Inventory slots = ((PlayerInventory) inventory).getHotbar().query(QueryOperationTypes.INVENTORY_PROPERTY.of(new SlotIndex(3, Property.Operator.LESS)));
src.sendMessage(Text.of("You have ", slots.totalItems(), " items in the first 3 slots of your hotbar."));
return CommandResult.success();
}).build();
CommandSpec inventoryTranslation = CommandSpec.builder().executor((src, args) -> {
Inventory inventory = getPlayerInventory(src);
Inventory slots = ((PlayerInventory) inventory).getHotbar().query(QueryOperationTypes.INVENTORY_TRANSLATION.of(Sponge.getRegistry().getTranslationById("slot.name").get()));
src.sendMessage(Text.of("You have ", slots.totalItems(), " items in your hotbar."));
return CommandResult.success();
}).build();
Sponge.getCommandManager().register(this, CommandSpec.builder().child(inventoryType, "inventorytype").child(itemType, "itemtype").child(itemStackGeneral, "itemstackgeneral").child(itemStackSpecific, "itemstackspecific").child(itemStackCustom, "itemstackcustom").child(inventoryProperty, "inventoryproperty").child(inventoryTranslation, "inventorytranslation").build(), "invquery");
}
use of org.spongepowered.api.command.spec.CommandSpec in project SpongeCommon by SpongePowered.
the class SpongeCommandFactory method createSpongePluginsCommand.
private static CommandSpec createSpongePluginsCommand() {
return CommandSpec.builder().description(Text.of("List currently installed plugins")).permission("sponge.command.plugins").arguments(optionalWeak(literal(Text.of("reload"), "reload")), optional(plugin(Text.of("plugin")))).executor((src, args) -> {
if (args.hasAny("reload") && src.hasPermission("sponge.command.plugins.reload")) {
src.sendMessage(Text.of("Sending reload event to all plugins. Please wait."));
Sponge.getCauseStackManager().pushCause(src);
SpongeImpl.postEvent(SpongeEventFactory.createGameReloadEvent(Sponge.getCauseStackManager().getCurrentCause()));
Sponge.getCauseStackManager().popCause();
src.sendMessage(Text.of("Reload complete!"));
} else if (args.hasAny("plugin")) {
sendContainerMeta(src, args, "plugin");
} else {
final Collection<PluginContainer> containers = SpongeImpl.getGame().getPluginManager().getPlugins();
final List<PluginContainer> sortedContainers = new ArrayList<>();
// Add static listings first
CONTAINER_LIST_STATICS.forEach(containerId -> containers.stream().filter(container -> container.getId().equalsIgnoreCase(containerId)).findFirst().ifPresent(sortedContainers::add));
containers.stream().filter(SpongeImplHooks.getPluginFilterPredicate()).sorted(Comparator.comparing(PluginContainer::getName)).forEachOrdered(sortedContainers::add);
if (src instanceof Player) {
final List<Text> containerList = new ArrayList<>();
final PaginationList.Builder builder = PaginationList.builder();
builder.title(Text.of(TextColors.YELLOW, "Plugins", TextColors.WHITE, " (", sortedContainers.size(), ")")).padding(Text.of(TextColors.DARK_GREEN, "="));
for (PluginContainer container : sortedContainers) {
final Text.Builder containerBuilder = Text.builder().append(Text.of(TextColors.RESET, " - ", TextColors.GREEN, container.getName())).onClick(TextActions.runCommand("/sponge:sponge plugins " + container.getId())).onHover(TextActions.showText(Text.of(TextColors.RESET, "ID: ", container.getId(), Text.NEW_LINE, "Version: ", container.getVersion().orElse("Unknown"))));
containerList.add(containerBuilder.build());
}
builder.contents(containerList).build().sendTo(src);
} else {
final Text.Builder builder = Text.builder();
builder.append(Text.of(TextColors.YELLOW, "Plugins", TextColors.WHITE, " (", sortedContainers.size(), "): "));
boolean first = true;
for (PluginContainer container : sortedContainers) {
if (!first) {
builder.append(SEPARATOR_TEXT);
}
first = false;
builder.append(Text.of(TextColors.GREEN, container.getName()));
}
src.sendMessage(builder.build());
}
}
return CommandResult.success();
}).build();
}
use of org.spongepowered.api.command.spec.CommandSpec in project SpongeCommon by SpongePowered.
the class SpongeCommandFactory method createSpongeChunksCommand.
// Flag children
private static CommandSpec createSpongeChunksCommand() {
return CommandSpec.builder().description(Text.of("Print chunk information, optionally dump")).arguments(optional(seq(literal(Text.of("dump"), "dump"), optional(literal(Text.of("dump-all"), "all"))))).permission("sponge.command.chunks").executor(new ConfigUsingExecutor(true) {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
CommandResult res = super.execute(src, args);
if (args.hasAny("dump")) {
File file = new File(new File(new File("."), "chunk-dumps"), "chunk-info-" + DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss").format(Instant.now()) + "-server.txt");
src.sendMessage(Text.of("Writing chunk info to: ", file));
ChunkSaveHelper.writeChunks(file, args.hasAny("dump-all"));
src.sendMessage(Text.of("Chunk info complete"));
}
return res;
}
@Override
protected Text processGlobal(SpongeConfig<GlobalConfig> config, CommandSource source, CommandContext args) throws CommandException {
for (World world : SpongeImpl.getGame().getServer().getWorlds()) {
source.sendMessage(Text.of("World ", Text.of(TextStyles.BOLD, world.getName()), getChunksInfo(((WorldServer) world))));
}
return Text.of("Printed chunk info for all worlds ");
}
@Override
protected Text processDimension(SpongeConfig<DimensionConfig> config, DimensionType dim, CommandSource source, CommandContext args) throws CommandException {
SpongeImpl.getGame().getServer().getWorlds().stream().filter(world -> world.getDimension().getType().equals(dim)).forEach(world -> source.sendMessage(Text.of("World ", Text.of(TextStyles.BOLD, world.getName()), getChunksInfo(((WorldServer) world)))));
return Text.of("Printed chunk info for all worlds in dimension ", dim.getName());
}
@Override
protected Text processWorld(SpongeConfig<WorldConfig> config, World world, CommandSource source, CommandContext args) throws CommandException {
return getChunksInfo((WorldServer) world);
}
protected Text key(Object text) {
return Text.of(TextColors.GOLD, text);
}
protected Text value(Object text) {
return Text.of(TextColors.GRAY, text);
}
protected Text getChunksInfo(WorldServer worldserver) {
return Text.of(NEWLINE_TEXT, key("DimensionId: "), value(WorldManager.getDimensionId(worldserver)), NEWLINE_TEXT, key("Loaded chunks: "), value(worldserver.getChunkProvider().getLoadedChunkCount()), NEWLINE_TEXT, key("Active chunks: "), value(worldserver.getChunkProvider().getLoadedChunks().size()), NEWLINE_TEXT, key("Entities: "), value(worldserver.loadedEntityList.size()), NEWLINE_TEXT, key("Tile Entities: "), value(worldserver.loadedTileEntityList.size()), NEWLINE_TEXT, key("Removed Entities:"), value(worldserver.unloadedEntityList.size()), NEWLINE_TEXT, key("Removed Tile Entities: "), value(worldserver.tileEntitiesToBeRemoved), NEWLINE_TEXT);
}
}).build();
}
Aggregations