Merge support for platform capabilities and overhaul of command executors.

This commit is contained in:
sk89q 2014-06-28 19:29:26 -07:00
commit bc73d12f25
145 changed files with 8441 additions and 1983 deletions

View File

@ -44,6 +44,7 @@ dependencies {
compile group: 'com.google.guava', name: 'guava', version:'10.0.1' compile group: 'com.google.guava', name: 'guava', version:'10.0.1'
compile group: 'com.sk89q', name: 'jchronic', version:'0.2.4a' compile group: 'com.sk89q', name: 'jchronic', version:'0.2.4a'
compile group: 'com.google.code.findbugs', name: 'jsr305', version: '1.3.9' compile group: 'com.google.code.findbugs', name: 'jsr305', version: '1.3.9'
compile group: 'com.thoughtworks.paranamer', name: 'paranamer', version: '2.6'
testCompile group: 'org.mockito', name: 'mockito-core', version:'1.9.0-rc1' testCompile group: 'org.mockito', name: 'mockito-core', version:'1.9.0-rc1'
} }
@ -87,6 +88,7 @@ shadow {
destinationDir "${buildDir}/libs/" destinationDir "${buildDir}/libs/"
artifactSet { artifactSet {
include '*:jchronic:jar:' include '*:jchronic:jar:'
include '*:paranamer:jar:'
} }
} }

37
pom.xml
View File

@ -97,6 +97,13 @@
</repository> </repository>
</repositories> </repositories>
<pluginRepositories>
<pluginRepository>
<id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url>
</pluginRepository>
</pluginRepositories>
<dependencies> <dependencies>
<!-- Used for snapshots --> <!-- Used for snapshots -->
<dependency> <dependency>
@ -151,6 +158,15 @@
<type>jar</type> <type>jar</type>
</dependency> </dependency>
<!-- Method names for the command framework -->
<dependency>
<groupId>com.thoughtworks.paranamer</groupId>
<artifactId>paranamer</artifactId>
<version>2.6</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<!-- Unit tests --> <!-- Unit tests -->
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
@ -297,6 +313,26 @@
</configuration> </configuration>
</plugin> </plugin>
<!-- Stores parameter information -->
<plugin>
<groupId>com.thoughtworks.paranamer</groupId>
<artifactId>paranamer-maven-plugin-largestack</artifactId>
<version>2.5.5-SNAPSHOT</version>
<executions>
<execution>
<id>run</id>
<phase>compile</phase>
<configuration>
<sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>
<outputDirectory>${project.build.outputDirectory}</outputDirectory>
</configuration>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- JAR plugin --> <!-- JAR plugin -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
@ -352,6 +388,7 @@
<artifactSet> <artifactSet>
<includes> <includes>
<include>com.sk89q:jchronic</include> <include>com.sk89q:jchronic</include>
<include>com.thoughtworks.paranamer:paranamer</include>
</includes> </includes>
</artifactSet> </artifactSet>
</configuration> </configuration>

View File

@ -0,0 +1,32 @@
/*
* 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.bukkit.util;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
public interface CommandInspector {
String getShortText(Command command);
String getFullText(Command command);
boolean testPermission(CommandSender sender, Command command);
}

View File

@ -26,9 +26,12 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginIdentifiableCommand; import org.bukkit.command.PluginIdentifiableCommand;
import org.bukkit.command.TabCompleter;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/** /**
* An implementation of a dynamically registered {@link org.bukkit.command.Command} attached to a plugin * An implementation of a dynamically registered {@link org.bukkit.command.Command} attached to a plugin
@ -76,6 +79,15 @@ public class DynamicPluginCommand extends org.bukkit.command.Command implements
return owningPlugin; return owningPlugin;
} }
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
if (owner instanceof TabCompleter) {
return ((TabCompleter) owner).onTabComplete(sender, this, alias, args);
} else {
return Collections.emptyList();
}
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public boolean testPermissionSilent(CommandSender sender) { public boolean testPermissionSilent(CommandSender sender) {
@ -83,7 +95,10 @@ public class DynamicPluginCommand extends org.bukkit.command.Command implements
return true; return true;
} }
if (registeredWith instanceof CommandsManager<?>) { if (registeredWith instanceof CommandInspector) {
CommandInspector resolver = (CommandInspector) registeredWith;
return resolver.testPermission(sender, this);
} else if (registeredWith instanceof CommandsManager<?>) {
try { try {
for (String permission : permissions) { for (String permission : permissions) {
if (((CommandsManager<CommandSender>) registeredWith).hasPermission(sender, permission)) { if (((CommandsManager<CommandSender>) registeredWith).hasPermission(sender, permission)) {

View File

@ -40,55 +40,64 @@ public class DynamicPluginCommandHelpTopic extends HelpTopic {
this.cmd = cmd; this.cmd = cmd;
this.name = "/" + cmd.getName(); this.name = "/" + cmd.getName();
String fullTextTemp = null; if (cmd.getRegisteredWith() instanceof CommandInspector) {
StringBuilder fullText = new StringBuilder(); CommandInspector resolver = (CommandInspector) cmd.getRegisteredWith();
this.shortText = resolver.getShortText(cmd);
if (cmd.getRegisteredWith() instanceof CommandsManager) { this.fullText = resolver.getFullText(cmd);
Map<String, String> helpText = ((CommandsManager<?>) cmd.getRegisteredWith()).getHelpMessages();
final String lookupName = cmd.getName().replaceAll("/", "");
if (helpText.containsKey(lookupName)) { // We have full help text for this command
fullTextTemp = helpText.get(lookupName);
}
// No full help text, assemble help text from info
helpText = ((CommandsManager<?>) cmd.getRegisteredWith()).getCommands();
if (helpText.containsKey(cmd.getName())) {
final String shortText = helpText.get(cmd.getName());
if (fullTextTemp == null) {
fullTextTemp = this.name + " " + shortText;
}
this.shortText = shortText;
}
} else { } else {
this.shortText = cmd.getDescription(); String fullTextTemp = null;
} StringBuilder fullText = new StringBuilder();
// Put the usage in the format: Usage string (newline) Aliases (newline) Help text if (cmd.getRegisteredWith() instanceof CommandsManager) {
String[] split = fullTextTemp == null ? new String[2] : fullTextTemp.split("\n", 2); Map<String, String> helpText = ((CommandsManager<?>) cmd.getRegisteredWith()).getHelpMessages();
fullText.append(ChatColor.BOLD).append(ChatColor.GOLD).append("Usage: ").append(ChatColor.WHITE); final String lookupName = cmd.getName().replaceAll("/", "");
fullText.append(split[0]).append("\n"); if (helpText.containsKey(lookupName)) { // We have full help text for this command
fullTextTemp = helpText.get(lookupName);
if (cmd.getAliases().size() > 0) {
fullText.append(ChatColor.BOLD).append(ChatColor.GOLD).append("Aliases: ").append(ChatColor.WHITE);
boolean first = true;
for (String alias : cmd.getAliases()) {
if (!first) {
fullText.append(", ");
} }
fullText.append(alias); // No full help text, assemble help text from info
first = false; helpText = ((CommandsManager<?>) cmd.getRegisteredWith()).getCommands();
if (helpText.containsKey(cmd.getName())) {
final String shortText = helpText.get(cmd.getName());
if (fullTextTemp == null) {
fullTextTemp = this.name + " " + shortText;
}
this.shortText = shortText;
}
} else {
this.shortText = cmd.getDescription();
} }
fullText.append("\n");
// Put the usage in the format: Usage string (newline) Aliases (newline) Help text
String[] split = fullTextTemp == null ? new String[2] : fullTextTemp.split("\n", 2);
fullText.append(ChatColor.BOLD).append(ChatColor.GOLD).append("Usage: ").append(ChatColor.WHITE);
fullText.append(split[0]).append("\n");
if (!cmd.getAliases().isEmpty()) {
fullText.append(ChatColor.BOLD).append(ChatColor.GOLD).append("Aliases: ").append(ChatColor.WHITE);
boolean first = true;
for (String alias : cmd.getAliases()) {
if (!first) {
fullText.append(", ");
}
fullText.append(alias);
first = false;
}
fullText.append("\n");
}
if (split.length > 1) {
fullText.append(split[1]);
}
this.fullText = fullText.toString();
} }
if (split.length > 1) {
fullText.append(split[1]);
}
this.fullText = fullText.toString();
} }
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public boolean canSee(CommandSender player) { public boolean canSee(CommandSender player) {
if (cmd.getPermissions() != null && cmd.getPermissions().length > 0) { if (cmd.getRegisteredWith() instanceof CommandInspector) {
CommandInspector resolver = (CommandInspector) cmd.getRegisteredWith();
return resolver.testPermission(player, cmd);
} else if (cmd.getPermissions() != null && cmd.getPermissions().length > 0) {
if (cmd.getRegisteredWith() instanceof CommandsManager) { if (cmd.getRegisteredWith() instanceof CommandsManager) {
try { try {
for (String perm : cmd.getPermissions()) { for (String perm : cmd.getPermissions()) {
@ -123,7 +132,7 @@ public class DynamicPluginCommandHelpTopic extends HelpTopic {
@Override @Override
public String getFullText(CommandSender forWho) { public String getFullText(CommandSender forWho) {
if (this.fullText == null || this.fullText.length() == 0) { if (this.fullText == null || this.fullText.isEmpty()) {
return getShortText(); return getShortText();
} else { } else {
return this.fullText; return this.fullText;

View File

@ -0,0 +1,83 @@
/*
* 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.bukkit;
import com.sk89q.bukkit.util.CommandInspector;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.command.CommandMapping;
import com.sk89q.worldedit.util.command.Description;
import com.sk89q.worldedit.util.command.Dispatcher;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import java.util.logging.Logger;
import static com.google.common.base.Preconditions.checkNotNull;
class BukkitCommandInspector implements CommandInspector {
private static final Logger logger = Logger.getLogger(BukkitCommandInspector.class.getCanonicalName());
private final WorldEditPlugin plugin;
private final Dispatcher dispatcher;
BukkitCommandInspector(WorldEditPlugin plugin, Dispatcher dispatcher) {
checkNotNull(plugin);
checkNotNull(dispatcher);
this.plugin = plugin;
this.dispatcher = dispatcher;
}
@Override
public String getShortText(Command command) {
CommandMapping mapping = dispatcher.get(command.getName());
if (mapping != null) {
return mapping.getDescription().getShortDescription();
} else {
logger.warning("BukkitCommandInspector doesn't know how about the command '" + command + "'");
return "Help text not available";
}
}
@Override
public String getFullText(Command command) {
CommandMapping mapping = dispatcher.get(command.getName());
if (mapping != null) {
Description description = mapping.getDescription();
return "Usage: " + description.getUsage() + (description.getHelp() != null ? "\n" + description.getHelp() : "");
} else {
logger.warning("BukkitCommandInspector doesn't know how about the command '" + command + "'");
return "Help text not available";
}
}
@Override
public boolean testPermission(CommandSender sender, Command command) {
CommandMapping mapping = dispatcher.get(command.getName());
if (mapping != null) {
CommandLocals locals = new CommandLocals();
locals.put(Actor.class, plugin.wrapCommandSender(sender));
return mapping.getCallable().testPermission(locals);
} else {
logger.warning("BukkitCommandInspector doesn't know how about the command '" + command + "'");
return false;
}
}
}

View File

@ -19,18 +19,29 @@
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.PlayerNeededException;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.WorldEditPermissionException;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.internal.cui.CUIEvent;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class BukkitCommandSender extends LocalPlayer { import java.io.File;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
class BukkitCommandSender implements Actor {
private CommandSender sender; private CommandSender sender;
private WorldEditPlugin plugin; private WorldEditPlugin plugin;
public BukkitCommandSender(WorldEditPlugin plugin, ServerInterface server, CommandSender sender) { BukkitCommandSender(WorldEditPlugin plugin, CommandSender sender) {
super(server); checkNotNull(plugin);
checkNotNull(sender);
checkArgument(!(sender instanceof Player), "Cannot wrap a player");
this.plugin = plugin; this.plugin = plugin;
this.sender = sender; this.sender = sender;
} }
@ -68,6 +79,11 @@ public class BukkitCommandSender extends LocalPlayer {
} }
} }
@Override
public boolean canDestroyBedrock() {
return true;
}
@Override @Override
public String[] getGroups() { public String[] getGroups() {
return new String[0]; return new String[0];
@ -75,60 +91,30 @@ public class BukkitCommandSender extends LocalPlayer {
@Override @Override
public boolean hasPermission(String perm) { public boolean hasPermission(String perm) {
if (!plugin.getLocalConfiguration().noOpPermissions && sender.isOp()) { return true;
return true; }
}
return plugin.getPermissionsResolver().hasPermission(null, sender.getName(), perm); @Override
public void checkPermission(String permission) throws WorldEditPermissionException {
} }
@Override @Override
public boolean isPlayer() { public boolean isPlayer() {
return sender instanceof Player; return false;
} }
@Override @Override
public int getItemInHand() { public File openFileOpenDialog(String[] extensions) {
throw new PlayerNeededException(); return null;
} }
@Override @Override
public Location getLocation() { public File openFileSaveDialog(String[] extensions) {
throw new PlayerNeededException(); return null;
} }
@Override @Override
public WorldVector getPosition() { public void dispatchCUIEvent(CUIEvent event) {
throw new PlayerNeededException();
} }
@Override
public LocalWorld getWorld() {
throw new PlayerNeededException();
}
@Override
public double getPitch() {
throw new PlayerNeededException();
}
@Override
public double getYaw() {
throw new PlayerNeededException();
}
@Override
public void giveItem(int type, int amt) {
throw new PlayerNeededException();
}
@Override
public void setPosition(Vector pos, float pitch, float yaw) {
throw new PlayerNeededException();
}
@Override
public BlockBag getInventoryBlockBag() {
throw new PlayerNeededException();
}
} }

View File

@ -41,7 +41,6 @@ public class BukkitPlayer extends LocalPlayer {
private WorldEditPlugin plugin; private WorldEditPlugin plugin;
public BukkitPlayer(WorldEditPlugin plugin, ServerInterface server, Player player) { public BukkitPlayer(WorldEditPlugin plugin, ServerInterface server, Player player) {
super(server);
this.plugin = plugin; this.plugin = plugin;
this.player = player; this.player = player;
} }
@ -52,6 +51,7 @@ public class BukkitPlayer extends LocalPlayer {
return itemStack != null ? itemStack.getTypeId() : 0; return itemStack != null ? itemStack.getTypeId() : 0;
} }
@Override
public BaseBlock getBlockInHand() throws WorldEditException { public BaseBlock getBlockInHand() throws WorldEditException {
ItemStack itemStack = player.getItemInHand(); ItemStack itemStack = player.getItemInHand();
return BukkitUtil.toBlock(getWorld(), itemStack); return BukkitUtil.toBlock(getWorld(), itemStack);

View File

@ -21,19 +21,25 @@ package com.sk89q.worldedit.bukkit;
import com.sk89q.bukkit.util.CommandInfo; import com.sk89q.bukkit.util.CommandInfo;
import com.sk89q.bukkit.util.CommandRegistration; import com.sk89q.bukkit.util.CommandRegistration;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.worldedit.BiomeTypes;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.minecraft.util.commands.CommandsManager; import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.ServerInterface;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Preference;
import com.sk89q.worldedit.util.command.CommandMapping;
import com.sk89q.worldedit.util.command.Description;
import com.sk89q.worldedit.util.command.Dispatcher;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import java.lang.reflect.Method; import javax.annotation.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.EnumMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -42,6 +48,7 @@ public class BukkitServerInterface extends ServerInterface {
public WorldEditPlugin plugin; public WorldEditPlugin plugin;
private CommandRegistration dynamicCommands; private CommandRegistration dynamicCommands;
private BukkitBiomeTypes biomes; private BukkitBiomeTypes biomes;
private boolean hookingEvents;
public BukkitServerInterface(WorldEditPlugin plugin, Server server) { public BukkitServerInterface(WorldEditPlugin plugin, Server server) {
this.plugin = plugin; this.plugin = plugin;
@ -50,6 +57,10 @@ public class BukkitServerInterface extends ServerInterface {
dynamicCommands = new CommandRegistration(plugin); dynamicCommands = new CommandRegistration(plugin);
} }
boolean isHookingEvents() {
return hookingEvents;
}
@Override @Override
public int resolveItem(String name) { public int resolveItem(String name) {
Material mat = Material.matchMaterial(name); Material mat = Material.matchMaterial(name);
@ -89,31 +100,50 @@ public class BukkitServerInterface extends ServerInterface {
return ret; return ret;
} }
@Nullable
@Override @Override
public void onCommandRegistration(List<Command> commands, CommandsManager<LocalPlayer> manager) { public Player matchPlayer(Player player) {
if (player instanceof BukkitPlayer) {
return player;
} else {
org.bukkit.entity.Player bukkitPlayer = server.getPlayerExact(player.getName());
return bukkitPlayer != null ? new BukkitPlayer(plugin, this, bukkitPlayer) : null;
}
}
@Nullable
@Override
public com.sk89q.worldedit.world.World matchWorld(com.sk89q.worldedit.world.World world) {
if (world instanceof BukkitWorld) {
return world;
} else {
World bukkitWorld = server.getWorld(world.getName());
return bukkitWorld != null ? new BukkitWorld(bukkitWorld) : null;
}
}
@Override
public void registerCommands(Dispatcher dispatcher) {
List<CommandInfo> toRegister = new ArrayList<CommandInfo>(); List<CommandInfo> toRegister = new ArrayList<CommandInfo>();
for (Command command : commands) { BukkitCommandInspector inspector = new BukkitCommandInspector(plugin, dispatcher);
List<String> permissions = null;
Method cmdMethod = manager.getMethods().get(null).get(command.aliases()[0]); for (CommandMapping command : dispatcher.getCommands()) {
Map<String, Method> childMethods = manager.getMethods().get(cmdMethod); Description description = command.getDescription();
List<String> permissions = description.getPermissions();
String[] permissionsArray = new String[permissions.size()];
permissions.toArray(permissionsArray);
if (cmdMethod != null && cmdMethod.isAnnotationPresent(CommandPermissions.class)) { toRegister.add(new CommandInfo(description.getUsage(), description.getShortDescription(), command.getAllAliases(), inspector, permissionsArray));
permissions = Arrays.asList(cmdMethod.getAnnotation(CommandPermissions.class).value());
} else if (cmdMethod != null && childMethods != null && childMethods.size() > 0) {
permissions = new ArrayList<String>();
for (Method m : childMethods.values()) {
if (m.isAnnotationPresent(CommandPermissions.class)) {
permissions.addAll(Arrays.asList(m.getAnnotation(CommandPermissions.class).value()));
}
}
}
toRegister.add(new CommandInfo(command.usage(), command.desc(), command.aliases(), commands, permissions == null ? null : permissions.toArray(new String[permissions.size()])));
} }
dynamicCommands.register(toRegister); dynamicCommands.register(toRegister);
} }
@Override
public void registerGameHooks() {
hookingEvents = true;
}
@Override @Override
public LocalConfiguration getConfiguration() { public LocalConfiguration getConfiguration() {
return plugin.getLocalConfiguration(); return plugin.getLocalConfiguration();
@ -134,6 +164,17 @@ public class BukkitServerInterface extends ServerInterface {
return plugin.getDescription().getVersion(); return plugin.getDescription().getVersion();
} }
@Override
public Map<Capability, Preference> getCapabilities() {
Map<Capability, Preference> capabilities = new EnumMap<Capability, Preference>(Capability.class);
capabilities.put(Capability.CONFIGURATION, Preference.NORMAL);
capabilities.put(Capability.GAME_HOOKS, Preference.PREFERRED);
capabilities.put(Capability.PERMISSIONS, Preference.PREFERRED);
capabilities.put(Capability.USER_COMMANDS, Preference.PREFERRED);
capabilities.put(Capability.WORLD_EDITING, Preference.PREFER_OTHERS);
return capabilities;
}
public void unregisterCommands() { public void unregisterCommands() {
dynamicCommands.unregisterCommands(); dynamicCommands.unregisterCommands();
} }

View File

@ -1110,13 +1110,15 @@ public class BukkitWorld extends LocalWorld {
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
World world = getWorld(); if (other == null) {
return false;
if (!(other instanceof BukkitWorld)) { } else if ((other instanceof BukkitWorld)) {
return ((BukkitWorld) other).getWorld().equals(getWorld());
} else if (other instanceof com.sk89q.worldedit.world.World) {
return ((com.sk89q.worldedit.world.World) other).getName().equals(getName());
} else {
return false; return false;
} }
return ((BukkitWorld) other).getWorld().equals(world);
} }
@Override @Override

View File

@ -69,11 +69,19 @@ public class WorldEditListener implements Listener {
*/ */
@EventHandler @EventHandler
public void onPlayerQuit(PlayerQuitEvent event) { public void onPlayerQuit(PlayerQuitEvent event) {
if (!plugin.getInternalPlatform().isHookingEvents()) {
return;
}
plugin.getWorldEdit().markExpire(plugin.wrapPlayer(event.getPlayer())); plugin.getWorldEdit().markExpire(plugin.wrapPlayer(event.getPlayer()));
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onGamemode(PlayerGameModeChangeEvent event) { public void onGamemode(PlayerGameModeChangeEvent event) {
if (!plugin.getInternalPlatform().isHookingEvents()) {
return;
}
// this will automatically refresh their sesssion, we don't have to do anything // this will automatically refresh their sesssion, we don't have to do anything
WorldEdit.getInstance().getSession(plugin.wrapPlayer(event.getPlayer())); WorldEdit.getInstance().getSession(plugin.wrapPlayer(event.getPlayer()));
} }
@ -88,20 +96,21 @@ public class WorldEditListener implements Listener {
String[] split = event.getMessage().split(" "); String[] split = event.getMessage().split(" ");
if (split.length > 0) { if (split.length > 0) {
split = plugin.getWorldEdit().commandDetection(split); split[0] = split[0].substring(1);
split[0] = "/" + split[0]; split = plugin.getWorldEdit().getPlatformManager().getCommandManager().commandDetection(split);
} }
final String newMessage = StringUtil.joinString(split, " "); final String newMessage = "/" + StringUtil.joinString(split, " ");
if (!newMessage.equals(event.getMessage())) { if (!newMessage.equals(event.getMessage())) {
event.setMessage(newMessage); event.setMessage(newMessage);
plugin.getServer().getPluginManager().callEvent(event); plugin.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {
if (event.getMessage().length() > 0) { if (!event.getMessage().isEmpty()) {
plugin.getServer().dispatchCommand(event.getPlayer(), plugin.getServer().dispatchCommand(event.getPlayer(), event.getMessage().substring(1));
event.getMessage().substring(1));
} }
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -114,6 +123,10 @@ public class WorldEditListener implements Listener {
*/ */
@EventHandler @EventHandler
public void onPlayerInteract(PlayerInteractEvent event) { public void onPlayerInteract(PlayerInteractEvent event) {
if (!plugin.getInternalPlatform().isHookingEvents()) {
return;
}
if (event.useItemInHand() == Result.DENY) { if (event.useItemInHand() == Result.DENY) {
return; return;
} }

View File

@ -19,6 +19,7 @@
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import com.google.common.base.Joiner;
import com.sk89q.util.yaml.YAMLProcessor; import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.wepif.PermissionsResolverManager; import com.sk89q.wepif.PermissionsResolverManager;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
@ -26,20 +27,22 @@ import com.sk89q.worldedit.bukkit.selections.CuboidSelection;
import com.sk89q.worldedit.bukkit.selections.CylinderSelection; import com.sk89q.worldedit.bukkit.selections.CylinderSelection;
import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection; import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection;
import com.sk89q.worldedit.bukkit.selections.Selection; import com.sk89q.worldedit.bukkit.selections.Selection;
import com.sk89q.worldedit.extension.platform.PlatformRejectionException; import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.event.platform.CommandSuggestionEvent;
import com.sk89q.worldedit.event.platform.PlatformReadyEvent;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.*;
import com.sk89q.worldedit.regions.CylinderRegion;
import com.sk89q.worldedit.regions.Polygonal2DRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import java.io.*; import java.io.*;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
@ -49,7 +52,7 @@ import java.util.zip.ZipEntry;
* *
* @author sk89q * @author sk89q
*/ */
public class WorldEditPlugin extends JavaPlugin { public class WorldEditPlugin extends JavaPlugin implements TabCompleter {
/** /**
* The name of the CUI's plugin channel registration * The name of the CUI's plugin channel registration
@ -106,21 +109,19 @@ public class WorldEditPlugin extends JavaPlugin {
// Setup interfaces // Setup interfaces
server = new BukkitServerInterface(this, getServer()); server = new BukkitServerInterface(this, getServer());
controller = WorldEdit.getInstance(); controller = WorldEdit.getInstance();
try { controller.getPlatformManager().register(server);
controller.getPlatformManager().register(server); api = new WorldEditAPI(this);
api = new WorldEditAPI(this); getServer().getMessenger().registerIncomingPluginChannel(this, CUI_PLUGIN_CHANNEL, new CUIChannelListener(this));
getServer().getMessenger().registerIncomingPluginChannel(this, CUI_PLUGIN_CHANNEL, new CUIChannelListener(this)); getServer().getMessenger().registerOutgoingPluginChannel(this, CUI_PLUGIN_CHANNEL);
getServer().getMessenger().registerOutgoingPluginChannel(this, CUI_PLUGIN_CHANNEL); // Now we can register events!
// Now we can register events! getServer().getPluginManager().registerEvents(new WorldEditListener(this), this);
getServer().getPluginManager().registerEvents(new WorldEditListener(this), this);
getServer().getScheduler().runTaskTimerAsynchronously(this, getServer().getScheduler().runTaskTimerAsynchronously(this, new SessionTimer(controller, getServer()), 120, 120);
new SessionTimer(controller, getServer()), 120, 120);
} catch (PlatformRejectionException e) { // If we are on MCPC+/Cauldron, then Forge will have already loaded
throw new RuntimeException( // Forge WorldEdit and there's (probably) not going to be any other
"WorldEdit rejected the Bukkit implementation of WorldEdit! This is strange and should " + // platforms to be worried about... at the current time of writing
"not have happened. Please report this error.", e); WorldEdit.getInstance().getEventBus().post(new PlatformReadyEvent());
}
} }
private void copyNmsBlockClasses(File target) { private void copyNmsBlockClasses(File target) {
@ -220,24 +221,33 @@ public class WorldEditPlugin extends JavaPlugin {
} }
} }
/**
* Called on WorldEdit command.
*/
@Override @Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
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] = "/" + cmd.getName(); split[0] = cmd.getName();
controller.handleCommand(wrapCommandSender(sender), split); CommandEvent event = new CommandEvent(wrapCommandSender(sender), Joiner.on(" ").join(split));
getWorldEdit().getEventBus().post(event);
return true; return true;
} }
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String commandLabel, String[] args) {
// Add the command to the array because the underlying command handling
// code of WorldEdit expects it
String[] split = new String[args.length + 1];
System.arraycopy(args, 0, split, 1, args.length);
split[0] = cmd.getName();
CommandSuggestionEvent event = new CommandSuggestionEvent(wrapCommandSender(sender), Joiner.on(" ").join(split));
getWorldEdit().getEventBus().post(event);
return event.getSuggestions();
}
/** /**
* Gets the session for the player. * Gets the session for the player.
* *
@ -340,12 +350,12 @@ public class WorldEditPlugin extends JavaPlugin {
return new BukkitPlayer(this, this.server, player); return new BukkitPlayer(this, this.server, player);
} }
public LocalPlayer wrapCommandSender(CommandSender sender) { public Actor wrapCommandSender(CommandSender sender) {
if (sender instanceof Player) { if (sender instanceof Player) {
return wrapPlayer((Player) sender); return wrapPlayer((Player) sender);
} }
return new BukkitCommandSender(this, this.server, sender); return new BukkitCommandSender(this, sender);
} }
/** /**
@ -357,6 +367,10 @@ public class WorldEditPlugin extends JavaPlugin {
return server; return server;
} }
BukkitServerInterface getInternalPlatform() {
return server;
}
/** /**
* Get WorldEdit. * Get WorldEdit.
* *

View File

@ -19,36 +19,49 @@
package com.sk89q.worldedit.forge; package com.sk89q.worldedit.forge;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.worldedit.BiomeTypes; import com.sk89q.worldedit.BiomeTypes;
import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.ServerInterface; import com.sk89q.worldedit.ServerInterface;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Preference;
import com.sk89q.worldedit.util.command.CommandMapping;
import com.sk89q.worldedit.util.command.Description;
import com.sk89q.worldedit.util.command.Dispatcher;
import com.sk89q.worldedit.world.World;
import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLCommonHandler;
import net.minecraft.command.CommandBase; import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommand; import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
import net.minecraft.command.ServerCommandManager; import net.minecraft.command.ServerCommandManager;
import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityList;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer; import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.DimensionManager;
import java.util.ArrayList; import javax.annotation.Nullable;
import java.util.Arrays; import java.util.*;
import java.util.List;
class ForgePlatform extends ServerInterface { class ForgePlatform extends ServerInterface {
private final ForgeWorldEdit mod; private final ForgeWorldEdit mod;
private final MinecraftServer server; private final MinecraftServer server;
private final ForgeBiomeTypes biomes; private final ForgeBiomeTypes biomes;
private boolean hookingEvents = false;
public ForgePlatform(ForgeWorldEdit mod) { ForgePlatform(ForgeWorldEdit mod) {
this.mod = mod; this.mod = mod;
this.server = FMLCommonHandler.instance().getMinecraftServerInstance(); this.server = FMLCommonHandler.instance().getMinecraftServerInstance();
this.biomes = new ForgeBiomeTypes(); this.biomes = new ForgeBiomeTypes();
} }
boolean isHookingEvents() {
return hookingEvents;
}
@Override
public int resolveItem(String name) { public int resolveItem(String name) {
if (name == null) return 0; if (name == null) return 0;
for (Item item : Item.itemsList) { for (Item item : Item.itemsList) {
@ -65,21 +78,26 @@ class ForgePlatform extends ServerInterface {
return 0; return 0;
} }
@Override
public boolean isValidMobType(String type) { public boolean isValidMobType(String type) {
return EntityList.stringToClassMapping.containsKey(type); return EntityList.stringToClassMapping.containsKey(type);
} }
@Override
public void reload() { public void reload() {
} }
@Override
public BiomeTypes getBiomes() { public BiomeTypes getBiomes() {
return this.biomes; return this.biomes;
} }
@Override
public int schedule(long delay, long period, Runnable task) { public int schedule(long delay, long period, Runnable task) {
return -1; return -1;
} }
@Override
public List<? extends com.sk89q.worldedit.world.World> getWorlds() { public List<? extends com.sk89q.worldedit.world.World> getWorlds() {
List<WorldServer> worlds = Arrays.asList(DimensionManager.getWorlds()); List<WorldServer> worlds = Arrays.asList(DimensionManager.getWorlds());
List<com.sk89q.worldedit.world.World> ret = new ArrayList<com.sk89q.worldedit.world.World>(worlds.size()); List<com.sk89q.worldedit.world.World> ret = new ArrayList<com.sk89q.worldedit.world.World>(worlds.size());
@ -89,20 +107,50 @@ class ForgePlatform extends ServerInterface {
return ret; return ret;
} }
@Nullable
@Override @Override
public void onCommandRegistration(List<Command> commands) { public Player matchPlayer(Player player) {
if (player instanceof ForgePlayer) {
return player;
} else {
EntityPlayerMP entity = server.getConfigurationManager().getPlayerForUsername(player.getName());
return entity != null ? new ForgePlayer(entity) : null;
}
}
@Nullable
@Override
public World matchWorld(World world) {
if (world instanceof ForgeWorld) {
return world;
} else {
for (WorldServer ws : DimensionManager.getWorlds()) {
if (ws.getWorldInfo().getWorldName().equals(world.getName())) {
return new ForgeWorld(ws);
}
}
return null;
}
}
@Override
public void registerCommands(Dispatcher dispatcher) {
if (server == null) return; if (server == null) return;
ServerCommandManager mcMan = (ServerCommandManager) server.getCommandManager(); ServerCommandManager mcMan = (ServerCommandManager) server.getCommandManager();
for (final Command cmd : commands) {
for (final CommandMapping command : dispatcher.getCommands()) {
final Description description = command.getDescription();
mcMan.registerCommand(new CommandBase() { mcMan.registerCommand(new CommandBase() {
@Override @Override
public String getCommandName() { public String getCommandName() {
return cmd.aliases()[0]; return command.getPrimaryAlias();
} }
@Override @Override
public List<String> getCommandAliases() { public List<String> getCommandAliases() {
return Arrays.asList(cmd.aliases()); return Arrays.asList(command.getAllAliases());
} }
@Override @Override
@ -110,12 +158,14 @@ class ForgePlatform extends ServerInterface {
@Override @Override
public String getCommandUsage(ICommandSender icommandsender) { public String getCommandUsage(ICommandSender icommandsender) {
return "/" + cmd.aliases()[0] + " " + cmd.usage(); return "/" + command.getPrimaryAlias() + " " + description.getUsage();
} }
@Override @Override
public int compareTo(Object o) { public int compareTo(@Nullable Object o) {
if (o instanceof ICommand) { if (o == null) {
return -1;
} else if (o instanceof ICommand) {
return super.compareTo((ICommand) o); return super.compareTo((ICommand) o);
} else { } else {
return -1; return -1;
@ -125,6 +175,12 @@ class ForgePlatform extends ServerInterface {
} }
} }
@Override
public void registerGameHooks() {
// We registered the events already anyway, so we just 'turn them on'
hookingEvents = true;
}
@Override @Override
public LocalConfiguration getConfiguration() { public LocalConfiguration getConfiguration() {
return mod.getConfig(); return mod.getConfig();
@ -144,4 +200,16 @@ class ForgePlatform extends ServerInterface {
public String getPlatformVersion() { public String getPlatformVersion() {
return mod.getInternalVersion(); return mod.getInternalVersion();
} }
@Override
public Map<Capability, Preference> getCapabilities() {
Map<Capability, Preference> capabilities = new EnumMap<Capability, Preference>(Capability.class);
capabilities.put(Capability.CONFIGURATION, Preference.PREFER_OTHERS);
capabilities.put(Capability.GAME_HOOKS, Preference.NORMAL);
capabilities.put(Capability.PERMISSIONS, Preference.PREFER_OTHERS);
capabilities.put(Capability.USER_COMMANDS, Preference.NORMAL);
capabilities.put(Capability.WORLD_EDITING, Preference.PREFERRED);
return capabilities;
}
} }

View File

@ -38,7 +38,6 @@ public class ForgePlayer extends LocalPlayer {
private EntityPlayerMP player; private EntityPlayerMP player;
protected ForgePlayer(EntityPlayerMP player) { protected ForgePlayer(EntityPlayerMP player) {
super((ServerInterface) ForgeWorldEdit.inst.getPlatform());
this.player = player; this.player = player;
} }

View File

@ -107,7 +107,7 @@ public class ForgeWorld extends AbstractWorld {
@Override @Override
public String getName() { public String getName() {
return getWorld().provider.getDimensionName(); return getWorld().getWorldInfo().getWorldName();
} }
@Override @Override
@ -459,11 +459,15 @@ public class ForgeWorld extends AbstractWorld {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if ((o instanceof ForgeWorld)) { if (o == null) {
ForgeWorld other = ((ForgeWorld) o); return false;
World otherWorld = other.worldRef.get(); } else if ((o instanceof ForgeWorld)) {
World thisWorld = other.worldRef.get(); ForgeWorld other = ((ForgeWorld) o);
return otherWorld != null && thisWorld != null && otherWorld.equals(thisWorld); World otherWorld = other.worldRef.get();
World thisWorld = other.worldRef.get();
return otherWorld != null && thisWorld != null && otherWorld.equals(thisWorld);
} else if (o instanceof com.sk89q.worldedit.world.World) {
return ((com.sk89q.worldedit.world.World) o).getName().equals(getName());
} else { } else {
return false; return false;
} }

View File

@ -19,13 +19,14 @@
package com.sk89q.worldedit.forge; package com.sk89q.worldedit.forge;
import com.google.common.base.Joiner;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import com.google.common.io.Closer; import com.google.common.io.Closer;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldVector; import com.sk89q.worldedit.WorldVector;
import com.sk89q.worldedit.event.platform.PlatformReadyEvent;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extension.platform.PlatformRejectionException;
import com.sk89q.worldedit.internal.LocalWorldAdapter; import com.sk89q.worldedit.internal.LocalWorldAdapter;
import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod;
@ -103,11 +104,8 @@ public class ForgeWorldEdit {
} }
this.platform = new ForgePlatform(this); this.platform = new ForgePlatform(this);
try {
WorldEdit.getInstance().getPlatformManager().register(platform); WorldEdit.getInstance().getPlatformManager().register(platform);
} catch (PlatformRejectionException e) {
throw new RuntimeException("Failed to register with WorldEdit", e);
}
} }
@EventHandler @EventHandler
@ -115,19 +113,28 @@ public class ForgeWorldEdit {
WorldEdit.getInstance().getPlatformManager().unregister(platform); WorldEdit.getInstance().getPlatformManager().unregister(platform);
} }
@EventHandler
public void serverStarted(FMLServerStartedEvent event) {
WorldEdit.getInstance().getEventBus().post(new PlatformReadyEvent());
}
@ForgeSubscribe @ForgeSubscribe
public void onCommandEvent(CommandEvent event) { public void onCommandEvent(CommandEvent event) {
if ((event.sender instanceof EntityPlayerMP)) { if ((event.sender instanceof EntityPlayerMP)) {
if (((EntityPlayerMP) event.sender).worldObj.isRemote) return; if (((EntityPlayerMP) event.sender).worldObj.isRemote) return;
String[] split = new String[event.parameters.length + 1]; String[] split = new String[event.parameters.length + 1];
System.arraycopy(event.parameters, 0, split, 1, event.parameters.length); System.arraycopy(event.parameters, 0, split, 1, event.parameters.length);
split[0] = ("/" + event.command.getCommandName()); split[0] = event.command.getCommandName();
WorldEdit.getInstance().handleCommand(wrap((EntityPlayerMP) event.sender), split); com.sk89q.worldedit.event.platform.CommandEvent weEvent =
new com.sk89q.worldedit.event.platform.CommandEvent(wrap((EntityPlayerMP) event.sender), Joiner.on(" ").join(split));
WorldEdit.getInstance().getEventBus().post(weEvent);
} }
} }
@ForgeSubscribe @ForgeSubscribe
public void onPlayerInteract(PlayerInteractEvent event) { public void onPlayerInteract(PlayerInteractEvent event) {
if (!platform.isHookingEvents()) return; // We have to be told to catch these events
if (event.useItem == Result.DENY || event.entity.worldObj.isRemote) return; if (event.useItem == Result.DENY || event.entity.worldObj.isRemote) return;
WorldEdit we = WorldEdit.getInstance(); WorldEdit we = WorldEdit.getInstance();

View File

@ -9,6 +9,7 @@
<allow pkg="org.mockito"/> <allow pkg="org.mockito"/>
<allow pkg="com.sk89q"/> <allow pkg="com.sk89q"/>
<allow pkg="com.google.common"/> <allow pkg="com.google.common"/>
<allow pkg="com.thoughtworks.paranamer"/>
<subpackage name="util.yaml"> <subpackage name="util.yaml">
<allow pkg="org.yaml.snakeyaml"/> <allow pkg="org.yaml.snakeyaml"/>

View File

@ -28,15 +28,22 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
public class CommandContext { public class CommandContext {
protected final String command; protected final String command;
protected final List<String> parsedArgs; protected final List<String> parsedArgs;
protected final List<Integer> originalArgIndices; protected final List<Integer> originalArgIndices;
protected final String[] originalArgs; protected final String[] originalArgs;
protected final Set<Character> booleanFlags = new HashSet<Character>(); protected final Set<Character> booleanFlags = new HashSet<Character>();
protected final Map<Character, String> valueFlags = new HashMap<Character, String>(); protected final Map<Character, String> valueFlags = new HashMap<Character, String>();
protected final SuggestionContext suggestionContext;
protected final CommandLocals locals;
public static String[] split(String args) {
return args.split(" ", -1);
}
public CommandContext(String args) throws CommandException { public CommandContext(String args) throws CommandException {
this(args.split(" "), null); this(args.split(" ", -1), null);
} }
public CommandContext(String[] args) throws CommandException { public CommandContext(String[] args) throws CommandException {
@ -44,28 +51,50 @@ public class CommandContext {
} }
public CommandContext(String args, Set<Character> valueFlags) throws CommandException { public CommandContext(String args, Set<Character> valueFlags) throws CommandException {
this(args.split(" "), valueFlags); this(args.split(" ", -1), valueFlags);
}
public CommandContext(String args, Set<Character> valueFlags, boolean allowHangingFlag)
throws CommandException {
this(args.split(" ", -1), valueFlags, allowHangingFlag, new CommandLocals());
}
public CommandContext(String[] args, Set<Character> valueFlags) throws CommandException {
this(args, valueFlags, false, null);
} }
/** /**
* @param args An array with arguments. Empty strings outside quotes will be removed. * Parse the given array of arguments.
* @param valueFlags A set containing all value flags. Pass null to disable value flag parsing. *
* @throws CommandException This is thrown if flag fails for some reason. * <p>Empty arguments are removed from the list of arguments.</p>
*
* @param args an array with arguments
* @param valueFlags a set containing all value flags (pass null to disable value flag parsing)
* @param allowHangingFlag true if hanging flags are allowed
* @param locals the locals, null to create empty one
* @throws CommandException thrown on a parsing error
*/ */
public CommandContext(String[] args, Set<Character> valueFlags) throws CommandException { public CommandContext(String[] args, Set<Character> valueFlags,
boolean allowHangingFlag, CommandLocals locals) throws CommandException {
if (valueFlags == null) { if (valueFlags == null) {
valueFlags = Collections.emptySet(); valueFlags = Collections.emptySet();
} }
originalArgs = args; originalArgs = args;
command = args[0]; command = args[0];
this.locals = locals != null ? locals : new CommandLocals();
boolean isHanging = false;
SuggestionContext suggestionContext = SuggestionContext.hangingValue();
// Eliminate empty args and combine multiword args first // Eliminate empty args and combine multiword args first
List<Integer> argIndexList = new ArrayList<Integer>(args.length); List<Integer> argIndexList = new ArrayList<Integer>(args.length);
List<String> argList = new ArrayList<String>(args.length); List<String> argList = new ArrayList<String>(args.length);
for (int i = 1; i < args.length; ++i) { for (int i = 1; i < args.length; ++i) {
isHanging = false;
String arg = args[i]; String arg = args[i];
if (arg.length() == 0) { if (arg.length() == 0) {
isHanging = true;
continue; continue;
} }
@ -113,9 +142,14 @@ public class CommandContext {
for (int nextArg = 0; nextArg < argList.size(); ) { for (int nextArg = 0; nextArg < argList.size(); ) {
// Fetch argument // Fetch argument
String arg = argList.get(nextArg++); String arg = argList.get(nextArg++);
suggestionContext = SuggestionContext.hangingValue();
// Not a flag? // Not a flag?
if (arg.charAt(0) != '-' || arg.length() == 1 || !arg.matches("^-[a-zA-Z]+$")) { if (arg.charAt(0) != '-' || arg.length() == 1 || !arg.matches("^-[a-zA-Z]+$")) {
if (!isHanging) {
suggestionContext = SuggestionContext.lastValue();
}
originalArgIndices.add(argIndexList.get(nextArg - 1)); originalArgIndices.add(argIndexList.get(nextArg - 1));
parsedArgs.add(arg); parsedArgs.add(arg);
continue; continue;
@ -140,16 +174,30 @@ public class CommandContext {
} }
if (nextArg >= argList.size()) { if (nextArg >= argList.size()) {
throw new CommandException("No value specified for the '-" + flagName + "' flag."); if (allowHangingFlag) {
suggestionContext = SuggestionContext.flag(flagName);
break;
} else {
throw new CommandException("No value specified for the '-" + flagName + "' flag.");
}
} }
// If it is a value flag, read another argument and add it // If it is a value flag, read another argument and add it
this.valueFlags.put(flagName, argList.get(nextArg++)); this.valueFlags.put(flagName, argList.get(nextArg++));
if (!isHanging) {
suggestionContext = SuggestionContext.flag(flagName);
}
} else { } else {
booleanFlags.add(flagName); booleanFlags.add(flagName);
} }
} }
} }
this.suggestionContext = suggestionContext;
}
public SuggestionContext getSuggestionContext() {
return suggestionContext;
} }
public String getCommand() { public String getCommand() {
@ -176,6 +224,18 @@ public class CommandContext {
} }
return buffer.toString(); return buffer.toString();
} }
public String getRemainingString(int start) {
return getString(start, parsedArgs.size() - 1);
}
public String getString(int start, int end) {
StringBuilder buffer = new StringBuilder(parsedArgs.get(start));
for (int i = start + 1; i < end + 1; ++i) {
buffer.append(" ").append(parsedArgs.get(i));
}
return buffer.toString();
}
public int getInteger(int index) throws NumberFormatException { public int getInteger(int index) throws NumberFormatException {
return Integer.parseInt(parsedArgs.get(index)); return Integer.parseInt(parsedArgs.get(index));
@ -271,4 +331,8 @@ public class CommandContext {
public int argsLength() { public int argsLength() {
return parsedArgs.size(); return parsedArgs.size();
} }
public CommandLocals getLocals() {
return locals;
}
} }

View File

@ -19,8 +19,14 @@
package com.sk89q.minecraft.util.commands; package com.sk89q.minecraft.util.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class CommandException extends Exception { public class CommandException extends Exception {
private static final long serialVersionUID = 870638193072101739L; private static final long serialVersionUID = 870638193072101739L;
private List<String> commandStack = new ArrayList<String>();
public CommandException() { public CommandException() {
super(); super();
@ -30,8 +36,37 @@ public class CommandException extends Exception {
super(message); super(message);
} }
public CommandException(String message, Throwable t) {
super(message, t);
}
public CommandException(Throwable t) { public CommandException(Throwable t) {
super(t); super(t);
} }
public void prependStack(String name) {
commandStack.add(name);
}
public String toStackString(String prefix, String spacedSuffix) {
StringBuilder builder = new StringBuilder();
if (prefix != null) {
builder.append(prefix);
}
ListIterator<String> li = commandStack.listIterator(commandStack.size());
while (li.hasPrevious()) {
if (li.previousIndex() != commandStack.size() - 1) {
builder.append(" ");
}
builder.append(li.previous());
}
if (spacedSuffix != null) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(spacedSuffix);
}
return builder.toString();
}
} }

View File

@ -0,0 +1,50 @@
/*
* 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.minecraft.util.commands;
import java.util.HashMap;
import java.util.Map;
public class CommandLocals {
private final Map<Object, Object> locals = new HashMap<Object, Object>();
public boolean containsKey(Object key) {
return locals.containsKey(key);
}
public boolean containsValue(Object value) {
return locals.containsValue(value);
}
public Object get(Object key) {
return locals.get(key);
}
@SuppressWarnings("unchecked")
public <T> T get(Class<T> key) {
return (T) locals.get(key);
}
public Object put(Object key, Object value) {
return locals.put(key, value);
}
}

View File

@ -0,0 +1,68 @@
/*
* 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.minecraft.util.commands;
public class SuggestionContext {
private static final SuggestionContext FOR_LAST = new SuggestionContext(null, true);
private static final SuggestionContext FOR_HANGING = new SuggestionContext(null, false);
private final Character flag;
private final boolean forLast;
private SuggestionContext(Character flag, boolean forLast) {
this.flag = flag;
this.forLast = forLast;
}
public boolean forHangingValue() {
return flag == null && !forLast;
}
public boolean forLastValue() {
return flag == null && forLast;
}
public boolean forFlag() {
return flag != null;
}
public Character getFlag() {
return flag;
}
@Override
public String toString() {
return forFlag() ? ("-" + getFlag()) : (forHangingValue() ? "hanging" : "last");
}
public static SuggestionContext flag(Character flag) {
return new SuggestionContext(flag, false);
}
public static SuggestionContext lastValue() {
return FOR_LAST;
}
public static SuggestionContext hangingValue() {
return FOR_HANGING;
}
}

View File

@ -57,7 +57,6 @@ import com.sk89q.worldedit.history.changeset.ChangeSet;
import com.sk89q.worldedit.internal.expression.Expression; 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.internal.expression.runtime.RValue; import com.sk89q.worldedit.internal.expression.runtime.RValue;
import com.sk89q.worldedit.masks.Mask;
import com.sk89q.worldedit.math.interpolation.Interpolation; import com.sk89q.worldedit.math.interpolation.Interpolation;
import com.sk89q.worldedit.math.interpolation.KochanekBartelsInterpolation; import com.sk89q.worldedit.math.interpolation.KochanekBartelsInterpolation;
import com.sk89q.worldedit.math.interpolation.Node; import com.sk89q.worldedit.math.interpolation.Node;
@ -275,7 +274,6 @@ public class EditSession implements Extent {
* *
* @return mask, may be null * @return mask, may be null
*/ */
@SuppressWarnings("deprecation")
public Mask getMask() { public Mask getMask() {
return oldMask; return oldMask;
} }
@ -285,13 +283,24 @@ public class EditSession implements Extent {
* *
* @param mask mask or null * @param mask mask or null
*/ */
@SuppressWarnings("deprecation")
public void setMask(Mask mask) { public void setMask(Mask mask) {
this.oldMask = mask; this.oldMask = mask;
if (mask == null) { if (mask == null) {
maskingExtent.setMask(Masks.alwaysTrue()); maskingExtent.setMask(Masks.alwaysTrue());
} else { } else {
maskingExtent.setMask(Masks.wrap(mask, this)); maskingExtent.setMask(mask);
}
}
/**
* @deprecated Use {@link #setMask(Mask)}
*/
@Deprecated
public void setMask(com.sk89q.worldedit.masks.Mask mask) {
if (mask == null) {
setMask((Mask) null);
} else {
setMask(Masks.wrap(mask));
} }
} }
@ -786,7 +795,7 @@ public class EditSession implements Extent {
checkNotNull(position); checkNotNull(position);
checkArgument(apothem >= 1, "apothem >= 1"); checkArgument(apothem >= 1, "apothem >= 1");
Mask mask = new com.sk89q.worldedit.masks.FuzzyBlockMask(new BaseBlock(blockType, -1)); Mask mask = new FuzzyBlockMask(this, new BaseBlock(blockType, -1));
Vector adjustment = new Vector(1, 1, 1).multiply(apothem - 1); Vector adjustment = new Vector(1, 1, 1).multiply(apothem - 1);
Region region = new CuboidRegion( Region region = new CuboidRegion(
getWorld(), // Causes clamping of Y range getWorld(), // Causes clamping of Y range
@ -855,7 +864,7 @@ public class EditSession implements Extent {
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public int replaceBlocks(Region region, Set<BaseBlock> filter, Pattern pattern) throws MaxChangedBlocksException { public int replaceBlocks(Region region, Set<BaseBlock> filter, Pattern pattern) throws MaxChangedBlocksException {
Mask mask = filter == null ? new com.sk89q.worldedit.masks.ExistingBlockMask() : new com.sk89q.worldedit.masks.FuzzyBlockMask(filter); Mask mask = filter == null ? new ExistingBlockMask(this) : new FuzzyBlockMask(this, filter);
return replaceBlocks(region, mask, pattern); return replaceBlocks(region, mask, pattern);
} }
@ -876,7 +885,7 @@ public class EditSession implements Extent {
checkNotNull(pattern); checkNotNull(pattern);
BlockReplace replace = new BlockReplace(this, Patterns.wrap(pattern)); BlockReplace replace = new BlockReplace(this, Patterns.wrap(pattern));
RegionMaskingFilter filter = new RegionMaskingFilter(Masks.wrap(mask, this), replace); RegionMaskingFilter filter = new RegionMaskingFilter(mask, replace);
RegionVisitor visitor = new RegionVisitor(region, filter); RegionVisitor visitor = new RegionVisitor(region, filter);
Operations.completeLegacy(visitor); Operations.completeLegacy(visitor);
return visitor.getAffected(); return visitor.getAffected();

View File

@ -19,6 +19,7 @@
package com.sk89q.worldedit; package com.sk89q.worldedit;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.extent.EditSessionEvent; import com.sk89q.worldedit.event.extent.EditSessionEvent;
import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.util.eventbus.EventBus; import com.sk89q.worldedit.util.eventbus.EventBus;
@ -63,7 +64,7 @@ public class EditSessionFactory {
* @param maxBlocks the maximum number of blocks that can be changed, or -1 to use no limit * @param maxBlocks the maximum number of blocks that can be changed, or -1 to use no limit
* @param player the player that the {@link EditSession} is for * @param player the player that the {@link EditSession} is for
*/ */
public EditSession getEditSession(World world, int maxBlocks, LocalPlayer player) { public EditSession getEditSession(World world, int maxBlocks, Player player) {
throw new IllegalArgumentException("This class is being removed"); throw new IllegalArgumentException("This class is being removed");
} }
@ -96,7 +97,7 @@ public class EditSessionFactory {
* @param blockBag an optional {@link BlockBag} to use, otherwise null * @param blockBag an optional {@link BlockBag} to use, otherwise null
* @param player the player that the {@link EditSession} is for * @param player the player that the {@link EditSession} is for
*/ */
public EditSession getEditSession(World world, int maxBlocks, BlockBag blockBag, LocalPlayer player) { public EditSession getEditSession(World world, int maxBlocks, BlockBag blockBag, Player player) {
throw new IllegalArgumentException("This class is being removed"); throw new IllegalArgumentException("This class is being removed");
} }
@ -123,7 +124,7 @@ public class EditSessionFactory {
} }
@Override @Override
public EditSession getEditSession(World world, int maxBlocks, LocalPlayer player) { public EditSession getEditSession(World world, int maxBlocks, Player player) {
return new EditSession(eventBus, world, maxBlocks, null, new EditSessionEvent(world, player, maxBlocks, null)); return new EditSession(eventBus, world, maxBlocks, null, new EditSessionEvent(world, player, maxBlocks, null));
} }
@ -133,7 +134,7 @@ public class EditSessionFactory {
} }
@Override @Override
public EditSession getEditSession(World world, int maxBlocks, BlockBag blockBag, LocalPlayer player) { public EditSession getEditSession(World world, int maxBlocks, BlockBag blockBag, Player player) {
return new EditSession(eventBus, world, maxBlocks, blockBag, new EditSessionEvent(world, player, maxBlocks, null)); return new EditSession(eventBus, world, maxBlocks, blockBag, new EditSessionEvent(world, player, maxBlocks, null));
} }

View File

@ -31,13 +31,4 @@ import com.sk89q.worldedit.extension.platform.Actor;
@Deprecated @Deprecated
public abstract class LocalPlayer extends AbstractPlayerActor { public abstract class LocalPlayer extends AbstractPlayerActor {
/**
* Construct the object.
*
* @param server A reference to the server this player is on
*/
protected LocalPlayer(ServerInterface server) {
super(server);
}
} }

View File

@ -27,15 +27,17 @@ import com.sk89q.worldedit.command.tool.BlockTool;
import com.sk89q.worldedit.command.tool.BrushTool; import com.sk89q.worldedit.command.tool.BrushTool;
import com.sk89q.worldedit.command.tool.SinglePickaxe; import com.sk89q.worldedit.command.tool.SinglePickaxe;
import com.sk89q.worldedit.command.tool.Tool; import com.sk89q.worldedit.command.tool.Tool;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.mask.Masks;
import com.sk89q.worldedit.internal.cui.CUIEvent; import com.sk89q.worldedit.internal.cui.CUIEvent;
import com.sk89q.worldedit.internal.cui.CUIRegion; import com.sk89q.worldedit.internal.cui.CUIRegion;
import com.sk89q.worldedit.internal.cui.SelectionShapeEvent; import com.sk89q.worldedit.internal.cui.SelectionShapeEvent;
import com.sk89q.worldedit.masks.Mask;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.regions.Region; 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.session.request.Request; import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.snapshot.Snapshot; import com.sk89q.worldedit.world.snapshot.Snapshot;
@ -140,6 +142,17 @@ public class LocalSession {
* @return whether anything was undone * @return whether anything was undone
*/ */
public EditSession undo(BlockBag newBlockBag, LocalPlayer player) { public EditSession undo(BlockBag newBlockBag, LocalPlayer player) {
return undo(newBlockBag, (Player) player);
}
/**
* Performs an undo.
*
* @param newBlockBag
* @param player
* @return whether anything was undone
*/
public EditSession undo(BlockBag newBlockBag, Player player) {
--historyPointer; --historyPointer;
if (historyPointer >= 0) { if (historyPointer >= 0) {
EditSession editSession = history.get(historyPointer); EditSession editSession = history.get(historyPointer);
@ -163,6 +176,17 @@ public class LocalSession {
* @return whether anything was redone * @return whether anything was redone
*/ */
public EditSession redo(BlockBag newBlockBag, LocalPlayer player) { public EditSession redo(BlockBag newBlockBag, LocalPlayer player) {
return redo(newBlockBag, (Player) player);
}
/**
* Performs a redo
*
* @param newBlockBag
* @param player
* @return whether anything was redone
*/
public EditSession redo(BlockBag newBlockBag, Player player) {
if (historyPointer < history.size()) { if (historyPointer < history.size()) {
EditSession editSession = history.get(historyPointer); EditSession editSession = history.get(historyPointer);
EditSession newEditSession = WorldEdit.getInstance().getEditSessionFactory() EditSession newEditSession = WorldEdit.getInstance().getEditSessionFactory()
@ -394,8 +418,7 @@ public class LocalSession {
* @return position * @return position
* @throws IncompleteRegionException * @throws IncompleteRegionException
*/ */
public Vector getPlacementPosition(LocalPlayer player) public Vector getPlacementPosition(Player player) throws IncompleteRegionException {
throws IncompleteRegionException {
if (!placeAtPos1) { if (!placeAtPos1) {
return player.getBlockIn(); return player.getBlockIn();
} }
@ -419,7 +442,7 @@ public class LocalSession {
* @param player * @param player
* @return * @return
*/ */
public BlockBag getBlockBag(LocalPlayer player) { public BlockBag getBlockBag(Player player) {
if (!useInventory) { if (!useInventory) {
return null; return null;
} }
@ -550,7 +573,7 @@ public class LocalSession {
* *
* @param player * @param player
*/ */
public void tellVersion(LocalPlayer player) { public void tellVersion(Actor player) {
if (config.showFirstUseVersion) { if (config.showFirstUseVersion) {
if (!beenToldVersion) { if (!beenToldVersion) {
player.printRaw("\u00A78WorldEdit ver. " + WorldEdit.getVersion() player.printRaw("\u00A78WorldEdit ver. " + WorldEdit.getVersion()
@ -577,7 +600,7 @@ public class LocalSession {
* *
* @param player * @param player
*/ */
public void dispatchCUISetup(LocalPlayer player) { public void dispatchCUISetup(Player player) {
if (selector != null) { if (selector != null) {
dispatchCUISelection(player); dispatchCUISelection(player);
} }
@ -588,7 +611,7 @@ public class LocalSession {
* *
* @param player * @param player
*/ */
public void dispatchCUISelection(LocalPlayer player) { public void dispatchCUISelection(Player player) {
if (!hasCUISupport) { if (!hasCUISupport) {
return; return;
} }
@ -713,6 +736,17 @@ public class LocalSession {
* @return * @return
*/ */
public EditSession createEditSession(LocalPlayer player) { public EditSession createEditSession(LocalPlayer player) {
return createEditSession((Player) player);
}
/**
* Construct a new edit session.
*
* @param player
* @return
*/
@SuppressWarnings("deprecation")
public EditSession createEditSession(Player player) {
BlockBag blockBag = getBlockBag(player); BlockBag blockBag = getBlockBag(player);
// Create an edit session // Create an edit session
@ -721,9 +755,6 @@ public class LocalSession {
getBlockChangeLimit(), blockBag, player); getBlockChangeLimit(), blockBag, player);
editSession.setFastMode(fastMode); editSession.setFastMode(fastMode);
Request.request().setEditSession(editSession); Request.request().setEditSession(editSession);
if (mask != null) {
mask.prepare(this, player, null);
}
editSession.setMask(mask); editSession.setMask(mask);
return editSession; return editSession;
@ -764,4 +795,15 @@ public class LocalSession {
public void setMask(Mask mask) { public void setMask(Mask mask) {
this.mask = mask; this.mask = mask;
} }
/**
* Set a mask.
*
* @param mask mask or null
*/
@SuppressWarnings("deprecation")
public void setMask(com.sk89q.worldedit.masks.Mask mask) {
setMask(mask != null ? Masks.wrap(mask) : null);
}
} }

View File

@ -19,16 +19,16 @@
package com.sk89q.worldedit; package com.sk89q.worldedit;
import com.sk89q.minecraft.util.commands.CommandsManager;
import com.sk89q.worldedit.CuboidClipboard.FlipDirection; import com.sk89q.worldedit.CuboidClipboard.FlipDirection;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockType; import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.event.platform.BlockInteractEvent; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.extent.EditSessionEvent; import com.sk89q.worldedit.event.extent.EditSessionEvent;
import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.event.platform.BlockInteractEvent;
import com.sk89q.worldedit.event.platform.InputType; import com.sk89q.worldedit.event.platform.InputType;
import com.sk89q.worldedit.event.platform.PlayerInputEvent; import com.sk89q.worldedit.event.platform.PlayerInputEvent;
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.Platform; import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extension.platform.PlatformManager; import com.sk89q.worldedit.extension.platform.PlatformManager;
import com.sk89q.worldedit.extension.registry.BlockRegistry; import com.sk89q.worldedit.extension.registry.BlockRegistry;
@ -182,7 +182,7 @@ public class WorldEdit {
* @deprecated use {@link #getSessionManager()} * @deprecated use {@link #getSessionManager()}
*/ */
@Deprecated @Deprecated
public LocalSession getSession(LocalPlayer player) { public LocalSession getSession(Player player) {
return sessions.get(player); return sessions.get(player);
} }
@ -190,7 +190,7 @@ public class WorldEdit {
* @deprecated use {@link #getSessionManager()} * @deprecated use {@link #getSessionManager()}
*/ */
@Deprecated @Deprecated
public void removeSession(LocalPlayer player) { public void removeSession(Player player) {
sessions.remove(player); sessions.remove(player);
} }
@ -206,7 +206,7 @@ public class WorldEdit {
* @deprecated use {@link #getSessionManager()} * @deprecated use {@link #getSessionManager()}
*/ */
@Deprecated @Deprecated
public boolean hasSession(LocalPlayer player) { public boolean hasSession(Player player) {
return sessions.contains(player); return sessions.contains(player);
} }
@ -215,7 +215,7 @@ public class WorldEdit {
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Deprecated @Deprecated
public BaseBlock getBlock(LocalPlayer player, String arg, boolean allAllowed) throws WorldEditException { public BaseBlock getBlock(Player player, String arg, boolean allAllowed) throws WorldEditException {
return getBlock(player, arg, allAllowed, false); return getBlock(player, arg, allAllowed, false);
} }
@ -224,7 +224,7 @@ public class WorldEdit {
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Deprecated @Deprecated
public BaseBlock getBlock(LocalPlayer player, String arg, boolean allAllowed, boolean allowNoData) throws WorldEditException { public BaseBlock getBlock(Player player, String arg, boolean allAllowed, boolean allowNoData) throws WorldEditException {
ParserContext context = new ParserContext(); ParserContext context = new ParserContext();
context.setActor(player); context.setActor(player);
context.setWorld(player.getWorld()); context.setWorld(player.getWorld());
@ -239,7 +239,7 @@ public class WorldEdit {
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Deprecated @Deprecated
public BaseBlock getBlock(LocalPlayer player, String id) throws WorldEditException { public BaseBlock getBlock(Player player, String id) throws WorldEditException {
return getBlock(player, id, false); return getBlock(player, id, false);
} }
@ -248,7 +248,7 @@ public class WorldEdit {
*/ */
@Deprecated @Deprecated
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Set<BaseBlock> getBlocks(LocalPlayer player, String list, boolean allAllowed, boolean allowNoData) throws WorldEditException { public Set<BaseBlock> getBlocks(Player player, String list, boolean allAllowed, boolean allowNoData) throws WorldEditException {
String[] items = list.split(","); String[] items = list.split(",");
Set<BaseBlock> blocks = new HashSet<BaseBlock>(); Set<BaseBlock> blocks = new HashSet<BaseBlock>();
for (String id : items) { for (String id : items) {
@ -262,7 +262,7 @@ public class WorldEdit {
*/ */
@Deprecated @Deprecated
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Set<BaseBlock> getBlocks(LocalPlayer player, String list, boolean allAllowed) throws WorldEditException { public Set<BaseBlock> getBlocks(Player player, String list, boolean allAllowed) throws WorldEditException {
return getBlocks(player, list, allAllowed, false); return getBlocks(player, list, allAllowed, false);
} }
@ -271,7 +271,7 @@ public class WorldEdit {
*/ */
@Deprecated @Deprecated
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Set<BaseBlock> getBlocks(LocalPlayer player, String list) throws WorldEditException { public Set<BaseBlock> getBlocks(Player player, String list) throws WorldEditException {
return getBlocks(player, list, false); return getBlocks(player, list, false);
} }
@ -280,7 +280,7 @@ public class WorldEdit {
*/ */
@Deprecated @Deprecated
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Set<Integer> getBlockIDs(LocalPlayer player, String list, boolean allBlocksAllowed) throws WorldEditException { public Set<Integer> getBlockIDs(Player player, String list, boolean allBlocksAllowed) throws WorldEditException {
String[] items = list.split(","); String[] items = list.split(",");
Set<Integer> blocks = new HashSet<Integer>(); Set<Integer> blocks = new HashSet<Integer>();
for (String s : items) { for (String s : items) {
@ -294,7 +294,7 @@ public class WorldEdit {
*/ */
@Deprecated @Deprecated
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Pattern getBlockPattern(LocalPlayer player, String input) throws WorldEditException { public Pattern getBlockPattern(Player player, String input) throws WorldEditException {
ParserContext context = new ParserContext(); ParserContext context = new ParserContext();
context.setActor(player); context.setActor(player);
context.setWorld(player.getWorld()); context.setWorld(player.getWorld());
@ -307,7 +307,7 @@ public class WorldEdit {
*/ */
@Deprecated @Deprecated
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Mask getBlockMask(LocalPlayer player, LocalSession session, String input) throws WorldEditException { public Mask getBlockMask(Player player, LocalSession session, String input) throws WorldEditException {
ParserContext context = new ParserContext(); ParserContext context = new ParserContext();
context.setActor(player); context.setActor(player);
context.setWorld(player.getWorld()); context.setWorld(player.getWorld());
@ -329,8 +329,7 @@ public class WorldEdit {
* @return a file * @return a file
* @throws FilenameException thrown if the filename is invalid * @throws FilenameException thrown if the filename is invalid
*/ */
public File getSafeSaveFile(LocalPlayer player, File dir, String filename, String defaultExt, String... extensions) public File getSafeSaveFile(Player player, File dir, String filename, String defaultExt, String... extensions) throws FilenameException {
throws FilenameException {
return getSafeFile(player, dir, filename, defaultExt, extensions, true); return getSafeFile(player, dir, filename, defaultExt, extensions, true);
} }
@ -348,8 +347,7 @@ public class WorldEdit {
* @return a file * @return a file
* @throws FilenameException thrown if the filename is invalid * @throws FilenameException thrown if the filename is invalid
*/ */
public File getSafeOpenFile(LocalPlayer player, File dir, String filename, String defaultExt, String... extensions) public File getSafeOpenFile(Player player, File dir, String filename, String defaultExt, String... extensions) throws FilenameException {
throws FilenameException {
return getSafeFile(player, dir, filename, defaultExt, extensions, false); return getSafeFile(player, dir, filename, defaultExt, extensions, false);
} }
@ -365,9 +363,7 @@ public class WorldEdit {
* @return a file * @return a file
* @throws FilenameException thrown if the filename is invalid * @throws FilenameException thrown if the filename is invalid
*/ */
private File getSafeFile(LocalPlayer player, File dir, String filename, private File getSafeFile(Player player, File dir, String filename, String defaultExt, String[] extensions, boolean isSave) throws FilenameException {
String defaultExt, String[] extensions, boolean isSave)
throws FilenameException {
if (extensions != null && (extensions.length == 1 && extensions[0] == null)) extensions = null; if (extensions != null && (extensions.length == 1 && extensions[0] == null)) extensions = null;
File f; File f;
@ -410,7 +406,7 @@ public class WorldEdit {
} }
} }
public int getMaximumPolygonalPoints(LocalPlayer player) { public int getMaximumPolygonalPoints(Player player) {
if (player.hasPermission("worldedit.limit.unrestricted") || getConfiguration().maxPolygonalPoints < 0) { if (player.hasPermission("worldedit.limit.unrestricted") || getConfiguration().maxPolygonalPoints < 0) {
return getConfiguration().defaultMaxPolygonalPoints; return getConfiguration().defaultMaxPolygonalPoints;
} }
@ -422,7 +418,7 @@ public class WorldEdit {
return Math.min(getConfiguration().defaultMaxPolygonalPoints, getConfiguration().maxPolygonalPoints); return Math.min(getConfiguration().defaultMaxPolygonalPoints, getConfiguration().maxPolygonalPoints);
} }
public int getMaximumPolyhedronPoints(LocalPlayer player) { public int getMaximumPolyhedronPoints(Player player) {
if (player.hasPermission("worldedit.limit.unrestricted") || getConfiguration().maxPolyhedronPoints < 0) { if (player.hasPermission("worldedit.limit.unrestricted") || getConfiguration().maxPolyhedronPoints < 0) {
return getConfiguration().defaultMaxPolyhedronPoints; return getConfiguration().defaultMaxPolyhedronPoints;
} }
@ -483,7 +479,7 @@ public class WorldEdit {
* @return a direction vector * @return a direction vector
* @throws UnknownDirectionException thrown if the direction is not known * @throws UnknownDirectionException thrown if the direction is not known
*/ */
public Vector getDirection(LocalPlayer player, String dirStr) throws UnknownDirectionException { public Vector getDirection(Player player, String dirStr) throws UnknownDirectionException {
dirStr = dirStr.toLowerCase(); dirStr = dirStr.toLowerCase();
final PlayerDirection dir = getPlayerDirection(player, dirStr); final PlayerDirection dir = getPlayerDirection(player, dirStr);
@ -511,7 +507,7 @@ public class WorldEdit {
* @return a direction enum value * @return a direction enum value
* @throws UnknownDirectionException thrown if the direction is not known * @throws UnknownDirectionException thrown if the direction is not known
*/ */
private PlayerDirection getPlayerDirection(LocalPlayer player, String dirStr) throws UnknownDirectionException { private PlayerDirection getPlayerDirection(Player player, String dirStr) throws UnknownDirectionException {
final PlayerDirection dir; final PlayerDirection dir;
switch (dirStr.charAt(0)) { switch (dirStr.charAt(0)) {
@ -585,9 +581,7 @@ public class WorldEdit {
* @return a direction vector * @return a direction vector
* @throws UnknownDirectionException thrown if the direction is not known * @throws UnknownDirectionException thrown if the direction is not known
*/ */
public Vector getDiagonalDirection(LocalPlayer player, String dirStr) public Vector getDiagonalDirection(Player player, String dirStr) throws UnknownDirectionException {
throws UnknownDirectionException {
return getPlayerDirection(player, dirStr.toLowerCase()).vector(); return getPlayerDirection(player, dirStr.toLowerCase()).vector();
} }
@ -599,8 +593,7 @@ public class WorldEdit {
* @return a direction vector * @return a direction vector
* @throws UnknownDirectionException thrown if the direction is not known * @throws UnknownDirectionException thrown if the direction is not known
*/ */
public FlipDirection getFlipDirection(LocalPlayer player, String dirStr) throws UnknownDirectionException { public FlipDirection getFlipDirection(Player player, String dirStr) throws UnknownDirectionException {
final PlayerDirection dir = getPlayerDirection(player, dirStr); final PlayerDirection dir = getPlayerDirection(player, dirStr);
switch (dir) { switch (dir) {
case WEST: case WEST:
@ -623,10 +616,10 @@ public class WorldEdit {
/** /**
* Flush a block bag's changes to a player. * Flush a block bag's changes to a player.
* *
* @param player the player * @param actor the actor
* @param editSession the edit session * @param editSession the edit session
*/ */
public void flushBlockBag(LocalPlayer player, EditSession editSession) { public void flushBlockBag(Actor actor, EditSession editSession) {
BlockBag blockBag = editSession.getBlockBag(); BlockBag blockBag = editSession.getBlockBag();
if (blockBag != null) { if (blockBag != null) {
@ -635,7 +628,7 @@ public class WorldEdit {
Map<Integer, Integer> missingBlocks = editSession.popMissingBlocks(); Map<Integer, Integer> missingBlocks = editSession.popMissingBlocks();
if (missingBlocks.size() > 0) { if (!missingBlocks.isEmpty()) {
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
str.append("Missing these blocks: "); str.append("Missing these blocks: ");
int size = missingBlocks.size(); int size = missingBlocks.size();
@ -657,35 +650,17 @@ public class WorldEdit {
} }
} }
player.printError(str.toString()); actor.printError(str.toString());
} }
} }
/**
* Get the map of commands (internal usage only).
*
* @return the commands
*/
public Map<String, String> getCommands() {
return getCommandsManager().getCommands();
}
/**
* Get the commands manager (internal usage only).
*
* @return the commands
*/
public CommandsManager<LocalPlayer> getCommandsManager() {
return getPlatformManager().getCommandManager().getCommands();
}
/** /**
* Handle a disconnection. * Handle a disconnection.
* *
* @param player the player * @param player the player
*/ */
@Deprecated @Deprecated
public void handleDisconnect(LocalPlayer player) { public void handleDisconnect(Player player) {
forgetPlayer(player); forgetPlayer(player);
} }
@ -694,7 +669,7 @@ public class WorldEdit {
* *
* @param player the player * @param player the player
*/ */
public void markExpire(LocalPlayer player) { public void markExpire(Player player) {
sessions.markforExpiration(player); sessions.markforExpiration(player);
} }
@ -703,7 +678,7 @@ public class WorldEdit {
* *
* @param player the player * @param player the player
*/ */
public void forgetPlayer(LocalPlayer player) { public void forgetPlayer(Player player) {
sessions.remove(player); sessions.remove(player);
} }
@ -720,7 +695,7 @@ public class WorldEdit {
* @param player the player * @param player the player
* @return true if the swing was handled * @return true if the swing was handled
*/ */
public boolean handleArmSwing(LocalPlayer player) { public boolean handleArmSwing(Player player) {
PlayerInputEvent event = new PlayerInputEvent(player, InputType.PRIMARY); PlayerInputEvent event = new PlayerInputEvent(player, InputType.PRIMARY);
getEventBus().post(event); getEventBus().post(event);
return event.isCancelled(); return event.isCancelled();
@ -732,7 +707,7 @@ public class WorldEdit {
* @param player the player * @param player the player
* @return true if the right click was handled * @return true if the right click was handled
*/ */
public boolean handleRightClick(LocalPlayer player) { public boolean handleRightClick(Player player) {
PlayerInputEvent event = new PlayerInputEvent(player, InputType.SECONDARY); PlayerInputEvent event = new PlayerInputEvent(player, InputType.SECONDARY);
getEventBus().post(event); getEventBus().post(event);
return event.isCancelled(); return event.isCancelled();
@ -745,7 +720,7 @@ public class WorldEdit {
* @param clicked the clicked block * @param clicked the clicked block
* @return false if you want the action to go through * @return false if you want the action to go through
*/ */
public boolean handleBlockRightClick(LocalPlayer player, WorldVector clicked) { public boolean handleBlockRightClick(Player player, WorldVector clicked) {
BlockInteractEvent event = new BlockInteractEvent(player, clicked.toLocation(), OPEN); BlockInteractEvent event = new BlockInteractEvent(player, clicked.toLocation(), OPEN);
getEventBus().post(event); getEventBus().post(event);
return event.isCancelled(); return event.isCancelled();
@ -758,28 +733,12 @@ public class WorldEdit {
* @param clicked the clicked block * @param clicked the clicked block
* @return false if you want the action to go through * @return false if you want the action to go through
*/ */
public boolean handleBlockLeftClick(LocalPlayer player, WorldVector clicked) { public boolean handleBlockLeftClick(Player player, WorldVector clicked) {
BlockInteractEvent event = new BlockInteractEvent(player, clicked.toLocation(), HIT); BlockInteractEvent event = new BlockInteractEvent(player, clicked.toLocation(), HIT);
getEventBus().post(event); getEventBus().post(event);
return event.isCancelled(); return event.isCancelled();
} }
/**
*
* @param player
* @param split
* @return whether the command was processed
*/
public boolean handleCommand(LocalPlayer player, String[] split) {
CommandEvent event = new CommandEvent(player, split);
getEventBus().post(event);
return event.isCancelled();
}
public String[] commandDetection(String[] split) {
return getPlatformManager().getCommandManager().commandDetection(split);
}
/** /**
* Executes a WorldEdit script. * Executes a WorldEdit script.
* *
@ -788,7 +747,7 @@ public class WorldEdit {
* @param args arguments for the script * @param args arguments for the script
* @throws WorldEditException * @throws WorldEditException
*/ */
public void runScript(LocalPlayer player, File f, String[] args) throws WorldEditException { public void runScript(Player player, File f, String[] args) throws WorldEditException {
Request.reset(); Request.reset();
String filename = f.getPath(); String filename = f.getPath();
@ -826,9 +785,8 @@ public class WorldEdit {
return; return;
} }
LocalSession session = getSession(player); LocalSession session = getSessionManager().get(player);
CraftScriptContext scriptContext = CraftScriptContext scriptContext = new CraftScriptContext(this, getServer(), getConfiguration(), session, player, args);
new CraftScriptContext(this, getServer(), getConfiguration(), session, player, args);
CraftScriptEngine engine = null; CraftScriptEngine engine = null;

View File

@ -24,9 +24,11 @@ import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging; import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.masks.BiomeTypeMask; import com.sk89q.worldedit.masks.BiomeTypeMask;
import com.sk89q.worldedit.masks.InvertedMask; import com.sk89q.worldedit.masks.InvertedMask;
import com.sk89q.worldedit.masks.Mask;
import com.sk89q.worldedit.regions.FlatRegion; import com.sk89q.worldedit.regions.FlatRegion;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
@ -35,14 +37,24 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION; import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;
/**
* Implements biome-related commands such as "/biomelist".
*/
public class BiomeCommands { public class BiomeCommands {
private WorldEdit we; private final WorldEdit worldEdit;
public BiomeCommands(WorldEdit we) { /**
this.we = we; * Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/
public BiomeCommands(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
} }
@Command( @Command(
@ -52,9 +64,7 @@ public class BiomeCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.biome.list") @CommandPermissions("worldedit.biome.list")
public void biomeList(CommandContext args, LocalSession session, LocalPlayer player, public void biomeList(Actor actor, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int page; int page;
int offset; int offset;
int count = 0; int count = 0;
@ -66,14 +76,14 @@ public class BiomeCommands {
offset = (page - 1) * 19; offset = (page - 1) * 19;
} }
List<BiomeType> biomes = we.getServer().getBiomes().all(); List<BiomeType> biomes = worldEdit.getServer().getBiomes().all();
int totalPages = biomes.size() / 19 + 1; int totalPages = biomes.size() / 19 + 1;
player.print("Available Biomes (page " + page + "/" + totalPages + ") :"); actor.print("Available Biomes (page " + page + "/" + totalPages + ") :");
for (BiomeType biome : biomes) { for (BiomeType biome : biomes) {
if (offset > 0) { if (offset > 0) {
offset--; offset--;
} else { } else {
player.print(" " + biome.getName()); actor.print(" " + biome.getName());
if (++count == 19) { if (++count == 19) {
break; break;
} }
@ -93,9 +103,7 @@ public class BiomeCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.biome.info") @CommandPermissions("worldedit.biome.info")
public void biomeInfo(CommandContext args, LocalSession session, LocalPlayer player, public void biomeInfo(CommandContext args, Player player, LocalSession session) throws WorldEditException {
EditSession editSession) throws WorldEditException {
if (args.hasFlag('t')) { if (args.hasFlag('t')) {
Vector blockPosition = player.getBlockTrace(300); Vector blockPosition = player.getBlockTrace(300);
if (blockPosition == null) { if (blockPosition == null) {
@ -144,10 +152,8 @@ public class BiomeCommands {
) )
@Logging(REGION) @Logging(REGION)
@CommandPermissions("worldedit.biome.set") @CommandPermissions("worldedit.biome.set")
public void setBiome(CommandContext args, LocalSession session, LocalPlayer player, public void setBiome(CommandContext args, Player player, LocalSession session, EditSession editSession) throws WorldEditException {
EditSession editSession) throws WorldEditException { final BiomeType target = worldEdit.getServer().getBiomes().get(args.getString(0));
final BiomeType target = we.getServer().getBiomes().get(args.getString(0));
if (target == null) { if (target == null) {
player.printError("Biome '" + args.getString(0) + "' does not exist!"); player.printError("Biome '" + args.getString(0) + "' does not exist!");
return; return;
@ -199,4 +205,5 @@ public class BiomeCommands {
player.print("Biome changed to " + target.getName() + ". " + affected + " columns affected."); player.print("Biome changed to " + target.getName() + ". " + affected + " columns affected.");
} }
} }
} }

View File

@ -22,46 +22,42 @@ package com.sk89q.worldedit.command;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.CuboidClipboard; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.LocalWorld.KillFlags; import com.sk89q.worldedit.LocalWorld.KillFlags;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.command.UtilityCommands.FlagContainer; import com.sk89q.worldedit.command.UtilityCommands.FlagContainer;
import com.sk89q.worldedit.masks.BlockMask;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.patterns.SingleBlockPattern;
import com.sk89q.worldedit.command.tool.BrushTool; import com.sk89q.worldedit.command.tool.BrushTool;
import com.sk89q.worldedit.command.tool.brush.ButcherBrush; import com.sk89q.worldedit.command.tool.brush.*;
import com.sk89q.worldedit.command.tool.brush.ClipboardBrush; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.command.tool.brush.CylinderBrush; import com.sk89q.worldedit.function.mask.BlockMask;
import com.sk89q.worldedit.command.tool.brush.GravityBrush; import com.sk89q.worldedit.function.pattern.BlockPattern;
import com.sk89q.worldedit.command.tool.brush.HollowCylinderBrush; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.command.tool.brush.HollowSphereBrush; import com.sk89q.worldedit.util.command.binding.Switch;
import com.sk89q.worldedit.command.tool.brush.SmoothBrush; import com.sk89q.worldedit.util.command.parametric.Optional;
import com.sk89q.worldedit.command.tool.brush.SphereBrush;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Brush shape commands. * Commands to set brush shape.
*
* @author sk89q
*/ */
public class BrushCommands { public class BrushCommands {
private final WorldEdit we;
private final WorldEdit worldEdit;
public BrushCommands(WorldEdit we) {
this.we = we; /**
* Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/
public BrushCommands(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
} }
@Command( @Command(
aliases = { "sphere", "s" }, aliases = { "sphere", "s" },
usage = "<block> [radius]", usage = "<pattern> [radius]",
flags = "h", flags = "h",
desc = "Choose the sphere brush", desc = "Choose the sphere brush",
help = help =
@ -71,25 +67,21 @@ public class BrushCommands {
max = 2 max = 2
) )
@CommandPermissions("worldedit.brush.sphere") @CommandPermissions("worldedit.brush.sphere")
public void sphereBrush(CommandContext args, LocalSession session, public void sphereBrush(Player player, LocalSession session, EditSession editSession, Pattern fill,
LocalPlayer player, EditSession editSession) throws WorldEditException { @Optional("2") double radius, @Switch('h') boolean hollow) throws WorldEditException {
worldEdit.checkMaxBrushRadius(radius);
double radius = args.argsLength() > 1 ? args.getDouble(1) : 2;
we.checkMaxBrushRadius(radius);
BrushTool tool = session.getBrushTool(player.getItemInHand()); BrushTool tool = session.getBrushTool(player.getItemInHand());
Pattern fill = we.getBlockPattern(player, args.getString(0));
tool.setFill(fill); tool.setFill(fill);
tool.setSize(radius); tool.setSize(radius);
if (args.hasFlag('h')) { if (hollow) {
tool.setBrush(new HollowSphereBrush(), "worldedit.brush.sphere"); tool.setBrush(new HollowSphereBrush(), "worldedit.brush.sphere");
} else { } else {
tool.setBrush(new SphereBrush(), "worldedit.brush.sphere"); tool.setBrush(new SphereBrush(), "worldedit.brush.sphere");
} }
player.print(String.format("Sphere brush shape equipped (%.0f).", player.print(String.format("Sphere brush shape equipped (%.0f).", radius));
radius));
} }
@Command( @Command(
@ -104,28 +96,22 @@ public class BrushCommands {
max = 3 max = 3
) )
@CommandPermissions("worldedit.brush.cylinder") @CommandPermissions("worldedit.brush.cylinder")
public void cylinderBrush(CommandContext args, LocalSession session, public void cylinderBrush(Player player, LocalSession session, EditSession editSession, Pattern fill,
LocalPlayer player, EditSession editSession) throws WorldEditException { @Optional("2") double radius, @Optional("1") int height, @Switch('h') boolean hollow) throws WorldEditException {
worldEdit.checkMaxBrushRadius(radius);
double radius = args.argsLength() > 1 ? args.getDouble(1) : 2; worldEdit.checkMaxBrushRadius(height);
we.checkMaxBrushRadius(radius);
int height = args.argsLength() > 2 ? args.getInteger(2) : 1;
we.checkMaxBrushRadius(height);
BrushTool tool = session.getBrushTool(player.getItemInHand()); BrushTool tool = session.getBrushTool(player.getItemInHand());
Pattern fill = we.getBlockPattern(player, args.getString(0));
tool.setFill(fill); tool.setFill(fill);
tool.setSize(radius); tool.setSize(radius);
if (args.hasFlag('h')) { if (hollow) {
tool.setBrush(new HollowCylinderBrush(height), "worldedit.brush.cylinder"); tool.setBrush(new HollowCylinderBrush(height), "worldedit.brush.cylinder");
} else { } else {
tool.setBrush(new CylinderBrush(height), "worldedit.brush.cylinder"); tool.setBrush(new CylinderBrush(height), "worldedit.brush.cylinder");
} }
player.print(String.format("Cylinder brush shape equipped (%.0f by %d).", player.print(String.format("Cylinder brush shape equipped (%.0f by %d).", radius, height));
radius, height));
} }
@Command( @Command(
@ -140,8 +126,7 @@ public class BrushCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.brush.clipboard") @CommandPermissions("worldedit.brush.clipboard")
public void clipboardBrush(CommandContext args, LocalSession session, public void clipboardBrush(Player player, LocalSession session, EditSession editSession, @Switch('a') boolean ignoreAir) throws WorldEditException {
LocalPlayer player, EditSession editSession) throws WorldEditException {
CuboidClipboard clipboard = session.getClipboard(); CuboidClipboard clipboard = session.getClipboard();
@ -152,12 +137,12 @@ public class BrushCommands {
Vector size = clipboard.getSize(); Vector size = clipboard.getSize();
we.checkMaxBrushRadius(size.getBlockX()); worldEdit.checkMaxBrushRadius(size.getBlockX());
we.checkMaxBrushRadius(size.getBlockY()); worldEdit.checkMaxBrushRadius(size.getBlockY());
we.checkMaxBrushRadius(size.getBlockZ()); worldEdit.checkMaxBrushRadius(size.getBlockZ());
BrushTool tool = session.getBrushTool(player.getItemInHand()); BrushTool tool = session.getBrushTool(player.getItemInHand());
tool.setBrush(new ClipboardBrush(clipboard, args.hasFlag('a')), "worldedit.brush.clipboard"); tool.setBrush(new ClipboardBrush(clipboard, ignoreAir), "worldedit.brush.clipboard");
player.print("Clipboard brush shape equipped."); player.print("Clipboard brush shape equipped.");
} }
@ -169,24 +154,22 @@ public class BrushCommands {
desc = "Choose the terrain softener brush", desc = "Choose the terrain softener brush",
help = help =
"Chooses the terrain softener brush.\n" + "Chooses the terrain softener brush.\n" +
"The -n flag makes it only consider naturally occuring blocks.", "The -n flag makes it only consider naturally occurring blocks.",
min = 0, min = 0,
max = 2 max = 2
) )
@CommandPermissions("worldedit.brush.smooth") @CommandPermissions("worldedit.brush.smooth")
public void smoothBrush(CommandContext args, LocalSession session, public void smoothBrush(Player player, LocalSession session, EditSession editSession,
LocalPlayer player, EditSession editSession) throws WorldEditException { @Optional("2") double radius, @Optional("4") int iterations, @Switch('n')
boolean naturalBlocksOnly) throws WorldEditException {
double radius = args.argsLength() > 0 ? args.getDouble(0) : 2; worldEdit.checkMaxBrushRadius(radius);
we.checkMaxBrushRadius(radius);
int iterations = args.argsLength() > 1 ? args.getInteger(1) : 4;
BrushTool tool = session.getBrushTool(player.getItemInHand()); BrushTool tool = session.getBrushTool(player.getItemInHand());
tool.setSize(radius); tool.setSize(radius);
tool.setBrush(new SmoothBrush(iterations, args.hasFlag('n')), "worldedit.brush.smooth"); tool.setBrush(new SmoothBrush(iterations, naturalBlocksOnly), "worldedit.brush.smooth");
player.print(String.format("Smooth brush equipped (%.0f x %dx, using " + (args.hasFlag('n') ? "natural blocks only" : "any block") + ").", player.print(String.format("Smooth brush equipped (%.0f x %dx, using " + (naturalBlocksOnly ? "natural blocks only" : "any block") + ").",
radius, iterations)); radius, iterations));
} }
@ -198,21 +181,17 @@ public class BrushCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.brush.ex") @CommandPermissions("worldedit.brush.ex")
public void extinguishBrush(CommandContext args, LocalSession session, public void extinguishBrush(Player player, LocalSession session, EditSession editSession, @Optional("5") double radius) throws WorldEditException {
LocalPlayer player, EditSession editSession) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius);
double radius = args.argsLength() > 1 ? args.getDouble(1) : 5;
we.checkMaxBrushRadius(radius);
BrushTool tool = session.getBrushTool(player.getItemInHand()); BrushTool tool = session.getBrushTool(player.getItemInHand());
Pattern fill = new SingleBlockPattern(new BaseBlock(0)); Pattern fill = new BlockPattern(new BaseBlock(0));
tool.setFill(fill); tool.setFill(fill);
tool.setSize(radius); tool.setSize(radius);
tool.setMask(new BlockMask(new BaseBlock(BlockID.FIRE))); tool.setMask(new BlockMask(editSession, new BaseBlock(BlockID.FIRE)));
tool.setBrush(new SphereBrush(), "worldedit.brush.ex"); tool.setBrush(new SphereBrush(), "worldedit.brush.ex");
player.print(String.format("Extinguisher equipped (%.0f).", player.print(String.format("Extinguisher equipped (%.0f).", radius));
radius));
} }
@Command( @Command(
@ -228,15 +207,12 @@ public class BrushCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.brush.gravity") @CommandPermissions("worldedit.brush.gravity")
public void gravityBrush(CommandContext args, LocalSession session, public void gravityBrush(Player player, LocalSession session, EditSession editSession, @Optional("5") double radius, @Switch('h') boolean fromMaxY) throws WorldEditException {
LocalPlayer player, EditSession editSession) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius);
double radius = args.argsLength() > 0 ? args.getDouble(0) : 5;
we.checkMaxBrushRadius(radius);
BrushTool tool = session.getBrushTool(player.getItemInHand()); BrushTool tool = session.getBrushTool(player.getItemInHand());
tool.setSize(radius); tool.setSize(radius);
tool.setBrush(new GravityBrush(args.hasFlag('h')), "worldedit.brush.gravity"); tool.setBrush(new GravityBrush(fromMaxY), "worldedit.brush.gravity");
player.print(String.format("Gravity brush equipped (%.0f).", player.print(String.format("Gravity brush equipped (%.0f).",
radius)); radius));
@ -253,10 +229,8 @@ public class BrushCommands {
max = 2 max = 2
) )
@CommandPermissions("worldedit.brush.butcher") @CommandPermissions("worldedit.brush.butcher")
public void butcherBrush(CommandContext args, LocalSession session, public void butcherBrush(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
LocalPlayer player, EditSession editSession) throws WorldEditException { LocalConfiguration config = worldEdit.getConfiguration();
LocalConfiguration config = we.getConfiguration();
double radius = args.argsLength() > 0 ? args.getDouble(0) : 5; double radius = args.argsLength() > 0 ? args.getDouble(0) : 5;
double maxRadius = config.maxBrushRadius; double maxRadius = config.maxBrushRadius;

View File

@ -24,6 +24,7 @@ import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging; import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.math.MathUtils; import com.sk89q.worldedit.math.MathUtils;
import com.sk89q.worldedit.world.storage.LegacyChunkStore; import com.sk89q.worldedit.world.storage.LegacyChunkStore;
import com.sk89q.worldedit.world.storage.McRegionChunkStore; import com.sk89q.worldedit.world.storage.McRegionChunkStore;
@ -33,18 +34,19 @@ import java.io.IOException;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.util.Set; import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION; import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;
/** /**
* Chunk tools. * Commands for working with chunks.
*
* @author sk89q
*/ */
public class ChunkCommands { public class ChunkCommands {
private final WorldEdit we;
private final WorldEdit worldEdit;
public ChunkCommands(WorldEdit we) { public ChunkCommands(WorldEdit worldEdit) {
this.we = we; checkNotNull(worldEdit);
this.worldEdit = worldEdit;
} }
@Command( @Command(
@ -55,9 +57,7 @@ public class ChunkCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.chunkinfo") @CommandPermissions("worldedit.chunkinfo")
public void chunkInfo(CommandContext args, LocalSession session, LocalPlayer player, public void chunkInfo(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Vector pos = player.getBlockIn(); Vector pos = player.getBlockIn();
int chunkX = (int) Math.floor(pos.getBlockX() / 16.0); int chunkX = (int) Math.floor(pos.getBlockX() / 16.0);
int chunkZ = (int) Math.floor(pos.getBlockZ() / 16.0); int chunkZ = (int) Math.floor(pos.getBlockZ() / 16.0);
@ -81,9 +81,7 @@ public class ChunkCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.listchunks") @CommandPermissions("worldedit.listchunks")
public void listChunks(CommandContext args, LocalSession session, LocalPlayer player, public void listChunks(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Set<Vector2D> chunks = session.getSelection(player.getWorld()).getChunks(); Set<Vector2D> chunks = session.getSelection(player.getWorld()).getChunks();
for (Vector2D chunk : chunks) { for (Vector2D chunk : chunks) {
@ -100,11 +98,9 @@ public class ChunkCommands {
) )
@CommandPermissions("worldedit.delchunks") @CommandPermissions("worldedit.delchunks")
@Logging(REGION) @Logging(REGION)
public void deleteChunks(CommandContext args, LocalSession session, LocalPlayer player, public void deleteChunks(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
player.print("Note that this command does not yet support the mcregion format."); player.print("Note that this command does not yet support the mcregion format.");
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = worldEdit.getConfiguration();
Set<Vector2D> chunks = session.getSelection(player.getWorld()).getChunks(); Set<Vector2D> chunks = session.getSelection(player.getWorld()).getChunks();
FileOutputStream out = null; FileOutputStream out = null;
@ -139,7 +135,7 @@ public class ChunkCommands {
if (out != null) { if (out != null) {
try { try {
out.close(); out.close();
} catch (IOException ie) { } } catch (IOException ignored) { }
} }
} }
} else if (config.shellSaveType.equalsIgnoreCase("bash")) { } else if (config.shellSaveType.equalsIgnoreCase("bash")) {
@ -171,7 +167,7 @@ public class ChunkCommands {
if (out != null) { if (out != null) {
try { try {
out.close(); out.close();
} catch (IOException ie) { } catch (IOException ignored) {
} }
} }
} }
@ -179,4 +175,5 @@ public class ChunkCommands {
player.printError("Shell script type must be configured: 'bat' or 'bash' expected."); player.printError("Shell script type must be configured: 'bat' or 'bash' expected.");
} }
} }
} }

View File

@ -19,28 +19,40 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import com.sk89q.minecraft.util.commands.*; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector; import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.util.command.binding.Switch;
import com.sk89q.worldedit.util.command.parametric.Optional;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.PLACEMENT; import static com.sk89q.minecraft.util.commands.Logging.LogMode.PLACEMENT;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION; import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;
/** /**
* Clipboard commands. * Clipboard commands.
*
* @author sk89q
*/ */
public class ClipboardCommands { public class ClipboardCommands {
private final WorldEdit we;
public ClipboardCommands(WorldEdit we) { private final WorldEdit worldEdit;
this.we = we;
/**
* Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/
public ClipboardCommands(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
} }
@Command( @Command(
@ -55,9 +67,7 @@ public class ClipboardCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.clipboard.copy") @CommandPermissions("worldedit.clipboard.copy")
public void copy(CommandContext args, LocalSession session, LocalPlayer player, public void copy(Player player, LocalSession session, EditSession editSession, @Switch('e') boolean copyEntities) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Region region = session.getSelection(player.getWorld()); Region region = session.getSelection(player.getWorld());
Vector min = region.getMinimumPoint(); Vector min = region.getMinimumPoint();
Vector max = region.getMaximumPoint(); Vector max = region.getMaximumPoint();
@ -73,11 +83,12 @@ public class ClipboardCommands {
clipboard.copy(editSession, region); clipboard.copy(editSession, region);
} }
if (args.hasFlag('e')) { if (copyEntities) {
for (LocalEntity entity : player.getWorld().getEntities(region)) { for (LocalEntity entity : player.getWorld().getEntities(region)) {
clipboard.storeEntity(entity); clipboard.storeEntity(entity);
} }
} }
session.setClipboard(clipboard); session.setClipboard(clipboard);
player.print("Block(s) copied."); player.print("Block(s) copied.");
@ -97,16 +108,9 @@ public class ClipboardCommands {
) )
@CommandPermissions("worldedit.clipboard.cut") @CommandPermissions("worldedit.clipboard.cut")
@Logging(REGION) @Logging(REGION)
public void cut(CommandContext args, LocalSession session, LocalPlayer player, public void cut(Player player, LocalSession session, EditSession editSession, @Optional("air") BaseBlock block, @Switch('e') boolean copyEntities) throws WorldEditException {
EditSession editSession) throws WorldEditException {
BaseBlock block = new BaseBlock(BlockID.AIR);
World world = player.getWorld(); World world = player.getWorld();
if (args.argsLength() > 0) {
block = we.getBlock(player, args.getString(0));
}
Region region = session.getSelection(world); Region region = session.getSelection(world);
Vector min = region.getMinimumPoint(); Vector min = region.getMinimumPoint();
Vector max = region.getMaximumPoint(); Vector max = region.getMaximumPoint();
@ -122,13 +126,14 @@ public class ClipboardCommands {
clipboard.copy(editSession, region); clipboard.copy(editSession, region);
} }
if (args.hasFlag('e')) { if (copyEntities) {
LocalEntity[] entities = world.getEntities(region); LocalEntity[] entities = world.getEntities(region);
for (LocalEntity entity : entities) { for (LocalEntity entity : entities) {
clipboard.storeEntity(entity); clipboard.storeEntity(entity);
} }
world.killEntities(entities); world.killEntities(entities);
} }
session.setClipboard(clipboard); session.setClipboard(clipboard);
editSession.setBlocks(region, block); editSession.setBlocks(region, block);
@ -151,8 +156,7 @@ public class ClipboardCommands {
) )
@CommandPermissions("worldedit.clipboard.paste") @CommandPermissions("worldedit.clipboard.paste")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void paste(CommandContext args, LocalSession session, LocalPlayer player, public void paste(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
boolean atOrigin = args.hasFlag('o'); boolean atOrigin = args.hasFlag('o');
boolean pasteNoAir = args.hasFlag('a'); boolean pasteNoAir = args.hasFlag('a');
@ -194,8 +198,7 @@ public class ClipboardCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.clipboard.rotate") @CommandPermissions("worldedit.clipboard.rotate")
public void rotate(CommandContext args, LocalSession session, LocalPlayer player, public void rotate(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int angle = args.getInteger(0); int angle = args.getInteger(0);
@ -221,12 +224,8 @@ public class ClipboardCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.clipboard.flip") @CommandPermissions("worldedit.clipboard.flip")
public void flip(CommandContext args, LocalSession session, LocalPlayer player, public void flip(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException { CuboidClipboard.FlipDirection dir = worldEdit.getFlipDirection(player, args.argsLength() > 0 ? args.getString(0).toLowerCase() : "me");
CuboidClipboard.FlipDirection dir = we.getFlipDirection(player,
args.argsLength() > 0 ? args.getString(0).toLowerCase() : "me");
CuboidClipboard clipboard = session.getClipboard(); CuboidClipboard clipboard = session.getClipboard();
clipboard.flip(dir, args.hasFlag('p')); clipboard.flip(dir, args.hasFlag('p'));
player.print("Clipboard flipped."); player.print("Clipboard flipped.");
@ -241,9 +240,8 @@ public class ClipboardCommands {
) )
@Deprecated @Deprecated
@CommandPermissions("worldedit.clipboard.load") @CommandPermissions("worldedit.clipboard.load")
public void load(CommandContext args, LocalSession session, LocalPlayer player, public void load(Actor actor) {
EditSession editSession) throws WorldEditException { actor.printError("This command is no longer used. See //schematic load.");
player.printError("This command is no longer used. See //schematic load.");
} }
@Command( @Command(
@ -255,18 +253,10 @@ public class ClipboardCommands {
) )
@Deprecated @Deprecated
@CommandPermissions("worldedit.clipboard.save") @CommandPermissions("worldedit.clipboard.save")
public void save(CommandContext args, LocalSession session, LocalPlayer player, public void save(Actor actor) {
EditSession editSession) throws WorldEditException { actor.printError("This command is no longer used. See //schematic save.");
player.printError("This command is no longer used. See //schematic save.");
} }
@Command(
aliases = { "/schematic", "/schem"},
desc = "Schematic-related commands"
)
@NestedCommand(SchematicCommands.class)
public void schematic() {}
@Command( @Command(
aliases = { "clearclipboard" }, aliases = { "clearclipboard" },
usage = "", usage = "",
@ -275,9 +265,7 @@ public class ClipboardCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.clipboard.clear") @CommandPermissions("worldedit.clipboard.clear")
public void clearClipboard(CommandContext args, LocalSession session, LocalPlayer player, public void clearClipboard(Player player, LocalSession session, EditSession editSession) throws WorldEditException {
EditSession editSession) throws WorldEditException {
session.setClipboard(null); session.setClipboard(null);
player.print("Clipboard cleared."); player.print("Clipboard cleared.");
} }

View File

@ -22,27 +22,30 @@ package com.sk89q.worldedit.command;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Console; import com.sk89q.worldedit.*;
import com.sk89q.minecraft.util.commands.NestedCommand;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.ItemType; import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldedit.masks.Mask; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.util.command.parametric.Optional;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* General WorldEdit commands. * General WorldEdit commands.
*
* @author sk89q
*/ */
public class GeneralCommands { public class GeneralCommands {
private final WorldEdit we;
public GeneralCommands(WorldEdit we) { private final WorldEdit worldEdit;
this.we = we;
/**
* Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/
public GeneralCommands(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
} }
@Command( @Command(
@ -53,10 +56,9 @@ public class GeneralCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.limit") @CommandPermissions("worldedit.limit")
public void limit(CommandContext args, LocalSession session, LocalPlayer player, public void limit(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = worldEdit.getConfiguration();
boolean mayDisable = player.hasPermission("worldedit.limit.unrestricted"); boolean mayDisable = player.hasPermission("worldedit.limit.unrestricted");
int limit = Math.max(-1, args.getInteger(0)); int limit = Math.max(-1, args.getInteger(0));
@ -84,8 +86,7 @@ public class GeneralCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.fast") @CommandPermissions("worldedit.fast")
public void fast(CommandContext args, LocalSession session, LocalPlayer player, public void fast(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
String newState = args.getString(0, null); String newState = args.getString(0, null);
if (session.hasFastMode()) { if (session.hasFastMode()) {
@ -115,13 +116,11 @@ public class GeneralCommands {
max = -1 max = -1
) )
@CommandPermissions("worldedit.global-mask") @CommandPermissions("worldedit.global-mask")
public void gmask(CommandContext args, LocalSession session, LocalPlayer player, public void gmask(Player player, LocalSession session, EditSession editSession, @Optional Mask mask) throws WorldEditException {
EditSession editSession) throws WorldEditException { if (mask == null) {
if (args.argsLength() == 0) { session.setMask((Mask) null);
session.setMask(null);
player.print("Global mask disabled."); player.print("Global mask disabled.");
} else { } else {
Mask mask = we.getBlockMask(player, session, args.getJoinedStrings(0));
session.setMask(mask); session.setMask(mask);
player.print("Global mask set."); player.print("Global mask set.");
} }
@ -134,8 +133,7 @@ public class GeneralCommands {
min = 0, min = 0,
max = 0 max = 0
) )
public void togglePlace(CommandContext args, LocalSession session, LocalPlayer player, public void togglePlace(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
if (session.togglePlacementPosition()) { if (session.togglePlacementPosition()) {
player.print("Now placing at pos #1."); player.print("Now placing at pos #1.");
@ -157,9 +155,7 @@ public class GeneralCommands {
min = 1, min = 1,
max = 1 max = 1
) )
@Console public void searchItem(Actor actor, CommandContext args) throws WorldEditException {
public void searchItem(CommandContext args, LocalSession session, LocalPlayer player,
EditSession editSession) throws WorldEditException {
String query = args.getString(0).trim().toLowerCase(); String query = args.getString(0).trim().toLowerCase();
boolean blocksOnly = args.hasFlag('b'); boolean blocksOnly = args.hasFlag('b');
@ -171,9 +167,9 @@ public class GeneralCommands {
ItemType type = ItemType.fromID(id); ItemType type = ItemType.fromID(id);
if (type != null) { if (type != null) {
player.print("#" + type.getID() + " (" + type.getName() + ")"); actor.print("#" + type.getID() + " (" + type.getName() + ")");
} else { } else {
player.printError("No item found by ID " + id); actor.printError("No item found by ID " + id);
} }
return; return;
@ -181,26 +177,26 @@ public class GeneralCommands {
} }
if (query.length() <= 2) { if (query.length() <= 2) {
player.printError("Enter a longer search string (len > 2)."); actor.printError("Enter a longer search string (len > 2).");
return; return;
} }
if (!blocksOnly && !itemsOnly) { if (!blocksOnly && !itemsOnly) {
player.print("Searching for: " + query); actor.print("Searching for: " + query);
} else if (blocksOnly && itemsOnly) { } else if (blocksOnly && itemsOnly) {
player.printError("You cannot use both the 'b' and 'i' flags simultaneously."); actor.printError("You cannot use both the 'b' and 'i' flags simultaneously.");
return; return;
} else if (blocksOnly) { } else if (blocksOnly) {
player.print("Searching for blocks: " + query); actor.print("Searching for blocks: " + query);
} else { } else {
player.print("Searching for items: " + query); actor.print("Searching for items: " + query);
} }
int found = 0; int found = 0;
for (ItemType type : ItemType.values()) { for (ItemType type : ItemType.values()) {
if (found >= 15) { if (found >= 15) {
player.print("Too many results!"); actor.print("Too many results!");
break; break;
} }
@ -214,7 +210,7 @@ public class GeneralCommands {
for (String alias : type.getAliases()) { for (String alias : type.getAliases()) {
if (alias.contains(query)) { if (alias.contains(query)) {
player.print("#" + type.getID() + " (" + type.getName() + ")"); actor.print("#" + type.getID() + " (" + type.getName() + ")");
++found; ++found;
break; break;
} }
@ -222,17 +218,8 @@ public class GeneralCommands {
} }
if (found == 0) { if (found == 0) {
player.printError("No items found."); actor.printError("No items found.");
} }
} }
@Command(
aliases = { "we", "worldedit" },
desc = "WorldEdit commands"
)
@NestedCommand(WorldEditCommands.class)
@Console
public void we(CommandContext args, LocalSession session, LocalPlayer player,
EditSession editSession) throws WorldEditException {
}
} }

View File

@ -19,41 +19,46 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.ALL;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.PLACEMENT;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.POSITION;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging; import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.worldedit.BiomeType; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.LocalPlayer; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.function.pattern.Patterns;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.internal.annotation.Selection;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.internal.expression.ExpressionException; import com.sk89q.worldedit.internal.expression.ExpressionException;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.util.TreeGenerator.TreeType;
import com.sk89q.worldedit.util.command.binding.Range;
import com.sk89q.worldedit.util.command.binding.Switch;
import com.sk89q.worldedit.util.command.binding.Text;
import com.sk89q.worldedit.util.command.parametric.Optional;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.*;
/** /**
* Generation commands. * Commands for the generation of shapes and other objects.
*
* @author sk89q
*/ */
public class GenerationCommands { public class GenerationCommands {
private final WorldEdit we;
private final WorldEdit worldEdit;
public GenerationCommands(WorldEdit we) {
this.we = we; /**
* Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/
public GenerationCommands(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
} }
@Command( @Command(
aliases = { "/hcyl" }, aliases = { "/hcyl" },
usage = "<block> <radius>[,<radius>] [height]", usage = "<pattern> <radius>[,<radius>] [height]",
desc = "Generates a hollow cylinder.", desc = "Generates a hollow cylinder.",
help = help =
"Generates a hollow cylinder.\n" + "Generates a hollow cylinder.\n" +
@ -65,40 +70,14 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.cylinder") @CommandPermissions("worldedit.generation.cylinder")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void hcyl(CommandContext args, LocalSession session, LocalPlayer player, public void hcyl(Player player, LocalSession session, EditSession editSession, Pattern pattern, String radiusString, @Optional("1") int height) throws WorldEditException {
EditSession editSession) throws WorldEditException { cyl(player, session, editSession, pattern, radiusString, height, true);
Pattern block = we.getBlockPattern(player, args.getString(0));
String[] radiuses = args.getString(1).split(",");
final double radiusX, radiusZ;
switch (radiuses.length) {
case 1:
radiusX = radiusZ = Math.max(1, Double.parseDouble(radiuses[0]));
break;
case 2:
radiusX = Math.max(1, Double.parseDouble(radiuses[0]));
radiusZ = Math.max(1, Double.parseDouble(radiuses[1]));
break;
default:
player.printError("You must either specify 1 or 2 radius values.");
return;
}
int height = args.argsLength() > 2 ? args.getInteger(2) : 1;
we.checkMaxRadius(radiusX);
we.checkMaxRadius(radiusZ);
we.checkMaxRadius(height);
Vector pos = session.getPlacementPosition(player);
int affected = editSession.makeCylinder(pos, block, radiusX, radiusZ, height, false);
player.print(affected + " block(s) have been created.");
} }
@Command( @Command(
aliases = { "/cyl" }, aliases = { "/cyl" },
usage = "<block> <radius>[,<radius>] [height]", usage = "<block> <radius>[,<radius>] [height]",
flags = "h",
desc = "Generates a cylinder.", desc = "Generates a cylinder.",
help = help =
"Generates a cylinder.\n" + "Generates a cylinder.\n" +
@ -110,34 +89,30 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.cylinder") @CommandPermissions("worldedit.generation.cylinder")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void cyl(CommandContext args, LocalSession session, LocalPlayer player, public void cyl(Player player, LocalSession session, EditSession editSession, Pattern pattern, String radiusString, @Optional("1") int height, @Switch('h') boolean hollow) throws WorldEditException {
EditSession editSession) throws WorldEditException { String[] radii = radiusString.split(",");
Pattern block = we.getBlockPattern(player, args.getString(0));
String[] radiuses = args.getString(1).split(",");
final double radiusX, radiusZ; final double radiusX, radiusZ;
switch (radiuses.length) { switch (radii.length) {
case 1: case 1:
radiusX = radiusZ = Math.max(1, Double.parseDouble(radiuses[0])); radiusX = radiusZ = Math.max(1, Double.parseDouble(radii[0]));
break; break;
case 2: case 2:
radiusX = Math.max(1, Double.parseDouble(radiuses[0])); radiusX = Math.max(1, Double.parseDouble(radii[0]));
radiusZ = Math.max(1, Double.parseDouble(radiuses[1])); radiusZ = Math.max(1, Double.parseDouble(radii[1]));
break; break;
default: default:
player.printError("You must either specify 1 or 2 radius values."); player.printError("You must either specify 1 or 2 radius values.");
return; return;
} }
int height = args.argsLength() > 2 ? args.getInteger(2) : 1;
we.checkMaxRadius(radiusX); worldEdit.checkMaxRadius(radiusX);
we.checkMaxRadius(radiusZ); worldEdit.checkMaxRadius(radiusZ);
we.checkMaxRadius(height); worldEdit.checkMaxRadius(height);
Vector pos = session.getPlacementPosition(player); Vector pos = session.getPlacementPosition(player);
int affected = editSession.makeCylinder(pos, block, radiusX, radiusZ, height, true); int affected = editSession.makeCylinder(pos, Patterns.wrap(pattern), radiusX, radiusZ, height, !hollow);
player.print(affected + " block(s) have been created."); player.print(affected + " block(s) have been created.");
} }
@ -155,52 +130,14 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.sphere") @CommandPermissions("worldedit.generation.sphere")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void hsphere(CommandContext args, LocalSession session, LocalPlayer player, public void hsphere(Player player, LocalSession session, EditSession editSession, Pattern pattern, String radiusString, @Optional("false") boolean raised) throws WorldEditException {
EditSession editSession) throws WorldEditException { sphere(player, session, editSession, pattern, radiusString, raised, true);
final Pattern block = we.getBlockPattern(player, args.getString(0));
String[] radiuses = args.getString(1).split(",");
final double radiusX, radiusY, radiusZ;
switch (radiuses.length) {
case 1:
radiusX = radiusY = radiusZ = Math.max(1, Double.parseDouble(radiuses[0]));
break;
case 3:
radiusX = Math.max(1, Double.parseDouble(radiuses[0]));
radiusY = Math.max(1, Double.parseDouble(radiuses[1]));
radiusZ = Math.max(1, Double.parseDouble(radiuses[2]));
break;
default:
player.printError("You must either specify 1 or 3 radius values.");
return;
}
we.checkMaxRadius(radiusX);
we.checkMaxRadius(radiusY);
we.checkMaxRadius(radiusZ);
final boolean raised;
if (args.argsLength() > 2) {
raised = args.getString(2).equalsIgnoreCase("true") || args.getString(2).equalsIgnoreCase("yes");
} else {
raised = false;
}
Vector pos = session.getPlacementPosition(player);
if (raised) {
pos = pos.add(0, radiusY, 0);
}
int affected = editSession.makeSphere(pos, block, radiusX, radiusY, radiusZ, false);
player.findFreePosition();
player.print(affected + " block(s) have been created.");
} }
@Command( @Command(
aliases = { "/sphere" }, aliases = { "/sphere" },
usage = "<block> <radius>[,<radius>,<radius>] [raised?]", usage = "<block> <radius>[,<radius>,<radius>] [raised?]",
flags = "h",
desc = "Generates a filled sphere.", desc = "Generates a filled sphere.",
help = help =
"Generates a filled sphere.\n" + "Generates a filled sphere.\n" +
@ -212,21 +149,18 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.sphere") @CommandPermissions("worldedit.generation.sphere")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void sphere(CommandContext args, LocalSession session, LocalPlayer player, public void sphere(Player player, LocalSession session, EditSession editSession, Pattern pattern, String radiusString, @Optional("false") boolean raised, @Switch('h') boolean hollow) throws WorldEditException {
EditSession editSession) throws WorldEditException { String[] radii = radiusString.split(",");
Pattern block = we.getBlockPattern(player, args.getString(0));
String[] radiuses = args.getString(1).split(",");
final double radiusX, radiusY, radiusZ; final double radiusX, radiusY, radiusZ;
switch (radiuses.length) { switch (radii.length) {
case 1: case 1:
radiusX = radiusY = radiusZ = Math.max(1, Double.parseDouble(radiuses[0])); radiusX = radiusY = radiusZ = Math.max(1, Double.parseDouble(radii[0]));
break; break;
case 3: case 3:
radiusX = Math.max(1, Double.parseDouble(radiuses[0])); radiusX = Math.max(1, Double.parseDouble(radii[0]));
radiusY = Math.max(1, Double.parseDouble(radiuses[1])); radiusY = Math.max(1, Double.parseDouble(radii[1]));
radiusZ = Math.max(1, Double.parseDouble(radiuses[2])); radiusZ = Math.max(1, Double.parseDouble(radii[2]));
break; break;
default: default:
@ -234,23 +168,16 @@ public class GenerationCommands {
return; return;
} }
we.checkMaxRadius(radiusX); worldEdit.checkMaxRadius(radiusX);
we.checkMaxRadius(radiusY); worldEdit.checkMaxRadius(radiusY);
we.checkMaxRadius(radiusZ); worldEdit.checkMaxRadius(radiusZ);
final boolean raised;
if (args.argsLength() > 2) {
raised = args.getString(2).equalsIgnoreCase("true") || args.getString(2).equalsIgnoreCase("yes");
} else {
raised = false;
}
Vector pos = session.getPlacementPosition(player); Vector pos = session.getPlacementPosition(player);
if (raised) { if (raised) {
pos = pos.add(0, radiusY, 0); pos = pos.add(0, radiusY, 0);
} }
int affected = editSession.makeSphere(pos, block, radiusX, radiusY, radiusZ, true); int affected = editSession.makeSphere(pos, Patterns.wrap(pattern), radiusX, radiusY, radiusZ, !hollow);
player.findFreePosition(); player.findFreePosition();
player.print(affected + " block(s) have been created."); player.print(affected + " block(s) have been created.");
} }
@ -265,22 +192,9 @@ public class GenerationCommands {
@CommandPermissions("worldedit.generation.forest") @CommandPermissions("worldedit.generation.forest")
@Logging(POSITION) @Logging(POSITION)
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void forestGen(CommandContext args, LocalSession session, LocalPlayer player, public void forestGen(Player player, LocalSession session, EditSession editSession, @Optional("10") int size, @Optional("tree") TreeType type, @Optional("5") double density) throws WorldEditException {
EditSession editSession) throws WorldEditException { density = density / 100;
int affected = editSession.makeForest(session.getPlacementPosition(player), size, density, new TreeGenerator(type));
int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 10;
TreeGenerator.TreeType type = args.argsLength() > 1 ?
TreeGenerator.lookup(args.getString(1))
: TreeGenerator.TreeType.TREE;
double density = args.argsLength() > 2 ? args.getDouble(2) / 100 : 0.05;
if (type == null) {
player.printError("Tree type '" + args.getString(1) + "' is unknown.");
return;
}
int affected = editSession.makeForest(session.getPlacementPosition(player),
size, density, new TreeGenerator(type));
player.print(affected + " trees created."); player.print(affected + " trees created.");
} }
@ -293,59 +207,38 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.pumpkins") @CommandPermissions("worldedit.generation.pumpkins")
@Logging(POSITION) @Logging(POSITION)
public void pumpkins(CommandContext args, LocalSession session, LocalPlayer player, public void pumpkins(Player player, LocalSession session, EditSession editSession, @Optional("10") int apothem) throws WorldEditException {
EditSession editSession) throws WorldEditException { int affected = editSession.makePumpkinPatches(session.getPlacementPosition(player), apothem);
int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 10;
int affected = editSession.makePumpkinPatches(session.getPlacementPosition(player), size);
player.print(affected + " pumpkin patches created."); player.print(affected + " pumpkin patches created.");
} }
@Command(
aliases = { "/hpyramid" },
usage = "<block> <size>",
desc = "Generate a hollow pyramid",
min = 2,
max = 2
)
@CommandPermissions("worldedit.generation.pyramid")
@Logging(PLACEMENT)
public void hollowPyramid(Player player, LocalSession session, EditSession editSession, Pattern pattern, @Range(min = 1) int size) throws WorldEditException {
pyramid(player, session, editSession, pattern, size, true);
}
@Command( @Command(
aliases = { "/pyramid" }, aliases = { "/pyramid" },
usage = "<block> <size>", usage = "<block> <size>",
flags = "h",
desc = "Generate a filled pyramid", desc = "Generate a filled pyramid",
min = 2, min = 2,
max = 2 max = 2
) )
@CommandPermissions("worldedit.generation.pyramid") @CommandPermissions("worldedit.generation.pyramid")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void pyramid(CommandContext args, LocalSession session, LocalPlayer player, public void pyramid(Player player, LocalSession session, EditSession editSession, Pattern pattern, @Range(min = 1) int size, @Switch('h') boolean hollow) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Pattern block = we.getBlockPattern(player, args.getString(0));
int size = Math.max(1, args.getInteger(1));
Vector pos = session.getPlacementPosition(player); Vector pos = session.getPlacementPosition(player);
worldEdit.checkMaxRadius(size);
we.checkMaxRadius(size); int affected = editSession.makePyramid(pos, Patterns.wrap(pattern), size, !hollow);
int affected = editSession.makePyramid(pos, block, size, true);
player.findFreePosition();
player.print(affected + " block(s) have been created.");
}
@Command(
aliases = { "/hpyramid" },
usage = "<block> <size>",
desc = "Generate a hollow pyramid",
min = 2,
max = 2
)
@CommandPermissions("worldedit.generation.pyramid")
@Logging(PLACEMENT)
public void hpyramid(CommandContext args, LocalSession session, LocalPlayer player,
EditSession editSession) throws WorldEditException {
Pattern block = we.getBlockPattern(player, args.getString(0));
int size = Math.max(1, args.getInteger(1));
Vector pos = session.getPlacementPosition(player);
we.checkMaxRadius(size);
int affected = editSession.makePyramid(pos, block, size, false);
player.findFreePosition(); player.findFreePosition();
player.print(affected + " block(s) have been created."); player.print(affected + " block(s) have been created.");
} }
@ -371,26 +264,25 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.shape") @CommandPermissions("worldedit.generation.shape")
@Logging(ALL) @Logging(ALL)
public void generate(CommandContext args, LocalSession session, LocalPlayer player, public void generate(Player player, LocalSession session, EditSession editSession,
EditSession editSession) throws WorldEditException { @Selection Region region,
Pattern pattern,
final Pattern pattern = we.getBlockPattern(player, args.getString(0)); @Text String expression,
final Region region = session.getSelection(player.getWorld()); @Switch('h') boolean hollow,
@Switch('r') boolean useRawCoords,
final boolean hollow = args.hasFlag('h'); @Switch('o') boolean offset,
@Switch('c') boolean offsetCenter) throws WorldEditException {
final String expression = args.getJoinedStrings(1);
final Vector zero; final Vector zero;
Vector unit; Vector unit;
if (args.hasFlag('r')) { if (useRawCoords) {
zero = Vector.ZERO; zero = Vector.ZERO;
unit = Vector.ONE; unit = Vector.ONE;
} else if (args.hasFlag('o')) { } else if (offset) {
zero = session.getPlacementPosition(player); zero = session.getPlacementPosition(player);
unit = Vector.ONE; unit = Vector.ONE;
} else if (args.hasFlag('c')) { } else if (offsetCenter) {
final Vector min = region.getMinimumPoint(); final Vector min = region.getMinimumPoint();
final Vector max = region.getMaximumPoint(); final Vector max = region.getMaximumPoint();
@ -409,7 +301,7 @@ public class GenerationCommands {
} }
try { try {
final int affected = editSession.makeShape(region, zero, unit, pattern, expression, hollow); final int affected = editSession.makeShape(region, zero, unit, Patterns.wrap(pattern), expression, hollow);
player.findFreePosition(); player.findFreePosition();
player.print(affected + " block(s) have been created."); player.print(affected + " block(s) have been created.");
} catch (ExpressionException e) { } catch (ExpressionException e) {
@ -438,26 +330,24 @@ public class GenerationCommands {
) )
@CommandPermissions({"worldedit.generation.shape", "worldedit.biome.set"}) @CommandPermissions({"worldedit.generation.shape", "worldedit.biome.set"})
@Logging(ALL) @Logging(ALL)
public void generateBiome(CommandContext args, LocalSession session, LocalPlayer player, public void generateBiome(Player player, LocalSession session, EditSession editSession,
EditSession editSession) throws WorldEditException { @Selection Region region,
BiomeType target,
final BiomeType target = we.getServer().getBiomes().get(args.getString(0)); @Text String expression,
final Region region = session.getSelection(player.getWorld()); @Switch('h') boolean hollow,
@Switch('r') boolean useRawCoords,
final boolean hollow = args.hasFlag('h'); @Switch('o') boolean offset,
@Switch('c') boolean offsetCenter) throws WorldEditException {
final String expression = args.getJoinedStrings(1);
final Vector zero; final Vector zero;
Vector unit; Vector unit;
if (args.hasFlag('r')) { if (useRawCoords) {
zero = Vector.ZERO; zero = Vector.ZERO;
unit = Vector.ONE; unit = Vector.ONE;
} else if (args.hasFlag('o')) { } else if (offset) {
zero = session.getPlacementPosition(player); zero = session.getPlacementPosition(player);
unit = Vector.ONE; unit = Vector.ONE;
} else if (args.hasFlag('c')) { } else if (offsetCenter) {
final Vector min = region.getMinimumPoint(); final Vector min = region.getMinimumPoint();
final Vector max = region.getMaximumPoint(); final Vector max = region.getMaximumPoint();
@ -483,4 +373,5 @@ public class GenerationCommands {
player.printError(e.getMessage()); player.printError(e.getMessage());
} }
} }
} }

View File

@ -23,17 +23,25 @@ import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.entity.Player;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* History little commands. * Commands to undo, redo, and clear history.
*
* @author sk89q
*/ */
public class HistoryCommands { public class HistoryCommands {
private final WorldEdit we;
private final WorldEdit worldEdit;
public HistoryCommands(WorldEdit we) {
this.we = we; /**
* Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/
public HistoryCommands(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
} }
@Command( @Command(
@ -44,9 +52,7 @@ public class HistoryCommands {
max = 2 max = 2
) )
@CommandPermissions("worldedit.history.undo") @CommandPermissions("worldedit.history.undo")
public void undo(CommandContext args, LocalSession session, LocalPlayer player, public void undo(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int times = Math.max(1, args.getInteger(0, 1)); int times = Math.max(1, args.getInteger(0, 1));
for (int i = 0; i < times; ++i) { for (int i = 0; i < times; ++i) {
EditSession undone; EditSession undone;
@ -54,7 +60,7 @@ public class HistoryCommands {
undone = session.undo(session.getBlockBag(player), player); undone = session.undo(session.getBlockBag(player), player);
} else { } else {
player.checkPermission("worldedit.history.undo.other"); player.checkPermission("worldedit.history.undo.other");
LocalSession sess = we.getSession(args.getString(1)); LocalSession sess = worldEdit.getSession(args.getString(1));
if (sess == null) { if (sess == null) {
player.printError("Unable to find session for " + args.getString(1)); player.printError("Unable to find session for " + args.getString(1));
break; break;
@ -63,7 +69,7 @@ public class HistoryCommands {
} }
if (undone != null) { if (undone != null) {
player.print("Undo successful."); player.print("Undo successful.");
we.flushBlockBag(player, undone); worldEdit.flushBlockBag(player, undone);
} else { } else {
player.printError("Nothing left to undo."); player.printError("Nothing left to undo.");
break; break;
@ -79,8 +85,7 @@ public class HistoryCommands {
max = 2 max = 2
) )
@CommandPermissions("worldedit.history.redo") @CommandPermissions("worldedit.history.redo")
public void redo(CommandContext args, LocalSession session, LocalPlayer player, public void redo(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int times = Math.max(1, args.getInteger(0, 1)); int times = Math.max(1, args.getInteger(0, 1));
@ -90,7 +95,7 @@ public class HistoryCommands {
redone = session.redo(session.getBlockBag(player), player); redone = session.redo(session.getBlockBag(player), player);
} else { } else {
player.checkPermission("worldedit.history.redo.other"); player.checkPermission("worldedit.history.redo.other");
LocalSession sess = we.getSession(args.getString(1)); LocalSession sess = worldEdit.getSession(args.getString(1));
if (sess == null) { if (sess == null) {
player.printError("Unable to find session for " + args.getString(1)); player.printError("Unable to find session for " + args.getString(1));
break; break;
@ -99,7 +104,7 @@ public class HistoryCommands {
} }
if (redone != null) { if (redone != null) {
player.print("Redo successful."); player.print("Redo successful.");
we.flushBlockBag(player, redone); worldEdit.flushBlockBag(player, redone);
} else { } else {
player.printError("Nothing left to redo."); player.printError("Nothing left to redo.");
} }
@ -114,10 +119,9 @@ public class HistoryCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.history.clear") @CommandPermissions("worldedit.history.clear")
public void clearHistory(CommandContext args, LocalSession session, LocalPlayer player, public void clearHistory(Player player, LocalSession session, EditSession editSession) throws WorldEditException {
EditSession editSession) throws WorldEditException {
session.clearHistory(); session.clearHistory();
player.print("History cleared."); player.print("History cleared.");
} }
} }

View File

@ -19,31 +19,32 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.POSITION;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging; import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession; import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.WorldEdit; import static com.sk89q.minecraft.util.commands.Logging.LogMode.POSITION;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.WorldVector;
/** /**
* Navigation commands. * Commands for moving the player around.
*
* @author sk89q
*/ */
public class NavigationCommands { public class NavigationCommands {
@SuppressWarnings("unused")
private final WorldEdit we;
public NavigationCommands(WorldEdit we) { @SuppressWarnings("unused")
this.we = we; private final WorldEdit worldEdit;
/**
* Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/
public NavigationCommands(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
} }
@Command( @Command(
@ -54,9 +55,7 @@ public class NavigationCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.navigation.unstuck") @CommandPermissions("worldedit.navigation.unstuck")
public void unstuck(CommandContext args, LocalSession session, LocalPlayer player, public void unstuck(Player player) throws WorldEditException {
EditSession editSession) throws WorldEditException {
player.print("There you go!"); player.print("There you go!");
player.findFreePosition(); player.findFreePosition();
} }
@ -69,8 +68,7 @@ public class NavigationCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.navigation.ascend") @CommandPermissions("worldedit.navigation.ascend")
public void ascend(CommandContext args, LocalSession session, LocalPlayer player, public void ascend(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int levelsToAscend = 0; int levelsToAscend = 0;
if (args.argsLength() == 0) { if (args.argsLength() == 0) {
levelsToAscend = 1; levelsToAscend = 1;
@ -96,8 +94,7 @@ public class NavigationCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.navigation.descend") @CommandPermissions("worldedit.navigation.descend")
public void descend(CommandContext args, LocalSession session, LocalPlayer player, public void descend(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int levelsToDescend = 0; int levelsToDescend = 0;
if (args.argsLength() == 0) { if (args.argsLength() == 0) {
levelsToDescend = 1; levelsToDescend = 1;
@ -125,8 +122,7 @@ public class NavigationCommands {
) )
@CommandPermissions("worldedit.navigation.ceiling") @CommandPermissions("worldedit.navigation.ceiling")
@Logging(POSITION) @Logging(POSITION)
public void ceiling(CommandContext args, LocalSession session, LocalPlayer player, public void ceiling(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
final int clearance = args.argsLength() > 0 ? final int clearance = args.argsLength() > 0 ?
Math.max(0, args.getInteger(0)) : 0; Math.max(0, args.getInteger(0)) : 0;
@ -147,8 +143,7 @@ public class NavigationCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.navigation.thru.command") @CommandPermissions("worldedit.navigation.thru.command")
public void thru(CommandContext args, LocalSession session, LocalPlayer player, public void thru(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
if (player.passThroughForwardWall(6)) { if (player.passThroughForwardWall(6)) {
player.print("Whoosh!"); player.print("Whoosh!");
} else { } else {
@ -164,8 +159,7 @@ public class NavigationCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.navigation.jumpto.command") @CommandPermissions("worldedit.navigation.jumpto.command")
public void jumpTo(CommandContext args, LocalSession session, LocalPlayer player, public void jumpTo(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
WorldVector pos = player.getSolidBlockTrace(300); WorldVector pos = player.getSolidBlockTrace(300);
if (pos != null) { if (pos != null) {
@ -186,8 +180,7 @@ public class NavigationCommands {
) )
@CommandPermissions("worldedit.navigation.up") @CommandPermissions("worldedit.navigation.up")
@Logging(POSITION) @Logging(POSITION)
public void up(CommandContext args, LocalSession session, LocalPlayer player, public void up(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
final int distance = args.getInteger(0); final int distance = args.getInteger(0);
@ -206,7 +199,7 @@ public class NavigationCommands {
* @return true, if glass should always be put under the player * @return true, if glass should always be put under the player
*/ */
private boolean getAlwaysGlass(CommandContext args) { private boolean getAlwaysGlass(CommandContext args) {
final LocalConfiguration config = we.getConfiguration(); final LocalConfiguration config = worldEdit.getConfiguration();
final boolean forceFlight = args.hasFlag('f'); final boolean forceFlight = args.hasFlag('f');
final boolean forceGlass = args.hasFlag('g'); final boolean forceGlass = args.hasFlag('g');

View File

@ -20,50 +20,61 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging; import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.internal.expression.ExpressionException;
import com.sk89q.worldedit.function.mask.ExistingBlockMask;
import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.math.convolution.GaussianKernel;
import com.sk89q.worldedit.math.convolution.HeightMap;
import com.sk89q.worldedit.math.convolution.HeightMapFilter;
import com.sk89q.worldedit.function.GroundFunction; import com.sk89q.worldedit.function.GroundFunction;
import com.sk89q.worldedit.function.generator.FloraGenerator; import com.sk89q.worldedit.function.generator.FloraGenerator;
import com.sk89q.worldedit.function.generator.ForestGenerator; import com.sk89q.worldedit.function.generator.ForestGenerator;
import com.sk89q.worldedit.function.visitor.LayerVisitor; import com.sk89q.worldedit.function.mask.ExistingBlockMask;
import com.sk89q.worldedit.masks.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.patterns.Pattern; import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.patterns.SingleBlockPattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.pattern.Patterns;
import com.sk89q.worldedit.function.visitor.LayerVisitor;
import com.sk89q.worldedit.internal.annotation.Direction;
import com.sk89q.worldedit.internal.annotation.Selection;
import com.sk89q.worldedit.internal.expression.ExpressionException;
import com.sk89q.worldedit.math.convolution.GaussianKernel;
import com.sk89q.worldedit.math.convolution.HeightMap;
import com.sk89q.worldedit.math.convolution.HeightMapFilter;
import com.sk89q.worldedit.math.noise.RandomNoise;
import com.sk89q.worldedit.regions.ConvexPolyhedralRegion; import com.sk89q.worldedit.regions.ConvexPolyhedralRegion;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
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.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.math.noise.RandomNoise; import com.sk89q.worldedit.util.TreeGenerator.TreeType;
import com.sk89q.worldedit.util.command.binding.Range;
import com.sk89q.worldedit.util.command.binding.Switch;
import com.sk89q.worldedit.util.command.binding.Text;
import com.sk89q.worldedit.util.command.parametric.Optional;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.*; import static com.sk89q.minecraft.util.commands.Logging.LogMode.*;
import static com.sk89q.worldedit.regions.Regions.*; import static com.sk89q.worldedit.regions.Regions.*;
/** /**
* Region related commands. * Commands that operate on regions.
*
* @author sk89q
*/ */
public class RegionCommands { public class RegionCommands {
private final WorldEdit we;
public RegionCommands(WorldEdit we) { private final WorldEdit worldEdit;
this.we = we;
/**
* Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/
public RegionCommands(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
} }
@Command( @Command(
@ -75,20 +86,8 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.set") @CommandPermissions("worldedit.region.set")
@Logging(REGION) @Logging(REGION)
public void set(CommandContext args, LocalSession session, LocalPlayer player, public void set(Player player, LocalSession session, EditSession editSession, Pattern pattern) throws WorldEditException {
EditSession editSession) throws WorldEditException { int affected = editSession.setBlocks(session.getSelection(player.getWorld()), Patterns.wrap(pattern));
Pattern pattern = we.getBlockPattern(player, args.getString(0));
int affected;
if (pattern instanceof SingleBlockPattern) {
affected = editSession.setBlocks(session.getSelection(player.getWorld()),
((SingleBlockPattern) pattern).getBlock());
} else {
affected = editSession.setBlocks(session.getSelection(player.getWorld()), pattern);
}
player.print(affected + " block(s) have been changed."); player.print(affected + " block(s) have been changed.");
} }
@ -107,24 +106,21 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.line") @CommandPermissions("worldedit.region.line")
@Logging(REGION) @Logging(REGION)
public void line(CommandContext args, LocalSession session, LocalPlayer player, public void line(Player player, EditSession editSession,
EditSession editSession) throws WorldEditException { @Selection Region region,
Pattern pattern,
@Optional("0") @Range(min = 0) int thickness,
@Switch('h') boolean shell) throws WorldEditException {
Region region = session.getSelection(session.getSelectionWorld());
if (!(region instanceof CuboidRegion)) { if (!(region instanceof CuboidRegion)) {
player.printError("Invalid region type"); player.printError("//line only works with cuboid selections");
return;
}
if (args.argsLength() < 2 ? false : args.getDouble(1) < 0) {
player.printError("Invalid thickness. Must not be negative");
return; return;
} }
Pattern pattern = we.getBlockPattern(player, args.getString(0));
CuboidRegion cuboidregion = (CuboidRegion) region; CuboidRegion cuboidregion = (CuboidRegion) region;
Vector pos1 = cuboidregion.getPos1(); Vector pos1 = cuboidregion.getPos1();
Vector pos2 = cuboidregion.getPos2(); Vector pos2 = cuboidregion.getPos2();
int blocksChanged = editSession.drawLine(pattern, pos1, pos2, args.argsLength() < 2 ? 0 : args.getDouble(1), !args.hasFlag('h')); int blocksChanged = editSession.drawLine(Patterns.wrap(pattern), pos1, pos2, thickness, !shell);
player.print(blocksChanged + " block(s) have been changed."); player.print(blocksChanged + " block(s) have been changed.");
} }
@ -144,24 +140,20 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.curve") @CommandPermissions("worldedit.region.curve")
@Logging(REGION) @Logging(REGION)
public void curve(CommandContext args, LocalSession session, LocalPlayer player, public void curve(Player player, EditSession editSession,
EditSession editSession) throws WorldEditException { @Selection Region region,
Pattern pattern,
Region region = session.getSelection(session.getSelectionWorld()); @Optional("0") @Range(min = 0) int thickness,
@Switch('h') boolean shell) throws WorldEditException {
if (!(region instanceof ConvexPolyhedralRegion)) { if (!(region instanceof ConvexPolyhedralRegion)) {
player.printError("Invalid region type"); player.printError("//line only works with convex polyhedral selections");
return;
}
if (args.argsLength() < 2 ? false : args.getDouble(1) < 0) {
player.printError("Invalid thickness. Must not be negative");
return; return;
} }
Pattern pattern = we.getBlockPattern(player, args.getString(0));
ConvexPolyhedralRegion cpregion = (ConvexPolyhedralRegion) region; ConvexPolyhedralRegion cpregion = (ConvexPolyhedralRegion) region;
List<Vector> vectors = new ArrayList<Vector>(cpregion.getVertices()); List<Vector> vectors = new ArrayList<Vector>(cpregion.getVertices());
int blocksChanged = editSession.drawSpline(pattern, vectors, 0, 0, 0, 10, args.argsLength() < 2 ? 0 : args.getDouble(1), !args.hasFlag('h')); int blocksChanged = editSession.drawSpline(Patterns.wrap(pattern), vectors, 0, 0, 0, 10, thickness, !shell);
player.print(blocksChanged + " block(s) have been changed."); player.print(blocksChanged + " block(s) have been changed.");
} }
@ -176,27 +168,11 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.replace") @CommandPermissions("worldedit.region.replace")
@Logging(REGION) @Logging(REGION)
public void replace(CommandContext args, LocalSession session, LocalPlayer player, public void replace(Player player, EditSession editSession, @Selection Region region, @Optional Mask from, Pattern to) throws WorldEditException {
EditSession editSession) throws WorldEditException { if (from == null) {
from = new ExistingBlockMask(editSession);
Set<BaseBlock> from;
Pattern to;
if (args.argsLength() == 1) {
from = null;
to = we.getBlockPattern(player, args.getString(0));
} else {
from = we.getBlocks(player, args.getString(0), true, !args.hasFlag('f'));
to = we.getBlockPattern(player, args.getString(1));
} }
int affected = editSession.replaceBlocks(region, from, Patterns.wrap(to));
final int affected;
if (to instanceof SingleBlockPattern) {
affected = editSession.replaceBlocks(session.getSelection(player.getWorld()), from,
((SingleBlockPattern) to).getBlock());
} else {
affected = editSession.replaceBlocks(session.getSelection(player.getWorld()), from, to);
}
player.print(affected + " block(s) have been replaced."); player.print(affected + " block(s) have been replaced.");
} }
@ -209,20 +185,9 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.overlay") @CommandPermissions("worldedit.region.overlay")
@Logging(REGION) @Logging(REGION)
public void overlay(CommandContext args, LocalSession session, LocalPlayer player, public void overlay(Player player, EditSession editSession, @Selection Region region, Pattern pattern) throws WorldEditException {
EditSession editSession) throws WorldEditException { int affected = editSession.overlayCuboidBlocks(region, Patterns.wrap(pattern));
player.print(affected + " block(s) have been overlaid.");
Pattern pat = we.getBlockPattern(player, args.getString(0));
Region region = session.getSelection(player.getWorld());
int affected = 0;
if (pat instanceof SingleBlockPattern) {
affected = editSession.overlayCuboidBlocks(region,
((SingleBlockPattern) pat).getBlock());
} else {
affected = editSession.overlayCuboidBlocks(region, pat);
}
player.print(affected + " block(s) have been overlayed.");
} }
@Command( @Command(
@ -234,12 +199,8 @@ public class RegionCommands {
) )
@Logging(REGION) @Logging(REGION)
@CommandPermissions("worldedit.region.center") @CommandPermissions("worldedit.region.center")
public void center(CommandContext args, LocalSession session, LocalPlayer player, public void center(Player player, EditSession editSession, @Selection Region region, Pattern pattern) throws WorldEditException {
EditSession editSession) throws WorldEditException { int affected = editSession.center(region, Patterns.wrap(pattern));
Pattern pattern = we.getBlockPattern(player, args.getString(0));
Region region = session.getSelection(player.getWorld());
int affected = editSession.center(region, pattern);
player.print("Center set ("+ affected + " blocks changed)"); player.print("Center set ("+ affected + " blocks changed)");
} }
@ -252,12 +213,9 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.naturalize") @CommandPermissions("worldedit.region.naturalize")
@Logging(REGION) @Logging(REGION)
public void naturalize(CommandContext args, LocalSession session, LocalPlayer player, public void naturalize(Player player, EditSession editSession, @Selection Region region) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Region region = session.getSelection(player.getWorld());
int affected = editSession.naturalizeCuboidBlocks(region); int affected = editSession.naturalizeCuboidBlocks(region);
player.print(affected + " block(s) have been naturalized."); player.print(affected + " block(s) have been made to look more natural.");
} }
@Command( @Command(
@ -269,20 +227,8 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.walls") @CommandPermissions("worldedit.region.walls")
@Logging(REGION) @Logging(REGION)
public void walls(CommandContext args, LocalSession session, LocalPlayer player, public void walls(Player player, EditSession editSession, @Selection Region region, Pattern pattern) throws WorldEditException {
EditSession editSession) throws WorldEditException { int affected = editSession.makeCuboidWalls(region, Patterns.wrap(pattern));
final Pattern pattern = we.getBlockPattern(player, args.getString(0));
final int affected;
final Region region = session.getSelection(player.getWorld());
if (!(region instanceof CuboidRegion)) {
affected = editSession.makeWalls(region, pattern);
} else if (pattern instanceof SingleBlockPattern) {
affected = editSession.makeCuboidWalls(region, ((SingleBlockPattern) pattern).getBlock());
} else {
affected = editSession.makeCuboidWalls(region, pattern);
}
player.print(affected + " block(s) have been changed."); player.print(affected + " block(s) have been changed.");
} }
@ -295,20 +241,8 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.faces") @CommandPermissions("worldedit.region.faces")
@Logging(REGION) @Logging(REGION)
public void faces(CommandContext args, LocalSession session, LocalPlayer player, public void faces(Player player, EditSession editSession, @Selection Region region, Pattern pattern) throws WorldEditException {
EditSession editSession) throws WorldEditException { int affected = editSession.makeCuboidFaces(region, Patterns.wrap(pattern));
final Pattern pattern = we.getBlockPattern(player, args.getString(0));
final int affected;
final Region region = session.getSelection(player.getWorld());
if (!(region instanceof CuboidRegion)) {
affected = editSession.makeFaces(region, pattern);
} else if (pattern instanceof SingleBlockPattern) {
affected = editSession.makeCuboidFaces(region, ((SingleBlockPattern) pattern).getBlock());
} else {
affected = editSession.makeCuboidFaces(region, pattern);
}
player.print(affected + " block(s) have been changed."); player.print(affected + " block(s) have been changed.");
} }
@ -325,15 +259,8 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.smooth") @CommandPermissions("worldedit.region.smooth")
@Logging(REGION) @Logging(REGION)
public void smooth(CommandContext args, LocalSession session, LocalPlayer player, public void smooth(Player player, EditSession editSession, @Selection Region region, @Optional("1") int iterations, @Switch('n') boolean affectNatural) throws WorldEditException {
EditSession editSession) throws WorldEditException { HeightMap heightMap = new HeightMap(editSession, region, affectNatural);
int iterations = 1;
if (args.argsLength() > 0) {
iterations = args.getInteger(0);
}
HeightMap heightMap = new HeightMap(editSession, session.getSelection(player.getWorld()), args.hasFlag('n'));
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);
player.print("Terrain's height map smoothed. " + affected + " block(s) changed."); player.print("Terrain's height map smoothed. " + affected + " block(s) changed.");
@ -354,28 +281,18 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.move") @CommandPermissions("worldedit.region.move")
@Logging(ORIENTATION_REGION) @Logging(ORIENTATION_REGION)
public void move(CommandContext args, LocalSession session, LocalPlayer player, public void move(Player player, EditSession editSession, LocalSession session,
EditSession editSession) throws WorldEditException { @Selection Region region,
@Optional("1") @Range(min = 1) int count,
@Optional(Direction.AIM) @Direction Vector direction,
@Optional("air") BaseBlock replace,
@Switch('s') boolean moveSelection) throws WorldEditException {
int count = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1; int affected = editSession.moveRegion(region, direction, count, true, replace);
Vector dir = we.getDirection(player,
args.argsLength() > 1 ? args.getString(1).toLowerCase() : "me");
BaseBlock replace;
// Replacement block argument if (moveSelection) {
if (args.argsLength() > 2) {
replace = we.getBlock(player, args.getString(2));
} else {
replace = new BaseBlock(BlockID.AIR);
}
int affected = editSession.moveRegion(session.getSelection(player.getWorld()),
dir, count, true, replace);
if (args.hasFlag('s')) {
try { try {
Region region = session.getSelection(player.getWorld()); region.shift(direction.multiply(count));
region.shift(dir.multiply(count));
session.getRegionSelector(player.getWorld()).learnChanges(); session.getRegionSelector(player.getWorld()).learnChanges();
session.getRegionSelector(player.getWorld()).explainRegionAdjust(player, session); session.getRegionSelector(player.getWorld()).explainRegionAdjust(player, session);
@ -402,22 +319,19 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.stack") @CommandPermissions("worldedit.region.stack")
@Logging(ORIENTATION_REGION) @Logging(ORIENTATION_REGION)
public void stack(CommandContext args, LocalSession session, LocalPlayer player, public void stack(Player player, EditSession editSession, LocalSession session,
EditSession editSession) throws WorldEditException { @Selection Region region,
@Optional("1") @Range(min = 1) int count,
@Optional(Direction.AIM) @Direction Vector direction,
@Switch('s') boolean moveSelection,
@Switch('a') boolean ignoreAirBlocks) throws WorldEditException {
int affected = editSession.stackCuboidRegion(region, direction, count, !ignoreAirBlocks);
int count = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1; if (moveSelection) {
Vector dir = we.getDiagonalDirection(player,
args.argsLength() > 1 ? args.getString(1).toLowerCase() : "me");
int affected = editSession.stackCuboidRegion(session.getSelection(player.getWorld()),
dir, count, !args.hasFlag('a'));
if (args.hasFlag('s')) {
try { try {
final Region region = session.getSelection(player.getWorld());
final Vector size = region.getMaximumPoint().subtract(region.getMinimumPoint()); final Vector size = region.getMaximumPoint().subtract(region.getMinimumPoint());
final Vector shiftVector = dir.multiply(count * (Math.abs(dir.dot(size)) + 1)); final Vector shiftVector = direction.multiply(count * (Math.abs(direction.dot(size)) + 1));
region.shift(shiftVector); region.shift(shiftVector);
session.getRegionSelector(player.getWorld()).learnChanges(); session.getRegionSelector(player.getWorld()).learnChanges();
@ -443,14 +357,14 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.regen") @CommandPermissions("worldedit.regen")
@Logging(REGION) @Logging(REGION)
public void regenerateChunk(CommandContext args, LocalSession session, LocalPlayer player, public void regenerateChunk(Player player, LocalSession session, EditSession editSession, @Selection Region region) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Region region = session.getSelection(player.getWorld());
Mask mask = session.getMask(); Mask mask = session.getMask();
session.setMask(null); try {
player.getWorld().regenerate(region, editSession); session.setMask((Mask) null);
session.setMask(mask); player.getWorld().regenerate(region, editSession);
} finally {
session.setMask(mask);
}
player.print("Region regenerated."); player.print("Region regenerated.");
} }
@ -469,20 +383,18 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.deform") @CommandPermissions("worldedit.region.deform")
@Logging(ALL) @Logging(ALL)
public void deform(CommandContext args, LocalSession session, LocalPlayer player, public void deform(Player player, LocalSession session, EditSession editSession,
EditSession editSession) throws WorldEditException { @Selection Region region,
@Text String expression,
final Region region = session.getSelection(player.getWorld()); @Switch('r') boolean useRawCoords,
@Switch('o') boolean offset) throws WorldEditException {
final String expression = args.getJoinedStrings(0);
final Vector zero; final Vector zero;
Vector unit; Vector unit;
if (args.hasFlag('r')) { if (useRawCoords) {
zero = Vector.ZERO; zero = Vector.ZERO;
unit = Vector.ONE; unit = Vector.ONE;
} else if (args.hasFlag('o')) { } else if (offset) {
zero = session.getPlacementPosition(player); zero = session.getPlacementPosition(player);
unit = Vector.ONE; unit = Vector.ONE;
} else { } else {
@ -519,14 +431,12 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.hollow") @CommandPermissions("worldedit.region.hollow")
@Logging(REGION) @Logging(REGION)
public void hollow(CommandContext args, LocalSession session, LocalPlayer player, public void hollow(Player player, EditSession editSession,
EditSession editSession) throws WorldEditException { @Selection Region region,
@Optional("0") @Range(min = 0) int thickness,
final int thickness = args.argsLength() >= 1 ? Math.max(1, args.getInteger(0)) : 1; @Optional("air") Pattern pattern) throws WorldEditException {
final Pattern pattern = args.argsLength() >= 2 ? we.getBlockPattern(player, args.getString(1)) : new SingleBlockPattern(new BaseBlock(BlockID.AIR));
final int affected = editSession.hollowOutRegion(session.getSelection(player.getWorld()), thickness, pattern);
int affected = editSession.hollowOutRegion(region, thickness, Patterns.wrap(pattern));
player.print(affected + " block(s) have been changed."); player.print(affected + " block(s) have been changed.");
} }
@ -539,18 +449,8 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.forest") @CommandPermissions("worldedit.region.forest")
@Logging(REGION) @Logging(REGION)
public void forest(CommandContext args, LocalSession session, LocalPlayer player, public void forest(Player player, EditSession editSession, @Selection Region region, @Optional("tree") TreeType type, @Optional("5") double density) throws WorldEditException {
EditSession editSession) throws WorldEditException { density = density / 100;
TreeGenerator.TreeType type = args.argsLength() > 0 ? TreeGenerator.lookup(args.getString(0)) : TreeGenerator.TreeType.TREE;
double density = args.argsLength() > 1 ? args.getDouble(1) / 100 : 0.05;
if (type == null) {
player.printError("Tree type '" + args.getString(0) + "' is unknown.");
return;
}
Region region = session.getSelection(player.getWorld());
ForestGenerator generator = new ForestGenerator(editSession, new TreeGenerator(type)); ForestGenerator generator = new ForestGenerator(editSession, new TreeGenerator(type));
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);
@ -569,10 +469,8 @@ public class RegionCommands {
) )
@CommandPermissions("worldedit.region.flora") @CommandPermissions("worldedit.region.flora")
@Logging(REGION) @Logging(REGION)
public void flora(CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession) throws WorldEditException { public void flora(Player player, EditSession editSession, @Selection Region region, @Optional("10") double density) throws WorldEditException {
double density = args.argsLength() > 0 ? args.getDouble(0) / 100 : 0.1; density = density / 100;
Region region = session.getSelection(player.getWorld());
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);

View File

@ -21,6 +21,8 @@ package com.sk89q.worldedit.command;
import com.sk89q.minecraft.util.commands.*; import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.schematic.SchematicFormat; import com.sk89q.worldedit.schematic.SchematicFormat;
import com.sk89q.worldedit.world.DataException; import com.sk89q.worldedit.world.DataException;
@ -30,16 +32,23 @@ import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Commands related to schematics * Commands that work with schematic files.
*
* @see com.sk89q.worldedit.command.ClipboardCommands#schematic()
*/ */
public class SchematicCommands { public class SchematicCommands {
private final WorldEdit we;
public SchematicCommands(WorldEdit we) { private final WorldEdit worldEdit;
this.we = we;
/**
* Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/
public SchematicCommands(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
} }
@Command( @Command(
@ -55,10 +64,9 @@ public class SchematicCommands {
max = 2 max = 2
) )
@CommandPermissions({"worldedit.clipboard.load", "worldedit.schematic.load"}) // TODO: Remove 'clipboard' perm @CommandPermissions({"worldedit.clipboard.load", "worldedit.schematic.load"}) // TODO: Remove 'clipboard' perm
public void load(CommandContext args, LocalSession session, LocalPlayer player, public void load(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = worldEdit.getConfiguration();
String fileName; String fileName;
String formatName; String formatName;
@ -69,8 +77,8 @@ public class SchematicCommands {
formatName = args.getString(0); formatName = args.getString(0);
fileName = args.getString(1); fileName = args.getString(1);
} }
File dir = we.getWorkingDirectoryFile(config.saveDir); File dir = worldEdit.getWorkingDirectoryFile(config.saveDir);
File f = we.getSafeOpenFile(player, dir, fileName, "schematic", "schematic"); File f = worldEdit.getSafeOpenFile(player, dir, fileName, "schematic", "schematic");
if (!f.exists()) { if (!f.exists()) {
player.printError("Schematic " + fileName + " does not exist!"); player.printError("Schematic " + fileName + " does not exist!");
@ -120,10 +128,9 @@ public class SchematicCommands {
max = 2 max = 2
) )
@CommandPermissions({"worldedit.clipboard.save", "worldedit.schematic.save"}) // TODO: Remove 'clipboard' perm @CommandPermissions({"worldedit.clipboard.save", "worldedit.schematic.save"}) // TODO: Remove 'clipboard' perm
public void save(CommandContext args, LocalSession session, LocalPlayer player, public void save(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException, CommandException {
EditSession editSession) throws WorldEditException, CommandException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = worldEdit.getConfiguration();
SchematicFormat format; SchematicFormat format;
if (args.argsLength() == 1) { if (args.argsLength() == 1) {
if (SchematicFormat.getFormats().size() == 1) { if (SchematicFormat.getFormats().size() == 1) {
@ -142,8 +149,8 @@ public class SchematicCommands {
String filename = args.getString(args.argsLength() - 1); String filename = args.getString(args.argsLength() - 1);
File dir = we.getWorkingDirectoryFile(config.saveDir); File dir = worldEdit.getWorkingDirectoryFile(config.saveDir);
File f = we.getSafeSaveFile(player, dir, filename, "schematic", "schematic"); File f = worldEdit.getSafeSaveFile(player, dir, filename, "schematic", "schematic");
if (!dir.exists()) { if (!dir.exists()) {
if (!dir.mkdir()) { if (!dir.mkdir()) {
@ -180,14 +187,13 @@ public class SchematicCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.schematic.delete") @CommandPermissions("worldedit.schematic.delete")
public void delete(CommandContext args, LocalSession session, LocalPlayer player, public void delete(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = worldEdit.getConfiguration();
String filename = args.getString(0); String filename = args.getString(0);
File dir = we.getWorkingDirectoryFile(config.saveDir); File dir = worldEdit.getWorkingDirectoryFile(config.saveDir);
File f = we.getSafeSaveFile(player, dir, filename, "schematic", "schematic"); File f = worldEdit.getSafeSaveFile(player, dir, filename, "schematic", "schematic");
if (!f.exists()) { if (!f.exists()) {
player.printError("Schematic " + filename + " does not exist!"); player.printError("Schematic " + filename + " does not exist!");
@ -207,11 +213,9 @@ public class SchematicCommands {
desc = "List available schematic formats", desc = "List available schematic formats",
max = 0 max = 0
) )
@Console
@CommandPermissions("worldedit.schematic.formats") @CommandPermissions("worldedit.schematic.formats")
public void formats(CommandContext args, LocalSession session, LocalPlayer player, public void formats(Actor actor) throws WorldEditException {
EditSession editSession) throws WorldEditException { actor.print("Available schematic formats (Name: Lookup names)");
player.print("Available schematic formats (Name: Lookup names)");
StringBuilder builder; StringBuilder builder;
boolean first = true; boolean first = true;
for (SchematicFormat format : SchematicFormat.getFormats()) { for (SchematicFormat format : SchematicFormat.getFormats()) {
@ -225,7 +229,7 @@ public class SchematicCommands {
first = false; first = false;
} }
first = true; first = true;
player.print(builder.toString()); actor.print(builder.toString());
} }
} }
@ -238,11 +242,9 @@ public class SchematicCommands {
" -d sorts by date, oldest first\n" + " -d sorts by date, oldest first\n" +
" -n sorts by date, newest first\n" " -n sorts by date, newest first\n"
) )
@Console
@CommandPermissions("worldedit.schematic.list") @CommandPermissions("worldedit.schematic.list")
public void list(CommandContext args, LocalSession session, LocalPlayer player, public void list(Actor actor, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException { File dir = worldEdit.getWorkingDirectoryFile(worldEdit.getConfiguration().saveDir);
File dir = we.getWorkingDirectoryFile(we.getConfiguration().saveDir);
File[] files = dir.listFiles(new FileFilter(){ File[] files = dir.listFiles(new FileFilter(){
@Override @Override
public boolean accept(File file) { public boolean accept(File file) {
@ -273,8 +275,8 @@ public class SchematicCommands {
} }
}); });
player.print("Available schematics (Filename (Format)):"); actor.print("Available schematics (Filename (Format)):");
player.print(listFiles("", files)); actor.print(listFiles("", files));
} }
private String listFiles(String prefix, File[] files) { private String listFiles(String prefix, File[] files) {

View File

@ -19,24 +19,36 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import java.io.File;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging; import com.sk89q.minecraft.util.commands.Logging;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.*; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.entity.Player;
import java.io.File;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.ALL;
/** /**
* Scripting commands. * Commands related to scripting.
*
* @author sk89q
*/ */
public class ScriptingCommands { public class ScriptingCommands {
private final WorldEdit we;
public ScriptingCommands(WorldEdit we) { private final WorldEdit worldEdit;
this.we = we;
/**
* Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/
public ScriptingCommands(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
} }
@Command( @Command(
@ -48,8 +60,7 @@ public class ScriptingCommands {
) )
@CommandPermissions("worldedit.scripting.execute") @CommandPermissions("worldedit.scripting.execute")
@Logging(ALL) @Logging(ALL)
public void execute(CommandContext args, LocalSession session, LocalPlayer player, public void execute(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
String[] scriptArgs = args.getSlice(1); String[] scriptArgs = args.getSlice(1);
String name = args.getString(0); String name = args.getString(0);
@ -61,10 +72,10 @@ public class ScriptingCommands {
session.setLastScript(name); session.setLastScript(name);
File dir = we.getWorkingDirectoryFile(we.getConfiguration().scriptsDir); File dir = worldEdit.getWorkingDirectoryFile(worldEdit.getConfiguration().scriptsDir);
File f = we.getSafeOpenFile(player, dir, name, "js", "js"); File f = worldEdit.getSafeOpenFile(player, dir, name, "js", "js");
we.runScript(player, f, scriptArgs); worldEdit.runScript(player, f, scriptArgs);
} }
@Command( @Command(
@ -76,8 +87,7 @@ public class ScriptingCommands {
) )
@CommandPermissions("worldedit.scripting.execute") @CommandPermissions("worldedit.scripting.execute")
@Logging(ALL) @Logging(ALL)
public void executeLast(CommandContext args, LocalSession session, LocalPlayer player, public void executeLast(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
String lastScript = session.getLastScript(); String lastScript = session.getLastScript();
@ -93,9 +103,9 @@ public class ScriptingCommands {
String[] scriptArgs = args.getSlice(0); String[] scriptArgs = args.getSlice(0);
File dir = we.getWorkingDirectoryFile(we.getConfiguration().scriptsDir); File dir = worldEdit.getWorkingDirectoryFile(worldEdit.getConfiguration().scriptsDir);
File f = we.getSafeOpenFile(player, dir, lastScript, "js", "js"); File f = worldEdit.getSafeOpenFile(player, dir, lastScript, "js", "js");
we.runScript(player, f, scriptArgs); worldEdit.runScript(player, f, scriptArgs);
} }
} }

View File

@ -31,6 +31,7 @@ import com.sk89q.minecraft.util.commands.CommandAlias;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging; import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.util.Countable; import com.sk89q.worldedit.util.Countable;
import com.sk89q.worldedit.CuboidClipboard; import com.sk89q.worldedit.CuboidClipboard;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
@ -76,8 +77,7 @@ public class SelectionCommands {
) )
@Logging(POSITION) @Logging(POSITION)
@CommandPermissions("worldedit.selection.pos") @CommandPermissions("worldedit.selection.pos")
public void pos1(CommandContext args, LocalSession session, LocalPlayer player, public void pos1(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Vector pos; Vector pos;
@ -111,8 +111,7 @@ public class SelectionCommands {
) )
@Logging(POSITION) @Logging(POSITION)
@CommandPermissions("worldedit.selection.pos") @CommandPermissions("worldedit.selection.pos")
public void pos2(CommandContext args, LocalSession session, LocalPlayer player, public void pos2(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Vector pos; Vector pos;
if (args.argsLength() == 1) { if (args.argsLength() == 1) {
@ -146,8 +145,7 @@ public class SelectionCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.selection.hpos") @CommandPermissions("worldedit.selection.hpos")
public void hpos1(CommandContext args, LocalSession session, LocalPlayer player, public void hpos1(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Vector pos = player.getBlockTrace(300); Vector pos = player.getBlockTrace(300);
@ -173,8 +171,7 @@ public class SelectionCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.selection.hpos") @CommandPermissions("worldedit.selection.hpos")
public void hpos2(CommandContext args, LocalSession session, LocalPlayer player, public void hpos2(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Vector pos = player.getBlockTrace(300); Vector pos = player.getBlockTrace(300);
@ -210,8 +207,7 @@ public class SelectionCommands {
) )
@Logging(POSITION) @Logging(POSITION)
@CommandPermissions("worldedit.selection.chunk") @CommandPermissions("worldedit.selection.chunk")
public void chunk(CommandContext args, LocalSession session, LocalPlayer player, public void chunk(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
final Vector min; final Vector min;
final Vector max; final Vector max;
@ -274,8 +270,7 @@ public class SelectionCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.wand") @CommandPermissions("worldedit.wand")
public void wand(CommandContext args, LocalSession session, LocalPlayer player, public void wand(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
player.giveItem(we.getConfiguration().wandItem, 1); player.giveItem(we.getConfiguration().wandItem, 1);
player.print("Left click: select pos #1; Right click: select pos #2"); player.print("Left click: select pos #1; Right click: select pos #2");
@ -289,8 +284,7 @@ public class SelectionCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.wand.toggle") @CommandPermissions("worldedit.wand.toggle")
public void toggleWand(CommandContext args, LocalSession session, LocalPlayer player, public void toggleWand(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
session.setToolControl(!session.isToolControlEnabled()); session.setToolControl(!session.isToolControlEnabled());
@ -310,8 +304,7 @@ public class SelectionCommands {
) )
@Logging(REGION) @Logging(REGION)
@CommandPermissions("worldedit.selection.expand") @CommandPermissions("worldedit.selection.expand")
public void expand(CommandContext args, LocalSession session, LocalPlayer player, public void expand(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
// Special syntax (//expand vert) to expand the selection between // Special syntax (//expand vert) to expand the selection between
// sky and bedrock. // sky and bedrock.
@ -406,8 +399,7 @@ public class SelectionCommands {
) )
@Logging(REGION) @Logging(REGION)
@CommandPermissions("worldedit.selection.contract") @CommandPermissions("worldedit.selection.contract")
public void contract(CommandContext args, LocalSession session, LocalPlayer player, public void contract(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
List<Vector> dirs = new ArrayList<Vector>(); List<Vector> dirs = new ArrayList<Vector>();
int change = args.getInteger(0); int change = args.getInteger(0);
@ -482,8 +474,7 @@ public class SelectionCommands {
) )
@Logging(REGION) @Logging(REGION)
@CommandPermissions("worldedit.selection.shift") @CommandPermissions("worldedit.selection.shift")
public void shift(CommandContext args, LocalSession session, LocalPlayer player, public void shift(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
List<Vector> dirs = new ArrayList<Vector>(); List<Vector> dirs = new ArrayList<Vector>();
int change = args.getInteger(0); int change = args.getInteger(0);
@ -531,8 +522,7 @@ public class SelectionCommands {
) )
@Logging(REGION) @Logging(REGION)
@CommandPermissions("worldedit.selection.outset") @CommandPermissions("worldedit.selection.outset")
public void outset(CommandContext args, LocalSession session, LocalPlayer player, public void outset(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Region region = session.getSelection(player.getWorld()); Region region = session.getSelection(player.getWorld());
region.expand(getChangesForEachDir(args)); region.expand(getChangesForEachDir(args));
session.getRegionSelector(player.getWorld()).learnChanges(); session.getRegionSelector(player.getWorld()).learnChanges();
@ -555,8 +545,7 @@ public class SelectionCommands {
) )
@Logging(REGION) @Logging(REGION)
@CommandPermissions("worldedit.selection.inset") @CommandPermissions("worldedit.selection.inset")
public void inset(CommandContext args, LocalSession session, LocalPlayer player, public void inset(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Region region = session.getSelection(player.getWorld()); Region region = session.getSelection(player.getWorld());
region.contract(getChangesForEachDir(args)); region.contract(getChangesForEachDir(args));
session.getRegionSelector(player.getWorld()).learnChanges(); session.getRegionSelector(player.getWorld()).learnChanges();
@ -592,8 +581,7 @@ public class SelectionCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.selection.size") @CommandPermissions("worldedit.selection.size")
public void size(CommandContext args, LocalSession session, LocalPlayer player, public void size(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
if (args.hasFlag('c')) { if (args.hasFlag('c')) {
CuboidClipboard clipboard = session.getClipboard(); CuboidClipboard clipboard = session.getClipboard();
@ -637,8 +625,7 @@ public class SelectionCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.analysis.count") @CommandPermissions("worldedit.analysis.count")
public void count(CommandContext args, LocalSession session, LocalPlayer player, public void count(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
boolean useData = args.hasFlag('d'); boolean useData = args.hasFlag('d');
if (args.getString(0).contains(":")) { if (args.getString(0).contains(":")) {
@ -668,8 +655,7 @@ public class SelectionCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.analysis.distr") @CommandPermissions("worldedit.analysis.distr")
public void distr(CommandContext args, LocalSession session, LocalPlayer player, public void distr(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int size; int size;
boolean useData = args.hasFlag('d'); boolean useData = args.hasFlag('d');
@ -730,8 +716,7 @@ public class SelectionCommands {
min = 0, min = 0,
max = 1 max = 1
) )
public void select(CommandContext args, LocalSession session, LocalPlayer player, public void select(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
final World world = player.getWorld(); final World world = player.getWorld();
if (args.argsLength() == 0) { if (args.argsLength() == 0) {

View File

@ -21,6 +21,15 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.world.snapshot.InvalidSnapshotException;
import com.sk89q.worldedit.world.snapshot.Snapshot;
import com.sk89q.worldedit.world.storage.MissingWorldException;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.text.DateFormat; import java.text.DateFormat;
@ -28,13 +37,6 @@ import java.text.SimpleDateFormat;
import java.util.Calendar; import java.util.Calendar;
import java.util.List; import java.util.List;
import java.util.logging.Logger; import java.util.logging.Logger;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.world.storage.MissingWorldException;
import com.sk89q.worldedit.world.snapshot.InvalidSnapshotException;
import com.sk89q.worldedit.world.snapshot.Snapshot;
/** /**
* Snapshot commands. * Snapshot commands.
@ -59,8 +61,7 @@ public class SnapshotCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.snapshots.list") @CommandPermissions("worldedit.snapshots.list")
public void list(CommandContext args, LocalSession session, LocalPlayer player, public void list(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
@ -110,8 +111,7 @@ public class SnapshotCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.snapshots.restore") @CommandPermissions("worldedit.snapshots.restore")
public void use(CommandContext args, LocalSession session, LocalPlayer player, public void use(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
@ -154,8 +154,7 @@ public class SnapshotCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.snapshots.restore") @CommandPermissions("worldedit.snapshots.restore")
public void sel(CommandContext args, LocalSession session, LocalPlayer player, public void sel(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
if (config.snapshotRepo == null) { if (config.snapshotRepo == null) {
@ -202,8 +201,7 @@ public class SnapshotCommands {
max = -1 max = -1
) )
@CommandPermissions("worldedit.snapshots.restore") @CommandPermissions("worldedit.snapshots.restore")
public void before(CommandContext args, LocalSession session, LocalPlayer player, public void before(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
@ -242,8 +240,7 @@ public class SnapshotCommands {
max = -1 max = -1
) )
@CommandPermissions("worldedit.snapshots.restore") @CommandPermissions("worldedit.snapshots.restore")
public void after(CommandContext args, LocalSession session, LocalPlayer player, public void after(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();

View File

@ -19,30 +19,25 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.snapshot.InvalidSnapshotException;
import com.sk89q.worldedit.world.snapshot.Snapshot;
import com.sk89q.worldedit.world.snapshot.SnapshotRestore;
import com.sk89q.worldedit.world.storage.ChunkStore;
import com.sk89q.worldedit.world.storage.MissingWorldException;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.logging.Logger; import java.util.logging.Logger;
import com.sk89q.minecraft.util.commands.Command; import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.minecraft.util.commands.NestedCommand;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.world.storage.ChunkStore;
import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.storage.MissingWorldException;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.snapshot.InvalidSnapshotException;
import com.sk89q.worldedit.world.snapshot.Snapshot;
import com.sk89q.worldedit.world.snapshot.SnapshotRestore;
public class SnapshotUtilCommands { public class SnapshotUtilCommands {
@ -54,15 +49,6 @@ public class SnapshotUtilCommands {
this.we = we; this.we = we;
} }
@Command(
aliases = { "snapshot", "snap" },
desc = "Snapshot commands"
)
@NestedCommand(SnapshotCommands.class)
public void snapshot(CommandContext args, LocalSession session, LocalPlayer player,
EditSession editSession) throws WorldEditException {
}
@Command( @Command(
aliases = { "restore", "/restore" }, aliases = { "restore", "/restore" },
usage = "[snapshot]", usage = "[snapshot]",
@ -72,8 +58,7 @@ public class SnapshotUtilCommands {
) )
@Logging(REGION) @Logging(REGION)
@CommandPermissions("worldedit.snapshots.restore") @CommandPermissions("worldedit.snapshots.restore")
public void restore(CommandContext args, LocalSession session, LocalPlayer player, public void restore(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();

View File

@ -22,15 +22,11 @@ package com.sk89q.worldedit.command;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.tool.AreaPickaxe; import com.sk89q.worldedit.command.tool.AreaPickaxe;
import com.sk89q.worldedit.command.tool.RecursivePickaxe; import com.sk89q.worldedit.command.tool.RecursivePickaxe;
import com.sk89q.worldedit.command.tool.SinglePickaxe; import com.sk89q.worldedit.command.tool.SinglePickaxe;
import com.sk89q.worldedit.entity.Player;
public class SuperPickaxeCommands { public class SuperPickaxeCommands {
private final WorldEdit we; private final WorldEdit we;
@ -47,8 +43,7 @@ public class SuperPickaxeCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.superpickaxe") @CommandPermissions("worldedit.superpickaxe")
public void single(CommandContext args, LocalSession session, LocalPlayer player, public void single(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
session.setSuperPickaxe(new SinglePickaxe()); session.setSuperPickaxe(new SinglePickaxe());
session.enableSuperPickAxe(); session.enableSuperPickAxe();
@ -63,8 +58,7 @@ public class SuperPickaxeCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.superpickaxe.area") @CommandPermissions("worldedit.superpickaxe.area")
public void area(CommandContext args, LocalSession session, LocalPlayer player, public void area(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
int range = args.getInteger(0); int range = args.getInteger(0);
@ -87,8 +81,7 @@ public class SuperPickaxeCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.superpickaxe.recursive") @CommandPermissions("worldedit.superpickaxe.recursive")
public void recursive(CommandContext args, LocalSession session, LocalPlayer player, public void recursive(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
double range = args.getDouble(0); double range = args.getDouble(0);

View File

@ -26,6 +26,7 @@ import com.sk89q.minecraft.util.commands.NestedCommand;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.ItemType; import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.command.tool.*; import com.sk89q.worldedit.command.tool.*;
import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator;
@ -44,8 +45,7 @@ public class ToolCommands {
min = 0, min = 0,
max = 0 max = 0
) )
public void none(CommandContext args, LocalSession session, LocalPlayer player, public void none(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
session.setTool(player.getItemInHand(), null); session.setTool(player.getItemInHand(), null);
player.print("Tool unbound from your current item."); player.print("Tool unbound from your current item.");
@ -59,8 +59,7 @@ public class ToolCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.tool.info") @CommandPermissions("worldedit.tool.info")
public void info(CommandContext args, LocalSession session, LocalPlayer player, public void info(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
session.setTool(player.getItemInHand(), new QueryTool()); session.setTool(player.getItemInHand(), new QueryTool());
player.print("Info tool bound to " player.print("Info tool bound to "
@ -76,8 +75,7 @@ public class ToolCommands {
) )
@CommandPermissions("worldedit.tool.tree") @CommandPermissions("worldedit.tool.tree")
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void tree(CommandContext args, LocalSession session, LocalPlayer player, public void tree(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
TreeGenerator.TreeType type = args.argsLength() > 0 ? TreeGenerator.TreeType type = args.argsLength() > 0 ?
type = TreeGenerator.lookup(args.getString(0)) type = TreeGenerator.lookup(args.getString(0))
@ -101,8 +99,7 @@ public class ToolCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.tool.replacer") @CommandPermissions("worldedit.tool.replacer")
public void repl(CommandContext args, LocalSession session, LocalPlayer player, public void repl(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
BaseBlock targetBlock = we.getBlock(player, args.getString(0)); BaseBlock targetBlock = we.getBlock(player, args.getString(0));
session.setTool(player.getItemInHand(), new BlockReplacer(targetBlock)); session.setTool(player.getItemInHand(), new BlockReplacer(targetBlock));
@ -118,8 +115,7 @@ public class ToolCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.tool.data-cycler") @CommandPermissions("worldedit.tool.data-cycler")
public void cycler(CommandContext args, LocalSession session, LocalPlayer player, public void cycler(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
session.setTool(player.getItemInHand(), new BlockDataCyler()); session.setTool(player.getItemInHand(), new BlockDataCyler());
player.print("Block data cycler tool bound to " player.print("Block data cycler tool bound to "
@ -134,8 +130,7 @@ public class ToolCommands {
max = 2 max = 2
) )
@CommandPermissions("worldedit.tool.flood-fill") @CommandPermissions("worldedit.tool.flood-fill")
public void floodFill(CommandContext args, LocalSession session, LocalPlayer player, public void floodFill(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
int range = args.getInteger(1); int range = args.getInteger(1);
@ -151,15 +146,6 @@ public class ToolCommands {
+ ItemType.toHeldName(player.getItemInHand()) + "."); + ItemType.toHeldName(player.getItemInHand()) + ".");
} }
@Command(
aliases = { "brush", "br" },
desc = "Brush tool"
)
@NestedCommand(BrushCommands.class)
public void brush(CommandContext args, LocalSession session, LocalPlayer player,
EditSession editSession) throws WorldEditException {
}
@Command( @Command(
aliases = { "deltree" }, aliases = { "deltree" },
usage = "", usage = "",
@ -168,8 +154,7 @@ public class ToolCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.tool.deltree") @CommandPermissions("worldedit.tool.deltree")
public void deltree(CommandContext args, LocalSession session, LocalPlayer player, public void deltree(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
session.setTool(player.getItemInHand(), new FloatingTreeRemover()); session.setTool(player.getItemInHand(), new FloatingTreeRemover());
player.print("Floating tree remover tool bound to " player.print("Floating tree remover tool bound to "
@ -184,8 +169,7 @@ public class ToolCommands {
max = 0 max = 0
) )
@CommandPermissions("worldedit.tool.farwand") @CommandPermissions("worldedit.tool.farwand")
public void farwand(CommandContext args, LocalSession session, LocalPlayer player, public void farwand(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
session.setTool(player.getItemInHand(), new DistanceWand()); session.setTool(player.getItemInHand(), new DistanceWand());
player.print("Far wand tool bound to " + ItemType.toHeldName(player.getItemInHand()) + "."); player.print("Far wand tool bound to " + ItemType.toHeldName(player.getItemInHand()) + ".");
@ -199,8 +183,7 @@ public class ToolCommands {
max = 2 max = 2
) )
@CommandPermissions("worldedit.tool.lrbuild") @CommandPermissions("worldedit.tool.lrbuild")
public void longrangebuildtool(CommandContext args, LocalSession session, LocalPlayer player, public void longrangebuildtool(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
BaseBlock secondary = we.getBlock(player, args.getString(0)); BaseBlock secondary = we.getBlock(player, args.getString(0));
BaseBlock primary = we.getBlock(player, args.getString(1)); BaseBlock primary = we.getBlock(player, args.getString(1));

View File

@ -22,15 +22,14 @@ package com.sk89q.worldedit.command;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.NestedCommand;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.masks.Mask; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.util.command.parametric.Optional;
/** /**
* Tool commands. * Tool commands.
*
* @author sk89q
*/ */
public class ToolUtilCommands { public class ToolUtilCommands {
private final WorldEdit we; private final WorldEdit we;
@ -47,8 +46,7 @@ public class ToolUtilCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.superpickaxe") @CommandPermissions("worldedit.superpickaxe")
public void togglePickaxe(CommandContext args, LocalSession session, LocalPlayer player, public void togglePickaxe(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
String newState = args.getString(0, null); String newState = args.getString(0, null);
if (session.hasSuperPickAxe()) { if (session.hasSuperPickAxe()) {
@ -70,24 +68,6 @@ public class ToolUtilCommands {
} }
@Command(
aliases = { "superpickaxe", "pickaxe", "sp" },
desc = "Select super pickaxe mode"
)
@NestedCommand(SuperPickaxeCommands.class)
public void pickaxe(CommandContext args, LocalSession session, LocalPlayer player,
EditSession editSession) throws WorldEditException {
}
@Command(
aliases = {"tool"},
desc = "Select a tool to bind"
)
@NestedCommand(ToolCommands.class)
public void tool(CommandContext args, LocalSession session, LocalPlayer player,
EditSession editSession) throws WorldEditException {
}
@Command( @Command(
aliases = { "mask" }, aliases = { "mask" },
usage = "[mask]", usage = "[mask]",
@ -96,13 +76,11 @@ public class ToolUtilCommands {
max = -1 max = -1
) )
@CommandPermissions("worldedit.brush.options.mask") @CommandPermissions("worldedit.brush.options.mask")
public void mask(CommandContext args, LocalSession session, LocalPlayer player, public void mask(Player player, LocalSession session, EditSession editSession, @Optional Mask mask) throws WorldEditException {
EditSession editSession) throws WorldEditException { if (mask == null) {
if (args.argsLength() == 0) {
session.getBrushTool(player.getItemInHand()).setMask(null); session.getBrushTool(player.getItemInHand()).setMask(null);
player.print("Brush mask disabled."); player.print("Brush mask disabled.");
} else { } else {
Mask mask = we.getBlockMask(player, session, args.getJoinedStrings(0));
session.getBrushTool(player.getItemInHand()).setMask(mask); session.getBrushTool(player.getItemInHand()).setMask(mask);
player.print("Brush mask set."); player.print("Brush mask set.");
} }
@ -116,9 +94,7 @@ public class ToolUtilCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.brush.options.material") @CommandPermissions("worldedit.brush.options.material")
public void material(CommandContext args, LocalSession session, LocalPlayer player, public void material(Player player, LocalSession session, EditSession editSession, Pattern pattern) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Pattern pattern = we.getBlockPattern(player, args.getString(0));
session.getBrushTool(player.getItemInHand()).setFill(pattern); session.getBrushTool(player.getItemInHand()).setFill(pattern);
player.print("Brush material set."); player.print("Brush material set.");
} }
@ -131,8 +107,7 @@ public class ToolUtilCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.brush.options.range") @CommandPermissions("worldedit.brush.options.range")
public void range(CommandContext args, LocalSession session, LocalPlayer player, public void range(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int range = args.getInteger(0); int range = args.getInteger(0);
session.getBrushTool(player.getItemInHand()).setRange(range); session.getBrushTool(player.getItemInHand()).setRange(range);
player.print("Brush range set."); player.print("Brush range set.");
@ -146,8 +121,7 @@ public class ToolUtilCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.brush.options.size") @CommandPermissions("worldedit.brush.options.size")
public void size(CommandContext args, LocalSession session, LocalPlayer player, public void size(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int radius = args.getInteger(0); int radius = args.getInteger(0);
we.checkMaxBrushRadius(radius); we.checkMaxBrushRadius(radius);

View File

@ -23,10 +23,16 @@ import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.LocalWorld.KillFlags; import com.sk89q.worldedit.LocalWorld.KillFlags;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.patterns.SingleBlockPattern; import com.sk89q.worldedit.patterns.SingleBlockPattern;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.command.CommandMapping;
import com.sk89q.worldedit.util.command.Description;
import com.sk89q.worldedit.util.command.Dispatcher;
import com.sk89q.worldedit.util.command.parametric.Optional;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import java.util.Comparator; import java.util.Comparator;
@ -57,8 +63,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.fill") @CommandPermissions("worldedit.fill")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void fill(CommandContext args, LocalSession session, LocalPlayer player, public void fill(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Pattern pattern = we.getBlockPattern(player, args.getString(0)); Pattern pattern = we.getBlockPattern(player, args.getString(0));
double radius = Math.max(1, args.getDouble(1)); double radius = Math.max(1, args.getDouble(1));
@ -86,8 +91,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.fill.recursive") @CommandPermissions("worldedit.fill.recursive")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void fillr(CommandContext args, LocalSession session, LocalPlayer player, public void fillr(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
Pattern pattern = we.getBlockPattern(player, args.getString(0)); Pattern pattern = we.getBlockPattern(player, args.getString(0));
double radius = Math.max(1, args.getDouble(1)); double radius = Math.max(1, args.getDouble(1));
@ -115,8 +119,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.drain") @CommandPermissions("worldedit.drain")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void drain(CommandContext args, LocalSession session, LocalPlayer player, public void drain(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
double radius = Math.max(0, args.getDouble(0)); double radius = Math.max(0, args.getDouble(0));
we.checkMaxRadius(radius); we.checkMaxRadius(radius);
@ -134,8 +137,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.fixlava") @CommandPermissions("worldedit.fixlava")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void fixLava(CommandContext args, LocalSession session, LocalPlayer player, public void fixLava(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
double radius = Math.max(0, args.getDouble(0)); double radius = Math.max(0, args.getDouble(0));
we.checkMaxRadius(radius); we.checkMaxRadius(radius);
@ -153,8 +155,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.fixwater") @CommandPermissions("worldedit.fixwater")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void fixWater(CommandContext args, LocalSession session, LocalPlayer player, public void fixWater(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
double radius = Math.max(0, args.getDouble(0)); double radius = Math.max(0, args.getDouble(0));
we.checkMaxRadius(radius); we.checkMaxRadius(radius);
@ -172,8 +173,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.removeabove") @CommandPermissions("worldedit.removeabove")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void removeAbove(CommandContext args, LocalSession session, LocalPlayer player, public void removeAbove(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1; int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
we.checkMaxRadius(size); we.checkMaxRadius(size);
@ -194,8 +194,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.removebelow") @CommandPermissions("worldedit.removebelow")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void removeBelow(CommandContext args, LocalSession session, LocalPlayer player, public void removeBelow(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1; int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
we.checkMaxRadius(size); we.checkMaxRadius(size);
@ -215,8 +214,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.removenear") @CommandPermissions("worldedit.removenear")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void removeNear(CommandContext args, LocalSession session, LocalPlayer player, public void removeNear(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
BaseBlock block = we.getBlock(player, args.getString(0), true); BaseBlock block = we.getBlock(player, args.getString(0), true);
int size = Math.max(1, args.getInteger(1, 50)); int size = Math.max(1, args.getInteger(1, 50));
@ -236,8 +234,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.replacenear") @CommandPermissions("worldedit.replacenear")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void replaceNear(CommandContext args, LocalSession session, LocalPlayer player, public void replaceNear(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
int size = Math.max(1, args.getInteger(0)); int size = Math.max(1, args.getInteger(0));
int affected; int affected;
@ -273,8 +270,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.snow") @CommandPermissions("worldedit.snow")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void snow(CommandContext args, LocalSession session, LocalPlayer player, public void snow(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10; double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;
@ -291,8 +287,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.thaw") @CommandPermissions("worldedit.thaw")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void thaw(CommandContext args, LocalSession session, LocalPlayer player, public void thaw(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10; double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;
@ -310,8 +305,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.green") @CommandPermissions("worldedit.green")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void green(CommandContext args, LocalSession session, LocalPlayer player, public void green(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
final double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10; final double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;
final boolean onlyNormalDirt = !args.hasFlag('f'); final boolean onlyNormalDirt = !args.hasFlag('f');
@ -329,8 +323,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.extinguish") @CommandPermissions("worldedit.extinguish")
@Logging(PLACEMENT) @Logging(PLACEMENT)
public void extinguish(CommandContext args, LocalSession session, LocalPlayer player, public void extinguish(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
@ -364,9 +357,7 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.butcher") @CommandPermissions("worldedit.butcher")
@Logging(PLACEMENT) @Logging(PLACEMENT)
@Console public void butcher(Actor actor, @Optional Player player, @Optional LocalSession session, CommandContext args) throws WorldEditException {
public void butcher(CommandContext args, LocalSession session, LocalPlayer player,
EditSession editSession) throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
@ -385,7 +376,7 @@ public class UtilityCommands {
} }
} }
FlagContainer flags = new FlagContainer(player); FlagContainer flags = new FlagContainer(actor);
flags.or(KillFlags.FRIENDLY , args.hasFlag('f')); // No permission check here. Flags will instead be filtered by the subsequent calls. flags.or(KillFlags.FRIENDLY , args.hasFlag('f')); // No permission check here. Flags will instead be filtered by the subsequent calls.
flags.or(KillFlags.PETS , args.hasFlag('p'), "worldedit.butcher.pets"); flags.or(KillFlags.PETS , args.hasFlag('p'), "worldedit.butcher.pets");
flags.or(KillFlags.NPCS , args.hasFlag('n'), "worldedit.butcher.npcs"); flags.or(KillFlags.NPCS , args.hasFlag('n'), "worldedit.butcher.npcs");
@ -397,7 +388,7 @@ public class UtilityCommands {
// If you add flags here, please add them to com.sk89q.worldedit.commands.BrushCommands.butcherBrush() as well // If you add flags here, please add them to com.sk89q.worldedit.commands.BrushCommands.butcherBrush() as well
int killed; int killed;
if (player.isPlayer()) { if (player != null) {
killed = player.getWorld().killMobs(session.getPlacementPosition(player), radius, flags.flags); killed = player.getWorld().killMobs(session.getPlacementPosition(player), radius, flags.flags);
} else { } else {
killed = 0; killed = 0;
@ -407,16 +398,16 @@ public class UtilityCommands {
} }
if (radius < 0) { if (radius < 0) {
player.print("Killed " + killed + " mobs."); actor.print("Killed " + killed + " mobs.");
} else { } else {
player.print("Killed " + killed + " mobs in a radius of " + radius + "."); actor.print("Killed " + killed + " mobs in a radius of " + radius + ".");
} }
} }
public static class FlagContainer { public static class FlagContainer {
private final LocalPlayer player; private final Actor player;
public int flags = 0; public int flags = 0;
public FlagContainer(LocalPlayer player) { public FlagContainer(Actor player) {
this.player = player; this.player = player;
} }
@ -442,15 +433,13 @@ public class UtilityCommands {
) )
@CommandPermissions("worldedit.remove") @CommandPermissions("worldedit.remove")
@Logging(PLACEMENT) @Logging(PLACEMENT)
@Console public void remove(Actor actor, @Optional Player player, @Optional LocalSession session, CommandContext args) throws WorldEditException {
public void remove(CommandContext args, LocalSession session, LocalPlayer player,
EditSession editSession) throws WorldEditException {
String typeStr = args.getString(0); String typeStr = args.getString(0);
int radius = args.getInteger(1); int radius = args.getInteger(1);
if (radius < -1) { if (radius < -1) {
player.printError("Use -1 to remove all entities in loaded chunks"); actor.printError("Use -1 to remove all entities in loaded chunks");
return; return;
} }
@ -480,12 +469,12 @@ public class UtilityCommands {
} else if (typeStr.matches("xp")) { } else if (typeStr.matches("xp")) {
type = EntityType.XP_ORBS; type = EntityType.XP_ORBS;
} else { } else {
player.printError("Acceptable types: projectiles, items, paintings, itemframes, boats, minecarts, tnt, xp, or all"); actor.printError("Acceptable types: projectiles, items, paintings, itemframes, boats, minecarts, tnt, xp, or all");
return; return;
} }
int removed = 0; int removed = 0;
if (player.isPlayer()) { if (player != null) {
Vector origin = session.getPlacementPosition(player); Vector origin = session.getPlacementPosition(player);
removed = player.getWorld().removeEntities(type, origin, radius); removed = player.getWorld().removeEntities(type, origin, radius);
} else { } else {
@ -499,20 +488,17 @@ public class UtilityCommands {
@Command( @Command(
aliases = { "/help" }, aliases = { "/help" },
usage = "[<command>]", usage = "[<command>]",
desc = "Displays help for the given command or lists all commands.", desc = "Displays help for WorldEdit commands",
min = 0, min = 0,
max = -1 max = -1
) )
@Console
@CommandPermissions("worldedit.help") @CommandPermissions("worldedit.help")
public void help(CommandContext args, LocalSession session, LocalPlayer player, public void help(Actor actor, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException { help(args, we, actor);
help(args, we, session, player, editSession);
} }
public static void help(CommandContext args, WorldEdit we, LocalSession session, LocalPlayer player, EditSession editSession) { public static void help(CommandContext args, WorldEdit we, Actor actor) {
final CommandsManager<LocalPlayer> commandsManager = we.getCommandsManager(); final Dispatcher dispatcher = we.getPlatformManager().getCommandManager().getDispatcher();
if (args.argsLength() == 0) { if (args.argsLength() == 0) {
SortedSet<String> commands = new TreeSet<String>(new Comparator<String>() { SortedSet<String> commands = new TreeSet<String>(new Comparator<String>() {
@ -525,7 +511,7 @@ public class UtilityCommands {
return ret; return ret;
} }
}); });
commands.addAll(commandsManager.getCommands().keySet()); commands.addAll(dispatcher.getPrimaryAliases());
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
boolean first = true; boolean first = true;
@ -539,19 +525,31 @@ public class UtilityCommands {
first = false; first = false;
} }
player.print(sb.toString()); actor.print(sb.toString());
return; return;
} }
String command = args.getJoinedStrings(0).toLowerCase().replaceAll("/", ""); String command = args.getJoinedStrings(0).toLowerCase().replaceAll("^/", "");
CommandMapping mapping = dispatcher.get(command);
String helpMessage = commandsManager.getHelpMessages().get(command); if (mapping == null) {
if (helpMessage == null) { actor.printError("Unknown command '" + command + "'.");
player.printError("Unknown command '" + command + "'.");
return; return;
} }
player.print(helpMessage); Description description = mapping.getDescription();
if (description.getUsage() != null) {
actor.printDebug("Usage: " + description.getUsage());
}
if (description.getHelp() != null) {
actor.print(description.getHelp());
} else if (description.getShortDescription() != null) {
actor.print(description.getShortDescription());
} else {
actor.print("No further help is available.");
}
} }
} }

View File

@ -22,8 +22,10 @@ package com.sk89q.worldedit.command;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Console;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extension.platform.PlatformManager; import com.sk89q.worldedit.extension.platform.PlatformManager;
@ -48,55 +50,45 @@ public class WorldEditCommands {
min = 0, min = 0,
max = 0 max = 0
) )
@Console public void version(Actor actor) throws WorldEditException {
public void version(CommandContext args, LocalSession session, LocalPlayer player, actor.print("WorldEdit version " + WorldEdit.getVersion());
EditSession editSession) throws WorldEditException { actor.print("https://github.com/sk89q/worldedit/");
player.print("WorldEdit version " + WorldEdit.getVersion());
player.print("https://github.com/sk89q/worldedit/");
PlatformManager pm = we.getPlatformManager(); PlatformManager pm = we.getPlatformManager();
Platform primary = pm.getPrimaryPlatform();
player.printDebug(""); actor.printDebug("----------- Platforms -----------");
player.printDebug("Platforms:");
for (Platform platform : pm.getPlatforms()) { for (Platform platform : pm.getPlatforms()) {
String prefix = ""; actor.printDebug(String.format("* %s (%s)", platform.getPlatformName(), platform.getPlatformVersion()));
}
if (primary != null && primary.equals(platform)) { actor.printDebug("----------- Capabilities -----------");
prefix = "[PRIMARY] "; for (Capability capability : Capability.values()) {
} Platform platform = pm.queryCapability(capability);
actor.printDebug(String.format("%s: %s", capability.name(), platform != null ? platform.getPlatformName() : "NONE"));
player.printDebug(String.format("- %s%s v%s (WE v%s)",
prefix, platform.getPlatformName(), platform.getPlatformVersion(), platform.getVersion()));
} }
} }
@Command( @Command(
aliases = { "reload" }, aliases = { "reload" },
usage = "", usage = "",
desc = "Reload WorldEdit", desc = "Reload configuration",
min = 0, min = 0,
max = 0 max = 0
) )
@CommandPermissions("worldedit.reload") @CommandPermissions("worldedit.reload")
@Console public void reload(Actor actor) throws WorldEditException {
public void reload(CommandContext args, LocalSession session, LocalPlayer player,
EditSession editSession) throws WorldEditException {
we.getServer().reload(); we.getServer().reload();
player.print("Configuration reloaded!"); actor.print("Configuration reloaded!");
} }
@Command( @Command(
aliases = { "cui" }, aliases = { "cui" },
usage = "", usage = "",
desc = "Complete CUI handshake", desc = "Complete CUI handshake (internal usage)",
min = 0, min = 0,
max = 0 max = 0
) )
public void cui(CommandContext args, LocalSession session, LocalPlayer player, public void cui(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
EditSession editSession) throws WorldEditException {
session.setCUISupport(true); session.setCUISupport(true);
session.dispatchCUISetup(player); session.dispatchCUISetup(player);
} }
@ -104,13 +96,11 @@ public class WorldEditCommands {
@Command( @Command(
aliases = { "tz" }, aliases = { "tz" },
usage = "[timezone]", usage = "[timezone]",
desc = "Set your timezone", desc = "Set your timezone for snapshots",
min = 1, min = 1,
max = 1 max = 1
) )
@Console public void tz(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
public void tz(CommandContext args, LocalSession session, LocalPlayer player,
EditSession editSession) throws WorldEditException {
TimeZone tz = TimeZone.getTimeZone(args.getString(0)); TimeZone tz = TimeZone.getTimeZone(args.getString(0));
session.setTimezone(tz); session.setTimezone(tz);
player.print("Timezone set for this session to: " + tz.getDisplayName()); player.print("Timezone set for this session to: " + tz.getDisplayName());
@ -121,15 +111,12 @@ public class WorldEditCommands {
@Command( @Command(
aliases = { "help" }, aliases = { "help" },
usage = "[<command>]", usage = "[<command>]",
desc = "Displays help for the given command or lists all commands.", desc = "Displays help for WorldEdit commands",
min = 0, min = 0,
max = -1 max = -1
) )
@CommandPermissions("worldedit.help") @CommandPermissions("worldedit.help")
@Console public void help(Actor actor, CommandContext args) throws WorldEditException {
public void help(CommandContext args, LocalSession session, LocalPlayer player, UtilityCommands.help(args, we, actor);
EditSession editSession) throws WorldEditException {
UtilityCommands.help(args, we, session, player, editSession);
} }
} }

View File

@ -22,13 +22,15 @@ package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
/** /**
* A super pickaxe mode that will remove blocks in an area. * A super pickaxe mode that will remove blocks in an area.
*
* @author sk89q
*/ */
public class AreaPickaxe implements BlockTool { public class AreaPickaxe implements BlockTool {
private static final BaseBlock air = new BaseBlock(0); private static final BaseBlock air = new BaseBlock(0);
private int range; private int range;
@ -36,17 +38,17 @@ public class AreaPickaxe implements BlockTool {
this.range = range; this.range = range;
} }
public boolean canUse(LocalPlayer player) { @Override
public boolean canUse(Actor player) {
return player.hasPermission("worldedit.superpickaxe.area"); return player.hasPermission("worldedit.superpickaxe.area");
} }
public boolean actPrimary(ServerInterface server, LocalConfiguration config, @Override
LocalPlayer player, LocalSession session, WorldVector clicked) { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) {
LocalWorld world = clicked.getWorld();
int ox = clicked.getBlockX(); int ox = clicked.getBlockX();
int oy = clicked.getBlockY(); int oy = clicked.getBlockY();
int oz = clicked.getBlockZ(); int oz = clicked.getBlockZ();
int initialType = world.getBlockType(clicked); int initialType = clicked.getWorld().getBlockType(clicked.toVector());
if (initialType == 0) { if (initialType == 0) {
return true; return true;
@ -68,7 +70,7 @@ public class AreaPickaxe implements BlockTool {
continue; continue;
} }
world.queueBlockBreakEffect(server, pos, initialType, clicked.distanceSq(pos)); clicked.getWorld().queueBlockBreakEffect(server, pos, initialType, clicked.toVector().distanceSq(pos));
editSession.setBlock(pos, air); editSession.setBlock(pos, air);
} }
@ -83,4 +85,5 @@ public class AreaPickaxe implements BlockTool {
return true; return true;
} }
} }

View File

@ -19,29 +19,34 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
/** /**
* A mode that cycles the data values of supported blocks. * A mode that cycles the data values of supported blocks.
*
* @author sk89q
*/ */
public class BlockDataCyler implements DoubleActionBlockTool { public class BlockDataCyler implements DoubleActionBlockTool {
public boolean canUse(LocalPlayer player) { @Override
public boolean canUse(Actor player) {
return player.hasPermission("worldedit.tool.data-cycler"); return player.hasPermission("worldedit.tool.data-cycler");
} }
private boolean handleCycle(ServerInterface server, LocalConfiguration config, private boolean handleCycle(Platform server, LocalConfiguration config,
LocalPlayer player, LocalSession session, WorldVector clicked, boolean forward) { Player player, LocalSession session, Location clicked, boolean forward) {
LocalWorld world = clicked.getWorld(); World world = clicked.getWorld();
int type = world.getBlockType(clicked); int type = world.getBlockType(clicked.toVector());
int data = world.getBlockData(clicked); int data = world.getBlockData(clicked.toVector());
if (config.allowedDataCycleBlocks.size() > 0 if (!config.allowedDataCycleBlocks.isEmpty()
&& !player.hasPermission("worldedit.override.data-cycler") && !player.hasPermission("worldedit.override.data-cycler")
&& !config.allowedDataCycleBlocks.contains(type)) { && !config.allowedDataCycleBlocks.contains(type)) {
player.printError("You are not permitted to cycle the data value of that block."); player.printError("You are not permitted to cycle the data value of that block.");
@ -54,20 +59,19 @@ public class BlockDataCyler implements DoubleActionBlockTool {
if (data < 0) { if (data < 0) {
player.printError("That block's data cannot be cycled!"); player.printError("That block's data cannot be cycled!");
} else { } else {
world.setBlockData(clicked, data); world.setBlockData(clicked.toVector(), data);
} }
return true; return true;
} }
public boolean actPrimary(ServerInterface server, LocalConfiguration config, @Override
LocalPlayer player, LocalSession session, WorldVector clicked) { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked) {
return handleCycle(server, config, player, session, clicked, true); return handleCycle(server, config, player, session, clicked, true);
} }
public boolean actSecondary(ServerInterface server, @Override
LocalConfiguration config, LocalPlayer player, public boolean actSecondary(Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked) {
LocalSession session, WorldVector clicked) {
return handleCycle(server, config, player, session, clicked, false); return handleCycle(server, config, player, session, clicked, false);
} }

View File

@ -20,37 +20,40 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockType; import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.world.World;
/** /**
* A mode that replaces one block. * A mode that replaces one block.
*
* @author sk89q
*/ */
public class BlockReplacer implements DoubleActionBlockTool { public class BlockReplacer implements DoubleActionBlockTool {
private BaseBlock targetBlock; private BaseBlock targetBlock;
public BlockReplacer(BaseBlock targetBlock) { public BlockReplacer(BaseBlock targetBlock) {
this.targetBlock = targetBlock; this.targetBlock = targetBlock;
} }
public boolean canUse(LocalPlayer player) { @Override
public boolean canUse(Actor player) {
return player.hasPermission("worldedit.tool.replacer"); return player.hasPermission("worldedit.tool.replacer");
} }
public boolean actPrimary(ServerInterface server, LocalConfiguration config, @Override
LocalPlayer player, LocalSession session, WorldVector clicked) { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) {
BlockBag bag = session.getBlockBag(player);
BlockBag bag = session.getBlockBag(player); World world = clicked.getWorld();
LocalWorld world = clicked.getWorld();
EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(world, -1, bag, player); EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(world, -1, bag, player);
try { try {
editSession.setBlock(clicked, targetBlock); editSession.setBlock(clicked.toVector(), targetBlock);
} catch (MaxChangedBlocksException e) { } catch (MaxChangedBlocksException ignored) {
} finally { } finally {
if (bag != null) { if (bag != null) {
bag.flushChanges(); bag.flushChanges();
@ -61,13 +64,12 @@ public class BlockReplacer implements DoubleActionBlockTool {
return true; return true;
} }
public boolean actSecondary(ServerInterface server,
LocalConfiguration config, LocalPlayer player,
LocalSession session, WorldVector clicked) {
LocalWorld world = clicked.getWorld(); @Override
public boolean actSecondary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) {
World world = clicked.getWorld();
EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(world, -1, player); EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(world, -1, player);
targetBlock = (editSession).getBlock(clicked); targetBlock = (editSession).getBlock(clicked.toVector());
BlockType type = BlockType.fromID(targetBlock.getType()); BlockType type = BlockType.fromID(targetBlock.getType());
if (type != null) { if (type != null) {

View File

@ -19,25 +19,13 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.util.Location;
/**
* Represents a tool that uses a block..
*
* @author sk89q
*/
public interface BlockTool extends Tool { public interface BlockTool extends Tool {
/**
* Perform the action. Should return true to deny the default public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked);
* action.
*
* @param server
* @param config
* @param player
* @param session
* @param clicked
* @return true to deny
*/
public boolean actPrimary(ServerInterface server, LocalConfiguration config,
LocalPlayer player, LocalSession session, WorldVector clicked);
} }

View File

@ -20,28 +20,30 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.masks.CombinedMask;
import com.sk89q.worldedit.masks.Mask;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.patterns.SingleBlockPattern;
import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.command.tool.brush.Brush;
import com.sk89q.worldedit.command.tool.brush.SphereBrush; import com.sk89q.worldedit.command.tool.brush.SphereBrush;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.mask.MaskIntersection;
import com.sk89q.worldedit.function.pattern.BlockPattern;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.session.request.Request;
/** /**
* Builds a shape at the place being looked at. * Builds a shape at the place being looked at.
*
* @author sk89q
*/ */
public class BrushTool implements TraceTool { public class BrushTool implements TraceTool {
protected static int MAX_RANGE = 500; protected static int MAX_RANGE = 500;
protected int range = -1; protected int range = -1;
private Mask mask = null; private Mask mask = null;
private Brush brush = new SphereBrush(); private Brush brush = new SphereBrush();
private Pattern material = new SingleBlockPattern(new BaseBlock(BlockID.COBBLESTONE)); private Pattern material = new BlockPattern(new BaseBlock(BlockID.COBBLESTONE));
private double size = 1; private double size = 1;
private String permission; private String permission;
@ -54,14 +56,8 @@ public class BrushTool implements TraceTool {
this.permission = permission; this.permission = permission;
} }
/** @Override
* Checks to see if the player can still be using this tool (considering public boolean canUse(Actor player) {
* permissions and such).
*
* @param player
* @return
*/
public boolean canUse(LocalPlayer player) {
return player.hasPermission(permission); return player.hasPermission(permission);
} }
@ -151,22 +147,14 @@ public class BrushTool implements TraceTool {
/** /**
* Set the set brush range. * Set the set brush range.
* *
* @param size * @param range
*/ */
public void setRange(int range) { public void setRange(int range) {
this.range = range; this.range = range;
} }
/** @Override
* Perform the action. Should return true to deny the default public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session) {
* action.
*
* @param player
* @param session
* @return true to deny
*/
public boolean actPrimary(ServerInterface server, LocalConfiguration config,
LocalPlayer player, LocalSession session) {
WorldVector target = null; WorldVector target = null;
target = player.getBlockTrace(getRange(), true); target = player.getBlockTrace(getRange(), true);
@ -180,14 +168,14 @@ public class BrushTool implements TraceTool {
EditSession editSession = session.createEditSession(player); EditSession editSession = session.createEditSession(player);
Request.request().setEditSession(editSession); Request.request().setEditSession(editSession);
if (mask != null) { if (mask != null) {
mask.prepare(session, player, target);
Mask existingMask = editSession.getMask(); Mask existingMask = editSession.getMask();
if (existingMask == null) { if (existingMask == null) {
editSession.setMask(mask); editSession.setMask(mask);
} else if (existingMask instanceof CombinedMask) { } else if (existingMask instanceof MaskIntersection) {
((CombinedMask) existingMask).add(mask); ((MaskIntersection) existingMask).add(mask);
} else { } else {
CombinedMask newMask = new CombinedMask(existingMask); MaskIntersection newMask = new MaskIntersection(existingMask);
newMask.add(mask); newMask.add(mask);
editSession.setMask(newMask); editSession.setMask(newMask);
} }

View File

@ -20,12 +20,13 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.regions.RegionSelector;
/** /**
* A wand that can be used at a distance. * A wand that can be used at a distance.
*
* @author wizjany
*/ */
public class DistanceWand extends BrushTool implements DoubleActionTraceTool { public class DistanceWand extends BrushTool implements DoubleActionTraceTool {
@ -34,12 +35,12 @@ public class DistanceWand extends BrushTool implements DoubleActionTraceTool {
} }
@Override @Override
public boolean canUse(LocalPlayer player) { public boolean canUse(Actor player) {
return player.hasPermission("worldedit.wand"); return player.hasPermission("worldedit.wand");
} }
public boolean actSecondary(ServerInterface server, LocalConfiguration config, @Override
LocalPlayer player, LocalSession session) { public boolean actSecondary(Platform server, LocalConfiguration config, Player player, LocalSession session) {
if (session.isToolControlEnabled() && player.hasPermission("worldedit.selection.pos")) { if (session.isToolControlEnabled() && player.hasPermission("worldedit.selection.pos")) {
WorldVector target = getTarget(player); WorldVector target = getTarget(player);
if (target == null) return true; if (target == null) return true;
@ -56,8 +57,7 @@ public class DistanceWand extends BrushTool implements DoubleActionTraceTool {
} }
@Override @Override
public boolean actPrimary(ServerInterface server, LocalConfiguration config, public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session) {
LocalPlayer player, LocalSession session) {
if (session.isToolControlEnabled() && player.hasPermission("worldedit.selection.pos")) { if (session.isToolControlEnabled() && player.hasPermission("worldedit.selection.pos")) {
WorldVector target = getTarget(player); WorldVector target = getTarget(player);
if (target == null) return true; if (target == null) return true;
@ -72,7 +72,7 @@ public class DistanceWand extends BrushTool implements DoubleActionTraceTool {
return false; return false;
} }
public WorldVector getTarget(LocalPlayer player) { public WorldVector getTarget(Player player) {
WorldVector target = null; WorldVector target = null;
if (this.range > -1) { if (this.range > -1) {
target = player.getBlockTrace(getRange(), true); target = player.getBlockTrace(getRange(), true);

View File

@ -20,28 +20,16 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.ServerInterface; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.WorldVector; import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.util.Location;
/** /**
* Represents a block tool that also has a secondary/primary function. * Represents a block tool that also has a secondary/primary function.
*
* @author sk89q
*/ */
public interface DoubleActionBlockTool extends BlockTool { public interface DoubleActionBlockTool extends BlockTool {
/**
* Perform the secondary action. Should return true to deny the default public boolean actSecondary(Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked);
* action.
*
* @param server
* @param config
* @param player
* @param session
* @param clicked
* @return true to deny
*/
public boolean actSecondary(ServerInterface server, LocalConfiguration config,
LocalPlayer player, LocalSession session, WorldVector clicked);
} }

View File

@ -20,24 +20,15 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.ServerInterface; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Platform;
/** /**
* Represents a trace tool that also has a secondary/primary function. * Represents a trace tool that also has a secondary/primary function.
*/ */
public interface DoubleActionTraceTool extends TraceTool { public interface DoubleActionTraceTool extends TraceTool {
/**
* Perform the secondary action. Should return true to deny the default public boolean actSecondary(Platform server, LocalConfiguration config, Player player, LocalSession session);
* action.
*
* @param server
* @param config
* @param player
* @param session
* @return true to deny
*/
public boolean actSecondary(ServerInterface server, LocalConfiguration config,
LocalPlayer player, LocalSession session);
} }

View File

@ -19,18 +19,22 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
/** /**
* A pickaxe mode that removes floating treetops (logs and leaves not connected * A pickaxe mode that removes floating treetops (logs and leaves not connected
* to anything else) * to anything else)
*
* @author Moo0
*/ */
public class FloatingTreeRemover implements BlockTool { public class FloatingTreeRemover implements BlockTool {
private static final BaseBlock AIR = new BaseBlock(BlockID.AIR); private static final BaseBlock AIR = new BaseBlock(BlockID.AIR);
@ -40,16 +44,18 @@ public class FloatingTreeRemover implements BlockTool {
rangeSq = 100*100; rangeSq = 100*100;
} }
public boolean canUse(LocalPlayer player) { @Override
public boolean canUse(Actor player) {
return player.hasPermission("worldedit.tool.deltree"); return player.hasPermission("worldedit.tool.deltree");
} }
public boolean actPrimary(ServerInterface server, LocalConfiguration config, @Override
LocalPlayer player, LocalSession session, WorldVector clicked) { public boolean actPrimary(Platform server, LocalConfiguration config,
Player player, LocalSession session, Location clicked) {
final LocalWorld world = clicked.getWorld(); final World world = clicked.getWorld();
switch (world.getBlockType(clicked)) { switch (world.getBlockType(clicked.toVector())) {
case BlockID.LOG: case BlockID.LOG:
case BlockID.LOG2: case BlockID.LOG2:
case BlockID.LEAVES: case BlockID.LEAVES:
@ -67,7 +73,7 @@ public class FloatingTreeRemover implements BlockTool {
final EditSession editSession = session.createEditSession(player); final EditSession editSession = session.createEditSession(player);
try { try {
final Set<Vector> blockSet = bfs(world, clicked); final Set<Vector> blockSet = bfs(world, clicked.toVector());
if (blockSet == null) { if (blockSet == null) {
player.printError("That's not a floating tree."); player.printError("That's not a floating tree.");
return true; return true;
@ -111,7 +117,7 @@ public class FloatingTreeRemover implements BlockTool {
* @param origin any point contained in the floating tree * @param origin any point contained in the floating tree
* @return a set containing all blocks in the tree/shroom or null if this is not a floating tree/shroom. * @return a set containing all blocks in the tree/shroom or null if this is not a floating tree/shroom.
*/ */
private Set<Vector> bfs(LocalWorld world, Vector origin) throws MaxChangedBlocksException { private Set<Vector> bfs(World world, Vector origin) throws MaxChangedBlocksException {
final Set<Vector> visited = new HashSet<Vector>(); final Set<Vector> visited = new HashSet<Vector>();
final LinkedList<Vector> queue = new LinkedList<Vector>(); final LinkedList<Vector> queue = new LinkedList<Vector>();

View File

@ -19,18 +19,23 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import java.util.HashSet;
import java.util.Set;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import java.util.HashSet;
import java.util.Set;
/** /**
* A tool that flood fills blocks. * A tool that flood fills blocks.
*
* @author sk89q
*/ */
public class FloodFillTool implements BlockTool { public class FloodFillTool implements BlockTool {
private int range; private int range;
private Pattern pattern; private Pattern pattern;
@ -39,15 +44,16 @@ public class FloodFillTool implements BlockTool {
this.pattern = pattern; this.pattern = pattern;
} }
public boolean canUse(LocalPlayer player) { @Override
public boolean canUse(Actor player) {
return player.hasPermission("worldedit.tool.flood-fill"); return player.hasPermission("worldedit.tool.flood-fill");
} }
public boolean actPrimary(ServerInterface server, LocalConfiguration config, @Override
LocalPlayer player, LocalSession session, WorldVector clicked) { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked) {
LocalWorld world = clicked.getWorld(); World world = clicked.getWorld();
int initialType = world.getBlockType(clicked); int initialType = world.getBlockType(clicked.toVector());
if (initialType == BlockID.AIR) { if (initialType == BlockID.AIR) {
return true; return true;
@ -60,8 +66,8 @@ public class FloodFillTool implements BlockTool {
EditSession editSession = session.createEditSession(player); EditSession editSession = session.createEditSession(player);
try { try {
recurse(server, editSession, world, clicked.toBlockVector(), recurse(server, editSession, world, clicked.toVector().toBlockVector(),
clicked, range, initialType, new HashSet<BlockVector>()); clicked.toVector(), range, initialType, new HashSet<BlockVector>());
} catch (MaxChangedBlocksException e) { } catch (MaxChangedBlocksException e) {
player.printError("Max blocks change limit reached."); player.printError("Max blocks change limit reached.");
} finally { } finally {
@ -71,23 +77,8 @@ public class FloodFillTool implements BlockTool {
return true; return true;
} }
/** private void recurse(Platform server, EditSession editSession, World world, BlockVector pos, Vector origin, int size, int initialType,
* Helper method. Set<BlockVector> visited) throws MaxChangedBlocksException {
*
* @param server
* @param superPickaxeManyDrop
* @param world
* @param pos
* @param origin
* @param size
* @param initialType
* @param visited
*/
private void recurse(ServerInterface server, EditSession editSession,
LocalWorld world, BlockVector pos,
Vector origin, int size, int initialType,
Set<BlockVector> visited)
throws MaxChangedBlocksException {
if (origin.distance(pos) > size || visited.contains(pos)) { if (origin.distance(pos) > size || visited.contains(pos)) {
return; return;

View File

@ -22,11 +22,12 @@ package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
/** /**
* A tool that can place (or remove) blocks at a distance. * A tool that can place (or remove) blocks at a distance.
*
* @author wizjany
*/ */
public class LongRangeBuildTool extends BrushTool implements DoubleActionTraceTool { public class LongRangeBuildTool extends BrushTool implements DoubleActionTraceTool {
@ -40,13 +41,12 @@ public class LongRangeBuildTool extends BrushTool implements DoubleActionTraceTo
} }
@Override @Override
public boolean canUse(LocalPlayer player) { public boolean canUse(Actor player) {
return player.hasPermission("worldedit.tool.lrbuild"); return player.hasPermission("worldedit.tool.lrbuild");
} }
public boolean actSecondary(ServerInterface server, LocalConfiguration config, @Override
LocalPlayer player, LocalSession session) { public boolean actSecondary(Platform server, LocalConfiguration config, Player player, LocalSession session) {
WorldVectorFace pos = getTargetFace(player); WorldVectorFace pos = getTargetFace(player);
if (pos == null) return false; if (pos == null) return false;
EditSession eS = session.createEditSession(player); EditSession eS = session.createEditSession(player);
@ -65,9 +65,7 @@ public class LongRangeBuildTool extends BrushTool implements DoubleActionTraceTo
} }
@Override @Override
public boolean actPrimary(ServerInterface server, LocalConfiguration config, public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session) {
LocalPlayer player, LocalSession session) {
WorldVectorFace pos = getTargetFace(player); WorldVectorFace pos = getTargetFace(player);
if (pos == null) return false; if (pos == null) return false;
EditSession eS = session.createEditSession(player); EditSession eS = session.createEditSession(player);
@ -84,7 +82,7 @@ public class LongRangeBuildTool extends BrushTool implements DoubleActionTraceTo
return false; return false;
} }
public WorldVectorFace getTargetFace(LocalPlayer player) { public WorldVectorFace getTargetFace(Player player) {
WorldVectorFace target = null; WorldVectorFace target = null;
target = player.getBlockTraceFace(getRange(), true); target = player.getBlockTraceFace(getRange(), true);
@ -95,4 +93,5 @@ public class LongRangeBuildTool extends BrushTool implements DoubleActionTraceTo
return target; return target;
} }
} }

View File

@ -19,33 +19,39 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.blocks.*; import com.sk89q.worldedit.blocks.*;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.world.World;
/** /**
* Plants a tree. * Looks up information about a block.
*
* @author sk89q
*/ */
public class QueryTool implements BlockTool { public class QueryTool implements BlockTool {
public boolean canUse(LocalPlayer player) { @Override
public boolean canUse(Actor player) {
return player.hasPermission("worldedit.tool.info"); return player.hasPermission("worldedit.tool.info");
} }
public boolean actPrimary(ServerInterface server, LocalConfiguration config, @Override
LocalPlayer player, LocalSession session, WorldVector clicked) { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) {
LocalWorld world = clicked.getWorld(); World world = clicked.getWorld();
EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(world, 0, player); EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(world, 0, player);
BaseBlock block = (editSession).rawGetBlock(clicked); BaseBlock block = (editSession).rawGetBlock(clicked.toVector());
BlockType type = BlockType.fromID(block.getType()); BlockType type = BlockType.fromID(block.getType());
player.print("\u00A79@" + clicked + ": " + "\u00A7e" player.print("\u00A79@" + clicked.toVector() + ": " + "\u00A7e"
+ "#" + block.getType() + "\u00A77" + " (" + "#" + block.getType() + "\u00A77" + " ("
+ (type == null ? "Unknown" : type.getName()) + ") " + (type == null ? "Unknown" : type.getName()) + ") "
+ "\u00A7f" + "\u00A7f"
+ "[" + block.getData() + "]" + " (" + world.getBlockLightLevel(clicked) + "/" + world.getBlockLightLevel(clicked.add(0, 1, 0)) + ")"); + "[" + block.getData() + "]" + " (" + world.getBlockLightLevel(clicked.toVector()) + "/" + world.getBlockLightLevel(clicked.toVector().add(0, 1, 0)) + ")");
if (block instanceof MobSpawnerBlock) { if (block instanceof MobSpawnerBlock) {
player.printRaw("\u00A7e" + "Mob Type: " player.printRaw("\u00A7e" + "Mob Type: "

View File

@ -22,6 +22,10 @@ package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.world.World;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
@ -29,10 +33,9 @@ import java.util.Set;
/** /**
* A pickaxe mode that recursively finds adjacent blocks within range of * A pickaxe mode that recursively finds adjacent blocks within range of
* an initial block and of the same type. * an initial block and of the same type.
*
* @author sk89q
*/ */
public class RecursivePickaxe implements BlockTool { public class RecursivePickaxe implements BlockTool {
private static final BaseBlock air = new BaseBlock(0); private static final BaseBlock air = new BaseBlock(0);
private double range; private double range;
@ -40,15 +43,16 @@ public class RecursivePickaxe implements BlockTool {
this.range = range; this.range = range;
} }
public boolean canUse(LocalPlayer player) { @Override
public boolean canUse(Actor player) {
return player.hasPermission("worldedit.superpickaxe.recursive"); return player.hasPermission("worldedit.superpickaxe.recursive");
} }
public boolean actPrimary(ServerInterface server, LocalConfiguration config, @Override
LocalPlayer player, LocalSession session, WorldVector clicked) { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) {
LocalWorld world = clicked.getWorld(); World world = clicked.getWorld();
int initialType = world.getBlockType(clicked); int initialType = world.getBlockType(clicked.toVector());
if (initialType == BlockID.AIR) { if (initialType == BlockID.AIR) {
return true; return true;
@ -62,8 +66,8 @@ public class RecursivePickaxe implements BlockTool {
editSession.getSurvivalExtent().setToolUse(config.superPickaxeManyDrop); editSession.getSurvivalExtent().setToolUse(config.superPickaxeManyDrop);
try { try {
recurse(server, editSession, world, clicked.toBlockVector(), recurse(server, editSession, world, clicked.toVector().toBlockVector(),
clicked, range, initialType, new HashSet<BlockVector>()); clicked.toVector(), range, initialType, new HashSet<BlockVector>());
} catch (MaxChangedBlocksException e) { } catch (MaxChangedBlocksException e) {
player.printError("Max blocks change limit reached."); player.printError("Max blocks change limit reached.");
} finally { } finally {
@ -74,22 +78,8 @@ public class RecursivePickaxe implements BlockTool {
return true; return true;
} }
/** private static void recurse(Platform server, EditSession editSession, World world, BlockVector pos,
* Helper method. Vector origin, double size, int initialType, Set<BlockVector> visited) throws MaxChangedBlocksException {
*
* @param server
* @param world
* @param pos
* @param origin
* @param size
* @param initialType
* @param visited
*/
private static void recurse(ServerInterface server, EditSession editSession,
LocalWorld world, BlockVector pos,
Vector origin, double size, int initialType,
Set<BlockVector> visited)
throws MaxChangedBlocksException {
final double distanceSq = origin.distanceSq(pos); final double distanceSq = origin.distanceSq(pos);
if (distanceSq > size*size || visited.contains(pos)) { if (distanceSq > size*size || visited.contains(pos)) {

View File

@ -19,26 +19,31 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.world.World;
/** /**
* A super pickaxe mode that removes one block. * A super pickaxe mode that removes one block.
*
* @author sk89q
*/ */
public class SinglePickaxe implements BlockTool { public class SinglePickaxe implements BlockTool {
public boolean canUse(LocalPlayer player) { @Override
public boolean canUse(Actor player) {
return player.hasPermission("worldedit.superpickaxe"); return player.hasPermission("worldedit.superpickaxe");
} }
public boolean actPrimary(ServerInterface server, LocalConfiguration config, @Override
LocalPlayer player, LocalSession session, WorldVector clicked) { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) {
LocalWorld world = clicked.getWorld(); World world = clicked.getWorld();
final int blockType = world.getBlockType(clicked.toVector());
final int blockType = world.getBlockType(clicked);
if (blockType == BlockID.BEDROCK if (blockType == BlockID.BEDROCK
&& !player.canDestroyBedrock()) { && !player.canDestroyBedrock()) {
return true; return true;
@ -48,14 +53,14 @@ public class SinglePickaxe implements BlockTool {
editSession.getSurvivalExtent().setToolUse(config.superPickaxeDrop); editSession.getSurvivalExtent().setToolUse(config.superPickaxeDrop);
try { try {
editSession.setBlock(clicked, new BaseBlock(BlockID.AIR)); editSession.setBlock(clicked.toVector(), new BaseBlock(BlockID.AIR));
} catch (MaxChangedBlocksException e) { } catch (MaxChangedBlocksException e) {
player.printError("Max blocks change limit reached."); player.printError("Max blocks change limit reached.");
} finally { } finally {
editSession.flushQueue(); editSession.flushQueue();
} }
world.playEffect(clicked, 2001, blockType); world.playEffect(clicked.toVector(), 2001, blockType);
return true; return true;
} }

View File

@ -19,23 +19,21 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.LocalPlayer; import com.sk89q.worldedit.extension.platform.Actor;
/** /**
* Represents a tool. This interface alone defines nothing. A tool also * Represents a tool. This interface alone defines nothing. A tool also
* has to implement <code>BlockTool</code> or <code>TraceTool</code>. * has to implement <code>BlockTool</code> or <code>TraceTool</code>.
*
* @author sk89q
*/ */
public abstract interface Tool { public interface Tool {
/** /**
* Checks to see if the player can still be using this tool (considering * Checks to see if the player can still be using this tool (considering
* permissions and such). * permissions and such).
* *
* @param player * @param actor the actor
* @return * @return true if use is permitted
*/ */
public boolean canUse(LocalPlayer player); public boolean canUse(Actor actor);
} }

View File

@ -20,26 +20,11 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.ServerInterface; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Platform;
/**
* Represents a tool that does not require a block.
*
* @author sk89q
*/
public interface TraceTool extends Tool { public interface TraceTool extends Tool {
/**
* Perform the action. Should return true to deny the default public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session);
* action.
*
* @param server
* @param config
* @param player
* @param session
* @return true to deny
*/
public boolean actPrimary(ServerInterface server, LocalConfiguration config,
LocalPlayer player, LocalSession session);
} }

View File

@ -20,26 +20,30 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.util.*;
import com.sk89q.worldedit.util.Location;
/** /**
* Plants a tree. * Plants a tree.
*
* @author sk89q
*/ */
public class TreePlanter implements BlockTool { public class TreePlanter implements BlockTool {
private TreeGenerator gen; private TreeGenerator gen;
public TreePlanter(TreeGenerator gen) { public TreePlanter(TreeGenerator gen) {
this.gen = gen; this.gen = gen;
} }
public boolean canUse(LocalPlayer player) { @Override
public boolean canUse(Actor player) {
return player.hasPermission("worldedit.tool.tree"); return player.hasPermission("worldedit.tool.tree");
} }
public boolean actPrimary(ServerInterface server, LocalConfiguration config, @Override
LocalPlayer player, LocalSession session, WorldVector clicked) { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked) {
EditSession editSession = session.createEditSession(player); EditSession editSession = session.createEditSession(player);
@ -47,7 +51,7 @@ public class TreePlanter implements BlockTool {
boolean successful = false; boolean successful = false;
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
if (gen.generate(editSession, clicked.add(0, 1, 0))) { if (gen.generate(editSession, clicked.toVector().add(0, 1, 0))) {
successful = true; successful = true;
break; break;
} }

View File

@ -22,7 +22,7 @@ package com.sk89q.worldedit.command.tool.brush;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
/** /**
* Represents a brush. * Represents a brush.
@ -39,6 +39,5 @@ public interface Brush {
* @param size * @param size
* @throws MaxChangedBlocksException * @throws MaxChangedBlocksException
*/ */
public void build(EditSession editSession, Vector pos, Pattern mat, double size) public void build(EditSession editSession, Vector pos, Pattern mat, double size) throws MaxChangedBlocksException;
throws MaxChangedBlocksException;
} }

View File

@ -22,9 +22,10 @@ package com.sk89q.worldedit.command.tool.brush;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
public class ButcherBrush implements Brush { public class ButcherBrush implements Brush {
private int flags; private int flags;
public ButcherBrush(int flags) { public ButcherBrush(int flags) {
@ -32,8 +33,7 @@ public class ButcherBrush implements Brush {
} }
@Override @Override
public void build(EditSession editSession, Vector pos, Pattern mat, double size) public void build(EditSession editSession, Vector pos, Pattern mat, double size) throws MaxChangedBlocksException {
throws MaxChangedBlocksException {
editSession.getWorld().killMobs(pos, size, flags); editSession.getWorld().killMobs(pos, size, flags);
} }

View File

@ -23,9 +23,10 @@ import com.sk89q.worldedit.CuboidClipboard;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
public class ClipboardBrush implements Brush { public class ClipboardBrush implements Brush {
private CuboidClipboard clipboard; private CuboidClipboard clipboard;
private boolean noAir; private boolean noAir;
@ -34,8 +35,8 @@ public class ClipboardBrush implements Brush {
this.noAir = noAir; this.noAir = noAir;
} }
public void build(EditSession editSession, Vector pos, Pattern mat, double size) public void build(EditSession editSession, Vector pos, Pattern mat, double size) throws MaxChangedBlocksException {
throws MaxChangedBlocksException {
clipboard.place(editSession, pos.subtract(clipboard.getSize().divide(2)), noAir); clipboard.place(editSession, pos.subtract(clipboard.getSize().divide(2)), noAir);
} }
} }

View File

@ -22,17 +22,19 @@ package com.sk89q.worldedit.command.tool.brush;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.pattern.Patterns;
public class CylinderBrush implements Brush { public class CylinderBrush implements Brush {
private int height; private int height;
public CylinderBrush(int height) { public CylinderBrush(int height) {
this.height = height; this.height = height;
} }
public void build(EditSession editSession, Vector pos, Pattern mat, double size) public void build(EditSession editSession, Vector pos, Pattern mat, double size) throws MaxChangedBlocksException {
throws MaxChangedBlocksException { editSession.makeCylinder(pos, Patterns.wrap(mat), size, size, height, true);
editSession.makeCylinder(pos, mat, size, size, height, true);
} }
} }

View File

@ -24,14 +24,12 @@ import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import java.util.*; import java.util.*;
/**
* @author zml2008
*/
public class GravityBrush implements Brush { public class GravityBrush implements Brush {
private final boolean fullHeight; private final boolean fullHeight;
public GravityBrush(boolean fullHeight) { public GravityBrush(boolean fullHeight) {
@ -65,4 +63,5 @@ public class GravityBrush implements Brush {
} }
} }
} }
} }

View File

@ -22,17 +22,20 @@ package com.sk89q.worldedit.command.tool.brush;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.pattern.Patterns;
public class HollowCylinderBrush implements Brush { public class HollowCylinderBrush implements Brush {
private int height; private int height;
public HollowCylinderBrush(int height) { public HollowCylinderBrush(int height) {
this.height = height; this.height = height;
} }
public void build(EditSession editSession, Vector pos, Pattern mat, double size) @Override
throws MaxChangedBlocksException { public void build(EditSession editSession, Vector pos, Pattern mat, double size) throws MaxChangedBlocksException {
editSession.makeCylinder(pos, mat, size, size, height, false); editSession.makeCylinder(pos, Patterns.wrap(mat), size, size, height, false);
} }
} }

View File

@ -22,14 +22,13 @@ package com.sk89q.worldedit.command.tool.brush;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.pattern.Patterns;
public class HollowSphereBrush implements Brush { public class HollowSphereBrush implements Brush {
public HollowSphereBrush() {
}
public void build(EditSession editSession, Vector pos, Pattern mat, double size) @Override
throws MaxChangedBlocksException { public void build(EditSession editSession, Vector pos, Pattern mat, double size) throws MaxChangedBlocksException {
editSession.makeSphere(pos, mat, size, size, size, false); editSession.makeSphere(pos, Patterns.wrap(mat), size, size, size, false);
} }
} }

View File

@ -20,6 +20,7 @@
package com.sk89q.worldedit.command.tool.brush; package com.sk89q.worldedit.command.tool.brush;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.internal.LocalWorldAdapter; import com.sk89q.worldedit.internal.LocalWorldAdapter;
import com.sk89q.worldedit.math.convolution.HeightMap; import com.sk89q.worldedit.math.convolution.HeightMap;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
@ -27,11 +28,11 @@ import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldVector; import com.sk89q.worldedit.WorldVector;
import com.sk89q.worldedit.math.convolution.GaussianKernel; import com.sk89q.worldedit.math.convolution.GaussianKernel;
import com.sk89q.worldedit.math.convolution.HeightMapFilter; import com.sk89q.worldedit.math.convolution.HeightMapFilter;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
public class SmoothBrush implements Brush { public class SmoothBrush implements Brush {
private int iterations; private int iterations;
private boolean naturalOnly; private boolean naturalOnly;
@ -53,4 +54,5 @@ public class SmoothBrush implements Brush {
HeightMapFilter filter = new HeightMapFilter(new GaussianKernel(5, 1.0)); HeightMapFilter filter = new HeightMapFilter(new GaussianKernel(5, 1.0));
heightMap.applyFilter(filter, iterations); heightMap.applyFilter(filter, iterations);
} }
} }

View File

@ -22,14 +22,13 @@ package com.sk89q.worldedit.command.tool.brush;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.patterns.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.pattern.Patterns;
public class SphereBrush implements Brush { public class SphereBrush implements Brush {
public SphereBrush() {
}
public void build(EditSession editSession, Vector pos, Pattern mat, double size) @Override
throws MaxChangedBlocksException { public void build(EditSession editSession, Vector pos, Pattern mat, double size) throws MaxChangedBlocksException {
editSession.makeSphere(pos, mat, size, size, size, true); editSession.makeSphere(pos, Patterns.wrap(mat), size, size, size, true);
} }
} }

View File

@ -19,8 +19,8 @@
package com.sk89q.worldedit.event.platform; package com.sk89q.worldedit.event.platform;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.event.AbstractCancellable; import com.sk89q.worldedit.event.AbstractCancellable;
import com.sk89q.worldedit.extension.platform.Actor;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -29,30 +29,30 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/ */
public class CommandEvent extends AbstractCancellable { public class CommandEvent extends AbstractCancellable {
private final LocalPlayer player; private final Actor actor;
private final String[] args; private final String arguments;
/** /**
* Create a new instance. * Create a new instance.
* *
* @param player the player * @param actor the player
* @param args the arguments * @param arguments the arguments
*/ */
public CommandEvent(LocalPlayer player, String[] args) { public CommandEvent(Actor actor, String arguments) {
checkNotNull(player); checkNotNull(actor);
checkNotNull(args); checkNotNull(arguments);
this.player = player; this.actor = actor;
this.args = args; this.arguments = arguments;
} }
/** /**
* Get the player. * Get the actor that issued the command.
* *
* @return the player * @return the actor that issued the command
*/ */
public LocalPlayer getPlayer() { public Actor getActor() {
return player; return actor;
} }
/** /**
@ -60,8 +60,8 @@ public class CommandEvent extends AbstractCancellable {
* *
* @return the arguments * @return the arguments
*/ */
public String[] getArguments() { public String getArguments() {
return args; return arguments;
} }
} }

View File

@ -0,0 +1,90 @@
/*
* 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.event.platform;
import com.sk89q.worldedit.event.Event;
import com.sk89q.worldedit.extension.platform.Actor;
import java.util.Collections;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Posted when suggestions for auto-completion are requested for command input.
*/
public class CommandSuggestionEvent extends Event {
private final Actor actor;
private final String arguments;
private List<String> suggestions = Collections.emptyList();
/**
* Create a new instance.
*
* @param actor the player
* @param arguments the arguments
*/
public CommandSuggestionEvent(Actor actor, String arguments) {
checkNotNull(actor);
checkNotNull(arguments);
this.actor = actor;
this.arguments = arguments;
}
/**
* Get the actor that issued the command.
*
* @return the actor that issued the command
*/
public Actor getActor() {
return actor;
}
/**
* Get the arguments.
*
* @return the arguments
*/
public String getArguments() {
return arguments;
}
/**
* Get the list of suggestions that are to be presented.
*
* @return the list of suggestions
*/
public List<String> getSuggestions() {
return suggestions;
}
/**
* Set the list of suggestions that are to be presented.
*
* @param suggestions the list of suggestions
*/
public void setSuggestions(List<String> suggestions) {
checkNotNull(suggestions);
this.suggestions = suggestions;
}
}

View File

@ -0,0 +1,29 @@
/*
* 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.event.platform;
import com.sk89q.worldedit.event.Event;
/**
* Raised when a platform thinks that all the platforms have had a chance to
* register themselves.
*/
public class PlatformReadyEvent extends Event {
}

View File

@ -42,15 +42,4 @@ public abstract class AbstractPlatform implements Platform {
return Collections.emptyList(); return Collections.emptyList();
} }
@Override
@Deprecated
public void onCommandRegistration(List<Command> commands) {
// Do nothing :)
}
@Override
public void onCommandRegistration(List<Command> commands, CommandsManager<LocalPlayer> manager) {
onCommandRegistration(commands);
}
} }

View File

@ -40,19 +40,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/ */
public abstract class AbstractPlayerActor implements Actor, Player { public abstract class AbstractPlayerActor implements Actor, Player {
private final Platform platform;
/**
* Create a new instance.
*
* @param platform the platform
*/
protected AbstractPlayerActor(Platform platform) {
checkNotNull(platform);
this.platform = platform;
}
/** /**
* Returns direction according to rotation. May return null. * Returns direction according to rotation. May return null.
* *

View File

@ -37,13 +37,6 @@ public interface Actor {
*/ */
String getName(); String getName();
/**
* Get the actor's world.
*
* @return the world
*/
World getWorld();
/** /**
* Print a message. * Print a message.
* *

View File

@ -0,0 +1,81 @@
/*
* 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.extension.platform;
/**
* A collection of capabilities that a {@link Platform} may support.
*/
public enum Capability {
/**
* The capability of registering game hooks to catch events such as
* a player clicking a block.
*/
GAME_HOOKS {
@Override
void initialize(PlatformManager platformManager, Platform platform) {
platform.registerGameHooks();
}
@Override
void unload(PlatformManager platformManager, Platform platform) {
}
},
/**
* The capability of providing configuration.
*/
CONFIGURATION,
/**
* The capability of handling user commands entered in chat or console.
*/
USER_COMMANDS {
@Override
void initialize(PlatformManager platformManager, Platform platform) {
platformManager.getCommandManager().register(platform);
}
@Override
void unload(PlatformManager platformManager, Platform platform) {
platformManager.getCommandManager().unregister();
}
},
/**
* The capability of a platform to assess whether a given
* {@link Actor} has sufficient authorization to perform a task.
*/
PERMISSIONS,
/**
* The capability of a platform to perform modifications to a world.
*/
WORLD_EDITING;
void initialize(PlatformManager platformManager, Platform platform) {
}
void unload(PlatformManager platformManager, Platform platform) {
}
}

View File

@ -19,22 +19,37 @@
package com.sk89q.worldedit.extension.platform; package com.sk89q.worldedit.extension.platform;
import com.sk89q.minecraft.util.commands.*; import com.google.common.base.Joiner;
import com.sk89q.util.StringUtil; import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.*; import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.worldedit.blocks.ItemType; import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.command.*; import com.sk89q.worldedit.command.*;
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.internal.command.ActorAuthorizer;
import com.sk89q.worldedit.internal.command.CommandLoggingHandler;
import com.sk89q.worldedit.internal.command.WorldEditBinding;
import com.sk89q.worldedit.internal.command.WorldEditExceptionConverter;
import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.util.logging.LogFormat; import com.sk89q.worldedit.util.command.Dispatcher;
import com.sk89q.worldedit.util.command.InvalidUsageException;
import com.sk89q.worldedit.util.command.fluent.CommandGraph;
import com.sk89q.worldedit.util.command.parametric.LegacyCommandsHandler;
import com.sk89q.worldedit.util.command.parametric.ParametricBuilder;
import com.sk89q.worldedit.util.eventbus.Subscribe; import com.sk89q.worldedit.util.eventbus.Subscribe;
import com.sk89q.worldedit.util.logging.DynamicStreamHandler; import com.sk89q.worldedit.util.logging.DynamicStreamHandler;
import com.sk89q.worldedit.util.logging.LogFormat;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Method; import java.util.logging.FileHandler;
import java.util.logging.*; import java.util.logging.Level;
import java.util.regex.Matcher; import java.util.logging.Logger;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -49,7 +64,8 @@ public final class CommandManager {
private static final java.util.regex.Pattern numberFormatExceptionPattern = java.util.regex.Pattern.compile("^For input string: \"(.*)\"$"); private static final java.util.regex.Pattern numberFormatExceptionPattern = java.util.regex.Pattern.compile("^For input string: \"(.*)\"$");
private final WorldEdit worldEdit; private final WorldEdit worldEdit;
private final CommandsManager<LocalPlayer> commands; private final PlatformManager platformManager;
private final Dispatcher dispatcher;
private final DynamicStreamHandler dynamicHandler = new DynamicStreamHandler(); private final DynamicStreamHandler dynamicHandler = new DynamicStreamHandler();
/** /**
@ -57,9 +73,11 @@ public final class CommandManager {
* *
* @param worldEdit the WorldEdit instance * @param worldEdit the WorldEdit instance
*/ */
CommandManager(final WorldEdit worldEdit) { CommandManager(final WorldEdit worldEdit, PlatformManager platformManager) {
checkNotNull(worldEdit); checkNotNull(worldEdit);
checkNotNull(platformManager);
this.worldEdit = worldEdit; this.worldEdit = worldEdit;
this.platformManager = platformManager;
// Register this instance for command events // Register this instance for command events
worldEdit.getEventBus().register(this); worldEdit.getEventBus().register(this);
@ -69,8 +87,56 @@ public final class CommandManager {
dynamicHandler.setFormatter(new LogFormat()); dynamicHandler.setFormatter(new LogFormat());
// Set up the commands manager // Set up the commands manager
commands = new CommandsManagerImpl(); ParametricBuilder builder = new ParametricBuilder();
commands.setInjector(new SimpleInjector(worldEdit)); builder.setAuthorizer(new ActorAuthorizer());
builder.addBinding(new WorldEditBinding(worldEdit));
builder.addExceptionConverter(new WorldEditExceptionConverter(worldEdit));
builder.addInvokeListener(new LegacyCommandsHandler());
builder.addInvokeListener(new CommandLoggingHandler(worldEdit, logger));
dispatcher = new CommandGraph()
.builder(builder)
.commands()
.registerMethods(new BiomeCommands(worldEdit))
.registerMethods(new ChunkCommands(worldEdit))
.registerMethods(new ClipboardCommands(worldEdit))
.registerMethods(new GeneralCommands(worldEdit))
.registerMethods(new GenerationCommands(worldEdit))
.registerMethods(new HistoryCommands(worldEdit))
.registerMethods(new NavigationCommands(worldEdit))
.registerMethods(new RegionCommands(worldEdit))
.registerMethods(new ScriptingCommands(worldEdit))
.registerMethods(new SelectionCommands(worldEdit))
.registerMethods(new SnapshotUtilCommands(worldEdit))
.registerMethods(new ToolUtilCommands(worldEdit))
.registerMethods(new ToolCommands(worldEdit))
.registerMethods(new UtilityCommands(worldEdit))
.group("worldedit", "we")
.describeAs("WorldEdit commands")
.registerMethods(new WorldEditCommands(worldEdit))
.parent()
.group("schematic", "schem", "/schematic", "/schem")
.describeAs("Schematic commands for saving/loading areas")
.registerMethods(new SchematicCommands(worldEdit))
.parent()
.group("snapshot", "snap")
.describeAs("Schematic commands for saving/loading areas")
.registerMethods(new SnapshotCommands(worldEdit))
.parent()
.group("brush", "br")
.describeAs("Brushing commands")
.registerMethods(new BrushCommands(worldEdit))
.parent()
.group("superpickaxe", "pickaxe", "sp")
.describeAs("Super-pickaxe commands")
.registerMethods(new SuperPickaxeCommands(worldEdit))
.parent()
.group("tool")
.describeAs("Bind functions to held items")
.registerMethods(new ToolCommands(worldEdit))
.parent()
.graph()
.getDispatcher();
} }
void register(Platform platform) { void register(Platform platform) {
@ -83,9 +149,12 @@ public final class CommandManager {
// Register log // Register log
if (!logging || path.isEmpty()) { if (!logging || path.isEmpty()) {
dynamicHandler.setHandler(null); dynamicHandler.setHandler(null);
logger.setLevel(Level.OFF);
} else { } else {
File file = new File(config.getWorkingDirectory(), path); File file = new File(config.getWorkingDirectory(), path);
logger.setLevel(Level.ALL);
logger.log(Level.INFO, "Logging WorldEdit commands to " + file.getAbsolutePath()); logger.log(Level.INFO, "Logging WorldEdit commands to " + file.getAbsolutePath());
try { try {
@ -95,39 +164,14 @@ public final class CommandManager {
} }
} }
register(platform, BiomeCommands.class); platform.registerCommands(dispatcher);
register(platform, ChunkCommands.class);
register(platform, ClipboardCommands.class);
register(platform, GeneralCommands.class);
register(platform, GenerationCommands.class);
register(platform, HistoryCommands.class);
register(platform, NavigationCommands.class);
register(platform, RegionCommands.class);
register(platform, ScriptingCommands.class);
register(platform, SelectionCommands.class);
register(platform, SnapshotUtilCommands.class);
register(platform, ToolUtilCommands.class);
register(platform, ToolCommands.class);
register(platform, UtilityCommands.class);
} }
void unregister() { void unregister() {
dynamicHandler.setHandler(null); dynamicHandler.setHandler(null);
} }
private void register(Platform platform, Class<?> clazz) {
platform.onCommandRegistration(commands.registerAndReturn(clazz), commands);
}
public CommandsManager<LocalPlayer> getCommands() {
return commands;
}
public String[] commandDetection(String[] split) { public String[] commandDetection(String[] split) {
Request.reset();
split[0] = split[0].substring(1);
// Quick script shortcut // Quick script shortcut
if (split[0].matches("^[^/].*\\.js$")) { if (split[0].matches("^[^/].*\\.js$")) {
String[] newSplit = new String[split.length + 1]; String[] newSplit = new String[split.length + 1];
@ -140,12 +184,12 @@ public final class CommandManager {
String searchCmd = split[0].toLowerCase(); String searchCmd = split[0].toLowerCase();
// Try to detect the command // Try to detect the command
if (commands.hasCommand(searchCmd)) { if (!dispatcher.contains(searchCmd)) {
} else if (worldEdit.getConfiguration().noDoubleSlash && commands.hasCommand("/" + searchCmd)) { if (worldEdit.getConfiguration().noDoubleSlash && dispatcher.contains("/" + searchCmd)) {
split[0] = "/" + split[0]; split[0] = "/" + split[0];
} else if (split[0].length() >= 2 && split[0].charAt(0) == '/' } else if (searchCmd.length() >= 2 && searchCmd.charAt(0) == '/' && dispatcher.contains(searchCmd.substring(1))) {
&& commands.hasCommand(searchCmd.substring(1))) { split[0] = split[0].substring(1);
split[0] = split[0].substring(1); }
} }
return split; return split;
@ -155,185 +199,80 @@ public final class CommandManager {
public void handleCommand(CommandEvent event) { public void handleCommand(CommandEvent event) {
Request.reset(); Request.reset();
LocalPlayer player = event.getPlayer(); Actor actor = platformManager.createProxyActor(event.getActor());
String[] split = event.getArguments(); String split[] = commandDetection(event.getArguments().split(" "));
// No command found!
if (!dispatcher.contains(split[0])) {
return;
}
LocalSession session = worldEdit.getSessionManager().get(actor);
LocalConfiguration config = worldEdit.getConfiguration();
CommandLocals locals = new CommandLocals();
locals.put(Actor.class, actor);
long start = System.currentTimeMillis();
try { try {
split = commandDetection(split); dispatcher.call(Joiner.on(" ").join(split), locals, new String[0]);
} catch (CommandPermissionsException e) {
actor.printError("You don't have permission to do this.");
} catch (InvalidUsageException e) {
actor.printError(e.getMessage() + "\nUsage: " + e.getUsage("/"));
} catch (WrappedCommandException e) {
Throwable t = e.getCause();
actor.printError("Please report this error: [See console]");
actor.printRaw(t.getClass().getName() + ": " + t.getMessage());
t.printStackTrace();
} catch (CommandException e) {
actor.printError(e.getMessage());
} finally {
EditSession editSession = locals.get(EditSession.class);
// No command found! if (editSession != null) {
if (!commands.hasCommand(split[0])) {
return;
}
LocalSession session = worldEdit.getSession(player);
EditSession editSession = session.createEditSession(player);
editSession.enableQueue();
session.tellVersion(player);
long start = System.currentTimeMillis();
try {
commands.execute(split, player, session, player, editSession);
} catch (CommandPermissionsException e) {
player.printError("You don't have permission to do this.");
} catch (MissingNestedCommandException e) {
player.printError(e.getUsage());
} catch (CommandUsageException e) {
player.printError(e.getMessage());
player.printError(e.getUsage());
} catch (PlayerNeededException e) {
player.printError(e.getMessage());
} catch (WrappedCommandException e) {
throw e.getCause();
} catch (UnhandledCommandException e) {
player.printError("Command could not be handled; invalid sender!");
event.setCancelled(true);
return;
} finally {
session.remember(editSession); session.remember(editSession);
editSession.flushQueue(); editSession.flushQueue();
if (worldEdit.getConfiguration().profile) { if (config.profile) {
long time = System.currentTimeMillis() - start; long time = System.currentTimeMillis() - start;
int changed = editSession.getBlockChangeCount(); int changed = editSession.getBlockChangeCount();
if (time > 0) { if (time > 0) {
double throughput = changed / (time / 1000.0); double throughput = changed / (time / 1000.0);
player.printDebug((time / 1000.0) + "s elapsed (history: " actor.printDebug((time / 1000.0) + "s elapsed (history: "
+ changed + " changed; " + changed + " changed; "
+ Math.round(throughput) + " blocks/sec)."); + Math.round(throughput) + " blocks/sec).");
} else { } else {
player.printDebug((time / 1000.0) + "s elapsed."); actor.printDebug((time / 1000.0) + "s elapsed.");
} }
} }
worldEdit.flushBlockBag(player, editSession); worldEdit.flushBlockBag(actor, editSession);
} }
} catch (NumberFormatException e) {
final Matcher matcher = numberFormatExceptionPattern.matcher(e.getMessage());
if (matcher.matches()) {
player.printError("Number expected; string \"" + matcher.group(1) + "\" given.");
} else {
player.printError("Number expected; string given.");
}
} catch (IncompleteRegionException e) {
player.printError("Make a region selection first.");
} catch (UnknownItemException e) {
player.printError("Block name '" + e.getID() + "' was not recognized.");
} catch (InvalidItemException e) {
player.printError(e.getMessage());
} catch (DisallowedItemException e) {
player.printError("Block '" + e.getID() + "' not allowed (see WorldEdit configuration).");
} catch (MaxChangedBlocksException e) {
player.printError("Max blocks changed in an operation reached ("
+ e.getBlockLimit() + ").");
} catch (MaxBrushRadiusException e) {
player.printError("Maximum allowed brush size: " + worldEdit.getConfiguration().maxBrushRadius);
} catch (MaxRadiusException e) {
player.printError("Maximum allowed size: " + worldEdit.getConfiguration().maxRadius);
} catch (UnknownDirectionException e) {
player.printError("Unknown direction: " + e.getDirection());
} catch (InsufficientArgumentsException e) {
player.printError(e.getMessage());
} catch (EmptyClipboardException e) {
player.printError("Your clipboard is empty. Use //copy first.");
} catch (InvalidFilenameException e) {
player.printError("Filename '" + e.getFilename() + "' invalid: "
+ e.getMessage());
} catch (FilenameResolutionException e) {
player.printError("File '" + e.getFilename() + "' resolution error: "
+ e.getMessage());
} catch (InvalidToolBindException e) {
player.printError("Can't bind tool to "
+ ItemType.toHeldName(e.getItemId()) + ": " + e.getMessage());
} catch (FileSelectionAbortedException e) {
player.printError("File selection aborted.");
} catch (WorldEditException e) {
player.printError(e.getMessage());
} catch (Throwable excp) {
player.printError("Please report this error: [See console]");
player.printRaw(excp.getClass().getName() + ": " + excp.getMessage());
excp.printStackTrace();
} }
event.setCancelled(true); event.setCancelled(true);
} }
private class CommandsManagerImpl extends CommandsManager<LocalPlayer> { @Subscribe
@Override public void handleCommandSuggestion(CommandSuggestionEvent event) {
protected void checkPermission(LocalPlayer player, Method method) throws CommandException { try {
if (!player.isPlayer() && !method.isAnnotationPresent(Console.class)) { CommandLocals locals = new CommandLocals();
throw new UnhandledCommandException(); locals.put(Actor.class, event.getActor());
} event.setSuggestions(dispatcher.getSuggestions(event.getArguments(), locals));
} catch (CommandException e) {
super.checkPermission(player, method); event.getActor().printError(e.getMessage());
} }
}
@Override /**
public boolean hasPermission(LocalPlayer player, String perm) { * Get the command dispatcher instance.
return player.hasPermission(perm); *
} * @return the command dispatcher
*/
@Override public Dispatcher getDispatcher() {
public void invokeMethod(Method parent, String[] args, return dispatcher;
LocalPlayer player, Method method, Object instance,
Object[] methodArgs, int level) throws CommandException {
if (worldEdit.getConfiguration().logCommands) {
final Logging loggingAnnotation = method.getAnnotation(Logging.class);
final Logging.LogMode logMode;
if (loggingAnnotation == null) {
logMode = null;
} else {
logMode = loggingAnnotation.value();
}
String msg = "WorldEdit: " + player.getName();
if (player.isPlayer()) {
msg += " (in \"" + player.getWorld().getName() + "\")";
}
msg += ": " + StringUtil.joinString(args, " ");
if (logMode != null && player.isPlayer()) {
Vector position = player.getPosition();
final LocalSession session = worldEdit.getSessionManager().get(player);
switch (logMode) {
case PLACEMENT:
try {
position = session.getPlacementPosition(player);
} catch (IncompleteRegionException e) {
break;
}
/* FALL-THROUGH */
case POSITION:
msg += " - Position: " + position;
break;
case ALL:
msg += " - Position: " + position;
/* FALL-THROUGH */
case ORIENTATION_REGION:
msg += " - Orientation: " + player.getCardinalDirection().name();
/* FALL-THROUGH */
case REGION:
try {
msg += " - Region: " + session.getSelection(player.getWorld());
} catch (IncompleteRegionException e) {
break;
}
break;
}
}
getLogger().info(msg);
}
super.invokeMethod(parent, args, player, method, instance, methodArgs, level);
}
} }
public static Logger getLogger() { public static Logger getLogger() {

View File

@ -19,31 +19,24 @@
package com.sk89q.worldedit.extension.platform; package com.sk89q.worldedit.extension.platform;
import com.sk89q.worldedit.WorldEditException;
/** /**
* Thrown when a platform registration request is rejected, which may * Thrown when no capable platform is found.
* be because another platform is already registered.
*/ */
public class PlatformRejectionException extends WorldEditException { public class NoCapablePlatformException extends RuntimeException {
/** public NoCapablePlatformException() {
* Create with a message. }
*
* @param message the message public NoCapablePlatformException(String message) {
*/
public PlatformRejectionException(String message) {
super(message); super(message);
} }
/** public NoCapablePlatformException(String message, Throwable cause) {
* Create with a message and a cause.
*
* @param message the message
* @param cause the cause
*/
public PlatformRejectionException(String message, Throwable cause) {
super(message, cause); super(message, cause);
} }
public NoCapablePlatformException(Throwable cause) {
super(cause);
}
} }

View File

@ -19,14 +19,15 @@
package com.sk89q.worldedit.extension.platform; package com.sk89q.worldedit.extension.platform;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandsManager;
import com.sk89q.worldedit.BiomeTypes; import com.sk89q.worldedit.BiomeTypes;
import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalPlayer; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.util.command.Dispatcher;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import javax.annotation.Nullable;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* Represents a platform that WorldEdit has been implemented for. * Represents a platform that WorldEdit has been implemented for.
@ -77,10 +78,37 @@ public interface Platform {
List<? extends World> getWorlds(); List<? extends World> getWorlds();
@Deprecated /**
void onCommandRegistration(List<Command> commands); * Create a duplicate of the given player.
* </p>
* The given player may have been provided by a different platform.
*
* @param player the player to match
* @return a matched player, otherwise null
*/
@Nullable Player matchPlayer(Player player);
void onCommandRegistration(List<Command> commands, CommandsManager<LocalPlayer> manager); /**
* Create a duplicate of the given world.
* </p>
* The given world may have been provided by a different platform.
*
* @param world the world to match
* @return a matched world, otherwise null
*/
@Nullable World matchWorld(World world);
/**
* Register the commands contained within the given command dispatcher.
*
* @param dispatcher the dispatcher
*/
void registerCommands(Dispatcher dispatcher);
/**
* Register game hooks.
*/
void registerGameHooks();
/** /**
* Get the configuration from this platform. * Get the configuration from this platform.
@ -116,4 +144,13 @@ public interface Platform {
*/ */
String getPlatformVersion(); String getPlatformVersion();
/**
* Get a map of advertised capabilities of this platform, where each key
* in the given map is a supported capability and the respective value
* indicates the preference for this platform for that given capability.
*
* @return a map of capabilities
*/
Map<Capability, Preference> getCapabilities();
} }

View File

@ -20,19 +20,22 @@
package com.sk89q.worldedit.extension.platform; package com.sk89q.worldedit.extension.platform;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.command.tool.*; import com.sk89q.worldedit.command.tool.*;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.platform.BlockInteractEvent; import com.sk89q.worldedit.event.platform.BlockInteractEvent;
import com.sk89q.worldedit.event.platform.Interaction; import com.sk89q.worldedit.event.platform.Interaction;
import com.sk89q.worldedit.event.platform.PlatformReadyEvent;
import com.sk89q.worldedit.event.platform.PlayerInputEvent; import com.sk89q.worldedit.event.platform.PlayerInputEvent;
import com.sk89q.worldedit.internal.ServerInterfaceAdapter; import com.sk89q.worldedit.internal.ServerInterfaceAdapter;
import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.eventbus.Subscribe; import com.sk89q.worldedit.util.eventbus.Subscribe;
import com.sk89q.worldedit.world.World;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.ArrayList; import java.util.*;
import java.util.List; import java.util.Map.Entry;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -48,11 +51,11 @@ public class PlatformManager {
private static final Logger logger = Logger.getLogger(PlatformManager.class.getCanonicalName()); private static final Logger logger = Logger.getLogger(PlatformManager.class.getCanonicalName());
private final LocalConfiguration defaultConfig = new DefaultConfiguration();
private final List<Platform> platforms = new ArrayList<Platform>();
private final WorldEdit worldEdit; private final WorldEdit worldEdit;
private final CommandManager commandManager; private final CommandManager commandManager;
private @Nullable Platform primary = null; private final List<Platform> platforms = new ArrayList<Platform>();
private final Map<Capability, Platform> preferences = new EnumMap<Capability, Platform>(Capability.class);
private @Nullable String firstSeenVersion;
/** /**
* Create a new platform manager. * Create a new platform manager.
@ -62,7 +65,7 @@ public class PlatformManager {
public PlatformManager(WorldEdit worldEdit) { public PlatformManager(WorldEdit worldEdit) {
checkNotNull(worldEdit); checkNotNull(worldEdit);
this.worldEdit = worldEdit; this.worldEdit = worldEdit;
this.commandManager = new CommandManager(worldEdit); this.commandManager = new CommandManager(worldEdit, this);
// Register this instance for events // Register this instance for events
worldEdit.getEventBus().register(this); worldEdit.getEventBus().register(this);
@ -72,56 +75,128 @@ public class PlatformManager {
* Register a platform with WorldEdit. * Register a platform with WorldEdit.
* *
* @param platform the platform * @param platform the platform
* @throws PlatformRejectionException thrown if the registration is rejected
*/ */
public synchronized void register(Platform platform) throws PlatformRejectionException { public synchronized void register(Platform platform) {
checkNotNull(platform); checkNotNull(platform);
logger.log(Level.FINE, "Got request to register " + platform.getClass() + " with WorldEdit [" + super.toString() + "]"); logger.log(Level.FINE, "Got request to register " + platform.getClass() + " with WorldEdit [" + super.toString() + "]");
// Just add the platform to the list of platforms: we'll pick favorites
// once all the platforms have been loaded
platforms.add(platform); platforms.add(platform);
// Register primary platform // Make sure that versions are in sync
if (this.primary == null) { if (firstSeenVersion != null) {
commandManager.register(platform); if (!firstSeenVersion.equals(platform.getVersion())) {
this.primary = platform;
} else {
// Make sure that versions are in sync
if (!primary.getVersion().equals(platform.getVersion())) {
logger.log(Level.WARNING, logger.log(Level.WARNING,
"\n**********************************************\n" + "\n**********************************************\n" +
"** There is a mismatch in available WorldEdit platforms!\n" + "** You have WorldEdit installed for multiple platforms in the same \n" +
"** game/program. This is OK except that you have different WorldEdit versions\n" +
"** installed (i.e. {0} and {1}).\n" +
"**\n" + "**\n" +
"** {0} v{1} is trying to register WE version v{2}\n" + "** WorldEdit has seen both versions {0} and {1}.\n" +
"** but the primary platform, {3} v{4}, uses WE version v{5}\n" +
"**\n" + "**\n" +
"** Things may break! Please make sure that your WE versions are in sync.\n" + "** Things may break! Please make sure that your WE versions are in sync.\n" +
"**********************************************\n", "**********************************************\n",
new Object[]{ new Object[]{
platform.getClass(), platform.getPlatformVersion(), platform.getVersion(), firstSeenVersion, platform.getVersion()
primary.getClass(), primary.getPlatformVersion(), primary.getVersion()
}); });
} }
} else {
firstSeenVersion = platform.getVersion();
} }
} }
/** /**
* Unregister a platform from WorldEdit. * Unregister a platform from WorldEdit.
* </p>
* If the platform has been chosen for any capabilities, then a new
* platform will be found.
* *
* @param platform the platform * @param platform the platform
*/ */
public synchronized boolean unregister(Platform platform) { public synchronized boolean unregister(Platform platform) {
checkNotNull(platform); checkNotNull(platform);
boolean removed = platforms.remove(platform); boolean removed = platforms.remove(platform);
if (removed) { if (removed) {
logger.log(Level.FINE, "Unregistering " + platform.getClass().getCanonicalName() + " from WorldEdit"); logger.log(Level.FINE, "Unregistering " + platform.getClass().getCanonicalName() + " from WorldEdit");
if (platform == primary) { boolean choosePreferred = false;
primary = null;
commandManager.unregister(); // Check whether this platform was chosen to be the preferred one
// for any capability and be sure to remove it
Iterator<Entry<Capability, Platform>> it = preferences.entrySet().iterator();
while (it.hasNext()) {
Entry<Capability, Platform> entry = it.next();
if (entry.getValue().equals(platform)) {
entry.getKey().unload(this, entry.getValue());
it.remove();
choosePreferred = true; // Have to choose new favorites
}
}
if (choosePreferred) {
choosePreferred();
} }
} }
return removed; return removed;
} }
/**
* Get the preferred platform for handling a certain capability. Returns
* null if none is available.
*
* @param capability the capability
* @return the platform
* @throws NoCapablePlatformException thrown if no platform is capable
*/
public synchronized Platform queryCapability(Capability capability) throws NoCapablePlatformException {
Platform platform = preferences.get(checkNotNull(capability));
if (platform != null) {
return platform;
} else {
throw new NoCapablePlatformException("No platform was found supporting " + capability.name());
}
}
/**
* Choose preferred platforms and perform necessary initialization.
*/
private synchronized void choosePreferred() {
for (Capability capability : Capability.values()) {
Platform preferred = findMostPreferred(capability);
if (preferred != null) {
preferences.put(capability, preferred);
capability.initialize(this, preferred);
}
}
}
/**
* Find the most preferred platform for a given capability from the list of
* platforms. This does not use the map of preferred platforms.
*
* @param capability the capability
* @return the most preferred platform, or null if no platform was found
*/
private synchronized @Nullable Platform findMostPreferred(Capability capability) {
Platform preferred = null;
Preference highest = null;
for (Platform platform : platforms) {
Preference preference = platform.getCapabilities().get(capability);
if (preference != null && (highest == null || preference.isPreferredOver(highest))) {
preferred = platform;
highest = preference;
}
}
return preferred;
}
/** /**
* Get a list of loaded platforms. * Get a list of loaded platforms.
* </p> * </p>
@ -134,12 +209,41 @@ public class PlatformManager {
} }
/** /**
* Get the primary platform. * Given a world, possibly return the same world but using a different
* platform preferred for world editing operations.
* *
* @return the primary platform (may be null) * @param base the world to match
* @return the preferred world, if one was found, otherwise the given world
*/ */
public @Nullable Platform getPrimaryPlatform() { public World getWorldForEditing(World base) {
return primary; checkNotNull(base);
World match = queryCapability(Capability.WORLD_EDITING).matchWorld(base);
return match != null ? match : base;
}
/**
* Given an actor, return a new one that may use a different platform
* for permissions and world editing.
*
* @param base the base actor to match
* @return a new delegate actor
*/
@SuppressWarnings("unchecked")
public <T extends Actor> T createProxyActor(T base) {
checkNotNull(base);
if (base instanceof Player) {
Player player = (Player) base;
Player permActor = queryCapability(Capability.PERMISSIONS).matchPlayer(player);
if (permActor == null) {
permActor = player;
}
return (T) new PlayerProxy(player, permActor, getWorldForEditing(player.getWorld()));
} else {
return base;
}
} }
/** /**
@ -160,26 +264,7 @@ public class PlatformManager {
* @return the configuration * @return the configuration
*/ */
public LocalConfiguration getConfiguration() { public LocalConfiguration getConfiguration() {
Platform platform = primary; return queryCapability(Capability.CONFIGURATION).getConfiguration();
if (platform != null) {
return platform.getConfiguration();
} else {
return defaultConfig;
}
}
/**
* Return a {@link Platform}.
*
* @return a {@link Platform}
* @throws IllegalStateException if no platform has been registered
*/
public Platform getPlatform() throws IllegalStateException {
Platform platform = primary;
if (platform != null) {
return platform;
} else {
throw new IllegalStateException("No platform has been registered");
}
} }
/** /**
@ -188,22 +273,23 @@ public class PlatformManager {
* @return a {@link ServerInterface} * @return a {@link ServerInterface}
* @throws IllegalStateException if no platform has been registered * @throws IllegalStateException if no platform has been registered
*/ */
@SuppressWarnings("deprecation")
public ServerInterface getServerInterface() throws IllegalStateException { public ServerInterface getServerInterface() throws IllegalStateException {
Platform platform = primary; return ServerInterfaceAdapter.adapt(queryCapability(Capability.USER_COMMANDS));
if (platform != null) {
if (platform instanceof ServerInterface) {
return (ServerInterface) platform;
} else {
return ServerInterfaceAdapter.adapt(platform);
}
} else {
throw new IllegalStateException("No platform has been registered");
}
} }
@Subscribe
public void handlePlatformReady(PlatformReadyEvent event) {
choosePreferred();
}
@SuppressWarnings("deprecation")
@Subscribe @Subscribe
public void handleBlockInteract(BlockInteractEvent event) { public void handleBlockInteract(BlockInteractEvent event) {
Actor actor = event.getCause(); // Create a proxy actor with a potentially different world for
// making changes to the world
Actor actor = createProxyActor(event.getCause());
Location location = event.getLocation(); Location location = event.getLocation();
Vector vector = location.toVector(); Vector vector = location.toVector();
@ -232,24 +318,19 @@ public class PlatformManager {
return; return;
} }
if (player instanceof LocalPlayer) { // Temporary workaround if (player.isHoldingPickAxe() && session.hasSuperPickAxe()) {
LocalPlayer localPlayer = (LocalPlayer) player; final BlockTool superPickaxe = session.getSuperPickaxe();
WorldVector worldVector = new WorldVector(location); if (superPickaxe != null && superPickaxe.canUse(player)) {
event.setCancelled(superPickaxe.actPrimary(queryCapability(Capability.WORLD_EDITING), getConfiguration(), player, session, location));
if (player.isHoldingPickAxe() && session.hasSuperPickAxe()) { return;
final BlockTool superPickaxe = session.getSuperPickaxe();
if (superPickaxe != null && superPickaxe.canUse(localPlayer)) {
event.setCancelled(superPickaxe.actPrimary(getServerInterface(), getConfiguration(), localPlayer, session, worldVector));
return;
}
} }
}
Tool tool = session.getTool(player.getItemInHand()); Tool tool = session.getTool(player.getItemInHand());
if (tool != null && tool instanceof DoubleActionBlockTool) { if (tool != null && tool instanceof DoubleActionBlockTool) {
if (tool.canUse(localPlayer)) { if (tool.canUse(player)) {
((DoubleActionBlockTool) tool).actSecondary(getServerInterface(), getConfiguration(), localPlayer, session, worldVector); ((DoubleActionBlockTool) tool).actSecondary(queryCapability(Capability.WORLD_EDITING), getConfiguration(), player, session, location);
event.setCancelled(true); event.setCancelled(true);
}
} }
} }
@ -272,25 +353,24 @@ public class PlatformManager {
return; return;
} }
if (player instanceof LocalPlayer) { // Temporary workaround Tool tool = session.getTool(player.getItemInHand());
LocalPlayer localPlayer = (LocalPlayer) player; if (tool != null && tool instanceof BlockTool) {
WorldVector worldVector = new WorldVector(location); if (tool.canUse(player)) {
((BlockTool) tool).actPrimary(queryCapability(Capability.WORLD_EDITING), getConfiguration(), player, session, location);
Tool tool = session.getTool(player.getItemInHand()); event.setCancelled(true);
if (tool != null && tool instanceof BlockTool) {
if (tool.canUse(localPlayer)) {
((BlockTool) tool).actPrimary(getServerInterface(), getConfiguration(), localPlayer, session, worldVector);
event.setCancelled(true);
}
} }
} }
} }
} }
} }
@SuppressWarnings("deprecation")
@Subscribe @Subscribe
public void handlePlayerInput(PlayerInputEvent event) { public void handlePlayerInput(PlayerInputEvent event) {
Player player = event.getPlayer(); // Create a proxy actor with a potentially different world for
// making changes to the world
Player player = createProxyActor(event.getPlayer());
World world = player.getWorld();
switch (event.getInputType()) { switch (event.getInputType()) {
case PRIMARY: { case PRIMARY: {
@ -316,16 +396,12 @@ public class PlatformManager {
LocalSession session = worldEdit.getSessionManager().get(player); LocalSession session = worldEdit.getSessionManager().get(player);
if (player instanceof LocalPlayer) { // Temporary workaround Tool tool = session.getTool(player.getItemInHand());
LocalPlayer localPlayer = (LocalPlayer) player; if (tool != null && tool instanceof DoubleActionTraceTool) {
if (tool.canUse(player)) {
Tool tool = session.getTool(player.getItemInHand()); ((DoubleActionTraceTool) tool).actSecondary(queryCapability(Capability.WORLD_EDITING), getConfiguration(), player, session);
if (tool != null && tool instanceof DoubleActionTraceTool) { event.setCancelled(true);
if (tool.canUse(localPlayer)) { return;
((DoubleActionTraceTool) tool).actSecondary(getServerInterface(), getConfiguration(), localPlayer, session);
event.setCancelled(true);
return;
}
} }
} }
@ -352,16 +428,12 @@ public class PlatformManager {
LocalSession session = worldEdit.getSessionManager().get(player); LocalSession session = worldEdit.getSessionManager().get(player);
if (player instanceof LocalPlayer) { // Temporary workaround Tool tool = session.getTool(player.getItemInHand());
LocalPlayer localPlayer = (LocalPlayer) player; if (tool != null && tool instanceof TraceTool) {
if (tool.canUse(player)) {
Tool tool = session.getTool(player.getItemInHand()); ((TraceTool) tool).actPrimary(queryCapability(Capability.WORLD_EDITING), getConfiguration(), player, session);
if (tool != null && tool instanceof TraceTool) { event.setCancelled(true);
if (tool.canUse(localPlayer)) { return;
((TraceTool) tool).actPrimary(getServerInterface(), getConfiguration(), localPlayer, session);
event.setCancelled(true);
return;
}
} }
} }
@ -370,13 +442,5 @@ public class PlatformManager {
} }
} }
/**
* A default configuration for when none is set.
*/
private static class DefaultConfiguration extends LocalConfiguration {
@Override
public void load() {
}
}
} }

View File

@ -0,0 +1,125 @@
/*
* 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.extension.platform;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldVector;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import static com.google.common.base.Preconditions.checkNotNull;
class PlayerProxy extends AbstractPlayerActor {
private final Player basePlayer;
private final Actor permActor;
private final World world;
PlayerProxy(Player basePlayer, Actor permActor, World world) {
checkNotNull(basePlayer);
checkNotNull(permActor);
checkNotNull(world);
this.basePlayer = basePlayer;
this.permActor = permActor;
this.world = world;
}
@Override
public int getItemInHand() {
return basePlayer.getItemInHand();
}
@Override
public void giveItem(int type, int amount) {
basePlayer.giveItem(type, amount);
}
@Override
public BlockBag getInventoryBlockBag() {
return basePlayer.getInventoryBlockBag();
}
@Override
public String getName() {
return basePlayer.getName();
}
@Override
public Location getLocation() {
return basePlayer.getLocation();
}
@Override
public WorldVector getPosition() {
return basePlayer.getPosition();
}
@Override
public double getPitch() {
return basePlayer.getPitch();
}
@Override
public double getYaw() {
return basePlayer.getYaw();
}
@Override
public void setPosition(Vector pos, float pitch, float yaw) {
basePlayer.setPosition(pos, pitch, yaw);
}
@Override
public World getWorld() {
return world;
}
@Override
public void printRaw(String msg) {
basePlayer.printRaw(msg);
}
@Override
public void printDebug(String msg) {
basePlayer.printDebug(msg);
}
@Override
public void print(String msg) {
basePlayer.print(msg);
}
@Override
public void printError(String msg) {
basePlayer.printError(msg);
}
@Override
public String[] getGroups() {
return permActor.getGroups();
}
@Override
public boolean hasPermission(String perm) {
return permActor.hasPermission(perm);
}
}

View File

@ -0,0 +1,59 @@
/*
* 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.extension.platform;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Indicates the preference of a platform for a particular
* {@link Capability}.
*/
public enum Preference {
/**
* Indicates that the platform should be preferred for a given capability.
*/
PREFERRED,
/**
* Indicates that preference for a platform is neutral for a given
* capability.
*/
NORMAL,
/**
* Indicates that there should not be a preference for the platform for
* a given capability.
*/
PREFER_OTHERS;
/**
* Returns whether this given preference is preferred over the given
* other preference.
*
* @param other the other preference
* @return true if this preference is greater
*/
public boolean isPreferredOver(Preference other) {
checkNotNull(other);
return ordinal() < other.ordinal();
}
}

View File

@ -22,6 +22,7 @@ package com.sk89q.worldedit.internal;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operation;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
@ -250,7 +251,7 @@ public class LocalWorldAdapter extends LocalWorld {
} }
@Override @Override
public boolean queueBlockBreakEffect(ServerInterface server, Vector position, int blockId, double priority) { public boolean queueBlockBreakEffect(Platform server, Vector position, int blockId, double priority) {
return world.queueBlockBreakEffect(server, position, blockId, priority); return world.queueBlockBreakEffect(server, position, blockId, priority);
} }

View File

@ -19,13 +19,19 @@
package com.sk89q.worldedit.internal; package com.sk89q.worldedit.internal;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.worldedit.BiomeTypes;
import com.sk89q.minecraft.util.commands.CommandsManager; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.ServerInterface;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extension.platform.Preference;
import com.sk89q.worldedit.util.command.Dispatcher;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import javax.annotation.Nullable;
import java.util.List; import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -76,15 +82,25 @@ public class ServerInterfaceAdapter extends ServerInterface {
return platform.getWorlds(); return platform.getWorlds();
} }
@Nullable
@Override @Override
@Deprecated public Player matchPlayer(Player player) {
public void onCommandRegistration(List<Command> commands) { return platform.matchPlayer(player);
platform.onCommandRegistration(commands); }
@Nullable
@Override
public World matchWorld(World world) {
return platform.matchWorld(world);
} }
@Override @Override
public void onCommandRegistration(List<Command> commands, CommandsManager<LocalPlayer> manager) { public void registerCommands(Dispatcher dispatcher) {
platform.onCommandRegistration(commands, manager); platform.registerCommands(dispatcher);
}
@Override
public void registerGameHooks() {
} }
@Override @Override
@ -107,6 +123,11 @@ public class ServerInterfaceAdapter extends ServerInterface {
return platform.getPlatformVersion(); return platform.getPlatformVersion();
} }
@Override
public Map<Capability, Preference> getCapabilities() {
return platform.getCapabilities();
}
/** /**
* Adapt an {@link Platform} instance into a {@link ServerInterface}. * Adapt an {@link Platform} instance into a {@link ServerInterface}.
* *

View File

@ -0,0 +1,39 @@
/*
* 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.annotation;
import com.sk89q.worldedit.Vector;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotates a {@link Vector} parameter to inject a direction.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Direction {
public static final String AIM = "me";
}

View File

@ -0,0 +1,34 @@
/*
* 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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that this value should come from the current selection.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Selection {
}

View File

@ -0,0 +1,40 @@
/*
* 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.minecraft.util.commands.CommandLocals;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.auth.Authorizer;
/**
* Implementation of an authorizer that uses {@link Actor#hasPermission(String)}.
*/
public class ActorAuthorizer implements Authorizer {
@Override
public boolean testPermission(CommandLocals locals, String permission) {
Actor sender = locals.get(Actor.class);
if (sender == null) {
throw new RuntimeException("Uh oh! No 'Actor' specified so that we can check permissions");
} else {
return sender.hasPermission(permission);
}
}
}

View File

@ -0,0 +1,156 @@
/*
* 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.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.command.parametric.AbstractInvokeListener;
import com.sk89q.worldedit.util.command.parametric.InvokeHandler;
import com.sk89q.worldedit.util.command.parametric.ParameterData;
import com.sk89q.worldedit.util.command.parametric.ParameterException;
import java.io.Closeable;
import java.lang.reflect.Method;
import java.util.logging.Handler;
import java.util.logging.Logger;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Logs called commands to a logger.
*/
public class CommandLoggingHandler extends AbstractInvokeListener implements InvokeHandler, Closeable {
private final WorldEdit worldEdit;
private final Logger logger;
/**
* Create a new instance.
*
* @param worldEdit an instance of WorldEdit
* @param logger the logger to send messages to
*/
public CommandLoggingHandler(WorldEdit worldEdit, Logger logger) {
checkNotNull(worldEdit);
checkNotNull(logger);
this.worldEdit = worldEdit;
this.logger = logger;
}
@Override
public void preProcess(Object object, Method method, ParameterData[] parameters, CommandContext context) throws CommandException, ParameterException {
}
@Override
public void preInvoke(Object object, Method method, ParameterData[] parameters, Object[] args, CommandContext context) throws CommandException {
Logging loggingAnnotation = method.getAnnotation(Logging.class);
Logging.LogMode logMode;
StringBuilder builder = new StringBuilder();
if (loggingAnnotation == null) {
logMode = null;
} else {
logMode = loggingAnnotation.value();
}
Actor sender = context.getLocals().get(Actor.class);
Player player;
if (sender == null) {
return;
}
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
builder.append("WorldEdit: ").append(sender.getName());
if (sender.isPlayer()) {
builder.append(" (in \"" + player.getWorld().getName() + "\")");
}
builder.append(": ").append(context.getCommand());
if (context.argsLength() > 0) {
builder.append(" ").append(context.getJoinedStrings(0));
}
if (logMode != null && sender.isPlayer()) {
Vector position = player.getPosition();
LocalSession session = worldEdit.getSessionManager().get(player);
switch (logMode) {
case PLACEMENT:
try {
position = session.getPlacementPosition(player);
} catch (IncompleteRegionException e) {
break;
}
/* FALL-THROUGH */
case POSITION:
builder.append(" - Position: " + position);
break;
case ALL:
builder.append(" - Position: " + position);
/* FALL-THROUGH */
case ORIENTATION_REGION:
builder.append(" - Orientation: " + player.getCardinalDirection().name());
/* FALL-THROUGH */
case REGION:
try {
builder.append(" - Region: ")
.append(session.getSelection(player.getWorld()));
} catch (IncompleteRegionException e) {
break;
}
break;
}
}
logger.info(builder.toString());
}
@Override
public void postInvoke(Object object, Method method, ParameterData[] parameters, Object[] args, CommandContext context) throws CommandException {
}
@Override
public InvokeHandler createInvokeHandler() {
return this;
}
@Override
public void close() {
for (Handler h : logger.getHandlers()) {
h.close();
}
}
}

View File

@ -0,0 +1,296 @@
/*
* 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.*;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.input.NoMatchException;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.internal.annotation.Direction;
import com.sk89q.worldedit.internal.annotation.Selection;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.util.TreeGenerator.TreeType;
import com.sk89q.worldedit.util.command.parametric.*;
import java.util.Arrays;
/**
* Binds standard WorldEdit classes such as {@link Player} and {@link LocalSession}.
*/
public class WorldEditBinding extends BindingHelper {
private final WorldEdit worldEdit;
/**
* Create a new instance.
*
* @param worldEdit the WorldEdit instance to bind to
*/
public WorldEditBinding(WorldEdit worldEdit) {
this.worldEdit = worldEdit;
}
/**
* Gets a selection from a {@link ArgumentStack}.
*
* @param context the context
* @param selection the annotation
* @return a selection
* @throws IncompleteRegionException if no selection is available
* @throws ParameterException on other error
*/
@BindingMatch(classifier = Selection.class,
type = Region.class,
behavior = BindingBehavior.PROVIDES)
public Object getSelection(ArgumentStack context, Selection selection) throws IncompleteRegionException, ParameterException {
Player sender = getPlayer(context);
LocalSession session = worldEdit.getSessionManager().get(sender);
return session.getSelection(sender.getWorld());
}
/**
* Gets an {@link EditSession} from a {@link ArgumentStack}.
*
* @param context the context
* @return an edit session
* @throws ParameterException on other error
*/
@BindingMatch(type = EditSession.class,
behavior = BindingBehavior.PROVIDES)
public EditSession getEditSession(ArgumentStack context) throws ParameterException {
Player sender = getPlayer(context);
LocalSession session = worldEdit.getSessionManager().get(sender);
EditSession editSession = session.createEditSession(sender);
editSession.enableQueue();
context.getContext().getLocals().put(EditSession.class, editSession);
session.tellVersion(sender);
return editSession;
}
/**
* Gets an {@link LocalSession} from a {@link ArgumentStack}.
*
* @param context the context
* @return a local session
* @throws ParameterException on error
*/
@BindingMatch(type = LocalSession.class,
behavior = BindingBehavior.PROVIDES)
public LocalSession getLocalSession(ArgumentStack context) throws ParameterException {
Player sender = getPlayer(context);
return worldEdit.getSessionManager().get(sender);
}
/**
* Gets an {@link Actor} from a {@link ArgumentStack}.
*
* @param context the context
* @return a local player
* @throws ParameterException on error
*/
@BindingMatch(type = Actor.class,
behavior = BindingBehavior.PROVIDES)
public Actor getActor(ArgumentStack context) throws ParameterException {
Actor sender = context.getContext().getLocals().get(Actor.class);
if (sender == null) {
throw new ParameterException("Missing 'Actor'");
} else {
return sender;
}
}
/**
* Gets an {@link Player} from a {@link ArgumentStack}.
*
* @param context the context
* @return a local player
* @throws ParameterException on error
*/
@BindingMatch(type = Player.class,
behavior = BindingBehavior.PROVIDES)
public Player getPlayer(ArgumentStack context) throws ParameterException {
Actor sender = context.getContext().getLocals().get(Actor.class);
if (sender == null) {
throw new ParameterException("No player to get a session for");
} else if (sender instanceof Player) {
return (Player) sender;
} else {
throw new ParameterException("Caller is not a player");
}
}
/**
* Gets an {@link BaseBlock} from a {@link ArgumentStack}.
*
* @param context the context
* @return a pattern
* @throws ParameterException on error
* @throws WorldEditException on error
*/
@BindingMatch(type = BaseBlock.class,
behavior = BindingBehavior.CONSUMES,
consumedCount = 1)
public BaseBlock getBaseBlock(ArgumentStack context) throws ParameterException, WorldEditException {
Actor actor = context.getContext().getLocals().get(Actor.class);
ParserContext parserContext = new ParserContext();
parserContext.setActor(context.getContext().getLocals().get(Actor.class));
if (actor instanceof Entity) {
parserContext.setWorld(((Entity) actor).getWorld());
}
parserContext.setSession(worldEdit.getSessionManager().get(actor));
try {
return worldEdit.getBlockRegistry().parseFromInput(context.next(), parserContext);
} catch (NoMatchException e) {
throw new ParameterException(e.getMessage(), e);
}
}
/**
* Gets an {@link Pattern} from a {@link ArgumentStack}.
*
* @param context the context
* @return a pattern
* @throws ParameterException on error
* @throws WorldEditException on error
*/
@BindingMatch(type = Pattern.class,
behavior = BindingBehavior.CONSUMES,
consumedCount = 1)
public Pattern getPattern(ArgumentStack context) throws ParameterException, WorldEditException {
Actor actor = context.getContext().getLocals().get(Actor.class);
ParserContext parserContext = new ParserContext();
parserContext.setActor(context.getContext().getLocals().get(Actor.class));
if (actor instanceof Entity) {
parserContext.setWorld(((Entity) actor).getWorld());
}
parserContext.setSession(worldEdit.getSessionManager().get(actor));
try {
return worldEdit.getPatternRegistry().parseFromInput(context.next(), parserContext);
} catch (NoMatchException e) {
throw new ParameterException(e.getMessage(), e);
}
}
/**
* Gets an {@link Mask} from a {@link ArgumentStack}.
*
* @param context the context
* @return a pattern
* @throws ParameterException on error
* @throws WorldEditException on error
*/
@BindingMatch(type = Mask.class,
behavior = BindingBehavior.CONSUMES,
consumedCount = 1)
public Mask getMask(ArgumentStack context) throws ParameterException, WorldEditException {
Actor actor = context.getContext().getLocals().get(Actor.class);
ParserContext parserContext = new ParserContext();
parserContext.setActor(context.getContext().getLocals().get(Actor.class));
if (actor instanceof Entity) {
parserContext.setWorld(((Entity) actor).getWorld());
}
parserContext.setSession(worldEdit.getSessionManager().get(actor));
try {
return worldEdit.getMaskRegistry().parseFromInput(context.next(), parserContext);
} catch (NoMatchException e) {
throw new ParameterException(e.getMessage(), e);
}
}
/**
* Get a direction from the player.
*
* @param context the context
* @param direction the direction annotation
* @return a pattern
* @throws ParameterException on error
* @throws UnknownDirectionException on an unknown direction
*/
@BindingMatch(classifier = Direction.class,
type = Vector.class,
behavior = BindingBehavior.CONSUMES,
consumedCount = 1)
public Vector getDirection(ArgumentStack context, Direction direction)
throws ParameterException, UnknownDirectionException {
Player sender = getPlayer(context);
return worldEdit.getDirection(sender, context.next());
}
/**
* Gets an {@link TreeType} from a {@link ArgumentStack}.
*
* @param context the context
* @return a pattern
* @throws ParameterException on error
* @throws WorldEditException on error
*/
@BindingMatch(type = TreeType.class,
behavior = BindingBehavior.CONSUMES,
consumedCount = 1)
public TreeType getTreeType(ArgumentStack context) throws ParameterException, WorldEditException {
String input = context.next();
if (input != null) {
TreeType type = TreeGenerator.lookup(input);
if (type != null) {
return type;
} else {
throw new ParameterException(
String.format("Can't recognize tree type '%s' -- choose from: %s", input, Arrays.toString(TreeType.values())));
}
} else {
return TreeType.TREE;
}
}
/**
* Gets an {@link BiomeType} from a {@link ArgumentStack}.
*
* @param context the context
* @return a pattern
* @throws ParameterException on error
* @throws WorldEditException on error
*/
@BindingMatch(type = BiomeType.class,
behavior = BindingBehavior.CONSUMES,
consumedCount = 1)
public BiomeType getBiomeType(ArgumentStack context) throws ParameterException, WorldEditException {
String input = context.next();
if (input != null) {
BiomeType type = worldEdit.getServer().getBiomes().get(input);
if (type != null) {
return type;
} else {
throw new ParameterException(
String.format("Can't recognize biome type '%s' -- use //biomelist to list available types", input));
}
} else {
throw new ParameterException(
"This command takes a 'default' biome if one is not set, except there is no particular " +
"biome that should be 'default', so the command should not be taking a default biome");
}
}
}

View File

@ -0,0 +1,156 @@
/*
* 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.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldedit.command.InsufficientArgumentsException;
import com.sk89q.worldedit.internal.expression.ExpressionException;
import com.sk89q.worldedit.regions.RegionOperationException;
import com.sk89q.worldedit.util.command.parametric.ExceptionConverterHelper;
import com.sk89q.worldedit.util.command.parametric.ExceptionMatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* converts WorldEdit exceptions and converts them into {@link CommandException}s.
*/
public class WorldEditExceptionConverter extends ExceptionConverterHelper {
private static final Pattern numberFormat = Pattern.compile("^For input string: \"(.*)\"$");
private final WorldEdit worldEdit;
public WorldEditExceptionConverter(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
}
@ExceptionMatch
public void convert(PlayerNeededException e) throws CommandException {
throw new CommandException(e.getMessage());
}
@ExceptionMatch
public void convert(NumberFormatException e) throws CommandException {
final Matcher matcher = numberFormat.matcher(e.getMessage());
if (matcher.matches()) {
throw new CommandException("Number expected; string \"" + matcher.group(1)
+ "\" given.");
} else {
throw new CommandException("Number expected; string given.");
}
}
@ExceptionMatch
public void convert(IncompleteRegionException e) throws CommandException {
throw new CommandException("Make a region selection first.");
}
@ExceptionMatch
public void convert(UnknownItemException e) throws CommandException {
throw new CommandException("Block name '" + e.getID() + "' was not recognized.");
}
@ExceptionMatch
public void convert(InvalidItemException e) throws CommandException {
throw new CommandException(e.getMessage());
}
@ExceptionMatch
public void convert(DisallowedItemException e) throws CommandException {
throw new CommandException("Block '" + e.getID()
+ "' not allowed (see WorldEdit configuration).");
}
@ExceptionMatch
public void convert(MaxChangedBlocksException e) throws CommandException {
throw new CommandException("Max blocks changed in an operation reached ("
+ e.getBlockLimit() + ").");
}
@ExceptionMatch
public void convert(MaxBrushRadiusException e) throws CommandException {
throw new CommandException("Maximum brush radius (in configuration): " + worldEdit.getConfiguration().maxBrushRadius);
}
@ExceptionMatch
public void convert(MaxRadiusException e) throws CommandException {
throw new CommandException("Maximum radius (in configuration): " + worldEdit.getConfiguration().maxRadius);
}
@ExceptionMatch
public void convert(UnknownDirectionException e) throws CommandException {
throw new CommandException("Unknown direction: " + e.getDirection());
}
@ExceptionMatch
public void convert(InsufficientArgumentsException e) throws CommandException {
throw new CommandException(e.getMessage());
}
@ExceptionMatch
public void convert(RegionOperationException e) throws CommandException {
throw new CommandException(e.getMessage());
}
@ExceptionMatch
public void convert(ExpressionException e) throws CommandException {
throw new CommandException(e.getMessage());
}
@ExceptionMatch
public void convert(EmptyClipboardException e) throws CommandException {
throw new CommandException("Your clipboard is empty. Use //copy first.");
}
@ExceptionMatch
public void convert(InvalidFilenameException e) throws CommandException {
throw new CommandException("Filename '" + e.getFilename() + "' invalid: "
+ e.getMessage());
}
@ExceptionMatch
public void convert(FilenameResolutionException e) throws CommandException {
throw new CommandException(
"File '" + e.getFilename() + "' resolution error: " + e.getMessage());
}
@ExceptionMatch
public void convert(InvalidToolBindException e) throws CommandException {
throw new CommandException("Can't bind tool to "
+ ItemType.toHeldName(e.getItemId()) + ": " + e.getMessage());
}
@ExceptionMatch
public void convert(FileSelectionAbortedException e) throws CommandException {
throw new CommandException("File selection aborted.");
}
@ExceptionMatch
public void convert(WorldEditException e) throws CommandException {
throw new CommandException(e.getMessage());
}
}

View File

@ -19,24 +19,18 @@
package com.sk89q.worldedit.scripting; package com.sk89q.worldedit.scripting;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.command.InsufficientArgumentsException;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.patterns.Pattern;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import com.sk89q.worldedit.DisallowedItemException;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.FilenameException;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.ServerInterface;
import com.sk89q.worldedit.UnknownItemException;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.command.InsufficientArgumentsException;
import com.sk89q.worldedit.patterns.Pattern;
/** /**
* The context given to scripts. * The context given to scripts.
@ -48,8 +42,8 @@ public class CraftScriptContext extends CraftScriptEnvironment {
private String[] args; private String[] args;
public CraftScriptContext(WorldEdit controller, public CraftScriptContext(WorldEdit controller,
ServerInterface server, LocalConfiguration config, Platform server, LocalConfiguration config,
LocalSession session, LocalPlayer player, String[] args) { LocalSession session, Player player, String[] args) {
super(controller, server, config, session, player); super(controller, server, config, session, player);
this.args = args; this.args = args;
} }
@ -74,7 +68,7 @@ public class CraftScriptContext extends CraftScriptEnvironment {
* *
* @return * @return
*/ */
public LocalPlayer getPlayer() { public Player getPlayer() {
return player; return player;
} }

View File

@ -20,24 +20,25 @@
package com.sk89q.worldedit.scripting; package com.sk89q.worldedit.scripting;
import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.ServerInterface;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Platform;
public abstract class CraftScriptEnvironment { public abstract class CraftScriptEnvironment {
protected WorldEdit controller; protected WorldEdit controller;
protected LocalPlayer player; protected Player player;
protected LocalConfiguration config; protected LocalConfiguration config;
protected LocalSession session; protected LocalSession session;
protected ServerInterface server; protected Platform server;
public CraftScriptEnvironment(WorldEdit controller, ServerInterface server, public CraftScriptEnvironment(WorldEdit controller, Platform server, LocalConfiguration config, LocalSession session, Player player) {
LocalConfiguration config, LocalSession session, LocalPlayer player) {
this.controller = controller; this.controller = controller;
this.player = player; this.player = player;
this.config = config; this.config = config;
this.server = server; this.server = server;
this.session = session; this.session = session;
} }
} }

View File

@ -0,0 +1,38 @@
/*
* 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.util.auth;
import com.sk89q.minecraft.util.commands.CommandLocals;
/**
* Tests whether permission is granted.
*/
public interface Authorizer {
/**
* Tests whether permission is granted for the given context.
*
* @param locals locals
* @param permission the permission string
* @return true if permitted
*/
boolean testPermission(CommandLocals locals, String permission);
}

View File

@ -0,0 +1,35 @@
/*
* 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.util.auth;
import com.sk89q.minecraft.util.commands.CommandLocals;
/**
* An implementation of {@link Authorizer} that always returns false for
* tests of permissions.
*/
public class NullAuthorizer implements Authorizer {
@Override
public boolean testPermission(CommandLocals locals, String permission) {
return false;
}
}

View File

@ -0,0 +1,78 @@
/*
* 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.util.command;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandLocals;
import java.util.List;
import java.util.Set;
/**
* A command that can be executed.
*/
public interface CommandCallable {
/**
* Get a list of value flags used by this command.
*
* @return a list of value flags
*/
Set<Character> getValueFlags();
/**
* Execute the correct command based on the input.
* </p>
* The implementing class must perform the necessary permission checks.
*
* @param arguments the arguments
* @param locals the locals
* @param parentCommands a list of parent commands, with the first most entry being the top-level command
* @return the called command, or null if there was no command found
* @throws CommandException thrown on a command error
*/
boolean call(String arguments, CommandLocals locals, String[] parentCommands) throws CommandException;
/**
* Get a list of suggestions based on input.
*
* @param arguments the arguments entered up to this point
* @param locals the locals
* @return a list of suggestions
* @throws CommandException thrown if there was a parsing error
*/
List<String> getSuggestions(String arguments, CommandLocals locals) throws CommandException;
/**
* Get an object describing this command.
*
* @return the command description
*/
Description getDescription();
/**
* Test whether this command can be executed with the given context.
*
* @param locals the locals
* @return true if execution is permitted
*/
boolean testPermission(CommandLocals locals);
}

View File

@ -0,0 +1,88 @@
/*
* 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.util.command;
import java.util.Arrays;
/**
* Tracks a command registration.
*/
public class CommandMapping {
private final String[] aliases;
private final CommandCallable callable;
/**
* Create a new instance.
*
* @param callable the command callable
* @param alias a list of all aliases, where the first one is the primary one
*/
public CommandMapping(CommandCallable callable, String... alias) {
super();
this.aliases = alias;
this.callable = callable;
}
/**
* Get the primary alias.
*
* @return the primary alias
*/
public String getPrimaryAlias() {
return aliases[0];
}
/**
* Get a list of all aliases.
*
* @return aliases
*/
public String[] getAllAliases() {
return aliases;
}
/**
* Get the callable
*
* @return the callable
*/
public CommandCallable getCallable() {
return callable;
}
/**
* Get the {@link Description} form the callable.
*
* @return the description
*/
public Description getDescription() {
return getCallable().getDescription();
}
@Override
public String toString() {
return "CommandMapping{" +
"aliases=" + Arrays.toString(aliases) +
", callable=" + callable +
'}';
}
}

View File

@ -0,0 +1,70 @@
/*
* 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.util.command;
import java.util.List;
/**
* A description of a command.
*/
public interface Description {
/**
* Get the list of parameters for this command.
*
* @return a list of parameters
*/
List<Parameter> getParameters();
/**
* Get a short one-line description of this command.
*
* @return a description, or null if no description is available
*/
String getShortDescription();
/**
* Get a longer help text about this command.
*
* @return a help text, or null if no help is available
*/
String getHelp();
/**
* Get the usage string of this command.
*
* <p>A usage string may look like
* <code>[-w &lt;world&gt;] &lt;var1&gt; &lt;var2&gt;</code>.</p>
*
* @return a usage string
*/
String getUsage();
/**
* Get a list of permissions that the player may have to have permission.
*
* <p>Permission data may or may not be available. This is only useful as a
* potential hint.</p>
*
* @return the list of permissions
*/
List<String> getPermissions();
}

View File

@ -0,0 +1,85 @@
/*
* 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.util.command;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Set;
/**
* Executes a command based on user input.
*/
public interface Dispatcher extends CommandCallable {
/**
* Register a command with this dispatcher.
*
* @param callable the command executor
* @param alias a list of aliases, where the first alias is the primary name
*/
void registerCommand(CommandCallable callable, String... alias);
/**
* Get a list of commands. Each command, regardless of how many aliases
* it may have, will only appear once in the returned set.
*
* <p>The returned collection cannot be modified.</p>
*
* @return a list of registrations
*/
Set<CommandMapping> getCommands();
/**
* Get a list of primary aliases.
*
* <p>The returned collection cannot be modified.</p>
*
* @return a list of aliases
*/
Collection<String> getPrimaryAliases();
/**
* Get a list of all the command aliases, which includes the primary alias.
*
* <p>A command may have more than one alias assigned to it. The returned
* collection cannot be modified.</p>
*
* @return a list of aliases
*/
Collection<String> getAliases();
/**
* Get the {@link CommandCallable} associated with an alias. Returns
* null if no command is named by the given alias.
*
* @param alias the alias
* @return the command mapping (null if not found)
*/
@Nullable CommandMapping get(String alias);
/**
* Returns whether the dispatcher contains a registered command for the given alias.
*
* @param alias the alias
* @return true if a registered command exists
*/
boolean contains(String alias);
}

Some files were not shown because too many files have changed in this diff Show More