More work on commands

This commit is contained in:
MattBDev 2019-07-23 16:26:18 -04:00
parent 478c330c1e
commit 9816eb3102
16 changed files with 349 additions and 396 deletions

View File

@ -1,6 +1,7 @@
<!DOCTYPE import-control PUBLIC <!DOCTYPE import-control PUBLIC
"-//Puppy Crawl//DTD Import Control 1.1//EN" "-//Checkstyle//DTD ImportControl Configuration 1.4//EN"
"http://www.puppycrawl.com/dtds/import_control_1_1.dtd"> "https://checkstyle.org/dtds/import_control_1_4.dtd">
<import-control pkg="com.sk89q"> <import-control pkg="com.sk89q">
<allow pkg="java"/> <allow pkg="java"/>
@ -9,6 +10,7 @@
<allow pkg="org.hamcrest"/> <allow pkg="org.hamcrest"/>
<allow pkg="org.mockito"/> <allow pkg="org.mockito"/>
<allow pkg="com.sk89q"/> <allow pkg="com.sk89q"/>
<allow pkg="com.boydti"/>
<allow pkg="com.google.common"/> <allow pkg="com.google.common"/>
<allow pkg="com.thoughtworks.paranamer"/> <allow pkg="com.thoughtworks.paranamer"/>
<allow pkg="gnu.trove"/> <allow pkg="gnu.trove"/>

View File

@ -13,12 +13,12 @@ public class BukkitCommand implements CommandExecutor {
private final FaweCommand cmd; private final FaweCommand cmd;
public BukkitCommand(final FaweCommand cmd) { public BukkitCommand(FaweCommand cmd) {
this.cmd = cmd; this.cmd = cmd;
} }
@Override @Override
public boolean onCommand(@NotNull final CommandSender sender, final Command cmd, final String label, final String[] args) { public boolean onCommand(@NotNull CommandSender sender, Command cmd, String label, String[] args) {
final FawePlayer plr = Fawe.imp().wrap(sender); final FawePlayer plr = Fawe.imp().wrap(sender);
if (!sender.hasPermission(this.cmd.getPerm()) && !sender.isOp()) { if (!sender.hasPermission(this.cmd.getPerm()) && !sender.isOp()) {
BBC.NO_PERM.send(plr, this.cmd.getPerm()); BBC.NO_PERM.send(plr, this.cmd.getPerm());

View File

@ -54,7 +54,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
} }
private List<MessagePart> messageParts; private List<MessagePart> messageParts;
private int index = 0; private int index;
private String jsonString; private String jsonString;
private boolean dirty; private boolean dirty;
@ -78,11 +78,11 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* *
* @param firstPartText The existing text in the message. * @param firstPartText The existing text in the message.
*/ */
public FancyMessage(final String firstPartText) { public FancyMessage(String firstPartText) {
this(rawText(firstPartText)); this(rawText(firstPartText));
} }
private FancyMessage(final TextualComponent firstPartText) { private FancyMessage(TextualComponent firstPartText) {
messageParts = new ArrayList<>(); messageParts = new ArrayList<>();
messageParts.add(new MessagePart(firstPartText)); messageParts.add(new MessagePart(firstPartText));
index = messageParts.size(); index = messageParts.size();
@ -165,7 +165,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
} }
} }
if (text.length() - last > 0) { if (text.length() - last > 0) {
append(text.substring(last, text.length())); append(text.substring(last));
colors.forEach(this::color); colors.forEach(this::color);
} }
index++; index++;
@ -206,7 +206,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* represent formatters. * represent formatters.
*/ */
public FancyMessage style(ChatColor... styles) { public FancyMessage style(ChatColor... styles) {
for (final ChatColor style : styles) { for (ChatColor style : styles) {
if (!style.isFormat()) { if (!style.isFormat()) {
color(style); color(style);
} }
@ -224,7 +224,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @param path The path of the file on the client filesystem. * @param path The path of the file on the client filesystem.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage file(final String path) { public FancyMessage file(String path) {
onClick("open_file", path); onClick("open_file", path);
return this; return this;
} }
@ -237,7 +237,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @param url The URL of the page to open when the link is clicked. * @param url The URL of the page to open when the link is clicked.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage link(final String url) { public FancyMessage link(String url) {
onClick("open_url", url); onClick("open_url", url);
return this; return this;
} }
@ -252,7 +252,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @param command The text to display in the chat bar of the client. * @param command The text to display in the chat bar of the client.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage suggest(final String command) { public FancyMessage suggest(String command) {
onClick("suggest_command", command); onClick("suggest_command", command);
return this; return this;
} }
@ -267,7 +267,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @param command The text to append to the chat bar of the client. * @param command The text to append to the chat bar of the client.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage insert(final String command) { public FancyMessage insert(String command) {
onCurrent(m -> m.insertionData = command); onCurrent(m -> m.insertionData = command);
dirty = true; dirty = true;
return this; return this;
@ -282,7 +282,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @param command The text to display in the chat bar of the client. * @param command The text to display in the chat bar of the client.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage command(final String command) { public FancyMessage command(String command) {
onClick("run_command", command); onClick("run_command", command);
return this; return this;
} }
@ -297,7 +297,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* hovering. * hovering.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage tooltip(final String text) { public FancyMessage tooltip(String text) {
onHover("show_text", new JsonString(text)); onHover("show_text", new JsonString(text));
return this; return this;
} }
@ -313,8 +313,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* tooltip are created. * tooltip are created.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage tooltip(final Iterable<String> lines) { public FancyMessage tooltip(Iterable<String> lines) {
tooltip(com.boydti.fawe.bukkit.chat.ArrayWrapper.toArray(lines, String.class)); tooltip(ArrayWrapper.toArray(lines, String.class));
return this; return this;
} }
@ -327,7 +327,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @param lines The lines of text which will be displayed to the client upon hovering. * @param lines The lines of text which will be displayed to the client upon hovering.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage tooltip(final String... lines) { public FancyMessage tooltip(String... lines) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (int i = 0; i < lines.length; i++) { for (int i = 0; i < lines.length; i++) {
builder.append(lines[i]); builder.append(lines[i]);
@ -420,9 +420,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* tooltip are created. * tooltip are created.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage formattedTooltip(final Iterable<FancyMessage> lines) { public FancyMessage formattedTooltip(Iterable<FancyMessage> lines) {
return formattedTooltip( return formattedTooltip(ArrayWrapper.toArray(lines, FancyMessage.class));
com.boydti.fawe.bukkit.chat.ArrayWrapper.toArray(lines, FancyMessage.class));
} }
/** /**
@ -433,7 +432,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* message. * message.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage translationReplacements(final String... replacements) { public FancyMessage translationReplacements(String... replacements) {
for (String str : replacements) { for (String str : replacements) {
latest().translationReplacements.add(new JsonString(str)); latest().translationReplacements.add(new JsonString(str));
} }
@ -466,7 +465,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* message. * message.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage translationReplacements(final FancyMessage... replacements) { public FancyMessage translationReplacements(FancyMessage... replacements) {
Collections.addAll(latest().translationReplacements, replacements); Collections.addAll(latest().translationReplacements, replacements);
dirty = true; dirty = true;
@ -482,9 +481,9 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* message. * message.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage translationReplacements(final Iterable<FancyMessage> replacements) { public FancyMessage translationReplacements(Iterable<FancyMessage> replacements) {
return translationReplacements( return translationReplacements(
com.boydti.fawe.bukkit.chat.ArrayWrapper.toArray(replacements, FancyMessage.class)); ArrayWrapper.toArray(replacements, FancyMessage.class));
} }
/** /**
@ -495,11 +494,11 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @param text The text which will populate the new message component. * @param text The text which will populate the new message component.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage then(final String text) { public FancyMessage then(String text) {
return then(rawText(text)); return then(rawText(text));
} }
private FancyMessage append(final String text) { private FancyMessage append(String text) {
if (!latest().hasText()) { if (!latest().hasText()) {
throw new IllegalStateException("previous message part has no text"); throw new IllegalStateException("previous message part has no text");
} }
@ -519,7 +518,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @param text The text which will populate the new message component. * @param text The text which will populate the new message component.
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage then(final TextualComponent text) { public FancyMessage then(TextualComponent text) {
if (!latest().hasText()) { if (!latest().hasText()) {
throw new IllegalStateException("previous message part has no text"); throw new IllegalStateException("previous message part has no text");
} }
@ -552,7 +551,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
latest().writeJson(writer); latest().writeJson(writer);
} else { } else {
writer.beginObject().name("text").value("").name("extra").beginArray(); writer.beginObject().name("text").value("").name("extra").beginArray();
for (final MessagePart part : this) { for (MessagePart part : this) {
part.writeJson(writer); part.writeJson(writer);
} }
writer.endArray().endObject(); writer.endArray().endObject();
@ -644,7 +643,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
int minorVersion = Integer.parseInt(split[1]); int minorVersion = Integer.parseInt(split[1]);
int revisionVersion = Integer.parseInt(split[2].substring(1)); // Substring to ignore R int revisionVersion = Integer.parseInt(split[2].substring(1)); // Substring to ignore R
if (minorVersion < 8 || (minorVersion == 8 && revisionVersion == 1)) { if (minorVersion < 8 || minorVersion == 8 && revisionVersion == 1) {
chatSerializerClazz = Reflection.getNMSClass("ChatSerializer"); chatSerializerClazz = Reflection.getNMSClass("ChatSerializer");
} else { } else {
chatSerializerClazz = Reflection.getNMSClass("IChatBaseComponent$ChatSerializer"); chatSerializerClazz = Reflection.getNMSClass("IChatBaseComponent$ChatSerializer");
@ -694,9 +693,9 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @param senders The command senders who will receive the message. * @param senders The command senders who will receive the message.
* @see #send(CommandSender) * @see #send(CommandSender)
*/ */
public void send(final Iterable<? extends CommandSender> senders) { public void send(Iterable<? extends CommandSender> senders) {
String string = toJSONString(); String string = toJSONString();
for (final CommandSender sender : senders) { for (CommandSender sender : senders) {
send(sender, string); send(sender, string);
} }
} }
@ -742,7 +741,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
return messageParts.get(messageParts.size() - 1); return messageParts.get(messageParts.size() - 1);
} }
private void onClick(final String name, final String data) { private void onClick(String name, String data) {
onCurrent(m -> { onCurrent(m -> {
m.clickActionName = name; m.clickActionName = name;
m.clickActionData = data; m.clickActionData = data;
@ -750,7 +749,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
dirty = true; dirty = true;
} }
private void onHover(final String name, final JsonRepresentedObject data) { private void onHover(String name, JsonRepresentedObject data) {
onCurrent(m -> { onCurrent(m -> {
m.hoverActionName = name; m.hoverActionName = name;
m.hoverActionData = data; m.hoverActionData = data;
@ -759,6 +758,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
} }
// Doc copied from interface // Doc copied from interface
@Override
public Map<String, Object> serialize() { public Map<String, Object> serialize() {
HashMap<String, Object> map = new HashMap<>(); HashMap<String, Object> map = new HashMap<>();
map.put("messageParts", messageParts); map.put("messageParts", messageParts);
@ -784,6 +784,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
/** /**
* <b>Internally called method. Not for API consumption.</b> * <b>Internally called method. Not for API consumption.</b>
*/ */
@Override
@NotNull @NotNull
public Iterator<MessagePart> iterator() { public Iterator<MessagePart> iterator() {
return messageParts.iterator(); return messageParts.iterator();
@ -830,8 +831,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
.add(MessagePart.stylesToNames.inverse().get(entry.getKey())); .add(MessagePart.stylesToNames.inverse().get(entry.getKey()));
} }
} else if (entry.getKey().equals("color")) { } else if (entry.getKey().equals("color")) {
component.color = ChatColor component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase());
.valueOf(entry.getValue().getAsString().toUpperCase());
} else if (entry.getKey().equals("clickEvent")) { } else if (entry.getKey().equals("clickEvent")) {
JsonObject object = entry.getValue().getAsJsonObject(); JsonObject object = entry.getValue().getAsJsonObject();
component.clickActionName = object.get("action").getAsString(); component.clickActionName = object.get("action").getAsString();

View File

@ -85,7 +85,10 @@ public class BukkitServerInterface implements MultiUserPlatform {
@Override @Override
public boolean isValidMobType(String type) { public boolean isValidMobType(String type) {
final EntityType entityType = EntityType.fromName(type); if (!type.startsWith("minecraft:")) {
return false;
}
final EntityType entityType = EntityType.fromName(type.substring(10));
return entityType != null && entityType.isAlive(); return entityType != null && entityType.isAlive();
} }

View File

@ -56,7 +56,7 @@ public class CFICommand extends CommandProcessor<Object, Object> {
hmCmd = hmCmd =
Commands.getAlias(CFICommands.class, "heightmap") + " " + settings.imageArg; Commands.getAlias(CFICommands.class, "heightmap") + " " + settings.imageArg;
} }
CFICommands.msg("What do you want to use as the base?").newline() TextComponent.of("What do you want to use as the base?").newline()
.text("[HeightMap]").cmdTip(hmCmd).text(" - A heightmap like ") .text("[HeightMap]").cmdTip(hmCmd).text(" - A heightmap like ")
.text("[this]").linkTip("http://i.imgur.com/qCd30MR.jpg") .text("[this]").linkTip("http://i.imgur.com/qCd30MR.jpg")
.newline() .newline()

View File

@ -1,6 +1,8 @@
package com.boydti.fawe.command; package com.boydti.fawe.command;
import static com.boydti.fawe.util.image.ImageUtil.load; import static com.boydti.fawe.util.image.ImageUtil.load;
import static com.sk89q.worldedit.command.MethodCommands.getArguments;
import static com.sk89q.worldedit.util.formatting.text.TextComponent.newline;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweAPI; import com.boydti.fawe.FaweAPI;
@ -18,7 +20,6 @@ import com.boydti.fawe.util.MathMan;
import com.boydti.fawe.util.StringMan; import com.boydti.fawe.util.StringMan;
import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.TaskManager;
import com.boydti.fawe.util.TextureUtil; import com.boydti.fawe.util.TextureUtil;
import com.boydti.fawe.util.chat.Message;
import com.boydti.fawe.util.image.ImageUtil; import com.boydti.fawe.util.image.ImageUtil;
import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.EmptyClipboardException; import com.sk89q.worldedit.EmptyClipboardException;
@ -44,19 +45,13 @@ import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.formatting.text.TextComponent; import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TextComponent.Builder;
import com.sk89q.worldedit.util.formatting.text.event.ClickEvent;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypes;
import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg;
import org.enginehub.piston.annotation.param.Switch;
import org.enginehub.piston.exception.StopExecutionException;
import org.enginehub.piston.inject.InjectedValueAccess;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt; import java.awt.image.DataBufferInt;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@ -76,6 +71,7 @@ import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.enginehub.piston.annotation.Command; import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer; import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg; import org.enginehub.piston.annotation.param.Arg;
@ -83,9 +79,6 @@ import org.enginehub.piston.annotation.param.Switch;
import org.enginehub.piston.exception.StopExecutionException; import org.enginehub.piston.exception.StopExecutionException;
import org.enginehub.piston.inject.InjectedValueAccess; import org.enginehub.piston.inject.InjectedValueAccess;
import static com.boydti.fawe.util.image.ImageUtil.load;
import static com.sk89q.worldedit.command.MethodCommands.*;
@CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class) @CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class)
public class CFICommands { public class CFICommands {
@ -161,16 +154,17 @@ public class CFICommands {
public void brush(FawePlayer fp) { public void brush(FawePlayer fp) {
CFISettings settings = assertSettings(fp); CFISettings settings = assertSettings(fp);
settings.popMessages(fp); settings.popMessages(fp);
Message msg; @NonNull Builder msg;
if (settings.getGenerator().getImageViewer() != null) { if (settings.getGenerator().getImageViewer() != null) {
msg = msg("CFI supports using brushes during creation").newline() msg = TextComponent.builder("CFI supports using brushes during creation").append(newline())
.text(" - Place the map on a wall of item frames").newline() .append(" - Place the map on a wall of item frames").append(newline())
.text(" - Use any WorldEdit brush on the item frames").newline() .append(" - Use any WorldEdit brush on the item frames").append(newline())
.text(" - Example: ").text("Video").linkTip("https://goo.gl/PK4DMG").newline(); .append(" - Example: ").append(TextComponent.of("Video").clickEvent(ClickEvent.openUrl("https://goo.gl/PK4DMG"))).append(newline());
} else { } else {
msg = msg("This is not supported with your platform/version").newline(); msg = TextComponent.builder("This is not supported with your platform/version").append(newline());
} }
msg.text("< [Back]").cmdTip(alias()).send(fp); //TODO msg.text("< [Back]").cmdTip(alias()).send(fp);
fp.toWorldEditPlayer().print(msg.build());
} }
@Command( @Command(
@ -360,7 +354,7 @@ public class CFICommands {
floor(fp, BlockTypes.SNOW.getDefaultState().with(PropertyKey.LAYERS, 7), image, mask, disableWhiteOnly); floor(fp, BlockTypes.SNOW.getDefaultState().with(PropertyKey.LAYERS, 7), image, mask, disableWhiteOnly);
main(fp, BlockTypes.SNOW_BLOCK, image, mask, disableWhiteOnly); main(fp, BlockTypes.SNOW_BLOCK, image, mask, disableWhiteOnly);
smooth(fp, 1, 8, image, mask, disableWhiteOnly); smooth(fp, 1, 8, image, mask, disableWhiteOnly);
msg("Added snow!").send(fp); TextComponent.of("Added snow!").send(fp);
assertSettings(fp).resetComponent(); assertSettings(fp).resetComponent();
component(fp); component(fp);
} }
@ -389,15 +383,15 @@ public class CFICommands {
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void paletteblocks(FawePlayer fp, Player player, LocalSession session, @Arg(name = "arg", desc = "String", def = "") String arg) throws EmptyClipboardException, InputParseException, FileNotFoundException { public void paletteblocks(FawePlayer fp, Player player, LocalSession session, @Arg(name = "arg", desc = "String", def = "") String arg) throws EmptyClipboardException, InputParseException, FileNotFoundException {
if (arg == null) { if (arg == null) {
msg("What blocks do you want to color with?").newline() TextComponent.of("What blocks do you want to color with?").append(newline())
.text("[All]").cmdTip(alias() + " PaletteBlocks *").text(" - All available blocks") .text("[All]").cmdTip(alias() + " PaletteBlocks *").text(" - All available blocks")
.newline() .append(newline())
.text("[Clipboard]").cmdTip(alias() + " PaletteBlocks #clipboard").text(" - The blocks in your clipboard") .text("[Clipboard]").cmdTip(alias() + " PaletteBlocks #clipboard").text(" - The blocks in your clipboard")
.newline() .append(newline())
.text("[List]").suggestTip(alias() + " PaletteBlocks stone,gravel").text(" - A comma separated list of blocks") .text("[List]").suggestTip(alias() + " PaletteBlocks stone,gravel").text(" - A comma separated list of blocks")
.newline() .append(newline())
.text("[Complexity]").cmdTip(alias() + " Complexity").text(" - Block textures within a complexity range") .text("[Complexity]").cmdTip(alias() + " Complexity").text(" - Block textures within a complexity range")
.newline() .append(newline())
.text("< [Back]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "coloring")) .text("< [Back]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "coloring"))
.send(fp); .send(fp);
return; return;
@ -511,7 +505,7 @@ public class CFICommands {
} else { } else {
gen.addSchems(load(imageMask), mask, multi.getHolders(), rarity, distance, rotate); gen.addSchems(load(imageMask), mask, multi.getHolders(), rarity, distance, rotate);
} }
msg("Added schematics!").send(fp); TextComponent.of("Added schematics!").send(fp);
populate(fp); populate(fp);
} }
@ -533,7 +527,7 @@ public class CFICommands {
} else { } else {
gen.setBiome(biome); gen.setBiome(biome);
} }
msg("Set biome!").send(fp); TextComponent.of("Set biome!").send(fp);
assertSettings(fp).resetComponent(); assertSettings(fp).resetComponent();
component(fp); component(fp);
} }
@ -545,7 +539,7 @@ public class CFICommands {
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void caves(FawePlayer fp) throws WorldEditException { public void caves(FawePlayer fp) throws WorldEditException {
assertSettings(fp).getGenerator().addCaves(); assertSettings(fp).getGenerator().addCaves();
msg("Added caves!").send(fp); TextComponent.of("Added caves!").send(fp);
populate(fp); populate(fp);
} }
@ -557,7 +551,7 @@ public class CFICommands {
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void ore(FawePlayer fp, Mask mask, Pattern pattern, int size, int frequency, int rariry, int minY, int maxY) throws WorldEditException { public void ore(FawePlayer fp, Mask mask, Pattern pattern, int size, int frequency, int rariry, int minY, int maxY) throws WorldEditException {
assertSettings(fp).getGenerator().addOre(mask, pattern, size, frequency, rariry, minY, maxY); assertSettings(fp).getGenerator().addOre(mask, pattern, size, frequency, rariry, minY, maxY);
msg("Added ore!").send(fp); fp.toWorldEditPlayer().print(TextComponent.of("Added ore!"));
populate(fp); populate(fp);
} }
@ -568,7 +562,7 @@ public class CFICommands {
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void ores(FawePlayer fp, Mask mask) throws WorldEditException { public void ores(FawePlayer fp, Mask mask) throws WorldEditException {
assertSettings(fp).getGenerator().addDefaultOres(mask); assertSettings(fp).getGenerator().addDefaultOres(mask);
msg("Added ores!").send(fp); fp.toWorldEditPlayer().print(TextComponent.of("Added ores!"));
populate(fp); populate(fp);
} }
@ -585,7 +579,8 @@ public class CFICommands {
} else { } else {
gen.setHeights(Integer.parseInt(arg)); gen.setHeights(Integer.parseInt(arg));
} }
msg("Set height!").send(fp); fp.toWorldEditPlayer().print("Set Height!");
TextComponent.of("Set height!").send(fp);
component(fp); component(fp);
} }
@ -597,7 +592,7 @@ public class CFICommands {
public void waterId(FawePlayer fp, BlockStateHolder block) throws WorldEditException { public void waterId(FawePlayer fp, BlockStateHolder block) throws WorldEditException {
CFISettings settings = assertSettings(fp); CFISettings settings = assertSettings(fp);
settings.getGenerator().setWaterId(block.getBlockType().getInternalId()); settings.getGenerator().setWaterId(block.getBlockType().getInternalId());
msg("Set water id!").send(fp); TextComponent.of("Set water id!").send(fp);
settings.resetComponent(); settings.resetComponent();
component(fp); component(fp);
} }
@ -611,7 +606,7 @@ public class CFICommands {
public void baseId(FawePlayer fp, BlockStateHolder block) throws WorldEditException { public void baseId(FawePlayer fp, BlockStateHolder block) throws WorldEditException {
CFISettings settings = assertSettings(fp); CFISettings settings = assertSettings(fp);
settings.getGenerator().setBedrockId(block.getBlockType().getInternalId()); settings.getGenerator().setBedrockId(block.getBlockType().getInternalId());
msg("Set base id!").send(fp); TextComponent.of("Set base id!").send(fp);
settings.resetComponent(); settings.resetComponent();
component(fp); component(fp);
} }
@ -625,7 +620,7 @@ public class CFICommands {
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void worldthickness(FawePlayer fp, int height) throws WorldEditException { public void worldthickness(FawePlayer fp, int height) throws WorldEditException {
assertSettings(fp).getGenerator().setWorldThickness(height); assertSettings(fp).getGenerator().setWorldThickness(height);
msg("Set world thickness!").send(fp); TextComponent.of("Set world thickness!").send(fp);
component(fp); component(fp);
} }
@ -638,7 +633,7 @@ public class CFICommands {
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void floorthickness(FawePlayer fp, int height) throws WorldEditException { public void floorthickness(FawePlayer fp, int height) throws WorldEditException {
assertSettings(fp).getGenerator().setFloorThickness(height); assertSettings(fp).getGenerator().setFloorThickness(height);
msg("Set floor thickness!").send(fp); TextComponent.of("Set floor thickness!").send(fp);
component(fp); component(fp);
} }
@ -650,7 +645,7 @@ public class CFICommands {
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void update(FawePlayer fp) throws WorldEditException { public void update(FawePlayer fp) throws WorldEditException {
assertSettings(fp).getGenerator().update(); assertSettings(fp).getGenerator().update();
msg("Chunks refreshed!").send(fp); TextComponent.of("Chunks refreshed!").send(fp);
mainMenu(fp); mainMenu(fp);
} }
@ -662,7 +657,7 @@ public class CFICommands {
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void tp(FawePlayer fp) throws WorldEditException { public void tp(FawePlayer fp) throws WorldEditException {
HeightMapMCAGenerator gen = assertSettings(fp).getGenerator(); HeightMapMCAGenerator gen = assertSettings(fp).getGenerator();
msg("Teleporting...").send(fp); TextComponent.of("Teleporting...").send(fp);
Vector3 origin = gen.getOrigin(); Vector3 origin = gen.getOrigin();
Player player = fp.getPlayer(); Player player = fp.getPlayer();
player.setPosition(origin.subtract(16, 0, 16)); player.setPosition(origin.subtract(16, 0, 16));
@ -680,7 +675,7 @@ public class CFICommands {
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void waterheight(FawePlayer fp, int height) throws WorldEditException { public void waterheight(FawePlayer fp, int height) throws WorldEditException {
assertSettings(fp).getGenerator().setWaterHeight(height); assertSettings(fp).getGenerator().setWaterHeight(height);
msg("Set water height!").send(fp); TextComponent.of("Set water height!").send(fp);
component(fp); component(fp);
} }
@ -694,7 +689,7 @@ public class CFICommands {
public void glass(FawePlayer fp, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(name = "mask", desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException { public void glass(FawePlayer fp, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(name = "mask", desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException {
CFISettings settings = assertSettings(fp); CFISettings settings = assertSettings(fp);
settings.getGenerator().setColorWithGlass(load(image)); settings.getGenerator().setColorWithGlass(load(image));
msg("Set color with glass!").send(fp); TextComponent.of("Set color with glass!").send(fp);
settings.resetColoring(); settings.resetColoring();
mainMenu(fp); mainMenu(fp);
} }
@ -719,7 +714,7 @@ public class CFICommands {
gen.setColor(load(image)); gen.setColor(load(image));
} }
settings.resetColoring(); settings.resetColoring();
msg("Set color with blocks!").send(fp); TextComponent.of("Set color with blocks!").send(fp);
mainMenu(fp); mainMenu(fp);
} }
@ -735,7 +730,7 @@ public class CFICommands {
public void blockbiome(FawePlayer fp, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(name = "mask", desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException { public void blockbiome(FawePlayer fp, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(name = "mask", desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException {
CFISettings settings = assertSettings(fp); CFISettings settings = assertSettings(fp);
settings.getGenerator().setBlockAndBiomeColor(load(image), mask, load(imageMask), !disableWhiteOnly); settings.getGenerator().setBlockAndBiomeColor(load(image), mask, load(imageMask), !disableWhiteOnly);
msg("Set color with blocks and biomes!").send(fp); TextComponent.of("Set color with blocks and biomes!").send(fp);
settings.resetColoring(); settings.resetColoring();
mainMenu(fp); mainMenu(fp);
} }
@ -751,7 +746,7 @@ public class CFICommands {
public void biomecolor(FawePlayer fp, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(name = "mask", desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException { public void biomecolor(FawePlayer fp, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(name = "mask", desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException {
CFISettings settings = assertSettings(fp); CFISettings settings = assertSettings(fp);
settings.getGenerator().setBiomeColor(load(image)); settings.getGenerator().setBiomeColor(load(image));
msg("Set color with biomes!").send(fp); TextComponent.of("Set color with biomes!").send(fp);
settings.resetColoring(); settings.resetColoring();
mainMenu(fp); mainMenu(fp);
} }
@ -804,15 +799,16 @@ public class CFICommands {
int biomePriority = gen.getBiomePriority(); int biomePriority = gen.getBiomePriority();
Message msg = msg(">> Current Settings <<").newline() //TODO fix this so it can execute commands and show tooltips.
.text("Randomization ").text("[" + (Boolean.toString(rand).toUpperCase()) + "]").cmdTip(alias() + " randomization " + (!rand)) @NonNull Builder builder = TextComponent.builder(">> Current Settings <<").append(newline())
.newline() .append("Randomization ").append("[" + Boolean.toString(rand).toUpperCase() + "]")//.cmdTip(alias() + " randomization " + (!rand))
.text("Mask ").text("[" + mask + "]").cmdTip(alias() + " mask") .append(newline())
.newline() .append("Mask ").append("[" + mask + "]")//.cmdTip(alias() + " mask")
.text("Blocks ").text("[" + blocks + "]").tooltip(blockList).command(alias() + " paletteBlocks") .append(newline())
.newline() .append("Blocks ").append("[" + blocks + "]")//.tooltip(blockList).command(alias() + " paletteBlocks")
.text("BiomePriority ").text("[" + biomePriority + "]").cmdTip(alias() + " biomepriority") .append(newline())
.newline(); .append("BiomePriority ").append("[" + biomePriority + "]")//.cmdTip(alias() + " biomepriority")
.append(newline());
if (settings.image != null) { if (settings.image != null) {
StringBuilder colorArgs = new StringBuilder(); StringBuilder colorArgs = new StringBuilder();
@ -827,19 +823,20 @@ public class CFICommands {
colorArgs.append(" -w"); colorArgs.append(" -w");
} }
msg.text("Image: ") builder.append("Image: ")
.text("[" + settings.imageArg + "]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "image")) .append("[" + settings.imageArg + "]")//.cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "image"))
.newline().newline() .append(newline()).append(newline())
.text("&cLet's Color: ") .append("Let's Color: ")
.cmdOptions(alias() + " ", colorArgs.toString(), "Biomes", "Blocks", "BlockAndBiome", "Glass") //.cmdOptions(alias() + " ", colorArgs.toString(), "Biomes", "Blocks", "BlockAndBiome", "Glass")
.newline(); .append(newline());
} else { } else {
msg.newline().text("You can color a world using an image like ") builder.append(newline()).append("You can color a world using an image like ")
.text("[This]").linkTip("http://i.imgur.com/vJYinIU.jpg").newline() .append(TextComponent.of("[This]").clickEvent(ClickEvent.openUrl("http://i.imgur.com/vJYinIU.jpg"))).append(newline())
.text("&cYou MUST provide an image: ") .append("You MUST provide an image: ")
.text("[None]").cmdTip(alias() + " " + Commands.getAlias(Command.class, "image")).newline(); .append("[None]");//.cmdTip(alias() + " " + Commands.getAlias(Command.class, "image")).append(newline());
} }
msg.text("< [Back]").cmdTip(alias()).send(fp); builder.append("< [Back]");//.cmdTip(alias()).send(fp);
fp.toWorldEditPlayer().print(builder.build());
} }
@Command( @Command(
@ -859,11 +856,11 @@ public class CFICommands {
StringBuilder cmd = new StringBuilder(alias() + " mask "); StringBuilder cmd = new StringBuilder(alias() + " mask ");
msg(">> Current Settings <<").newline() TextComponent.of(">> Current Settings <<").append(newline())
.text("Image Mask ").text("[" + settings.imageMaskArg + "]").suggestTip(cmd + "http://") .text("Image Mask ").text("[" + settings.imageMaskArg + "]").suggestTip(cmd + "http://")
.newline() .append(newline())
.text("WorldEdit Mask ").text("[" + settings.maskArg + "]").suggestTip(cmd + "<mask>") .text("WorldEdit Mask ").text("[" + settings.maskArg + "]").suggestTip(cmd + "<mask>")
.newline() .append(newline())
.text("< [Back]").cmdTip(alias() + " " + settings.getCategory()).send(fp); .text("< [Back]").cmdTip(alias() + " " + settings.getCategory()).send(fp);
} }
@ -884,9 +881,9 @@ public class CFICommands {
if (pattern != null) { if (pattern != null) {
settings.getCategory().accept(fp); settings.getCategory().accept(fp);
} else { } else {
msg(">> Current Settings <<").newline() TextComponent.of(">> Current Settings <<").append(newline())
.text("Pattern ").text("[Click Here]").suggestTip(cmd + " stone") .text("Pattern ").text("[Click Here]").suggestTip(cmd + " stone")
.newline() .append(newline())
.text("< [Back]").cmdTip(alias() + " " + settings.getCategory()).send(fp); .text("< [Back]").cmdTip(alias() + " " + settings.getCategory()).send(fp);
} }
} }
@ -922,11 +919,13 @@ public class CFICommands {
StringBuilder cmd = new StringBuilder(alias() + " image "); StringBuilder cmd = new StringBuilder(alias() + " image ");
if (image == null) { if (image == null) {
msg("Please provide an image:").newline() TextComponent build = TextComponent.builder("Please provide an image:")
.text("From a URL: ").text("[Click Here]").suggestTip(cmd + "http://") .append(newline())
.newline() .append("From a URL: ").append("[Click Here]")//TODO .suggestTip(cmd + "http://")
.text("From a file: ").text("[Click Here]").suggestTip(cmd + "file://") .append(newline())
.send(fp); .append("From a file: ").append("[Click Here]")//TODO .suggestTip(cmd + "file://")
.build();
fp.toWorldEditPlayer().print(build);
} else { } else {
if (settings.hasGenerator()) { if (settings.hasGenerator()) {
coloring(fp); coloring(fp);
@ -947,11 +946,14 @@ public class CFICommands {
CFISettings settings = assertSettings(fp); CFISettings settings = assertSettings(fp);
settings.popMessages(fp); settings.popMessages(fp);
settings.setCategory(this::populate); settings.setCategory(this::populate);
msg("What would you like to populate?").newline() TextComponent build = TextComponent.builder("What would you like to populate?")
.text("(You will need to type these commands)").newline() .append(newline())
.cmdOptions(alias() + " ", "", "Ores", "Ore", "Caves", "Schematics", "Smooth") .append("(You will need to type these commands)").append(newline())
.newline().text("< [Back]").cmdTip(alias()) //TODO .cmdOptions(alias() + " ", "", "Ores", "Ore", "Caves", "Schematics", "Smooth")
.send(fp); .append(newline())
.append(TextComponent.of("< [Back]").clickEvent(ClickEvent.runCommand(alias())))
.build();
fp.toWorldEditPlayer().print(build);
} }
@Command( @Command(
@ -991,50 +993,51 @@ public class CFICommands {
String waterHeight = Commands.getAlias(CFICommands.class, "waterheight"); String waterHeight = Commands.getAlias(CFICommands.class, "waterheight");
String snow = Commands.getAlias(CFICommands.class, "snow"); String snow = Commands.getAlias(CFICommands.class, "snow");
Message msg = msg(">> Current Settings <<").newline() //TODO
.text("Mask ").text("[" + mask + "]").cmdTip(alias() + " mask") // Message msg = TextComponent.builder(">> Current Settings <<").append(newline())
.newline() // .append("Mask ").append("[" + mask + "]").cmdTip(alias() + " mask")
.text("Pattern ").text("[" + pattern + "]").cmdTip(alias() + " pattern") // .append(newline())
.newline() // .append("Pattern ").append("[" + pattern + "]").cmdTip(alias() + " pattern")
.newline() // .append(newline())
.text(">> Components <<") // .append(newline())
.newline() // .append(">> Components <<")
.text("[Height]").suggestTip(alias() + " " + alias("height") + " 120").text(" - Terrain height for whole map") // .append(newline())
.newline() // .append("[Height]").suggestTip(alias() + " " + alias("height") + " 120").text(" - Terrain height for whole map")
.text("[WaterHeight]").suggestTip(alias() + " " + alias("waterheight") + " 60").text(" - Sea level for whole map") // .append(newline())
.newline() // .text("[WaterHeight]").suggestTip(alias() + " " + alias("waterheight") + " 60").text(" - Sea level for whole map")
.text("[FloorThickness]").suggestTip(alias() + " " + alias("floorthickness") + " 60").text(" - Floor thickness of entire map") // .append(newline())
.newline() // .text("[FloorThickness]").suggestTip(alias() + " " + alias("floorthickness") + " 60").text(" - Floor thickness of entire map")
.text("[WorldThickness]").suggestTip(alias() + " " + alias("worldthickness") + " 60").text(" - World thickness of entire map") // .append(newline())
.newline() // .text("[WorldThickness]").suggestTip(alias() + " " + alias("worldthickness") + " 60").text(" - World thickness of entire map")
.text("[Snow]").suggestTip(alias() + " " + alias("snow") + maskArgs).text(" - Set snow in the masked areas") // .append(newline())
.newline(); // .text("[Snow]").suggestTip(alias() + " " + alias("snow") + maskArgs).text(" - Set snow in the masked areas")
// .append(newline());
if (pattern != null) { //
String disabled = "You must specify a pattern"; // if (pattern != null) {
msg // String disabled = "You must specify a pattern";
.text("[&cWaterId]").tooltip(disabled).newline() // msg
.text("[&cBedrockId]").tooltip(disabled).newline() // .text("[&cWaterId]").tooltip(disabled).append(newline())
.text("[&cFloor]").tooltip(disabled).newline() // .text("[&cBedrockId]").tooltip(disabled).append(newline())
.text("[&cMain]").tooltip(disabled).newline() // .text("[&cFloor]").tooltip(disabled).append(newline())
.text("[&cColumn]").tooltip(disabled).newline() // .text("[&cMain]").tooltip(disabled).append(newline())
.text("[&cOverlay]").tooltip(disabled).newline(); // .text("[&cColumn]").tooltip(disabled).append(newline())
} else { // .text("[&cOverlay]").tooltip(disabled).append(newline());
StringBuilder compArgs = new StringBuilder(); // } else {
compArgs.append(" " + settings.patternArg + maskArgs); // StringBuilder compArgs = new StringBuilder();
// compArgs.append(" " + settings.patternArg + maskArgs);
msg //
.text("[WaterId]").cmdTip(alias() + " waterId " + pattern).text(" - Water id for whole map").newline() // msg
.text("[BedrockId]").cmdTip(alias() + " baseId " + pattern).text(" - Bedrock id for whole map").newline() // .text("[WaterId]").cmdTip(alias() + " waterId " + pattern).text(" - Water id for whole map").append(newline())
.text("[Floor]").cmdTip(alias() + " floor" + compArgs).text(" - Set the floor in the masked areas").newline() // .text("[BedrockId]").cmdTip(alias() + " baseId " + pattern).text(" - Bedrock id for whole map").append(newline())
.text("[Main]").cmdTip(alias() + " main" + compArgs).text(" - Set the main block in the masked areas").newline() // .text("[Floor]").cmdTip(alias() + " floor" + compArgs).text(" - Set the floor in the masked areas").append(newline())
.text("[Column]").cmdTip(alias() + " column" + compArgs).text(" - Set the columns in the masked areas").newline() // .text("[Main]").cmdTip(alias() + " main" + compArgs).text(" - Set the main block in the masked areas").append(newline())
.text("[Overlay]").cmdTip(alias() + " overlay" + compArgs).text(" - Set the overlay in the masked areas").newline(); // .text("[Column]").cmdTip(alias() + " column" + compArgs).text(" - Set the columns in the masked areas").append(newline())
} // .text("[Overlay]").cmdTip(alias() + " overlay" + compArgs).text(" - Set the overlay in the masked areas").append(newline());
// }
msg.newline() //
.text("< [Back]").cmdTip(alias()) // msg.append(newline())
.send(fp); // .text("< [Back]").cmdTip(alias())
// .send(fp);
} }
private static CFISettings assertSettings(FawePlayer fp) { private static CFISettings assertSettings(FawePlayer fp) {
@ -1180,18 +1183,14 @@ public class CFICommands {
return Commands.getAlias(CFICommands.class, command); return Commands.getAlias(CFICommands.class, command);
} }
protected static Message msg(String text) { @SuppressWarnings("unused")
return new Message().newline()
.text(BBC.getPrefix())
.text(text);
}
protected static void mainMenu(FawePlayer fp) { protected static void mainMenu(FawePlayer fp) {
msg("What do you want to do now?").newline() //TODO
.cmdOptions(alias() + " ", "", "Coloring", "Component", "Populate", "Brush") // msg("What do you want to do now?").append(newline())
.newline().text("<> [View]").command(alias() + " " + Commands.getAlias(CFICommands.class, "download")).tooltip("View full resolution image") // .cmdOptions(alias() + " ", "", "Coloring", "Component", "Populate", "Brush")
.newline().text(">< [Cancel]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "cancel")) // .append(newline()).text("<> [View]").command(alias() + " " + Commands.getAlias(CFICommands.class, "download")).tooltip("View full resolution image")
.newline().text("&2>> [Done]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "done")) // .append(newline()).text(">< [Cancel]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "cancel"))
.send(fp); // .append(newline()).text("&2>> [Done]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "done"))
// .send(fp);
} }
} }

View File

@ -6,11 +6,9 @@ import com.boydti.fawe.configuration.file.YamlConfiguration;
import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.object.RunnableVal3; import com.boydti.fawe.object.RunnableVal3;
import com.boydti.fawe.util.StringMan; import com.boydti.fawe.util.StringMan;
import com.boydti.fawe.util.chat.Message;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import java.io.File; import java.io.File;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -369,7 +367,7 @@ public enum BBC {
private static final HashMap<String, String> replacements = new HashMap<>(); private static final HashMap<String, String> replacements = new HashMap<>();
static { static {
for (final char letter : "1234567890abcdefklmnor".toCharArray()) { for (char letter : "1234567890abcdefklmnor".toCharArray()) {
replacements.put("&" + letter, "\u00a7" + letter); replacements.put("&" + letter, "\u00a7" + letter);
} }
replacements.put("\\\\n", "\n"); replacements.put("\\\\n", "\n");
@ -394,17 +392,13 @@ public enum BBC {
* *
* @param defaultMessage default * @param defaultMessage default
*/ */
BBC(final String defaultMessage, final String category) { BBC(String defaultMessage, String category) {
this.defaultMessage = defaultMessage; this.defaultMessage = defaultMessage;
this.translatedMessage = defaultMessage; this.translatedMessage = defaultMessage;
this.category = category.toLowerCase(); this.category = category.toLowerCase();
} }
public String f(final Object... args) { public String format(Object... args) {
return format(args);
}
public String format(final Object... args) {
String m = this.translatedMessage; String m = this.translatedMessage;
for (int i = args.length - 1; i >= 0; i--) { for (int i = args.length - 1; i >= 0; i--) {
if (args[i] == null) { if (args[i] == null) {
@ -418,7 +412,7 @@ public enum BBC {
return m; return m;
} }
public static void load(final File file) { public static void load(File file) {
try { try {
if (!file.exists()) { if (!file.exists()) {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
@ -430,13 +424,13 @@ public enum BBC {
final HashSet<String> allNames = new HashSet<>(); final HashSet<String> allNames = new HashSet<>();
final HashSet<String> allCats = new HashSet<>(); final HashSet<String> allCats = new HashSet<>();
final HashSet<String> toRemove = new HashSet<>(); final HashSet<String> toRemove = new HashSet<>();
for (final BBC c : all) { for (BBC c : all) {
allNames.add(c.name()); allNames.add(c.name());
allCats.add(c.category.toLowerCase()); allCats.add(c.category.toLowerCase());
} }
final EnumSet<BBC> captions = EnumSet.noneOf(BBC.class); final EnumSet<BBC> captions = EnumSet.noneOf(BBC.class);
boolean changed = false; boolean changed = false;
for (final String key : keys) { for (String key : keys) {
final Object value = yml.get(key); final Object value = yml.get(key);
if (value instanceof MemorySection) { if (value instanceof MemorySection) {
continue; continue;
@ -456,11 +450,11 @@ public enum BBC {
toRemove.add(key); toRemove.add(key);
} }
} }
for (final String remove : toRemove) { for (String remove : toRemove) {
changed = true; changed = true;
yml.set(remove, null); yml.set(remove, null);
} }
for (final BBC caption : all) { for (BBC caption : all) {
if (!captions.contains(caption)) { if (!captions.contains(caption)) {
changed = true; changed = true;
yml.set(caption.category + "." + caption.name().toLowerCase(), caption.defaultMessage); yml.set(caption.category + "." + caption.name().toLowerCase(), caption.defaultMessage);
@ -470,7 +464,7 @@ public enum BBC {
if (changed) { if (changed) {
yml.save(file); yml.save(file);
} }
} catch (final Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -501,10 +495,6 @@ public enum BBC {
return this.translatedMessage; return this.translatedMessage;
} }
public Message m(Object... args) {
return new Message(this, args);
}
public String original() { public String original() {
return defaultMessage; return defaultMessage;
} }
@ -518,7 +508,7 @@ public enum BBC {
return index == 0 ? this : others[index - 1]; return index == 0 ? this : others[index - 1];
} }
public void send(Object actor, final Object... args) { public void send(Object actor, Object... args) {
if (isEmpty()) { if (isEmpty()) {
return; return;
} }
@ -536,10 +526,10 @@ public enum BBC {
} }
public static String getPrefix() { public static String getPrefix() {
return (PREFIX.isEmpty() ? "" : PREFIX.s() + " "); return PREFIX.isEmpty() ? "" : PREFIX.s() + " ";
} }
public void send(final FawePlayer<?> player, final Object... args) { public void send(FawePlayer<?> player, Object... args) {
if (isEmpty()) { if (isEmpty()) {
return; return;
} }
@ -549,7 +539,7 @@ public enum BBC {
player.sendMessage((PREFIX.isEmpty() ? "" : PREFIX.s() + " ") + this.format(args)); player.sendMessage((PREFIX.isEmpty() ? "" : PREFIX.s() + " ") + this.format(args));
} }
} }
public void send(final Actor player, final Object... args) { public void send(Actor player, Object... args) {
if (isEmpty()) { if (isEmpty()) {
return; return;
} }

View File

@ -159,7 +159,8 @@ public abstract class FawePlayer<T> extends Metadatable {
if (times > limit) { if (times > limit) {
setConfirmTask(task, context, command); setConfirmTask(task, context, command);
String volume = "<unspecified>"; String volume = "<unspecified>";
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(0, times, command, volume)); throw new RegionOperationException(
BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.format(0, times, command, volume));
} }
} }
task.run(); task.run();
@ -171,7 +172,9 @@ public abstract class FawePlayer<T> extends Metadatable {
if (radius > 448) { if (radius > 448) {
setConfirmTask(task, context, command); setConfirmTask(task, context, command);
long volume = (long) (Math.PI * ((double) radius * radius)); long volume = (long) (Math.PI * ((double) radius * radius));
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(0, radius, command, NumberFormat.getNumberInstance().format(volume))); throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM
.format(0, radius, command,
NumberFormat.getNumberInstance().format(volume)));
} }
} }
} }
@ -188,7 +191,8 @@ public abstract class FawePlayer<T> extends Metadatable {
setConfirmTask(task, context, command); setConfirmTask(task, context, command);
BlockVector3 base = max.subtract(min).add(BlockVector3.ONE); BlockVector3 base = max.subtract(min).add(BlockVector3.ONE);
long volume = (long) base.getX() * base.getZ() * base.getY() * times; long volume = (long) base.getX() * base.getZ() * base.getY() * times;
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(min, max, command, NumberFormat.getNumberInstance().format(volume))); throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM
.format(min, max, command, NumberFormat.getNumberInstance().format(volume)));
} }
} }
} }
@ -205,7 +209,8 @@ public abstract class FawePlayer<T> extends Metadatable {
setConfirmTask(task, context, command); setConfirmTask(task, context, command);
BlockVector3 base = max.subtract(min).add(BlockVector3.ONE); BlockVector3 base = max.subtract(min).add(BlockVector3.ONE);
long volume = (long) base.getX() * base.getZ() * base.getY(); long volume = (long) base.getX() * base.getZ() * base.getY();
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(min, max, command, NumberFormat.getNumberInstance().format(volume))); throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM
.format(min, max, command, NumberFormat.getNumberInstance().format(volume)));
} }
} }
} }

View File

@ -60,11 +60,12 @@ public class InspectBrush extends BrushTool implements DoubleActionTraceTool {
public boolean perform(final Player player, LocalSession session, boolean rightClick) { public boolean perform(final Player player, LocalSession session, boolean rightClick) {
if (!session.isToolControlEnabled() || !player.hasPermission("worldedit.tool.inspect")) { if (!session.isToolControlEnabled() || !player.hasPermission("worldedit.tool.inspect")) {
player.print(BBC.getPrefix() + BBC.NO_PERM.f("worldedit.tool.inspect")); player.print(BBC.getPrefix() + BBC.NO_PERM.format("worldedit.tool.inspect"));
return false; return false;
} }
if (!Settings.IMP.HISTORY.USE_DATABASE) { if (!Settings.IMP.HISTORY.USE_DATABASE) {
player.print(BBC.getPrefix() + BBC.SETTING_DISABLE.f("history.use-database (Import with /frb #import )")); player.print(BBC.getPrefix() + BBC.SETTING_DISABLE
.format("history.use-database (Import with /frb #import )"));
return false; return false;
} }
BlockVector3 target = getTarget(player, rightClick).toBlockPoint(); BlockVector3 target = getTarget(player, rightClick).toBlockPoint();

View File

@ -3,9 +3,8 @@ package com.boydti.fawe.util.chat;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.BBC;
import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FawePlayer;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import java.io.Serializable;
import java.util.Objects; import java.util.Objects;
public class Message { public class Message {
@ -24,10 +23,6 @@ public class Message {
active = !(Fawe.get().getChatManager() instanceof PlainChatManager); active = !(Fawe.get().getChatManager() instanceof PlainChatManager);
} }
public Message(BBC caption, Object... args) {
this(BBC.getPrefix() + caption.format(args));
}
public Message(String text) { public Message(String text) {
this(); this();
text(text); text(text);
@ -41,13 +36,6 @@ public class Message {
return (T) (this.builder = manager.builder()); return (T) (this.builder = manager.builder());
} }
public Message activeText(String text) {
if (active) {
text(text);
}
return this;
}
public boolean supportsInteraction() { public boolean supportsInteraction() {
return active; return active;
} }
@ -56,7 +44,7 @@ public class Message {
return text(caption.format(args)); return text(caption.format(args));
} }
public Message text(java.io.Serializable text) { public Message text(Serializable text) {
Fawe.get().getChatManager().text(this, BBC.color(Objects.toString(text))); Fawe.get().getChatManager().text(this, BBC.color(Objects.toString(text)));
return this; return this;
} }
@ -76,14 +64,10 @@ public class Message {
} }
public Message command(String command) { public Message command(String command) {
Fawe.get().getChatManager().command(this, ("/") + command); Fawe.get().getChatManager().command(this, "/" + command);
return this; return this;
} }
public Message prefix() {
return text(BBC.getPrefix());
}
public Message newline() { public Message newline() {
return text("\n"); return text("\n");
} }
@ -98,8 +82,8 @@ public class Message {
public Message cmdOptions(String prefix, String suffix, String... options) { public Message cmdOptions(String prefix, String suffix, String... options) {
for (int i = 0; i < options.length; i++) { for (int i = 0; i < options.length; i++) {
if (i != 0) text(" &8|&7 "); if (i != 0) text(" | ");
text("&7[&a" + options[i] + "&7]") text("[" + options[i] + "]")
.cmdTip(prefix + options[i] + suffix); .cmdTip(prefix + options[i] + suffix);
} }
return this; return this;
@ -114,11 +98,6 @@ public class Message {
return this; return this;
} }
public Message color(String color) {
Fawe.get().getChatManager().color(this, BBC.color(color));
return this;
}
public void send(Actor player) { public void send(Actor player) {
send(FawePlayer.wrap(player)); send(FawePlayer.wrap(player));
} }
@ -129,19 +108,19 @@ public class Message {
public Message paginate(String baseCommand, int page, int totalPages) { public Message paginate(String baseCommand, int page, int totalPages) {
if (!active) { if (!active) {
return text(BBC.PAGE_FOOTER.f(baseCommand, page + 1)); return text(BBC.PAGE_FOOTER.format(baseCommand, page + 1));
} }
if (page < totalPages && page > 1) { // Back | Next if (page < totalPages && page > 1) { // Back | Next
this.text("&f<<").command(baseCommand + " " + (page - 1)).text("&8 | ").text("&f>>") this.text("<<").command(baseCommand + " " + (page - 1)).text(" | ").text(">>")
.command(baseCommand + " " + (page + 1)); .command(baseCommand + " " + (page + 1));
} else if (page <= 1 && totalPages > page) { // Next } else if (page <= 1 && totalPages > page) { // Next
this.text("&8 -").text(" | ").text("&f>>") this.text(" -").text(" | ").text(">>")
.command(baseCommand + " " + (page + 1)); .command(baseCommand + " " + (page + 1));
} else if (page == totalPages && totalPages > 1) { // Back } else if (page == totalPages && totalPages > 1) { // Back
this.text("&f<<").command(baseCommand + " " + (page - 1)).text("&8 | ").text("- "); this.text("<<").command(baseCommand + " " + (page - 1)).text(" | ").text("- ");
} else { } else {
this.text("&8 - | - "); this.text(" - | - ");
} }
return this; return this;
} }

View File

@ -124,8 +124,6 @@ import org.enginehub.piston.annotation.param.Switch;
import org.enginehub.piston.inject.InjectedValueAccess; import org.enginehub.piston.inject.InjectedValueAccess;
import org.enginehub.piston.inject.Key; import org.enginehub.piston.inject.Key;
import static com.sk89q.worldedit.command.MethodCommands.*;
/** /**
* Commands to set brush shape. * Commands to set brush shape.
*/ */
@ -254,7 +252,7 @@ public class BrushCommands {
@Arg(desc = "The radius to sample for blending", def = "25") @Arg(desc = "The radius to sample for blending", def = "25")
Expression radius, InjectedValueAccess context) throws WorldEditException { Expression radius, InjectedValueAccess context) throws WorldEditException {
worldEdit.checkMaxBrushRadius(radius); worldEdit.checkMaxBrushRadius(radius);
player.print(BBC.BRUSH_SPLINE.f(radius)); player.print(BBC.BRUSH_SPLINE.format(radius));
return set(session, context, return set(session, context,
new SplineBrush(player, session)) new SplineBrush(player, session))
.setSize(radius) .setSize(radius)
@ -310,7 +308,7 @@ public class BrushCommands {
public BrushSettings surfaceSpline(Player player, LocalSession session, Pattern fill, public BrushSettings surfaceSpline(Player player, LocalSession session, Pattern fill,
@Arg(desc = "The radius to sample for blending", def = "0") @Arg(desc = "The radius to sample for blending", def = "0")
Expression radius, @Arg(name = "tension", desc = "double", def = "0") double tension, @Arg(name = "bias", desc = "double", def = "0") double bias, @Arg(name = "continuity", desc = "double", def = "0") double continuity, @Arg(name = "quality", desc = "double", def = "10") double quality, InjectedValueAccess context) throws WorldEditException { Expression radius, @Arg(name = "tension", desc = "double", def = "0") double tension, @Arg(name = "bias", desc = "double", def = "0") double bias, @Arg(name = "continuity", desc = "double", def = "0") double continuity, @Arg(name = "quality", desc = "double", def = "10") double quality, InjectedValueAccess context) throws WorldEditException {
player.print(BBC.BRUSH_SPLINE.f(radius)); player.print(BBC.BRUSH_SPLINE.format(radius));
worldEdit.checkMaxBrushRadius(radius); worldEdit.checkMaxBrushRadius(radius);
return set(session, context, return set(session, context,
new SurfaceSpline(tension, bias, continuity, quality)) new SurfaceSpline(tension, bias, continuity, quality))
@ -795,7 +793,7 @@ public class BrushCommands {
@CommandPermissions("worldedit.brush.copy") @CommandPermissions("worldedit.brush.copy")
public BrushSettings copy(Player player, LocalSession session, @Arg(name = "radius", desc = "Expression", def = "5") Expression radius, @Switch(name = 'r', desc = "Apply random rotation on paste") boolean randomRotate, @Switch(name = 'a', desc = "Apply auto view based rotation on paste") boolean autoRotate, InjectedValueAccess context) throws WorldEditException { public BrushSettings copy(Player player, LocalSession session, @Arg(name = "radius", desc = "Expression", def = "5") Expression radius, @Switch(name = 'r', desc = "Apply random rotation on paste") boolean randomRotate, @Switch(name = 'a', desc = "Apply auto view based rotation on paste") boolean autoRotate, InjectedValueAccess context) throws WorldEditException {
worldEdit.checkMaxBrushRadius(radius); worldEdit.checkMaxBrushRadius(radius);
player.print(BBC.BRUSH_COPY.f(radius)); player.print(BBC.BRUSH_COPY.format(radius));
return set(session, context, return set(session, context,
new CopyPastaBrush(player, session, randomRotate, autoRotate)) new CopyPastaBrush(player, session, randomRotate, autoRotate))

View File

@ -43,6 +43,7 @@ import java.util.zip.GZIPInputStream;
import org.enginehub.piston.annotation.Command; import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer; import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg; import org.enginehub.piston.annotation.param.Arg;
import org.enginehub.piston.annotation.param.ArgFlag;
import org.enginehub.piston.annotation.param.Switch; import org.enginehub.piston.annotation.param.Switch;
import org.enginehub.piston.inject.InjectedValueAccess; import org.enginehub.piston.inject.InjectedValueAccess;
@ -138,7 +139,7 @@ public class BrushOptionsCommands {
) )
@CommandPermissions("worldedit.brush.list") @CommandPermissions("worldedit.brush.list")
public void list(Actor actor, InjectedValueAccess args, public void list(Actor actor, InjectedValueAccess args,
@Switch(name = 'p', desc = "Prints the requested page") @ArgFlag(name = 'p', desc = "Prints the requested page", def = "0")
int page) throws WorldEditException { int page) throws WorldEditException {
String baseCmd = Commands.getAlias(BrushCommands.class, "brush") + " " + Commands.getAlias(BrushOptionsCommands.class, "loadbrush"); String baseCmd = Commands.getAlias(BrushCommands.class, "brush") + " " + Commands.getAlias(BrushOptionsCommands.class, "loadbrush");
File dir = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes"); File dir = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes");
@ -349,7 +350,7 @@ public class BrushOptionsCommands {
throws WorldEditException { throws WorldEditException {
BrushTool tool = session.getBrushTool(player, false); BrushTool tool = session.getBrushTool(player, false);
if (tool == null) { if (tool == null) {
player.print(BBC.BRUSH_NONE.f()); player.print(BBC.BRUSH_NONE.s());
return; return;
} }
if (mask == null) { if (mask == null) {
@ -381,7 +382,7 @@ public class BrushOptionsCommands {
Arguments arguments) throws WorldEditException { Arguments arguments) throws WorldEditException {
BrushTool tool = session.getBrushTool(player, false); BrushTool tool = session.getBrushTool(player, false);
if (tool == null) { if (tool == null) {
player.print(BBC.BRUSH_NONE.f()); player.print(BBC.BRUSH_NONE.s());
return; return;
} }
if (mask == null) { if (mask == null) {
@ -409,7 +410,7 @@ public class BrushOptionsCommands {
Arguments arguments) throws WorldEditException { Arguments arguments) throws WorldEditException {
BrushTool tool = session.getBrushTool(player, false); BrushTool tool = session.getBrushTool(player, false);
if (tool == null) { if (tool == null) {
player.print(BBC.BRUSH_NONE.f()); player.print(BBC.BRUSH_NONE.s());
return; return;
} }
if (transform == null) { if (transform == null) {
@ -438,7 +439,7 @@ public class BrushOptionsCommands {
Arguments arguments) throws WorldEditException { Arguments arguments) throws WorldEditException {
BrushTool tool = session.getBrushTool(player, false); BrushTool tool = session.getBrushTool(player, false);
if (tool == null) { if (tool == null) {
player.print(BBC.BRUSH_NONE.f()); player.print(BBC.BRUSH_NONE.s());
return; return;
} }
if (pattern == null) { if (pattern == null) {
@ -465,7 +466,7 @@ public class BrushOptionsCommands {
range = Math.max(0, Math.min(256, range)); range = Math.max(0, Math.min(256, range));
BrushTool tool = session.getBrushTool(player, false); BrushTool tool = session.getBrushTool(player, false);
if (tool == null) { if (tool == null) {
player.print(BBC.BRUSH_NONE.f()); player.print(BBC.BRUSH_NONE.s());
return; return;
} }
tool.setRange(range); tool.setRange(range);
@ -485,7 +486,7 @@ public class BrushOptionsCommands {
worldEdit.checkMaxBrushRadius(radius); worldEdit.checkMaxBrushRadius(radius);
BrushTool tool = session.getBrushTool(player, false); BrushTool tool = session.getBrushTool(player, false);
if (tool == null) { if (tool == null) {
player.print(BBC.BRUSH_NONE.f()); player.print(BBC.BRUSH_NONE.s());
return; return;
} }
BrushSettings settings = offHand ? tool.getOffHand() : tool.getContext(); BrushSettings settings = offHand ? tool.getOffHand() : tool.getContext();

View File

@ -1,24 +1,19 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.StringMan; import com.boydti.fawe.util.StringMan;
import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.formatting.text.TextComponent; import com.sk89q.worldedit.util.formatting.text.TextComponent;
import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg;
import org.enginehub.piston.exception.StopExecutionException;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.util.Locale; import java.util.Locale;
import java.util.UUID; import java.util.UUID;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException; import java.util.regex.PatternSyntaxException;
import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.exception.StopExecutionException;
//TODO This class breaks compilation
@CommandContainer @CommandContainer
public class ListFilters { public class ListFilters {
public class Filter { public class Filter {
@ -81,7 +76,7 @@ public class ListFilters {
} }
@Command( @Command(
name = "", name = "*", //TODO originally this was left blank but doing so causes a major compilation error
desc = "wildcard" desc = "wildcard"
) )
public Filter wildcard(Actor actor, File root, String arg) { public Filter wildcard(Actor actor, File root, String arg) {

View File

@ -19,25 +19,16 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import static com.boydti.fawe.util.ReflectionUtils.as;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.BBC;
import com.boydti.fawe.config.Commands;
import com.boydti.fawe.config.Settings; import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.object.RunnableVal3;
import com.boydti.fawe.object.clipboard.MultiClipboardHolder; import com.boydti.fawe.object.clipboard.MultiClipboardHolder;
import com.boydti.fawe.object.clipboard.URIClipboardHolder; import com.boydti.fawe.object.clipboard.URIClipboardHolder;
import com.boydti.fawe.object.clipboard.remap.ClipboardRemapper; import com.boydti.fawe.object.clipboard.remap.ClipboardRemapper;
import com.boydti.fawe.object.schematic.MinecraftStructure; import com.boydti.fawe.object.schematic.MinecraftStructure;
import com.boydti.fawe.object.schematic.StructureFormat;
import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.chat.Message;
import com.sk89q.worldedit.command.util.AsyncCommandBuilder;
import org.enginehub.piston.inject.InjectedValueAccess;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
@ -51,7 +42,6 @@ import com.sk89q.worldedit.event.extent.PlayerSaveClipboardEvent;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader;
@ -59,7 +49,6 @@ import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter;
import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.math.transform.Transform;
import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.util.formatting.component.CodeFormat;
import com.sk89q.worldedit.util.formatting.component.ErrorFormat; import com.sk89q.worldedit.util.formatting.component.ErrorFormat;
import com.sk89q.worldedit.util.formatting.component.PaginationBox; import com.sk89q.worldedit.util.formatting.component.PaginationBox;
import com.sk89q.worldedit.util.formatting.component.SchematicPaginationBox; import com.sk89q.worldedit.util.formatting.component.SchematicPaginationBox;
@ -87,7 +76,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.enginehub.piston.annotation.Command; import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer; import org.enginehub.piston.annotation.CommandContainer;
@ -95,6 +83,7 @@ import org.enginehub.piston.annotation.param.Arg;
import org.enginehub.piston.annotation.param.ArgFlag; import org.enginehub.piston.annotation.param.ArgFlag;
import org.enginehub.piston.annotation.param.Switch; import org.enginehub.piston.annotation.param.Switch;
import org.enginehub.piston.exception.StopExecutionException; import org.enginehub.piston.exception.StopExecutionException;
import org.enginehub.piston.inject.InjectedValueAccess;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -218,7 +207,8 @@ public class SchematicCommands {
@Arg(desc = "Format name.", def = "sponge") @Arg(desc = "Format name.", def = "sponge")
String formatName) throws FilenameException { String formatName) throws FilenameException {
LocalConfiguration config = worldEdit.getConfiguration(); LocalConfiguration config = worldEdit.getConfiguration();
ClipboardFormat format = formatName == null ? null : ClipboardFormats.findByAlias(formatName);
ClipboardFormat format = ClipboardFormats.findByAlias(formatName);
InputStream in = null; InputStream in = null;
try { try {
URI uri; URI uri;
@ -228,19 +218,15 @@ public class SchematicCommands {
return; return;
} }
UUID uuid = UUID.fromString(filename.substring(4)); UUID uuid = UUID.fromString(filename.substring(4));
URL base = new URL(Settings.IMP.WEB.URL); URL webUrl = new URL(Settings.IMP.WEB.URL);
URL url = new URL(base, "uploads/" + uuid + "." + format.getPrimaryFileExtension()); URL url = new URL(webUrl, "uploads/" + uuid + "." + format.getPrimaryFileExtension());
ReadableByteChannel rbc = Channels.newChannel(url.openStream()); ReadableByteChannel byteChannel = Channels.newChannel(url.openStream());
in = Channels.newInputStream(rbc); in = Channels.newInputStream(byteChannel);
uri = url.toURI(); uri = url.toURI();
} else { } else {
if (!player.hasPermission("worldedit.schematic.load") && !player.hasPermission("worldedit.clipboard.load")) { File saveDir = worldEdit.getWorkingDirectoryFile(config.saveDir);
BBC.NO_PERM.send(player, "worldedit.clipboard.load"); File dir = Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS ? new File(saveDir, player.getUniqueId().toString()) : saveDir;
return; File file;
}
File working = worldEdit.getWorkingDirectoryFile(config.saveDir);
File dir = Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS ? new File(working, player.getUniqueId().toString()) : working;
File f;
if (filename.startsWith("#")) { if (filename.startsWith("#")) {
String[] extensions; String[] extensions;
if (format != null) { if (format != null) {
@ -248,9 +234,9 @@ public class SchematicCommands {
} else { } else {
extensions = ClipboardFormats.getFileExtensionArray(); extensions = ClipboardFormats.getFileExtensionArray();
} }
f = player.openFileOpenDialog(extensions); file = player.openFileOpenDialog(extensions);
if (f == null || !f.exists()) { if (file == null || !file.exists()) {
player.printError("Schematic " + filename + " does not exist! (" + f + ")"); player.printError("Schematic " + filename + " does not exist! (" + file + ")");
return; return;
} }
} else { } else {
@ -262,27 +248,27 @@ public class SchematicCommands {
String extension = filename.substring(filename.lastIndexOf('.') + 1); String extension = filename.substring(filename.lastIndexOf('.') + 1);
format = ClipboardFormats.findByExtension(extension); format = ClipboardFormats.findByExtension(extension);
} }
f = MainUtil.resolve(dir, filename, format, false); file = MainUtil.resolve(dir, filename, format, false);
} }
if (f == null || !f.exists()) { if (file == null || !file.exists()) {
if (!filename.contains("../")) { if (!filename.contains("../")) {
dir = this.worldEdit.getWorkingDirectoryFile(config.saveDir); dir = this.worldEdit.getWorkingDirectoryFile(config.saveDir);
f = MainUtil.resolve(dir, filename, format, false); file = MainUtil.resolve(dir, filename, format, false);
} }
} }
if (f == null || !f.exists() || !MainUtil.isInSubDirectory(working, f)) { if (file == null || !file.exists() || !MainUtil.isInSubDirectory(saveDir, file)) {
player.printError("Schematic " + filename + " does not exist! (" + (f != null && f.exists()) + "|" + f + "|" + (f != null && !MainUtil.isInSubDirectory(working, f)) + ")"); player.printError("Schematic " + filename + " does not exist! (" + (file != null && file.exists()) + "|" + file + "|" + (file != null && !MainUtil.isInSubDirectory(saveDir, file)) + ")");
return; return;
} }
if (format == null) { if (format == null) {
format = ClipboardFormats.findByFile(f); format = ClipboardFormats.findByFile(file);
if (format == null) { if (format == null) {
BBC.CLIPBOARD_INVALID_FORMAT.send(player, f.getName()); BBC.CLIPBOARD_INVALID_FORMAT.send(player, file.getName());
return; return;
} }
} }
in = new FileInputStream(f); in = new FileInputStream(file);
uri = f.toURI(); uri = file.toURI();
} }
format.hold(player, uri, in); format.hold(player, uri, in);
BBC.SCHEMATIC_LOADED.send(player, filename); BBC.SCHEMATIC_LOADED.send(player, filename);
@ -418,7 +404,8 @@ public class SchematicCommands {
continue; continue;
} }
if (Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS && (!MainUtil.isInSubDirectory(dir, destFile) || !MainUtil.isInSubDirectory(dir, source)) && !player.hasPermission("worldedit.schematic.delete.other")) { if (Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS && (!MainUtil.isInSubDirectory(dir, destFile) || !MainUtil.isInSubDirectory(dir, source)) && !player.hasPermission("worldedit.schematic.delete.other")) {
BBC.SCHEMATIC_MOVE_FAILED.send(player, destFile, BBC.NO_PERM.f("worldedit.schematic.move.other")); BBC.SCHEMATIC_MOVE_FAILED.send(player, destFile,
BBC.NO_PERM.format("worldedit.schematic.move.other"));
continue; continue;
} }
try { try {
@ -522,7 +509,7 @@ public class SchematicCommands {
" -f <format> restricts by format\n" " -f <format> restricts by format\n"
) )
@CommandPermissions("worldedit.schematic.show") @CommandPermissions("worldedit.schematic.show")
public void show(Player player, InjectedValueAccess args, @Switch(name='f', desc = "TODO") String formatName) { public void show(Player player, InjectedValueAccess args, @Switch(name='f', desc = "") String formatName) {
FawePlayer fp = FawePlayer.wrap(player); FawePlayer fp = FawePlayer.wrap(player);
if (args.argsLength() == 0) { if (args.argsLength() == 0) {
if (fp.getSession().getVirtualWorld() != null) fp.setVirtualWorld(null); if (fp.getSession().getVirtualWorld() != null) fp.setVirtualWorld(null);
@ -586,66 +573,65 @@ public class SchematicCommands {
public void list(FawePlayer fp, Actor actor, InjectedValueAccess args, public void list(FawePlayer fp, Actor actor, InjectedValueAccess args,
@ArgFlag(name = 'p', desc = "Page to view.", def = "1") @ArgFlag(name = 'p', desc = "Page to view.", def = "1")
int page, int page,
@Switch(name = 'd', desc = "Sort by date, oldest first")
boolean oldFirst,
@Switch(name = 'n', desc = "Sort by date, newest first")
boolean newFirst,
@Switch(name = 'f', desc = "Restricts by format.") @Switch(name = 'f', desc = "Restricts by format.")
String formatName) throws WorldEditException { String formatName,
LocalConfiguration config = worldEdit.getConfiguration(); @Arg(name = "filter", desc = "Filter for schematics", def = "all")
File dir = worldEdit.getWorkingDirectoryFile(config.saveDir); String filter) throws WorldEditException {
if (oldFirst && newFirst) {
String schemCmd = "/" + Commands.getAlias(SchematicCommands.class, "schematic"); throw new StopExecutionException(TextComponent.of("Cannot sort by oldest and newest."));
String loadSingle = schemCmd + " " + Commands.getAlias(SchematicCommands.class, "load");
String loadMulti = schemCmd + " " + Commands.getAlias(SchematicCommands.class, "loadall");
String unload = schemCmd + " " + Commands.getAlias(SchematicCommands.class, "unload");
String delete = schemCmd + " " + Commands.getAlias(SchematicCommands.class, "delete");
String list = schemCmd + " " + Commands.getAlias(SchematicCommands.class, "list");
String showCmd = schemCmd + " " + Commands.getAlias(SchematicCommands.class, "show");
URIClipboardHolder multi = as(URIClipboardHolder.class, fp.getSession().getExistingClipboard());
final boolean hasShow = actor.hasPermission("worldedit.schematic.show");
UtilityCommands.list(dir, actor, args, page, -1, formatName, Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS, new RunnableVal3<Message, URI, String>() {
@Override
public void run(Message msg, URI uri, String relFilePath) {
boolean isDir = false;
boolean loaded = multi != null && multi.contains(uri);
String name = relFilePath;
String uriStr = uri.toString();
if (uriStr.startsWith("file:/")) {
File file = new File(uri.getPath());
name = file.getName();
try {
if (!MainUtil.isInSubDirectory(dir, file)) {
throw new RuntimeException(new CommandException("Invalid path"));
} }
} catch (IOException ignore) {} final String saveDir = worldEdit.getConfiguration().saveDir;
if (file.isDirectory()) { final int sortType = oldFirst ? -1 : newFirst ? 1 : 0;
isDir = true;
} else if (name.indexOf('.') != -1) {
name = name.substring(0, name.lastIndexOf('.'));
}
} // url
msg.text(" - "); final String pageCommand = actor.isPlayer()
? "//schem list -p %page%" + (sortType == -1 ? " -d" : sortType == 1 ? " -n" : "") : null;
if (msg.supportsInteraction()) { WorldEditAsyncCommandBuilder.createAndSendMessage(actor,
if (loaded) { new SchematicListTask(saveDir, sortType, page, pageCommand, filter, formatName), "(Please wait... gathering schematic list.)");
msg.text("[-]").command(unload + " " + relFilePath).tooltip("Unload");
} else { // UtilityCommands.list(dir, actor, args, page, -1, formatName, Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS, new RunnableVal3<Message, URI, String>() {
msg.text("[+]").command(loadMulti + " " + relFilePath).tooltip("Add to clipboard"); // @Override
} // public void run(Message msg, URI uri, String relFilePath) {
if (!isDir) msg.text("[X]").suggest("/" + delete + " " + relFilePath).tooltip("Delete"); // boolean isDir = false;
else if (hasShow) msg.text("[O]").command(showCmd + " " + args.getJoinedStrings(0) + " " + relFilePath).tooltip("Show"); // boolean loaded = multi != null && multi.contains(uri);
msg.text(name); //
if (isDir) { // String name = relFilePath;
msg.command(list + " " + relFilePath).tooltip("List"); // String uriStr = uri.toString();
} else { // if (uriStr.startsWith("file:/")) {
msg.command(loadSingle + " " + relFilePath).tooltip("Load"); // File file1 = new File(uri.getPath());
} // name = file1.getName();
} else { // try {
msg.text(name); // if (!MainUtil.isInSubDirectory(dir, file1)) {
} // throw new RuntimeException(new CommandException("Invalid path"));
} // }
}); // } catch (IOException ignore) {}
// if (file1.isDirectory()) {
// isDir = true;
// } else if (name.indexOf('.') != -1) {
// name = name.substring(0, name.lastIndexOf('.'));
// }
// } // url
//
// msg.text(" - ");
//
// if (loaded) {
// msg.text("[-]").command(unload + " " + relFilePath).tooltip("Unload");
// } else {
// msg.text("[+]").command(loadMulti + " " + relFilePath).tooltip("Add to clipboard");
// }
// if (!isDir) msg.text("[X]").suggest("/" + delete + " " + relFilePath).tooltip("Delete");
// msg.text(name);
// if (isDir) {
// msg.command(list + " " + relFilePath).tooltip("List");
// } else {
// msg.command(loadSingle + " " + relFilePath).tooltip("Load");
// }
// }
// });
} }
private static class SchematicLoadTask implements Callable<ClipboardHolder> { private static class SchematicLoadTask implements Callable<ClipboardHolder> {
@ -734,18 +720,24 @@ public class SchematicCommands {
private final int page; private final int page;
private final File rootDir; private final File rootDir;
private final String pageCommand; private final String pageCommand;
private final String filter;
private String formatName;
SchematicListTask(String prefix, int sortType, int page, String pageCommand) { SchematicListTask(String prefix, int sortType, int page, String pageCommand,
String filter, String formatName) {
this.prefix = prefix; this.prefix = prefix;
this.sortType = sortType; this.sortType = sortType;
this.page = page; this.page = page;
this.rootDir = WorldEdit.getInstance().getWorkingDirectoryFile(prefix); this.rootDir = WorldEdit.getInstance().getWorkingDirectoryFile(prefix);
this.pageCommand = pageCommand; this.pageCommand = pageCommand;
this.filter = filter;
this.formatName = formatName;
} }
@Override @Override
public Component call() throws Exception { public Component call() throws Exception {
List<File> fileList = allFiles(rootDir); ClipboardFormat format = ClipboardFormats.findByAlias(formatName);
List<File> fileList = getFiles(rootDir,filter,format);
if (fileList == null || fileList.isEmpty()) { if (fileList == null || fileList.isEmpty()) {
return ErrorFormat.wrap("No schematics found."); return ErrorFormat.wrap("No schematics found.");
@ -776,13 +768,18 @@ public class SchematicCommands {
} }
} }
private static List<File> allFiles(File root) { //TODO filtering for directories, global, and private scheamtics needs to be reimplemented here
private static List<File> getFiles(File root, String filter, ClipboardFormat format) {
File[] files = root.listFiles(); File[] files = root.listFiles();
if (files == null) return null; if (files == null) return null;
//Only get the files that match the format parameter
if (format != null) {
files = Arrays.stream(files).filter(format::isFormat).toArray(File[]::new);
}
List<File> fileList = new ArrayList<>(); List<File> fileList = new ArrayList<>();
for (File f : files) { for (File f : files) {
if (f.isDirectory()) { if (f.isDirectory()) {
List<File> subFiles = allFiles(f); List<File> subFiles = getFiles(f, filter, format);
if (subFiles == null) continue; // empty subdir if (subFiles == null) continue; // empty subdir
fileList.addAll(subFiles); fileList.addAll(subFiles);
} else { } else {

View File

@ -554,7 +554,7 @@ public class SelectionCommands {
newSelector = new Polygonal2DRegionSelector(oldSelector); newSelector = new Polygonal2DRegionSelector(oldSelector);
player.print(BBC.SEL_2D_POLYGON.s()); player.print(BBC.SEL_2D_POLYGON.s());
Optional<Integer> limit = ActorSelectorLimits.forActor(player).getPolygonVertexLimit(); Optional<Integer> limit = ActorSelectorLimits.forActor(player).getPolygonVertexLimit();
limit.ifPresent(integer -> player.print(BBC.SEL_MAX.f(integer))); limit.ifPresent(integer -> player.print(BBC.SEL_MAX.format(integer)));
break; break;
} }
case ELLIPSOID: case ELLIPSOID:
@ -575,14 +575,14 @@ public class SelectionCommands {
newSelector = new ConvexPolyhedralRegionSelector(oldSelector); newSelector = new ConvexPolyhedralRegionSelector(oldSelector);
player.print(BBC.SEL_CONVEX_POLYHEDRAL.s()); player.print(BBC.SEL_CONVEX_POLYHEDRAL.s());
Optional<Integer> limit = ActorSelectorLimits.forActor(player).getPolyhedronVertexLimit(); Optional<Integer> limit = ActorSelectorLimits.forActor(player).getPolyhedronVertexLimit();
limit.ifPresent(integer -> player.print(BBC.SEL_MAX.f(integer))); limit.ifPresent(integer -> player.print(BBC.SEL_MAX.format(integer)));
break; break;
} }
case POLYHEDRAL: case POLYHEDRAL:
newSelector = new PolyhedralRegionSelector(player.getWorld()); newSelector = new PolyhedralRegionSelector(player.getWorld());
player.print(BBC.SEL_CONVEX_POLYHEDRAL.s()); player.print(BBC.SEL_CONVEX_POLYHEDRAL.s());
Optional<Integer> limit = ActorSelectorLimits.forActor(player).getPolyhedronVertexLimit(); Optional<Integer> limit = ActorSelectorLimits.forActor(player).getPolyhedronVertexLimit();
limit.ifPresent(integer -> player.print(BBC.SEL_MAX.f(integer))); limit.ifPresent(integer -> player.print(BBC.SEL_MAX.format(integer)));
player.print(BBC.SEL_LIST.s()); player.print(BBC.SEL_LIST.s());
break; break;
case FUZZY: case FUZZY:
@ -591,8 +591,8 @@ public class SelectionCommands {
mask = new IdMask(world); mask = new IdMask(world);
} }
newSelector = new FuzzyRegionSelector(player, editSession, mask); newSelector = new FuzzyRegionSelector(player, editSession, mask);
player.print(BBC.SEL_FUZZY.f()); player.print(BBC.SEL_FUZZY.s());
player.print(BBC.SEL_LIST.f()); player.print(BBC.SEL_LIST.s());
break; break;
case LIST: case LIST:
default: default:

View File

@ -188,14 +188,11 @@ public class UtilityCommands {
@Arg(desc = "The blocks to fill with") @Arg(desc = "The blocks to fill with")
Pattern pattern, Pattern pattern,
@Arg(desc = "The radius to fill in") @Arg(desc = "The radius to fill in")
double radius, @Range(min = 1) double radius,
@Arg(desc = "The depth to fill", def = "1") @Arg(desc = "The depth to fill", def = "1")
int depth, @Range(min = 1) int depth,
@Arg(desc = "Direction to fill", def = "down") @Arg(desc = "Direction to fill", def = "down") BlockVector3 direction) throws WorldEditException {
BlockVector3 direction) throws WorldEditException {
radius = Math.max(1, radius);
we.checkMaxRadius(radius); we.checkMaxRadius(radius);
depth = Math.max(1, depth);
BlockVector3 pos = session.getPlacementPosition(player); BlockVector3 pos = session.getPlacementPosition(player);
int affected = editSession.fillDirection(pos, pattern, radius, depth, direction); int affected = editSession.fillDirection(pos, pattern, radius, depth, direction);
@ -284,10 +281,9 @@ public class UtilityCommands {
@Arg(desc = "The blocks to fill with") @Arg(desc = "The blocks to fill with")
Pattern pattern, Pattern pattern,
@Arg(desc = "The radius to fill in") @Arg(desc = "The radius to fill in")
double radius, @Range(min = 1) double radius,
@Arg(desc = "The depth to fill", def = "") @Arg(desc = "The depth to fill", def = "")
Integer depth) throws WorldEditException { @Range(min = 1) Integer depth) throws WorldEditException {
radius = Math.max(1, radius);
we.checkMaxRadius(radius); we.checkMaxRadius(radius);
depth = depth == null ? Integer.MAX_VALUE : Math.max(1, depth); depth = depth == null ? Integer.MAX_VALUE : Math.max(1, depth);
we.checkMaxRadius(radius); we.checkMaxRadius(radius);
@ -306,10 +302,9 @@ public class UtilityCommands {
@Logging(PLACEMENT) @Logging(PLACEMENT)
public int drain(Player player, LocalSession session, EditSession editSession, public int drain(Player player, LocalSession session, EditSession editSession,
@Arg(desc = "The radius to drain") @Arg(desc = "The radius to drain")
double radius, @Range(min = 0) double radius,
@Switch(name = 'w', desc = "Also un-waterlog blocks") @Switch(name = 'w', desc = "Also un-waterlog blocks")
boolean waterlogged) throws WorldEditException { boolean waterlogged) throws WorldEditException {
radius = Math.max(0, radius);
we.checkMaxRadius(radius); we.checkMaxRadius(radius);
int affected = editSession.drainArea( int affected = editSession.drainArea(
session.getPlacementPosition(player), radius, waterlogged); session.getPlacementPosition(player), radius, waterlogged);
@ -326,8 +321,7 @@ public class UtilityCommands {
@Logging(PLACEMENT) @Logging(PLACEMENT)
public int fixLava(Player player, LocalSession session, EditSession editSession, public int fixLava(Player player, LocalSession session, EditSession editSession,
@Arg(desc = "The radius to fix in") @Arg(desc = "The radius to fix in")
double radius) throws WorldEditException { @Range(min = 0) double radius) throws WorldEditException {
radius = Math.max(0, radius);
we.checkMaxRadius(radius); we.checkMaxRadius(radius);
int affected = editSession.fixLiquid(session.getPlacementPosition(player), radius, BlockTypes.LAVA); int affected = editSession.fixLiquid(session.getPlacementPosition(player), radius, BlockTypes.LAVA);
player.print(affected + " block(s) have been changed."); player.print(affected + " block(s) have been changed.");
@ -360,14 +354,10 @@ public class UtilityCommands {
@Logging(PLACEMENT) @Logging(PLACEMENT)
public int removeAbove(Player player, LocalSession session, EditSession editSession, public int removeAbove(Player player, LocalSession session, EditSession editSession,
@Arg(desc = "The apothem of the square to remove from", def = "1") @Arg(desc = "The apothem of the square to remove from", def = "1")
int size, @Range(min = 1) int size,
@Arg(desc = "The maximum height above you to remove from", def = "") @Arg(desc = "The maximum height above you to remove from", def = "")
Integer height) throws WorldEditException { Integer height) throws WorldEditException {
size = Math.max(1, size);
we.checkMaxRadius(size); we.checkMaxRadius(size);
World world = player.getWorld();
height = height != null ? Math.min((world.getMaxY() + 1), height + 1) : (world.getMaxY() + 1);
int affected = editSession.removeAbove(session.getPlacementPosition(player), size, height); int affected = editSession.removeAbove(session.getPlacementPosition(player), size, height);
BBC.VISITOR_BLOCK.send(player, affected); BBC.VISITOR_BLOCK.send(player, affected);
return affected; return affected;
@ -382,10 +372,9 @@ public class UtilityCommands {
@Logging(PLACEMENT) @Logging(PLACEMENT)
public int removeBelow(Player player, LocalSession session, EditSession editSession, public int removeBelow(Player player, LocalSession session, EditSession editSession,
@Arg(desc = "The apothem of the square to remove from", def = "1") @Arg(desc = "The apothem of the square to remove from", def = "1")
int size, @Range(min =1) int size,
@Arg(desc = "The maximum height below you to remove from", def = "") @Arg(desc = "The maximum height below you to remove from", def = "")
Integer height) throws WorldEditException { Integer height) throws WorldEditException {
size = Math.max(1, size);
we.checkMaxRadius(size); we.checkMaxRadius(size);
World world = player.getWorld(); World world = player.getWorld();
height = height != null ? Math.min((world.getMaxY() + 1), height + 1) : (world.getMaxY() + 1); height = height != null ? Math.min((world.getMaxY() + 1), height + 1) : (world.getMaxY() + 1);
@ -406,8 +395,7 @@ public class UtilityCommands {
@Arg(desc = "The mask of blocks to remove") @Arg(desc = "The mask of blocks to remove")
Mask mask, Mask mask,
@Arg(desc = "The radius of the square to remove from", def = "50") @Arg(desc = "The radius of the square to remove from", def = "50")
int radius) throws WorldEditException { @Range(min=1) int radius) throws WorldEditException {
radius = Math.max(1, radius);
we.checkMaxRadius(radius); we.checkMaxRadius(radius);
int affected = editSession.removeNear(session.getPlacementPosition(player), mask, radius); int affected = editSession.removeNear(session.getPlacementPosition(player), mask, radius);
@ -424,12 +412,11 @@ public class UtilityCommands {
@Logging(PLACEMENT) @Logging(PLACEMENT)
public int replaceNear(Player player, LocalSession session, EditSession editSession, public int replaceNear(Player player, LocalSession session, EditSession editSession,
@Arg(desc = "The radius of the square to remove in") @Arg(desc = "The radius of the square to remove in")
int radius, @Range(min=1) int radius,
@Arg(desc = "The mask matching blocks to remove", def = "") @Arg(desc = "The mask matching blocks to remove", def = "")
Mask from, Mask from,
@Arg(desc = "The pattern of blocks to replace with") @Arg(desc = "The pattern of blocks to replace with")
Pattern to) throws WorldEditException { Pattern to) throws WorldEditException {
radius = Math.max(1, radius);
we.checkMaxRadius(radius); we.checkMaxRadius(radius);
BlockVector3 base = session.getPlacementPosition(player); BlockVector3 base = session.getPlacementPosition(player);
@ -455,8 +442,7 @@ public class UtilityCommands {
@Logging(PLACEMENT) @Logging(PLACEMENT)
public int snow(Player player, LocalSession session, EditSession editSession, public int snow(Player player, LocalSession session, EditSession editSession,
@Arg(desc = "The radius of the circle to snow in", def = "10") @Arg(desc = "The radius of the circle to snow in", def = "10")
double size) throws WorldEditException { @Range(min=1) double size) throws WorldEditException {
size = Math.max(1, size);
we.checkMaxRadius(size); we.checkMaxRadius(size);
int affected = editSession.simulateSnow(session.getPlacementPosition(player), size); int affected = editSession.simulateSnow(session.getPlacementPosition(player), size);
@ -473,12 +459,11 @@ public class UtilityCommands {
@Logging(PLACEMENT) @Logging(PLACEMENT)
public int thaw(Player player, LocalSession session, EditSession editSession, public int thaw(Player player, LocalSession session, EditSession editSession,
@Arg(desc = "The radius of the circle to thaw in", def = "10") @Arg(desc = "The radius of the circle to thaw in", def = "10")
double size) throws WorldEditException { @Range(min=1) double size) throws WorldEditException {
size = Math.max(1, size);
we.checkMaxRadius(size); we.checkMaxRadius(size);
int affected = editSession.thaw(session.getPlacementPosition(player), size); int affected = editSession.thaw(session.getPlacementPosition(player), size);
player.print(affected + " surface(s) thawed."); player.print(affected + " surfaces thawed.");
return affected; return affected;
} }
@ -491,10 +476,9 @@ public class UtilityCommands {
@Logging(PLACEMENT) @Logging(PLACEMENT)
public int green(Player player, LocalSession session, EditSession editSession, public int green(Player player, LocalSession session, EditSession editSession,
@Arg(desc = "The radius of the circle to convert in", def = "10") @Arg(desc = "The radius of the circle to convert in", def = "10")
double size, @Range(min=1) double size,
@Switch(name = 'f', desc = "Also convert coarse dirt") @Switch(name = 'f', desc = "Also convert coarse dirt")
boolean convertCoarse) throws WorldEditException { boolean convertCoarse) throws WorldEditException {
size = Math.max(1, size);
we.checkMaxRadius(size); we.checkMaxRadius(size);
final boolean onlyNormalDirt = !convertCoarse; final boolean onlyNormalDirt = !convertCoarse;
@ -512,12 +496,12 @@ public class UtilityCommands {
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void extinguish(Player player, LocalSession session, EditSession editSession, public void extinguish(Player player, LocalSession session, EditSession editSession,
@Arg(desc = "The radius of the square to remove in", def = "") @Arg(desc = "The radius of the square to remove in", def = "")
Integer radius) throws WorldEditException { @Range(min=1) Integer radius) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
int defaultRadius = config.maxRadius != -1 ? Math.min(40, config.maxRadius) : 40; int defaultRadius = config.maxRadius != -1 ? Math.min(40, config.maxRadius) : 40;
int size = radius != null ? Math.max(1, radius) : defaultRadius; int size = radius != null ? radius : defaultRadius;
we.checkMaxRadius(size); we.checkMaxRadius(size);
Mask mask = new BlockTypeMask(editSession, BlockTypes.FIRE); Mask mask = new BlockTypeMask(editSession, BlockTypes.FIRE);
@ -673,8 +657,7 @@ public class UtilityCommands {
return; return;
} }
WorldEditAsyncCommandBuilder.createAndSendMessage(actor, () -> { WorldEditAsyncCommandBuilder.createAndSendMessage(actor, () -> {
double result = expression.evaluate( double result = expression.evaluateTimeout(WorldEdit.getInstance().getSessionManager().get(actor).getTimeout());
new double[]{}, WorldEdit.getInstance().getSessionManager().get(actor).getTimeout());
String formatted = Double.isNaN(result) ? "NaN" : formatter.format(result); String formatted = Double.isNaN(result) ? "NaN" : formatter.format(result);
return SubtleFormat.wrap(input + " = ").append(TextComponent.of(formatted, TextColor.LIGHT_PURPLE)); return SubtleFormat.wrap(input + " = ").append(TextComponent.of(formatted, TextColor.LIGHT_PURPLE));
}, null); }, null);
@ -804,7 +787,7 @@ public class UtilityCommands {
page = args.getInteger(--len); page = args.getInteger(--len);
} }
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
String arg = args.getString(i); String arg = "";
switch (arg.toLowerCase()) { switch (arg.toLowerCase()) {
case "me": case "me":
case "mine": case "mine":