Search in sources :

Example 6 with TextComponent

use of com.sk89q.worldedit.util.formatting.text.TextComponent in project FastAsyncWorldEdit by IntellectualSites.

the class InspectBrush method perform.

public boolean perform(final Player player, LocalSession session, boolean rightClick) {
    if (!player.hasPermission("worldedit.tool.inspect")) {
        player.print(Caption.of("fawe.error.no-perm", "worldedit.tool.inspect"));
        return false;
    }
    if (!Settings.settings().HISTORY.USE_DATABASE) {
        player.print(Caption.of("fawe.error.setting.disable", "history.use-database (Import with /history import )"));
        return false;
    }
    try {
        BlockVector3 target = getTarget(player, rightClick).toBlockPoint();
        final int x = target.getBlockX();
        final int y = target.getBlockY();
        final int z = target.getBlockZ();
        World world = player.getWorld();
        RollbackDatabase db = DBHandler.dbHandler().getDatabase(world);
        int count = 0;
        for (Supplier<RollbackOptimizedHistory> supplier : db.getEdits(target, false)) {
            count++;
            RollbackOptimizedHistory edit = supplier.get();
            Iterator<MutableFullBlockChange> iter = edit.getFullBlockIterator(null, 0, false);
            while (iter.hasNext()) {
                MutableFullBlockChange change = iter.next();
                if (change.x != x || change.y != y || change.z != z) {
                    continue;
                }
                int from = change.from;
                int to = change.to;
                UUID uuid = edit.getUUID();
                String name = Fawe.platform().getName(uuid);
                int index = edit.getIndex();
                long age = System.currentTimeMillis() - edit.getBDFile().lastModified();
                String ageFormatted = MainUtil.secToTime(age / 1000);
                BlockState blockFrom = BlockState.getFromOrdinal(from);
                BlockState blockTo = BlockState.getFromOrdinal(to);
                TranslatableComponent msg = Caption.of("fawe.worldedit.tool.tool.inspect.info", name, blockFrom, blockTo, ageFormatted);
                TextComponent hover = TextComponent.of("/tool inspect", TextColor.GOLD);
                String infoCmd = "//history summary " + uuid + " " + index;
                msg = msg.hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, hover));
                msg = msg.clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, infoCmd));
                player.print(msg);
            }
        }
        player.print(Caption.of("fawe.worldedit.tool.tool.inspect.info.footer", count));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return true;
}
Also used : TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) IOException(java.io.IOException) BlockVector3(com.sk89q.worldedit.math.BlockVector3) World(com.sk89q.worldedit.world.World) RollbackOptimizedHistory(com.fastasyncworldedit.core.history.RollbackOptimizedHistory) BlockState(com.sk89q.worldedit.world.block.BlockState) TranslatableComponent(com.sk89q.worldedit.util.formatting.text.TranslatableComponent) MutableFullBlockChange(com.fastasyncworldedit.core.history.change.MutableFullBlockChange) UUID(java.util.UUID) RollbackDatabase(com.fastasyncworldedit.core.database.RollbackDatabase)

Example 7 with TextComponent

use of com.sk89q.worldedit.util.formatting.text.TextComponent in project FastAsyncWorldEdit by IntellectualSites.

the class SchematicCommands method list.

@Command(name = "list", aliases = { "all", "ls" }, desc = "List saved schematics", descFooter = "Note: Format is not fully verified until loading.")
@CommandPermissions("worldedit.schematic.list")
public void list(Actor actor, LocalSession session, @ArgFlag(name = 'p', desc = "Page to view.", def = "1") int page, @Switch(name = 'd', desc = "Sort by date, oldest first") boolean oldFirst, @Switch(name = 'n', desc = "Sort by date, newest first") boolean newFirst, @ArgFlag(name = 'f', desc = "Restricts by format.", def = "") String formatName, @Arg(name = "filter", desc = "Filter for schematics", def = "all") String filter, Arguments arguments) throws WorldEditException {
    if (oldFirst && newFirst) {
        throw new StopExecutionException(Caption.of("worldedit.schematic.sorting-old-new"));
    }
    // FAWE start
    String pageCommand = "/" + arguments.get();
    LocalConfiguration config = worldEdit.getConfiguration();
    File dir = worldEdit.getWorkingDirectoryPath(config.saveDir).toFile();
    String schemCmd = "//schematic";
    String loadSingle = schemCmd + " load";
    String loadMulti = schemCmd + " loadall";
    String unload = schemCmd + " unload";
    String delete = schemCmd + " delete";
    String list = schemCmd + " list";
    String showCmd = schemCmd + " show";
    List<String> args = filter.isEmpty() ? Collections.emptyList() : Arrays.asList(filter.split(" "));
    URIClipboardHolder multi = as(URIClipboardHolder.class, session.getExistingClipboard());
    final boolean hasShow = false;
    // If player forgot -p argument
    boolean playerFolder = Settings.settings().PATHS.PER_PLAYER_SCHEMATICS;
    UUID uuid = playerFolder ? actor.getUniqueId() : null;
    List<File> files = UtilityCommands.getFiles(dir, actor, args, formatName, playerFolder, oldFirst, newFirst);
    List<Map.Entry<URI, String>> entries = UtilityCommands.filesToEntry(dir, files, uuid);
    Function<URI, Boolean> isLoaded = multi == null ? f -> false : multi::contains;
    List<Component> components = UtilityCommands.entryToComponent(dir, entries, isLoaded, (name, path, type, loaded) -> {
        TextComponentProducer msg = new TextComponentProducer();
        msg.append(Caption.of("worldedit.schematic.dash.symbol"));
        if (loaded) {
            msg.append(Caption.of("worldedit.schematic.minus.symbol").clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, unload + " " + path)).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.unload"))));
        } else {
            msg.append(Caption.of("worldedit.schematic.plus.symbol").clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, loadMulti + " " + path)).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.clipboard"))));
        }
        if (type != UtilityCommands.URIType.DIRECTORY) {
            msg.append(Caption.of("worldedit.schematic.x.symbol").clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, delete + " " + path)).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.delete"))));
        } else if (hasShow) {
            msg.append(Caption.of("worldedit.schematic.0.symbol").clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, showCmd + " " + path)).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.visualize"))));
        }
        TextComponent msgElem = TextComponent.of(name);
        if (type != UtilityCommands.URIType.DIRECTORY) {
            msgElem = msgElem.clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, loadSingle + " " + path));
            msgElem = msgElem.hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.load")));
        } else {
            msgElem = msgElem.clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, list + " " + path));
            msgElem = msgElem.hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.list")));
        }
        msg.append(msgElem);
        if (type == UtilityCommands.URIType.FILE) {
            long filesize = 0;
            try {
                filesize = Files.size(Paths.get(dir.getAbsolutePath() + File.separator + (playerFolder ? (uuid.toString() + File.separator) : "") + path));
            } catch (IOException e) {
                e.printStackTrace();
            }
            TextComponent sizeElem = TextComponent.of(String.format(" (%.1f kb)", filesize / 1000.0), TextColor.GRAY);
            msg.append(sizeElem);
        }
        return msg.create();
    });
    long totalBytes = 0;
    File parentDir = new File(dir.getAbsolutePath() + (playerFolder ? File.separator + uuid.toString() : ""));
    try {
        List<File> toAddUp = getFiles(parentDir, null, null);
        if (toAddUp != null && toAddUp.size() != 0) {
            for (File schem : toAddUp) {
                if (schem.getName().endsWith(".schem") || schem.getName().endsWith(".schematic")) {
                    totalBytes += Files.size(Paths.get(schem.getAbsolutePath()));
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    String headerBytesElem = String.format("%.1fkb", totalBytes / 1000.0);
    if (Settings.settings().PATHS.PER_PLAYER_SCHEMATICS && Settings.settings().EXPERIMENTAL.PER_PLAYER_FILE_SIZE_LIMIT > -1) {
        headerBytesElem += String.format(" / %dkb", Settings.settings().EXPERIMENTAL.PER_PLAYER_FILE_SIZE_LIMIT);
    }
    if (Settings.settings().PATHS.PER_PLAYER_SCHEMATICS) {
        String fullHeader = "| My Schematics: " + headerBytesElem + " |";
        PaginationBox paginationBox = PaginationBox.fromComponents(fullHeader, pageCommand, components);
        actor.print(paginationBox.create(page));
    } else {
        String fullHeader = "| Schematics: " + headerBytesElem + " |";
        PaginationBox paginationBox = PaginationBox.fromComponents(fullHeader, pageCommand, components);
        actor.print(paginationBox.create(page));
    }
// FAWE end
}
Also used : TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) TextComponentProducer(com.sk89q.worldedit.util.formatting.component.TextComponentProducer) IOException(java.io.IOException) LocalConfiguration(com.sk89q.worldedit.LocalConfiguration) URI(java.net.URI) URIClipboardHolder(com.fastasyncworldedit.core.extent.clipboard.URIClipboardHolder) StopExecutionException(org.enginehub.piston.exception.StopExecutionException) UUID(java.util.UUID) Component(com.sk89q.worldedit.util.formatting.text.Component) TranslatableComponent(com.sk89q.worldedit.util.formatting.text.TranslatableComponent) TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) PaginationBox(com.sk89q.worldedit.util.formatting.component.PaginationBox) File(java.io.File) Command(org.enginehub.piston.annotation.Command) CommandPermissions(com.sk89q.worldedit.command.util.CommandPermissions)

Example 8 with TextComponent

use of com.sk89q.worldedit.util.formatting.text.TextComponent in project FastAsyncWorldEdit by IntellectualSites.

the class PaginationBox method create.

public Component create(int page) throws InvalidComponentException {
    if (page == 1 && getComponentsSize() == 0) {
        return getContents().reset().append("No results found.").create();
    }
    int pageCount = (int) Math.ceil(getComponentsSize() / (double) componentsPerPage);
    if (page < 1 || page > pageCount) {
        throw new InvalidComponentException(Caption.of("worldedit.error.invalid-page"));
    }
    currentPage = page;
    final int lastComp = Math.min(page * componentsPerPage, getComponentsSize());
    for (int i = (page - 1) * componentsPerPage; i < lastComp; i++) {
        getContents().append(getComponent(i));
        if (i + 1 != lastComp) {
            getContents().newline();
        }
    }
    if (pageCount == 1) {
        return super.create();
    }
    getContents().newline();
    TextComponent pageNumberComponent = TextComponent.of("Page ", TextColor.YELLOW).append(TextComponent.of(String.valueOf(page), TextColor.GOLD)).append(TextComponent.of(" of ")).append(TextComponent.of(String.valueOf(pageCount), TextColor.GOLD));
    if (pageCommand != null) {
        TextComponentProducer navProducer = new TextComponentProducer();
        if (page > 1) {
            TextComponent prevComponent = TextComponent.of("<<< ", TextColor.GOLD).clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, pageCommand.replace("%page%", String.valueOf(page - 1)))).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("Click to navigate")));
            navProducer.append(prevComponent);
        }
        navProducer.append(pageNumberComponent);
        if (page < pageCount) {
            TextComponent nextComponent = TextComponent.of(" >>>", TextColor.GOLD).clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, pageCommand.replace("%page%", String.valueOf(page + 1)))).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("Click to navigate")));
            navProducer.append(nextComponent);
        }
        getContents().append(centerAndBorder(navProducer.create()));
    } else {
        getContents().append(centerAndBorder(pageNumberComponent));
    }
    return super.create();
}
Also used : TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent)

Example 9 with TextComponent

use of com.sk89q.worldedit.util.formatting.text.TextComponent in project WorldGuard by EngineHub.

the class FlagHelperBox method appendStringFlagValue.

private void appendStringFlagValue(TextComponent.Builder builder, StringFlag flag) {
    String currVal = region.getFlag(flag);
    if (currVal == null) {
        currVal = getInheritedValue(region, flag);
    }
    if (currVal == null) {
        final String defVal = flag.getDefault();
        if (defVal == null) {
            appendValueText(builder, flag, "unset string", null);
        } else {
            final TextComponent defComp = LegacyComponentSerializer.INSTANCE.deserialize(defVal);
            String display = reduceToText(defComp);
            display = display.replace("\n", "\\n");
            if (display.length() > 23) {
                display = display.substring(0, 20) + "...";
            }
            appendValueText(builder, flag, display, TextComponent.of("Default value:").append(TextComponent.newline()).append(defComp));
        }
    } else {
        TextComponent currComp = LegacyComponentSerializer.INSTANCE.deserialize(currVal);
        String display = reduceToText(currComp);
        display = display.replace("\n", "\\n");
        if (display.length() > 23) {
            display = display.substring(0, 20) + "...";
        }
        appendValueText(builder, flag, display, TextComponent.of("Current value:").append(TextComponent.newline()).append(currComp));
    }
}
Also used : TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent)

Example 10 with TextComponent

use of com.sk89q.worldedit.util.formatting.text.TextComponent in project WorldGuard by EngineHub.

the class RegionPrintoutBuilder method appendFlagsList.

/**
 * Append just the list of flags (without "Flags:"), including colors.
 *
 * @param useColors true to use colors
 */
public void appendFlagsList(boolean useColors) {
    boolean hasFlags = false;
    for (Flag<?> flag : WorldGuard.getInstance().getFlagRegistry()) {
        Object val = region.getFlag(flag);
        // No value
        if (val == null) {
            continue;
        }
        if (hasFlags) {
            builder.append(TextComponent.of(", "));
        }
        RegionGroupFlag groupFlag = flag.getRegionGroupFlag();
        Object group = null;
        if (groupFlag != null) {
            group = region.getFlag(groupFlag);
        }
        String flagString;
        if (group == null) {
            flagString = flag.getName() + ": ";
        } else {
            flagString = flag.getName() + " -g " + group + ": ";
        }
        TextColor flagColor = TextColor.WHITE;
        if (useColors) {
            // passthrough is ok on global
            if (FlagHelperBox.DANGER_ZONE.contains(flag) && !(region.getId().equals(ProtectedRegion.GLOBAL_REGION) && flag == Flags.PASSTHROUGH)) {
                flagColor = TextColor.DARK_RED;
            } else if (Flags.INBUILT_FLAGS.contains(flag.getName())) {
                flagColor = TextColor.GOLD;
            } else if (flag instanceof UnknownFlag) {
                flagColor = TextColor.GRAY;
            } else {
                flagColor = TextColor.LIGHT_PURPLE;
            }
        }
        TextComponent flagText = TextComponent.of(flagString, flagColor).append(TextComponent.of(String.valueOf(val), useColors ? TextColor.YELLOW : TextColor.WHITE));
        if (perms != null && perms.maySetFlag(region, flag)) {
            flagText = flagText.hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("Click to set flag"))).clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, "/rg flag -w \"" + world + "\" " + region.getId() + " " + flag.getName() + " "));
        }
        builder.append(flagText);
        hasFlags = true;
    }
    if (!hasFlags) {
        TextComponent noFlags = TextComponent.of("(none)", useColors ? TextColor.RED : TextColor.WHITE);
        builder.append(noFlags);
    }
    if (perms != null && perms.maySetFlag(region)) {
        builder.append(TextComponent.space()).append(TextComponent.of("[Flags]", useColors ? TextColor.GREEN : TextColor.GRAY).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("Click to set a flag"))).clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, "/rg flags -w \"" + world + "\" " + region.getId())));
    }
}
Also used : TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) RegionGroupFlag(com.sk89q.worldguard.protection.flags.RegionGroupFlag) TextColor(com.sk89q.worldedit.util.formatting.text.format.TextColor) UnknownFlag(com.sk89q.worldguard.protection.flags.registry.UnknownFlag)

Aggregations

TextComponent (com.sk89q.worldedit.util.formatting.text.TextComponent)11 UUID (java.util.UUID)3 BlockVector3 (com.sk89q.worldedit.math.BlockVector3)2 Component (com.sk89q.worldedit.util.formatting.text.Component)2 TranslatableComponent (com.sk89q.worldedit.util.formatting.text.TranslatableComponent)2 TextColor (com.sk89q.worldedit.util.formatting.text.format.TextColor)2 World (com.sk89q.worldedit.world.World)2 LocalPlayer (com.sk89q.worldguard.LocalPlayer)2 IOException (java.io.IOException)2 RollbackDatabase (com.fastasyncworldedit.core.database.RollbackDatabase)1 URIClipboardHolder (com.fastasyncworldedit.core.extent.clipboard.URIClipboardHolder)1 RollbackOptimizedHistory (com.fastasyncworldedit.core.history.RollbackOptimizedHistory)1 MutableFullBlockChange (com.fastasyncworldedit.core.history.change.MutableFullBlockChange)1 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 Lists (com.google.common.collect.Lists)1 Maps (com.google.common.collect.Maps)1 Command (com.sk89q.minecraft.util.commands.Command)1 CommandException (com.sk89q.minecraft.util.commands.CommandException)1 CommandPermissions (com.sk89q.minecraft.util.commands.CommandPermissions)1