Pagination changes and cleanup.

Refactored PaginationBox to be abstract. Implementations can generate individual components as needed now.
Add lots of Component usage to schematic list, help listings, etc.
Fix a few schematic and file resolution issues.
This commit is contained in:
wizjany
2019-04-28 01:12:05 -04:00
parent 62353a46db
commit b3053f19ce
17 changed files with 307 additions and 202 deletions

View File

@ -45,7 +45,6 @@ import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.Regions;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.formatting.component.PaginationBox;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeData;
import com.sk89q.worldedit.world.biome.BiomeType;
@ -56,7 +55,7 @@ import org.enginehub.piston.annotation.param.Arg;
import org.enginehub.piston.annotation.param.Switch;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@ -83,10 +82,11 @@ public class BiomeCommands {
int page) throws WorldEditException {
BiomeRegistry biomeRegistry = WorldEdit.getInstance().getPlatformManager()
.queryCapability(Capability.GAME_HOOKS).getRegistries().getBiomeRegistry();
List<BiomeData> biomes = BiomeType.REGISTRY.values().stream().map(biomeRegistry::getData).collect(Collectors.toList());
PaginationBox paginationBox = new PaginationBox("Available Biomes", "/biomelist %page%");
paginationBox.setComponents(biomes.stream().map(biome -> TextComponent.of(biome.getName())).collect(Collectors.toList()));
PaginationBox paginationBox = PaginationBox.fromStrings("Available Biomes", "/biomelist %page%",
BiomeType.REGISTRY.values().stream()
.map(biomeRegistry::getData).filter(Objects::nonNull)
.map(BiomeData::getName).collect(Collectors.toList()));
player.print(paginationBox.create(page));
}
@ -152,7 +152,7 @@ public class BiomeCommands {
@Command(
name = "/setbiome",
desc = "Sets the biome of the player's current block or region.",
desc = "Sets the biome of your current block or region.",
descFooter = "By default, uses all the blocks in your selection"
)
@Logging(REGION)

View File

@ -34,7 +34,6 @@ import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.MathUtils;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.formatting.component.PaginationBox;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.world.storage.LegacyChunkStore;
import com.sk89q.worldedit.world.storage.McRegionChunkStore;
import org.enginehub.piston.annotation.Command;
@ -62,10 +61,10 @@ public class ChunkCommands {
@Command(
name = "chunkinfo",
desc = "Get information about the chunk that you are inside"
desc = "Get information about the chunk you're inside"
)
@CommandPermissions("worldedit.chunkinfo")
public void chunkInfo(Player player) throws WorldEditException {
public void chunkInfo(Player player) {
Location pos = player.getBlockIn();
int chunkX = (int) Math.floor(pos.getBlockX() / 16.0);
int chunkZ = (int) Math.floor(pos.getBlockZ() / 16.0);
@ -90,8 +89,8 @@ public class ChunkCommands {
@Arg(desc = "Page number.", def = "1") int page) throws WorldEditException {
Set<BlockVector2> chunks = session.getSelection(player.getWorld()).getChunks();
PaginationBox paginationBox = new PaginationBox("Selected Chunks", "/listchunks %page%");
paginationBox.setComponents(chunks.stream().map(chunk -> TextComponent.of(chunk.toString())).collect(Collectors.toList()));
PaginationBox paginationBox = PaginationBox.fromStrings("Selected Chunks", "/listchunks %page%",
chunks.stream().map(BlockVector2::toString).collect(Collectors.toList()));
player.print(paginationBox.create(page));
}

View File

@ -19,8 +19,6 @@
package com.sk89q.worldedit.command;
import com.google.common.collect.Multimap;
import com.google.common.io.Files;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
@ -39,6 +37,8 @@ import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter;
import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.math.transform.Transform;
import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.util.formatting.component.PaginationBox;
import com.sk89q.worldedit.util.formatting.component.SchematicPaginationBox;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.io.Closer;
import com.sk89q.worldedit.util.io.file.FilenameException;
@ -60,7 +60,6 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
@ -70,10 +69,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
@CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class)
public class SchematicCommands {
/**
* 9 schematics per page fits in the MC chat window.
*/
private static final int SCHEMATICS_PER_PAGE = 9;
private static final Logger log = LoggerFactory.getLogger(SchematicCommands.class);
private final WorldEdit worldEdit;
@ -100,7 +95,9 @@ public class SchematicCommands {
LocalConfiguration config = worldEdit.getConfiguration();
File dir = worldEdit.getWorkingDirectoryFile(config.saveDir);
File f = worldEdit.getSafeOpenFile(player, dir, filename, BuiltInClipboardFormat.SPONGE_SCHEMATIC.getPrimaryFileExtension(), ClipboardFormats.getFileExtensionArray());
File f = worldEdit.getSafeOpenFile(player, dir, filename,
BuiltInClipboardFormat.SPONGE_SCHEMATIC.getPrimaryFileExtension(),
ClipboardFormats.getFileExtensionArray());
if (!f.exists()) {
player.printError("Schematic " + filename + " does not exist!");
@ -128,7 +125,7 @@ public class SchematicCommands {
player.print(filename + " loaded. Paste it with //paste");
} catch (IOException e) {
player.printError("Schematic could not read or it does not exist: " + e.getMessage());
log.warn("Failed to load a saved clipboard", e);
log.warn("Failed to load schematic: " + e.getMessage());
}
}
@ -277,7 +274,7 @@ public class SchematicCommands {
@Switch(name = 'd', desc = "Sort by date, oldest first")
boolean oldFirst,
@Switch(name = 'n', desc = "Sort by date, newest first")
boolean newFirst) {
boolean newFirst) throws WorldEditException {
if (oldFirst && newFirst) {
throw new StopExecutionException(TextComponent.of("Cannot sort by oldest and newest."));
}
@ -292,16 +289,6 @@ public class SchematicCommands {
File[] files = new File[fileList.size()];
fileList.toArray(files);
int pageCount = files.length / SCHEMATICS_PER_PAGE + 1;
if (page < 1) {
actor.printError("Page must be at least 1");
return;
}
if (page > pageCount) {
actor.printError("Page must be less than " + (pageCount + 1));
return;
}
final int sortType = oldFirst ? -1 : newFirst ? 1 : 0;
// cleanup file list
Arrays.sort(files, (f1, f2) -> {
@ -321,20 +308,9 @@ public class SchematicCommands {
return res;
});
List<String> schematics = listFiles(worldEdit.getConfiguration().saveDir, files);
int offset = (page - 1) * SCHEMATICS_PER_PAGE;
actor.print("Available schematics (Filename: Format) [" + page + "/" + pageCount + "]:");
StringBuilder build = new StringBuilder();
int limit = Math.min(offset + SCHEMATICS_PER_PAGE, schematics.size());
for (int i = offset; i < limit; ) {
build.append(schematics.get(i));
if (++i != limit) {
build.append("\n");
}
}
actor.print(build.toString());
String pageCommand = actor.isPlayer() ? "/schem list -p %page%" + (oldFirst ? " -d" : newFirst ? " -n" : "") : null;
PaginationBox paginationBox = new SchematicPaginationBox(worldEdit.getConfiguration().saveDir, files, pageCommand);
actor.print(paginationBox.create(page));
}
private List<File> allFiles(File root) {
@ -353,22 +329,4 @@ public class SchematicCommands {
return fileList;
}
private List<String> listFiles(String prefix, File[] files) {
if (prefix == null) prefix = "";
List<String> result = new ArrayList<>();
for (File file : files) {
StringBuilder build = new StringBuilder();
build.append("\u00a72");
//ClipboardFormat format = ClipboardFormats.findByFile(file);
Multimap<String, ClipboardFormat> exts = ClipboardFormats.getFileExtensionMap();
ClipboardFormat format = exts.get(Files.getFileExtension(file.getName()))
.stream().findFirst().orElse(null);
boolean inRoot = file.getParentFile().getName().equals(prefix);
build.append(inRoot ? file.getName() : file.getPath().split(Pattern.quote(prefix + File.separator))[1])
.append(": ").append(format == null ? "Unknown" : format.getName() + "*");
result.add(build.toString());
}
return result;
}
}

View File

@ -624,7 +624,7 @@ public class SelectionCommands {
}
case UNKNOWN:
default:
CommandListBox box = new CommandListBox("Selection modes");
CommandListBox box = new CommandListBox("Selection modes", null);
TextComponentProducer contents = box.getContents();
contents.append(SubtleFormat.wrap("Select one of the modes below:")).newline();
@ -636,7 +636,7 @@ public class SelectionCommands {
box.appendCommand("cyl", "Select a cylinder", "//sel cyl");
box.appendCommand("convex", "Select a convex polyhedral", "//sel convex");
player.print(box.create());
player.print(box.create(1));
return;
}

View File

@ -51,6 +51,10 @@ import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.CylinderRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.formatting.component.InvalidComponentException;
import com.sk89q.worldedit.util.formatting.component.SubtleFormat;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BlockTypes;
import org.enginehub.piston.annotation.Command;
@ -58,8 +62,11 @@ import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg;
import org.enginehub.piston.annotation.param.Switch;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.function.Supplier;
import static com.sk89q.worldedit.command.util.Logging.LogMode.PLACEMENT;
@ -474,6 +481,12 @@ public class UtilityCommands {
return killed;
}
// get the formatter with the system locale. in the future, if we can get a local from a player, we can use that
private static final DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.getDefault());
static {
formatter.applyPattern("#,##0.#####"); // pattern is locale-insensitive. this can translate to "1.234,56789"
}
@Command(
name = "/calculate",
aliases = { "/calc", "/eval", "/evaluate", "/solve" },
@ -485,8 +498,14 @@ public class UtilityCommands {
String input) {
try {
Expression expression = Expression.compile(input);
actor.print("= " + expression.evaluate(
new double[] {}, WorldEdit.getInstance().getSessionManager().get(actor).getTimeout()));
double result = expression.evaluate(
new double[]{}, WorldEdit.getInstance().getSessionManager().get(actor).getTimeout());
String formatted = formatter.format(result);
actor.print(SubtleFormat.wrap(input + " = ")
.append(TextComponent.of(formatted, TextColor.LIGHT_PURPLE)));
//actor.print(SubtleFormat.wrap(input).append(Component.newline())
// .append(SubtleFormat.wrap("= "))
// .append(TextComponent.of(formatted, TextColor.LIGHT_PURPLE)));
} catch (EvaluationException e) {
actor.printError(String.format(
"'%s' could not be evaluated (error: %s)", input, e.getMessage()));

View File

@ -22,13 +22,10 @@ package com.sk89q.worldedit.command.util;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.formatting.component.CodeFormat;
import com.sk89q.worldedit.util.formatting.component.CommandListBox;
import com.sk89q.worldedit.util.formatting.component.CommandUsageBox;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldedit.util.formatting.component.InvalidComponentException;
import org.enginehub.piston.Command;
import org.enginehub.piston.CommandManager;
@ -46,7 +43,7 @@ import static java.util.stream.Collectors.toList;
/**
* Implementation of the //help command.
*/
// Stored in a separate class to prevent import conflicts.
// Stored in a separate class to prevent import conflicts, and because it's aliased via /we help.
public class PrintCommandHelp {
private static Command detectCommand(CommandManager manager, String command) {
@ -69,17 +66,11 @@ public class PrintCommandHelp {
return mapping.orElse(null);
}
public static void help(List<String> commandPath, int page, WorldEdit we, Actor actor) {
if (page < 1) {
actor.printError("Page must be >= 1.");
return;
}
public static void help(List<String> commandPath, int page, WorldEdit we, Actor actor) throws InvalidComponentException {
CommandManager manager = we.getPlatformManager().getPlatformCommandManager().getCommandManager();
final int perPage = actor instanceof Player ? 8 : 20; // More pages for console
if (commandPath.isEmpty()) {
printAllCommands(page, perPage, manager.getAllCommands(), actor, ImmutableList.of());
printCommands(page, manager.getAllCommands(), actor, ImmutableList.of());
return;
}
@ -98,7 +89,11 @@ public class PrintCommandHelp {
if (subCommands.isEmpty()) {
actor.printError(String.format("'%s' has no sub-commands. (Maybe '%s' is for a parameter?)",
Joiner.on(" ").join(visited), subCommand));
Joiner.on(" ").join(visited.stream().map(Command::getName).iterator()), subCommand));
// full help for single command
CommandUsageBox box = new CommandUsageBox(visited, visited.stream()
.map(Command::getName).collect(Collectors.joining(" ")));
actor.print(box.create());
return;
}
@ -107,7 +102,11 @@ public class PrintCommandHelp {
visited.add(currentCommand);
} else {
actor.printError(String.format("The sub-command '%s' under '%s' could not be found.",
subCommand, Joiner.on(" ").join(visited)));
subCommand, Joiner.on(" ").join(visited.stream().map(Command::getName).iterator())));
// list subcommands for currentCommand
CommandUsageBox box = new CommandUsageBox(visited, visited.stream()
.map(Command::getName).collect(Collectors.joining(" ")));
actor.print(box.create());
return;
}
}
@ -120,46 +119,35 @@ public class PrintCommandHelp {
.map(Command::getName).collect(Collectors.joining(" ")));
actor.print(box.create());
} else {
printAllCommands(page, perPage, subCommands.values().stream(), actor, visited);
printCommands(page, subCommands.values().stream(), actor, visited);
}
}
private static void printAllCommands(int page, int perPage, Stream<Command> commandStream, Actor actor,
List<Command> commandList) {
private static void printCommands(int page, Stream<Command> commandStream, Actor actor,
List<Command> commandList) throws InvalidComponentException {
// Get a list of aliases
List<Command> commands = commandStream
.sorted(byCleanName())
.collect(toList());
// Calculate pagination
int offset = perPage * (page - 1);
int pageTotal = (int) Math.ceil(commands.size() / (double) perPage);
// Box
CommandListBox box = new CommandListBox(String.format("Help: page %d/%d ", page, pageTotal));
TextComponent.Builder tip = box.getContents().getBuilder().color(TextColor.GRAY);
if (offset >= commands.size()) {
tip.color(TextColor.RED)
.append(TextComponent.of(String.format("There is no page %d (total number of pages is %d).\n", page, pageTotal)));
} else {
List<Command> list = commands.subList(offset, Math.min(offset + perPage, commands.size()));
tip.append(TextComponent.of("Type "));
tip.append(CodeFormat.wrap("//help [<page>] <command...>"));
tip.append(TextComponent.of(" for more information.\n"));
// Add each command
for (Command mapping : list) {
String alias = (commandList.isEmpty() ? "/" : "") + mapping.getName();
String command = Stream.concat(commandList.stream(), Stream.of(mapping))
.map(Command::getName)
.collect(Collectors.joining(" ", "/", ""));
box.appendCommand(alias, mapping.getDescription(), command);
}
String used = commandList.isEmpty() ? null
: Joiner.on(" ").join(commandList.stream().map(Command::getName).iterator());
CommandListBox box = new CommandListBox(
(used == null ? "Help" : "Subcommands: " + used),
"//help %page%" + (used == null ? "" : " " + used));
if (!actor.isPlayer()) {
box.formatForConsole();
}
actor.print(box.create());
for (Command mapping : commands) {
String alias = (commandList.isEmpty() ? "/" : "") + mapping.getName();
String command = Stream.concat(commandList.stream(), Stream.of(mapping))
.map(Command::getName)
.collect(Collectors.joining(" ", "/", ""));
box.appendCommand(alias, mapping.getDescription(), command);
}
actor.print(box.create(page));
}
private PrintCommandHelp() {