Refactor confirmation

This commit is contained in:
Jesse Boyd 2019-11-21 06:50:37 +00:00
parent 444aa0dda7
commit 52a502a1c6
No known key found for this signature in database
GPG Key ID: 59F1DE6293AF6E1F
22 changed files with 782 additions and 575 deletions

View File

@ -341,19 +341,19 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
} }
} }
@Override // @Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String commandLabel, String[] args) { // public List<String> onTabComplete(CommandSender sender, Command cmd, String commandLabel, String[] args) {
// Add the command to the array because the underlying command handling // // Add the command to the array because the underlying command handling
// code of WorldEdit expects it // // code of WorldEdit expects it
String[] split = new String[args.length + 1]; // String[] split = new String[args.length + 1];
System.arraycopy(args, 0, split, 1, args.length); // System.arraycopy(args, 0, split, 1, args.length);
split[0] = commandLabel; // split[0] = commandLabel;
//
String arguments = Joiner.on(" ").join(split); // String arguments = Joiner.on(" ").join(split);
CommandSuggestionEvent event = new CommandSuggestionEvent(wrapCommandSender(sender), arguments); // CommandSuggestionEvent event = new CommandSuggestionEvent(wrapCommandSender(sender), arguments);
getWorldEdit().getEventBus().post(event); // getWorldEdit().getEventBus().post(event);
return CommandUtil.fixSuggestions(arguments, event.getSuggestions()); // return CommandUtil.fixSuggestions(arguments, event.getSuggestions());
} // }
private void fail(Runnable run, String message) { private void fail(Runnable run, String message) {
try { try {

View File

@ -4,9 +4,7 @@ import com.boydti.fawe.util.StringMan;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.PlatformCommandManager; import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.internal.registry.InputParser; import com.sk89q.worldedit.internal.registry.InputParser;
import org.enginehub.piston.inject.InjectedValueAccess; import org.enginehub.piston.inject.InjectedValueAccess;
@ -29,9 +27,9 @@ public abstract class FaweParser<T> extends InputParser<T> {
input = prefix + " " + input; input = prefix + " " + input;
InjectedValueAccess injected = context.getInjected(); InjectedValueAccess injected = context.getInjected();
if (injected != null) { if (injected != null) {
return getPlatform().parse(input, injected); return getPlatform().parseCommand(input, injected);
} else { } else {
return getPlatform().parse(input, context.getActor()); return getPlatform().parseCommand(input, context.getActor());
} }
} }

View File

@ -265,7 +265,8 @@ public enum BBC {
WORLDEDIT_SOME_FAILS_BLOCKBAG("Missing blocks: %s0", "Error"), WORLDEDIT_SOME_FAILS_BLOCKBAG("Missing blocks: %s0", "Error"),
WORLDEDIT_CANCEL_COUNT("Cancelled %s0 edits.", "Cancel"), WORLDEDIT_CANCEL_COUNT("Cancelled %s0 edits.", "Cancel"),
WORLDEDIT_CANCEL_REASON_CONFIRM("Your selection is large (%s0 -> %s1, containing %s3 blocks). Use //confirm to execute %s2", "Cancel"), WORLDEDIT_CANCEL_REASON_CONFIRM("Use //confirm to execute %s2", "Cancel"),
WORLDEDIT_CANCEL_REASON_CONFIRM_REGION("Your selection is large (%s0 -> %s1, containing %s3 blocks). Use //confirm to execute %s2", "Cancel"),
WORLDEDIT_CANCEL_REASON("Your WorldEdit action was cancelled: %s0.", "Cancel"), WORLDEDIT_CANCEL_REASON("Your WorldEdit action was cancelled: %s0.", "Cancel"),
WORLDEDIT_CANCEL_REASON_MANUAL("Manual cancellation", "Cancel"), WORLDEDIT_CANCEL_REASON_MANUAL("Manual cancellation", "Cancel"),
WORLDEDIT_CANCEL_REASON_LOW_MEMORY("Low memory", "Cancel"), WORLDEDIT_CANCEL_REASON_LOW_MEMORY("Low memory", "Cancel"),

View File

@ -63,7 +63,7 @@ public class BrushSettings {
if (constructor == null) { if (constructor == null) {
return new BrushSettings(); return new BrushSettings();
} }
BrushSettings bs = manager.parse(constructor, player); BrushSettings bs = manager.parseCommand(constructor, player);
bs.constructor.put(SettingType.BRUSH, constructor); bs.constructor.put(SettingType.BRUSH, constructor);
if (settings.containsKey(SettingType.PERMISSIONS.name())) { if (settings.containsKey(SettingType.PERMISSIONS.name())) {
bs.permissions.addAll((Collection<? extends String>) settings.get(SettingType.PERMISSIONS.name())); bs.permissions.addAll((Collection<? extends String>) settings.get(SettingType.PERMISSIONS.name()));

View File

@ -0,0 +1,34 @@
package com.boydti.fawe.util.task;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import static com.google.common.base.Preconditions.checkNotNull;
public class InterruptableCondition {
private final Condition condition;
private final Thread thread;
private final Lock lock;
public InterruptableCondition(Lock lock, Condition condition, Thread thread) {
checkNotNull(condition);
checkNotNull(thread);
checkNotNull(lock);
this.lock = lock;
this.condition = condition;
this.thread = thread;
}
public void signal() {
try {
lock.lock();
condition.signalAll();
} finally {
lock.unlock();
}
}
public void interrupt() {
this.thread.interrupt();
}
}

View File

@ -30,7 +30,6 @@ import com.boydti.fawe.object.RunnableVal;
import com.boydti.fawe.object.clipboard.MultiClipboardHolder; import com.boydti.fawe.object.clipboard.MultiClipboardHolder;
import com.boydti.fawe.object.clipboard.ReadOnlyClipboard; import com.boydti.fawe.object.clipboard.ReadOnlyClipboard;
import com.boydti.fawe.object.clipboard.URIClipboardHolder; import com.boydti.fawe.object.clipboard.URIClipboardHolder;
import com.boydti.fawe.object.clipboard.WorldCutClipboard;
import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.object.exception.FaweException;
import com.boydti.fawe.object.io.FastByteArrayOutputStream; import com.boydti.fawe.object.io.FastByteArrayOutputStream;
import com.boydti.fawe.util.ImgurUtility; import com.boydti.fawe.util.ImgurUtility;
@ -44,10 +43,10 @@ import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.util.CommandPermissions; import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.command.util.Logging; import com.sk89q.worldedit.command.util.Logging;
import com.sk89q.worldedit.command.util.annotation.Confirm;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.extent.PasteEvent; import com.sk89q.worldedit.event.extent.PasteEvent;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.Extent;
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.BuiltInClipboardFormat;
@ -74,7 +73,6 @@ import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector; import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import org.enginehub.piston.annotation.Command; import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer; import org.enginehub.piston.annotation.CommandContainer;
@ -92,7 +90,6 @@ import java.net.URLEncoder;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.function.Supplier;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
import static com.sk89q.worldedit.command.util.Logging.LogMode.REGION; import static com.sk89q.worldedit.command.util.Logging.LogMode.REGION;
@ -113,6 +110,7 @@ public class ClipboardCommands {
desc = "Copy the selection to the clipboard" desc = "Copy the selection to the clipboard"
) )
@CommandPermissions("worldedit.clipboard.copy") @CommandPermissions("worldedit.clipboard.copy")
@Confirm(Confirm.Processor.REGION)
public void copy(Actor actor, LocalSession session, EditSession editSession, public void copy(Actor actor, LocalSession session, EditSession editSession,
@Selection Region region, @Selection Region region,
@Switch(name = 'e', desc = "Skip copy entities") @Switch(name = 'e', desc = "Skip copy entities")
@ -120,7 +118,7 @@ public class ClipboardCommands {
@Switch(name = 'b', desc = "Also copy biomes") @Switch(name = 'b', desc = "Also copy biomes")
boolean copyBiomes, boolean copyBiomes,
@ArgFlag(name = 'm', desc = "Set the exclude mask, matching blocks become air", def = "") @ArgFlag(name = 'm', desc = "Set the exclude mask, matching blocks become air", def = "")
Mask mask, InjectedValueAccess context) throws WorldEditException { Mask mask) throws WorldEditException {
BlockVector3 min = region.getMinimumPoint(); BlockVector3 min = region.getMinimumPoint();
BlockVector3 max = region.getMaximumPoint(); BlockVector3 max = region.getMaximumPoint();
@ -130,33 +128,31 @@ public class ClipboardCommands {
if (volume >= limit.MAX_CHECKS) { if (volume >= limit.MAX_CHECKS) {
throw FaweCache.MAX_CHECKS; throw FaweCache.MAX_CHECKS;
} }
actor.checkConfirmationRegion(() -> { session.setClipboard(null);
session.setClipboard(null);
Clipboard clipboard = new BlockArrayClipboard(region, actor.getUniqueId()); Clipboard clipboard = new BlockArrayClipboard(region, actor.getUniqueId());
session.setClipboard(new ClipboardHolder(clipboard)); session.setClipboard(new ClipboardHolder(clipboard));
clipboard.setOrigin(session.getPlacementPosition(actor)); clipboard.setOrigin(session.getPlacementPosition(actor));
ForwardExtentCopy copy = new ForwardExtentCopy(editSession, region, clipboard, region.getMinimumPoint()); ForwardExtentCopy copy = new ForwardExtentCopy(editSession, region, clipboard, region.getMinimumPoint());
copy.setCopyingEntities(!skipEntities); copy.setCopyingEntities(!skipEntities);
copy.setCopyingBiomes(copyBiomes); copy.setCopyingBiomes(copyBiomes);
Mask sourceMask = editSession.getSourceMask(); Mask sourceMask = editSession.getSourceMask();
if (sourceMask != null) { if (sourceMask != null) {
new MaskTraverser(sourceMask).reset(editSession); new MaskTraverser(sourceMask).reset(editSession);
copy.setSourceMask(sourceMask); copy.setSourceMask(sourceMask);
editSession.setSourceMask(null); editSession.setSourceMask(null);
} }
if (mask != null && mask != Masks.alwaysTrue()) { if (mask != null && mask != Masks.alwaysTrue()) {
copy.setSourceMask(mask); copy.setSourceMask(mask);
} }
Operations.completeLegacy(copy); Operations.completeLegacy(copy);
BBC.COMMAND_COPY.send(actor, region.getArea()); BBC.COMMAND_COPY.send(actor, region.getArea());
if (!actor.hasPermission("fawe.tips")) { if (!actor.hasPermission("fawe.tips")) {
BBC.TIP_PASTE.or(BBC.TIP_DOWNLOAD, BBC.TIP_ROTATE, BBC.TIP_COPYPASTE, BBC.TIP_REPLACE_MARKER, BBC.TIP_COPY_PATTERN).send(actor); BBC.TIP_PASTE.or(BBC.TIP_DOWNLOAD, BBC.TIP_ROTATE, BBC.TIP_COPYPASTE, BBC.TIP_REPLACE_MARKER, BBC.TIP_COPY_PATTERN).send(actor);
} }
}, "/copy", region, context);
} }
@Command( @Command(
@ -229,6 +225,7 @@ public class ClipboardCommands {
) )
@CommandPermissions("worldedit.clipboard.cut") @CommandPermissions("worldedit.clipboard.cut")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public void cut(Actor actor, LocalSession session, EditSession editSession, public void cut(Actor actor, LocalSession session, EditSession editSession,
@Selection Region region, @Selection Region region,
@Arg(desc = "Pattern to leave in place of the selection", def = "air") @Arg(desc = "Pattern to leave in place of the selection", def = "air")
@ -238,8 +235,7 @@ public class ClipboardCommands {
@Switch(name = 'b', desc = "Also copy biomes, source biomes are unaffected") @Switch(name = 'b', desc = "Also copy biomes, source biomes are unaffected")
boolean copyBiomes, boolean copyBiomes,
@ArgFlag(name = 'm', desc = "Set the exclude mask, matching blocks become air", def = "") @ArgFlag(name = 'm', desc = "Set the exclude mask, matching blocks become air", def = "")
Mask mask, Mask mask) throws WorldEditException {
InjectedValueAccess context) throws WorldEditException {
BlockVector3 min = region.getMinimumPoint(); BlockVector3 min = region.getMinimumPoint();
BlockVector3 max = region.getMaximumPoint(); BlockVector3 max = region.getMaximumPoint();
@ -251,35 +247,32 @@ public class ClipboardCommands {
if (volume >= limit.MAX_CHANGES) { if (volume >= limit.MAX_CHANGES) {
throw FaweCache.MAX_CHANGES; throw FaweCache.MAX_CHANGES;
} }
actor.checkConfirmationRegion(() -> { session.setClipboard(null);
session.setClipboard(null);
BlockArrayClipboard clipboard = new BlockArrayClipboard(region, actor.getUniqueId()); BlockArrayClipboard clipboard = new BlockArrayClipboard(region, actor.getUniqueId());
clipboard.setOrigin(session.getPlacementPosition(actor)); clipboard.setOrigin(session.getPlacementPosition(actor));
ForwardExtentCopy copy = new ForwardExtentCopy(editSession, region, clipboard, region.getMinimumPoint()); ForwardExtentCopy copy = new ForwardExtentCopy(editSession, region, clipboard, region.getMinimumPoint());
copy.setSourceFunction(new BlockReplace(editSession, leavePattern)); copy.setSourceFunction(new BlockReplace(editSession, leavePattern));
copy.setCopyingEntities(!skipEntities); copy.setCopyingEntities(!skipEntities);
copy.setRemovingEntities(true); copy.setRemovingEntities(true);
copy.setCopyingBiomes(copyBiomes); copy.setCopyingBiomes(copyBiomes);
Mask sourceMask = editSession.getSourceMask(); Mask sourceMask = editSession.getSourceMask();
if (sourceMask != null) { if (sourceMask != null) {
new MaskTraverser(sourceMask).reset(editSession); new MaskTraverser(sourceMask).reset(editSession);
copy.setSourceMask(sourceMask); copy.setSourceMask(sourceMask);
editSession.setSourceMask(null); editSession.setSourceMask(null);
} }
if (mask != null) { if (mask != null) {
copy.setSourceMask(mask); copy.setSourceMask(mask);
} }
Operations.completeLegacy(copy); Operations.completeLegacy(copy);
session.setClipboard(new ClipboardHolder(clipboard)); session.setClipboard(new ClipboardHolder(clipboard));
BBC.COMMAND_CUT_SLOW.send(actor, region.getArea());
if (!actor.hasPermission("fawe.tips")) {
BBC.TIP_LAZYCUT.send(actor);
}
}, "cut", region, context);
BBC.COMMAND_CUT_SLOW.send(actor, region.getArea());
if (!actor.hasPermission("fawe.tips")) {
BBC.TIP_LAZYCUT.send(actor);
}
} }
@Command( @Command(

View File

@ -37,6 +37,7 @@ import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.util.CommandPermissions; import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.command.util.Logging; import com.sk89q.worldedit.command.util.Logging;
import com.sk89q.worldedit.command.util.annotation.Confirm;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.function.generator.CavesGen; import com.sk89q.worldedit.function.generator.CavesGen;
@ -46,9 +47,7 @@ import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.visitor.RegionVisitor; import com.sk89q.worldedit.function.visitor.RegionVisitor;
import com.sk89q.worldedit.internal.annotation.Radii;
import com.sk89q.worldedit.internal.annotation.Selection; import com.sk89q.worldedit.internal.annotation.Selection;
import com.sk89q.worldedit.internal.expression.Expression;
import com.sk89q.worldedit.internal.expression.ExpressionException; import com.sk89q.worldedit.internal.expression.ExpressionException;
import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
@ -95,6 +94,7 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.caves") @CommandPermissions("worldedit.generation.caves")
@Logging(PLACEMENT) @Logging(PLACEMENT)
@Confirm(Confirm.Processor.REGION)
public void caves(Actor actor, LocalSession session, EditSession editSession, @Selection Region region, public void caves(Actor actor, LocalSession session, EditSession editSession, @Selection Region region,
@Arg(name = "size", desc = "TODO", def = "8") int sizeOpt, @Arg(name = "size", desc = "TODO", def = "8") int sizeOpt,
@Arg(name = "frequency", desc = "TODO", def = "40") int frequencyOpt, @Arg(name = "frequency", desc = "TODO", def = "40") int frequencyOpt,
@ -105,12 +105,10 @@ public class GenerationCommands {
@Arg(name = "individualRarity", desc = "TODO", def = "25") int individualRarityOpt, @Arg(name = "individualRarity", desc = "TODO", def = "25") int individualRarityOpt,
@Arg(name = "pocketChance", desc = "TODO", def = "0") int pocketChanceOpt, @Arg(name = "pocketChance", desc = "TODO", def = "0") int pocketChanceOpt,
@Arg(name = "pocketMin", desc = "TODO", def = "0") int pocketMinOpt, @Arg(name = "pocketMin", desc = "TODO", def = "0") int pocketMinOpt,
@Arg(name = "pocketMax", desc = "TODO", def = "3") int pocketMaxOpt, InjectedValueAccess context) throws WorldEditException { @Arg(name = "pocketMax", desc = "TODO", def = "3") int pocketMaxOpt) throws WorldEditException {
actor.checkConfirmationRegion(() -> { CavesGen gen = new CavesGen(sizeOpt, frequencyOpt, rarityOpt, minYOpt, maxYOpt, systemFrequencyOpt, individualRarityOpt, pocketChanceOpt, pocketMinOpt, pocketMaxOpt);
CavesGen gen = new CavesGen(sizeOpt, frequencyOpt, rarityOpt, minYOpt, maxYOpt, systemFrequencyOpt, individualRarityOpt, pocketChanceOpt, pocketMinOpt, pocketMaxOpt); editSession.generate(region, gen);
editSession.generate(region, gen); BBC.VISITOR_BLOCK.send(actor, editSession.getBlockChangeCount());
BBC.VISITOR_BLOCK.send(actor, editSession.getBlockChangeCount());
}, "/caves", region, context);
} }
@ -120,11 +118,10 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.ore") @CommandPermissions("worldedit.generation.ore")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void ores(Actor actor, LocalSession session, EditSession editSession, @Selection Region region, @Arg(desc = "Mask") Mask mask, InjectedValueAccess context) throws WorldEditException { @Confirm(Confirm.Processor.REGION)
actor.checkConfirmationRegion(() -> { public void ores(Actor actor, LocalSession session, EditSession editSession, @Selection Region region, @Arg(desc = "Mask") Mask mask) throws WorldEditException {
editSession.addOres(region, mask); editSession.addOres(region, mask);
BBC.VISITOR_BLOCK.send(actor, editSession.getBlockChangeCount()); BBC.VISITOR_BLOCK.send(actor, editSession.getBlockChangeCount());
}, "/ores", region, context);
} }
@Command( @Command(
@ -174,11 +171,10 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.ore") @CommandPermissions("worldedit.generation.ore")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void ore(Actor actor, LocalSession session, EditSession editSession, @Selection Region region, @Arg(desc = "Mask") Mask mask, @Arg(desc = "Pattern") Pattern material, @Arg(desc="Ore vein size") @Range(from = 0, to=Integer.MAX_VALUE) int size, int freq, @Range(from=0, to=100) int rarity, @Range(from=0, to=255) int minY, @Range(from=0, to=255) int maxY, InjectedValueAccess context) throws WorldEditException { @Confirm(Confirm.Processor.REGION)
actor.checkConfirmationRegion(() -> { public void ore(Actor actor, LocalSession session, EditSession editSession, @Selection Region region, @Arg(desc = "Mask") Mask mask, @Arg(desc = "Pattern") Pattern material, @Arg(desc="Ore vein size") @Range(from = 0, to=Integer.MAX_VALUE) int size, int freq, @Range(from=0, to=100) int rarity, @Range(from=0, to=255) int minY, @Range(from=0, to=255) int maxY) throws WorldEditException {
editSession.addOre(region, mask, material, size, freq, rarity, minY, maxY); editSession.addOre(region, mask, material, size, freq, rarity, minY, maxY);
BBC.VISITOR_BLOCK.send(actor, editSession.getBlockChangeCount()); BBC.VISITOR_BLOCK.send(actor, editSession.getBlockChangeCount());
}, "/ore", region, context);
} }
@Command( @Command(
@ -187,14 +183,14 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.cylinder") @CommandPermissions("worldedit.generation.cylinder")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void hcyl(Actor actor, LocalSession session, EditSession editSession, InjectedValueAccess context, public void hcyl(Actor actor, LocalSession session, EditSession editSession,
@Arg(desc = "The pattern of blocks to generate") @Arg(desc = "The pattern of blocks to generate")
Pattern pattern, Pattern pattern,
@Arg(desc = "The radii of the cylinder. 1st is N/S, 2nd is E/W") @Confirm(Confirm.Processor.RADIUS) @Arg(desc = "The radii of the cylinder. 1st is N/S, 2nd is E/W")
BlockVector2 radii, BlockVector2 radii,
@Arg(desc = "The height of the cylinder", def = "1") @Arg(desc = "The height of the cylinder", def = "1")
int height) throws WorldEditException { int height) throws WorldEditException {
cyl(actor, session, editSession, pattern, radii, height, true, context); cyl(actor, session, editSession, pattern, radii, height, true);
} }
@Command( @Command(
@ -206,18 +202,16 @@ public class GenerationCommands {
public void cyl(Actor actor, LocalSession session, EditSession editSession, public void cyl(Actor actor, LocalSession session, EditSession editSession,
@Arg(desc = "The pattern of blocks to generate") @Arg(desc = "The pattern of blocks to generate")
Pattern pattern, Pattern pattern,
@Arg(desc = "The radii of the cylinder. Order is N/S, E/W") BlockVector2 radius, @Confirm(Confirm.Processor.RADIUS) @Arg(desc = "The radii of the cylinder. Order is N/S, E/W") BlockVector2 radius,
@Arg(desc = "The height of the cylinder", def = "1") @Arg(desc = "The height of the cylinder", def = "1")
int height, int height,
@Switch(name = 'h', desc = "Make a hollow cylinder") @Switch(name = 'h', desc = "Make a hollow cylinder")
boolean hollow, InjectedValueAccess context) throws WorldEditException { boolean hollow) throws WorldEditException {
double max = Math.max(radius.getBlockX(), radius.getBlockZ()); double max = Math.max(radius.getBlockX(), radius.getBlockZ());
worldEdit.checkMaxRadius(max); worldEdit.checkMaxRadius(max);
BlockVector3 pos = session.getPlacementPosition(actor); BlockVector3 pos = session.getPlacementPosition(actor);
actor.checkConfirmationRadius(() -> { int affected = editSession.makeCylinder(pos, pattern, radius.getX(), radius.getZ(), Math.min(256, height), !hollow);
int affected = editSession.makeCylinder(pos, pattern, radius.getX(), radius.getZ(), Math.min(256, height), !hollow); BBC.VISITOR_BLOCK.send(actor, affected);
BBC.VISITOR_BLOCK.send(actor, affected);
}, "/cyl", (int) max, context);
} }
@Command( @Command(
@ -229,11 +223,10 @@ public class GenerationCommands {
public void hsphere(Actor actor, LocalSession session, EditSession editSession, public void hsphere(Actor actor, LocalSession session, EditSession editSession,
@Arg(desc = "The pattern of blocks to generate") @Arg(desc = "The pattern of blocks to generate")
Pattern pattern, Pattern pattern,
@Arg(desc = "The radii of the sphere. Order is N/S, U/D, E/W") BlockVector3 radii, @Confirm(Confirm.Processor.RADIUS) @Arg(desc = "The radii of the sphere. Order is N/S, U/D, E/W") BlockVector3 radii,
@Switch(name = 'r', desc = "Raise the bottom of the sphere to the placement position") @Switch(name = 'r', desc = "Raise the bottom of the sphere to the placement position")
boolean raised, boolean raised) throws WorldEditException {
InjectedValueAccess context) throws WorldEditException { sphere(actor, session, editSession, pattern, radii, raised, true);
sphere(actor, session, editSession, pattern, radii, raised, true, context);
} }
@Command( @Command(
@ -245,23 +238,21 @@ public class GenerationCommands {
public void sphere(Actor actor, LocalSession session, EditSession editSession, public void sphere(Actor actor, LocalSession session, EditSession editSession,
@Arg(desc = "The pattern of blocks to generate") @Arg(desc = "The pattern of blocks to generate")
Pattern pattern, Pattern pattern,
@Arg(desc = "The radii of the sphere. Order is N/S, U/D, E/W") @Confirm(Confirm.Processor.RADIUS) @Arg(desc = "The radii of the sphere. Order is N/S, U/D, E/W")
BlockVector3 radii, BlockVector3 radii,
@Switch(name = 'r', desc = "Raise the bottom of the sphere to the placement position") @Switch(name = 'r', desc = "Raise the bottom of the sphere to the placement position")
boolean raised, boolean raised,
@Switch(name = 'h', desc = "Make a hollow sphere") @Switch(name = 'h', desc = "Make a hollow sphere")
boolean hollow, InjectedValueAccess context) throws WorldEditException { boolean hollow) throws WorldEditException {
double max = MathMan.max(radii.getBlockX(), radii.getBlockY(), radii.getBlockZ()); double max = MathMan.max(radii.getBlockX(), radii.getBlockY(), radii.getBlockZ());
worldEdit.checkMaxRadius(max); worldEdit.checkMaxRadius(max);
BlockVector3 pos = session.getPlacementPosition(actor); BlockVector3 pos = session.getPlacementPosition(actor);
BlockVector3 finalPos = raised ? pos.add(0, radii.getY(), 0) : pos; BlockVector3 finalPos = raised ? pos.add(0, radii.getY(), 0) : pos;
actor.checkConfirmationRadius(() -> { int affected = editSession.makeSphere(finalPos, pattern, radii.getX(), radii.getY(), radii.getZ(), !hollow);
int affected = editSession.makeSphere(finalPos, pattern, radii.getX(), radii.getY(), radii.getZ(), !hollow); if (actor instanceof Player) {
if (actor instanceof Player) { ((Player) actor).findFreePosition();
((Player) actor).findFreePosition(); }
} BBC.VISITOR_BLOCK.send(actor, affected);
BBC.VISITOR_BLOCK.send(actor, affected);
}, "sphere", (int) max, context);
} }
@Command( @Command(
@ -312,9 +303,9 @@ public class GenerationCommands {
public void hollowPyramid(Actor actor, LocalSession session, EditSession editSession, public void hollowPyramid(Actor actor, LocalSession session, EditSession editSession,
@Arg(desc = "The pattern of blocks to set") @Arg(desc = "The pattern of blocks to set")
Pattern pattern, Pattern pattern,
@Arg(desc = "The size of the pyramid") @Confirm(Confirm.Processor.RADIUS) @Arg(desc = "The size of the pyramid")
int size, InjectedValueAccess context) throws WorldEditException { int size) throws WorldEditException {
pyramid(actor, session, editSession, pattern, size, true, context); pyramid(actor, session, editSession, pattern, size, true);
} }
@Command( @Command(
@ -326,20 +317,17 @@ public class GenerationCommands {
public void pyramid(Actor actor, LocalSession session, EditSession editSession, public void pyramid(Actor actor, LocalSession session, EditSession editSession,
@Arg(desc = "The pattern of blocks to set") @Arg(desc = "The pattern of blocks to set")
Pattern pattern, Pattern pattern,
@Arg(desc = "The size of the pyramid") @Confirm(Confirm.Processor.RADIUS) @Arg(desc = "The size of the pyramid")
int size, int size,
@Switch(name = 'h', desc = "Make a hollow pyramid") @Switch(name = 'h', desc = "Make a hollow pyramid")
boolean hollow, boolean hollow) throws WorldEditException {
InjectedValueAccess context) throws WorldEditException {
BlockVector3 pos = session.getPlacementPosition(actor); BlockVector3 pos = session.getPlacementPosition(actor);
worldEdit.checkMaxRadius(size); worldEdit.checkMaxRadius(size);
actor.checkConfirmationRadius(() -> { int affected = editSession.makePyramid(pos, pattern, size, !hollow);
int affected = editSession.makePyramid(pos, pattern, size, !hollow); if (actor instanceof Player) {
if (actor instanceof Player) { ((Player) actor).findFreePosition();
((Player) actor).findFreePosition(); }
} BBC.VISITOR_BLOCK.send(actor, affected);
BBC.VISITOR_BLOCK.send(actor, affected);
}, getArguments(context), size, context);
} }
@Command( @Command(
@ -350,6 +338,7 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.shape") @CommandPermissions("worldedit.generation.shape")
@Logging(ALL) @Logging(ALL)
@Confirm(Confirm.Processor.REGION)
public void generate(Actor actor, LocalSession session, EditSession editSession, public void generate(Actor actor, LocalSession session, EditSession editSession,
@Selection Region region, @Selection Region region,
@Arg(desc = "The pattern of blocks to set") @Arg(desc = "The pattern of blocks to set")
@ -363,8 +352,7 @@ public class GenerationCommands {
@Switch(name = 'o', desc = "Use the placement's coordinate origin") @Switch(name = 'o', desc = "Use the placement's coordinate origin")
boolean offset, boolean offset,
@Switch(name = 'c', desc = "Use the selection's center as origin") @Switch(name = 'c', desc = "Use the selection's center as origin")
boolean offsetCenter, boolean offsetCenter) throws WorldEditException {
InjectedValueAccess context) throws WorldEditException {
final Vector3 zero; final Vector3 zero;
Vector3 unit; Vector3 unit;
@ -395,17 +383,15 @@ public class GenerationCommands {
final Vector3 unit1 = unit; final Vector3 unit1 = unit;
actor.checkConfirmationRegion(() -> { try {
try { final int affected = editSession.makeShape(region, zero, unit1, pattern, String.join(" ", expression), hollow, session.getTimeout());
final int affected = editSession.makeShape(region, zero, unit1, pattern, String.join(" ", expression), hollow, session.getTimeout()); if (actor instanceof Player) {
if (actor instanceof Player) { ((Player) actor).findFreePosition();
((Player) actor).findFreePosition();
}
BBC.VISITOR_BLOCK.send(actor, affected);
} catch (ExpressionException e) {
actor.printError(e.getMessage());
} }
}, "/generate", region, context); BBC.VISITOR_BLOCK.send(actor, affected);
} catch (ExpressionException e) {
actor.printError(e.getMessage());
}
} }
@Command( @Command(
@ -418,6 +404,7 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.shape.biome") @CommandPermissions("worldedit.generation.shape.biome")
@Logging(ALL) @Logging(ALL)
@Confirm(Confirm.Processor.REGION)
public void generateBiome(Actor actor, LocalSession session, EditSession editSession, public void generateBiome(Actor actor, LocalSession session, EditSession editSession,
@Selection Region region, @Selection Region region,
@Arg(desc = "The biome type to set") @Arg(desc = "The biome type to set")
@ -431,8 +418,7 @@ public class GenerationCommands {
@Switch(name = 'o', desc = "Use the placement's coordinate origin") @Switch(name = 'o', desc = "Use the placement's coordinate origin")
boolean offset, boolean offset,
@Switch(name = 'c', desc = "Use the selection's center as origin") @Switch(name = 'c', desc = "Use the selection's center as origin")
boolean offsetCenter, boolean offsetCenter) throws WorldEditException {
InjectedValueAccess context) throws WorldEditException {
final Vector3 zero; final Vector3 zero;
Vector3 unit; Vector3 unit;
@ -461,14 +447,12 @@ public class GenerationCommands {
} }
final Vector3 unit1 = unit; final Vector3 unit1 = unit;
actor.checkConfirmationRegion(() -> { try {
try { final int affected = editSession.makeBiomeShape(region, zero, unit1, target, String.join(" ", expression), hollow, session.getTimeout());
final int affected = editSession.makeBiomeShape(region, zero, unit1, target, String.join(" ", expression), hollow, session.getTimeout()); BBC.VISITOR_FLAT.send(actor, affected);
BBC.VISITOR_FLAT.send(actor, affected); } catch (ExpressionException e) {
} catch (ExpressionException e) { actor.printError(e.getMessage());
actor.printError(e.getMessage()); }
}
}, "/generatebiome", region, context);
} }
} }

View File

@ -38,6 +38,7 @@ import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.util.CommandPermissions; import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.command.util.annotation.Confirm;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
@ -225,11 +226,10 @@ public class HistoryCommands {
) )
@CommandPermissions({"worldedit.history.undo", "worldedit.history.undo.self"}) @CommandPermissions({"worldedit.history.undo", "worldedit.history.undo.self"})
public void undo(Player player, LocalSession session, public void undo(Player player, LocalSession session,
@Arg(desc = "Number of undoes to perform", def = "1") @Confirm(Confirm.Processor.LIMIT) @Arg(desc = "Number of undoes to perform", def = "1")
int times, int times,
@Arg(name = "player", desc = "Undo this player's operations", def = "") @Arg(name = "player", desc = "Undo this player's operations", def = "")
String playerName, String playerName) throws WorldEditException {
InjectedValueAccess context) throws WorldEditException {
times = Math.max(1, times); times = Math.max(1, times);
LocalSession undoSession; LocalSession undoSession;
if (session.hasFastMode()) { if (session.hasFastMode()) {
@ -247,22 +247,20 @@ public class HistoryCommands {
undoSession = session; undoSession = session;
} }
int finalTimes = times; int finalTimes = times;
player.checkConfirmation(() -> { EditSession undone = null;
EditSession undone = null; int i = 0;
int i = 0; for (; i < finalTimes; ++i) {
for (; i < finalTimes; ++i) { undone = undoSession.undo(undoSession.getBlockBag(player), player);
undone = undoSession.undo(undoSession.getBlockBag(player), player); if (undone == null) break;
if (undone == null) break; worldEdit.flushBlockBag(player, undone);
worldEdit.flushBlockBag(player, undone); }
} if (undone == null) i--;
if (undone == null) i--; if (i > 0) {
if (i > 0) { BBC.COMMAND_UNDO_SUCCESS.send(player, i == 1 ? "" : " x" + i);
BBC.COMMAND_UNDO_SUCCESS.send(player, i == 1 ? "" : " x" + i); }
} if (undone == null) {
if (undone == null) { player.printError(BBC.COMMAND_UNDO_ERROR.s());
player.printError(BBC.COMMAND_UNDO_ERROR.s()); }
}
}, "undo", times, 50, context);
} }
@Command( @Command(
@ -272,7 +270,7 @@ public class HistoryCommands {
) )
@CommandPermissions({"worldedit.history.redo", "worldedit.history.redo.self"}) @CommandPermissions({"worldedit.history.redo", "worldedit.history.redo.self"})
public void redo(Player player, LocalSession session, public void redo(Player player, LocalSession session,
@Arg(desc = "Number of redoes to perform", def = "1") @Confirm(Confirm.Processor.LIMIT) @Arg(desc = "Number of redoes to perform", def = "1")
int times, int times,
@Arg(name = "player", desc = "Redo this player's operations", def = "") @Arg(name = "player", desc = "Redo this player's operations", def = "")
String playerName) throws WorldEditException { String playerName) throws WorldEditException {

View File

@ -19,39 +19,29 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import com.google.common.base.Joiner;
import com.boydti.fawe.FaweAPI; import com.boydti.fawe.FaweAPI;
import com.boydti.fawe.FaweCache; import com.boydti.fawe.FaweCache;
import com.boydti.fawe.beta.implementation.processors.ChunkSendProcessor;
import com.boydti.fawe.beta.implementation.processors.NullProcessor;
import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.BBC;
import com.boydti.fawe.object.FaweLimit; import com.boydti.fawe.object.FaweLimit;
import com.google.common.collect.Lists;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.util.CommandPermissions; import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.command.util.annotation.Confirm;
import com.sk89q.worldedit.function.block.BlockReplace;
import com.sk89q.worldedit.command.util.Logging; import com.sk89q.worldedit.command.util.Logging;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.function.FlatRegionFunction;
import com.sk89q.worldedit.function.GroundFunction; import com.sk89q.worldedit.function.GroundFunction;
import com.sk89q.worldedit.function.biome.BiomeReplace;
import com.sk89q.worldedit.function.generator.FloraGenerator; import com.sk89q.worldedit.function.generator.FloraGenerator;
import com.sk89q.worldedit.function.mask.MaskIntersection; import com.sk89q.worldedit.function.mask.MaskIntersection;
import com.sk89q.worldedit.function.mask.ExistingBlockMask; import com.sk89q.worldedit.function.mask.ExistingBlockMask;
import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.mask.NoiseFilter2D; import com.sk89q.worldedit.function.mask.NoiseFilter2D;
import com.sk89q.worldedit.function.visitor.RegionVisitor;
import com.sk89q.worldedit.function.mask.SolidBlockMask; import com.sk89q.worldedit.function.mask.SolidBlockMask;
import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.visitor.FlatRegionVisitor;
import com.sk89q.worldedit.function.visitor.LayerVisitor; import com.sk89q.worldedit.function.visitor.LayerVisitor;
import com.sk89q.worldedit.internal.annotation.Direction; import com.sk89q.worldedit.internal.annotation.Direction;
import com.sk89q.worldedit.internal.annotation.Selection; import com.sk89q.worldedit.internal.annotation.Selection;
@ -85,13 +75,13 @@ import org.enginehub.piston.inject.InjectedValueAccess;
import org.jetbrains.annotations.Range; import org.jetbrains.annotations.Range;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.stream.Stream;
import static com.sk89q.worldedit.command.MethodCommands.getArguments;
import static com.sk89q.worldedit.command.util.Logging.LogMode.ORIENTATION_REGION; import static com.sk89q.worldedit.command.util.Logging.LogMode.ORIENTATION_REGION;
import static com.sk89q.worldedit.command.util.Logging.LogMode.REGION; import static com.sk89q.worldedit.command.util.Logging.LogMode.REGION;
import static com.sk89q.worldedit.command.util.annotation.Confirm.Processor.ALWAYS;
import static com.sk89q.worldedit.command.util.annotation.Confirm.Processor.RADIUS;
import static com.sk89q.worldedit.internal.command.CommandUtil.checkCommandArgument; import static com.sk89q.worldedit.internal.command.CommandUtil.checkCommandArgument;
import static com.sk89q.worldedit.regions.Regions.asFlatRegion; import static com.sk89q.worldedit.regions.Regions.asFlatRegion;
import static com.sk89q.worldedit.regions.Regions.maximumBlockY; import static com.sk89q.worldedit.regions.Regions.maximumBlockY;
@ -116,19 +106,17 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.set") @CommandPermissions("worldedit.region.set")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public int set(Actor actor, EditSession editSession, public int set(Actor actor, EditSession editSession,
@Selection Region region, @Selection Region region,
@Arg(desc = "The pattern of blocks to set") @Arg(desc = "The pattern of blocks to set")
Pattern pattern, Pattern pattern) {
InjectedValueAccess context) { int affected = editSession.setBlocks(region, pattern);
actor.checkConfirmationRegion(() -> { if (affected != 0) {
int affected = editSession.setBlocks(region, pattern); BBC.OPERATION.send(actor, affected);
if (affected != 0) { if (!actor.hasPermission("fawe.tips"))
BBC.OPERATION.send(actor, affected); BBC.TIP_FAST.or(BBC.TIP_CANCEL, BBC.TIP_MASK, BBC.TIP_MASK_ANGLE, BBC.TIP_SET_LINEAR, BBC.TIP_SURFACE_SPREAD, BBC.TIP_SET_HAND).send(actor);
if (!actor.hasPermission("fawe.tips")) }
BBC.TIP_FAST.or(BBC.TIP_CANCEL, BBC.TIP_MASK, BBC.TIP_MASK_ANGLE, BBC.TIP_SET_LINEAR, BBC.TIP_SURFACE_SPREAD, BBC.TIP_SET_HAND).send(actor);
}
}, getArguments(context), region, context);
return 0; return 0;
} }
@ -139,10 +127,8 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.set") @CommandPermissions("worldedit.region.set")
@Logging(REGION) @Logging(REGION)
public void air(Actor actor, EditSession editSession, public void air(Actor actor, EditSession editSession, @Selection Region region) throws WorldEditException {
@Selection Region region, set(actor, editSession, region, BlockTypes.AIR);
InjectedValueAccess context) throws WorldEditException {
set(actor, editSession, region, BlockTypes.AIR, context);
} }
@Command( @Command(
@ -151,12 +137,13 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.test") @CommandPermissions("worldedit.region.test")
@Logging(REGION) @Logging(REGION)
public void test(Player player, EditSession editSession, @Selection Region region, @Arg(desc = "hello there") BiomeType biome) throws WorldEditException { public void test(Player player, EditSession editSession, @Arg(desc = "test") @Confirm(RADIUS) BlockVector3 radius) throws WorldEditException {
editSession.addProcessor(new ChunkSendProcessor(editSession.getWorld(), () -> Collections.singleton(player))); player.print("Run test " + radius);
editSession.addProcessor(NullProcessor.INSTANCE); // editSession.addProcessor(new ChunkSendProcessor(editSession.getWorld(), () -> Collections.singleton(player)));
FlatRegionFunction replace = new BiomeReplace(editSession, biome); // editSession.addProcessor(NullProcessor.INSTANCE);
FlatRegionVisitor visitor = new FlatRegionVisitor(Regions.asFlatRegion(region), replace); // FlatRegionFunction replace = new BiomeReplace(editSession, biome);
Operations.completeLegacy(visitor); // FlatRegionVisitor visitor = new FlatRegionVisitor(Regions.asFlatRegion(region), replace);
// Operations.completeLegacy(visitor);
} }
@Command( @Command(
@ -279,6 +266,7 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.curve") @CommandPermissions("worldedit.region.curve")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public void curve(Actor actor, EditSession editSession, public void curve(Actor actor, EditSession editSession,
@Selection Region region, @Selection Region region,
@Arg(desc = "The pattern of blocks to place") @Arg(desc = "The pattern of blocks to place")
@ -286,21 +274,19 @@ public class RegionCommands {
@Arg(desc = "The thickness of the curve", def = "0") @Arg(desc = "The thickness of the curve", def = "0")
int thickness, int thickness,
@Switch(name = 'h', desc = "Generate only a shell") @Switch(name = 'h', desc = "Generate only a shell")
boolean shell, InjectedValueAccess context) throws WorldEditException { boolean shell) throws WorldEditException {
if (!(region instanceof ConvexPolyhedralRegion)) { if (!(region instanceof ConvexPolyhedralRegion)) {
actor.printError("//curve only works with convex polyhedral selections"); actor.printError("//curve only works with convex polyhedral selections");
return; return;
} }
checkCommandArgument(thickness >= 0, "Thickness must be >= 0"); checkCommandArgument(thickness >= 0, "Thickness must be >= 0");
actor.checkConfirmationRegion(() -> {
ConvexPolyhedralRegion cpregion = (ConvexPolyhedralRegion) region; ConvexPolyhedralRegion cpregion = (ConvexPolyhedralRegion) region;
List<BlockVector3> vectors = new ArrayList<>(cpregion.getVertices()); List<BlockVector3> vectors = new ArrayList<>(cpregion.getVertices());
int blocksChanged = editSession.drawSpline(pattern, vectors, 0, 0, 0, 10, thickness, !shell); int blocksChanged = editSession.drawSpline(pattern, vectors, 0, 0, 0, 10, thickness, !shell);
actor.print(blocksChanged + " block(s) have been changed."); actor.print(blocksChanged + " block(s) have been changed.");
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -310,19 +296,18 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.replace") @CommandPermissions("worldedit.region.replace")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public void replace(Actor actor, EditSession editSession, @Selection Region region, public void replace(Actor actor, EditSession editSession, @Selection Region region,
@Arg(desc = "The mask representing blocks to replace", def = "") @Arg(desc = "The mask representing blocks to replace", 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, InjectedValueAccess context) throws WorldEditException { Pattern to) throws WorldEditException {
if (from == null) { if (from == null) {
from = new ExistingBlockMask(editSession); from = new ExistingBlockMask(editSession);
} }
Mask finalFrom = from; Mask finalFrom = from;
actor.checkConfirmationRegion(() -> {
int affected = editSession.replaceBlocks(region, finalFrom, to); int affected = editSession.replaceBlocks(region, finalFrom, to);
actor.print(affected + " block(s) have been replaced."); actor.print(affected + " block(s) have been replaced.");
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -331,13 +316,12 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.overlay") @CommandPermissions("worldedit.region.overlay")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public void overlay(Actor actor, EditSession editSession, @Selection Region region, public void overlay(Actor actor, EditSession editSession, @Selection Region region,
@Arg(desc = "The pattern of blocks to overlay") @Arg(desc = "The pattern of blocks to overlay")
Pattern pattern, InjectedValueAccess context) throws WorldEditException { Pattern pattern) throws WorldEditException {
actor.checkConfirmationRegion(() -> {
int affected = editSession.overlayCuboidBlocks(region, pattern); int affected = editSession.overlayCuboidBlocks(region, pattern);
actor.print(affected + " block(s) have been overlaid."); actor.print(affected + " block(s) have been overlaid.");
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -346,24 +330,23 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.overlay") @CommandPermissions("worldedit.region.overlay")
@Logging(REGION) @Logging(REGION)
public void lay(Player player, EditSession editSession, @Selection Region region, @Arg(name = "pattern", desc = "The pattern of blocks to lay") Pattern patternArg, InjectedValueAccess context) throws WorldEditException { @Confirm(Confirm.Processor.REGION)
player.checkConfirmationRegion(() -> { public void lay(Player player, EditSession editSession, @Selection Region region, @Arg(name = "pattern", desc = "The pattern of blocks to lay") Pattern patternArg) throws WorldEditException {
BlockVector3 max = region.getMaximumPoint(); BlockVector3 max = region.getMaximumPoint();
int maxY = max.getBlockY(); int maxY = max.getBlockY();
Iterable<BlockVector2> flat = Regions.asFlatRegion(region).asFlatRegion(); Iterable<BlockVector2> flat = Regions.asFlatRegion(region).asFlatRegion();
Iterator<BlockVector2> iter = flat.iterator(); Iterator<BlockVector2> iter = flat.iterator();
int y = 0; int y = 0;
int affected = 0; int affected = 0;
while (iter.hasNext()) { while (iter.hasNext()) {
BlockVector2 pos = iter.next(); BlockVector2 pos = iter.next();
int x = pos.getBlockX(); int x = pos.getBlockX();
int z = pos.getBlockZ(); int z = pos.getBlockZ();
y = editSession.getNearestSurfaceTerrainBlock(x, z, y, 0, maxY); y = editSession.getNearestSurfaceTerrainBlock(x, z, y, 0, maxY);
editSession.setBlock(x, y, z, patternArg); editSession.setBlock(x, y, z, patternArg);
affected++; affected++;
} }
BBC.VISITOR_BLOCK.send(player, affected); BBC.VISITOR_BLOCK.send(player, affected);
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -387,11 +370,10 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.naturalize") @CommandPermissions("worldedit.region.naturalize")
@Logging(REGION) @Logging(REGION)
public void naturalize(Actor actor, EditSession editSession, @Selection Region region, InjectedValueAccess context) throws WorldEditException { @Confirm(Confirm.Processor.REGION)
actor.checkConfirmationRegion(() -> { public void naturalize(Actor actor, EditSession editSession, @Selection Region region) throws WorldEditException {
int affected = editSession.naturalizeCuboidBlocks(region); int affected = editSession.naturalizeCuboidBlocks(region);
actor.print(affected + " block(s) have been made to look more natural."); actor.print(affected + " block(s) have been made to look more natural.");
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -400,13 +382,12 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.walls") @CommandPermissions("worldedit.region.walls")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public void walls(Actor actor, EditSession editSession, @Selection Region region, public void walls(Actor actor, EditSession editSession, @Selection Region region,
@Arg(desc = "The pattern of blocks to set") @Arg(desc = "The pattern of blocks to set")
Pattern pattern, InjectedValueAccess context) throws WorldEditException { Pattern pattern) throws WorldEditException {
actor.checkConfirmationRegion(() -> { int affected = editSession.makeWalls(region, pattern);
int affected = editSession.makeWalls(region, pattern); actor.print(affected + " block(s) have been changed.");
actor.print(affected + " block(s) have been changed.");
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -416,13 +397,12 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.faces") @CommandPermissions("worldedit.region.faces")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public void faces(Actor actor, EditSession editSession, @Selection Region region, public void faces(Actor actor, EditSession editSession, @Selection Region region,
@Arg(desc = "The pattern of blocks to set") @Arg(desc = "The pattern of blocks to set")
Pattern pattern, InjectedValueAccess context) throws WorldEditException { Pattern pattern) throws WorldEditException {
actor.checkConfirmationRegion(() -> { int affected = editSession.makeCuboidFaces(region, pattern);
int affected = editSession.makeCuboidFaces(region, pattern); actor.print(affected + " block(s) have been changed.");
actor.print(affected + " block(s) have been changed.");
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -432,12 +412,13 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.smooth") @CommandPermissions("worldedit.region.smooth")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public void smooth(Actor actor, EditSession editSession, @Selection Region region, public void smooth(Actor actor, EditSession editSession, @Selection Region region,
@Arg(desc = "# of iterations to perform", def = "1") @Arg(desc = "# of iterations to perform", def = "1")
int iterations, int iterations,
@Arg(desc = "The mask of blocks to use as the height map", def = "") @Arg(desc = "The mask of blocks to use as the height map", def = "")
Mask mask, Mask mask,
@Switch(name = 's', desc = "TODO") boolean snow, InjectedValueAccess context) throws WorldEditException { @Switch(name = 's', desc = "TODO") boolean snow) throws WorldEditException {
BlockVector3 min = region.getMinimumPoint(); BlockVector3 min = region.getMinimumPoint();
BlockVector3 max = region.getMaximumPoint(); BlockVector3 max = region.getMaximumPoint();
long volume = (((long) max.getX() - (long) min.getX() + 1) * ((long) max.getY() - (long) min.getY() + 1) * ((long) max.getZ() - (long) min.getZ() + 1)); long volume = (((long) max.getX() - (long) min.getX() + 1) * ((long) max.getY() - (long) min.getY() + 1) * ((long) max.getZ() - (long) min.getZ() + 1));
@ -445,16 +426,14 @@ public class RegionCommands {
if (volume >= limit.MAX_CHECKS) { if (volume >= limit.MAX_CHECKS) {
throw FaweCache.MAX_CHECKS; throw FaweCache.MAX_CHECKS;
} }
actor.checkConfirmationRegion(() -> { try {
try { HeightMap heightMap = new HeightMap(editSession, region, mask, snow);
HeightMap heightMap = new HeightMap(editSession, region, mask, snow); HeightMapFilter filter = new HeightMapFilter(new GaussianKernel(5, 1.0));
HeightMapFilter filter = new HeightMapFilter(new GaussianKernel(5, 1.0)); int affected = heightMap.applyFilter(filter, iterations);
int affected = heightMap.applyFilter(filter, iterations); actor.print("Terrain's height map smoothed. " + affected + " block(s) changed.");
actor.print("Terrain's height map smoothed. " + affected + " block(s) changed."); } catch (Throwable e) {
} catch (Throwable e) { throw new RuntimeException(e);
throw new RuntimeException(e); }
}
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -497,6 +476,7 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.move") @CommandPermissions("worldedit.region.move")
@Logging(ORIENTATION_REGION) @Logging(ORIENTATION_REGION)
@Confirm(Confirm.Processor.REGION)
public void move(Actor actor, World world, EditSession editSession, LocalSession session, public void move(Actor actor, World world, EditSession editSession, LocalSession session,
@Selection Region region, @Selection Region region,
@Arg(desc = "# of blocks to move", def = "1") @Arg(desc = "# of blocks to move", def = "1")
@ -515,8 +495,7 @@ public class RegionCommands {
@Switch(name = 'b', desc = "Also copy biomes") @Switch(name = 'b', desc = "Also copy biomes")
boolean copyBiomes, boolean copyBiomes,
@ArgFlag(name = 'm', desc = "Set the include mask, non-matching blocks become air", def = "") @ArgFlag(name = 'm', desc = "Set the include mask, non-matching blocks become air", def = "")
Mask mask, Mask mask) throws WorldEditException {
InjectedValueAccess context) throws WorldEditException {
checkCommandArgument(count >= 1, "Count must be >= 1"); checkCommandArgument(count >= 1, "Count must be >= 1");
Mask combinedMask; Mask combinedMask;
@ -530,22 +509,20 @@ public class RegionCommands {
combinedMask = mask; combinedMask = mask;
} }
actor.checkConfirmationRegion(() -> { int affected = editSession.moveRegion(region, direction, count, !skipEntities, copyBiomes, combinedMask, replace);
int affected = editSession.moveRegion(region, direction, count, !skipEntities, copyBiomes, combinedMask, replace);
if (moveSelection) { if (moveSelection) {
try { try {
region.shift(direction.multiply(count)); region.shift(direction.multiply(count));
session.getRegionSelector(world).learnChanges(); session.getRegionSelector(world).learnChanges();
session.getRegionSelector(world).explainRegionAdjust(actor, session); session.getRegionSelector(world).explainRegionAdjust(actor, session);
} catch (RegionOperationException e) { } catch (RegionOperationException e) {
actor.printError(e.getMessage()); actor.printError(e.getMessage());
}
} }
}
BBC.VISITOR_BLOCK.send(actor, affected); BBC.VISITOR_BLOCK.send(actor, affected);
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -556,15 +533,13 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.fall") @CommandPermissions("worldedit.region.fall")
@Logging(ORIENTATION_REGION) @Logging(ORIENTATION_REGION)
@Confirm(Confirm.Processor.REGION)
public void fall(Player player, EditSession editSession, LocalSession session, public void fall(Player player, EditSession editSession, LocalSession session,
@Selection Region region, @Selection Region region,
@Arg(desc = "BlockStateHolder", def = "air") BlockStateHolder replace, @Arg(desc = "BlockStateHolder", def = "air") BlockStateHolder replace,
@Switch(name = 'm', desc = "TODO") boolean notFullHeight, @Switch(name = 'm', desc = "TODO") boolean notFullHeight) throws WorldEditException {
InjectedValueAccess context) throws WorldEditException { int affected = editSession.fall(region, !notFullHeight, replace);
player.checkConfirmationRegion(() -> { BBC.VISITOR_BLOCK.send(player, affected);
int affected = editSession.fall(region, !notFullHeight, replace);
BBC.VISITOR_BLOCK.send(player, affected);
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -576,7 +551,7 @@ public class RegionCommands {
public void stack(Actor actor, World world, EditSession editSession, LocalSession session, public void stack(Actor actor, World world, EditSession editSession, LocalSession session,
@Selection Region region, @Selection Region region,
@Arg(desc = "# of copies to stack", def = "1") @Arg(desc = "# of copies to stack", def = "1")
int count, @Confirm(Confirm.Processor.REGION) int count,
@Arg(desc = "The direction to stack", def = Direction.AIM) @Arg(desc = "The direction to stack", def = Direction.AIM)
@Direction(includeDiagonals = true) @Direction(includeDiagonals = true)
BlockVector3 direction, BlockVector3 direction,
@ -589,8 +564,7 @@ public class RegionCommands {
@Switch(name = 'b', desc = "Also copy biomes") @Switch(name = 'b', desc = "Also copy biomes")
boolean copyBiomes, boolean copyBiomes,
@ArgFlag(name = 'm', desc = "Source mask", def="") @ArgFlag(name = 'm', desc = "Source mask", def="")
Mask mask, Mask mask) throws WorldEditException {
InjectedValueAccess context) throws WorldEditException {
Mask combinedMask; Mask combinedMask;
if (ignoreAirBlocks) { if (ignoreAirBlocks) {
@ -603,25 +577,23 @@ public class RegionCommands {
combinedMask = mask; combinedMask = mask;
} }
actor.checkConfirmationStack(() -> { int affected = editSession.stackCuboidRegion(region, direction, count, !skipEntities, copyBiomes, combinedMask);
int affected = editSession.stackCuboidRegion(region, direction, count, !skipEntities, copyBiomes, combinedMask);
if (moveSelection) { if (moveSelection) {
try { try {
final BlockVector3 size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); final BlockVector3 size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1);
final BlockVector3 shiftVector = direction.multiply(size).multiply(count); final BlockVector3 shiftVector = direction.multiply(size).multiply(count);
region.shift(shiftVector); region.shift(shiftVector);
session.getRegionSelector(world).learnChanges(); session.getRegionSelector(world).learnChanges();
session.getRegionSelector(world).explainRegionAdjust(actor, session); session.getRegionSelector(world).explainRegionAdjust(actor, session);
} catch (RegionOperationException e) { } catch (RegionOperationException e) {
actor.printError(e.getMessage()); actor.printError(e.getMessage());
}
} }
}
BBC.VISITOR_BLOCK.send(actor, affected); BBC.VISITOR_BLOCK.send(actor, affected);
}, getArguments(context), region, count, context);
} }
@Command( @Command(
@ -633,7 +605,8 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.deform") @CommandPermissions("worldedit.region.deform")
@Logging(ALL) @Logging(ALL)
public void deform(Actor actor, LocalSession session, EditSession editSession, InjectedValueAccess context, @Confirm(Confirm.Processor.REGION)
public void deform(Actor actor, LocalSession session, EditSession editSession,
@Selection Region region, @Selection Region region,
@Arg(desc = "The expression to use", variable = true) @Arg(desc = "The expression to use", variable = true)
List<String> expression, List<String> expression,
@ -663,17 +636,15 @@ public class RegionCommands {
} }
final Vector3 unit1 = unit; final Vector3 unit1 = unit;
actor.checkConfirmationRegion(() -> { try {
try { final int affected = editSession.deformRegion(region, zero, unit1, String.join(" ", expression), session.getTimeout());
final int affected = editSession.deformRegion(region, zero, unit1, String.join(" ", expression), session.getTimeout()); if (actor instanceof Player) {
if (actor instanceof Player) { ((Player) actor).findFreePosition();
((Player) actor).findFreePosition();
}
actor.print(affected + " block(s) have been deformed.");
} catch (ExpressionException e) {
actor.printError(e.getMessage());
} }
}, getArguments(context), region, context); actor.print(affected + " block(s) have been deformed.");
} catch (ExpressionException e) {
actor.printError(e.getMessage());
}
} }
@Command( @Command(
@ -686,31 +657,27 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.regen") @CommandPermissions("worldedit.regen")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public void regenerateChunk(Player player, LocalSession session, EditSession editSession, @Selection Region region, public void regenerateChunk(Player player, LocalSession session, EditSession editSession, @Selection Region region,
@Arg(def = "", desc = "Regenerate with biome") BiomeType biome, @Arg(def = "", desc = "Regenerate with biome") BiomeType biome,
@Arg(def = "", desc = "Regenerate with seed") Long seed, @Arg(def = "", desc = "Regenerate with seed") Long seed) throws WorldEditException {
InjectedValueAccess context) throws WorldEditException { Mask mask = session.getMask();
player.checkConfirmationRegion(() -> { session.setMask((Mask) null);
Mask mask = session.getMask(); session.setSourceMask((Mask) null);
session.setMask((Mask) null); editSession.regenerate(region, biome, seed);
session.setSourceMask((Mask) null); session.setMask(mask);
editSession.regenerate(region, biome, seed); session.setSourceMask(mask);
session.setMask(mask); if (!player.hasPermission("fawe.tips")) {
session.setSourceMask(mask); player.print(BBC.COMMAND_REGEN_2.s());
if (!player.hasPermission("fawe.tips")) { } else if (biome == null) {
player.print(BBC.COMMAND_REGEN_2.s()); BBC.COMMAND_REGEN_0.send(player);
} else if (biome == null) { if (!player.hasPermission("fawe.tips")) player.print(BBC.TIP_REGEN_0.s());
BBC.COMMAND_REGEN_0.send(player); } else if (seed == null) {
if (!player.hasPermission("fawe.tips")) player.print(BBC.TIP_REGEN_0.s()); player.print(BBC.COMMAND_REGEN_1.s());
} else if (seed == null) { if (!player.hasPermission("fawe.tips")) BBC.TIP_REGEN_1.send(player);
player.print(BBC.COMMAND_REGEN_1.s()); } else {
if (!player.hasPermission("fawe.tips")) BBC.TIP_REGEN_1.send(player); player.print(BBC.COMMAND_REGEN_2.s());
} else { }
player.print(BBC.COMMAND_REGEN_2.s());
}
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -723,20 +690,18 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.hollow") @CommandPermissions("worldedit.region.hollow")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public void hollow(Actor actor, EditSession editSession, public void hollow(Actor actor, EditSession editSession,
@Selection Region region, @Selection Region region,
@Range(from=0, to=Integer.MAX_VALUE) @Arg(desc = "Thickness of the shell to leave", def = "0") @Range(from=0, to=Integer.MAX_VALUE) @Arg(desc = "Thickness of the shell to leave", def = "0")
int thickness, int thickness,
@Arg(desc = "The pattern of blocks to replace the hollowed area with", def = "air") @Arg(desc = "The pattern of blocks to replace the hollowed area with", def = "air")
Pattern pattern, Pattern pattern,
@ArgFlag(name = 'm', desc = "Mask to hollow with") Mask mask, @ArgFlag(name = 'm', desc = "Mask to hollow with") Mask mask) throws WorldEditException {
InjectedValueAccess context) throws WorldEditException {
checkCommandArgument(thickness >= 0, "Thickness must be >= 0"); checkCommandArgument(thickness >= 0, "Thickness must be >= 0");
Mask finalMask = mask == null ? new SolidBlockMask(editSession) : mask; Mask finalMask = mask == null ? new SolidBlockMask(editSession) : mask;
actor.checkConfirmationRegion(() -> { int affected = editSession.hollowOutRegion(region, thickness, pattern, finalMask);
int affected = editSession.hollowOutRegion(region, thickness, pattern, finalMask); actor.print(affected + " block(s) have been changed.");
actor.print(affected + " block(s) have been changed.");
}, getArguments(context), region, context);
} }
@Command( @Command(
@ -745,6 +710,7 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.forest") @CommandPermissions("worldedit.region.forest")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public int forest(Actor actor, EditSession editSession, @Selection Region region, public int forest(Actor actor, EditSession editSession, @Selection Region region,
@Arg(desc = "The type of tree to place", def = "tree") @Arg(desc = "The type of tree to place", def = "tree")
TreeType type, TreeType type,
@ -762,20 +728,19 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.flora") @CommandPermissions("worldedit.region.flora")
@Logging(REGION) @Logging(REGION)
@Confirm(Confirm.Processor.REGION)
public void flora(Actor actor, EditSession editSession, @Selection Region region, public void flora(Actor actor, EditSession editSession, @Selection Region region,
@Arg(desc = "The density of the forest", def = "5") @Arg(desc = "The density of the forest", def = "5")
double density, InjectedValueAccess context) throws WorldEditException { double density) throws WorldEditException {
checkCommandArgument(0 <= density && density <= 100, "Density must be in [0, 100]"); checkCommandArgument(0 <= density && density <= 100, "Density must be in [0, 100]");
actor.checkConfirmationRegion(() -> { FloraGenerator generator = new FloraGenerator(editSession);
FloraGenerator generator = new FloraGenerator(editSession); GroundFunction ground = new GroundFunction(new ExistingBlockMask(editSession), generator);
GroundFunction ground = new GroundFunction(new ExistingBlockMask(editSession), generator); LayerVisitor visitor = new LayerVisitor(asFlatRegion(region), minimumBlockY(region), maximumBlockY(region), ground);
LayerVisitor visitor = new LayerVisitor(asFlatRegion(region), minimumBlockY(region), maximumBlockY(region), ground); visitor.setMask(new NoiseFilter2D(new RandomNoise(), density / 100));
visitor.setMask(new NoiseFilter2D(new RandomNoise(), density / 100)); Operations.completeLegacy(visitor);
Operations.completeLegacy(visitor);
int affected = ground.getAffected(); int affected = ground.getAffected();
actor.print(affected + " flora created."); actor.print(affected + " flora created.");
}, "/flora", region, context);
} }
} }

View File

@ -39,11 +39,12 @@ import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.util.CommandPermissions; import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.command.util.CommandQueuedConditionGenerator;
import com.sk89q.worldedit.command.util.CreatureButcher; import com.sk89q.worldedit.command.util.CreatureButcher;
import com.sk89q.worldedit.command.util.EntityRemover; import com.sk89q.worldedit.command.util.EntityRemover;
import com.sk89q.worldedit.command.util.Logging; import com.sk89q.worldedit.command.util.Logging;
import com.sk89q.worldedit.command.util.PrintCommandHelp; import com.sk89q.worldedit.command.util.PrintCommandHelp;
import com.sk89q.worldedit.command.util.SkipQueue; import com.sk89q.worldedit.command.util.annotation.SkipQueue;
import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
@ -102,7 +103,7 @@ import org.jetbrains.annotations.Range;
/** /**
* Utility commands. * Utility commands.
*/ */
@CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class) @CommandContainer(superTypes = {CommandPermissionsConditionGenerator.Registration.class, CommandQueuedConditionGenerator.Registration.class})
public class UtilityCommands { public class UtilityCommands {
private final WorldEdit we; private final WorldEdit we;
@ -700,6 +701,7 @@ public class UtilityCommands {
name = "/confirm", name = "/confirm",
desc = "Confirm a command" desc = "Confirm a command"
) )
@SkipQueue
@CommandPermissions("fawe.confirm") @CommandPermissions("fawe.confirm")
public void confirm(Player fp) throws WorldEditException { public void confirm(Player fp) throws WorldEditException {
if (!fp.confirm()) { if (!fp.confirm()) {

View File

@ -29,7 +29,7 @@ import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.util.CommandPermissions; import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.command.util.SkipQueue; import com.sk89q.worldedit.command.util.annotation.SkipQueue;
import com.sk89q.worldedit.command.util.CommandQueuedConditionGenerator; import com.sk89q.worldedit.command.util.CommandQueuedConditionGenerator;
import com.sk89q.worldedit.command.util.PrintCommandHelp; import com.sk89q.worldedit.command.util.PrintCommandHelp;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;

View File

@ -1,5 +1,6 @@
package com.sk89q.worldedit.command.util; package com.sk89q.worldedit.command.util;
import com.sk89q.worldedit.command.util.annotation.SkipQueue;
import org.enginehub.piston.Command; import org.enginehub.piston.Command;
import org.enginehub.piston.gen.CommandConditionGenerator; import org.enginehub.piston.gen.CommandConditionGenerator;
import org.enginehub.piston.util.NonnullByDefault; import org.enginehub.piston.util.NonnullByDefault;

View File

@ -0,0 +1,136 @@
package com.sk89q.worldedit.command.util.annotation;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.config.BBC;
import com.boydti.fawe.util.task.InterruptableCondition;
import com.sk89q.worldedit.IncompleteRegionException;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.command.argument.Arguments;
import com.sk89q.worldedit.event.Event;
import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.internal.annotation.Selection;
import com.sk89q.worldedit.internal.command.CommandArgParser;
import com.sk89q.worldedit.internal.util.Substring;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import org.enginehub.piston.exception.StopExecutionException;
import org.enginehub.piston.inject.InjectAnnotation;
import org.enginehub.piston.inject.InjectedValueAccess;
import org.enginehub.piston.inject.Key;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Stream;
/**
* Indicates how the affected blocks should be hinted at in the log.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.METHOD})
@InjectAnnotation
public @interface Confirm {
Processor value() default Processor.ALWAYS;
enum Processor {
REGION {
@Override
public boolean passes(Actor actor, InjectedValueAccess context, double value) {
Region region = context.injectedValue(Key.of(Region.class, Selection.class)).orElseThrow(IncompleteRegionException::new);
BlockVector3 min = region.getMinimumPoint();
BlockVector3 max = region.getMaximumPoint();
long area = (max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1) * (int) value;
if (area > 2 << 18) {
BBC.WORLDEDIT_CANCEL_REASON_CONFIRM_REGION.send(actor, min, max, getArgs(context));
return confirm(actor, context);
}
return true;
}
},
RADIUS {
@Override
public boolean passes(Actor actor, InjectedValueAccess context, double value) {
int max = WorldEdit.getInstance().getConfiguration().maxRadius;
if (value > max) {
BBC.WORLDEDIT_CANCEL_REASON_CONFIRM_REGION.send(actor, value, max, getArgs(context));
return Processor.confirm(actor, context);
}
return true;
}
},
LIMIT {
@Override
public boolean passes(Actor actor, InjectedValueAccess context, double value) {
int max = 50;// TODO configurable, get Key.of(Method.class) @Limit
if (value > max) {
BBC.WORLDEDIT_CANCEL_REASON_CONFIRM_REGION.send(actor, value, max, getArgs(context));
return Processor.confirm(actor, context);
}
return true;
}
},
ALWAYS {
@Override
public boolean passes(Actor actor, InjectedValueAccess context, double value) {
BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.send(actor);
return confirm(actor, context);
}
}
;
public boolean passes(Actor actor, InjectedValueAccess context, double value){return true;}
public <T extends Number> T check(Actor actor, InjectedValueAccess context, T value) {
if (!passes(actor, context, value.doubleValue())) {
throw new StopExecutionException(TextComponent.empty());
}
return value;
}
private static String getArgs(InjectedValueAccess context) {
return context.injectedValue(Key.of(Arguments.class)).map(Arguments::get).get();
}
private static String getArg(InjectedValueAccess context, String def) {
Stream<Substring> split = CommandArgParser.forArgString(getArgs(context)).parseArgs();
Substring first = split.findFirst().orElse(null);
if (first == null && def == null) {
throw new StopExecutionException(TextComponent.of("No arguments"));
}
return first != null ? first.getSubstring() : def;
}
private static int getInt(InjectedValueAccess context, String def) {
return Integer.parseInt(getArg(context, def));
}
private static boolean confirm(Actor actor, InjectedValueAccess context) {
Event event = context.injectedValue(Key.of(Event.class)).orElse(null);
if (!(event instanceof CommandEvent)) {
return true;
}
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
InterruptableCondition wait = new InterruptableCondition(lock, condition, Thread.currentThread());
try {
lock.lock();
actor.setMeta("cmdConfirm", wait);
if (condition.await(15, TimeUnit.SECONDS)) {
return true;
}
} catch (InterruptedException e) {}
finally {
if (actor.getMeta("cmdConfirm") == wait) {
actor.deleteMeta("cmdConfirm");
}
}
return false;
}
}
}

View File

@ -1,5 +1,6 @@
package com.sk89q.worldedit.command.util; package com.sk89q.worldedit.command.util.annotation;
import com.sk89q.worldedit.command.util.CommandQueuedConditionGenerator;
import org.enginehub.piston.annotation.CommandCondition; import org.enginehub.piston.annotation.CommandCondition;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;

View File

@ -375,39 +375,6 @@ public interface Player extends Entity, Actor {
} }
} }
default int cancel(boolean close) {
int cancelled = 0;
for (Request request : Request.getAll()) {
EditSession editSession = request.getEditSession();
if (editSession != null) {
Player player = editSession.getPlayer();
if (equals(player)) {
editSession.cancel();
cancelled++;
}
}
}
VirtualWorld world = getSession().getVirtualWorld();
if (world != null) {
if (close) {
try {
world.close(false);
} catch (IOException e) {
e.printStackTrace();
}
}
else {
try {
world.close(false);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return cancelled;
}
void sendTitle(String title, String sub); void sendTitle(String title, String sub);
/** /**

View File

@ -23,7 +23,7 @@ package com.sk89q.worldedit.event;
* An abstract implementation of {@link Cancellable} that has all * An abstract implementation of {@link Cancellable} that has all
* of {@link Cancellable}'s methods implemented. * of {@link Cancellable}'s methods implemented.
*/ */
public abstract class AbstractCancellable implements Cancellable { public abstract class AbstractCancellable extends Event implements Cancellable {
private boolean cancelled; private boolean cancelled;

View File

@ -23,13 +23,18 @@ import com.boydti.fawe.Fawe;
import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.BBC;
import com.boydti.fawe.config.Settings; import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.FaweLimit; import com.boydti.fawe.object.FaweLimit;
import com.boydti.fawe.object.brush.visualization.VirtualWorld;
import com.boydti.fawe.util.task.InterruptableCondition;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.entity.MapMetadatable; import com.sk89q.worldedit.entity.MapMetadatable;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.internal.cui.CUIEvent; import com.sk89q.worldedit.internal.cui.CUIEvent;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionOperationException; import com.sk89q.worldedit.regions.RegionOperationException;
import com.sk89q.worldedit.session.SessionOwner; import com.sk89q.worldedit.session.SessionOwner;
import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.util.Identifiable; import com.sk89q.worldedit.util.Identifiable;
import com.sk89q.worldedit.util.auth.Subject; import com.sk89q.worldedit.util.auth.Subject;
import com.sk89q.worldedit.util.formatting.text.Component; import com.sk89q.worldedit.util.formatting.text.Component;
@ -37,7 +42,9 @@ import org.enginehub.piston.inject.InjectedValueAccess;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.util.concurrent.locks.Condition;
/** /**
* An object that can perform actions in WorldEdit. * An object that can perform actions in WorldEdit.
@ -134,100 +141,30 @@ public interface Actor extends Identifiable, SessionOwner, Subject, MapMetadatab
boolean runAction(Runnable ifFree, boolean checkFree, boolean async); boolean runAction(Runnable ifFree, boolean checkFree, boolean async);
default void checkConfirmationStack(@NotNull Runnable task, @NotNull String command, /**
Region region, int times, InjectedValueAccess context) throws RegionOperationException { * Decline any pending actions
if (!getMeta("cmdConfirmRunning", false)) { * @return true if an action was pending
if (region != null) { */
BlockVector3 min = region.getMinimumPoint(); default boolean decline() {
BlockVector3 max = region.getMaximumPoint(); InterruptableCondition confirm = deleteMeta("cmdConfirm");
long area = if (confirm != null) {
(long) ((max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1)) * times; confirm.interrupt();
if (area > 2 << 18) { return true;
setConfirmTask(task, context, command);
BlockVector3 base = max.subtract(min).add(BlockVector3.ONE);
long volume = (long) base.getX() * base.getZ() * base.getY() * times;
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM
.format(min, max, command,
NumberFormat.getNumberInstance().format(volume)));
}
}
} }
task.run(); return false;
}
default void checkConfirmationRegion(@NotNull Runnable task, @NotNull String command,
Region region, InjectedValueAccess context) throws RegionOperationException {
if (!getMeta("cmdConfirmRunning", false)) {
if (region != null) {
BlockVector3 min = region.getMinimumPoint();
BlockVector3 max = region.getMaximumPoint();
long area = (max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1);
if (area > 2 << 18) {
setConfirmTask(task, context, command);
BlockVector3 base = max.subtract(min).add(BlockVector3.ONE);
long volume = (long) base.getX() * base.getZ() * base.getY();
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM
.format(min, max, command,
NumberFormat.getNumberInstance().format(volume)));
}
}
}
task.run();
}
default void setConfirmTask(@NotNull Runnable task, InjectedValueAccess context,
@NotNull String command) {
CommandEvent event = new CommandEvent(this, command);
Runnable newTask = () -> PlatformCommandManager.getInstance().handleCommandTask(() -> {
task.run();
return null;
}, context, getSession(), event);
setMeta("cmdConfirm", newTask);
}
default void checkConfirmation(@NotNull Runnable task, @NotNull String command, int times,
int limit, InjectedValueAccess context) throws RegionOperationException {
if (!getMeta("cmdConfirmRunning", false)) {
if (times > limit) {
setConfirmTask(task, context, command);
String volume = "<unspecified>";
throw new RegionOperationException(
BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.format(0, times, command, volume));
}
}
task.run();
}
default void checkConfirmationRadius(@NotNull Runnable task, String command, int radius,
InjectedValueAccess context) throws RegionOperationException {
if (command != null && !getMeta("cmdConfirmRunning", false)) {
if (radius > 0) {
if (radius > 448) {
setConfirmTask(task, context, command);
long volume = (long) (Math.PI * ((double) radius * radius));
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM
.format(0, radius, command,
NumberFormat.getNumberInstance().format(volume)));
}
}
}
task.run();
} }
/**
* Confirm any pending actions
* @return true if an action was pending
*/
default boolean confirm() { default boolean confirm() {
Runnable confirm = deleteMeta("cmdConfirm"); InterruptableCondition confirm = deleteMeta("cmdConfirm");
if (confirm == null) { if (confirm != null) {
return false; confirm.signal();;
return true;
} }
queueAction(() -> { return false;
setMeta("cmdConfirmRunning", true);
try {
confirm.run();
} finally {
setMeta("cmdConfirmRunning", false);
}
});
return true;
} }
/** /**
@ -257,4 +194,42 @@ public interface Actor extends Identifiable, SessionOwner, Subject, MapMetadatab
default boolean runIfFree(Runnable r) { default boolean runIfFree(Runnable r) {
return runAction(r, true, false); return runAction(r, true, false);
} }
/**
* Attempt to cancel all pending and running actions
* @param close if Extents are closed
* @return number of cancelled actions
*/
default int cancel(boolean close) {
int cancelled = decline() ? 1 : 0;
for (Request request : Request.getAll()) {
EditSession editSession = request.getEditSession();
if (editSession != null) {
Player player = editSession.getPlayer();
if (equals(player)) {
editSession.cancel();
cancelled++;
}
}
}
VirtualWorld world = getSession().getVirtualWorld();
if (world != null) {
if (close) {
try {
world.close(false);
} catch (IOException e) {
e.printStackTrace();
}
}
else {
try {
world.close(false);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return cancelled;
}
} }

View File

@ -111,6 +111,7 @@ import com.sk89q.worldedit.command.util.PrintCommandHelp;
import com.sk89q.worldedit.command.util.SubCommandPermissionCondition; import com.sk89q.worldedit.command.util.SubCommandPermissionCondition;
import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.Event;
import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.event.platform.CommandSuggestionEvent; import com.sk89q.worldedit.event.platform.CommandSuggestionEvent;
import com.sk89q.worldedit.extension.platform.binding.Bindings; import com.sk89q.worldedit.extension.platform.binding.Bindings;
@ -122,6 +123,8 @@ import com.sk89q.worldedit.internal.annotation.Selection;
import com.sk89q.worldedit.internal.command.CommandArgParser; import com.sk89q.worldedit.internal.command.CommandArgParser;
import com.sk89q.worldedit.internal.command.CommandLoggingHandler; import com.sk89q.worldedit.internal.command.CommandLoggingHandler;
import com.sk89q.worldedit.internal.command.CommandRegistrationHandler; import com.sk89q.worldedit.internal.command.CommandRegistrationHandler;
import com.sk89q.worldedit.internal.command.ConfirmHandler;
import com.sk89q.worldedit.internal.command.MethodInjector;
import com.sk89q.worldedit.internal.command.exception.ExceptionConverter; import com.sk89q.worldedit.internal.command.exception.ExceptionConverter;
import com.sk89q.worldedit.internal.command.exception.WorldEditExceptionConverter; import com.sk89q.worldedit.internal.command.exception.WorldEditExceptionConverter;
import com.sk89q.worldedit.internal.util.Substring; import com.sk89q.worldedit.internal.util.Substring;
@ -130,6 +133,7 @@ import com.sk89q.worldedit.session.SessionKey;
import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.util.auth.AuthorizationException; import com.sk89q.worldedit.util.auth.AuthorizationException;
import com.sk89q.worldedit.util.eventbus.Subscribe; import com.sk89q.worldedit.util.eventbus.Subscribe;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TextComponent; import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor; import com.sk89q.worldedit.util.formatting.text.format.TextColor;
@ -138,12 +142,12 @@ import com.sk89q.worldedit.util.logging.LogFormat;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import org.enginehub.piston.Command; import org.enginehub.piston.Command;
import org.enginehub.piston.CommandManager; import org.enginehub.piston.CommandManager;
import org.enginehub.piston.config.TextConfig; import org.enginehub.piston.converter.ArgumentConverter;
import org.enginehub.piston.converter.ArgumentConverters; import org.enginehub.piston.converter.ArgumentConverters;
import org.enginehub.piston.converter.ConversionResult;
import org.enginehub.piston.exception.CommandException; import org.enginehub.piston.exception.CommandException;
import org.enginehub.piston.exception.CommandExecutionException; import org.enginehub.piston.exception.CommandExecutionException;
import org.enginehub.piston.exception.ConditionFailedException; import org.enginehub.piston.exception.ConditionFailedException;
import org.enginehub.piston.exception.StopExecutionException;
import org.enginehub.piston.exception.UsageException; import org.enginehub.piston.exception.UsageException;
import org.enginehub.piston.gen.CommandRegistration; import org.enginehub.piston.gen.CommandRegistration;
import org.enginehub.piston.impl.CommandManagerServiceImpl; import org.enginehub.piston.impl.CommandManagerServiceImpl;
@ -165,6 +169,8 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -221,7 +227,10 @@ public final class PlatformCommandManager {
this.globalInjectedValues = MapBackedValueStore.create(); this.globalInjectedValues = MapBackedValueStore.create();
this.registration = new CommandRegistrationHandler( this.registration = new CommandRegistrationHandler(
ImmutableList.of( ImmutableList.of(
new CommandLoggingHandler(worldEdit, COMMAND_LOG) new CommandLoggingHandler(worldEdit, COMMAND_LOG),
new MethodInjector(),
new ConfirmHandler()
)); ));
// setup separate from main constructor // setup separate from main constructor
// ensures that everything is definitely assigned // ensures that everything is definitely assigned
@ -262,7 +271,7 @@ public final class PlatformCommandManager {
WorldConverter.register(commandManager); WorldConverter.register(commandManager);
ExpressionConverter.register(commandManager); ExpressionConverter.register(commandManager);
registerBindings(new ConsumeBindings(worldEdit)); registerBindings(new ConsumeBindings(worldEdit, this));
registerBindings(new PrimitiveBindings(worldEdit)); registerBindings(new PrimitiveBindings(worldEdit));
registerBindings(new ProvideBindings(worldEdit)); registerBindings(new ProvideBindings(worldEdit));
} }
@ -611,17 +620,29 @@ public final class PlatformCommandManager {
return CommandArgParser.forArgString(input).parseArgs(); return CommandArgParser.forArgString(input).parseArgs();
} }
public <T> T parse(String args, Actor actor) { public <T> T parseCommand(String args, Actor actor) {
InjectedValueAccess context; InjectedValueAccess context;
if (actor == null) { if (actor == null) {
context = globalInjectedValues; context = globalInjectedValues;
} else { } else {
context = initializeInjectedValues(args::toString, actor); context = initializeInjectedValues(args::toString, actor, null);
} }
return parse(args, context); return parseCommand(args, context);
} }
public <T> T parse(String args, InjectedValueAccess access) { public <T> T parseConverter(String args, InjectedValueAccess access, Class<T> clazz) {
ArgumentConverter<T> converter = commandManager.getConverter(Key.of(clazz)).orElse(null);
if (converter != null) {
ConversionResult<T> result = converter.convert(args, access);
Collection<T> values = result.orElse(Collections.emptyList());
if (!values.isEmpty()) {
return values.iterator().next();
}
}
return null;
}
public <T> T parseCommand(String args, InjectedValueAccess access) {
if (args.isEmpty()) return null; if (args.isEmpty()) return null;
String[] split = parseArgs(args) String[] split = parseArgs(args)
.map(Substring::getSubstring) .map(Substring::getSubstring)
@ -639,8 +660,6 @@ public final class PlatformCommandManager {
String arg0 = space0 == -1 ? args : args.substring(0, space0); String arg0 = space0 == -1 ? args : args.substring(0, space0);
Optional<Command> optional = commandManager.getCommand(arg0); Optional<Command> optional = commandManager.getCommand(arg0);
if (!optional.isPresent()) { if (!optional.isPresent()) {
System.out.println("No command for '" + arg0 + "' " + StringMan.getString(commandManager.getAllCommands().map(
Command::getName).collect(Collectors.toList())));
return; return;
} }
Command cmd = optional.get(); Command cmd = optional.get();
@ -648,6 +667,8 @@ public final class PlatformCommandManager {
if (queued != null && !queued.isQueued()) { if (queued != null && !queued.isQueued()) {
handleCommandOnCurrentThread(event); handleCommandOnCurrentThread(event);
return; return;
} else {
actor.decline();
} }
LocalSession session = worldEdit.getSessionManager().get(actor); LocalSession session = worldEdit.getSessionManager().get(actor);
synchronized (session) { synchronized (session) {
@ -679,7 +700,7 @@ public final class PlatformCommandManager {
} }
} }
MemoizingValueAccess context = initializeInjectedValues(event::getArguments, actor); MemoizingValueAccess context = initializeInjectedValues(event::getArguments, actor, event);
ThrowableSupplier<Throwable> task = () -> commandManager.execute(context, ImmutableList.copyOf(split)); ThrowableSupplier<Throwable> task = () -> commandManager.execute(context, ImmutableList.copyOf(split));
@ -717,10 +738,6 @@ public final class PlatformCommandManager {
} catch (FaweException e) { } catch (FaweException e) {
actor.printError("Edit cancelled: " + e.getMessage()); actor.printError("Edit cancelled: " + e.getMessage());
} catch (UsageException e) { } catch (UsageException e) {
actor.print(TextComponent.builder("")
.color(TextColor.RED)
.append(e.getRichMessage())
.build());
ImmutableList<Command> cmd = e.getCommands(); ImmutableList<Command> cmd = e.getCommands();
if (!cmd.isEmpty()) { if (!cmd.isEmpty()) {
actor.print(TextComponent.builder("Usage: ") actor.print(TextComponent.builder("Usage: ")
@ -728,22 +745,27 @@ public final class PlatformCommandManager {
.append(HelpGenerator.create(e.getCommandParseResult()).getUsage()) .append(HelpGenerator.create(e.getCommandParseResult()).getUsage())
.build()); .build());
} }
} catch (CommandExecutionException e) {
handleUnknownException(actor, e.getCause());
} catch (CommandException e) {
actor.print(TextComponent.builder("") actor.print(TextComponent.builder("")
.color(TextColor.RED) .color(TextColor.RED)
.append(e.getRichMessage()) .append(e.getRichMessage())
.build()); .build());
List<String> argList = parseArgs(event.getArguments()).map(Substring::getSubstring).collect(Collectors.toList()); } catch (CommandExecutionException e) {
printUsage(actor, argList); handleUnknownException(actor, e.getCause());
} catch (CommandException e) {
Component msg = e.getRichMessage();
if (msg != TextComponent.empty()) {
actor.print(TextComponent.builder("")
.color(TextColor.RED)
.append(msg)
.build());
List<String> argList = parseArgs(event.getArguments()).map(Substring::getSubstring).collect(Collectors.toList());
printUsage(actor, argList);
}
} catch (Throwable t) { } catch (Throwable t) {
handleUnknownException(actor, t); handleUnknownException(actor, t);
} finally { } finally {
if (context instanceof MemoizingValueAccess) { if (context instanceof MemoizingValueAccess) {
context = ((MemoizingValueAccess) context).snapshotMemory(); context = ((MemoizingValueAccess) context).snapshotMemory();
} else {
System.out.println("Invalid context " + context);
} }
Optional<EditSession> editSessionOpt = context.injectedValue(Key.of(EditSession.class)); Optional<EditSession> editSessionOpt = context.injectedValue(Key.of(EditSession.class));
@ -783,7 +805,7 @@ public final class PlatformCommandManager {
getCommandManager(), actor, "//help"); getCommandManager(), actor, "//help");
} }
private MemoizingValueAccess initializeInjectedValues(Arguments arguments, Actor tmp) { private MemoizingValueAccess initializeInjectedValues(Arguments arguments, Actor tmp, Event event) {
InjectedValueStore store = MapBackedValueStore.create(); InjectedValueStore store = MapBackedValueStore.create();
Actor actor = wrapActor(tmp, store); Actor actor = wrapActor(tmp, store);
store.injectValue(Key.of(Actor.class), ValueProvider.constant(actor)); store.injectValue(Key.of(Actor.class), ValueProvider.constant(actor));
@ -801,9 +823,10 @@ public final class PlatformCommandManager {
localSession.tellVersion(actor); localSession.tellVersion(actor);
return Optional.of(localSession); return Optional.of(localSession);
}); });
store.injectValue(Key.of(InjectedValueStore.class), ValueProvider.constant(store));
store.injectValue(Key.of(Event.class), ValueProvider.constant(event));
return MemoizingValueAccess.wrap( return MemoizingValueAccess.wrap(
MergedValueAccess.of(store, globalInjectedValues) MergedValueAccess.of(store, globalInjectedValues)
); );
} }
@ -821,7 +844,7 @@ public final class PlatformCommandManager {
List<String> argStrings = split.stream() List<String> argStrings = split.stream()
.map(Substring::getSubstring) .map(Substring::getSubstring)
.collect(Collectors.toList()); .collect(Collectors.toList());
MemoizingValueAccess access = initializeInjectedValues(() -> arguments, event.getActor()); MemoizingValueAccess access = initializeInjectedValues(() -> arguments, event.getActor(), event);
ImmutableSet<Suggestion> suggestions; ImmutableSet<Suggestion> suggestions;
try { try {
suggestions = commandManager.getSuggestions(access, argStrings); suggestions = commandManager.getSuggestions(access, argStrings);
@ -832,7 +855,6 @@ public final class PlatformCommandManager {
} }
throw t; throw t;
} }
event.setSuggestions(suggestions.stream() event.setSuggestions(suggestions.stream()
.map(suggestion -> { .map(suggestion -> {
int noSlashLength = arguments.length() - 1; int noSlashLength = arguments.length() - 1;

View File

@ -2,20 +2,24 @@ package com.sk89q.worldedit.extension.platform.binding;
import com.boydti.fawe.util.MathMan; import com.boydti.fawe.util.MathMan;
import com.boydti.fawe.util.image.ImageUtil; import com.boydti.fawe.util.image.ImageUtil;
import com.sk89q.worldedit.UnknownDirectionException;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.util.annotation.Confirm;
import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.NoMatchException; import com.sk89q.worldedit.extension.input.NoMatchException;
import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.internal.annotation.Direction; import com.sk89q.worldedit.internal.annotation.Selection;
import com.sk89q.worldedit.internal.expression.Expression;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
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.biome.BiomeTypes; import com.sk89q.worldedit.world.biome.BiomeTypes;
@ -26,14 +30,73 @@ 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.registry.BiomeRegistry; import com.sk89q.worldedit.world.registry.BiomeRegistry;
import org.enginehub.piston.CommandManager; import org.enginehub.piston.CommandManager;
import org.enginehub.piston.inject.InjectedValueStore; import org.enginehub.piston.converter.ConversionResult;
import org.enginehub.piston.exception.StopExecutionException;
import org.enginehub.piston.inject.InjectedValueAccess;
import org.enginehub.piston.inject.Key; import org.enginehub.piston.inject.Key;
import java.util.Collection; import java.util.Collection;
public class ConsumeBindings extends Bindings { public class ConsumeBindings extends Bindings {
public ConsumeBindings(WorldEdit worldEdit) { private final PlatformCommandManager manager;
public ConsumeBindings(WorldEdit worldEdit, PlatformCommandManager manager) {
super(worldEdit); super(worldEdit);
this.manager = manager;
}
@Binding
@Confirm
@Selection
public int regionMultiple(Actor actor, InjectedValueAccess context, @Selection Region region, String argument) {
int times = (int) Expression.compile(argument).evaluate();
return Confirm.Processor.REGION.check(actor, context, times);
}
@Binding
@Confirm(Confirm.Processor.RADIUS)
public Integer radiusInteger(Actor actor, InjectedValueAccess context, String argument) {
int times = (int) Expression.compile(argument).evaluate();
return Confirm.Processor.RADIUS.check(actor, context, times);
}
@Binding
@Confirm(Confirm.Processor.LIMIT)
public Integer limitInteger(Actor actor, InjectedValueAccess context, String argument) {
int times = (int) Expression.compile(argument).evaluate();
return Confirm.Processor.LIMIT.check(actor, context, times);
}
@Binding
@Confirm(Confirm.Processor.RADIUS)
public Double radiusDouble(Actor actor, InjectedValueAccess context, String argument) {
double times = Expression.compile(argument).evaluate();
return Confirm.Processor.RADIUS.check(actor, context, times);
}
@Binding
@Confirm(Confirm.Processor.LIMIT)
public Double limitDouble(Actor actor, InjectedValueAccess context, String argument) {
double times = Expression.compile(argument).evaluate();
return Confirm.Processor.LIMIT.check(actor, context, times);
}
@Binding
@Confirm(Confirm.Processor.RADIUS)
public BlockVector2 radiusVec2(Actor actor, InjectedValueAccess context, String argument) {
BlockVector2 radius = manager.parseConverter(argument, context, BlockVector2.class);
double length = radius.length();
Confirm.Processor.RADIUS.check(actor, context, length);
return radius;
}
@Binding
@Confirm(Confirm.Processor.RADIUS)
public BlockVector3 radiusVec3(Actor actor, InjectedValueAccess context, String argument) {
BlockVector3 radius = manager.parseConverter(argument, context, BlockVector3.class);
double length = radius.length();
Confirm.Processor.RADIUS.check(actor, context, length);
return radius;
} }
@Binding @Binding

View File

@ -19,9 +19,6 @@
package com.sk89q.worldedit.internal.command; package com.sk89q.worldedit.internal.command;
import static com.google.common.base.Preconditions.checkState;
import static java.util.stream.Collectors.toList;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
@ -32,13 +29,6 @@ import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.event.ClickEvent; import com.sk89q.worldedit.util.formatting.text.event.ClickEvent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor; import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldedit.util.formatting.text.format.TextDecoration; import com.sk89q.worldedit.util.formatting.text.format.TextDecoration;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.enginehub.piston.Command; import org.enginehub.piston.Command;
import org.enginehub.piston.CommandParameters; import org.enginehub.piston.CommandParameters;
import org.enginehub.piston.NoInputCommandParameters; import org.enginehub.piston.NoInputCommandParameters;
@ -47,19 +37,30 @@ import org.enginehub.piston.inject.InjectedValueAccess;
import org.enginehub.piston.inject.Key; import org.enginehub.piston.inject.Key;
import org.enginehub.piston.part.SubCommandPart; import org.enginehub.piston.part.SubCommandPart;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkState;
import static java.util.stream.Collectors.toList;
public class CommandUtil { public class CommandUtil {
private static final Component DEPRECATION_MARKER = TextComponent.of("This command is deprecated."); private static final Component DEPRECATION_MARKER = TextComponent.of("This command is deprecated.");
private static Component makeDeprecatedFooter(String reason, Component newCommand) { private static Component makeDeprecatedFooter(String reason, Component newCommand) {
return TextComponent.builder() return TextComponent.builder()
.append(DEPRECATION_MARKER) .append(DEPRECATION_MARKER)
.append(" " + reason + ".") .append(" " + reason + ".")
.append(TextComponent.newline()) .append(TextComponent.newline())
.append(TextComponent.of("Use ", TextColor.GOLD, TextDecoration.ITALIC)) .append(TextComponent.of("Use ", TextColor.GOLD, TextDecoration.ITALIC))
.append(newCommand) .append(newCommand)
.append(TextComponent.of(" instead.", TextColor.GOLD, TextDecoration.ITALIC)) .append(TextComponent.of(" instead.", TextColor.GOLD, TextDecoration.ITALIC))
.build(); .build();
} }
public interface NewCommandGenerator { public interface NewCommandGenerator {
@ -71,45 +72,45 @@ public class CommandUtil {
public static Command deprecate(Command command, String reason, public static Command deprecate(Command command, String reason,
NewCommandGenerator newCommandGenerator) { NewCommandGenerator newCommandGenerator) {
Component deprecatedWarning = makeDeprecatedFooter( Component deprecatedWarning = makeDeprecatedFooter(
reason, reason,
newCommandSuggestion(newCommandGenerator, newCommandSuggestion(newCommandGenerator,
NoInputCommandParameters.builder().build(), NoInputCommandParameters.builder().build(),
command) command)
); );
return command.toBuilder() return command.toBuilder()
.action(parameters -> .action(parameters ->
deprecatedCommandWarning(parameters, command, reason, newCommandGenerator)) deprecatedCommandWarning(parameters, command, reason, newCommandGenerator))
.footer(command.getFooter() .footer(command.getFooter()
.map(existingFooter -> existingFooter .map(existingFooter -> existingFooter
.append(TextComponent.newline()).append(deprecatedWarning)) .append(TextComponent.newline()).append(deprecatedWarning))
.orElse(deprecatedWarning)) .orElse(deprecatedWarning))
.build(); .build();
} }
public static Optional<Component> footerWithoutDeprecation(Command command) { public static Optional<Component> footerWithoutDeprecation(Command command) {
return command.getFooter() return command.getFooter()
.filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER))) .filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER)))
.map(footer -> Optional.of( .map(footer -> Optional.of(
replaceDeprecation(footer) replaceDeprecation(footer)
)) ))
.orElseGet(command::getFooter); .orElseGet(command::getFooter);
} }
public static Optional<Component> deprecationWarning(Command command) { public static Optional<Component> deprecationWarning(Command command) {
return command.getFooter() return command.getFooter()
.map(CommandUtil::extractDeprecation) .map(CommandUtil::extractDeprecation)
.orElseGet(command::getFooter); .orElseGet(command::getFooter);
} }
public static boolean isDeprecated(Command command) { public static boolean isDeprecated(Command command) {
return command.getFooter() return command.getFooter()
.filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER))) .filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER)))
.isPresent(); .isPresent();
} }
private static boolean anyComponent(Component component, Predicate<Component> test) { private static boolean anyComponent(Component component, Predicate<Component> test) {
return test.test(component) || component.children().stream() return test.test(component) || component.children().stream()
.anyMatch(x -> anyComponent(x, test)); .anyMatch(x -> anyComponent(x, test));
} }
private static Component replaceDeprecation(Component component) { private static Component replaceDeprecation(Component component) {
@ -117,9 +118,9 @@ public class CommandUtil {
return TextComponent.empty(); return TextComponent.empty();
} }
return component.children( return component.children(
component.children().stream() component.children().stream()
.map(CommandUtil::replaceDeprecation) .map(CommandUtil::replaceDeprecation)
.collect(toList()) .collect(toList())
); );
} }
@ -128,26 +129,26 @@ public class CommandUtil {
return Optional.of(component); return Optional.of(component);
} }
return component.children().stream() return component.children().stream()
.map(CommandUtil::extractDeprecation) .map(CommandUtil::extractDeprecation)
.filter(Optional::isPresent) .filter(Optional::isPresent)
.map(Optional::get) .map(Optional::get)
.findAny(); .findAny();
} }
private static Object deprecatedCommandWarning( private static Object deprecatedCommandWarning(
CommandParameters parameters, CommandParameters parameters,
Command command, Command command,
String reason, String reason,
NewCommandGenerator generator NewCommandGenerator generator
) throws Exception { ) throws Exception {
parameters.injectedValue(Key.of(Actor.class)) parameters.injectedValue(Key.of(Actor.class))
.ifPresent(actor -> { .ifPresent(actor -> {
Component suggestion = newCommandSuggestion(generator, parameters, command); Component suggestion = newCommandSuggestion(generator, parameters, command);
actor.print(TextComponent.of(reason + ". Please use ", TextColor.GOLD) actor.print(TextComponent.of(reason + ". Please use ", TextColor.GOLD)
.append(suggestion) .append(suggestion)
.append(TextComponent.of(" instead.")) .append(TextComponent.of(" instead."))
); );
}); });
return command.getAction().run(parameters); return command.getAction().run(parameters);
} }
@ -156,15 +157,15 @@ public class CommandUtil {
Command command) { Command command) {
String suggestedCommand = generator.newCommand(command, parameters); String suggestedCommand = generator.newCommand(command, parameters);
return TextComponent.of(suggestedCommand) return TextComponent.of(suggestedCommand)
.decoration(TextDecoration.UNDERLINED, true) .decoration(TextDecoration.UNDERLINED, true)
.clickEvent(ClickEvent.suggestCommand(suggestedCommand)); .clickEvent(ClickEvent.suggestCommand(suggestedCommand));
} }
public static Map<String, Command> getSubCommands(Command currentCommand) { public static Map<String, Command> getSubCommands(Command currentCommand) {
return currentCommand.getParts().stream() return currentCommand.getParts().stream()
.filter(p -> p instanceof SubCommandPart) .filter(p -> p instanceof SubCommandPart)
.flatMap(p -> ((SubCommandPart) p).getCommands().stream()) .flatMap(p -> ((SubCommandPart) p).getCommands().stream())
.collect(Collectors.toMap(Command::getName, Function.identity())); .collect(Collectors.toMap(Command::getName, Function.identity()));
} }
private static String clean(String input) { private static String clean(String input) {
@ -172,7 +173,7 @@ public class CommandUtil {
} }
private static final Comparator<Command> BY_CLEAN_NAME = private static final Comparator<Command> BY_CLEAN_NAME =
Comparator.comparing(c -> clean(c.getName())); Comparator.comparing(c -> clean(c.getName()));
public static Comparator<Command> byCleanName() { public static Comparator<Command> byCleanName() {
return BY_CLEAN_NAME; return BY_CLEAN_NAME;
@ -183,15 +184,15 @@ public class CommandUtil {
*/ */
public static List<String> fixSuggestions(String arguments, List<Substring> suggestions) { public static List<String> fixSuggestions(String arguments, List<Substring> suggestions) {
Substring lastArg = Iterables.getLast( Substring lastArg = Iterables.getLast(
CommandArgParser.spaceSplit(arguments) CommandArgParser.spaceSplit(arguments)
); );
return suggestions.stream() return suggestions.stream()
// Re-map suggestions to only operate on the last non-quoted word // Re-map suggestions to only operate on the last non-quoted word
.map(suggestion -> onlyOnLastQuotedWord(lastArg, suggestion)) .map(suggestion -> onlyOnLastQuotedWord(lastArg, suggestion))
.map(suggestion -> suggestLast(lastArg, suggestion)) .map(suggestion -> suggestLast(lastArg, suggestion))
.filter(Optional::isPresent) .filter(Optional::isPresent)
.map(Optional::get) .map(Optional::get)
.collect(toList()); .collect(toList());
} }
private static Substring onlyOnLastQuotedWord(Substring lastArg, Substring suggestion) { private static Substring onlyOnLastQuotedWord(Substring lastArg, Substring suggestion) {
@ -227,7 +228,7 @@ public class CommandUtil {
return Optional.empty(); return Optional.empty();
} }
checkState(end <= builder.length(), checkState(end <= builder.length(),
"Suggestion ends too late, last=%s, suggestion=", last, suggestion); "Suggestion ends too late, last=%s, suggestion=", last, suggestion);
builder.replace(start, end, suggestion.getSubstring()); builder.replace(start, end, suggestion.getSubstring());
return Optional.of(builder.toString()); return Optional.of(builder.toString());
} }
@ -258,10 +259,10 @@ public class CommandUtil {
public static <T> T requireIV(Key<T> type, String name, InjectedValueAccess injectedValueAccess) { public static <T> T requireIV(Key<T> type, String name, InjectedValueAccess injectedValueAccess) {
return injectedValueAccess.injectedValue(type).orElseThrow(() -> return injectedValueAccess.injectedValue(type).orElseThrow(() ->
new IllegalStateException("No injected value for " + name + " (type " + type + ")") new IllegalStateException("No injected value for " + name + " (type " + type + ")")
); );
} }
private CommandUtil() { private CommandUtil() {
} }
} }

View File

@ -0,0 +1,47 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.internal.command;
import com.sk89q.worldedit.command.util.annotation.Confirm;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import org.enginehub.piston.CommandParameters;
import org.enginehub.piston.exception.StopExecutionException;
import org.enginehub.piston.gen.CommandCallListener;
import org.enginehub.piston.inject.Key;
import java.lang.reflect.Method;
/**
* Logs called commands to a logger.
*/
public class ConfirmHandler implements CommandCallListener {
@Override
public void beforeCall(Method method, CommandParameters parameters) {
Confirm confirmAnnotation = method.getAnnotation(Confirm.class);
if (confirmAnnotation == null) {
return;
}
Actor actor = parameters.injectedValue(Key.of(Actor.class)).get();
if (!confirmAnnotation.value().passes(actor, parameters, 1)) {
throw new StopExecutionException(TextComponent.empty());
}
}
}

View File

@ -0,0 +1,19 @@
package com.sk89q.worldedit.internal.command;
import org.enginehub.piston.CommandParameters;
import org.enginehub.piston.gen.CommandCallListener;
import org.enginehub.piston.inject.InjectedValueAccess;
import org.enginehub.piston.inject.InjectedValueStore;
import org.enginehub.piston.inject.Key;
import org.enginehub.piston.util.ValueProvider;
import java.lang.reflect.Method;
import java.util.Optional;
public class MethodInjector implements CommandCallListener {
@Override
public void beforeCall(Method commandMethod, CommandParameters parameters) {
InjectedValueStore store = parameters.injectedValue(Key.of(InjectedValueStore.class)).get();
store.injectValue(Key.of(Method.class), ValueProvider.constant(commandMethod));
}
}