Projects >> WorldEdit >>8f1943fd84cdd1b6e1f572fc223c291686b87d93

Chunk
Conflicting content
<<<<<<< HEAD:src/bukkit/java/com/sk89q/worldedit/bukkit/WorldEditPlugin.java
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

package com.sk89q.worldedit.bukkit;

import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.wepif.PermissionsResolverManager;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.bukkit.selections.CuboidSelection;
import com.sk89q.worldedit.bukkit.selections.CylinderSelection;
import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection;
import com.sk89q.worldedit.bukkit.selections.Selection;
import com.sk89q.worldedit.event.platform.PlatformReadyEvent;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.regions.*;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.*;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

/**
 * Plugin for Bukkit.
 *
 * @author sk89q
 */
public class WorldEditPlugin extends JavaPlugin {

    /**
     * The name of the CUI's plugin channel registration
     */
    public static final String CUI_PLUGIN_CHANNEL = "WECUI";

    /**
     * The server interface that all server-related API goes through.
     */
    private BukkitServerInterface server;
    /**
     * Main WorldEdit instance.
     */
    private WorldEdit controller;
    /**
     * Deprecated API.
     */
    private WorldEditAPI api;

    /**
     * Holds the configuration for WorldEdit.
     */
    private BukkitConfiguration config;

    /**
     * Called on plugin enable.
     */
    @Override
    public void onEnable() {
        final String pluginYmlVersion = getDescription().getVersion();
        final String manifestVersion = WorldEdit.getVersion();

        if (!manifestVersion.equalsIgnoreCase(pluginYmlVersion)) {
            WorldEdit.setVersion(manifestVersion + " (" + pluginYmlVersion + ")");
        }

        // Make the data folders that WorldEdit uses
        getDataFolder().mkdirs();
        File targetDir = new File(getDataFolder() + File.separator + "nmsblocks");
        targetDir.mkdir();
        copyNmsBlockClasses(targetDir);

        // Create the default configuration file
        createDefaultConfiguration("config.yml");

        // Set up configuration and such, including the permissions
        // resolver
        config = new BukkitConfiguration(new YAMLProcessor(new File(getDataFolder(), "config.yml"), true), this);
        PermissionsResolverManager.initialize(this);

        // Load the configuration
        config.load();

        // Setup interfaces
        server = new BukkitServerInterface(this, getServer());
        controller = WorldEdit.getInstance();
        controller.getPlatformManager().register(server);
        api = new WorldEditAPI(this);
        getServer().getMessenger().registerIncomingPluginChannel(this, CUI_PLUGIN_CHANNEL, new CUIChannelListener(this));
        getServer().getMessenger().registerOutgoingPluginChannel(this, CUI_PLUGIN_CHANNEL);
        // Now we can register events!
        getServer().getPluginManager().registerEvents(new WorldEditListener(this), this);

        getServer().getScheduler().runTaskTimerAsynchronously(this, new SessionTimer(controller, getServer()), 120, 120);

        // If we are on MCPC+/Cauldron, then Forge will have already loaded
        // Forge WorldEdit and there's (probably) not going to be any other
        // platforms to be worried about... at the current time of writing
        WorldEdit.getInstance().getEventBus().post(new PlatformReadyEvent());
    }

    private void copyNmsBlockClasses(File target) {
        try {
            JarFile jar = new JarFile(getFile());
            @SuppressWarnings("rawtypes")
            Enumeration entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry jarEntry = (JarEntry) entries.nextElement();
                if (!jarEntry.getName().startsWith("nmsblocks") || jarEntry.isDirectory()) continue;

                File file = new File(target + File.separator + jarEntry.getName().replace("nmsblocks", ""));
                if (file.exists()) continue;

                InputStream is = jar.getInputStream(jarEntry);
                FileOutputStream fos = new FileOutputStream(file);

                fos = new FileOutputStream(file);
                byte[] buf = new byte[8192];
                int length = 0;
                while ((length = is.read(buf)) > 0) {
                    fos.write(buf, 0, length);
                }
                fos.close();
                is.close();
            }
        } catch (Throwable e) {}
    }

    /**
     * Called on plugin disable.
     */
    @Override
    public void onDisable() {
        controller.clearSessions();
        controller.getPlatformManager().unregister(server);
        config.unload();
        server.unregisterCommands();
        this.getServer().getScheduler().cancelTasks(this);
    }

    /**
     * Loads and reloads all configuration.
     */
    protected void loadConfiguration() {
        config.unload();
        config.load();
        getPermissionsResolver().load();
    }

    /**
     * Create a default configuration file from the .jar.
     *
     * @param name
     */
    protected void createDefaultConfiguration(String name) {
        File actual = new File(getDataFolder(), name);
        if (!actual.exists()) {
            InputStream input =
                    null;
            try {
                JarFile file = new JarFile(getFile());
                ZipEntry copy = file.getEntry("defaults/" + name);
                if (copy == null) throw new FileNotFoundException();
                input = file.getInputStream(copy);
            } catch (IOException e) {
                getLogger().severe("Unable to read default configuration: " + name);
            }
            if (input != null) {
                FileOutputStream output = null;

                try {
                    output = new FileOutputStream(actual);
                    byte[] buf = new byte[8192];
                    int length = 0;
                    while ((length = input.read(buf)) > 0) {
                        output.write(buf, 0, length);
                    }

                    getLogger().info("Default configuration file written: " + name);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (input != null) {
                            input.close();
                        }
                    } catch (IOException e) {}

                    try {
                        if (output != null) {
                            output.close();
                        }
                    } catch (IOException e) {}
                }
            }
        }
    }

    /**
     * Called on WorldEdit command.
     */
    @Override
    public boolean onCommand(CommandSender sender, org.bukkit.command.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();

        controller.handleCommand(wrapCommandSender(sender), split);

        return true;
    }

    /**
     * Gets the session for the player.
     *
     * @param player
     * @return
     */
    public LocalSession getSession(Player player) {
        return controller.getSession(wrapPlayer(player));
    }

    /**
     * Gets the session for the player.
     *
     * @param player
     * @return
     */
    public EditSession createEditSession(Player player) {
        LocalPlayer wePlayer = wrapPlayer(player);
        LocalSession session = controller.getSession(wePlayer);
        BlockBag blockBag = session.getBlockBag(wePlayer);

        EditSession editSession = controller.getEditSessionFactory()
                .getEditSession(wePlayer.getWorld(), session.getBlockChangeLimit(), blockBag, wePlayer);
        editSession.enableQueue();

        return editSession;
    }

    /**
     * Remember an edit session.
     *
     * @param player


     * @param editSession
     */
    public void remember(Player player, EditSession editSession) {
        LocalPlayer wePlayer = wrapPlayer(player);
        LocalSession session = controller.getSession(wePlayer);

        session.remember(editSession);
        editSession.flushQueue();

        controller.flushBlockBag(wePlayer, editSession);
    }

    /**
     * Wrap an operation into an EditSession.
     *
     * @param player
     * @param op
     * @throws Throwable
     */
    public void perform(Player player, WorldEditOperation op)
            throws Throwable {
        LocalPlayer wePlayer = wrapPlayer(player);
        LocalSession session = controller.getSession(wePlayer);

        EditSession editSession = createEditSession(player);
        try {
            op.run(session, wePlayer, editSession);
        } finally {
            remember(player, editSession);
        }
    }

    /**
     * Get the API.
     *
     * @return
     */
    @Deprecated
    public WorldEditAPI getAPI() {
        return api;
    }

    /**
     * Returns the configuration used by WorldEdit.
     *
     * @return
     */
    public BukkitConfiguration getLocalConfiguration() {
        return config;
    }

    /**
     * Get the permissions resolver in use.
     *
     * @return
     */
    public PermissionsResolverManager getPermissionsResolver() {
        return PermissionsResolverManager.getInstance();
    }
    /**
     * Used to wrap a Bukkit Player as a LocalPlayer.
     *
     * @param player
     * @return
     */
    public BukkitPlayer wrapPlayer(Player player) {
        return new BukkitPlayer(this, this.server, player);
    }

    public LocalPlayer wrapCommandSender(CommandSender sender) {
        if (sender instanceof Player) {
            return wrapPlayer((Player) sender);
        }

        return new BukkitCommandSender(this, sender);
    }

    /**
     * Get the server interface.
     *
     * @return
     */
    public ServerInterface getServerInterface() {
        return server;
    }

    BukkitServerInterface getInternalPlatform() {
        return server;
    }

    /**
     * Get WorldEdit.
     *
     * @return
     */
    public WorldEdit getWorldEdit() {
        return controller;
    }

    /**
     * Gets the region selection for the player.
     *
     * @param player
     * @return the selection or null if there was none
     */
    public Selection getSelection(Player player) {
        if (player == null) {
            throw new IllegalArgumentException("Null player not allowed");
        }
        if (!player.isOnline()) {
            throw new IllegalArgumentException("Offline player not allowed");
        }

import com.sk89q.worldedit.regions.CuboidRegion;
        LocalSession session = controller.getSession(wrapPlayer(player));
        RegionSelector selector = session.getRegionSelector(BukkitUtil.getLocalWorld(player.getWorld()));

        try {
            Region region = selector.getRegion();
            World world = ((BukkitWorld) session.getSelectionWorld()).getWorld();

            if (region instanceof CuboidRegion) {
                return new CuboidSelection(world, selector, (CuboidRegion) region);
            } else if (region instanceof Polygonal2DRegion) {
                return new Polygonal2DSelection(world, selector, (Polygonal2DRegion) region);
            } else if (region instanceof CylinderRegion) {
                return new CylinderSelection(world, selector, (CylinderRegion) region);
            } else {
                return null;
            }
        } catch (IncompleteRegionException e) {
            return null;
        }
    }

    /**
     * Sets the region selection for a player.
     *
     * @param player
     * @param selection
     */
    public void setSelection(Player player, Selection selection) {
        if (player == null) {
            throw new IllegalArgumentException("Null player not allowed");
        }
        if (!player.isOnline()) {
            throw new IllegalArgumentException("Offline player not allowed");
        }
        if (selection == null) {
            throw new IllegalArgumentException("Null selection not allowed");
        }

        LocalSession session = controller.getSession(wrapPlayer(player));
        RegionSelector sel = selection.getRegionSelector();
        session.setRegionSelector(BukkitUtil.getLocalWorld(player.getWorld()), sel);
        session.dispatchCUISelection(wrapPlayer(player));
    }
}
=======
// $Id$
/*
 * WorldEdit
 * Copyright (C) 2010 sk89q  and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see .
*/

package com.sk89q.worldedit.bukkit;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.wepif.PermissionsResolverManager;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.IncompleteRegionException;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.ServerInterface;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditOperation;
import com.sk89q.worldedit.bags.BlockBag;
import com.sk89q.worldedit.bukkit.selections.CuboidSelection;
import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection;
import com.sk89q.worldedit.bukkit.selections.Selection;
import com.sk89q.worldedit.regions.Polygonal2DRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector;

/**
 * Plugin for Bukkit.
 *
 * @author sk89q
 */
public class WorldEditPlugin extends JavaPlugin {

    public static final String CUI_PLUGIN_CHANNEL = "WECUI";
    
    private BukkitServerInterface server;
    private WorldEdit controller;
    private WorldEditAPI api;
    private BukkitConfiguration config;

    @Override
    public void onEnable() {
        final String pluginYmlVersion = getDescription().getVersion();
        final String manifestVersion = WorldEdit.getVersion();

        if (!manifestVersion.equalsIgnoreCase(pluginYmlVersion)) {
            WorldEdit.setVersion(manifestVersion + " (" + pluginYmlVersion + ")");
        }

        // Make the data folders that WorldEdit uses
        getDataFolder().mkdirs();
        File targetDir = new File(getDataFolder() + File.separator + "nmsblocks");
        targetDir.mkdir();
        copyNmsBlockClasses(targetDir);

        // Create the default configuration file
        createDefaultConfiguration("config.yml");

        // Set up configuration and such, including the permissions
        // resolver
        config = new BukkitConfiguration(new YAMLProcessor(new File(getDataFolder(), "config.yml"), true), this);
        PermissionsResolverManager.initialize(this);

        // Load the configuration
        config.load();

        // Setup interfaces
        server = new BukkitServerInterface(this, getServer());
        controller = new WorldEdit(server, config);
        WorldEdit.getInstance().logger.setParent(Bukkit.getLogger());
        api = new WorldEditAPI(this);
        getServer().getMessenger().registerIncomingPluginChannel(this, CUI_PLUGIN_CHANNEL, new CUIChannelListener(this));
        getServer().getMessenger().registerOutgoingPluginChannel(this, CUI_PLUGIN_CHANNEL);
        // Now we can register events!
        getServer().getPluginManager().registerEvents(new WorldEditListener(this), this);

        getServer().getScheduler().scheduleAsyncRepeatingTask(this,
                new SessionTimer(controller, getServer()), 120, 120);
    }

    private void copyNmsBlockClasses(File target) {
        try {
            JarFile jar = new JarFile(getFile());
            Enumeration entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry jarEntry = (JarEntry) entries.nextElement();
                if (!jarEntry.getName().startsWith("nmsblocks") || jarEntry.isDirectory()) continue;

                File file = new File(target + File.separator + jarEntry.getName().replace("nmsblocks", ""));
                if (file.exists()) continue;

                InputStream is = jar.getInputStream(jarEntry);
                FileOutputStream fos = new FileOutputStream(file);

                fos = new FileOutputStream(file);
                byte[] buf = new byte[8192];
                int length = 0;
                while ((length = is.read(buf)) > 0) {
                    fos.write(buf, 0, length);
                }
                fos.close();
                is.close();
            }
        } catch (Throwable e) {}
    }

    /**
     * Called on plugin disable.
     */
    @Override
    public void onDisable() {
        for (Player player : getServer().getOnlinePlayers()) {
            LocalPlayer lPlayer = wrapPlayer(player);
            if (controller.getSession(lPlayer).hasCUISupport()) {
                lPlayer.dispatchCUIHandshake();
            }
        }
        controller.clearSessions();
        controller.getCommandLogger().close();
        config.unload();
        server.unregisterCommands();
        this.getServer().getScheduler().cancelTasks(this);
    }

    /**
     * Loads and reloads all configuration.
     */
    protected void loadConfiguration() {
        config.unload();
        config.load();
        getPermissionsResolver().load();
    }

    /**
     * Create a default configuration file from the .jar.
     *
     * @param name
     */
    protected void createDefaultConfiguration(String name) {
        File actual = new File(getDataFolder(), name);
        if (!actual.exists()) {
            InputStream input =
                    null;
            try {
                JarFile file = new JarFile(getFile());
                ZipEntry copy = file.getEntry("defaults/" + name);
                if (copy == null) throw new FileNotFoundException();
                input = file.getInputStream(copy);
            } catch (IOException e) {
                getLogger().severe("Unable to read default configuration: " + name);
            }
            if (input != null) {
                FileOutputStream output = null;

                try {
                    output = new FileOutputStream(actual);
                    byte[] buf = new byte[8192];
                    int length = 0;
                    while ((length = input.read(buf)) > 0) {
                        output.write(buf, 0, length);
                    }

                    getLogger().info("Default configuration file written: " + name);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (input != null) {
                            input.close();
                        }
                    } catch (IOException e) {}

                    try {
                        if (output != null) {
                            output.close();
                        }
                    } catch (IOException e) {}
                }
            }
        }
    }

    /**
     * Called on WorldEdit command.
     */
    @Override
    public boolean onCommand(CommandSender sender, org.bukkit.command.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();

        controller.handleCommand(wrapCommandSender(sender), split);

        return true;
    }

    /**
     * Gets the session for the player.
     *
     * @param player
     * @return
     */
    public LocalSession getSession(Player player) {
        return controller.getSession(wrapPlayer(player));
    }

    /**
     * Gets the session for the player.
     *
     * @param player
     * @return
     */
    public EditSession createEditSession(Player player) {
        LocalPlayer wePlayer = wrapPlayer(player);
        LocalSession session = controller.getSession(wePlayer);
        BlockBag blockBag = session.getBlockBag(wePlayer);
        EditSession editSession = controller.getEditSessionFactory()
                .getEditSession(wePlayer.getWorld(), session.getBlockChangeLimit(), blockBag, wePlayer);
        editSession.enableQueue();

        return editSession;
    }

    /**
     * Remember an edit session.
     *
     * @param player
     * @param editSession
     */
    public void remember(Player player, EditSession editSession) {
        LocalPlayer wePlayer = wrapPlayer(player);
        LocalSession session = controller.getSession(wePlayer);

        session.remember(editSession);
        editSession.flushQueue();

        controller.flushBlockBag(wePlayer, editSession);
    }

    /**
     * Wrap an operation into an EditSession.
     *
     * @param player
     * @param op
     * @throws Throwable
     */
    public void perform(Player player, WorldEditOperation op)
            throws Throwable {
        LocalPlayer wePlayer = wrapPlayer(player);
        LocalSession session = controller.getSession(wePlayer);

        EditSession editSession = createEditSession(player);
        try {
            op.run(session, wePlayer, editSession);
        } finally {
            remember(player, editSession);
        }
    }

    /**
     * Get the API.
     *
     * @return
     */
    @Deprecated
    public WorldEditAPI getAPI() {
        return api;
    }

    /**
     * Returns the configuration used by WorldEdit.
     *
     * @return
     */
    public BukkitConfiguration getLocalConfiguration() {
        return config;
    }

    /**
     * Get the permissions resolver in use.
     *
     * @return
     */
    public PermissionsResolverManager getPermissionsResolver() {
        return PermissionsResolverManager.getInstance();
    }

    /**
     * Used to wrap a Bukkit Player as a LocalPlayer.
     *
     * @param player
     * @return
     */
    public BukkitPlayer wrapPlayer(Player player) {
        return new BukkitPlayer(this, this.server, player);
    }

    public LocalPlayer wrapCommandSender(CommandSender sender) {
        if (sender instanceof Player) {
            return wrapPlayer((Player) sender);
        }

        return new BukkitCommandSender(this, this.server, sender);
    }

    /**
     * Get the server interface.
     *
     * @return
     */
    public ServerInterface getServerInterface() {
        return server;
    }

    /**
     * Get WorldEdit.
     *
     * @return
     */
    public WorldEdit getWorldEdit() {
        return controller;
    }

    /**
     * Gets the region selection for the player.
     *
     * @param player
     * @return the selection or null if there was none
     */
    public Selection getSelection(Player player) {
        if (player == null) {
            throw new IllegalArgumentException("Null player not allowed");
        }
        if (!player.isOnline()) {
            throw new IllegalArgumentException("Offline player not allowed");
        }

        LocalSession session = controller.getSession(wrapPlayer(player));
        RegionSelector selector = session.getRegionSelector(BukkitUtil.getLocalWorld(player.getWorld()));

        try {
            Region region = selector.getRegion();
            World world = ((BukkitWorld) session.getSelectionWorld()).getWorld();

            if (region instanceof CuboidRegion) {
                return new CuboidSelection(world, selector, (CuboidRegion) region);
            } else if (region instanceof Polygonal2DRegion) {
                return new Polygonal2DSelection(world, selector, (Polygonal2DRegion) region);
            } else {
                return null;
            }
        } catch (IncompleteRegionException e) {
            return null;
        }
    }

    /**
     * Sets the region selection for a player.
     *
     * @param player
     * @param selection
     */
    public void setSelection(Player player, Selection selection) {
        if (player == null) {
            throw new IllegalArgumentException("Null player not allowed");
        }
        if (!player.isOnline()) {
            throw new IllegalArgumentException("Offline player not allowed");
        }
        if (selection == null) {
            throw new IllegalArgumentException("Null selection not allowed");
        }

        LocalSession session = controller.getSession(wrapPlayer(player));
        RegionSelector sel = selection.getRegionSelector();
        session.setRegionSelector(BukkitUtil.getLocalWorld(player.getWorld()), sel);
        session.dispatchCUISelection(wrapPlayer(player));
    }
}
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df:src/main/java/com/sk89q/worldedit/bukkit/WorldEditPlugin.java
Solution content
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

package com.sk89q.worldedit.bukkit;

import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.wepif.PermissionsResolverManager;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.bukkit.selections.CuboidSelection;
import com.sk89q.worldedit.bukkit.selections.CylinderSelection;
import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection;
import com.sk89q.worldedit.bukkit.selections.Selection;
import com.sk89q.worldedit.event.platform.PlatformReadyEvent;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.regions.*;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.*;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

/**
 * Plugin for Bukkit.
 *
 * @author sk89q
 */
public class WorldEditPlugin extends JavaPlugin {

    /**
     * The name of the CUI's plugin channel registration
     */
    public static final String CUI_PLUGIN_CHANNEL = "WECUI";

    /**
        controller.clearSessions();
            }
                            output.close();
        }
                        }
                    } catch (IOException e) {}
     * The server interface that all server-related API goes through.
     */
    private BukkitServerInterface server;
    /**
     * Main WorldEdit instance.
     */
    private WorldEdit controller;
    /**
     * Deprecated API.
     */
    private WorldEditAPI api;

    /**
     * Holds the configuration for WorldEdit.
     */
    private BukkitConfiguration config;

    /**
     * Called on plugin enable.
     */
    @Override
    public void onEnable() {
        final String pluginYmlVersion = getDescription().getVersion();
        final String manifestVersion = WorldEdit.getVersion();

        if (!manifestVersion.equalsIgnoreCase(pluginYmlVersion)) {
            WorldEdit.setVersion(manifestVersion + " (" + pluginYmlVersion + ")");
        }

        // Make the data folders that WorldEdit uses
        getDataFolder().mkdirs();
        File targetDir = new File(getDataFolder() + File.separator + "nmsblocks");
        targetDir.mkdir();
        copyNmsBlockClasses(targetDir);

        // Create the default configuration file
        createDefaultConfiguration("config.yml");

        // Set up configuration and such, including the permissions
        // resolver
        config = new BukkitConfiguration(new YAMLProcessor(new File(getDataFolder(), "config.yml"), true), this);
        PermissionsResolverManager.initialize(this);

        // Load the configuration
        config.load();

        // Setup interfaces
        server = new BukkitServerInterface(this, getServer());
        controller = WorldEdit.getInstance();
        controller.getPlatformManager().register(server);
        api = new WorldEditAPI(this);
        getServer().getMessenger().registerIncomingPluginChannel(this, CUI_PLUGIN_CHANNEL, new CUIChannelListener(this));
        getServer().getMessenger().registerOutgoingPluginChannel(this, CUI_PLUGIN_CHANNEL);
        // Now we can register events!
        getServer().getPluginManager().registerEvents(new WorldEditListener(this), this);

                }
        getServer().getScheduler().runTaskTimerAsynchronously(this, new SessionTimer(controller, getServer()), 120, 120);

        // If we are on MCPC+/Cauldron, then Forge will have already loaded
        // Forge WorldEdit and there's (probably) not going to be any other
        // platforms to be worried about... at the current time of writing
        WorldEdit.getInstance().getEventBus().post(new PlatformReadyEvent());
    }

    private void copyNmsBlockClasses(File target) {
        try {
            JarFile jar = new JarFile(getFile());
            @SuppressWarnings("rawtypes")
            Enumeration entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry jarEntry = (JarEntry) entries.nextElement();
                if (!jarEntry.getName().startsWith("nmsblocks") || jarEntry.isDirectory()) continue;

                File file = new File(target + File.separator + jarEntry.getName().replace("nmsblocks", ""));
                if (file.exists()) continue;

                InputStream is = jar.getInputStream(jarEntry);
                FileOutputStream fos = new FileOutputStream(file);

                fos = new FileOutputStream(file);
                byte[] buf = new byte[8192];
                int length = 0;
                while ((length = is.read(buf)) > 0) {
                    fos.write(buf, 0, length);
                }
                fos.close();
                is.close();
            }
        } catch (Throwable e) {}
    }

    /**
     * Called on plugin disable.
     */
    @Override
    public void onDisable() {
        controller.getPlatformManager().unregister(server);
        config.unload();
        server.unregisterCommands();
        this.getServer().getScheduler().cancelTasks(this);
    }

    /**
     * Loads and reloads all configuration.
     */
    protected void loadConfiguration() {
        config.unload();
        config.load();
        getPermissionsResolver().load();
    }

    /**
     * Create a default configuration file from the .jar.
     *
     * @param name
     */
    protected void createDefaultConfiguration(String name) {
        File actual = new File(getDataFolder(), name);
        if (!actual.exists()) {
            InputStream input =
                    null;
            try {
                JarFile file = new JarFile(getFile());
                ZipEntry copy = file.getEntry("defaults/" + name);
                if (copy == null) throw new FileNotFoundException();
                input = file.getInputStream(copy);
            } catch (IOException e) {
                getLogger().severe("Unable to read default configuration: " + name);
            }
            if (input != null) {
                FileOutputStream output = null;

                try {
                    output = new FileOutputStream(actual);
                    byte[] buf = new byte[8192];
                    int length = 0;
                    while ((length = input.read(buf)) > 0) {
                        output.write(buf, 0, length);
                    }

                    getLogger().info("Default configuration file written: " + name);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (input != null) {
                            input.close();
                        }
                    } catch (IOException e) {}

                    try {
                        if (output != null) {
    }

    /**
     * Called on WorldEdit command.
     */
    @Override
    public boolean onCommand(CommandSender sender, org.bukkit.command.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();

        controller.handleCommand(wrapCommandSender(sender), split);

        return true;
    }

    /**
     * Gets the session for the player.
     *
     * @param player
     * @return
     */
    public LocalSession getSession(Player player) {
        return controller.getSession(wrapPlayer(player));
    }

    /**
     * Gets the session for the player.
     *
     * @param player
     * @return
     */
    public EditSession createEditSession(Player player) {
        LocalPlayer wePlayer = wrapPlayer(player);
        LocalSession session = controller.getSession(wePlayer);
        BlockBag blockBag = session.getBlockBag(wePlayer);

        EditSession editSession = controller.getEditSessionFactory()
                .getEditSession(wePlayer.getWorld(), session.getBlockChangeLimit(), blockBag, wePlayer);
        editSession.enableQueue();

        return editSession;
    }

    /**
     * Remember an edit session.
     *
     * @param player
     * @param editSession
     */
    public void remember(Player player, EditSession editSession) {
        LocalPlayer wePlayer = wrapPlayer(player);
        LocalSession session = controller.getSession(wePlayer);

        session.remember(editSession);
        editSession.flushQueue();

        controller.flushBlockBag(wePlayer, editSession);
    }

    /**
     * Wrap an operation into an EditSession.
     *
     * @param player
     * @param op
     * @throws Throwable
     */
    public void perform(Player player, WorldEditOperation op)
            throws Throwable {
        LocalPlayer wePlayer = wrapPlayer(player);
        LocalSession session = controller.getSession(wePlayer);

        EditSession editSession = createEditSession(player);
        try {
            op.run(session, wePlayer, editSession);
        } finally {
            remember(player, editSession);
        }
    }

    /**
     * Get the API.
     *
     * @return
     */
    @Deprecated
    public WorldEditAPI getAPI() {
        return api;
    }

    /**
     * Returns the configuration used by WorldEdit.
     *
     * @return
     */
    public BukkitConfiguration getLocalConfiguration() {
        return config;
    }

    /**
     * Get the permissions resolver in use.
     *
     * @return
     */
    public PermissionsResolverManager getPermissionsResolver() {
        return PermissionsResolverManager.getInstance();
    }

    /**
     * Used to wrap a Bukkit Player as a LocalPlayer.
     *
     * @param player
     * @return
     */
    public BukkitPlayer wrapPlayer(Player player) {
        return new BukkitPlayer(this, this.server, player);
    }

    public LocalPlayer wrapCommandSender(CommandSender sender) {
        if (sender instanceof Player) {
            return wrapPlayer((Player) sender);
        }

        return new BukkitCommandSender(this, sender);
    }

    /**
     * Get the server interface.
     *
     * @return
     */
    public ServerInterface getServerInterface() {
        return server;
    }

    BukkitServerInterface getInternalPlatform() {
        return server;
    }

    /**
     * Get WorldEdit.
     *
     * @return
     */
    public WorldEdit getWorldEdit() {
        return controller;
    }

    /**
     * Gets the region selection for the player.
     *
     * @param player
     * @return the selection or null if there was none
     */
    public Selection getSelection(Player player) {
        if (player == null) {
            throw new IllegalArgumentException("Null player not allowed");
        }
        if (!player.isOnline()) {
            throw new IllegalArgumentException("Offline player not allowed");
        }

        LocalSession session = controller.getSession(wrapPlayer(player));
        RegionSelector selector = session.getRegionSelector(BukkitUtil.getLocalWorld(player.getWorld()));

        try {
            Region region = selector.getRegion();
            World world = ((BukkitWorld) session.getSelectionWorld()).getWorld();

            if (region instanceof CuboidRegion) {
                return new CuboidSelection(world, selector, (CuboidRegion) region);
            } else if (region instanceof Polygonal2DRegion) {
                return new Polygonal2DSelection(world, selector, (Polygonal2DRegion) region);
            } else if (region instanceof CylinderRegion) {
                return new CylinderSelection(world, selector, (CylinderRegion) region);
            } else {
                return null;
            }
        } catch (IncompleteRegionException e) {
            return null;
        }
    }

    /**
     * Sets the region selection for a player.
     *
     * @param player
     * @param selection
     */
    public void setSelection(Player player, Selection selection) {
        if (player == null) {
            throw new IllegalArgumentException("Null player not allowed");
        }
        if (!player.isOnline()) {
            throw new IllegalArgumentException("Offline player not allowed");
        }
        if (selection == null) {
            throw new IllegalArgumentException("Null selection not allowed");
        }

        LocalSession session = controller.getSession(wrapPlayer(player));
        RegionSelector sel = selection.getRegionSelector();
        session.setRegionSelector(BukkitUtil.getLocalWorld(player.getWorld()), sel);
        session.dispatchCUISelection(wrapPlayer(player));
    }
}
File
WorldEditPlugin.java
Developer's decision
Version 1
Kind of conflict
Class declaration
Comment
Import
Package declaration
Chunk
Conflicting content
package com.sk89q.worldedit;

<<<<<<< HEAD
import com.sk89q.worldedit.extension.platform.AbstractPlatform;
import com.sk89q.worldedit.extension.platform.Platform;
=======
import java.util.Collections;
import java.util.List;
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df

import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandsManager;
Solution content
package com.sk89q.worldedit;

import com.sk89q.worldedit.extension.platform.AbstractPlatform;
import com.sk89q.worldedit.extension.platform.Platform;

/**
 * A legacy abstract class that is to be replaced with {@link Platform}.
 * Extend {@link AbstractPlatform} instead.
 *
 * @deprecated Use {@link Platform} wherever possible
 */
@Deprecated
public abstract class ServerInterface extends AbstractPlatform {
}
File
ServerInterface.java
Developer's decision
Manual
Kind of conflict
Import
Chunk
Conflicting content
 *
 * @deprecated Use {@link Platform} wherever possible
 */
<<<<<<< HEAD
@Deprecated
public abstract class ServerInterface extends AbstractPlatform {
=======
public abstract class ServerInterface {
    /**
     * Resolves an item name to its ID.
     *
     * @param name The name to look up
     * @return The id that corresponds to the name, or -1 if no such ID exists
     */
    public abstract int resolveItem(String name);

    /**
     * Checks if a mob type is valid.
     *
     * @param type The mob type name to check
     * @return Whether the name is a valid mod bype
     */
    public abstract boolean isValidMobType(String type);

    /**
     * Reload WorldEdit configuration.
     */
    public abstract void reload();

    /**
     * Returns all available biomes.
     *
     * @return
     */
    public abstract BiomeTypes getBiomes();

    /**
     * Schedules the given task to be invoked once every period ticks
     * after an initial delay of delay ticks.
     *
     * @param delay Delay in server ticks before executing first repeat
     * @param period Period in server ticks of the task
     * @param task Task to be executed
     * @return Task id number (-1 if scheduling failed)
     */
    public int schedule(long delay, long period, Runnable task) {
        return -1;
    }

    public List getWorlds() {
        return Collections.emptyList();
    }

    @Deprecated
    public void onCommandRegistration(List commands) {
        // Do nothing :)
    }

    public void onCommandRegistration(List commands, CommandsManager manager) {
        onCommandRegistration(commands);
    }
    
    public void registerCommands(Dispatcher dispatcher) {
    }
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df
}
Solution content
 *
 * @deprecated Use {@link Platform} wherever possible
 */
@Deprecated
public abstract class ServerInterface extends AbstractPlatform {
}
File
ServerInterface.java
Developer's decision
Version 1
Kind of conflict
Annotation
Class signature
Comment
Method declaration
Method interface
Chunk
Conflicting content
import com.sk89q.rebar.command.InvalidUsageException;

package com.sk89q.worldedit;

<<<<<<< HEAD
import com.sk89q.minecraft.util.commands.CommandsManager;
=======
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import javax.script.ScriptException;

import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
import com.sk89q.rebar.command.Dispatcher;
import com.sk89q.rebar.command.fluent.CommandGraph;
import com.sk89q.rebar.command.parametric.LegacyCommandsHandler;
import com.sk89q.rebar.command.parametric.ParametricBuilder;
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df
import com.sk89q.worldedit.CuboidClipboard.FlipDirection;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockType;
Solution content
package com.sk89q.worldedit;

import com.sk89q.worldedit.CuboidClipboard.FlipDirection;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockType;
File
WorldEdit.java
Developer's decision
None
Kind of conflict
Import
Chunk
Conflicting content
import com.sk89q.worldedit.CuboidClipboard.FlipDirection;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockType;
<<<<<<< HEAD
import com.sk89q.worldedit.event.platform.BlockInteractEvent;
import com.sk89q.worldedit.event.extent.EditSessionEvent;
import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.event.platform.InputType;
import com.sk89q.worldedit.event.platform.PlayerInputEvent;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extension.platform.PlatformManager;
import com.sk89q.worldedit.extension.registry.BlockRegistry;
import com.sk89q.worldedit.extension.registry.MaskRegistry;
import com.sk89q.worldedit.extension.registry.PatternRegistry;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.function.mask.Masks;
import com.sk89q.worldedit.function.pattern.Patterns;
=======
import com.sk89q.worldedit.blocks.ClothColor;
import com.sk89q.worldedit.blocks.MobSpawnerBlock;
import com.sk89q.worldedit.blocks.NoteBlock;
import com.sk89q.worldedit.blocks.SignBlock;
import com.sk89q.worldedit.blocks.SkullBlock;
import com.sk89q.worldedit.commands.BiomeCommands;
import com.sk89q.worldedit.commands.BrushCommands;
import com.sk89q.worldedit.commands.ChunkCommands;
import com.sk89q.worldedit.commands.ClipboardCommands;
import com.sk89q.worldedit.commands.GeneralCommands;
import com.sk89q.worldedit.commands.GenerationCommands;
import com.sk89q.worldedit.commands.HistoryCommands;
import com.sk89q.worldedit.commands.NavigationCommands;
import com.sk89q.worldedit.commands.RegionCommands;
import com.sk89q.worldedit.commands.SchematicCommands;
import com.sk89q.worldedit.commands.ScriptingCommands;
import com.sk89q.worldedit.commands.SelectionCommands;
import com.sk89q.worldedit.commands.SnapshotCommands;
import com.sk89q.worldedit.commands.SnapshotUtilCommands;
import com.sk89q.worldedit.commands.SuperPickaxeCommands;
import com.sk89q.worldedit.commands.ToolCommands;
import com.sk89q.worldedit.commands.ToolUtilCommands;
import com.sk89q.worldedit.commands.UtilityCommands;
import com.sk89q.worldedit.commands.WorldEditCommands;
import com.sk89q.worldedit.masks.BiomeTypeMask;
import com.sk89q.worldedit.masks.BlockMask;
import com.sk89q.worldedit.masks.CombinedMask;
import com.sk89q.worldedit.masks.DynamicRegionMask;
import com.sk89q.worldedit.masks.ExistingBlockMask;
import com.sk89q.worldedit.masks.InvertedMask;
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df
import com.sk89q.worldedit.masks.Mask;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.scripting.CraftScriptContext;
Solution content
import com.sk89q.worldedit.CuboidClipboard.FlipDirection;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.extent.EditSessionEvent;
import com.sk89q.worldedit.event.platform.BlockInteractEvent;
import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.event.platform.InputType;
import com.sk89q.worldedit.event.platform.PlayerInputEvent;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extension.platform.PlatformManager;
import com.sk89q.worldedit.extension.registry.BlockRegistry;
import com.sk89q.worldedit.extension.registry.MaskRegistry;
import com.sk89q.worldedit.extension.registry.PatternRegistry;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.function.mask.Masks;
import com.sk89q.worldedit.function.pattern.Patterns;
import com.sk89q.worldedit.masks.Mask;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.scripting.CraftScriptContext;
File
WorldEdit.java
Developer's decision
Manual
Kind of conflict
Import
Chunk
Conflicting content
import com.sk89q.worldedit.scripting.CraftScriptContext;
import com.sk89q.worldedit.scripting.CraftScriptEngine;
import com.sk89q.worldedit.scripting.RhinoCraftScriptEngine;
<<<<<<< HEAD
import com.sk89q.worldedit.session.SessionManager;
import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.util.eventbus.EventBus;
import com.sk89q.worldedit.util.logging.WorldEditPrefixHandler;

import javax.script.ScriptException;
import java.io.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.worldedit.event.platform.Interaction.HIT;
import static com.sk89q.worldedit.event.platform.Interaction.OPEN;
=======
import com.sk89q.worldedit.tools.BlockTool;
import com.sk89q.worldedit.tools.DoubleActionBlockTool;
import com.sk89q.worldedit.tools.DoubleActionTraceTool;
import com.sk89q.worldedit.tools.Tool;
import com.sk89q.worldedit.tools.TraceTool;
import com.sk89q.worldedit.util.CommandLoggingHandler;
import com.sk89q.worldedit.util.CommandPermissionsHandler;
import com.sk89q.worldedit.util.WorldEditBinding;
import com.sk89q.worldedit.util.WorldEditExceptionConverter;
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df

/**
 * The entry point and container for a working implementation of WorldEdit.
Solution content
import com.sk89q.worldedit.scripting.CraftScriptContext;
import com.sk89q.worldedit.scripting.CraftScriptEngine;
import com.sk89q.worldedit.scripting.RhinoCraftScriptEngine;
import com.sk89q.worldedit.session.SessionManager;
import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.util.eventbus.EventBus;
import com.sk89q.worldedit.util.logging.WorldEditPrefixHandler;

import javax.script.ScriptException;
import java.io.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.worldedit.event.platform.Interaction.HIT;
import static com.sk89q.worldedit.event.platform.Interaction.OPEN;

/**
 * The entry point and container for a working implementation of WorldEdit.
File
WorldEdit.java
Developer's decision
Version 1
Kind of conflict
Import
Chunk
Conflicting content
    }
 * platforms within the same classloader hierarchy.
 */
public class WorldEdit {
<<<<<<< HEAD

    public static final Logger logger = Logger.getLogger(WorldEdit.class.getCanonicalName());

    private final static WorldEdit instance = new WorldEdit();
    private static String version;

    private final EventBus eventBus = new EventBus();
    private final PlatformManager platformManager = new PlatformManager(this);
    private final EditSessionFactory editSessionFactory = new EditSessionFactory.EditSessionFactoryImpl(eventBus);
    private final SessionManager sessions = new SessionManager(this);

    private final BlockRegistry blockRegistry = new BlockRegistry(this);
    private final MaskRegistry maskRegistry = new MaskRegistry(this);
    private final PatternRegistry patternRegistry = new PatternRegistry(this);

    static {
        WorldEditPrefixHandler.register("com.sk89q.worldedit");
        getVersion();
    }

    private WorldEdit() {
    }

    /**
     * Gets the current instance of this class.
     * 

* An instance will always be available, but no platform may yet be * registered with WorldEdit, meaning that a number of operations * may fail. However, event handlers can be registered. * * @return an instance of WorldEdit. */ public static WorldEdit getInstance() { return instance; /** * Get the platform manager, where platforms (that implement WorldEdit) * can be registered and information about registered platforms can * be queried. * * @return the platform manager */ public PlatformManager getPlatformManager() { return platformManager; } /** * Get the event bus for WorldEdit. *

* Event handlers can be registered on the event bus. * * @return the event bus */ public EventBus getEventBus() { return eventBus; } /** * Get the block registry from which new {@link BaseBlock}s can be * constructed. * * @return the block registry */ public BlockRegistry getBlockRegistry() { return blockRegistry; } /** * Get the mask registry from which new {@link com.sk89q.worldedit.function.mask.Mask}s * can be constructed. * * @return the mask registry */ public MaskRegistry getMaskRegistry() { return maskRegistry; } /** * Get the pattern registry from which new {@link com.sk89q.worldedit.function.pattern.Pattern}s * can be constructed. * * @return the pattern registry */ public PatternRegistry getPatternRegistry() { return patternRegistry; } /** * Return the session manager. * * @return the session manager */ public SessionManager getSessionManager() { return sessions; ======= public static final Logger logger = Logger.getLogger("Minecraft.WorldEdit"); private static WorldEdit instance; private static String version; private final ServerInterface server; private final LocalConfiguration config; private final Dispatcher dispatcher; private final CommandLoggingHandler commandLogger; private final HashMap sessions = new HashMap(); private EditSessionFactory editSessionFactory = new EditSessionFactory(); static { getVersion(); } /** * Gets the current instance of this class. * *

An instance is available once a plugin/host has initialized WorldEdit.

* * @return an instance */ public static WorldEdit getInstance() { return instance; } /** * Construct an instance of the class. * * @param server the server interface * @param config the configuration */ public WorldEdit(ServerInterface server, final LocalConfiguration config) { WorldEdit.instance = this; this.server = server; this.config = config; ParametricBuilder builder = new ParametricBuilder(); builder.addBinding(new WorldEditBinding(this)); builder.attach(new CommandPermissionsHandler()); builder.attach(new WorldEditExceptionConverter(config)); builder.attach(new LegacyCommandsHandler()); builder.attach(commandLogger = new CommandLoggingHandler(this, config)); dispatcher = new CommandGraph() .builder(builder) .commands() .build(new BiomeCommands(this)) .build(new ChunkCommands(this)) .build(new ClipboardCommands(this)) .build(new GeneralCommands(this)) .build(new GenerationCommands(this)) .build(new HistoryCommands(this)) .build(new NavigationCommands(this)) .build(new RegionCommands(this)) .build(new ScriptingCommands(this)) .build(new SelectionCommands(this)) .build(new SnapshotUtilCommands(this)) .build(new ToolUtilCommands(this)) .build(new ToolCommands(this)) .build(new UtilityCommands(this)) .group("worldedit", "we") .describe("WorldEdit commands") .build(new WorldEditCommands(this)) .parent() .group("schematic", "schem", "/schematic", "/schem") .describe("Schematic commands for saving/loading areas") .build(new SchematicCommands(this)) .parent() .group("snapshot", "snap") .describe("Schematic commands for saving/loading areas") .build(new SnapshotCommands(this)) .parent() .group("brush", "br") .describe("Brushing commands") .build(new BrushCommands(this)) .parent() .group("superpickaxe", "pickaxe", "sp") .describe("Super-pickaxe commands") .build(new SuperPickaxeCommands(this)) .parent() .group("tool") .describe("Bind functions to held items") .build(new ToolCommands(this)) .parent() .graph() .getDispatcher(); server.registerCommands(dispatcher); >>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df } /**
Solution content
    /**
 * platforms within the same classloader hierarchy.
 */
public class WorldEdit {

    public static final Logger logger = Logger.getLogger(WorldEdit.class.getCanonicalName());

    private final static WorldEdit instance = new WorldEdit();
    private static String version;

    private final EventBus eventBus = new EventBus();
    private final PlatformManager platformManager = new PlatformManager(this);
    private final EditSessionFactory editSessionFactory = new EditSessionFactory.EditSessionFactoryImpl(eventBus);
    private final SessionManager sessions = new SessionManager(this);

    private final BlockRegistry blockRegistry = new BlockRegistry(this);
    private final MaskRegistry maskRegistry = new MaskRegistry(this);
    private final PatternRegistry patternRegistry = new PatternRegistry(this);

    static {
        WorldEditPrefixHandler.register("com.sk89q.worldedit");
        getVersion();
    }

    private WorldEdit() {
    }

    /**
     * Gets the current instance of this class.
     * 

* An instance will always be available, but no platform may yet be * registered with WorldEdit, meaning that a number of operations * may fail. However, event handlers can be registered. * * @return an instance of WorldEdit. */ public static WorldEdit getInstance() { return instance; } /** * Get the platform manager, where platforms (that implement WorldEdit) * can be registered and information about registered platforms can * be queried. * * @return the platform manager */ public PlatformManager getPlatformManager() { return platformManager; } /** * Get the event bus for WorldEdit. *

* Event handlers can be registered on the event bus. * * @return the event bus */ public EventBus getEventBus() { return eventBus; } /** * Get the block registry from which new {@link BaseBlock}s can be * constructed. * * @return the block registry */ public BlockRegistry getBlockRegistry() { return blockRegistry; } * Get the mask registry from which new {@link com.sk89q.worldedit.function.mask.Mask}s * can be constructed. * * @return the mask registry */ public MaskRegistry getMaskRegistry() { return maskRegistry; } /** * Get the pattern registry from which new {@link com.sk89q.worldedit.function.pattern.Pattern}s * can be constructed. * * @return the pattern registry */ public PatternRegistry getPatternRegistry() { return patternRegistry; } /** * Return the session manager. * * @return the session manager */ public SessionManager getSessionManager() { return sessions; } /**
File
WorldEdit.java
Developer's decision
Version 1
Kind of conflict
Attribute
Comment
Method declaration
Method invocation
Method signature
Return statement
Static initializer
Variable
Chunk
Conflicting content
    }

    /**
<<<<<<< HEAD
     * @deprecated use {@link #getSessionManager()}
=======
     * Gets the WorldEdit session for a player.
     *
     * @param player the player
     * @return the session
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df
     */
    @Deprecated
    public LocalSession getSession(LocalPlayer player) {
Solution content
    }

    /**
     * @deprecated use {@link #getSessionManager()}
     */
    @Deprecated
    public LocalSession getSession(LocalPlayer player) {
File
WorldEdit.java
Developer's decision
Version 1
Kind of conflict
Comment
Chunk
Conflicting content
    }

    /**
<<<<<<< HEAD
     * Get the map of commands (internal usage only).
     *
     * @return the commands
     */
    public Map getCommands() {
        return getCommandsManager().getCommands();
    }

    /**
     * Get the commands manager (internal usage only).
     *
     * @return the commands
     */
    public CommandsManager getCommandsManager() {
        return getPlatformManager().getCommandManager().getCommands();
=======
     * Get the command dispatcher.
     * 
     * @return the command dispatcher
     */
    public Dispatcher getDispatcher() {
        return dispatcher;
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df
    }

    /**
Solution content
    }

    /**
     * Handle a disconnection.
     *
     * @param player the player
     */
    @Deprecated
    public void handleDisconnect(LocalPlayer player) {
        forgetPlayer(player);
    }

    /**
     * Mark for expiration of the session.
     *
     * @param player the player
     */
    public void markExpire(LocalPlayer player) {
        sessions.markforExpiration(player);
    }

    /**
     * Forget a player.
     *
     * @param player the player
     */
    public void forgetPlayer(LocalPlayer player) {
        sessions.remove(player);
    }

    /*
     * Flush expired sessions.
     */
    public void flushExpiredSessions(SessionCheck checker) {
        sessions.removeExpired(checker);
    }

    /**
     * Called on arm swing.
     *
     * @param player the player
     * @return true if the swing was handled
     */
    public boolean handleArmSwing(LocalPlayer player) {
        PlayerInputEvent event = new PlayerInputEvent(player, InputType.PRIMARY);
        getEventBus().post(event);
        return event.isCancelled();
    }

    /**
     * Called on right click (not on a block).
     *
     * @param player the player
     * @return true if the right click was handled
     */
    public boolean handleRightClick(LocalPlayer player) {
        PlayerInputEvent event = new PlayerInputEvent(player, InputType.SECONDARY);
        getEventBus().post(event);
        return event.isCancelled();
    }

    /**
     * Called on right click.
     *
     * @param player the player
     * @param clicked the clicked block
     * @return false if you want the action to go through
     */
    public boolean handleBlockRightClick(LocalPlayer player, WorldVector clicked) {
        BlockInteractEvent event = new BlockInteractEvent(player, clicked.toLocation(), OPEN);
        getEventBus().post(event);
        return event.isCancelled();
    }

    /**
     * Called on left click.
     *
     * @param player the player
     * @param clicked the clicked block
     * @return false if you want the action to go through
     */
    public boolean handleBlockLeftClick(LocalPlayer player, WorldVector clicked) {
        BlockInteractEvent event = new BlockInteractEvent(player, clicked.toLocation(), HIT);
        getEventBus().post(event);
        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.
     *
     * @param player the player
     * @param f the script file to execute
     * @param args arguments for the script
     * @throws WorldEditException
     */
    public void runScript(LocalPlayer player, File f, String[] args) throws WorldEditException {
        Request.reset();

        String filename = f.getPath();
        int index = filename.lastIndexOf(".");
        String ext = filename.substring(index + 1, filename.length());

        if (!ext.equalsIgnoreCase("js")) {
            player.printError("Only .js scripts are currently supported");
            return;
        }

        String script;

        try {
            InputStream file;

            if (!f.exists()) {
                file = WorldEdit.class.getResourceAsStream("craftscripts/" + filename);

                if (file == null) {
                    player.printError("Script does not exist: " + filename);
                    return;
                }
            } else {
                file = new FileInputStream(f);
            }

            DataInputStream in = new DataInputStream(file);
            byte[] data = new byte[in.available()];
            in.readFully(data);
            in.close();
            script = new String(data, 0, data.length, "utf-8");
        } catch (IOException e) {
            player.printError("Script read error: " + e.getMessage());
            return;
        }

        LocalSession session = getSession(player);
        CraftScriptContext scriptContext =
                new CraftScriptContext(this, getServer(), getConfiguration(), session, player, args);

        CraftScriptEngine engine = null;

        try {
            engine = new RhinoCraftScriptEngine();
        } catch (NoClassDefFoundError e) {
            player.printError("Failed to find an installed script engine.");
            player.printError("Please see http://wiki.sk89q.com/wiki/WorldEdit/Installation");
            return;
        }

        engine.setTimeLimit(getConfiguration().scriptTimeout);

        Map vars = new HashMap();
        vars.put("argv", args);
        vars.put("context", scriptContext);
        vars.put("player", player);

        try {
            engine.evaluate(script, filename, vars);
        } catch (ScriptException e) {
            player.printError("Failed to execute:");
            player.printRaw(e.getMessage());
            e.printStackTrace();
        } catch (NumberFormatException e) {
            throw e;

        } catch (WorldEditException e) {
            throw e;
        } catch (Throwable e) {
            player.printError("Failed to execute (see console):");
            player.printRaw(e.getClass().getCanonicalName());
            e.printStackTrace();
        } finally {
            for (EditSession editSession : scriptContext.getEditSessions()) {
                editSession.flushQueue();
                session.remember(editSession);
            }
        }
    }

    /**
     * Get Worldedit's configuration.
     *
     * @return a configuration
     */
    public LocalConfiguration getConfiguration() {
        return getPlatformManager().getConfiguration();
    }

    /**
     * Get the server interface.
     *
     * @return the server interface
     */
    public ServerInterface getServer() {
        return getPlatformManager().getServerInterface();
    }

    /**
     * Get a factory for {@link EditSession}s.
     */
    public EditSessionFactory getEditSessionFactory() {
        return editSessionFactory;
    }

    /**
     * @deprecated EditSessionFactories are no longer used. Please register an {@link EditSessionEvent} event
     *             with the event bus in order to override or catch changes to the world
     */
    @Deprecated
    public void setEditSessionFactory(EditSessionFactory factory) {
        checkNotNull(factory);
        logger.severe("Got request to set EditSessionFactory of type " +
                factory.getClass().getName() + " from " + factory.getClass().getPackage().getName() +
                " but EditSessionFactories have been removed in favor of extending EditSession's extents.\n\n" +
                "This may mean that any block logger / intercepters addons/plugins/mods that you have installed will not " +
                "intercept WorldEdit's changes! Please notify the maintainer of the other addon about this.");
    }

    /**
     * Get the version.
     *
     * @return the version of WorldEdit
     */
    public static String getVersion() {
        if (version != null) {
            return version;
        }

        Package p = WorldEdit.class.getPackage();
        if (p == null) {
            p = Package.getPackage("com.sk89q.worldedit");
        }

        if (p == null) {
            version = "(unknown)";
        } else {
            version = p.getImplementationVersion();

            if (version == null) {
                version = "(unknown)";
            }
        }

        return version;
    }

    /**
     * @deprecated Declare your platform version with {@link Platform#getPlatformVersion()}
     */
    @Deprecated
    public static void setVersion(String version) {
    }

}
File
WorldEdit.java
Developer's decision
Manual
Kind of conflict
Attribute
Comment
Method declaration
Method invocation
Method signature
Return statement
Chunk
Conflicting content
     * @return whether the command was processed
     */
    public boolean handleCommand(LocalPlayer player, String[] split) {
<<<<<<< HEAD
        CommandEvent event = new CommandEvent(player, split);
        getEventBus().post(event);
        return event.isCancelled();
    }

    public String[] commandDetection(String[] split) {
        return getPlatformManager().getCommandManager().commandDetection(split);
=======
        split = commandDetection(split);

        // No command found!
        if (!dispatcher.contains(split[0])) {
            return false;
        }
        
        CommandLocals locals = new CommandLocals();
        locals.put(LocalPlayer.class, player);

        long start = System.currentTimeMillis();

        try {
            dispatcher.call(split, locals);
        } catch (CommandPermissionsException e) {
            player.printError("You don't have permission to do this.");
        } catch (InvalidUsageException e) {
            player.printError(e.getMessage() + "\nUsage: " + e.getUsage("/"));
        } catch (WrappedCommandException e) {
            Throwable t = e.getCause();
            player.printError("Please report this error: [See console]");
            player.printRaw(t.getClass().getName() + ": " + t.getMessage());
            t.printStackTrace();
        } catch (CommandException e) {
            player.printError(e.getMessage());
        } finally {
            EditSession editSession = locals.get(EditSession.class);
            
            if (editSession != null) {
                LocalSession session = getSession(player);
                session.remember(editSession);
                editSession.flushQueue();

                if (config.profile) {
                    long time = System.currentTimeMillis() - start;
                    int changed = editSession.getBlockChangeCount();
                    if (time > 0) {
                        double throughput = changed / (time / 1000.0);
                        player.printDebug((time / 1000.0) + "s elapsed (history: "
                                + changed + " changed; "
                                + Math.round(throughput) + " blocks/sec).");
                    } else {
                        player.printDebug((time / 1000.0) + "s elapsed.");
                    }
                }

                flushBlockBag(player, editSession);
            }
        }

        return true;
    }

    public String[] commandDetection(String[] split) {
        split[0] = split[0].substring(1);

        // Quick script shortcut
        if (split[0].matches("^[^/].*\\.js$")) {
            String[] newSplit = new String[split.length + 1];
            System.arraycopy(split, 0, newSplit, 1, split.length);
            newSplit[0] = "cs";
            newSplit[1] = newSplit[1];
            split = newSplit;
        }

        String searchCmd = split[0].toLowerCase();

        // Try to detect the command
        if (dispatcher.contains(searchCmd)) {
        } else if (config.noDoubleSlash && dispatcher.contains("/" + searchCmd)) {
            split[0] = "/" + split[0];
        } else if (split[0].length() >= 2 && split[0].charAt(0) == '/'
                && dispatcher.contains(searchCmd.substring(1))) {
            split[0] = split[0].substring(1);
        }
        return split;
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df
    }

    /**
Solution content
     * @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);
    }

    /**
File
WorldEdit.java
Developer's decision
Version 1
Kind of conflict
Array access
Comment
If statement
Method invocation
Method signature
Return statement
Try statement
Variable
Chunk
Conflicting content
<<<<<<< HEAD:src/main/java/com/sk89q/worldedit/command/BiomeCommands.java
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

package com.sk89q.worldedit.command;
=======
package com.sk89q.worldedit.commands;

import static com.sk89q.minecraft.util.commands.Logging.LogMode.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df:src/main/java/com/sk89q/worldedit/commands/BiomeCommands.java

import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
Solution content
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

package com.sk89q.worldedit.command;

import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
File
BiomeCommands.java
Developer's decision
Version 1
Kind of conflict
Comment
Import
Package declaration
Chunk
Conflicting content
<<<<<<< HEAD:src/main/java/com/sk89q/worldedit/command/ClipboardCommands.java
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

package com.sk89q.worldedit.command;

import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.world.World;

import static com.sk89q.minecraft.util.commands.Logging.LogMode.PLACEMENT;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;

/**
 * Clipboard commands.
 *
 * @author sk89q
 */
public class ClipboardCommands {
    private final WorldEdit we;

    public ClipboardCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "/copy" },
        flags = "e",
        desc = "Copy the selection to the clipboard",
        help = "Copy the selection to the clipboard\n" +
                "Flags:\n" +
                "  -e controls whether entities are copied\n" +
                "WARNING: Pasting entities cannot yet be undone!",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.clipboard.copy")
    public void copy(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        Region region = session.getSelection(player.getWorld());
        Vector min = region.getMinimumPoint();
        Vector max = region.getMaximumPoint();
        Vector pos = session.getPlacementPosition(player);

        CuboidClipboard clipboard = new CuboidClipboard(
                max.subtract(min).add(Vector.ONE),
                min, min.subtract(pos));

        if (region instanceof CuboidRegion) {


            clipboard.copy(editSession);
        } else {
            clipboard.copy(editSession, region);
        }

        if (args.hasFlag('e')) {
            for (LocalEntity entity : player.getWorld().getEntities(region)) {
                clipboard.storeEntity(entity);
            }
        }
        session.setClipboard(clipboard);

        player.print("Block(s) copied.");
    }

    @Command(
        aliases = { "/cut" },
        usage = "[leave-id]",
        desc = "Cut the selection to the clipboard",
        help = "Copy the selection to the clipboard\n" +
                "Flags:\n" +
                "  -e controls whether entities are copied\n" +
                "WARNING: Cutting and pasting entities cannot yet be undone!",
        flags = "e",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.clipboard.cut")
    @Logging(REGION)
    public void cut(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock block = new BaseBlock(BlockID.AIR);
        World world = player.getWorld();

        if (args.argsLength() > 0) {
            block = we.getBlock(player, args.getString(0));
        }

        Region region = session.getSelection(world);
        Vector min = region.getMinimumPoint();
        Vector max = region.getMaximumPoint();
        Vector pos = session.getPlacementPosition(player);

        CuboidClipboard clipboard = new CuboidClipboard(
                max.subtract(min).add(Vector.ONE),
                min, min.subtract(pos));

        if (region instanceof CuboidRegion) {
            clipboard.copy(editSession);
        } else {
            clipboard.copy(editSession, region);
        }

        if (args.hasFlag('e')) {
            LocalEntity[] entities = world.getEntities(region);
            for (LocalEntity entity : entities) {
                clipboard.storeEntity(entity);
            }
            world.killEntities(entities);
        }
        session.setClipboard(clipboard);

        editSession.setBlocks(region, block);
        player.print("Block(s) cut.");
    }

    @Command(
        aliases = { "/paste" },
        usage = "",
        flags = "sao",
        desc = "Paste the clipboard's contents",
        help =
            "Pastes the clipboard's contents.\n" +
            "Flags:\n" +
            "  -a skips air blocks\n" +
            "  -o pastes at the original position\n" +
            "  -s selects the region after pasting",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.clipboard.paste")
    @Logging(PLACEMENT)
    public void paste(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        boolean atOrigin = args.hasFlag('o');
        boolean pasteNoAir = args.hasFlag('a');

        CuboidClipboard clipboard = session.getClipboard();

        Vector pos = atOrigin ? session.getClipboard().getOrigin()
                : session.getPlacementPosition(player);

        if (atOrigin) {
            clipboard.place(editSession, pos, pasteNoAir);
            clipboard.pasteEntities(pos);
            player.findFreePosition();
            player.print("Pasted to copy origin. Undo with //undo");
        } else {
            clipboard.paste(editSession, pos, pasteNoAir, true);
            player.findFreePosition();
            player.print("Pasted relative to you. Undo with //undo");
        }

        if (args.hasFlag('s')) {
            World world = player.getWorld();
            Vector pos2 = pos.add(clipboard.getSize().subtract(1, 1, 1));
            if (!atOrigin) {
                pos2 = pos2.add(clipboard.getOffset());
                pos = pos.add(clipboard.getOffset());
            }
            session.setRegionSelector(world, new CuboidRegionSelector(world, pos, pos2));
            session.getRegionSelector(world).learnChanges();
            session.getRegionSelector(world).explainRegionAdjust(player, session);
        }
    }

    @Command(
        aliases = { "/rotate" },
        usage = "",
        desc = "Rotate the contents of the clipboard",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.clipboard.rotate")
    public void rotate(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        int angle = args.getInteger(0);

        if (angle % 90 == 0) {
            CuboidClipboard clipboard = session.getClipboard();
            clipboard.rotate2D(angle);
            player.print("Clipboard rotated by " + angle + " degrees.");
        } else {
            player.printError("Angles must be divisible by 90 degrees.");
        }
    }

    @Command(
        aliases = { "/flip" },
        usage = "[dir]",
        flags = "p",
        desc = "Flip the contents of the clipboard.",
        help =
            "Flips the contents of the clipboard.\n" +
            "The -p flag flips the selection around the player,\n" +
            "instead of the selections center.",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.clipboard.flip")
    public void flip(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        CuboidClipboard.FlipDirection dir = we.getFlipDirection(player,
                args.argsLength() > 0 ? args.getString(0).toLowerCase() : "me");

        CuboidClipboard clipboard = session.getClipboard();
        clipboard.flip(dir, args.hasFlag('p'));
        player.print("Clipboard flipped.");
    }

    @Command(
        aliases = { "/load" },
        usage = "",
        desc = "Load a schematic into your clipboard",
        min = 0,
        max = 1
    )
    @Deprecated
    @CommandPermissions("worldedit.clipboard.load")
    public void load(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        player.printError("This command is no longer used. See //schematic load.");
    }

    @Command(
        aliases = { "/save" },
        usage = "",
        desc = "Save a schematic into your clipboard",
        min = 0,
        max = 1
    )
    @Deprecated
    @CommandPermissions("worldedit.clipboard.save")
    public void save(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        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(
        aliases = { "clearclipboard" },
        usage = "",
        desc = "Clear your clipboard",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.clipboard.clear")
    public void clearClipboard(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setClipboard(null);
        player.print("Clipboard cleared.");
    }
}
=======
// $Id$
/*
 * WorldEdit
 * Copyright (C) 2010 sk89q  and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see .
*/

package com.sk89q.worldedit.commands;

import static com.sk89q.minecraft.util.commands.Logging.LogMode.*;

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.CuboidClipboard;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalEntity;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.LocalWorld;
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.BlockID;
import com.sk89q.worldedit.regions.Region;

/**
 * Clipboard commands.
 *
 * @author sk89q
 */
public class ClipboardCommands {
    private final WorldEdit we;

    public ClipboardCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "/copy" },
        flags = "e",
        desc = "Copy the selection to the clipboard",
        help = "Copy the selection to the clipboard\n" +
                "Flags:\n" +
                "  -e controls whether entities are copied\n" +
                "WARNING: Pasting entities cannot yet be undone!",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.clipboard.copy")
    public void copy(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        Region region = session.getSelection(player.getWorld());
        Vector min = region.getMinimumPoint();
        Vector max = region.getMaximumPoint();
        Vector pos = session.getPlacementPosition(player);

        CuboidClipboard clipboard = new CuboidClipboard(
                max.subtract(min).add(new Vector(1, 1, 1)),
                min, min.subtract(pos));
        clipboard.copy(editSession);
        if (args.hasFlag('e')) {
            for (LocalEntity entity : player.getWorld().getEntities(region)) {
                clipboard.storeEntity(entity);
            }
        }
        session.setClipboard(clipboard);

        player.print("Block(s) copied.");
    }

    @Command(
        aliases = { "/cut" },
        usage = "[leave-id]",
        desc = "Cut the selection to the clipboard",
        help = "Copy the selection to the clipboard\n" +
                "Flags:\n" +
                "  -e controls whether entities are copied\n" +
                "WARNING: Cutting and pasting entities cannot yet be undone!",
        flags = "e",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.clipboard.cut")
    @Logging(REGION)
    public void cut(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock block = new BaseBlock(BlockID.AIR);
        LocalWorld world = player.getWorld();

        if (args.argsLength() > 0) {
            block = we.getBlock(player, args.getString(0));
        }

        Region region = session.getSelection(world);
        Vector min = region.getMinimumPoint();
        Vector max = region.getMaximumPoint();
        Vector pos = session.getPlacementPosition(player);

        CuboidClipboard clipboard = new CuboidClipboard(
                max.subtract(min).add(new Vector(1, 1, 1)),
                min, min.subtract(pos));
        clipboard.copy(editSession);
        if (args.hasFlag('e')) {
            LocalEntity[] entities = world.getEntities(region);
            for (LocalEntity entity : entities) {
                clipboard.storeEntity(entity);
            }
            world.killEntities(entities);
        }
        session.setClipboard(clipboard);
        editSession.setBlocks(session.getSelection(world), block);
        player.print("Block(s) cut.");
    }

    @Command(
        aliases = { "/paste" },
        usage = "",
        flags = "ao",
        desc = "Paste the clipboard's contents",
        help =
            "Pastes the clipboard's contents.\n" +
            "Flags:\n" +
            "  -a skips air blocks\n" +
            "  -o pastes at the original position",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.clipboard.paste")
    @Logging(PLACEMENT)
    public void paste(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        boolean atOrigin = args.hasFlag('o');
        boolean pasteNoAir = args.hasFlag('a');

        if (atOrigin) {
            Vector pos = session.getClipboard().getOrigin();
            session.getClipboard().place(editSession, pos, pasteNoAir);
            session.getClipboard().pasteEntities(pos);
            player.findFreePosition();
            player.print("Pasted to copy origin. Undo with //undo");
        } else {
            Vector pos = session.getPlacementPosition(player);
            session.getClipboard().paste(editSession, pos, pasteNoAir, true);
            player.findFreePosition();
            player.print("Pasted relative to you. Undo with //undo");
        }
    }

    @Command(
        aliases = { "/rotate" },
        usage = "",
        desc = "Rotate the contents of the clipboard",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.clipboard.rotate")
    public void rotate(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        int angle = args.getInteger(0);
        if (angle % 90 == 0) {
            CuboidClipboard clipboard = session.getClipboard();
            clipboard.rotate2D(angle);
            player.print("Clipboard rotated by " + angle + " degrees.");
        } else {
            player.printError("Angles must be divisible by 90 degrees.");
        }
    }

    @Command(
        aliases = { "/flip" },
        usage = "[dir]",
        flags = "p",
        desc = "Flip the contents of the clipboard.",
        help =
            "Flips the contents of the clipboard.\n" +
            "The -p flag flips the selection around the player,\n" +
            "instead of the selections center.",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.clipboard.flip")
    public void flip(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        CuboidClipboard.FlipDirection dir = we.getFlipDirection(player,
                args.argsLength() > 0 ? args.getString(0).toLowerCase() : "me");

        CuboidClipboard clipboard = session.getClipboard();
        clipboard.flip(dir, args.hasFlag('p'));
        player.print("Clipboard flipped.");
    }

    @Command(
        aliases = { "/load" },
        usage = "",
        desc = "Load a schematic into your clipboard",
        min = 0,
        max = 1
    )
    @Deprecated
    @CommandPermissions("worldedit.clipboard.load")
    public void load(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        player.printError("This command is no longer used. See //schematic load.");
    }
    @Command(
        aliases = { "/save" },
        usage = "",
        desc = "Save a schematic into your clipboard",
        min = 0,
        max = 1
    )
    @Deprecated
    @CommandPermissions("worldedit.clipboard.save")
    public void save(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        player.printError("This command is no longer used. See //schematic save.");
    }

    @Command(
        aliases = { "clearclipboard" },
        usage = "",
        desc = "Clear your clipboard",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.clipboard.clear")
    public void clearClipboard(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setClipboard(null);
        player.print("Clipboard cleared.");
    }
}
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df:src/main/java/com/sk89q/worldedit/commands/ClipboardCommands.java
Solution content
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

package com.sk89q.worldedit.command;

import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.world.World;

import static com.sk89q.minecraft.util.commands.Logging.LogMode.PLACEMENT;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;

/**
 * Clipboard commands.
 *
 * @author sk89q
 */
public class ClipboardCommands {
    private final WorldEdit we;

    public ClipboardCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "/copy" },
        flags = "e",
        desc = "Copy the selection to the clipboard",
        help = "Copy the selection to the clipboard\n" +
                "Flags:\n" +
                "  -e controls whether entities are copied\n" +
                "WARNING: Pasting entities cannot yet be undone!",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.clipboard.copy")
    public void copy(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        Region region = session.getSelection(player.getWorld());
        Vector min = region.getMinimumPoint();
        Vector max = region.getMaximumPoint();
        Vector pos = session.getPlacementPosition(player);

        CuboidClipboard clipboard = new CuboidClipboard(
                max.subtract(min).add(Vector.ONE),
                min, min.subtract(pos));

        if (region instanceof CuboidRegion) {
            clipboard.copy(editSession);
        } else {
            clipboard.copy(editSession, region);
        }

        if (args.hasFlag('e')) {
            for (LocalEntity entity : player.getWorld().getEntities(region)) {
                clipboard.storeEntity(entity);
            }
        }
        session.setClipboard(clipboard);

        player.print("Block(s) copied.");
    }

    @Command(
        aliases = { "/cut" },
        usage = "[leave-id]",
        desc = "Cut the selection to the clipboard",
        help = "Copy the selection to the clipboard\n" +
                "Flags:\n" +
                "  -e controls whether entities are copied\n" +
                "WARNING: Cutting and pasting entities cannot yet be undone!",
        flags = "e",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.clipboard.cut")
    @Logging(REGION)
    public void cut(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock block = new BaseBlock(BlockID.AIR);
        World world = player.getWorld();

        if (args.argsLength() > 0) {
            block = we.getBlock(player, args.getString(0));
        }

        Region region = session.getSelection(world);
        Vector min = region.getMinimumPoint();
        Vector max = region.getMaximumPoint();
        Vector pos = session.getPlacementPosition(player);

        CuboidClipboard clipboard = new CuboidClipboard(
                max.subtract(min).add(Vector.ONE),
                min, min.subtract(pos));

        if (region instanceof CuboidRegion) {
            clipboard.copy(editSession);
        } else {
            clipboard.copy(editSession, region);
        }

        if (args.hasFlag('e')) {
            LocalEntity[] entities = world.getEntities(region);
            for (LocalEntity entity : entities) {
                clipboard.storeEntity(entity);
            }
            world.killEntities(entities);
        }
        session.setClipboard(clipboard);

        editSession.setBlocks(region, block);
        player.print("Block(s) cut.");
    }

    @Command(
        aliases = { "/paste" },
        usage = "",
        flags = "sao",
        max = 1
        desc = "Paste the clipboard's contents",
        help =
            "Pastes the clipboard's contents.\n" +
            "Flags:\n" +
            "  -a skips air blocks\n" +
            "  -o pastes at the original position\n" +
            "  -s selects the region after pasting",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.clipboard.paste")
    @Logging(PLACEMENT)
    public void paste(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        boolean atOrigin = args.hasFlag('o');
        boolean pasteNoAir = args.hasFlag('a');

        CuboidClipboard clipboard = session.getClipboard();

        Vector pos = atOrigin ? session.getClipboard().getOrigin()
                : session.getPlacementPosition(player);

        if (atOrigin) {
            clipboard.place(editSession, pos, pasteNoAir);
            clipboard.pasteEntities(pos);
            player.findFreePosition();
            player.print("Pasted to copy origin. Undo with //undo");
        } else {
            clipboard.paste(editSession, pos, pasteNoAir, true);
            player.findFreePosition();
            player.print("Pasted relative to you. Undo with //undo");
        }
        if (args.hasFlag('s')) {
            World world = player.getWorld();
            Vector pos2 = pos.add(clipboard.getSize().subtract(1, 1, 1));
            if (!atOrigin) {
                pos2 = pos2.add(clipboard.getOffset());
                pos = pos.add(clipboard.getOffset());
            }
            session.setRegionSelector(world, new CuboidRegionSelector(world, pos, pos2));
            session.getRegionSelector(world).learnChanges();
            session.getRegionSelector(world).explainRegionAdjust(player, session);
        }
    }

    @Command(
        aliases = { "/rotate" },
        usage = "",
        desc = "Rotate the contents of the clipboard",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.clipboard.rotate")
    public void rotate(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        int angle = args.getInteger(0);

        if (angle % 90 == 0) {
            CuboidClipboard clipboard = session.getClipboard();
            clipboard.rotate2D(angle);
            player.print("Clipboard rotated by " + angle + " degrees.");
        } else {
            player.printError("Angles must be divisible by 90 degrees.");
        }
    }

    @Command(
        aliases = { "/flip" },
        usage = "[dir]",
        flags = "p",
        desc = "Flip the contents of the clipboard.",
        help =
            "Flips the contents of the clipboard.\n" +
            "The -p flag flips the selection around the player,\n" +
            "instead of the selections center.",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.clipboard.flip")
    public void flip(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        CuboidClipboard.FlipDirection dir = we.getFlipDirection(player,
                args.argsLength() > 0 ? args.getString(0).toLowerCase() : "me");

        CuboidClipboard clipboard = session.getClipboard();
        clipboard.flip(dir, args.hasFlag('p'));
        player.print("Clipboard flipped.");
    }

    @Command(
        aliases = { "/load" },
        usage = "",
        desc = "Load a schematic into your clipboard",
        min = 0,
    )
    @Deprecated
    @CommandPermissions("worldedit.clipboard.load")
    public void load(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        player.printError("This command is no longer used. See //schematic load.");
    }

    @Command(
        aliases = { "/save" },
        usage = "",
        desc = "Save a schematic into your clipboard",
        min = 0,
        max = 1
    )
    @Deprecated
    @CommandPermissions("worldedit.clipboard.save")
    public void save(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        player.printError("This command is no longer used. See //schematic save.");
    }

    @Command(
        aliases = { "clearclipboard" },
        usage = "",
        desc = "Clear your clipboard",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.clipboard.clear")
    public void clearClipboard(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setClipboard(null);
        player.print("Clipboard cleared.");
    }
}
File
ClipboardCommands.java
Developer's decision
Combination
Kind of conflict
Class declaration
Comment
Import
Package declaration
Chunk
Conflicting content
 */
<<<<<<< HEAD:src/main/java/com/sk89q/worldedit/command/GeneralCommands.java
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
        }


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.minecraft.util.commands.Console;
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.masks.Mask;

/**
 * General WorldEdit commands.
 * 
 * @author sk89q
 */
public class GeneralCommands {
    private final WorldEdit we;

    public GeneralCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "/limit" },
        usage = "",
        desc = "Modify block change limit",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.limit")
    public void limit(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        LocalConfiguration config = we.getConfiguration();
        boolean mayDisable = player.hasPermission("worldedit.limit.unrestricted");

        int limit = Math.max(-1, args.getInteger(0));
        if (!mayDisable && config.maxChangeLimit > -1) {
            if (limit > config.maxChangeLimit) {
                player.printError("Your maximum allowable limit is " + config.maxChangeLimit + ".");
                return;
            }
        session.setBlockChangeLimit(limit);

        if (limit != -1) {
            player.print("Block change limit set to " + limit + ". (Use //limit -1 to go back to the default.)");
        } else {
            player.print("Block change limit set to " + limit + ".");
        }
    }

    @Command(
        aliases = { "/fast" },
        usage = "[on|off]",
        desc = "Toggle fast mode",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.fast")
    public void fast(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        String newState = args.getString(0, null);
        if (session.hasFastMode()) {
            if ("on".equals(newState)) {
                player.printError("Fast mode already enabled.");
                return;
            }

            session.setFastMode(false);
            player.print("Fast mode disabled.");
        } else {
            if ("off".equals(newState)) {
                player.printError("Fast mode already disabled.");
                return;
            }

            session.setFastMode(true);
            player.print("Fast mode enabled. Lighting in the affected chunks may be wrong and/or you may need to rejoin to see changes.");
        }
    }

    @Command(
        aliases = { "/gmask", "gmask" },
        usage = "[mask]",
        desc = "Set the global mask",
        min = 0,
        max = -1
    )
    @CommandPermissions("worldedit.global-mask")
    public void gmask(CommandContext args, LocalSession session, LocalPlayer player,
        boolean itemsOnly = args.hasFlag('i');

        try {
            EditSession editSession) throws WorldEditException {
        if (args.argsLength() == 0) {
            session.setMask(null);
            player.print("Global mask disabled.");
        } else {
            Mask mask = we.getBlockMask(player, session, args.getJoinedStrings(0));
            session.setMask(mask);
            player.print("Global mask set.");
        }
    }

    @Command(
        aliases = { "/toggleplace", "toggleplace" },
        usage = "",
        desc = "Switch between your position and pos1 for placement",
        min = 0,
        max = 0
    )
    public void togglePlace(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        if (session.togglePlacementPosition()) {
            player.print("Now placing at pos #1.");
        } else {
            player.print("Now placing at the block you stand in.");
        }
    }

    @Command(
        aliases = { "/searchitem", "/l", "/search", "searchitem" },
        usage = "",
        flags = "bi",
        desc = "Search for an item",
        help =
            "Searches for an item.\n" +
            "Flags:\n" +
            "  -b only search for blocks\n" +
            "  -i only search for items",
        min = 1,
        max = 1
    )
    @Console
    public void searchItem(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        String query = args.getString(0).trim().toLowerCase();
        boolean blocksOnly = args.hasFlag('b');
            int id = Integer.parseInt(query);

            ItemType type = ItemType.fromID(id);

            if (type != null) {
                player.print("#" + type.getID() + " (" + type.getName() + ")");
            } else {
                player.printError("No item found by ID " + id);
            }

            return;
        } catch (NumberFormatException e) {
        }

        if (query.length() <= 2) {
            player.printError("Enter a longer search string (len > 2).");
            return;
        }

        if (!blocksOnly && !itemsOnly) {
            player.print("Searching for: " + query);
        } else if (blocksOnly && itemsOnly) {
            player.printError("You cannot use both the 'b' and 'i' flags simultaneously.");
            return;
        } else if (blocksOnly) {
            player.print("Searching for blocks: " + query);
        } else {
            player.print("Searching for items: " + query);
        }

        int found = 0;

        for (ItemType type : ItemType.values()) {
            if (found >= 15) {
                player.print("Too many results!");
                break;
            }

            if (blocksOnly && type.getID() > 255) {
                continue;
            }

            if (itemsOnly && type.getID() <= 255) {
                continue;
            }

            for (String alias : type.getAliases()) {
                if (alias.contains(query)) {
                    player.print("#" + type.getID() + " (" + type.getName() + ")");
                    ++found;
                    break;
                }
            }
        }

        if (found == 0) {
            player.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 {
    }
}
=======
// $Id$
/*
 * WorldEdit
 * Copyright (C) 2010 sk89q  and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see .
*/

package com.sk89q.worldedit.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.Console;
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.masks.Mask;

/**
 * General WorldEdit commands.
 * 
 * @author sk89q
 */
public class GeneralCommands {
    private final WorldEdit we;

    public GeneralCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "/limit" },
        usage = "",
        desc = "Modify block change limit",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.limit")
    public void limit(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        LocalConfiguration config = we.getConfiguration();

        int limit = Math.max(-1, args.getInteger(0));
        if (!player.hasPermission("worldedit.limit.unrestricted")
                && config.maxChangeLimit > -1) {
            if (limit > config.maxChangeLimit) {
                player.printError("Your maximum allowable limit is "
                        + config.maxChangeLimit + ".");
                return;
            }
        }

        session.setBlockChangeLimit(limit);
        player.print("Block change limit set to " + limit + ".");
    }

    @Command(
        aliases = { "/fast" },
        usage = "[on|off]",
        desc = "Toggle fast mode",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.fast")
    public void fast(CommandContext args, LocalSession session, LocalPlayer player,
        String newState = args.getString(0, null);
    public void togglePlace(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        if (session.hasFastMode()) {
            if ("on".equals(newState)) {
                player.printError("Fast mode already enabled.");
                return;
            }

            session.setFastMode(false);
            player.print("Fast mode disabled.");
        } else {
            if ("off".equals(newState)) {
                player.printError("Fast mode already disabled.");
                return;
            }

            session.setFastMode(true);
            player.print("Fast mode enabled. Lighting in the affected chunks may be wrong and/or you may need to rejoin to see changes.");
        }
    }

    @Command(
        aliases = { "/gmask", "gmask" },
        usage = "[mask]",
        desc = "Set the global mask",
        min = 0,
        max = -1
    )
    @CommandPermissions("worldedit.global-mask")
    public void mask(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        if (args.argsLength() == 0) {
            session.setMask(null);
            player.print("Global mask disabled.");
        } else {
            Mask mask = we.getBlockMask(player, session, args.getJoinedStrings(0));
            session.setMask(mask);
            player.print("Global mask set.");
        }
    }

    @Command(
        aliases = { "/toggleplace", "toggleplace" },
        usage = "",
        desc = "Switch between your position and pos1 for placement",
        min = 0,
        max = 0
    )
            EditSession editSession) throws WorldEditException {

        if (session.togglePlacementPosition()) {
            player.print("Now placing at pos #1.");
        } else {
            player.print("Now placing at the block you stand in.");
        }
    }

    @Command(
        aliases = { "/searchitem", "/l", "/search", "searchitem" },
        usage = "",
        flags = "bi",
        desc = "Search for an item",
        help =
            "Searches for an item.\n" +
            "Flags:\n" +
            "  -b only search for blocks\n" +
            "  -i only search for items",
        min = 1,
        max = 1
    )
    @Console
    public void searchItem(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        String query = args.getString(0).trim().toLowerCase();
        boolean blocksOnly = args.hasFlag('b');
        boolean itemsOnly = args.hasFlag('i');

        try {
            int id = Integer.parseInt(query);

            ItemType type = ItemType.fromID(id);

            if (type != null) {
                player.print("#" + type.getID() + " (" + type.getName() + ")");
            } else {
                player.printError("No item found by ID " + id);
            }

            return;
        } catch (NumberFormatException e) {
        }

        if (query.length() <= 2) {
            player.printError("Enter a longer search string (len > 2).");
            return;
        }

        if (!blocksOnly && !itemsOnly) {
            player.print("Searching for: " + query);
        } else if (blocksOnly && itemsOnly) {
            player.printError("You cannot use both the 'b' and 'i' flags simultaneously.");
            return;
        } else if (blocksOnly) {
            player.print("Searching for blocks: " + query);
        } else {
            player.print("Searching for items: " + query);
        }

        int found = 0;

        for (ItemType type : ItemType.values()) {
            if (found >= 15) {
                player.print("Too many results!");
                break;
            }

            if (blocksOnly && type.getID() > 255) {
                continue;
            }

            if (itemsOnly && type.getID() <= 255) {
                continue;
            }

            for (String alias : type.getAliases()) {
                if (alias.contains(query)) {
                    player.print("#" + type.getID() + " (" + type.getName() + ")");
                    ++found;
                    break;
                }
            }
        }

        if (found == 0) {
            player.printError("No items found.");
        }
    }
    
}
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df:src/main/java/com/sk89q/worldedit/commands/GeneralCommands.java
Solution content
                return;
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

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.minecraft.util.commands.Console;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldedit.masks.Mask;

/**
 * General WorldEdit commands.
 * 
 * @author sk89q
 */
public class GeneralCommands {
    private final WorldEdit we;

    public GeneralCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "/limit" },
        usage = "",
        desc = "Modify block change limit",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.limit")
    public void limit(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        LocalConfiguration config = we.getConfiguration();
        boolean mayDisable = player.hasPermission("worldedit.limit.unrestricted");

        int limit = Math.max(-1, args.getInteger(0));
        if (!mayDisable && config.maxChangeLimit > -1) {
            if (limit > config.maxChangeLimit) {
                player.printError("Your maximum allowable limit is " + config.maxChangeLimit + ".");
                return;
            }
        }

        session.setBlockChangeLimit(limit);

        if (limit != -1) {
            player.print("Block change limit set to " + limit + ". (Use //limit -1 to go back to the default.)");
        } else {
            player.print("Block change limit set to " + limit + ".");
        }
    }

    @Command(
        aliases = { "/fast" },
        usage = "[on|off]",
        desc = "Toggle fast mode",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.fast")
    public void fast(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        String newState = args.getString(0, null);
        if (session.hasFastMode()) {
            if ("on".equals(newState)) {
                player.printError("Fast mode already enabled.");
                return;
            }

            session.setFastMode(false);
            player.print("Fast mode disabled.");
        } else {
            if ("off".equals(newState)) {
                player.printError("Fast mode already disabled.");
        try {
            }

            session.setFastMode(true);
            player.print("Fast mode enabled. Lighting in the affected chunks may be wrong and/or you may need to rejoin to see changes.");
        }
    }

    @Command(
        aliases = { "/gmask", "gmask" },
        usage = "[mask]",
        desc = "Set the global mask",
        min = 0,
        max = -1
    )
    @CommandPermissions("worldedit.global-mask")
    public void gmask(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        if (args.argsLength() == 0) {
            session.setMask(null);
            player.print("Global mask disabled.");
        } else {
            Mask mask = we.getBlockMask(player, session, args.getJoinedStrings(0));
            session.setMask(mask);
            player.print("Global mask set.");
        }
    }

    @Command(
        aliases = { "/toggleplace", "toggleplace" },
        usage = "",
        desc = "Switch between your position and pos1 for placement",
        min = 0,
        max = 0
    )
    public void togglePlace(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        if (session.togglePlacementPosition()) {
            player.print("Now placing at pos #1.");
        } else {
            player.print("Now placing at the block you stand in.");
        }
    }

    @Command(
        aliases = { "/searchitem", "/l", "/search", "searchitem" },
        usage = "",
        flags = "bi",
        desc = "Search for an item",
        help =
            "Searches for an item.\n" +
            "Flags:\n" +
            "  -b only search for blocks\n" +
            "  -i only search for items",
        min = 1,
        max = 1
    )
    @Console
    public void searchItem(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        String query = args.getString(0).trim().toLowerCase();
        boolean blocksOnly = args.hasFlag('b');
        boolean itemsOnly = args.hasFlag('i');

            int id = Integer.parseInt(query);

            ItemType type = ItemType.fromID(id);

            if (type != null) {
                player.print("#" + type.getID() + " (" + type.getName() + ")");
            } else {
                player.printError("No item found by ID " + id);
            }

            return;
        } catch (NumberFormatException e) {
        }

        if (query.length() <= 2) {
            player.printError("Enter a longer search string (len > 2).");
            return;
        }

        if (!blocksOnly && !itemsOnly) {
            player.print("Searching for: " + query);
        } else if (blocksOnly && itemsOnly) {
            player.printError("You cannot use both the 'b' and 'i' flags simultaneously.");
            return;
        } else if (blocksOnly) {
            player.print("Searching for blocks: " + query);
        } else {
            player.print("Searching for items: " + query);
        }

        int found = 0;

        for (ItemType type : ItemType.values()) {
            if (found >= 15) {
                player.print("Too many results!");
                break;
            }

            if (blocksOnly && type.getID() > 255) {
                continue;
            }

            if (itemsOnly && type.getID() <= 255) {
                continue;
            }

            for (String alias : type.getAliases()) {
                if (alias.contains(query)) {
                    player.print("#" + type.getID() + " (" + type.getName() + ")");
                    ++found;
                    break;
                }
            }
        }

        if (found == 0) {
            player.printError("No items found.");
        }
    }

}
File
GeneralCommands.java
Developer's decision
Manual
Kind of conflict
Class declaration
Comment
Import
Package declaration
Chunk
Conflicting content
<<<<<<< HEAD:src/main/java/com/sk89q/worldedit/command/SnapshotUtilCommands.java
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

package com.sk89q.worldedit.command;

import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;

import java.io.File;
import java.io.IOException;
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.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 {

    private static final Logger logger = Logger.getLogger("Minecraft.WorldEdit");

    private final WorldEdit we;

    public SnapshotUtilCommands(WorldEdit 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(
            aliases = { "restore", "/restore" },
            usage = "[snapshot]",
            desc = "Restore the selection from a snapshot",
            min = 0,
            max = 1
    )
    @Logging(REGION)
    @CommandPermissions("worldedit.snapshots.restore")
    public void restore(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();

        if (config.snapshotRepo == null) {
            player.printError("Snapshot/backup restore is not configured.");
            return;
        }

        Region region = session.getSelection(player.getWorld());
        Snapshot snapshot;

        if (args.argsLength() > 0) {
            try {
                snapshot = config.snapshotRepo.getSnapshot(args.getString(0));
            } catch (InvalidSnapshotException e) {
                player.printError("That snapshot does not exist or is not available.");
                return;
            }
        } else {
            snapshot = session.getSnapshot();
        }

        // No snapshot set?
        if (snapshot == null) {
            try {
                snapshot = config.snapshotRepo.getDefaultSnapshot(player.getWorld().getName());

                if (snapshot == null) {
                    player.printError("No snapshots were found. See console for details.");

                    // Okay, let's toss some debugging information!
                    File dir = config.snapshotRepo.getDirectory();

                    try {
                        logger.info("WorldEdit found no snapshots: looked in: "
                                + dir.getCanonicalPath());
                    } catch (IOException e) {
                        logger.info("WorldEdit found no snapshots: looked in "
                                + "(NON-RESOLVABLE PATH - does it exist?): "
                                + dir.getPath());
                    }

                    return;
                }
            } catch (MissingWorldException ex) {
                player.printError("No snapshots were found for this world.");
                return;
            }
        }

        ChunkStore chunkStore = null;

        // Load chunk store
        try {
            chunkStore = snapshot.getChunkStore();
            player.print("Snapshot '" + snapshot.getName() + "' loaded; now restoring...");
        } catch (DataException e) {
            player.printError("Failed to load snapshot: " + e.getMessage());
            return;
        } catch (IOException e) {
            player.printError("Failed to load snapshot: " + e.getMessage());
            return;
        }

        try {
            // Restore snapshot
            SnapshotRestore restore = new SnapshotRestore(chunkStore, editSession, region);
            //player.print(restore.getChunksAffected() + " chunk(s) will be loaded.");

            restore.restore();

            if (restore.hadTotalFailure()) {
                String error = restore.getLastErrorMessage();
                if (error != null) {
                    player.printError("Errors prevented any blocks from being restored.");
                    player.printError("Last error: " + error);
                } else {
                    player.printError("No chunks could be loaded. (Bad archive?)");
                }
            } else {
                player.print(String.format("Restored; %d "
                        + "missing chunks and %d other errors.",
                        restore.getMissingChunks().size(),
                        restore.getErrorChunks().size()));
            }
        } finally {
            try {
                chunkStore.close();
            } catch (IOException e) {
            }
        }
    }
}
=======
// $Id$
/*
 * WorldEdit
 * Copyright (C) 2010, 2011 sk89q  and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see .
 */

package com.sk89q.worldedit.commands;

import static com.sk89q.minecraft.util.commands.Logging.LogMode.*;

import java.io.File;
import java.io.IOException;
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.minecraft.util.commands.Logging;
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.data.ChunkStore;
import com.sk89q.worldedit.data.DataException;
import com.sk89q.worldedit.data.MissingWorldException;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.snapshots.InvalidSnapshotException;
import com.sk89q.worldedit.snapshots.Snapshot;
import com.sk89q.worldedit.snapshots.SnapshotRestore;

public class SnapshotUtilCommands {

    private static final Logger logger = Logger.getLogger("Minecraft.WorldEdit");

    private final WorldEdit we;

    public SnapshotUtilCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
            aliases = { "restore", "/restore" },
            usage = "[snapshot]",
            desc = "Restore the selection from a snapshot",
            min = 0,
            max = 1
    )
    @Logging(REGION)
    @CommandPermissions("worldedit.snapshots.restore")
    public void restore(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();

        if (config.snapshotRepo == null) {
            player.printError("Snapshot/backup restore is not configured.");
            return;
        }

        Region region = session.getSelection(player.getWorld());
        Snapshot snapshot;

        if (args.argsLength() > 0) {
            try {
                snapshot = config.snapshotRepo.getSnapshot(args.getString(0));
            } catch (InvalidSnapshotException e) {
                player.printError("That snapshot does not exist or is not available.");
                return;
            }
        } else {
            snapshot = session.getSnapshot();
        }

        // No snapshot set?
        if (snapshot == null) {
            try {
                snapshot = config.snapshotRepo.getDefaultSnapshot(player.getWorld().getName());

                if (snapshot == null) {
                    player.printError("No snapshots were found. See console for details.");

                    // Okay, let's toss some debugging information!
                    File dir = config.snapshotRepo.getDirectory();

                    try {
                        logger.info("WorldEdit found no snapshots: looked in: "
                                + dir.getCanonicalPath());
                    } catch (IOException e) {
                        logger.info("WorldEdit found no snapshots: looked in "
                                + "(NON-RESOLVABLE PATH - does it exist?): "
                                + dir.getPath());
                    }

                    return;
                }
            } catch (MissingWorldException ex) {
                player.printError("No snapshots were found for this world.");
                return;
            }
        }

        ChunkStore chunkStore = null;

        // Load chunk store
        try {
            chunkStore = snapshot.getChunkStore();
            player.print("Snapshot '" + snapshot.getName() + "' loaded; now restoring...");
        } catch (DataException e) {
            player.printError("Failed to load snapshot: " + e.getMessage());
            return;
        } catch (IOException e) {
            player.printError("Failed to load snapshot: " + e.getMessage());
            return;
        }

        try {
            // Restore snapshot
            SnapshotRestore restore = new SnapshotRestore(chunkStore, region);
            //player.print(restore.getChunksAffected() + " chunk(s) will be loaded.");

            restore.restore(editSession);

            if (restore.hadTotalFailure()) {
                String error = restore.getLastErrorMessage();
                if (error != null) {
                    player.printError("Errors prevented any blocks from being restored.");
                    player.printError("Last error: " + error);
                } else {
                    player.printError("No chunks could be loaded. (Bad archive?)");
                }
            } else {
                player.print(String.format("Restored; %d "
                        + "missing chunks and %d other errors.",
                        restore.getMissingChunks().size(),
                        restore.getErrorChunks().size()));
            }
        } finally {
            try {
                chunkStore.close();
            } catch (IOException e) {
            }
        }
    }
}
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df:src/main/java/com/sk89q/worldedit/commands/SnapshotUtilCommands.java
Solution content
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

package com.sk89q.worldedit.command;

import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;

import java.io.File;
import java.io.IOException;
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.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 {

    private static final Logger logger = Logger.getLogger("Minecraft.WorldEdit");

    private final WorldEdit we;

    public SnapshotUtilCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
            aliases = { "restore", "/restore" },
            usage = "[snapshot]",
            desc = "Restore the selection from a snapshot",
            min = 0,
            max = 1
    )
    @Logging(REGION)
    @CommandPermissions("worldedit.snapshots.restore")
    public void restore(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();

        if (config.snapshotRepo == null) {
            player.printError("Snapshot/backup restore is not configured.");
            return;
        }


        Region region = session.getSelection(player.getWorld());
        Snapshot snapshot;

        if (args.argsLength() > 0) {
            try {
                snapshot = config.snapshotRepo.getSnapshot(args.getString(0));
            } catch (InvalidSnapshotException e) {
                player.printError("That snapshot does not exist or is not available.");
                return;
            }
        } else {
            snapshot = session.getSnapshot();
        }

        // No snapshot set?
        if (snapshot == null) {
            try {
                snapshot = config.snapshotRepo.getDefaultSnapshot(player.getWorld().getName());

                if (snapshot == null) {
                    player.printError("No snapshots were found. See console for details.");

                    // Okay, let's toss some debugging information!
                    File dir = config.snapshotRepo.getDirectory();

                    try {
                        logger.info("WorldEdit found no snapshots: looked in: "
                                + dir.getCanonicalPath());
                    } catch (IOException e) {
                        logger.info("WorldEdit found no snapshots: looked in "
                                + "(NON-RESOLVABLE PATH - does it exist?): "
                                + dir.getPath());
                    }

                    return;
                }
            } catch (MissingWorldException ex) {
                player.printError("No snapshots were found for this world.");
                return;
            }
        }

        ChunkStore chunkStore = null;

        // Load chunk store
        try {
            chunkStore = snapshot.getChunkStore();
            player.print("Snapshot '" + snapshot.getName() + "' loaded; now restoring...");
        } catch (DataException e) {
            player.printError("Failed to load snapshot: " + e.getMessage());
            return;
        } catch (IOException e) {
            player.printError("Failed to load snapshot: " + e.getMessage());
            return;
        }

        try {
            // Restore snapshot
            SnapshotRestore restore = new SnapshotRestore(chunkStore, editSession, region);
            //player.print(restore.getChunksAffected() + " chunk(s) will be loaded.");

            restore.restore();
            if (restore.hadTotalFailure()) {
                String error = restore.getLastErrorMessage();
                if (error != null) {
                    player.printError("Errors prevented any blocks from being restored.");
                    player.printError("Last error: " + error);
                } else {
                    player.printError("No chunks could be loaded. (Bad archive?)");
                }
            } else {
                player.print(String.format("Restored; %d "
                        + "missing chunks and %d other errors.",
                        restore.getMissingChunks().size(),
                        restore.getErrorChunks().size()));
            }
        } finally {
            try {
                chunkStore.close();
            } catch (IOException e) {
            }
        }
    }
}
File
SnapshotUtilCommands.java
Developer's decision
Combination
Kind of conflict
Class declaration
Comment
Import
Package declaration
Chunk
Conflicting content
<<<<<<< HEAD:src/main/java/com/sk89q/worldedit/command/ToolCommands.java
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

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.minecraft.util.commands.NestedCommand;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.command.tool.*;
import com.sk89q.worldedit.util.TreeGenerator;

public class ToolCommands {
    private final WorldEdit we;

    public ToolCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "none" },
        usage = "",
        desc = "Unbind a bound tool from your current item",
        min = 0,
        max = 0
    )
    public void none(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), null);
        player.print("Tool unbound from your current item.");
    }

    @Command(
        aliases = { "info" },
        usage = "",
        desc = "Block information tool",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.tool.info")
    public void info(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), new QueryTool());
        player.print("Info tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "tree" },
        usage = "[type]",
        desc = "Tree generator tool",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.tool.tree")
    @SuppressWarnings("deprecation")
    public void tree(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        TreeGenerator.TreeType type = args.argsLength() > 0 ?
                type = TreeGenerator.lookup(args.getString(0))
                : TreeGenerator.TreeType.TREE;

        if (type == null) {
            player.printError("Tree type '" + args.getString(0) + "' is unknown.");
            return;
        }

        session.setTool(player.getItemInHand(), new TreePlanter(new TreeGenerator(type)));
        player.print("Tree tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "repl" },
        usage = "",
        desc = "Block replacer tool",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.tool.replacer")
    public void repl(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock targetBlock = we.getBlock(player, args.getString(0));
        session.setTool(player.getItemInHand(), new BlockReplacer(targetBlock));
        player.print("Block replacer tool bound to "
    @NestedCommand(BrushCommands.class)
import com.sk89q.worldedit.tools.FloodFillTool;
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "cycler" },
        usage = "",
        desc = "Block data cycler tool",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.tool.data-cycler")
    public void cycler(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), new BlockDataCyler());
        player.print("Block data cycler tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "floodfill", "flood" },
        usage = " ",
        desc = "Flood fill tool",
        min = 2,
        max = 2
    )
    @CommandPermissions("worldedit.tool.flood-fill")
    public void floodFill(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();
        int range = args.getInteger(1);

        if (range > config.maxSuperPickaxeSize) {
            player.printError("Maximum range: " + config.maxSuperPickaxeSize);
            return;
        }

        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        session.setTool(player.getItemInHand(), new FloodFillTool(range, pattern));
        player.print("Block flood fill tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "brush", "br" },
        desc = "Brush tool"
    )
    public void brush(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
    }

    @Command(
            aliases = { "deltree" },
            usage = "",
            desc = "Floating tree remover tool",
            min = 0,
            max = 0
    )
    @CommandPermissions("worldedit.tool.deltree")
    public void deltree(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

    session.setTool(player.getItemInHand(), new FloatingTreeRemover());
    player.print("Floating tree remover tool bound to "
            + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
            aliases = { "farwand" },
            usage = "",
            desc = "Wand at a distance tool",
            min = 0,
            max = 0
    )
    @CommandPermissions("worldedit.tool.farwand")
    public void farwand(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), new DistanceWand());
        player.print("Far wand tool bound to " + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
            aliases = { "lrbuild", "/lrbuild" },
            usage = " ",
            desc = "Long-range building tool",
            min = 2,
            max = 2
    )
    @CommandPermissions("worldedit.tool.lrbuild")
    public void longrangebuildtool(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock secondary = we.getBlock(player, args.getString(0));
        BaseBlock primary = we.getBlock(player, args.getString(1));
        session.setTool(player.getItemInHand(), new LongRangeBuildTool(primary, secondary));
        player.print("Long-range building tool bound to " + ItemType.toHeldName(player.getItemInHand()) + ".");
        player.print("Left-click set to " + ItemType.toName(secondary.getType()) + "; right-click set to "
                + ItemType.toName(primary.getType()) + ".");
    }
}
=======
// $Id$
/*
 * WorldEdit
 * Copyright (C) 2010, 2011 sk89q  and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see .
*/

package com.sk89q.worldedit.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.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.BaseBlock;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.tools.BlockDataCyler;
import com.sk89q.worldedit.tools.BlockReplacer;
import com.sk89q.worldedit.tools.DistanceWand;
import com.sk89q.worldedit.tools.FloatingTreeRemover;
    }
import com.sk89q.worldedit.tools.LongRangeBuildTool;
import com.sk89q.worldedit.tools.QueryTool;
import com.sk89q.worldedit.tools.TreePlanter;
import com.sk89q.worldedit.util.TreeGenerator;

public class ToolCommands {
    private final WorldEdit we;

    public ToolCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "none" },
        usage = "",
        desc = "Unbind a bound tool from your current item",
        min = 0,
        max = 0
    )
    public void none(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), null);
        player.print("Tool unbound from your current item.");
    }

    @Command(
        aliases = { "info" },
        usage = "",
        desc = "Block information tool",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.tool.info")
    public void info(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), new QueryTool());
        player.print("Info tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "tree" },
        usage = "[type]",
        desc = "Tree generator tool",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.tool.tree")
    @SuppressWarnings("deprecation")
    public void tree(CommandContext args, LocalSession session, LocalPlayer player,

    @Command(
            EditSession editSession) throws WorldEditException {

        TreeGenerator.TreeType type = args.argsLength() > 0 ?
                type = TreeGenerator.lookup(args.getString(0))
                : TreeGenerator.TreeType.TREE;

        if (type == null) {
            player.printError("Tree type '" + args.getString(0) + "' is unknown.");
            return;
        }

        session.setTool(player.getItemInHand(), new TreePlanter(new TreeGenerator(type)));
        player.print("Tree tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "repl" },
        usage = "",
        desc = "Block replacer tool",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.tool.replacer")
    public void repl(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock targetBlock = we.getBlock(player, args.getString(0));
        session.setTool(player.getItemInHand(), new BlockReplacer(targetBlock));
        player.print("Block replacer tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "cycler" },
        usage = "",
        desc = "Block data cycler tool",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.tool.data-cycler")
    public void cycler(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), new BlockDataCyler());
        player.print("Block data cycler tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
        aliases = { "floodfill", "flood" },
        usage = " ",
        desc = "Flood fill tool",
        min = 2,
        max = 2
    )
    @CommandPermissions("worldedit.tool.flood-fill")
    public void floodFill(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();
        int range = args.getInteger(1);

        if (range > config.maxSuperPickaxeSize) {
            player.printError("Maximum range: " + config.maxSuperPickaxeSize);
            return;
        }

        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        session.setTool(player.getItemInHand(), new FloodFillTool(range, pattern));
        player.print("Block flood fill tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
            aliases = { "deltree" },
            usage = "",
            desc = "Floating tree remover tool",
            min = 0,
            max = 0
    )
    @CommandPermissions("worldedit.tool.deltree")
    public void deltree(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

    session.setTool(player.getItemInHand(), new FloatingTreeRemover());
    player.print("Floating tree remover tool bound to "
            + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
            aliases = { "farwand" },
            usage = "",
            desc = "Wand at a distance tool",
            min = 0,
            max = 0
    )
    @CommandPermissions("worldedit.tool.farwand")
    public void farwand(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), new DistanceWand());
        player.print("Far wand tool bound to " + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
            aliases = { "lrbuild", "/lrbuild" },
            usage = " ",
            desc = "Long-range building tool",
            min = 2,
            max = 2
    )
    @CommandPermissions("worldedit.tool.lrbuild")
    public void longrangebuildtool(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock secondary = we.getBlock(player, args.getString(0));
        BaseBlock primary = we.getBlock(player, args.getString(1));
        session.setTool(player.getItemInHand(), new LongRangeBuildTool(primary, secondary));
        player.print("Long-range building tool bound to " + ItemType.toHeldName(player.getItemInHand()) + ".");
        player.print("Left-click set to " + ItemType.toName(secondary.getType()) + "; right-click set to "
                + ItemType.toName(primary.getType()) + ".");
    }
}
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df:src/main/java/com/sk89q/worldedit/commands/ToolCommands.java
Solution content
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

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.minecraft.util.commands.NestedCommand;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.command.tool.*;
import com.sk89q.worldedit.util.TreeGenerator;

public class ToolCommands {
    private final WorldEdit we;

    public ToolCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "none" },
        usage = "",
        desc = "Unbind a bound tool from your current item",
        min = 0,
        max = 0
    )
    public void none(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), null);
        player.print("Tool unbound from your current item.");
    }

    @Command(
        aliases = { "info" },
        usage = "",
        desc = "Block information tool",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.tool.info")
    public void info(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), new QueryTool());
        player.print("Info tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "tree" },
        usage = "[type]",
        desc = "Tree generator tool",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.tool.tree")
    @SuppressWarnings("deprecation")
    public void tree(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        TreeGenerator.TreeType type = args.argsLength() > 0 ?
                type = TreeGenerator.lookup(args.getString(0))
                : TreeGenerator.TreeType.TREE;

        if (type == null) {
            player.printError("Tree type '" + args.getString(0) + "' is unknown.");
            return;
        }

        session.setTool(player.getItemInHand(), new TreePlanter(new TreeGenerator(type)));
        player.print("Tree tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "repl" },
        usage = "",
        desc = "Block replacer tool",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.tool.replacer")
    public void repl(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock targetBlock = we.getBlock(player, args.getString(0));
        session.setTool(player.getItemInHand(), new BlockReplacer(targetBlock));
        player.print("Block replacer tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "cycler" },
        usage = "",
        desc = "Block data cycler tool",
        min = 0,
        max = 0
    )
    @CommandPermissions("worldedit.tool.data-cycler")
    public void cycler(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), new BlockDataCyler());
        player.print("Block data cycler tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
        aliases = { "floodfill", "flood" },
        usage = " ",
        desc = "Flood fill tool",
        min = 2,
        max = 2
    )
    @CommandPermissions("worldedit.tool.flood-fill")
    public void floodFill(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();
        int range = args.getInteger(1);

        if (range > config.maxSuperPickaxeSize) {
            player.printError("Maximum range: " + config.maxSuperPickaxeSize);
            return;
        }

        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        session.setTool(player.getItemInHand(), new FloodFillTool(range, pattern));
        player.print("Block flood fill tool bound to "
                + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
            aliases = { "deltree" },
            usage = "",
            desc = "Floating tree remover tool",
            min = 0,
            max = 0
    )
    @CommandPermissions("worldedit.tool.deltree")
    public void deltree(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

    session.setTool(player.getItemInHand(), new FloatingTreeRemover());
    player.print("Floating tree remover tool bound to "
            + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
            aliases = { "farwand" },
            usage = "",
            desc = "Wand at a distance tool",
            min = 0,
            max = 0
    )
    @CommandPermissions("worldedit.tool.farwand")
    public void farwand(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        session.setTool(player.getItemInHand(), new DistanceWand());
        player.print("Far wand tool bound to " + ItemType.toHeldName(player.getItemInHand()) + ".");
    }

    @Command(
            aliases = { "lrbuild", "/lrbuild" },
            usage = " ",
            desc = "Long-range building tool",
            min = 2,
            max = 2
    )
    @CommandPermissions("worldedit.tool.lrbuild")
    public void longrangebuildtool(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock secondary = we.getBlock(player, args.getString(0));
        BaseBlock primary = we.getBlock(player, args.getString(1));
        session.setTool(player.getItemInHand(), new LongRangeBuildTool(primary, secondary));
        player.print("Long-range building tool bound to " + ItemType.toHeldName(player.getItemInHand()) + ".");
        player.print("Left-click set to " + ItemType.toName(secondary.getType()) + "; right-click set to "
                + ItemType.toName(primary.getType()) + ".");
    }
File
ToolCommands.java
Developer's decision
Combination
Kind of conflict
Class declaration
Comment
Import
Package declaration
Chunk
Conflicting content
<<<<<<< HEAD:src/main/java/com/sk89q/worldedit/command/ToolUtilCommands.java
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

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.minecraft.util.commands.NestedCommand;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.masks.Mask;
import com.sk89q.worldedit.patterns.Pattern;

/**
 * Tool commands.
 * 
 * @author sk89q
 */
public class ToolUtilCommands {
    private final WorldEdit we;

    public ToolUtilCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "/", "," },
        usage = "[on|off]",
        desc = "Toggle the super pickaxe pickaxe function",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.superpickaxe")
    public void togglePickaxe(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        String newState = args.getString(0, null);
        if (session.hasSuperPickAxe()) {
            if ("on".equals(newState)) {
                player.printError("Super pick axe already enabled.");
                return;
            }

            session.disableSuperPickAxe();
            player.print("Super pick axe disabled.");
        } else {
            if ("off".equals(newState)) {
 *
                player.printError("Super pick axe already disabled.");
                return;
            }
            session.enableSuperPickAxe();
            player.print("Super pick axe enabled.");
        }

    }

    @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(
        aliases = { "mask" },
        usage = "[mask]",
        desc = "Set the brush mask",
        min = 0,
        max = -1
    )
    @CommandPermissions("worldedit.brush.options.mask")
    public void mask(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        if (args.argsLength() == 0) {
            session.getBrushTool(player.getItemInHand()).setMask(null);
            player.print("Brush mask disabled.");
        } else {
            Mask mask = we.getBlockMask(player, session, args.getJoinedStrings(0));
            session.getBrushTool(player.getItemInHand()).setMask(mask);
            player.print("Brush mask set.");
        }
    }

    @Command(
        aliases = { "mat", "material" },
        usage = "[pattern]",
        desc = "Set the brush material",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.brush.options.material")
    public void material(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        session.getBrushTool(player.getItemInHand()).setFill(pattern);
        player.print("Brush material set.");
    }

    @Command(
            aliases = { "range" },
            usage = "[pattern]",
            desc = "Set the brush range",
            min = 1,
            max = 1
        )
    @CommandPermissions("worldedit.brush.options.range")
    public void range(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        int range = args.getInteger(0);
        session.getBrushTool(player.getItemInHand()).setRange(range);
        player.print("Brush range set.");
    }

    @Command(
        aliases = { "size" },
        usage = "[pattern]",
        desc = "Set the brush size",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.brush.options.size")
    public void size(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        int radius = args.getInteger(0);
        we.checkMaxBrushRadius(radius);

        session.getBrushTool(player.getItemInHand()).setSize(radius);
        player.print("Brush size set.");
    }
}
=======
// $Id$
/*
 * WorldEdit
 * Copyright (C) 2010 sk89q  and contributors
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see .
*/

package com.sk89q.worldedit.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.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.masks.Mask;
import com.sk89q.worldedit.patterns.Pattern;

/**
 * Tool commands.
 * 
 * @author sk89q
 */
public class ToolUtilCommands {
    private final WorldEdit we;

    public ToolUtilCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "/", "," },
        usage = "[on|off]",
        desc = "Toggle the super pickaxe pickaxe function",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.superpickaxe")
    public void togglePickaxe(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        String newState = args.getString(0, null);
        if (session.hasSuperPickAxe()) {
            if ("on".equals(newState)) {
                player.printError("Super pick axe already enabled.");
                return;
            }

            session.disableSuperPickAxe();
            player.print("Super pick axe disabled.");
        } else {
            if ("off".equals(newState)) {
                player.printError("Super pick axe already disabled.");
                return;
            }
            session.enableSuperPickAxe();
            player.print("Super pick axe enabled.");
        }

    }

    @Command(
        aliases = { "mask" },
        usage = "[mask]",
        desc = "Set the brush mask",
        min = 0,
        max = -1
    )
    @CommandPermissions("worldedit.brush.options.mask")
    public void mask(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        if (args.argsLength() == 0) {
            session.getBrushTool(player.getItemInHand()).setMask(null);
            player.print("Brush mask disabled.");
        } else {
            Mask mask = we.getBlockMask(player, session, args.getJoinedStrings(0));
            session.getBrushTool(player.getItemInHand()).setMask(mask);
            player.print("Brush mask set.");
        }
    }

    @Command(
        aliases = { "mat", "material", "fill" },
        usage = "[pattern]",
        desc = "Set the brush material",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.brush.options.material")
    public void material(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        session.getBrushTool(player.getItemInHand()).setFill(pattern);
        player.print("Brush material set.");
    }

    @Command(
            aliases = { "range" },
            usage = "[pattern]",
            desc = "Set the brush range",
            min = 1,
            max = 1
        )
    @CommandPermissions("worldedit.brush.options.range")
    public void range(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        int range = args.getInteger(0);
        session.getBrushTool(player.getItemInHand()).setRange(range);
        player.print("Brush range set.");
    }

    @Command(
        aliases = { "size" },
        usage = "[pattern]",
        desc = "Set the brush size",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.brush.options.size")
    public void size(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        LocalConfiguration config = we.getConfiguration();

        int radius = args.getInteger(0);
        if (radius > config.maxBrushRadius) {
            player.printError("Maximum allowed brush radius: "
                    + config.maxBrushRadius);
            return;
        }

        session.getBrushTool(player.getItemInHand()).setSize(radius);
        player.print("Brush size set.");
    }
}
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df:src/main/java/com/sk89q/worldedit/commands/ToolUtilCommands.java
Solution content
                return;
            }
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

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.masks.Mask;
import com.sk89q.worldedit.patterns.Pattern;

/**
 * Tool commands.
 * 
 * @author sk89q
 */
public class ToolUtilCommands {
    private final WorldEdit we;

    public ToolUtilCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "/", "," },
        usage = "[on|off]",
        desc = "Toggle the super pickaxe pickaxe function",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.superpickaxe")
    public void togglePickaxe(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        String newState = args.getString(0, null);
        if (session.hasSuperPickAxe()) {
            if ("on".equals(newState)) {
                player.printError("Super pick axe already enabled.");
                return;
            }

            session.disableSuperPickAxe();
            player.print("Super pick axe disabled.");
        } else {
            if ("off".equals(newState)) {
                player.printError("Super pick axe already disabled.");
            session.enableSuperPickAxe();
            player.print("Super pick axe enabled.");
        }

    }

    @Command(
        aliases = { "mask" },
        usage = "[mask]",
        desc = "Set the brush mask",
        min = 0,
        max = -1
    )
    @CommandPermissions("worldedit.brush.options.mask")
    public void mask(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        if (args.argsLength() == 0) {
            session.getBrushTool(player.getItemInHand()).setMask(null);
            player.print("Brush mask disabled.");
        } else {
            Mask mask = we.getBlockMask(player, session, args.getJoinedStrings(0));
            session.getBrushTool(player.getItemInHand()).setMask(mask);
            player.print("Brush mask set.");
        }
    }

    @Command(
        aliases = { "mat", "material" },
        usage = "[pattern]",
        desc = "Set the brush material",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.brush.options.material")
    public void material(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        session.getBrushTool(player.getItemInHand()).setFill(pattern);
        player.print("Brush material set.");
    }

    @Command(
            aliases = { "range" },
            usage = "[pattern]",
            desc = "Set the brush range",
            min = 1,
            max = 1
        )
    @CommandPermissions("worldedit.brush.options.range")
    public void range(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        int range = args.getInteger(0);
        session.getBrushTool(player.getItemInHand()).setRange(range);
        player.print("Brush range set.");
    }

    @Command(
        aliases = { "size" },
        usage = "[pattern]",
        desc = "Set the brush size",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.brush.options.size")
    public void size(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        int radius = args.getInteger(0);
        we.checkMaxBrushRadius(radius);

        session.getBrushTool(player.getItemInHand()).setSize(radius);
        player.print("Brush size set.");
    }
}
File
ToolUtilCommands.java
Developer's decision
Combination
Kind of conflict
Class declaration
Comment
Import
Package declaration
Chunk
Conflicting content
    }


<<<<<<< HEAD:src/main/java/com/sk89q/worldedit/command/UtilityCommands.java
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

package com.sk89q.worldedit.command;

import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.LocalWorld.KillFlags;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.patterns.SingleBlockPattern;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.World;

import java.util.Comparator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import static com.sk89q.minecraft.util.commands.Logging.LogMode.PLACEMENT;

/**
 * Utility commands.
 * 
 * @author sk89q
 */
public class UtilityCommands {
    private final WorldEdit we;

    public UtilityCommands(WorldEdit we) {
        this.we = we;
    }
    @Command(
        aliases = { "/fill" },
        usage = "  [depth]",
        desc = "Fill a hole",
        min = 2,
        max = 3
    )
    @CommandPermissions("worldedit.fill")
    @Logging(PLACEMENT)
    public void fill(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        double radius = Math.max(1, args.getDouble(1));
        we.checkMaxRadius(radius);
        int depth = args.argsLength() > 2 ? Math.max(1, args.getInteger(2)) : 1;

        Vector pos = session.getPlacementPosition(player);
        int affected = 0;
        if (pattern instanceof SingleBlockPattern) {
            affected = editSession.fillXZ(pos,
                    ((SingleBlockPattern) pattern).getBlock(),
                    radius, depth, false);
        } else {
            affected = editSession.fillXZ(pos, pattern, radius, depth, false);
        }
        player.print(affected + " block(s) have been created.");
    }

    @Command(
        aliases = { "/fillr" },
        usage = "  [depth]",
        desc = "Fill a hole recursively",
        min = 2,
        max = 3
    )
    @CommandPermissions("worldedit.fill.recursive")
    @Logging(PLACEMENT)
    public void fillr(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        double radius = Math.max(1, args.getDouble(1));
        we.checkMaxRadius(radius);
        int depth = args.argsLength() > 2 ? Math.max(1, args.getInteger(2)) : Integer.MAX_VALUE;

        Vector pos = session.getPlacementPosition(player);
        int affected = 0;
        if (pattern instanceof SingleBlockPattern) {
            affected = editSession.fillXZ(pos,
                    ((SingleBlockPattern) pattern).getBlock(),
                    radius, depth, true);
        } else {
            affected = editSession.fillXZ(pos, pattern, radius, depth, true);
        }
        player.print(affected + " block(s) have been created.");
    }

    @Command(
        aliases = { "/drain" },
        usage = "",
        desc = "Drain a pool",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.drain")
    @Logging(PLACEMENT)
    public void drain(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double radius = Math.max(0, args.getDouble(0));
        we.checkMaxRadius(radius);
        int affected = editSession.drainArea(
                session.getPlacementPosition(player), radius);
        player.print(affected + " block(s) have been changed.");
    }

    @Command(
        aliases = { "/fixlava", "fixlava" },
        usage = "",
        desc = "Fix lava to be stationary",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.fixlava")
    @Logging(PLACEMENT)
    public void fixLava(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double radius = Math.max(0, args.getDouble(0));
        we.checkMaxRadius(radius);
        int affected = editSession.fixLiquid(
                session.getPlacementPosition(player), radius, 10, 11);
        player.print(affected + " block(s) have been changed.");
    }

    @Command(
        aliases = { "/fixwater", "fixwater" },
        usage = "",
        desc = "Fix water to be stationary",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.fixwater")
    @Logging(PLACEMENT)
    public void fixWater(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double radius = Math.max(0, args.getDouble(0));
        we.checkMaxRadius(radius);
        int affected = editSession.fixLiquid(
                session.getPlacementPosition(player), radius, 8, 9);
        player.print(affected + " block(s) have been changed.");
    }

    @Command(
        aliases = { "/removeabove", "removeabove" },
        usage = "[size] [height]",
        desc = "Remove blocks above your head.",
        min = 0,
        max = 2
    )
    @CommandPermissions("worldedit.removeabove")
    @Logging(PLACEMENT)
    public void removeAbove(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
        we.checkMaxRadius(size);
        World world = player.getWorld();
        int height = args.argsLength() > 1 ? Math.min((world.getMaxY() + 1), args.getInteger(1) + 2) : (world.getMaxY() + 1);

        int affected = editSession.removeAbove(
                session.getPlacementPosition(player), size, height);
        player.print(affected + " block(s) have been removed.");
    }

    @Command(
        aliases = { "/removebelow", "removebelow" },
        usage = "[size] [height]",
        desc = "Remove blocks below you.",
        min = 0,
        max = 2
    )
    @CommandPermissions("worldedit.removebelow")
    @Logging(PLACEMENT)
    public void removeBelow(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
        we.checkMaxRadius(size);
        World world = player.getWorld();
        int height = args.argsLength() > 1 ? Math.min((world.getMaxY() + 1), args.getInteger(1) + 2) : (world.getMaxY() + 1);

        int affected = editSession.removeBelow(session.getPlacementPosition(player), size, height);
        player.print(affected + " block(s) have been removed.");
    }

    @Command(
        aliases = { "/removenear", "removenear" },
        usage = " [size]",
        desc = "Remove blocks near you.",
        min = 1,
        max = 2
    )
    @CommandPermissions("worldedit.removenear")
    @Logging(PLACEMENT)
    public void removeNear(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock block = we.getBlock(player, args.getString(0), true);
        int size = Math.max(1, args.getInteger(1, 50));
        we.checkMaxRadius(size);

        int affected = editSession.removeNear(session.getPlacementPosition(player), block.getType(), size);
        player.print(affected + " block(s) have been removed.");
    }

    @Command(
        aliases = { "/replacenear", "replacenear" },
        usage = "  ",
        desc = "Replace nearby blocks",
        flags = "f",
        min = 3,
        max = 3
    )
    @CommandPermissions("worldedit.replacenear")
    @Logging(PLACEMENT)
    public void replaceNear(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        int size = Math.max(1, args.getInteger(0));
        int affected;
        Set from;
        Pattern to;
        if (args.argsLength() == 2) {
            from = null;
            to = we.getBlockPattern(player, args.getString(1));
        } else {
            from = we.getBlocks(player, args.getString(1), true, !args.hasFlag('f'));
            to = we.getBlockPattern(player, args.getString(2));
        }

        Vector base = session.getPlacementPosition(player);
        Vector min = base.subtract(size, size, size);
        Vector max = base.add(size, size, size);
        Region region = new CuboidRegion(player.getWorld(), min, max);

        if (to instanceof SingleBlockPattern) {
            affected = editSession.replaceBlocks(region, from, ((SingleBlockPattern) to).getBlock());
        } else {
            affected = editSession.replaceBlocks(region, from, to);
        }
        player.print(affected + " block(s) have been replaced.");
    }

    @Command(
        aliases = { "/snow", "snow" },
        usage = "[radius]",
        desc = "Simulates snow",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.snow")
    @Logging(PLACEMENT)
    public void snow(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;

        int affected = editSession.simulateSnow(session.getPlacementPosition(player), size);
        player.print(affected + " surfaces covered. Let it snow~");
    }

    @Command(
        aliases = {"/thaw", "thaw"},
        usage = "[radius]",
        desc = "Thaws the area",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.thaw")
    @Logging(PLACEMENT)
    public void thaw(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;

        int affected = editSession.thaw(session.getPlacementPosition(player), size);
        player.print(affected + " surfaces thawed.");
    }

    @Command(
        aliases = { "/green", "green" },
        usage = "[radius]",
        desc = "Greens the area",
        flags = "f",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.green")
    @Logging(PLACEMENT)
    public void green(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        final double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;
        final boolean onlyNormalDirt = !args.hasFlag('f');

        final int affected = editSession.green(session.getPlacementPosition(player), size, onlyNormalDirt);
        player.print(affected + " surfaces greened.");
    }

    @Command(
            aliases = { "/ex", "/ext", "/extinguish", "ex", "ext", "extinguish" },
            usage = "[radius]",
            desc = "Extinguish nearby fire",
            min = 0,
            max = 1
        )
    @CommandPermissions("worldedit.extinguish")
    @Logging(PLACEMENT)
    public void extinguish(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();

        int defaultRadius = config.maxRadius != -1 ? Math.min(40, config.maxRadius) : 40;
        int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0))
                : defaultRadius;
        we.checkMaxRadius(size);

        int affected = editSession.removeNear(session.getPlacementPosition(player), 51, size);
        player.print(affected + " block(s) have been removed.");
    }

    @Command(
        aliases = { "butcher" },
        usage = "[radius]",
        flags = "plangbtf",
        desc = "Kill all or nearby mobs",
        help =
            "Kills nearby mobs, based on radius, if none is given uses default in configuration.\n" +
            "Flags:" +
            "  -p also kills pets.\n" +
            "  -n also kills NPCs.\n" +
            "  -g also kills Golems.\n" +
            "  -a also kills animals.\n" +
            "  -b also kills ambient mobs.\n" +
            "  -t also kills mobs with name tags.\n" +
            "  -f compounds all previous flags.\n" +
            "  -l strikes lightning on each killed mob.",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.butcher")
    @Logging(PLACEMENT)
    @Console
    public void butcher(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();

        // technically the default can be larger than the max, but that's not my problem
        int radius = config.butcherDefaultRadius;

        // there might be a better way to do this but my brain is fried right now
        if (args.argsLength() > 0) { // user inputted radius, override the default
            radius = args.getInteger(0);
            if (config.butcherMaxRadius != -1) { // clamp if there is a max
                if (radius == -1) {
                    radius = config.butcherMaxRadius;
                } else { // Math.min does not work if radius is -1 (actually highest possible value)
                || typeStr.matches("carts?")) {
                    radius = Math.min(radius, config.butcherMaxRadius);
                }
            }
        }

        FlagContainer flags = new FlagContainer(player);
        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.NPCS          , args.hasFlag('n'), "worldedit.butcher.npcs");
        flags.or(KillFlags.GOLEMS        , args.hasFlag('g'), "worldedit.butcher.golems");
        flags.or(KillFlags.ANIMALS       , args.hasFlag('a'), "worldedit.butcher.animals");
        flags.or(KillFlags.AMBIENT       , args.hasFlag('b'), "worldedit.butcher.ambient");
        flags.or(KillFlags.TAGGED        , args.hasFlag('t'), "worldedit.butcher.tagged");
        flags.or(KillFlags.WITH_LIGHTNING, args.hasFlag('l'), "worldedit.butcher.lightning");
        // If you add flags here, please add them to com.sk89q.worldedit.commands.BrushCommands.butcherBrush() as well

        int killed;
        if (player.isPlayer()) {
            killed = player.getWorld().killMobs(session.getPlacementPosition(player), radius, flags.flags);
        } else {
            killed = 0;
            for (World world : we.getServer().getWorlds()) {
                killed += world.killMobs(new Vector(), radius, flags.flags);
            }
        }

        if (radius < 0) {
            player.print("Killed " + killed + " mobs.");
        } else {
            player.print("Killed " + killed + " mobs in a radius of " + radius + ".");
        }
    }

    public static class FlagContainer {
        private final LocalPlayer player;
        public int flags = 0;
        public FlagContainer(LocalPlayer player) {
            this.player = player;
        }

        public void or(int flag, boolean on) {
            if (on) flags |= flag;
        }

        public void or(int flag, boolean on, String permission) {
            or(flag, on);

            if ((flags & flag) != 0 && !player.hasPermission(permission)) {
                flags &= ~flag;
            }
        }
    }

    @Command(
        aliases = { "remove", "rem", "rement" },
        usage = " ",
        desc = "Remove all entities of a type",
        min = 2,
        max = 2
    )
    @CommandPermissions("worldedit.remove")
    @Logging(PLACEMENT)
    @Console
    public void remove(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        String typeStr = args.getString(0);
        int radius = args.getInteger(1);

        if (radius < -1) {
            player.printError("Use -1 to remove all entities in loaded chunks");
            return;
        }

        EntityType type = null;

        if (typeStr.matches("all")) {
            type = EntityType.ALL;
        } else if (typeStr.matches("projectiles?|arrows?")) {
            type = EntityType.PROJECTILES;
        } else if (typeStr.matches("items?")
                || typeStr.matches("drops?")) {
            type = EntityType.ITEMS;
        } else if (typeStr.matches("falling(blocks?|sand|gravel)")) {
            type = EntityType.FALLING_BLOCKS;
        } else if (typeStr.matches("paintings?")
                || typeStr.matches("art")) {
            type = EntityType.PAINTINGS;
        } else if (typeStr.matches("(item)frames?")) {
            type = EntityType.ITEM_FRAMES;
        } else if (typeStr.matches("boats?")) {
            type = EntityType.BOATS;
        } else if (typeStr.matches("minecarts?")
            type = EntityType.MINECARTS;
        } else if (typeStr.matches("tnt")) {
            type = EntityType.TNT;
        } else if (typeStr.matches("xp")) {
            type = EntityType.XP_ORBS;
        } else {
            player.printError("Acceptable types: projectiles, items, paintings, itemframes, boats, minecarts, tnt, xp, or all");
            return;
        }

        int removed = 0;
        if (player.isPlayer()) {
            Vector origin = session.getPlacementPosition(player);
            removed = player.getWorld().removeEntities(type, origin, radius);
        } else {
            for (World world : we.getServer().getWorlds()) {
                removed += world.removeEntities(type, new Vector(), radius);
            }
        }
        player.print("Marked " + removed + " entit(ies) for removal.");
    }

    @Command(
        aliases = { "/help" },
        usage = "[]",
        desc = "Displays help for the given command or lists all commands.",
        min = 0,
        max = -1
    )
    @Console
    @CommandPermissions("worldedit.help")
    public void help(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        help(args, we, session, player, editSession);
    }

    public static void help(CommandContext args, WorldEdit we, LocalSession session, LocalPlayer player, EditSession editSession) {
        final CommandsManager commandsManager = we.getCommandsManager();

        if (args.argsLength() == 0) {
            SortedSet commands = new TreeSet(new Comparator() {
                @Override
                public int compare(String o1, String o2) {
        this.we = we;
                    final int ret = o1.replaceAll("/", "").compareToIgnoreCase(o2.replaceAll("/", ""));
                    if (ret == 0) {
                        return o1.compareToIgnoreCase(o2);
                    }
                    return ret;
                }
            });
            commands.addAll(commandsManager.getCommands().keySet());

            StringBuilder sb = new StringBuilder();
            boolean first = true;
            for (String command : commands) {
                if (!first) {
                    sb.append(", ");
                }

                sb.append('/');
                sb.append(command);
                first = false;
            }

            player.print(sb.toString());

            return;
        }

        String command = args.getJoinedStrings(0).toLowerCase().replaceAll("/", "");

        String helpMessage = commandsManager.getHelpMessages().get(command);
        if (helpMessage == null) {
            player.printError("Unknown command '" + command + "'.");
            return;
        }

        player.print(helpMessage);
    }
}
=======
// $Id$
/*
 * WorldEdit
 * Copyright (C) 2010 sk89q  and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see .
*/

package com.sk89q.worldedit.commands;

import static com.sk89q.minecraft.util.commands.Logging.LogMode.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

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.Console;
import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.rebar.command.CommandMapping;
import com.sk89q.rebar.command.Description;
import com.sk89q.rebar.command.Dispatcher;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.EntityType;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.LocalWorld;
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.patterns.Pattern;
import com.sk89q.worldedit.patterns.SingleBlockPattern;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;

/**
 * Utility commands.
 * 
 * @author sk89q
 */
public class UtilityCommands {
    private final WorldEdit we;

    public UtilityCommands(WorldEdit we) {
    @Logging(PLACEMENT)
    @Command(
        aliases = { "/fill" },
        usage = "  [depth]",
        desc = "Fill a hole",
        min = 2,
        max = 3
    )
    @CommandPermissions("worldedit.fill")
    @Logging(PLACEMENT)
    public void fill(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        double radius = Math.max(1, args.getDouble(1));
        we.checkMaxRadius(radius);
        int depth = args.argsLength() > 2 ? Math.max(1, args.getInteger(2)) : 1;

        Vector pos = session.getPlacementPosition(player);
        int affected = 0;
        if (pattern instanceof SingleBlockPattern) {
            affected = editSession.fillXZ(pos,
                    ((SingleBlockPattern) pattern).getBlock(),
                    radius, depth, false);
        } else {
            affected = editSession.fillXZ(pos, pattern, radius, depth, false);
        }
        player.print(affected + " block(s) have been created.");
    }

    @Command(
        aliases = { "/fillr" },
        usage = "  [depth]",
        desc = "Fill a hole recursively",
        min = 2,
        max = 3
    )
    @CommandPermissions("worldedit.fill.recursive")
    @Logging(PLACEMENT)
    public void fillr(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        double radius = Math.max(1, args.getDouble(1));
        we.checkMaxRadius(radius);
        int depth = args.argsLength() > 2 ? Math.max(1, args.getInteger(2)) : 1;

        Vector pos = session.getPlacementPosition(player);
        int affected = 0;
        if (pattern instanceof SingleBlockPattern) {
            affected = editSession.fillXZ(pos,
                    ((SingleBlockPattern) pattern).getBlock(),
                    radius, depth, true);
        } else {
            affected = editSession.fillXZ(pos, pattern, radius, depth, true);
        }
        player.print(affected + " block(s) have been created.");
    }

    @Command(
        aliases = { "/drain" },
        usage = "",
        desc = "Drain a pool",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.drain")
    @Logging(PLACEMENT)
    public void drain(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double radius = Math.max(0, args.getDouble(0));
        we.checkMaxRadius(radius);
        int affected = editSession.drainArea(
                session.getPlacementPosition(player), radius);
        player.print(affected + " block(s) have been changed.");
    }

    @Command(
        aliases = { "/fixlava", "fixlava" },
        usage = "",
        desc = "Fix lava to be stationary",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.fixlava")
    @Logging(PLACEMENT)
    public void fixLava(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double radius = Math.max(0, args.getDouble(0));
        we.checkMaxRadius(radius);
        int affected = editSession.fixLiquid(
                session.getPlacementPosition(player), radius, 10, 11);
        player.print(affected + " block(s) have been changed.");
    }

    @Command(
        aliases = { "/fixwater", "fixwater" },
        usage = "",
        desc = "Fix water to be stationary",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.fixwater")
    @Logging(PLACEMENT)
    public void fixWater(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double radius = Math.max(0, args.getDouble(0));
        we.checkMaxRadius(radius);
        int affected = editSession.fixLiquid(
                session.getPlacementPosition(player), radius, 8, 9);
        player.print(affected + " block(s) have been changed.");
    }

    @Command(
        aliases = { "/removeabove", "removeabove" },
        usage = "[size] [height]",
        desc = "Remove blocks above your head.",
        min = 0,
        max = 2
    )
    @CommandPermissions("worldedit.removeabove")
    @Logging(PLACEMENT)
    public void removeAbove(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
        we.checkMaxRadius(size);
        LocalWorld world = player.getWorld();
        int height = args.argsLength() > 1 ? Math.min((world.getMaxY() + 1), args.getInteger(1) + 2) : (world.getMaxY() + 1);

        int affected = editSession.removeAbove(
                session.getPlacementPosition(player), size, height);
        player.print(affected + " block(s) have been removed.");
    }

    @Command(
        aliases = { "/removebelow", "removebelow" },
        usage = "[size] [height]",
        desc = "Remove blocks below you.",
        min = 0,
        max = 2
    )
    @CommandPermissions("worldedit.removebelow")
    public void removeBelow(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
        we.checkMaxRadius(size);
        LocalWorld world = player.getWorld();
        int height = args.argsLength() > 1 ? Math.min((world.getMaxY() + 1), args.getInteger(1) + 2) : (world.getMaxY() + 1);

        int affected = editSession.removeBelow(session.getPlacementPosition(player), size, height);
        player.print(affected + " block(s) have been removed.");
    }

    @Command(
        aliases = { "/removenear", "removenear" },
        usage = " [size]",
        desc = "Remove blocks near you.",
        min = 1,
        max = 2
    )
    @CommandPermissions("worldedit.removenear")
    @Logging(PLACEMENT)
    public void removeNear(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock block = we.getBlock(player, args.getString(0), true);
        int size = Math.max(1, args.getInteger(1, 50));
        we.checkMaxRadius(size);

        int affected = editSession.removeNear(session.getPlacementPosition(player), block.getType(), size);
        player.print(affected + " block(s) have been removed.");
    }

    @Command(
        aliases = { "/replacenear", "replacenear" },
        usage = "  ",
        desc = "Replace nearby blocks",
        flags = "f",
        min = 3,
        max = 3
    )
    @CommandPermissions("worldedit.replacenear")
    @Logging(PLACEMENT)
    public void replaceNear(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        int size = Math.max(1, args.getInteger(0));
        int affected;
        Set from;
        Pattern to;
        if (args.argsLength() == 2) {
            from = null;
            to = we.getBlockPattern(player, args.getString(1));
        } else {
            from = we.getBlocks(player, args.getString(1), true, !args.hasFlag('f'));
            to = we.getBlockPattern(player, args.getString(2));
        }

        Vector base = session.getPlacementPosition(player);
        Vector min = base.subtract(size, size, size);
        Vector max = base.add(size, size, size);
        Region region = new CuboidRegion(player.getWorld(), min, max);

        if (to instanceof SingleBlockPattern) {
            affected = editSession.replaceBlocks(region, from, ((SingleBlockPattern) to).getBlock());
        } else {
            affected = editSession.replaceBlocks(region, from, to);
        }
        player.print(affected + " block(s) have been replaced.");
    }

    @Command(
        aliases = { "/snow", "snow" },
        usage = "[radius]",
        desc = "Simulates snow",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.snow")
    @Logging(PLACEMENT)
    public void snow(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;

        int affected = editSession.simulateSnow(session.getPlacementPosition(player), size);
        player.print(affected + " surfaces covered. Let it snow~");
    }

    @Command(
        aliases = {"/thaw", "thaw"},
        usage = "[radius]",
        desc = "Thaws the area",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.thaw")
    @Logging(PLACEMENT)
    public void thaw(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;

        int affected = editSession.thaw(session.getPlacementPosition(player), size);
        player.print(affected + " surfaces thawed.");
    }

    @Command(
        aliases = { "/green", "green" },
        usage = "[radius]",
        desc = "Greens the area",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.green")
    @Logging(PLACEMENT)
    public void green(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;

        int affected = editSession.green(session.getPlacementPosition(player), size);
        player.print(affected + " surfaces greened.");
    }

    @Command(
            aliases = { "/ex", "/ext", "/extinguish", "ex", "ext", "extinguish" },
            usage = "[radius]",
            desc = "Extinguish nearby fire",
            min = 0,
            max = 1
        )
    @CommandPermissions("worldedit.extinguish")
    @Logging(PLACEMENT)
    public void extinguish(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();

        int defaultRadius = config.maxRadius != -1 ? Math.min(40, config.maxRadius) : 40;
        int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0))
                : defaultRadius;
        we.checkMaxRadius(size);

        int affected = editSession.removeNear(session.getPlacementPosition(player), 51, size);
        player.print(affected + " block(s) have been removed.");
    }

    @Command(
        aliases = { "butcher" },
        usage = "[radius]",
        flags = "plangbf",
        desc = "Kill all or nearby mobs",
        help =
            "Kills nearby mobs, based on radius, if none is given uses default in configuration.\n" +
            "Flags:" +
            "  -p also kills pets.\n" +
            "  -n also kills NPCs.\n" +
            "  -g also kills Golems.\n" +
            "  -a also kills animals.\n" +
            "  -b also kills ambient mobs.\n" +
            "  -f compounds all previous flags.\n" +
            "  -l strikes lightning on each killed mob.",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.butcher")
    @Logging(PLACEMENT)
    @Console
    public void butcher(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();

        // technically the default can be larger than the max, but that's not my problem
        int radius = config.butcherDefaultRadius;

        // there might be a better way to do this but my brain is fried right now
        if (args.argsLength() > 0) { // user inputted radius, override the default
            radius = args.getInteger(0);
            if (config.butcherMaxRadius != -1) { // clamp if there is a max
                if (radius == -1) {
                    radius = config.butcherMaxRadius;
                } else { // Math.min does not work if radius is -1 (actually highest possible value)
                    radius = Math.min(radius, config.butcherMaxRadius);
                }
            }
        }

        FlagContainer flags = new FlagContainer(player);
        flags.or(KillFlags.FRIENDLY      , args.hasFlag('f'));
        flags.or(KillFlags.PETS          , args.hasFlag('p'), "worldedit.butcher.pets");
        flags.or(KillFlags.NPCS          , args.hasFlag('n'), "worldedit.butcher.npcs");
        flags.or(KillFlags.GOLEMS        , args.hasFlag('g'), "worldedit.butcher.golems");
        flags.or(KillFlags.ANIMALS       , args.hasFlag('a'), "worldedit.butcher.animals");
        flags.or(KillFlags.AMBIENT       , args.hasFlag('b'), "worldedit.butcher.ambient");
        flags.or(KillFlags.WITH_LIGHTNING, args.hasFlag('l'), "worldedit.butcher.lightning");
        // If you add flags here, please add them to com.sk89q.worldedit.tools.brushes.ButcherBrush as well

        int killed;
        if (player.isPlayer()) {
            killed = player.getWorld().killMobs(session.getPlacementPosition(player), radius, flags.flags);
        } else {
            killed = 0;
            for (LocalWorld world : we.getServer().getWorlds()) {
                killed += world.killMobs(new Vector(), radius, flags.flags);
            }
        }

        if (radius < 0) {
            player.print("Killed " + killed + " mobs.");
        } else {
            player.print("Killed " + killed + " mobs in a radius of " + radius + ".");
        }
    }

    public static class FlagContainer {
        private final LocalPlayer player;
        public int flags = 0;
        public FlagContainer(LocalPlayer player) {
            this.player = player;
        }

        public void or(int flag, boolean on) {
            if (on) flags |= flag;
        }

        public void or(int flag, boolean on, String permission) {
            or(flag, on);

            if ((flags & flag) != 0 && !player.hasPermission(permission)) {
                flags &= ~flag;
            }
        }
    }

    @Command(
        aliases = { "remove", "rem", "rement" },
        usage = " ",
        desc = "Remove all entities of a type",
        min = 2,
        max = 2
    )
    @CommandPermissions("worldedit.remove")
    @Logging(PLACEMENT)
    @Console
    public void remove(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        String typeStr = args.getString(0);
        int radius = args.getInteger(1);

        if (radius < -1) {
            player.printError("Use -1 to remove all entities in loaded chunks");
            return;
        }

        EntityType type = null;

        if (typeStr.matches("all")) {
            type = EntityType.ALL;
        } else if (typeStr.matches("projectiles?|arrows?")) {
            type = EntityType.PROJECTILES;
        } else if (typeStr.matches("items?")
                || typeStr.matches("drops?")) {
            type = EntityType.ITEMS;
        } else if (typeStr.matches("falling(blocks?|sand|gravel)")) {
            type = EntityType.FALLING_BLOCKS;
        } else if (typeStr.matches("paintings?")
                || typeStr.matches("art")) {
            type = EntityType.PAINTINGS;
        } else if (typeStr.matches("(item)frames?")) {
            type = EntityType.ITEM_FRAMES;
        } else if (typeStr.matches("boats?")) {
            type = EntityType.BOATS;
        } else if (typeStr.matches("minecarts?")
                || typeStr.matches("carts?")) {
            type = EntityType.MINECARTS;
        } else if (typeStr.matches("tnt")) {
            type = EntityType.TNT;
        } else if (typeStr.matches("xp")) {
            type = EntityType.XP_ORBS;
        } else {
            player.printError("Acceptable types: projectiles, items, paintings, itemframes, boats, minecarts, tnt, xp, or all");
            return;
        }

        int removed = 0;
        if (player.isPlayer()) {
            Vector origin = session.getPlacementPosition(player);
            removed = player.getWorld().removeEntities(type, origin, radius);
        } else {
            for (LocalWorld world : we.getServer().getWorlds()) {
                removed += world.removeEntities(type, new Vector(), radius);
            }
        }
        player.print("Marked " + removed + " entit(ies) for removal.");
    }

    @Command(
        aliases = { "/help" },
        usage = "[]",
        desc = "Displays help for the given command or lists all commands.",
        min = 0,
        max = -1
    )
    @Console
    @CommandPermissions("worldedit.help")
    public void help(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        help(args, we, session, player, editSession);
    }

    public static void help(CommandContext args, WorldEdit we, LocalSession session, LocalPlayer player, EditSession editSession) {
        Dispatcher dispatcher = we.getDispatcher();

        if (args.argsLength() == 0) {
            SortedSet commands = new TreeSet(new Comparator() {
                @Override
                public int compare(String o1, String o2) {
                    final int ret = o1.replaceAll("/", "").compareToIgnoreCase(o2.replaceAll("/", ""));
                    if (ret == 0) {
                        return o1.compareToIgnoreCase(o2);
                    }
                    return ret;
                }
            });
            commands.addAll(dispatcher.getPrimaryAliases());

            StringBuilder sb = new StringBuilder();
            boolean first = true;
            for (String command : commands) {
                if (!first) {
                    sb.append(", ");
                }

                sb.append('/');
                sb.append(command);
                first = false;
            }

            player.print(sb.toString());

            return;
        }

        String command = args.getJoinedStrings(0);
        
        List mappings = new ArrayList();
        
        String testCommand = command.replaceAll("/", "");
        for (int i = 0; i < 3; i++) {
            CommandMapping mapping = dispatcher.get(testCommand);
            if (mapping != null) {
                mappings.add(mapping);
            }
            testCommand = "/" + testCommand;
        }
        
        if (mappings.size() == 0) {
            player.printError("Unknown command '" + command + "'.");
            return;
        }

        StringBuilder builder = new StringBuilder("\n");
        int index = 0;
        for (CommandMapping mapping : mappings) {
            if (index != 0) {
                builder.append("\n");
            }
            
            if (mappings.size() > 1) {
                builder.append("#").append(index + 1).append(". \n");
            }
            
            Description desc = mapping.getDescription();
            
            builder.append("Aliases: ");
            boolean first = true;
            for (String alias : mapping.getAllAliases()) {
                if (!first) {
                    builder.append(", ");
                }
                builder.append("/").append(alias);
                first = false;
            }
            builder.append("\n");
            
            builder.append("Usage: ").append(desc.getUsage()).append("\n");
            
            if (desc.getHelp() != null) {
                builder.append("Help: ").append(desc.getHelp()).append("\n");
            } else if (desc.getDescription() != null) {
                builder.append("Description: ").append(desc.getDescription()).append("\n");
            }
            index++;
        }
        
        player.print(builder.toString());
    }
}
>>>>>>> 142f5c8e5c889ee5098c05ba2fde20b52467c1df:src/main/java/com/sk89q/worldedit/commands/UtilityCommands.java
Solution content
        } else {
/*
 * WorldEdit, a Minecraft world manipulation toolkit
 * Copyright (C) sk89q 
 * 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 .
 */

package com.sk89q.worldedit.command;

import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.LocalWorld.KillFlags;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.patterns.SingleBlockPattern;
import com.sk89q.worldedit.regions.CuboidRegion;
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.world.World;

import java.util.Comparator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import static com.sk89q.minecraft.util.commands.Logging.LogMode.PLACEMENT;

/**
 * Utility commands.
 * 
 * @author sk89q
 */
public class UtilityCommands {
    private final WorldEdit we;

    public UtilityCommands(WorldEdit we) {
        this.we = we;
    }

    @Command(
        aliases = { "/fill" },
        usage = "  [depth]",
        desc = "Fill a hole",
        min = 2,
        max = 3
    )
    @CommandPermissions("worldedit.fill")
    @Logging(PLACEMENT)
    public void fill(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        double radius = Math.max(1, args.getDouble(1));
        we.checkMaxRadius(radius);
        int depth = args.argsLength() > 2 ? Math.max(1, args.getInteger(2)) : 1;

        Vector pos = session.getPlacementPosition(player);
        int affected = 0;
        if (pattern instanceof SingleBlockPattern) {
            affected = editSession.fillXZ(pos,
                    ((SingleBlockPattern) pattern).getBlock(),
                    radius, depth, false);
        } else {
            affected = editSession.fillXZ(pos, pattern, radius, depth, false);
        }
        player.print(affected + " block(s) have been created.");
    }

    @Command(
        aliases = { "/fillr" },
        usage = "  [depth]",
        desc = "Fill a hole recursively",
        min = 2,
        max = 3
    )
    @CommandPermissions("worldedit.fill.recursive")
    @Logging(PLACEMENT)
    public void fillr(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        Pattern pattern = we.getBlockPattern(player, args.getString(0));
        double radius = Math.max(1, args.getDouble(1));
        we.checkMaxRadius(radius);
        int depth = args.argsLength() > 2 ? Math.max(1, args.getInteger(2)) : Integer.MAX_VALUE;

        Vector pos = session.getPlacementPosition(player);
        int affected = 0;
        if (pattern instanceof SingleBlockPattern) {
            affected = editSession.fillXZ(pos,
                    ((SingleBlockPattern) pattern).getBlock(),
                    radius, depth, true);
        } else {
            affected = editSession.fillXZ(pos, pattern, radius, depth, true);
        }
        player.print(affected + " block(s) have been created.");
    }

    @Command(
        aliases = { "/drain" },
        usage = "",
        desc = "Drain a pool",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.drain")
    @Logging(PLACEMENT)
    public void drain(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double radius = Math.max(0, args.getDouble(0));
        we.checkMaxRadius(radius);
        int affected = editSession.drainArea(
                session.getPlacementPosition(player), radius);
        player.print(affected + " block(s) have been changed.");
    }

    @Command(
        aliases = { "/fixlava", "fixlava" },
        usage = "",
        desc = "Fix lava to be stationary",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.fixlava")
    @Logging(PLACEMENT)
    public void fixLava(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double radius = Math.max(0, args.getDouble(0));
        we.checkMaxRadius(radius);
        int affected = editSession.fixLiquid(
                session.getPlacementPosition(player), radius, 10, 11);
        player.print(affected + " block(s) have been changed.");
    }

    @Command(
        aliases = { "/fixwater", "fixwater" },
        usage = "",
        desc = "Fix water to be stationary",
        min = 1,
        max = 1
    )
    @CommandPermissions("worldedit.fixwater")
    @Logging(PLACEMENT)
    public void fixWater(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double radius = Math.max(0, args.getDouble(0));
        we.checkMaxRadius(radius);
        int affected = editSession.fixLiquid(
                session.getPlacementPosition(player), radius, 8, 9);
        player.print(affected + " block(s) have been changed.");
    }

    @Command(
        aliases = { "/removeabove", "removeabove" },
        usage = "[size] [height]",
        desc = "Remove blocks above your head.",
        min = 0,
        max = 2
    )
    @CommandPermissions("worldedit.removeabove")
    @Logging(PLACEMENT)
    public void removeAbove(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
        we.checkMaxRadius(size);
        World world = player.getWorld();
        int height = args.argsLength() > 1 ? Math.min((world.getMaxY() + 1), args.getInteger(1) + 2) : (world.getMaxY() + 1);

        int affected = editSession.removeAbove(
                session.getPlacementPosition(player), size, height);
        player.print(affected + " block(s) have been removed.");
    }

    @Command(
        aliases = { "/removebelow", "removebelow" },
        usage = "[size] [height]",
        desc = "Remove blocks below you.",
        min = 0,
        max = 2
    )
    @CommandPermissions("worldedit.removebelow")
    @Logging(PLACEMENT)
    public void removeBelow(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
        we.checkMaxRadius(size);
        World world = player.getWorld();
        int height = args.argsLength() > 1 ? Math.min((world.getMaxY() + 1), args.getInteger(1) + 2) : (world.getMaxY() + 1);

        int affected = editSession.removeBelow(session.getPlacementPosition(player), size, height);
        player.print(affected + " block(s) have been removed.");
    }

    @Command(
        aliases = { "/removenear", "removenear" },
        usage = " [size]",
        desc = "Remove blocks near you.",
        min = 1,
        max = 2
    )
    @CommandPermissions("worldedit.removenear")
    @Logging(PLACEMENT)
    public void removeNear(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        BaseBlock block = we.getBlock(player, args.getString(0), true);
        int size = Math.max(1, args.getInteger(1, 50));
        we.checkMaxRadius(size);

        int affected = editSession.removeNear(session.getPlacementPosition(player), block.getType(), size);
        player.print(affected + " block(s) have been removed.");
    }

    @Command(
        aliases = { "/replacenear", "replacenear" },
        usage = "  ",
        desc = "Replace nearby blocks",
        flags = "f",
        min = 3,
        max = 3
    )
    @CommandPermissions("worldedit.replacenear")
    @Logging(PLACEMENT)
    public void replaceNear(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {
        
        int size = Math.max(1, args.getInteger(0));
        int affected;
        Set from;
        Pattern to;
        if (args.argsLength() == 2) {
            from = null;
            to = we.getBlockPattern(player, args.getString(1));
            from = we.getBlocks(player, args.getString(1), true, !args.hasFlag('f'));
            to = we.getBlockPattern(player, args.getString(2));
        }

        Vector base = session.getPlacementPosition(player);
        Vector min = base.subtract(size, size, size);
        Vector max = base.add(size, size, size);
        Region region = new CuboidRegion(player.getWorld(), min, max);

        if (to instanceof SingleBlockPattern) {
            affected = editSession.replaceBlocks(region, from, ((SingleBlockPattern) to).getBlock());
        } else {
            affected = editSession.replaceBlocks(region, from, to);
        }
        player.print(affected + " block(s) have been replaced.");
    }

    @Command(
        aliases = { "/snow", "snow" },
        usage = "[radius]",
        desc = "Simulates snow",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.snow")
    @Logging(PLACEMENT)
    public void snow(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;

        int affected = editSession.simulateSnow(session.getPlacementPosition(player), size);
        player.print(affected + " surfaces covered. Let it snow~");
    }

    @Command(
        aliases = {"/thaw", "thaw"},
        usage = "[radius]",
        desc = "Thaws the area",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.thaw")
    @Logging(PLACEMENT)
    public void thaw(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;

        int affected = editSession.thaw(session.getPlacementPosition(player), size);
        player.print(affected + " surfaces thawed.");
    }

    @Command(
        aliases = { "/green", "green" },
        usage = "[radius]",
        desc = "Greens the area",
        flags = "f",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.green")
    @Logging(PLACEMENT)
    public void green(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        final double size = args.argsLength() > 0 ? Math.max(1, args.getDouble(0)) : 10;
        final boolean onlyNormalDirt = !args.hasFlag('f');

        final int affected = editSession.green(session.getPlacementPosition(player), size, onlyNormalDirt);
        player.print(affected + " surfaces greened.");
    }

    @Command(
            aliases = { "/ex", "/ext", "/extinguish", "ex", "ext", "extinguish" },
            usage = "[radius]",
            desc = "Extinguish nearby fire",
            min = 0,
            max = 1
        )
    @CommandPermissions("worldedit.extinguish")
    @Logging(PLACEMENT)
    public void extinguish(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();

        int defaultRadius = config.maxRadius != -1 ? Math.min(40, config.maxRadius) : 40;
        int size = args.argsLength() > 0 ? Math.max(1, args.getInteger(0))
                : defaultRadius;
        we.checkMaxRadius(size);

        int affected = editSession.removeNear(session.getPlacementPosition(player), 51, size);
        player.print(affected + " block(s) have been removed.");
    }


    @Command(
        aliases = { "butcher" },
        usage = "[radius]",
        flags = "plangbtf",
        desc = "Kill all or nearby mobs",
        help =
            "Kills nearby mobs, based on radius, if none is given uses default in configuration.\n" +
            "Flags:" +
            "  -p also kills pets.\n" +
            "  -n also kills NPCs.\n" +
            "  -g also kills Golems.\n" +
            "  -a also kills animals.\n" +
            "  -b also kills ambient mobs.\n" +
            "  -t also kills mobs with name tags.\n" +
            "  -f compounds all previous flags.\n" +
            "  -l strikes lightning on each killed mob.",
        min = 0,
        max = 1
    )
    @CommandPermissions("worldedit.butcher")
    @Logging(PLACEMENT)
    @Console
    public void butcher(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        LocalConfiguration config = we.getConfiguration();

        // technically the default can be larger than the max, but that's not my problem
        int radius = config.butcherDefaultRadius;

        // there might be a better way to do this but my brain is fried right now
        if (args.argsLength() > 0) { // user inputted radius, override the default
            radius = args.getInteger(0);
            if (config.butcherMaxRadius != -1) { // clamp if there is a max
                if (radius == -1) {
                    radius = config.butcherMaxRadius;
                } else { // Math.min does not work if radius is -1 (actually highest possible value)
                    radius = Math.min(radius, config.butcherMaxRadius);
                }
            }
        }

        FlagContainer flags = new FlagContainer(player);
        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.NPCS          , args.hasFlag('n'), "worldedit.butcher.npcs");
        flags.or(KillFlags.GOLEMS        , args.hasFlag('g'), "worldedit.butcher.golems");
        flags.or(KillFlags.ANIMALS       , args.hasFlag('a'), "worldedit.butcher.animals");
        flags.or(KillFlags.AMBIENT       , args.hasFlag('b'), "worldedit.butcher.ambient");
        flags.or(KillFlags.TAGGED        , args.hasFlag('t'), "worldedit.butcher.tagged");
        flags.or(KillFlags.WITH_LIGHTNING, args.hasFlag('l'), "worldedit.butcher.lightning");
        // If you add flags here, please add them to com.sk89q.worldedit.commands.BrushCommands.butcherBrush() as well

        int killed;
        if (player.isPlayer()) {
            killed = player.getWorld().killMobs(session.getPlacementPosition(player), radius, flags.flags);
        } else {
            killed = 0;
            for (World world : we.getServer().getWorlds()) {
                killed += world.killMobs(new Vector(), radius, flags.flags);
            }
        }

        if (radius < 0) {
            player.print("Killed " + killed + " mobs.");
        } else {
            player.print("Killed " + killed + " mobs in a radius of " + radius + ".");
        }
    }

    public static class FlagContainer {
        private final LocalPlayer player;
        public int flags = 0;
        public FlagContainer(LocalPlayer player) {
            this.player = player;
        }

        public void or(int flag, boolean on) {
            if (on) flags |= flag;
        }

        public void or(int flag, boolean on, String permission) {
            or(flag, on);

            if ((flags & flag) != 0 && !player.hasPermission(permission)) {
                flags &= ~flag;
            }
        }
    }
    @Command(
        aliases = { "remove", "rem", "rement" },
        usage = " ",
        desc = "Remove all entities of a type",
        min = 2,
        max = 2
    )
    @CommandPermissions("worldedit.remove")
    @Logging(PLACEMENT)
    @Console
    public void remove(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        String typeStr = args.getString(0);
        int radius = args.getInteger(1);

        if (radius < -1) {
            player.printError("Use -1 to remove all entities in loaded chunks");
            return;
        }

        EntityType type = null;

        if (typeStr.matches("all")) {
            type = EntityType.ALL;
        } else if (typeStr.matches("projectiles?|arrows?")) {
            type = EntityType.PROJECTILES;
        } else if (typeStr.matches("items?")
                || typeStr.matches("drops?")) {
            type = EntityType.ITEMS;
        } else if (typeStr.matches("falling(blocks?|sand|gravel)")) {
            type = EntityType.FALLING_BLOCKS;
        } else if (typeStr.matches("paintings?")
                || typeStr.matches("art")) {
            type = EntityType.PAINTINGS;
        } else if (typeStr.matches("(item)frames?")) {
            type = EntityType.ITEM_FRAMES;
        } else if (typeStr.matches("boats?")) {
            type = EntityType.BOATS;
        } else if (typeStr.matches("minecarts?")
                || typeStr.matches("carts?")) {
            type = EntityType.MINECARTS;
        } else if (typeStr.matches("tnt")) {
            type = EntityType.TNT;
        } else if (typeStr.matches("xp")) {
            type = EntityType.XP_ORBS;
        } else {
            player.printError("Acceptable types: projectiles, items, paintings, itemframes, boats, minecarts, tnt, xp, or all");
            return;
        }

        int removed = 0;
        if (player.isPlayer()) {
            Vector origin = session.getPlacementPosition(player);
            removed = player.getWorld().removeEntities(type, origin, radius);
        } else {
            for (World world : we.getServer().getWorlds()) {
                removed += world.removeEntities(type, new Vector(), radius);
            }
        }
        player.print("Marked " + removed + " entit(ies) for removal.");
    }

    @Command(
        aliases = { "/help" },
        usage = "[]",
        desc = "Displays help for the given command or lists all commands.",
        min = 0,
        max = -1
    )
    @Console
    @CommandPermissions("worldedit.help")
    public void help(CommandContext args, LocalSession session, LocalPlayer player,
            EditSession editSession) throws WorldEditException {

        help(args, we, session, player, editSession);
    }

    public static void help(CommandContext args, WorldEdit we, LocalSession session, LocalPlayer player, EditSession editSession) {
        final Dispatcher dispatcher = we.getPlatformManager().getCommandManager().getDispatcher();

        if (args.argsLength() == 0) {
            SortedSet commands = new TreeSet(new Comparator() {
                @Override
                public int compare(String o1, String o2) {
                    final int ret = o1.replaceAll("/", "").compareToIgnoreCase(o2.replaceAll("/", ""));
                    if (ret == 0) {
                        return o1.compareToIgnoreCase(o2);
                    }
                    return ret;
                }
            });
            commands.addAll(dispatcher.getPrimaryAliases());

            StringBuilder sb = new StringBuilder();
            boolean first = true;
            for (String command : commands) {
                if (!first) {
                    sb.append(", ");
                }

                sb.append('/');
                sb.append(command);
                first = false;
            }

            player.print(sb.toString());

            return;
        }

        String command = args.getJoinedStrings(0).toLowerCase().replaceAll("^/", "");
        CommandMapping mapping = dispatcher.get(command);

        if (mapping == null) {
            player.printError("Unknown command '" + command + "'.");
            return;
        }

        Description description = mapping.getDescription();

        if (description.getUsage() != null) {
            player.printDebug("Usage: " + description.getUsage());
        }

        if (description.getHelp() != null) {
            player.print(description.getHelp());
        } else if (description.getDescription() != null) {
            player.print(description.getDescription());
        } else {
            player.print("No further help is available.");
        }
    }
}
File
UtilityCommands.java
Developer's decision
Manual
Kind of conflict
Class declaration
Comment
Import
Package declaration