use of org.enginehub.piston.exception.StopExecutionException in project FastAsyncWorldEdit by IntellectualSites.
the class Bindings method invoke.
private Object invoke(String arg, Function<InjectedValueAccess, Object>[] argsFunc, InjectedValueAccess access, Method method) {
try {
Object[] args = new Object[argsFunc.length];
for (int i = 0; i < argsFunc.length; i++) {
Function<InjectedValueAccess, Object> func = argsFunc[i];
if (func != null) {
Optional optional = (Optional) func.apply(access);
args[i] = optional.get();
} else {
args[i] = arg;
}
}
return method.invoke(this, args);
} catch (IllegalAccessException | InvocationTargetException e) {
if (!(e.getCause() instanceof StopExecutionException)) {
throw new RuntimeException(e);
}
return null;
}
}
use of org.enginehub.piston.exception.StopExecutionException in project FastAsyncWorldEdit by IntellectualSites.
the class SelectionCommands method chunk.
@Command(name = "/chunk", desc = "Set the selection to your current chunk.", descFooter = "This command selects 256-block-tall areas,\nwhich can be specified by the y-coordinate.\nE.g. -c x,1,z will select from y=256 to y=511.")
@Logging(POSITION)
@CommandPermissions("worldedit.selection.chunk")
public void chunk(Actor actor, World world, LocalSession session, @Arg(desc = "The chunk to select", def = "") BlockVector3 coordinates, @Switch(name = 's', desc = "Expand your selection to encompass all chunks that are part of it") boolean expandSelection, @Switch(name = 'c', desc = "Use chunk coordinates instead of block coordinates") boolean useChunkCoordinates) throws WorldEditException {
final BlockVector3 min;
final BlockVector3 max;
if (expandSelection) {
Region region = session.getSelection(world);
int minChunkY = world.getMinY() >> CHUNK_SHIFTS_Y;
int maxChunkY = world.getMaxY() >> CHUNK_SHIFTS_Y;
BlockVector3 minChunk = ChunkStore.toChunk3d(region.getMinimumPoint()).clampY(minChunkY, maxChunkY);
BlockVector3 maxChunk = ChunkStore.toChunk3d(region.getMaximumPoint()).clampY(minChunkY, maxChunkY);
min = minChunk.shl(CHUNK_SHIFTS, CHUNK_SHIFTS_Y, CHUNK_SHIFTS);
max = maxChunk.shl(CHUNK_SHIFTS, CHUNK_SHIFTS_Y, CHUNK_SHIFTS).add(15, 255, 15);
actor.print(Caption.of("worldedit.chunk.selected-multiple", TextComponent.of(minChunk.getBlockX()), TextComponent.of(minChunk.getBlockY()), TextComponent.of(minChunk.getBlockZ()), TextComponent.of(maxChunk.getBlockX()), TextComponent.of(maxChunk.getBlockY()), TextComponent.of(maxChunk.getBlockZ())));
} else {
BlockVector3 minChunk;
if (coordinates != null) {
// coords specified
minChunk = useChunkCoordinates ? coordinates : ChunkStore.toChunk3d(coordinates);
} else {
// use player loc
if (actor instanceof Locatable) {
minChunk = ChunkStore.toChunk3d(((Locatable) actor).getBlockLocation().toVector().toBlockPoint());
} else {
throw new StopExecutionException(TextComponent.of("A player or coordinates are required."));
}
}
min = minChunk.shl(CHUNK_SHIFTS, CHUNK_SHIFTS_Y, CHUNK_SHIFTS);
max = min.add(15, 255, 15);
actor.print(Caption.of("worldedit.chunk.selected", TextComponent.of(minChunk.getBlockX()), TextComponent.of(minChunk.getBlockY()), TextComponent.of(minChunk.getBlockZ())));
}
final CuboidRegionSelector selector;
if (session.getRegionSelector(world) instanceof ExtendingCuboidRegionSelector) {
selector = new ExtendingCuboidRegionSelector(world);
} else {
selector = new CuboidRegionSelector(world);
}
selector.selectPrimary(min, ActorSelectorLimits.forActor(actor));
selector.selectSecondary(max, ActorSelectorLimits.forActor(actor));
session.setRegionSelector(world, selector);
session.dispatchCUISelection(actor);
}
use of org.enginehub.piston.exception.StopExecutionException in project FastAsyncWorldEdit by IntellectualSites.
the class ChunkCommands method deleteChunks.
@Command(name = "delchunks", aliases = { "/delchunks" }, desc = "Delete chunks that your selection includes")
@CommandPermissions("worldedit.delchunks")
@Logging(REGION)
public void deleteChunks(Actor actor, World world, LocalSession session, @ArgFlag(name = 'o', desc = "Only delete chunks older than the specified time.") ZonedDateTime beforeTime) throws WorldEditException {
Path worldDir = world.getStoragePath();
if (worldDir == null) {
throw new StopExecutionException(TextComponent.of("Couldn't find world folder for this world."));
}
Path chunkPath = worldEdit.getWorkingDirectoryPath(DELCHUNKS_FILE_NAME);
ChunkDeletionInfo currentInfo = null;
if (Files.exists(chunkPath)) {
try {
currentInfo = ChunkDeleter.readInfo(chunkPath);
} catch (IOException e) {
throw new StopExecutionException(TextComponent.of("Error reading existing chunk file."));
}
}
if (currentInfo == null) {
currentInfo = new ChunkDeletionInfo();
currentInfo.batches = new ArrayList<>();
}
ChunkDeletionInfo.ChunkBatch newBatch = new ChunkDeletionInfo.ChunkBatch();
newBatch.worldPath = worldDir.toAbsolutePath().normalize().toString();
newBatch.backup = true;
final Region selection = session.getSelection(world);
if (selection instanceof CuboidRegion) {
newBatch.minChunk = selection.getMinimumPoint().shr(4).toBlockVector2();
newBatch.maxChunk = selection.getMaximumPoint().shr(4).toBlockVector2();
} else {
// this has a possibility to OOM for very large selections still
Set<BlockVector2> chunks = selection.getChunks();
newBatch.chunks = new ArrayList<>(chunks);
}
if (beforeTime != null) {
newBatch.deletionPredicates = new ArrayList<>();
ChunkDeletionInfo.DeletionPredicate timePred = new ChunkDeletionInfo.DeletionPredicate();
timePred.property = "modification";
timePred.comparison = "<";
timePred.value = String.valueOf((int) beforeTime.toOffsetDateTime().toEpochSecond());
newBatch.deletionPredicates.add(timePred);
}
currentInfo.batches.add(newBatch);
try {
ChunkDeleter.writeInfo(currentInfo, chunkPath);
} catch (IOException | JsonIOException e) {
throw new StopExecutionException(TextComponent.of("Failed to write chunk list: " + e.getMessage()));
}
actor.print(TextComponent.of(String.format("%d chunk(s) have been marked for deletion the next time the server starts.", newBatch.getChunkCount())));
if (currentInfo.batches.size() > 1) {
actor.printDebug(TextComponent.of(String.format("%d chunks total marked for deletion. (May have overlaps).", currentInfo.batches.stream().mapToInt(ChunkDeletionInfo.ChunkBatch::getChunkCount).sum())));
}
actor.print(TextComponent.of("You can mark more chunks for deletion, or to stop now, run: ", TextColor.LIGHT_PURPLE).append(TextComponent.of("/stop", TextColor.AQUA).clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, "/stop"))));
}
use of org.enginehub.piston.exception.StopExecutionException in project FastAsyncWorldEdit by IntellectualSites.
the class ListFilters method wildcard.
@Command(// TODO NOT IMPLEMENTED originally this was left blank but doing so causes a major compilation error
name = "*", desc = "wildcard")
public Filter wildcard(Actor actor, File root, String arg) {
arg = arg.replace("/", File.separator);
String argLower = arg.toLowerCase(Locale.ROOT);
if (arg.endsWith(File.separator)) {
String finalArg = arg;
return new Filter() {
@Override
public File getPath(File root) {
File newRoot = new File(root, finalArg);
if (newRoot.exists()) {
return newRoot;
}
String firstArg = finalArg.substring(0, finalArg.length() - File.separator.length());
if (firstArg.length() > 3 && firstArg.length() <= 16) {
UUID fromName = Fawe.platform().getUUID(finalArg);
if (fromName != null) {
newRoot = new File(root, finalArg);
if (newRoot.exists()) {
return newRoot;
}
}
}
throw new StopExecutionException(TextComponent.of("Cannot find path: " + finalArg));
}
};
} else {
if (StringMan.containsAny(arg, "\\^$.|?+(){}<>~$!%^&*+-/")) {
Pattern pattern;
try {
pattern = Pattern.compile(argLower);
} catch (PatternSyntaxException ignored) {
pattern = Pattern.compile(Pattern.quote(argLower));
}
Pattern finalPattern = pattern;
return new Filter() {
@Override
public boolean applies(File file) {
String path = file.getPath().toLowerCase(Locale.ROOT);
return finalPattern.matcher(path).find();
}
};
}
return new Filter() {
@Override
public boolean applies(File file) {
return StringMan.containsIgnoreCase(file.getPath(), argLower);
}
};
}
}
use of org.enginehub.piston.exception.StopExecutionException in project FastAsyncWorldEdit by IntellectualSites.
the class SchematicCommands method list.
@Command(name = "list", aliases = { "all", "ls" }, desc = "List saved schematics", descFooter = "Note: Format is not fully verified until loading.")
@CommandPermissions("worldedit.schematic.list")
public void list(Actor actor, LocalSession session, @ArgFlag(name = 'p', desc = "Page to view.", def = "1") int page, @Switch(name = 'd', desc = "Sort by date, oldest first") boolean oldFirst, @Switch(name = 'n', desc = "Sort by date, newest first") boolean newFirst, @ArgFlag(name = 'f', desc = "Restricts by format.", def = "") String formatName, @Arg(name = "filter", desc = "Filter for schematics", def = "all") String filter, Arguments arguments) throws WorldEditException {
if (oldFirst && newFirst) {
throw new StopExecutionException(Caption.of("worldedit.schematic.sorting-old-new"));
}
// FAWE start
String pageCommand = "/" + arguments.get();
LocalConfiguration config = worldEdit.getConfiguration();
File dir = worldEdit.getWorkingDirectoryPath(config.saveDir).toFile();
String schemCmd = "//schematic";
String loadSingle = schemCmd + " load";
String loadMulti = schemCmd + " loadall";
String unload = schemCmd + " unload";
String delete = schemCmd + " delete";
String list = schemCmd + " list";
String showCmd = schemCmd + " show";
List<String> args = filter.isEmpty() ? Collections.emptyList() : Arrays.asList(filter.split(" "));
URIClipboardHolder multi = as(URIClipboardHolder.class, session.getExistingClipboard());
final boolean hasShow = false;
// If player forgot -p argument
boolean playerFolder = Settings.settings().PATHS.PER_PLAYER_SCHEMATICS;
UUID uuid = playerFolder ? actor.getUniqueId() : null;
List<File> files = UtilityCommands.getFiles(dir, actor, args, formatName, playerFolder, oldFirst, newFirst);
List<Map.Entry<URI, String>> entries = UtilityCommands.filesToEntry(dir, files, uuid);
Function<URI, Boolean> isLoaded = multi == null ? f -> false : multi::contains;
List<Component> components = UtilityCommands.entryToComponent(dir, entries, isLoaded, (name, path, type, loaded) -> {
TextComponentProducer msg = new TextComponentProducer();
msg.append(Caption.of("worldedit.schematic.dash.symbol"));
if (loaded) {
msg.append(Caption.of("worldedit.schematic.minus.symbol").clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, unload + " " + path)).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.unload"))));
} else {
msg.append(Caption.of("worldedit.schematic.plus.symbol").clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, loadMulti + " " + path)).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.clipboard"))));
}
if (type != UtilityCommands.URIType.DIRECTORY) {
msg.append(Caption.of("worldedit.schematic.x.symbol").clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, delete + " " + path)).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.delete"))));
} else if (hasShow) {
msg.append(Caption.of("worldedit.schematic.0.symbol").clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, showCmd + " " + path)).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.visualize"))));
}
TextComponent msgElem = TextComponent.of(name);
if (type != UtilityCommands.URIType.DIRECTORY) {
msgElem = msgElem.clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, loadSingle + " " + path));
msgElem = msgElem.hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.load")));
} else {
msgElem = msgElem.clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, list + " " + path));
msgElem = msgElem.hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, Caption.of("worldedit.schematic.list")));
}
msg.append(msgElem);
if (type == UtilityCommands.URIType.FILE) {
long filesize = 0;
try {
filesize = Files.size(Paths.get(dir.getAbsolutePath() + File.separator + (playerFolder ? (uuid.toString() + File.separator) : "") + path));
} catch (IOException e) {
e.printStackTrace();
}
TextComponent sizeElem = TextComponent.of(String.format(" (%.1f kb)", filesize / 1000.0), TextColor.GRAY);
msg.append(sizeElem);
}
return msg.create();
});
long totalBytes = 0;
File parentDir = new File(dir.getAbsolutePath() + (playerFolder ? File.separator + uuid.toString() : ""));
try {
List<File> toAddUp = getFiles(parentDir, null, null);
if (toAddUp != null && toAddUp.size() != 0) {
for (File schem : toAddUp) {
if (schem.getName().endsWith(".schem") || schem.getName().endsWith(".schematic")) {
totalBytes += Files.size(Paths.get(schem.getAbsolutePath()));
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
String headerBytesElem = String.format("%.1fkb", totalBytes / 1000.0);
if (Settings.settings().PATHS.PER_PLAYER_SCHEMATICS && Settings.settings().EXPERIMENTAL.PER_PLAYER_FILE_SIZE_LIMIT > -1) {
headerBytesElem += String.format(" / %dkb", Settings.settings().EXPERIMENTAL.PER_PLAYER_FILE_SIZE_LIMIT);
}
if (Settings.settings().PATHS.PER_PLAYER_SCHEMATICS) {
String fullHeader = "| My Schematics: " + headerBytesElem + " |";
PaginationBox paginationBox = PaginationBox.fromComponents(fullHeader, pageCommand, components);
actor.print(paginationBox.create(page));
} else {
String fullHeader = "| Schematics: " + headerBytesElem + " |";
PaginationBox paginationBox = PaginationBox.fromComponents(fullHeader, pageCommand, components);
actor.print(paginationBox.create(page));
}
// FAWE end
}
Aggregations