Split up source files into several source directories.

This commit is contained in:
sk89q 2014-04-02 20:03:52 -07:00
parent 469cb8c8b3
commit 6c460f02c5
85 changed files with 5577 additions and 5437 deletions

363
pom.xml
View File

@ -1,17 +1,27 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId> <groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId> <artifactId>worldedit</artifactId>
<version>5.7-SNAPSHOT</version> <version>6.0.0-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<!-- Project information --> <!-- Fix encoding warnings -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!--
=====================================
Project Information
=====================================
-->
<name>WorldEdit</name> <name>WorldEdit</name>
<inceptionYear>2010</inceptionYear> <inceptionYear>2010</inceptionYear>
<url>http://wiki.sk89q.com/wiki/WorldEdit</url> <url>http://wiki.sk89q.com/wiki/WorldEdit</url>
<description>A voxel map editor for Minecraft with tools for adventure map designers, <description>An in-game voxel map editor for Minecraft.</description>
server administrators, and anyone who enjoys building massive structures.</description>
<licenses> <licenses>
<license> <license>
<name>GNU General Public License 2.0</name> <name>GNU General Public License 2.0</name>
@ -26,36 +36,44 @@
<comments>License on all new contributions</comments> <comments>License on all new contributions</comments>
</license> </license>
</licenses> </licenses>
<issueManagement> <issueManagement>
<system>YouTrack</system> <system>YouTrack</system>
<url>http://youtrack.sk89q.com</url> <url>http://youtrack.sk89q.com</url>
</issueManagement> </issueManagement>
<ciManagement> <ciManagement>
<system>Jenkins</system> <system>TeamCity</system>
<url>http://build.sk89q.com</url> <url>http://builds.enginehub.org</url>
</ciManagement> </ciManagement>
<scm> <scm>
<connection>scm:git:git://github.com/sk89q/worldedit.git</connection> <connection>scm:git:git://github.com/sk89q/worldedit.git</connection>
<developerConnection>scm:git:git@github.com:sk89q/worldedit.git</developerConnection> <developerConnection>scm:git:git@github.com:sk89q/worldedit.git</developerConnection>
<url>https://github.com/sk89q/worldedit</url> <url>https://github.com/sk89q/worldedit</url>
<tag>master</tag> <tag>master</tag>
</scm> </scm>
<mailingLists> <mailingLists>
<mailingList> <mailingList>
<name>Developer Discussion</name> <name>Developer Discussion</name>
<archive>https://groups.google.com/d/forum/sk-dev-discuss</archive> <archive>https://groups.google.com/d/forum/sk-dev-discuss</archive>
</mailingList> </mailingList>
</mailingLists> </mailingLists>
<!--
=====================================
Distribution Management
=====================================
-->
<distributionManagement> <distributionManagement>
<site> <site>
<id>sk89q-docs-upload</id> <id>sk89q-docs-upload</id>
<url>ftp://sk89q-maven-deploy/worldedit/</url> <url>ftp://sk89q-maven-deploy/worldedit/</url>
</site> </site>
<!-- The CI server uses these -->
<repository> <repository>
<id>maven.sk89q.com</id> <id>maven.sk89q.com</id>
<url>http://maven.sk89q.com/artifactory/libs-release-local</url> <url>http://maven.sk89q.com/artifactory/libs-release-local</url>
@ -65,99 +83,89 @@
<url>http://maven.sk89q.com/artifactory/libs-snapshot-local</url> <url>http://maven.sk89q.com/artifactory/libs-snapshot-local</url>
</snapshotRepository> </snapshotRepository>
</distributionManagement> </distributionManagement>
<properties> <!-- Fix encoding warnings --> <!--
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> =====================================
</properties> Dependencies
=====================================
-->
<repositories> <repositories>
<repository> <repository>
<id>sk89q-repo</id> <id>maven.sk89q.com</id>
<url>http://maven.sk89q.com/repo/</url> <url>http://maven.sk89q.com/repo/</url>
</repository> </repository>
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public</url>
</repository>
</repositories> </repositories>
<dependencies> <dependencies>
<dependency> <!-- Used for snapshots --> <!-- Used for snapshots -->
<dependency>
<groupId>de.schlichtherle</groupId> <groupId>de.schlichtherle</groupId>
<artifactId>truezip</artifactId> <artifactId>truezip</artifactId>
<version>6.8.3</version> <version>6.8.3</version>
<scope>compile</scope> <scope>compile</scope> <!-- optional runtime dependency -->
<type>jar</type> <type>jar</type>
</dependency> </dependency>
<dependency> <!-- Used for CraftScripts --> <!-- Used for scripting -->
<dependency>
<groupId>rhino</groupId> <groupId>rhino</groupId>
<artifactId>js</artifactId> <artifactId>js</artifactId>
<version>1.7R2</version> <version>1.7R2</version>
<scope>compile</scope> <scope>compile</scope> <!-- optional runtime dependency -->
<type>jar</type> <type>jar</type>
</dependency> </dependency>
<dependency> <!-- Time format detection -->
<groupId>com.sk89q</groupId>
<artifactId>jchronic</artifactId> <!-- not original library -->
<version>0.2.4a</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<!-- Used for Permissions support (this version has both the legacy API
and the new Permissions API to compile against -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>dummypermscompat</artifactId>
<version>1.7</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional> <!-- Don't export -->
</dependency>
<dependency> <!-- Bukkit implementation --> <!-- YAML processing -->
<groupId>org.bukkit</groupId> <dependency>
<artifactId>bukkit</artifactId> <groupId>org.yaml</groupId>
<version>1.7.2-R0.2</version> <artifactId>snakeyaml</artifactId>
<scope>compile</scope> <version>1.9</version>
<type>jar</type> <type>jar</type>
<scope>compile</scope> <!-- optional runtime dependency -->
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<!-- It's Guava -->
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>10.0.1</version> <version>10.0.1</version> <!-- Bukkit only bundles 10.0.1 -->
<scope>compile</scope> <scope>compile</scope> <!-- required runtime dependency -->
<type>jar</type> <type>jar</type>
</dependency> </dependency>
<dependency> <!-- NMS blocks --> <!-- Used for time operations -->
<groupId>org.bukkit</groupId> <dependency>
<artifactId>craftbukkit</artifactId> <groupId>com.sk89q</groupId>
<version>1.7.5-R0.1-SNAPSHOT</version> <artifactId>jchronic</artifactId> <!-- not the original library -->
<scope>compile</scope> <version>0.2.4a</version>
<scope>compile</scope> <!-- shaded -->
<type>jar</type> <type>jar</type>
<optional>true</optional>
</dependency> </dependency>
<dependency> <!-- Unit tests --> <!-- Unit tests -->
<dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId> <artifactId>mockito-core</artifactId>
<version>1.9.0-rc1</version> <version>1.9.0-rc1</version>
<scope>test</scope> <scope>test</scope>
<type>jar</type> <type>jar</type>
</dependency> </dependency>
</dependencies> </dependencies>
<!--
=====================================
Build
=====================================
-->
<build> <build>
<defaultGoal>install</defaultGoal> <defaultGoal>install</defaultGoal>
<sourceDirectory>${basedir}/src/main/java/</sourceDirectory> <sourceDirectory>${basedir}/src/main/java/</sourceDirectory>
<extensions> <!-- Used for uploading the docs --> <!-- Used for uploading the docs -->
<extensions>
<extension> <extension>
<groupId>org.apache.maven.wagon</groupId> <groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ftp</artifactId> <artifactId>wagon-ftp</artifactId>
@ -165,34 +173,29 @@
</extension> </extension>
</extensions> </extensions>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
</includes>
</resource>
<resource>
<targetPath>defaults/</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>config.yml</include>
</includes>
</resource>
<resource> <!-- NMS support in Bukkit -->
<targetPath>nmsblocks/</targetPath>
<filtering>false</filtering>
<directory>${basedir}/src/main/resources/nmsblocks/</directory>
<includes>
<include>*.class</include>
</includes>
</resource>
</resources>
<plugins> <plugins>
<!-- Add source folder -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${basedir}/src/legacy/java/</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<!-- Compiler -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
@ -203,6 +206,7 @@
</configuration> </configuration>
</plugin> </plugin>
<!-- JAR plugin -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
@ -224,6 +228,7 @@
</configuration> </configuration>
</plugin> </plugin>
<!-- Assembly builds .zip, etc. -->
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-2</version> <version>2.2-beta-2</version>
@ -241,6 +246,7 @@
</executions> </executions>
</plugin> </plugin>
<!-- Shades -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
@ -262,6 +268,7 @@
</executions> </executions>
</plugin> </plugin>
<!-- Release plugin -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId> <artifactId>maven-release-plugin</artifactId>
@ -273,6 +280,7 @@
</configuration> </configuration>
</plugin> </plugin>
<!-- Test runner -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
@ -284,12 +292,14 @@
</configuration> </configuration>
</plugin> </plugin>
<!-- Site builder -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId> <artifactId>maven-site-plugin</artifactId>
<version>3.1</version> <version>3.1</version>
<configuration> <configuration>
<reportPlugins> <reportPlugins>
<!-- Project information -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId> <artifactId>maven-project-info-reports-plugin</artifactId>
@ -303,7 +313,8 @@
</reportSet> </reportSet>
</reportSets> </reportSets>
</plugin> </plugin>
<!-- Javadocs -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
@ -314,9 +325,141 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<!--
=====================================
Profiles
=====================================
-->
<profiles> <profiles>
<!-- Build WorldEdit for MC-Forge --> <!--
=====================================
Bukkit
=====================================
-->
<profile>
<id>bukkit</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<repositories>
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public</url>
</repository>
</repositories>
<dependencies>
<!-- Used for Permissions support (this version has both the legacy API
and the new Permissions API to compile against -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>dummypermscompat</artifactId>
<version>1.7</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional>
</dependency>
<!-- Bukkit implementation -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.7.2-R0.2</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional>
</dependency>
<!-- NMS blocks -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.7.5-R0.1-SNAPSHOT</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<resources>
<!-- Bukkit plugin.yml -->
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/bukkit/resources/</directory>
<includes>
<include>plugin.yml</include>
</includes>
</resource>
<!-- Default files -->
<resource>
<targetPath>defaults/</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/bukkit/resources/</directory>
<includes>
<include>config.yml</include>
</includes>
</resource>
<!-- NMS support in Bukkit -->
<resource>
<targetPath>nmsblocks/</targetPath>
<filtering>false</filtering>
<directory>${basedir}/src/bukkit/resources/nmsblocks/</directory>
<includes>
<include>*.class</include>
</includes>
</resource>
</resources>
<plugins>
<!-- Add source folder -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<id>add-bukkit-sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${basedir}/src/bukkit/java/</source>
</sources>
</configuration>
</execution>
<execution>
<id>add-bukkit-test-sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>${basedir}/src/bukkit-test/java/</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!--
=====================================
Forge
=====================================
-->
<profile> <profile>
<id>forge</id> <id>forge</id>
<build> <build>
@ -349,10 +492,14 @@
</build> </build>
</profile> </profile>
<!-- Attach javadocs and source .jars --> <!--
=====================================
Attach docs and source
=====================================
-->
<profile> <profile>
<id>attach-docs</id> <id>attach-docs</id>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@ -368,7 +515,7 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
@ -385,18 +532,22 @@
</plugins> </plugins>
</build> </build>
</profile> </profile>
<!-- Build Spout, disabled by default because it always breaks --> <!--
=====================================
Spout (BROKEN)
=====================================
-->
<profile> <profile>
<id>spout</id> <id>spout</id>
<repositories> <repositories>
<repository> <!-- WARNING: This breaks all the time --> <repository> <!-- WARNING: This breaks all the time -->
<id>spout-repo</id> <id>spout-repo</id>
<url>http://nexus.spout.org/content/groups/public/</url> <url>http://nexus.spout.org/content/groups/public/</url>
</repository> </repository>
</repositories> </repositories>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.spout</groupId> <groupId>org.spout</groupId>
@ -430,7 +581,7 @@
<version>1.5</version> <version>1.5</version>
<executions> <executions>
<execution> <execution>
<id>add-sources</id> <id>add-spout-sources</id>
<phase>generate-sources</phase> <phase>generate-sources</phase>
<goals> <goals>
<goal>add-source</goal> <goal>add-source</goal>

View File

@ -1,170 +1,170 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.wepif; package com.sk89q.wepif;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import com.sk89q.util.yaml.YAMLNode; import com.sk89q.util.yaml.YAMLNode;
import com.sk89q.util.yaml.YAMLProcessor; import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
public class ConfigurationPermissionsResolver implements PermissionsResolver { public class ConfigurationPermissionsResolver implements PermissionsResolver {
private YAMLProcessor config; private YAMLProcessor config;
private Map<String, Set<String>> userPermissionsCache; private Map<String, Set<String>> userPermissionsCache;
private Set<String> defaultPermissionsCache; private Set<String> defaultPermissionsCache;
private Map<String, Set<String>> userGroups; private Map<String, Set<String>> userGroups;
public ConfigurationPermissionsResolver(YAMLProcessor config) { public ConfigurationPermissionsResolver(YAMLProcessor config) {
this.config = config; this.config = config;
} }
public static YAMLNode generateDefaultPerms(YAMLNode section) { public static YAMLNode generateDefaultPerms(YAMLNode section) {
section.setProperty("groups.default.permissions", new String[] { section.setProperty("groups.default.permissions", new String[] {
"worldedit.reload", "worldedit.reload",
"worldedit.selection", "worldedit.selection",
"worlds.creative.worldedit.region"}); "worlds.creative.worldedit.region"});
section.setProperty("groups.admins.permissions", new String[] { "*" }); section.setProperty("groups.admins.permissions", new String[] { "*" });
section.setProperty("users.sk89q.permissions", new String[] { "worldedit" }); section.setProperty("users.sk89q.permissions", new String[] { "worldedit" });
section.setProperty("users.sk89q.groups", new String[] { "admins" }); section.setProperty("users.sk89q.groups", new String[] { "admins" });
return section; return section;
} }
public void load() { public void load() {
userGroups = new HashMap<String, Set<String>>(); userGroups = new HashMap<String, Set<String>>();
userPermissionsCache = new HashMap<String, Set<String>>(); userPermissionsCache = new HashMap<String, Set<String>>();
defaultPermissionsCache = new HashSet<String>(); defaultPermissionsCache = new HashSet<String>();
Map<String, Set<String>> userGroupPermissions = new HashMap<String, Set<String>>(); Map<String, Set<String>> userGroupPermissions = new HashMap<String, Set<String>>();
List<String> groupKeys = config.getStringList("permissions.groups", null); List<String> groupKeys = config.getStringList("permissions.groups", null);
if (groupKeys != null) { if (groupKeys != null) {
for (String key : groupKeys) { for (String key : groupKeys) {
List<String> permissions = List<String> permissions =
config.getStringList("permissions.groups." + key + ".permissions", null); config.getStringList("permissions.groups." + key + ".permissions", null);
if (permissions.size() > 0) { if (permissions.size() > 0) {
Set<String> groupPerms = new HashSet<String>(permissions); Set<String> groupPerms = new HashSet<String>(permissions);
userGroupPermissions.put(key, groupPerms); userGroupPermissions.put(key, groupPerms);
if (key.equals("default")) { if (key.equals("default")) {
defaultPermissionsCache.addAll(permissions); defaultPermissionsCache.addAll(permissions);
} }
} }
} }
} }
List<String> userKeys = config.getStringList("permissions.users", null); List<String> userKeys = config.getStringList("permissions.users", null);
if (userKeys != null) { if (userKeys != null) {
for (String key : userKeys) { for (String key : userKeys) {
Set<String> permsCache = new HashSet<String>(); Set<String> permsCache = new HashSet<String>();
List<String> permissions = List<String> permissions =
config.getStringList("permissions.users." + key + ".permissions", null); config.getStringList("permissions.users." + key + ".permissions", null);
if (permissions.size() > 0) { if (permissions.size() > 0) {
permsCache.addAll(permissions); permsCache.addAll(permissions);
} }
List<String> groups = List<String> groups =
config.getStringList("permissions.users." + key + ".groups", null); config.getStringList("permissions.users." + key + ".groups", null);
groups.add("default"); groups.add("default");
if (groups.size() > 0) { if (groups.size() > 0) {
for (String group : groups) { for (String group : groups) {
Set<String> groupPerms = userGroupPermissions.get(group); Set<String> groupPerms = userGroupPermissions.get(group);
if (groupPerms != null) { if (groupPerms != null) {
permsCache.addAll(groupPerms); permsCache.addAll(groupPerms);
} }
} }
} }
userPermissionsCache.put(key.toLowerCase(), permsCache); userPermissionsCache.put(key.toLowerCase(), permsCache);
userGroups.put(key.toLowerCase(), new HashSet<String>(groups)); userGroups.put(key.toLowerCase(), new HashSet<String>(groups));
} }
} }
} }
public boolean hasPermission(String player, String permission) { public boolean hasPermission(String player, String permission) {
int dotPos = permission.lastIndexOf("."); int dotPos = permission.lastIndexOf(".");
if (dotPos > -1) { if (dotPos > -1) {
if (hasPermission(player, permission.substring(0, dotPos))) { if (hasPermission(player, permission.substring(0, dotPos))) {
return true; return true;
} }
} }
Set<String> perms = userPermissionsCache.get(player.toLowerCase()); Set<String> perms = userPermissionsCache.get(player.toLowerCase());
if (perms == null) { if (perms == null) {
return defaultPermissionsCache.contains(permission) return defaultPermissionsCache.contains(permission)
|| defaultPermissionsCache.contains("*"); || defaultPermissionsCache.contains("*");
} }
return perms.contains("*") || perms.contains(permission); return perms.contains("*") || perms.contains(permission);
} }
public boolean hasPermission(String worldName, String player, String permission) { public boolean hasPermission(String worldName, String player, String permission) {
return hasPermission(player, "worlds." + worldName + "." + permission) return hasPermission(player, "worlds." + worldName + "." + permission)
|| hasPermission(player, permission); || hasPermission(player, permission);
} }
public boolean inGroup(String player, String group) { public boolean inGroup(String player, String group) {
Set<String> groups = userGroups.get(player.toLowerCase()); Set<String> groups = userGroups.get(player.toLowerCase());
if (groups == null) { if (groups == null) {
return false; return false;
} }
return groups.contains(group); return groups.contains(group);
} }
public String[] getGroups(String player) { public String[] getGroups(String player) {
Set<String> groups = userGroups.get(player.toLowerCase()); Set<String> groups = userGroups.get(player.toLowerCase());
if (groups == null) { if (groups == null) {
return new String[0]; return new String[0];
} }
return groups.toArray(new String[groups.size()]); return groups.toArray(new String[groups.size()]);
} }
public boolean hasPermission(OfflinePlayer player, String permission) { public boolean hasPermission(OfflinePlayer player, String permission) {
return hasPermission(player.getName(), permission); return hasPermission(player.getName(), permission);
} }
public boolean hasPermission(String worldName, OfflinePlayer player, String permission) { public boolean hasPermission(String worldName, OfflinePlayer player, String permission) {
return hasPermission(worldName, player.getName(), permission); return hasPermission(worldName, player.getName(), permission);
} }
public boolean inGroup(OfflinePlayer player, String group) { public boolean inGroup(OfflinePlayer player, String group) {
return inGroup(player.getName(), group); return inGroup(player.getName(), group);
} }
public String[] getGroups(OfflinePlayer player) { public String[] getGroups(OfflinePlayer player) {
return getGroups(player.getName()); return getGroups(player.getName());
} }
public String getDetectionMessage() { public String getDetectionMessage() {
return "No known permissions plugin detected. Using configuration file for permissions."; return "No known permissions plugin detected. Using configuration file for permissions.";
} }
} }

View File

@ -1,237 +1,237 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.wepif; package com.sk89q.wepif;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.HashMap; import java.util.HashMap;
import com.sk89q.util.yaml.YAMLProcessor; import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.Server; import org.bukkit.Server;
public class FlatFilePermissionsResolver implements PermissionsResolver { public class FlatFilePermissionsResolver implements PermissionsResolver {
private Map<String, Set<String>> userPermissionsCache; private Map<String, Set<String>> userPermissionsCache;
private Set<String> defaultPermissionsCache; private Set<String> defaultPermissionsCache;
private Map<String, Set<String>> userGroups; private Map<String, Set<String>> userGroups;
protected File groupFile; protected File groupFile;
protected File userFile; protected File userFile;
public static PermissionsResolver factory(Server server, YAMLProcessor config) { public static PermissionsResolver factory(Server server, YAMLProcessor config) {
File groups = new File("perms_groups.txt"); File groups = new File("perms_groups.txt");
File users = new File("perms_users.txt"); File users = new File("perms_users.txt");
if (!groups.exists() || !users.exists()) { if (!groups.exists() || !users.exists()) {
return null; return null;
} }
return new FlatFilePermissionsResolver(groups, users); return new FlatFilePermissionsResolver(groups, users);
} }
public FlatFilePermissionsResolver() { public FlatFilePermissionsResolver() {
this(new File("perms_groups.txt"), new File("perms_users.txt")); this(new File("perms_groups.txt"), new File("perms_users.txt"));
} }
public FlatFilePermissionsResolver(File groupFile, File userFile) { public FlatFilePermissionsResolver(File groupFile, File userFile) {
this.groupFile = groupFile; this.groupFile = groupFile;
this.userFile = userFile; this.userFile = userFile;
} }
@Deprecated @Deprecated
public static boolean filesExists() { public static boolean filesExists() {
return (new File("perms_groups.txt")).exists() && (new File("perms_users.txt")).exists(); return (new File("perms_groups.txt")).exists() && (new File("perms_users.txt")).exists();
} }
public Map<String, Set<String>> loadGroupPermissions() { public Map<String, Set<String>> loadGroupPermissions() {
Map<String, Set<String>> userGroupPermissions = new HashMap<String, Set<String>>(); Map<String, Set<String>> userGroupPermissions = new HashMap<String, Set<String>>();
BufferedReader buff = null; BufferedReader buff = null;
try { try {
FileReader input = new FileReader(this.groupFile); FileReader input = new FileReader(this.groupFile);
buff = new BufferedReader(input); buff = new BufferedReader(input);
String line; String line;
while ((line = buff.readLine()) != null) { while ((line = buff.readLine()) != null) {
line = line.trim(); line = line.trim();
// Blank line // Blank line
if (line.length() == 0) { if (line.length() == 0) {
continue; continue;
} else if (line.charAt(0) == ';' || line.charAt(0) == '#') { } else if (line.charAt(0) == ';' || line.charAt(0) == '#') {
continue; continue;
} }
String[] parts = line.split(":"); String[] parts = line.split(":");
String key = parts[0]; String key = parts[0];
if (parts.length > 1) { if (parts.length > 1) {
String[] perms = parts[1].split(","); String[] perms = parts[1].split(",");
Set<String> groupPerms = new HashSet<String>(Arrays.asList(perms)); Set<String> groupPerms = new HashSet<String>(Arrays.asList(perms));
userGroupPermissions.put(key, groupPerms); userGroupPermissions.put(key, groupPerms);
} }
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {
if (buff != null) { if (buff != null) {
buff.close(); buff.close();
} }
} catch (IOException e2) { } catch (IOException e2) {
} }
} }
return userGroupPermissions; return userGroupPermissions;
} }
public void load() { public void load() {
userGroups = new HashMap<String, Set<String>>(); userGroups = new HashMap<String, Set<String>>();
userPermissionsCache = new HashMap<String, Set<String>>(); userPermissionsCache = new HashMap<String, Set<String>>();
defaultPermissionsCache = new HashSet<String>(); defaultPermissionsCache = new HashSet<String>();
Map<String, Set<String>> userGroupPermissions = loadGroupPermissions(); Map<String, Set<String>> userGroupPermissions = loadGroupPermissions();
if (userGroupPermissions.containsKey("default")) { if (userGroupPermissions.containsKey("default")) {
defaultPermissionsCache = userGroupPermissions.get("default"); defaultPermissionsCache = userGroupPermissions.get("default");
} }
BufferedReader buff = null; BufferedReader buff = null;
try { try {
FileReader input = new FileReader(this.userFile); FileReader input = new FileReader(this.userFile);
buff = new BufferedReader(input); buff = new BufferedReader(input);
String line; String line;
while ((line = buff.readLine()) != null) { while ((line = buff.readLine()) != null) {
Set<String> permsCache = new HashSet<String>(); Set<String> permsCache = new HashSet<String>();
line = line.trim(); line = line.trim();
// Blank line // Blank line
if (line.length() == 0) { if (line.length() == 0) {
continue; continue;
} else if (line.charAt(0) == ';' || line.charAt(0) == '#') { } else if (line.charAt(0) == ';' || line.charAt(0) == '#') {
continue; continue;
} }
String[] parts = line.split(":"); String[] parts = line.split(":");
String key = parts[0]; String key = parts[0];
if (parts.length > 1) { if (parts.length > 1) {
String[] groups = (parts[1] + ",default").split(","); String[] groups = (parts[1] + ",default").split(",");
String[] perms = parts.length > 2 ? parts[2].split(",") : new String[0]; String[] perms = parts.length > 2 ? parts[2].split(",") : new String[0];
permsCache.addAll(Arrays.asList(perms)); permsCache.addAll(Arrays.asList(perms));
for (String group : groups) { for (String group : groups) {
Set<String> groupPerms = userGroupPermissions.get(group); Set<String> groupPerms = userGroupPermissions.get(group);
if (groupPerms != null) { if (groupPerms != null) {
permsCache.addAll(groupPerms); permsCache.addAll(groupPerms);
} }
} }
userPermissionsCache.put(key.toLowerCase(), permsCache); userPermissionsCache.put(key.toLowerCase(), permsCache);
userGroups.put(key.toLowerCase(), new HashSet<String>(Arrays.asList(groups))); userGroups.put(key.toLowerCase(), new HashSet<String>(Arrays.asList(groups)));
} }
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {
if (buff != null) { if (buff != null) {
buff.close(); buff.close();
} }
} catch (IOException e2) { } catch (IOException e2) {
} }
} }
} }
public boolean hasPermission(String player, String permission) { public boolean hasPermission(String player, String permission) {
int dotPos = permission.lastIndexOf("."); int dotPos = permission.lastIndexOf(".");
if (dotPos > -1) { if (dotPos > -1) {
if (hasPermission(player, permission.substring(0, dotPos))) { if (hasPermission(player, permission.substring(0, dotPos))) {
return true; return true;
} }
} }
Set<String> perms = userPermissionsCache.get(player.toLowerCase()); Set<String> perms = userPermissionsCache.get(player.toLowerCase());
if (perms == null) { if (perms == null) {
return defaultPermissionsCache.contains(permission) return defaultPermissionsCache.contains(permission)
|| defaultPermissionsCache.contains("*"); || defaultPermissionsCache.contains("*");
} }
return perms.contains("*") || perms.contains(permission); return perms.contains("*") || perms.contains(permission);
} }
public boolean hasPermission(String worldName, String player, String permission) { public boolean hasPermission(String worldName, String player, String permission) {
return hasPermission(player, "worlds." + worldName + "." + permission) return hasPermission(player, "worlds." + worldName + "." + permission)
|| hasPermission(player, permission); || hasPermission(player, permission);
} }
public boolean inGroup(String player, String group) { public boolean inGroup(String player, String group) {
Set<String> groups = userGroups.get(player.toLowerCase()); Set<String> groups = userGroups.get(player.toLowerCase());
if (groups == null) { if (groups == null) {
return false; return false;
} }
return groups.contains(group); return groups.contains(group);
} }
public String[] getGroups(String player) { public String[] getGroups(String player) {
Set<String> groups = userGroups.get(player.toLowerCase()); Set<String> groups = userGroups.get(player.toLowerCase());
if (groups == null) { if (groups == null) {
return new String[0]; return new String[0];
} }
return groups.toArray(new String[groups.size()]); return groups.toArray(new String[groups.size()]);
} }
public boolean hasPermission(OfflinePlayer player, String permission) { public boolean hasPermission(OfflinePlayer player, String permission) {
return hasPermission(player.getName(), permission); return hasPermission(player.getName(), permission);
} }
public boolean hasPermission(String worldName, OfflinePlayer player, String permission) { public boolean hasPermission(String worldName, OfflinePlayer player, String permission) {
return hasPermission(worldName, player.getName(), permission); return hasPermission(worldName, player.getName(), permission);
} }
public boolean inGroup(OfflinePlayer player, String group) { public boolean inGroup(OfflinePlayer player, String group) {
return inGroup(player.getName(), group); return inGroup(player.getName(), group);
} }
public String[] getGroups(OfflinePlayer player) { public String[] getGroups(OfflinePlayer player) {
return getGroups(player.getName()); return getGroups(player.getName());
} }
public String getDetectionMessage() { public String getDetectionMessage() {
return "perms_groups.txt and perms_users.txt detected! Using flat file permissions."; return "perms_groups.txt and perms_users.txt detected! Using flat file permissions.";
} }
} }

View File

@ -1,161 +1,161 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.wepif; package com.sk89q.wepif;
import com.sk89q.util.yaml.YAMLProcessor; import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.PluginCommand; import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import com.nijikokun.bukkit.Permissions.Permissions; import com.nijikokun.bukkit.Permissions.Permissions;
public class NijiPermissionsResolver implements PermissionsResolver { public class NijiPermissionsResolver implements PermissionsResolver {
private Server server; private Server server;
private Permissions api; private Permissions api;
public static PermissionsResolver factory(Server server, YAMLProcessor config) { public static PermissionsResolver factory(Server server, YAMLProcessor config) {
PluginManager pluginManager = server.getPluginManager(); PluginManager pluginManager = server.getPluginManager();
try { try {
Class.forName("com.nijikokun.bukkit.Permissions.Permissions"); Class.forName("com.nijikokun.bukkit.Permissions.Permissions");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
return null; return null;
} }
Plugin plugin = pluginManager.getPlugin("Permissions"); Plugin plugin = pluginManager.getPlugin("Permissions");
// Check if plugin is loaded and has Permissions interface // Check if plugin is loaded and has Permissions interface
if (plugin == null || !(plugin instanceof Permissions)) { if (plugin == null || !(plugin instanceof Permissions)) {
return null; return null;
} }
// Check for fake permissions // Check for fake permissions
if (config.getBoolean("ignore-nijiperms-bridges", true) && isFakeNijiPerms(plugin)) { if (config.getBoolean("ignore-nijiperms-bridges", true) && isFakeNijiPerms(plugin)) {
return null; return null;
} }
return new NijiPermissionsResolver(server, (Permissions) plugin); return new NijiPermissionsResolver(server, (Permissions) plugin);
} }
public void load() { public void load() {
} }
public NijiPermissionsResolver(Server server, Permissions plugin) { public NijiPermissionsResolver(Server server, Permissions plugin) {
this.server = server; this.server = server;
this.api = plugin; this.api = plugin;
} }
@SuppressWarnings("static-access") @SuppressWarnings("static-access")
public boolean hasPermission(String name, String permission) { public boolean hasPermission(String name, String permission) {
try { try {
Player player = server.getPlayerExact(name); Player player = server.getPlayerExact(name);
if (player == null) return false; if (player == null) return false;
try { try {
return api.getHandler().has(player, permission); return api.getHandler().has(player, permission);
} catch (Throwable t) { } catch (Throwable t) {
return api.Security.permission(player, permission); return api.Security.permission(player, permission);
} }
} catch (Throwable t) { } catch (Throwable t) {
t.printStackTrace(); t.printStackTrace();
return false; return false;
} }
} }
public boolean hasPermission(String worldName, String name, String permission) { public boolean hasPermission(String worldName, String name, String permission) {
try { try {
try { try {
return api.getHandler().has(worldName, name, permission); return api.getHandler().has(worldName, name, permission);
} catch (Throwable t) { } catch (Throwable t) {
return api.getHandler().has(server.getPlayerExact(name), permission); return api.getHandler().has(server.getPlayerExact(name), permission);
} }
} catch (Throwable t) { } catch (Throwable t) {
t.printStackTrace(); t.printStackTrace();
return false; return false;
} }
} }
@SuppressWarnings("static-access") @SuppressWarnings("static-access")
public boolean inGroup(String name, String group) { public boolean inGroup(String name, String group) {
try { try {
Player player = server.getPlayerExact(name); Player player = server.getPlayerExact(name);
if (player == null) return false; if (player == null) return false;
try { try {
return api.getHandler().inGroup(player.getWorld().getName(), name, group); return api.getHandler().inGroup(player.getWorld().getName(), name, group);
} catch (Throwable t) { } catch (Throwable t) {
return api.Security.inGroup(name, group); return api.Security.inGroup(name, group);
} }
} catch (Throwable t) { } catch (Throwable t) {
t.printStackTrace(); t.printStackTrace();
return false; return false;
} }
} }
@SuppressWarnings("static-access") @SuppressWarnings("static-access")
public String[] getGroups(String name) { public String[] getGroups(String name) {
try { try {
Player player = server.getPlayerExact(name); Player player = server.getPlayerExact(name);
if (player == null) return new String[0]; if (player == null) return new String[0];
String[] groups = null; String[] groups = null;
try { try {
groups = api.getHandler().getGroups(player.getWorld().getName(), player.getName()); groups = api.getHandler().getGroups(player.getWorld().getName(), player.getName());
} catch (Throwable t) { } catch (Throwable t) {
String group = api.Security.getGroup(player.getWorld().getName(), player.getName()); String group = api.Security.getGroup(player.getWorld().getName(), player.getName());
if (group != null) groups = new String[] { group }; if (group != null) groups = new String[] { group };
} }
if (groups == null) { if (groups == null) {
return new String[0]; return new String[0];
} else { } else {
return groups; return groups;
} }
} catch (Throwable t) { } catch (Throwable t) {
t.printStackTrace(); t.printStackTrace();
return new String[0]; return new String[0];
} }
} }
public boolean hasPermission(OfflinePlayer player, String permission) { public boolean hasPermission(OfflinePlayer player, String permission) {
return hasPermission(player.getName(), permission); return hasPermission(player.getName(), permission);
} }
public boolean hasPermission(String worldName, OfflinePlayer player, String permission) { public boolean hasPermission(String worldName, OfflinePlayer player, String permission) {
return hasPermission(worldName, player.getName(), permission); return hasPermission(worldName, player.getName(), permission);
} }
public boolean inGroup(OfflinePlayer player, String group) { public boolean inGroup(OfflinePlayer player, String group) {
return inGroup(player.getName(), group); return inGroup(player.getName(), group);
} }
public String[] getGroups(OfflinePlayer player) { public String[] getGroups(OfflinePlayer player) {
return getGroups(player.getName()); return getGroups(player.getName());
} }
public static boolean isFakeNijiPerms(Plugin plugin) { public static boolean isFakeNijiPerms(Plugin plugin) {
PluginCommand permsCommand = Bukkit.getServer().getPluginCommand("permissions"); PluginCommand permsCommand = Bukkit.getServer().getPluginCommand("permissions");
return permsCommand == null || !(permsCommand.getPlugin().equals(plugin)); return permsCommand == null || !(permsCommand.getPlugin().equals(plugin));
} }
public String getDetectionMessage() { public String getDetectionMessage() {
return "Permissions plugin detected! Using Permissions plugin for permissions."; return "Permissions plugin detected! Using Permissions plugin for permissions.";
} }
} }

View File

@ -1,40 +1,40 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.wepif; package com.sk89q.wepif;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
public interface PermissionsProvider { public interface PermissionsProvider {
public boolean hasPermission(String name, String permission); public boolean hasPermission(String name, String permission);
public boolean hasPermission(String worldName, String name, String permission); public boolean hasPermission(String worldName, String name, String permission);
public boolean inGroup(String player, String group); public boolean inGroup(String player, String group);
public String[] getGroups(String player); public String[] getGroups(String player);
public boolean hasPermission(OfflinePlayer player, String permission); public boolean hasPermission(OfflinePlayer player, String permission);
public boolean hasPermission(String worldName, OfflinePlayer player, String permission); public boolean hasPermission(String worldName, OfflinePlayer player, String permission);
public boolean inGroup(OfflinePlayer player, String group); public boolean inGroup(OfflinePlayer player, String group);
public String[] getGroups(OfflinePlayer player); public String[] getGroups(OfflinePlayer player);
} }

View File

@ -1,26 +1,26 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.wepif; package com.sk89q.wepif;
public interface PermissionsResolver extends PermissionsProvider { public interface PermissionsResolver extends PermissionsProvider {
public void load(); public void load();
public String getDetectionMessage(); public String getDetectionMessage();
} }

View File

@ -1,298 +1,298 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.wepif; package com.sk89q.wepif;
import com.sk89q.util.yaml.YAMLFormat; import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor; import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.logging.Logger; import java.util.logging.Logger;
public class PermissionsResolverManager implements PermissionsResolver { public class PermissionsResolverManager implements PermissionsResolver {
private static final String CONFIG_HEADER = "#\r\n" + private static final String CONFIG_HEADER = "#\r\n" +
"# WEPIF Configuration File\r\n" + "# WEPIF Configuration File\r\n" +
"#\r\n" + "#\r\n" +
"# This file handles permissions configuration for every plugin using WEPIF\r\n" + "# This file handles permissions configuration for every plugin using WEPIF\r\n" +
"#\r\n" + "#\r\n" +
"# About editing this file:\r\n" + "# About editing this file:\r\n" +
"# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If\r\n" + "# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If\r\n" +
"# you use an editor like Notepad++ (recommended for Windows users), you\r\n" + "# you use an editor like Notepad++ (recommended for Windows users), you\r\n" +
"# must configure it to \"replace tabs with spaces.\" In Notepad++, this can\r\n" + "# must configure it to \"replace tabs with spaces.\" In Notepad++, this can\r\n" +
"# be changed in Settings > Preferences > Language Menu.\r\n" + "# be changed in Settings > Preferences > Language Menu.\r\n" +
"# - Don't get rid of the indents. They are indented so some entries are\r\n" + "# - Don't get rid of the indents. They are indented so some entries are\r\n" +
"# in categories (like \"enforce-single-session\" is in the \"protection\"\r\n" + "# in categories (like \"enforce-single-session\" is in the \"protection\"\r\n" +
"# category.\r\n" + "# category.\r\n" +
"# - If you want to check the format of this file before putting it\r\n" + "# - If you want to check the format of this file before putting it\r\n" +
"# into WEPIF, paste it into http://yaml-online-parser.appspot.com/\r\n" + "# into WEPIF, paste it into http://yaml-online-parser.appspot.com/\r\n" +
"# and see if it gives \"ERROR:\".\r\n" + "# and see if it gives \"ERROR:\".\r\n" +
"# - Lines starting with # are comments and so they are ignored.\r\n" + "# - Lines starting with # are comments and so they are ignored.\r\n" +
"#\r\n" + "#\r\n" +
"# About Configuration Permissions\r\n" + "# About Configuration Permissions\r\n" +
"# - See http://wiki.sk89q.com/wiki/WorldEdit/Permissions/Bukkit\r\n" + "# - See http://wiki.sk89q.com/wiki/WorldEdit/Permissions/Bukkit\r\n" +
"# - Now with multiworld support (see example)\r\n" + "# - Now with multiworld support (see example)\r\n" +
"\r\n"; "\r\n";
private static PermissionsResolverManager instance; private static PermissionsResolverManager instance;
public static void initialize(Plugin plugin) { public static void initialize(Plugin plugin) {
if (!isInitialized()) { if (!isInitialized()) {
instance = new PermissionsResolverManager(plugin); instance = new PermissionsResolverManager(plugin);
} }
} }
public static boolean isInitialized() { public static boolean isInitialized() {
return instance != null; return instance != null;
} }
public static PermissionsResolverManager getInstance() { public static PermissionsResolverManager getInstance() {
if (!isInitialized()) { if (!isInitialized()) {
throw new WEPIFRuntimeException("WEPIF has not yet been initialized!"); throw new WEPIFRuntimeException("WEPIF has not yet been initialized!");
} }
return instance; return instance;
} }
private Server server; private Server server;
private PermissionsResolver permissionResolver; private PermissionsResolver permissionResolver;
private YAMLProcessor config; private YAMLProcessor config;
private Logger logger = Logger.getLogger(getClass().getCanonicalName()); private Logger logger = Logger.getLogger(getClass().getCanonicalName());
private List<Class<? extends PermissionsResolver>> enabledResolvers = new ArrayList<Class<? extends PermissionsResolver>>(); private List<Class<? extends PermissionsResolver>> enabledResolvers = new ArrayList<Class<? extends PermissionsResolver>>();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected Class<? extends PermissionsResolver>[] availableResolvers = new Class[] { protected Class<? extends PermissionsResolver>[] availableResolvers = new Class[] {
PluginPermissionsResolver.class, PluginPermissionsResolver.class,
PermissionsExResolver.class, PermissionsExResolver.class,
bPermissionsResolver.class, bPermissionsResolver.class,
GroupManagerResolver.class, GroupManagerResolver.class,
NijiPermissionsResolver.class, NijiPermissionsResolver.class,
DinnerPermsResolver.class, DinnerPermsResolver.class,
FlatFilePermissionsResolver.class FlatFilePermissionsResolver.class
}; };
protected PermissionsResolverManager(Plugin plugin) { protected PermissionsResolverManager(Plugin plugin) {
this.server = plugin.getServer(); this.server = plugin.getServer();
(new ServerListener()).register(plugin); // Register the events (new ServerListener()).register(plugin); // Register the events
loadConfig(new File("wepif.yml")); loadConfig(new File("wepif.yml"));
findResolver(); findResolver();
} }
public void findResolver() { public void findResolver() {
for (Class<? extends PermissionsResolver> resolverClass : enabledResolvers) { for (Class<? extends PermissionsResolver> resolverClass : enabledResolvers) {
try { try {
Method factoryMethod = resolverClass.getMethod("factory", Server.class, YAMLProcessor.class); Method factoryMethod = resolverClass.getMethod("factory", Server.class, YAMLProcessor.class);
this.permissionResolver = (PermissionsResolver) factoryMethod.invoke(null, this.server, this.config); this.permissionResolver = (PermissionsResolver) factoryMethod.invoke(null, this.server, this.config);
if (this.permissionResolver != null) { if (this.permissionResolver != null) {
break; break;
} }
} catch (Throwable e) { } catch (Throwable e) {
logger.warning("Error in factory method for " + resolverClass.getSimpleName() + ": " + e); logger.warning("Error in factory method for " + resolverClass.getSimpleName() + ": " + e);
e.printStackTrace(); e.printStackTrace();
continue; continue;
} }
} }
if (permissionResolver == null) { if (permissionResolver == null) {
permissionResolver = new ConfigurationPermissionsResolver(config); permissionResolver = new ConfigurationPermissionsResolver(config);
} }
permissionResolver.load(); permissionResolver.load();
logger.info("WEPIF: " + permissionResolver.getDetectionMessage()); logger.info("WEPIF: " + permissionResolver.getDetectionMessage());
} }
public void setPluginPermissionsResolver(Plugin plugin) { public void setPluginPermissionsResolver(Plugin plugin) {
if (!(plugin instanceof PermissionsProvider)) { if (!(plugin instanceof PermissionsProvider)) {
return; return;
} }
permissionResolver = new PluginPermissionsResolver((PermissionsProvider) plugin, plugin); permissionResolver = new PluginPermissionsResolver((PermissionsProvider) plugin, plugin);
logger.info("WEPIF: " + permissionResolver.getDetectionMessage()); logger.info("WEPIF: " + permissionResolver.getDetectionMessage());
} }
public void load() { public void load() {
findResolver(); findResolver();
} }
public boolean hasPermission(String name, String permission) { public boolean hasPermission(String name, String permission) {
return permissionResolver.hasPermission(name, permission); return permissionResolver.hasPermission(name, permission);
} }
public boolean hasPermission(String worldName, String name, String permission) { public boolean hasPermission(String worldName, String name, String permission) {
return permissionResolver.hasPermission(worldName, name, permission); return permissionResolver.hasPermission(worldName, name, permission);
} }
public boolean inGroup(String player, String group) { public boolean inGroup(String player, String group) {
return permissionResolver.inGroup(player, group); return permissionResolver.inGroup(player, group);
} }
public String[] getGroups(String player) { public String[] getGroups(String player) {
return permissionResolver.getGroups(player); return permissionResolver.getGroups(player);
} }
public boolean hasPermission(OfflinePlayer player, String permission) { public boolean hasPermission(OfflinePlayer player, String permission) {
return permissionResolver.hasPermission(player, permission); return permissionResolver.hasPermission(player, permission);
} }
public boolean hasPermission(String worldName, OfflinePlayer player, String permission) { public boolean hasPermission(String worldName, OfflinePlayer player, String permission) {
return permissionResolver.hasPermission(worldName, player, permission); return permissionResolver.hasPermission(worldName, player, permission);
} }
public boolean inGroup(OfflinePlayer player, String group) { public boolean inGroup(OfflinePlayer player, String group) {
return permissionResolver.inGroup(player, group); return permissionResolver.inGroup(player, group);
} }
public String[] getGroups(OfflinePlayer player) { public String[] getGroups(OfflinePlayer player) {
return permissionResolver.getGroups(player); return permissionResolver.getGroups(player);
} }
public String getDetectionMessage() { public String getDetectionMessage() {
return "Using WEPIF for permissions"; return "Using WEPIF for permissions";
} }
private boolean loadConfig(File file) { private boolean loadConfig(File file) {
boolean isUpdated = false; boolean isUpdated = false;
if (!file.exists()) { if (!file.exists()) {
try { try {
file.createNewFile(); file.createNewFile();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
config = new YAMLProcessor(file, false, YAMLFormat.EXTENDED); config = new YAMLProcessor(file, false, YAMLFormat.EXTENDED);
try { try {
config.load(); config.load();
} catch (IOException e) { } catch (IOException e) {
logger.severe("Error loading WEPIF Config: " + e); logger.severe("Error loading WEPIF Config: " + e);
e.printStackTrace(); e.printStackTrace();
} }
List<String> keys = config.getKeys(null); List<String> keys = config.getKeys(null);
config.setHeader(CONFIG_HEADER); config.setHeader(CONFIG_HEADER);
if (!keys.contains("ignore-nijiperms-bridges")) { if (!keys.contains("ignore-nijiperms-bridges")) {
config.setProperty("ignore-nijiperms-bridges", true); config.setProperty("ignore-nijiperms-bridges", true);
isUpdated = true; isUpdated = true;
} }
if (!keys.contains("resolvers")) { if (!keys.contains("resolvers")) {
//List<String> resolverKeys = config.getKeys("resolvers"); //List<String> resolverKeys = config.getKeys("resolvers");
List<String> resolvers = new ArrayList<String>(); List<String> resolvers = new ArrayList<String>();
for (Class<?> clazz : availableResolvers) { for (Class<?> clazz : availableResolvers) {
resolvers.add(clazz.getSimpleName()); resolvers.add(clazz.getSimpleName());
} }
enabledResolvers.addAll(Arrays.asList(availableResolvers)); enabledResolvers.addAll(Arrays.asList(availableResolvers));
config.setProperty("resolvers.enabled", resolvers); config.setProperty("resolvers.enabled", resolvers);
isUpdated = true; isUpdated = true;
} else { } else {
List<String> disabledResolvers = config.getStringList("resolvers.disabled", new ArrayList<String>()); List<String> disabledResolvers = config.getStringList("resolvers.disabled", new ArrayList<String>());
List<String> stagedEnabled = config.getStringList("resolvers.enabled", null); List<String> stagedEnabled = config.getStringList("resolvers.enabled", null);
for (Iterator<String> i = stagedEnabled.iterator(); i.hasNext();) { for (Iterator<String> i = stagedEnabled.iterator(); i.hasNext();) {
String nextName = i.next(); String nextName = i.next();
Class<?> next = null; Class<?> next = null;
try { try {
next = Class.forName(getClass().getPackage().getName() + "." + nextName); next = Class.forName(getClass().getPackage().getName() + "." + nextName);
} catch (ClassNotFoundException e) {} } catch (ClassNotFoundException e) {}
if (next == null || !PermissionsResolver.class.isAssignableFrom(next)) { if (next == null || !PermissionsResolver.class.isAssignableFrom(next)) {
logger.warning("WEPIF: Invalid or unknown class found in enabled resolvers: " logger.warning("WEPIF: Invalid or unknown class found in enabled resolvers: "
+ nextName + ". Moving to disabled resolvers list."); + nextName + ". Moving to disabled resolvers list.");
i.remove(); i.remove();
disabledResolvers.add(nextName); disabledResolvers.add(nextName);
isUpdated = true; isUpdated = true;
continue; continue;
} }
enabledResolvers.add(next.asSubclass(PermissionsResolver.class)); enabledResolvers.add(next.asSubclass(PermissionsResolver.class));
} }
for (Class<?> clazz : availableResolvers) { for (Class<?> clazz : availableResolvers) {
if (!stagedEnabled.contains(clazz.getSimpleName()) && if (!stagedEnabled.contains(clazz.getSimpleName()) &&
!disabledResolvers.contains(clazz.getSimpleName())) { !disabledResolvers.contains(clazz.getSimpleName())) {
disabledResolvers.add(clazz.getSimpleName()); disabledResolvers.add(clazz.getSimpleName());
logger.info("New permissions resolver: " logger.info("New permissions resolver: "
+ clazz.getSimpleName() + " detected. " + + clazz.getSimpleName() + " detected. " +
"Added to disabled resolvers list."); "Added to disabled resolvers list.");
isUpdated = true; isUpdated = true;
} }
} }
config.setProperty("resolvers.disabled", disabledResolvers); config.setProperty("resolvers.disabled", disabledResolvers);
config.setProperty("resolvers.enabled", stagedEnabled); config.setProperty("resolvers.enabled", stagedEnabled);
} }
if (keys.contains("dinner-perms") || keys.contains("dinnerperms")) { if (keys.contains("dinner-perms") || keys.contains("dinnerperms")) {
config.removeProperty("dinner-perms"); config.removeProperty("dinner-perms");
config.removeProperty("dinnerperms"); config.removeProperty("dinnerperms");
isUpdated = true; isUpdated = true;
} }
if (!keys.contains("permissions")) { if (!keys.contains("permissions")) {
ConfigurationPermissionsResolver.generateDefaultPerms( ConfigurationPermissionsResolver.generateDefaultPerms(
config.addNode("permissions")); config.addNode("permissions"));
isUpdated = true; isUpdated = true;
} }
if (isUpdated) { if (isUpdated) {
logger.info("WEPIF: Updated config file"); logger.info("WEPIF: Updated config file");
config.save(); config.save();
} }
return isUpdated; return isUpdated;
} }
public static class MissingPluginException extends Exception { public static class MissingPluginException extends Exception {
private static final long serialVersionUID = 7044832912491608706L; private static final long serialVersionUID = 7044832912491608706L;
} }
class ServerListener implements org.bukkit.event.Listener { class ServerListener implements org.bukkit.event.Listener {
@EventHandler @EventHandler
public void onPluginEnable(PluginEnableEvent event) { public void onPluginEnable(PluginEnableEvent event) {
Plugin plugin = event.getPlugin(); Plugin plugin = event.getPlugin();
String name = plugin.getDescription().getName(); String name = plugin.getDescription().getName();
if (plugin instanceof PermissionsProvider) { if (plugin instanceof PermissionsProvider) {
setPluginPermissionsResolver(plugin); setPluginPermissionsResolver(plugin);
} else if ("permissions".equalsIgnoreCase(name) || "permissionsex".equalsIgnoreCase(name) } else if ("permissions".equalsIgnoreCase(name) || "permissionsex".equalsIgnoreCase(name)
|| "bpermissions".equalsIgnoreCase(name) || "groupmanager".equalsIgnoreCase(name)) { || "bpermissions".equalsIgnoreCase(name) || "groupmanager".equalsIgnoreCase(name)) {
load(); load();
} }
} }
@EventHandler @EventHandler
public void onPluginDisable(PluginDisableEvent event) { public void onPluginDisable(PluginDisableEvent event) {
String name = event.getPlugin().getDescription().getName(); String name = event.getPlugin().getDescription().getName();
if (event.getPlugin() instanceof PermissionsProvider if (event.getPlugin() instanceof PermissionsProvider
|| "permissions".equalsIgnoreCase(name) || "permissionsex".equalsIgnoreCase(name) || "permissions".equalsIgnoreCase(name) || "permissionsex".equalsIgnoreCase(name)
|| "bpermissions".equalsIgnoreCase(name) || "groupmanager".equalsIgnoreCase(name)) { || "bpermissions".equalsIgnoreCase(name) || "groupmanager".equalsIgnoreCase(name)) {
load(); load();
} }
} }
void register(Plugin plugin) { void register(Plugin plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin); plugin.getServer().getPluginManager().registerEvents(this, plugin);
} }
} }
} }

View File

@ -1,95 +1,95 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.wepif; package com.sk89q.wepif;
import com.sk89q.util.yaml.YAMLProcessor; import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.RegisteredServiceProvider;
public class PluginPermissionsResolver implements PermissionsResolver { public class PluginPermissionsResolver implements PermissionsResolver {
protected PermissionsProvider resolver; protected PermissionsProvider resolver;
protected Plugin plugin; protected Plugin plugin;
public static PermissionsResolver factory(Server server, YAMLProcessor config) { public static PermissionsResolver factory(Server server, YAMLProcessor config) {
// Looking for service // Looking for service
RegisteredServiceProvider<PermissionsProvider> serviceProvider = server.getServicesManager().getRegistration(PermissionsProvider.class); RegisteredServiceProvider<PermissionsProvider> serviceProvider = server.getServicesManager().getRegistration(PermissionsProvider.class);
if (serviceProvider != null) { if (serviceProvider != null) {
return new PluginPermissionsResolver(serviceProvider.getProvider(), serviceProvider.getPlugin()); return new PluginPermissionsResolver(serviceProvider.getProvider(), serviceProvider.getPlugin());
} }
// Looking for plugin // Looking for plugin
for (Plugin plugin : server.getPluginManager().getPlugins()) { for (Plugin plugin : server.getPluginManager().getPlugins()) {
if (plugin instanceof PermissionsProvider) { if (plugin instanceof PermissionsProvider) {
return new PluginPermissionsResolver((PermissionsProvider) plugin, plugin); return new PluginPermissionsResolver((PermissionsProvider) plugin, plugin);
} }
} }
return null; return null;
} }
public PluginPermissionsResolver(PermissionsProvider resolver, Plugin permissionsPlugin) { public PluginPermissionsResolver(PermissionsProvider resolver, Plugin permissionsPlugin) {
this.resolver = resolver; this.resolver = resolver;
this.plugin = permissionsPlugin; this.plugin = permissionsPlugin;
} }
public void load() { public void load() {
} }
public boolean hasPermission(String name, String permission) { public boolean hasPermission(String name, String permission) {
return resolver.hasPermission(name, permission); return resolver.hasPermission(name, permission);
} }
public boolean hasPermission(String worldName, String name, String permission) { public boolean hasPermission(String worldName, String name, String permission) {
return resolver.hasPermission(worldName, name, permission); return resolver.hasPermission(worldName, name, permission);
} }
public boolean inGroup(String player, String group) { public boolean inGroup(String player, String group) {
return resolver.inGroup(player, group); return resolver.inGroup(player, group);
} }
public String[] getGroups(String player) { public String[] getGroups(String player) {
return resolver.getGroups(player); return resolver.getGroups(player);
} }
public boolean hasPermission(OfflinePlayer player, String permission) { public boolean hasPermission(OfflinePlayer player, String permission) {
return resolver.hasPermission(player, permission); return resolver.hasPermission(player, permission);
} }
public boolean hasPermission(String worldName, OfflinePlayer player, String permission) { public boolean hasPermission(String worldName, OfflinePlayer player, String permission) {
return resolver.hasPermission(worldName, player, permission); return resolver.hasPermission(worldName, player, permission);
} }
public boolean inGroup(OfflinePlayer player, String group) { public boolean inGroup(OfflinePlayer player, String group) {
return resolver.inGroup(player, group); return resolver.inGroup(player, group);
} }
public String[] getGroups(OfflinePlayer player) { public String[] getGroups(OfflinePlayer player) {
return resolver.getGroups(player); return resolver.getGroups(player);
} }
public String getDetectionMessage() { public String getDetectionMessage() {
return "Using plugin '" + this.plugin.getDescription().getName() + "' for permissions."; return "Using plugin '" + this.plugin.getDescription().getName() + "' for permissions.";
} }
} }

View File

@ -1,31 +1,31 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.wepif; package com.sk89q.wepif;
/** /**
* @author zml2008 * @author zml2008
*/ */
public class WEPIFRuntimeException extends RuntimeException { public class WEPIFRuntimeException extends RuntimeException {
private static final long serialVersionUID = 5092745960439109699L; private static final long serialVersionUID = 5092745960439109699L;
public WEPIFRuntimeException(String message) { public WEPIFRuntimeException(String message) {
super(message); super(message);
} }
} }

View File

@ -1,134 +1,134 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.sk89q.worldedit.LocalPlayer; import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalWorld; import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.PlayerNeededException; import com.sk89q.worldedit.PlayerNeededException;
import com.sk89q.worldedit.ServerInterface; import com.sk89q.worldedit.ServerInterface;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldVector; import com.sk89q.worldedit.WorldVector;
import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.BlockBag;
public class BukkitCommandSender extends LocalPlayer { public class BukkitCommandSender extends LocalPlayer {
private CommandSender sender; private CommandSender sender;
private WorldEditPlugin plugin; private WorldEditPlugin plugin;
public BukkitCommandSender(WorldEditPlugin plugin, ServerInterface server, CommandSender sender) { public BukkitCommandSender(WorldEditPlugin plugin, ServerInterface server, CommandSender sender) {
super(server); super(server);
this.plugin = plugin; this.plugin = plugin;
this.sender = sender; this.sender = sender;
} }
@Override @Override
public String getName() { public String getName() {
return sender.getName(); return sender.getName();
} }
@Override @Override
public void printRaw(String msg) { public void printRaw(String msg) {
for (String part : msg.split("\n")) { for (String part : msg.split("\n")) {
sender.sendMessage(part); sender.sendMessage(part);
} }
} }
@Override @Override
public void print(String msg) { public void print(String msg) {
for (String part : msg.split("\n")) { for (String part : msg.split("\n")) {
sender.sendMessage("\u00A7d" + part); sender.sendMessage("\u00A7d" + part);
} }
} }
@Override @Override
public void printDebug(String msg) { public void printDebug(String msg) {
for (String part : msg.split("\n")) { for (String part : msg.split("\n")) {
sender.sendMessage("\u00A77" + part); sender.sendMessage("\u00A77" + part);
} }
} }
@Override @Override
public void printError(String msg) { public void printError(String msg) {
for (String part : msg.split("\n")) { for (String part : msg.split("\n")) {
sender.sendMessage("\u00A7c" + part); sender.sendMessage("\u00A7c" + part);
} }
} }
@Override @Override
public String[] getGroups() { public String[] getGroups() {
return new String[0]; return new String[0];
} }
@Override @Override
public boolean hasPermission(String perm) { public boolean hasPermission(String perm) {
if (!plugin.getLocalConfiguration().noOpPermissions && sender.isOp()) { if (!plugin.getLocalConfiguration().noOpPermissions && sender.isOp()) {
return true; return true;
} }
return plugin.getPermissionsResolver().hasPermission(null, sender.getName(), perm); return plugin.getPermissionsResolver().hasPermission(null, sender.getName(), perm);
} }
@Override @Override
public boolean isPlayer() { public boolean isPlayer() {
return sender instanceof Player; return sender instanceof Player;
} }
@Override @Override
public int getItemInHand() { public int getItemInHand() {
throw new PlayerNeededException(); throw new PlayerNeededException();
} }
@Override @Override
public WorldVector getPosition() { public WorldVector getPosition() {
throw new PlayerNeededException(); throw new PlayerNeededException();
} }
@Override @Override
public LocalWorld getWorld() { public LocalWorld getWorld() {
throw new PlayerNeededException(); throw new PlayerNeededException();
} }
@Override @Override
public double getPitch() { public double getPitch() {
throw new PlayerNeededException(); throw new PlayerNeededException();
} }
@Override @Override
public double getYaw() { public double getYaw() {
throw new PlayerNeededException(); throw new PlayerNeededException();
} }
@Override @Override
public void giveItem(int type, int amt) { public void giveItem(int type, int amt) {
throw new PlayerNeededException(); throw new PlayerNeededException();
} }
@Override @Override
public void setPosition(Vector pos, float pitch, float yaw) { public void setPosition(Vector pos, float pitch, float yaw) {
throw new PlayerNeededException(); throw new PlayerNeededException();
} }
@Override @Override
public BlockBag getInventoryBlockBag() { public BlockBag getInventoryBlockBag() {
throw new PlayerNeededException(); throw new PlayerNeededException();
} }
} }

View File

@ -1,171 +1,171 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import com.sk89q.util.StringUtil; import com.sk89q.util.StringUtil;
import com.sk89q.worldedit.LocalPlayer; import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalWorld; import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.ServerInterface; import com.sk89q.worldedit.ServerInterface;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldVector; import com.sk89q.worldedit.WorldVector;
import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.internal.cui.CUIEvent; import com.sk89q.worldedit.internal.cui.CUIEvent;
public class BukkitPlayer extends LocalPlayer { public class BukkitPlayer extends LocalPlayer {
private Player player; private Player player;
private WorldEditPlugin plugin; private WorldEditPlugin plugin;
public BukkitPlayer(WorldEditPlugin plugin, ServerInterface server, Player player) { public BukkitPlayer(WorldEditPlugin plugin, ServerInterface server, Player player) {
super(server); super(server);
this.plugin = plugin; this.plugin = plugin;
this.player = player; this.player = player;
} }
@Override @Override
public int getItemInHand() { public int getItemInHand() {
ItemStack itemStack = player.getItemInHand(); ItemStack itemStack = player.getItemInHand();
return itemStack != null ? itemStack.getTypeId() : 0; return itemStack != null ? itemStack.getTypeId() : 0;
} }
public BaseBlock getBlockInHand() throws WorldEditException { public BaseBlock getBlockInHand() throws WorldEditException {
ItemStack itemStack = player.getItemInHand(); ItemStack itemStack = player.getItemInHand();
return BukkitUtil.toBlock(getWorld(), itemStack); return BukkitUtil.toBlock(getWorld(), itemStack);
} }
@Override @Override
public String getName() { public String getName() {
return player.getName(); return player.getName();
} }
@Override @Override
public WorldVector getPosition() { public WorldVector getPosition() {
Location loc = player.getLocation(); Location loc = player.getLocation();
return new WorldVector(BukkitUtil.getLocalWorld(loc.getWorld()), return new WorldVector(BukkitUtil.getLocalWorld(loc.getWorld()),
loc.getX(), loc.getY(), loc.getZ()); loc.getX(), loc.getY(), loc.getZ());
} }
@Override @Override
public double getPitch() { public double getPitch() {
return player.getLocation().getPitch(); return player.getLocation().getPitch();
} }
@Override @Override
public double getYaw() { public double getYaw() {
return player.getLocation().getYaw(); return player.getLocation().getYaw();
} }
@Override @Override
public void giveItem(int type, int amt) { public void giveItem(int type, int amt) {
player.getInventory().addItem(new ItemStack(type, amt)); player.getInventory().addItem(new ItemStack(type, amt));
} }
@Override @Override
public void printRaw(String msg) { public void printRaw(String msg) {
for (String part : msg.split("\n")) { for (String part : msg.split("\n")) {
player.sendMessage(part); player.sendMessage(part);
} }
} }
@Override @Override
public void print(String msg) { public void print(String msg) {
for (String part : msg.split("\n")) { for (String part : msg.split("\n")) {
player.sendMessage("\u00A7d" + part); player.sendMessage("\u00A7d" + part);
} }
} }
@Override @Override
public void printDebug(String msg) { public void printDebug(String msg) {
for (String part : msg.split("\n")) { for (String part : msg.split("\n")) {
player.sendMessage("\u00A77" + part); player.sendMessage("\u00A77" + part);
} }
} }
@Override @Override
public void printError(String msg) { public void printError(String msg) {
for (String part : msg.split("\n")) { for (String part : msg.split("\n")) {
player.sendMessage("\u00A7c" + part); player.sendMessage("\u00A7c" + part);
} }
} }
@Override @Override
public void setPosition(Vector pos, float pitch, float yaw) { public void setPosition(Vector pos, float pitch, float yaw) {
player.teleport(new Location(player.getWorld(), pos.getX(), pos.getY(), player.teleport(new Location(player.getWorld(), pos.getX(), pos.getY(),
pos.getZ(), yaw, pitch)); pos.getZ(), yaw, pitch));
} }
@Override @Override
public String[] getGroups() { public String[] getGroups() {
return plugin.getPermissionsResolver().getGroups(player); return plugin.getPermissionsResolver().getGroups(player);
} }
@Override @Override
public BlockBag getInventoryBlockBag() { public BlockBag getInventoryBlockBag() {
return new BukkitPlayerBlockBag(player); return new BukkitPlayerBlockBag(player);
} }
@Override @Override
public boolean hasPermission(String perm) { public boolean hasPermission(String perm) {
return (!plugin.getLocalConfiguration().noOpPermissions && player.isOp()) return (!plugin.getLocalConfiguration().noOpPermissions && player.isOp())
|| plugin.getPermissionsResolver().hasPermission( || plugin.getPermissionsResolver().hasPermission(
player.getWorld().getName(), player, perm); player.getWorld().getName(), player, perm);
} }
@Override @Override
public LocalWorld getWorld() { public LocalWorld getWorld() {
return BukkitUtil.getLocalWorld(player.getWorld()); return BukkitUtil.getLocalWorld(player.getWorld());
} }
@Override @Override
public void dispatchCUIEvent(CUIEvent event) { public void dispatchCUIEvent(CUIEvent event) {
String[] params = event.getParameters(); String[] params = event.getParameters();
String send = event.getTypeId(); String send = event.getTypeId();
if (params.length > 0) { if (params.length > 0) {
send = send + "|" + StringUtil.joinString(params, "|"); send = send + "|" + StringUtil.joinString(params, "|");
} }
player.sendPluginMessage(plugin, WorldEditPlugin.CUI_PLUGIN_CHANNEL, send.getBytes(CUIChannelListener.UTF_8_CHARSET)); player.sendPluginMessage(plugin, WorldEditPlugin.CUI_PLUGIN_CHANNEL, send.getBytes(CUIChannelListener.UTF_8_CHARSET));
} }
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
@Override @Override
public boolean hasCreativeMode() { public boolean hasCreativeMode() {
return player.getGameMode() == GameMode.CREATIVE; return player.getGameMode() == GameMode.CREATIVE;
} }
@Override @Override
public void floatAt(int x, int y, int z, boolean alwaysGlass) { public void floatAt(int x, int y, int z, boolean alwaysGlass) {
if (alwaysGlass || !player.getAllowFlight()) { if (alwaysGlass || !player.getAllowFlight()) {
super.floatAt(x, y, z, alwaysGlass); super.floatAt(x, y, z, alwaysGlass);
return; return;
} }
setPosition(new Vector(x + 0.5, y, z + 0.5)); setPosition(new Vector(x + 0.5, y, z + 0.5));
player.setFlying(true); player.setFlying(true);
} }
} }

View File

@ -1,228 +1,228 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import com.sk89q.worldedit.WorldVector; import com.sk89q.worldedit.WorldVector;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.extent.inventory.*; import com.sk89q.worldedit.extent.inventory.*;
import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.blocks.BaseItem;
import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.ItemType; import com.sk89q.worldedit.blocks.ItemType;
public class BukkitPlayerBlockBag extends BlockBag { public class BukkitPlayerBlockBag extends BlockBag {
/** /**
* Player instance. * Player instance.
*/ */
private Player player; private Player player;
/** /**
* The player's inventory; * The player's inventory;
*/ */
private ItemStack[] items; private ItemStack[] items;
/** /**
* Construct the object. * Construct the object.
* *
* @param player * @param player
*/ */
public BukkitPlayerBlockBag(Player player) { public BukkitPlayerBlockBag(Player player) {
this.player = player; this.player = player;
} }
/** /**
* Loads inventory on first use. * Loads inventory on first use.
*/ */
private void loadInventory() { private void loadInventory() {
if (items == null) { if (items == null) {
items = player.getInventory().getContents(); items = player.getInventory().getContents();
} }
} }
/** /**
* Get the player. * Get the player.
* *
* @return * @return
*/ */
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
/** /**
* Get a block. * Get a block.
* *
* @param id * @param id
*/ */
@Override @Override
public void fetchItem(BaseItem item) throws BlockBagException { public void fetchItem(BaseItem item) throws BlockBagException {
final int id = item.getType(); final int id = item.getType();
final int damage = item.getData(); final int damage = item.getData();
int amount = (item instanceof BaseItemStack) ? ((BaseItemStack) item).getAmount() : 1; int amount = (item instanceof BaseItemStack) ? ((BaseItemStack) item).getAmount() : 1;
assert(amount == 1); assert(amount == 1);
boolean usesDamageValue = ItemType.usesDamageValue(id); boolean usesDamageValue = ItemType.usesDamageValue(id);
if (id == BlockID.AIR) { if (id == BlockID.AIR) {
throw new IllegalArgumentException("Can't fetch air block"); throw new IllegalArgumentException("Can't fetch air block");
} }
loadInventory(); loadInventory();
boolean found = false; boolean found = false;
for (int slot = 0; slot < items.length; ++slot) { for (int slot = 0; slot < items.length; ++slot) {
ItemStack bukkitItem = items[slot]; ItemStack bukkitItem = items[slot];
if (bukkitItem == null) { if (bukkitItem == null) {
continue; continue;
} }
if (bukkitItem.getTypeId() != id) { if (bukkitItem.getTypeId() != id) {
// Type id doesn't fit // Type id doesn't fit
continue; continue;
} }
if (usesDamageValue && bukkitItem.getDurability() != damage) { if (usesDamageValue && bukkitItem.getDurability() != damage) {
// Damage value doesn't fit. // Damage value doesn't fit.
continue; continue;
} }
int currentAmount = bukkitItem.getAmount(); int currentAmount = bukkitItem.getAmount();
if (currentAmount < 0) { if (currentAmount < 0) {
// Unlimited // Unlimited
return; return;
} }
if (currentAmount > 1) { if (currentAmount > 1) {
bukkitItem.setAmount(currentAmount - 1); bukkitItem.setAmount(currentAmount - 1);
found = true; found = true;
} else { } else {
items[slot] = null; items[slot] = null;
found = true; found = true;
} }
break; break;
} }
if (!found) { if (!found) {
throw new OutOfBlocksException(); throw new OutOfBlocksException();
} }
} }
/** /**
* Store a block. * Store a block.
* *
* @param id * @param id
*/ */
@Override @Override
public void storeItem(BaseItem item) throws BlockBagException { public void storeItem(BaseItem item) throws BlockBagException {
final int id = item.getType(); final int id = item.getType();
final int damage = item.getData(); final int damage = item.getData();
int amount = (item instanceof BaseItemStack) ? ((BaseItemStack) item).getAmount() : 1; int amount = (item instanceof BaseItemStack) ? ((BaseItemStack) item).getAmount() : 1;
assert(amount <= 64); assert(amount <= 64);
boolean usesDamageValue = ItemType.usesDamageValue(id); boolean usesDamageValue = ItemType.usesDamageValue(id);
if (id == BlockID.AIR) { if (id == BlockID.AIR) {
throw new IllegalArgumentException("Can't store air block"); throw new IllegalArgumentException("Can't store air block");
} }
loadInventory(); loadInventory();
int freeSlot = -1; int freeSlot = -1;
for (int slot = 0; slot < items.length; ++slot) { for (int slot = 0; slot < items.length; ++slot) {
ItemStack bukkitItem = items[slot]; ItemStack bukkitItem = items[slot];
if (bukkitItem == null) { if (bukkitItem == null) {
// Delay using up a free slot until we know there are no stacks // Delay using up a free slot until we know there are no stacks
// of this item to merge into // of this item to merge into
if (freeSlot == -1) { if (freeSlot == -1) {
freeSlot = slot; freeSlot = slot;
} }
continue; continue;
} }
if (bukkitItem.getTypeId() != id) { if (bukkitItem.getTypeId() != id) {
// Type id doesn't fit // Type id doesn't fit
continue; continue;
} }
if (usesDamageValue && bukkitItem.getDurability() != damage) { if (usesDamageValue && bukkitItem.getDurability() != damage) {
// Damage value doesn't fit. // Damage value doesn't fit.
continue; continue;
} }
int currentAmount = bukkitItem.getAmount(); int currentAmount = bukkitItem.getAmount();
if (currentAmount < 0) { if (currentAmount < 0) {
// Unlimited // Unlimited
return; return;
} }
if (currentAmount >= 64) { if (currentAmount >= 64) {
// Full stack // Full stack
continue; continue;
} }
int spaceLeft = 64 - currentAmount; int spaceLeft = 64 - currentAmount;
if (spaceLeft >= amount) { if (spaceLeft >= amount) {
bukkitItem.setAmount(currentAmount + amount); bukkitItem.setAmount(currentAmount + amount);
return; return;
} }
bukkitItem.setAmount(64); bukkitItem.setAmount(64);
amount -= spaceLeft; amount -= spaceLeft;
} }
if (freeSlot > -1) { if (freeSlot > -1) {
items[freeSlot] = new ItemStack(id, amount); items[freeSlot] = new ItemStack(id, amount);
return; return;
} }
throw new OutOfSpaceException(id); throw new OutOfSpaceException(id);
} }
/** /**
* Flush any changes. This is called at the end. * Flush any changes. This is called at the end.
*/ */
@Override @Override
public void flushChanges() { public void flushChanges() {
if (items != null) { if (items != null) {
player.getInventory().setContents(items); player.getInventory().setContents(items);
items = null; items = null;
} }
} }
/** /**
* Adds a position to be used a source. * Adds a position to be used a source.
* *
* @param pos * @param pos
*/ */
@Override @Override
public void addSourcePosition(WorldVector pos) { public void addSourcePosition(WorldVector pos) {
} }
/** /**
* Adds a position to be used a source. * Adds a position to be used a source.
* *
* @param pos * @param pos
*/ */
@Override @Override
public void addSingleSourcePosition(WorldVector pos) { public void addSingleSourcePosition(WorldVector pos) {
} }
} }

View File

@ -1,125 +1,125 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.sk89q.bukkit.util.CommandInfo; import com.sk89q.bukkit.util.CommandInfo;
import com.sk89q.bukkit.util.CommandRegistration; import com.sk89q.bukkit.util.CommandRegistration;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.CommandsManager; import com.sk89q.minecraft.util.commands.CommandsManager;
import com.sk89q.worldedit.LocalPlayer; import com.sk89q.worldedit.LocalPlayer;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import com.sk89q.worldedit.BiomeTypes; import com.sk89q.worldedit.BiomeTypes;
import com.sk89q.worldedit.LocalWorld; import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.ServerInterface; import com.sk89q.worldedit.ServerInterface;
public class BukkitServerInterface extends ServerInterface { public class BukkitServerInterface extends ServerInterface {
public Server server; public Server server;
public WorldEditPlugin plugin; public WorldEditPlugin plugin;
private CommandRegistration dynamicCommands; private CommandRegistration dynamicCommands;
private BukkitBiomeTypes biomes; private BukkitBiomeTypes biomes;
public BukkitServerInterface(WorldEditPlugin plugin, Server server) { public BukkitServerInterface(WorldEditPlugin plugin, Server server) {
this.plugin = plugin; this.plugin = plugin;
this.server = server; this.server = server;
this.biomes = new BukkitBiomeTypes(); this.biomes = new BukkitBiomeTypes();
dynamicCommands = new CommandRegistration(plugin); dynamicCommands = new CommandRegistration(plugin);
} }
@Override @Override
public int resolveItem(String name) { public int resolveItem(String name) {
Material mat = Material.matchMaterial(name); Material mat = Material.matchMaterial(name);
return mat == null ? 0 : mat.getId(); return mat == null ? 0 : mat.getId();
} }
@Override @Override
public boolean isValidMobType(String type) { public boolean isValidMobType(String type) {
final EntityType entityType = EntityType.fromName(type); final EntityType entityType = EntityType.fromName(type);
return entityType != null && entityType.isAlive(); return entityType != null && entityType.isAlive();
} }
@Override @Override
public void reload() { public void reload() {
plugin.loadConfiguration(); plugin.loadConfiguration();
} }
@Override @Override
public BiomeTypes getBiomes() { public BiomeTypes getBiomes() {
return biomes; return biomes;
} }
@Override @Override
public int schedule(long delay, long period, Runnable task) { public int schedule(long delay, long period, Runnable task) {
return Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, task, delay, period); return Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, task, delay, period);
} }
@Override @Override
public List<LocalWorld> getWorlds() { public List<LocalWorld> getWorlds() {
List<World> worlds = server.getWorlds(); List<World> worlds = server.getWorlds();
List<LocalWorld> ret = new ArrayList<LocalWorld>(worlds.size()); List<LocalWorld> ret = new ArrayList<LocalWorld>(worlds.size());
for (World world : worlds) { for (World world : worlds) {
ret.add(BukkitUtil.getLocalWorld(world)); ret.add(BukkitUtil.getLocalWorld(world));
} }
return ret; return ret;
} }
@Override @Override
public void onCommandRegistration(List<Command> commands, CommandsManager<LocalPlayer> manager) { public void onCommandRegistration(List<Command> commands, CommandsManager<LocalPlayer> manager) {
List<CommandInfo> toRegister = new ArrayList<CommandInfo>(); List<CommandInfo> toRegister = new ArrayList<CommandInfo>();
for (Command command : commands) { for (Command command : commands) {
List<String> permissions = null; List<String> permissions = null;
Method cmdMethod = manager.getMethods().get(null).get(command.aliases()[0]); Method cmdMethod = manager.getMethods().get(null).get(command.aliases()[0]);
Map<String, Method> childMethods = manager.getMethods().get(cmdMethod); Map<String, Method> childMethods = manager.getMethods().get(cmdMethod);
if (cmdMethod != null && cmdMethod.isAnnotationPresent(CommandPermissions.class)) { if (cmdMethod != null && cmdMethod.isAnnotationPresent(CommandPermissions.class)) {
permissions = Arrays.asList(cmdMethod.getAnnotation(CommandPermissions.class).value()); permissions = Arrays.asList(cmdMethod.getAnnotation(CommandPermissions.class).value());
} else if (cmdMethod != null && childMethods != null && childMethods.size() > 0) { } else if (cmdMethod != null && childMethods != null && childMethods.size() > 0) {
permissions = new ArrayList<String>(); permissions = new ArrayList<String>();
for (Method m : childMethods.values()) { for (Method m : childMethods.values()) {
if (m.isAnnotationPresent(CommandPermissions.class)) { if (m.isAnnotationPresent(CommandPermissions.class)) {
permissions.addAll(Arrays.asList(m.getAnnotation(CommandPermissions.class).value())); permissions.addAll(Arrays.asList(m.getAnnotation(CommandPermissions.class).value()));
} }
} }
} }
toRegister.add(new CommandInfo(command.usage(), command.desc(), command.aliases(), commands, permissions == null ? null : permissions.toArray(new String[permissions.size()]))); toRegister.add(new CommandInfo(command.usage(), command.desc(), command.aliases(), commands, permissions == null ? null : permissions.toArray(new String[permissions.size()])));
} }
dynamicCommands.register(toRegister); dynamicCommands.register(toRegister);
} }
public void unregisterCommands() { public void unregisterCommands() {
dynamicCommands.unregisterCommands(); dynamicCommands.unregisterCommands();
} }
} }

View File

@ -1,195 +1,195 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import java.util.List; import java.util.List;
import com.sk89q.worldedit.NotABlockException; import com.sk89q.worldedit.NotABlockException;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.BlockType; import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ItemID; import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldedit.blocks.SkullBlock; import com.sk89q.worldedit.blocks.SkullBlock;
import org.bukkit.DyeColor; import org.bukkit.DyeColor;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.ExperienceOrb; import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Item; import org.bukkit.entity.Item;
import org.bukkit.entity.Painting; import org.bukkit.entity.Painting;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockWorldVector; import com.sk89q.worldedit.BlockWorldVector;
import com.sk89q.worldedit.LocalWorld; import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.Location; import com.sk89q.worldedit.Location;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldVector; import com.sk89q.worldedit.WorldVector;
import com.sk89q.worldedit.bukkit.entity.BukkitEntity; import com.sk89q.worldedit.bukkit.entity.BukkitEntity;
import com.sk89q.worldedit.bukkit.entity.BukkitExpOrb; import com.sk89q.worldedit.bukkit.entity.BukkitExpOrb;
import com.sk89q.worldedit.bukkit.entity.BukkitItem; import com.sk89q.worldedit.bukkit.entity.BukkitItem;
import com.sk89q.worldedit.bukkit.entity.BukkitPainting; import com.sk89q.worldedit.bukkit.entity.BukkitPainting;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Dye; import org.bukkit.material.Dye;
public class BukkitUtil { public class BukkitUtil {
private BukkitUtil() { private BukkitUtil() {
} }
public static LocalWorld getLocalWorld(World w) { public static LocalWorld getLocalWorld(World w) {
return new BukkitWorld(w); return new BukkitWorld(w);
} }
public static BlockVector toVector(Block block) { public static BlockVector toVector(Block block) {
return new BlockVector(block.getX(), block.getY(), block.getZ()); return new BlockVector(block.getX(), block.getY(), block.getZ());
} }
public static BlockVector toVector(BlockFace face) { public static BlockVector toVector(BlockFace face) {
return new BlockVector(face.getModX(), face.getModY(), face.getModZ()); return new BlockVector(face.getModX(), face.getModY(), face.getModZ());
} }
public static BlockWorldVector toWorldVector(Block block) { public static BlockWorldVector toWorldVector(Block block) {
return new BlockWorldVector(getLocalWorld(block.getWorld()), block.getX(), block.getY(), block.getZ()); return new BlockWorldVector(getLocalWorld(block.getWorld()), block.getX(), block.getY(), block.getZ());
} }
public static Vector toVector(org.bukkit.Location loc) { public static Vector toVector(org.bukkit.Location loc) {
return new Vector(loc.getX(), loc.getY(), loc.getZ()); return new Vector(loc.getX(), loc.getY(), loc.getZ());
} }
public static Location toLocation(org.bukkit.Location loc) { public static Location toLocation(org.bukkit.Location loc) {
return new Location( return new Location(
getLocalWorld(loc.getWorld()), getLocalWorld(loc.getWorld()),
new Vector(loc.getX(), loc.getY(), loc.getZ()), new Vector(loc.getX(), loc.getY(), loc.getZ()),
loc.getYaw(), loc.getPitch() loc.getYaw(), loc.getPitch()
); );
} }
public static Vector toVector(org.bukkit.util.Vector vector) { public static Vector toVector(org.bukkit.util.Vector vector) {
return new Vector(vector.getX(), vector.getY(), vector.getZ()); return new Vector(vector.getX(), vector.getY(), vector.getZ());
} }
public static org.bukkit.Location toLocation(WorldVector pt) { public static org.bukkit.Location toLocation(WorldVector pt) {
return new org.bukkit.Location(toWorld(pt), pt.getX(), pt.getY(), pt.getZ()); return new org.bukkit.Location(toWorld(pt), pt.getX(), pt.getY(), pt.getZ());
} }
public static org.bukkit.Location toLocation(World world, Vector pt) { public static org.bukkit.Location toLocation(World world, Vector pt) {
return new org.bukkit.Location(world, pt.getX(), pt.getY(), pt.getZ()); return new org.bukkit.Location(world, pt.getX(), pt.getY(), pt.getZ());
} }
public static org.bukkit.Location center(org.bukkit.Location loc) { public static org.bukkit.Location center(org.bukkit.Location loc) {
return new org.bukkit.Location( return new org.bukkit.Location(
loc.getWorld(), loc.getWorld(),
loc.getBlockX() + 0.5, loc.getBlockX() + 0.5,
loc.getBlockY() + 0.5, loc.getBlockY() + 0.5,
loc.getBlockZ() + 0.5, loc.getBlockZ() + 0.5,
loc.getPitch(), loc.getPitch(),
loc.getYaw() loc.getYaw()
); );
} }
public static Player matchSinglePlayer(Server server, String name) { public static Player matchSinglePlayer(Server server, String name) {
List<Player> players = server.matchPlayer(name); List<Player> players = server.matchPlayer(name);
if (players.size() == 0) { if (players.size() == 0) {
return null; return null;
} }
return players.get(0); return players.get(0);
} }
public static Block toBlock(BlockWorldVector pt) { public static Block toBlock(BlockWorldVector pt) {
return toWorld(pt).getBlockAt(toLocation(pt)); return toWorld(pt).getBlockAt(toLocation(pt));
} }
public static World toWorld(WorldVector pt) { public static World toWorld(WorldVector pt) {
return ((BukkitWorld) pt.getWorld()).getWorld(); return ((BukkitWorld) pt.getWorld()).getWorld();
} }
/** /**
* Bukkit's Location class has serious problems with floating point * Bukkit's Location class has serious problems with floating point
* precision. * precision.
*/ */
@SuppressWarnings("RedundantIfStatement") @SuppressWarnings("RedundantIfStatement")
public static boolean equals(org.bukkit.Location a, org.bukkit.Location b) { public static boolean equals(org.bukkit.Location a, org.bukkit.Location b) {
if (Math.abs(a.getX() - b.getX()) > EQUALS_PRECISION) return false; if (Math.abs(a.getX() - b.getX()) > EQUALS_PRECISION) return false;
if (Math.abs(a.getY() - b.getY()) > EQUALS_PRECISION) return false; if (Math.abs(a.getY() - b.getY()) > EQUALS_PRECISION) return false;
if (Math.abs(a.getZ() - b.getZ()) > EQUALS_PRECISION) return false; if (Math.abs(a.getZ() - b.getZ()) > EQUALS_PRECISION) return false;
return true; return true;
} }
public static final double EQUALS_PRECISION = 0.0001; public static final double EQUALS_PRECISION = 0.0001;
public static org.bukkit.Location toLocation(Location location) { public static org.bukkit.Location toLocation(Location location) {
Vector pt = location.getPosition(); Vector pt = location.getPosition();
return new org.bukkit.Location( return new org.bukkit.Location(
toWorld(location.getWorld()), toWorld(location.getWorld()),
pt.getX(), pt.getY(), pt.getZ(), pt.getX(), pt.getY(), pt.getZ(),
location.getYaw(), location.getPitch() location.getYaw(), location.getPitch()
); );
} }
public static World toWorld(final LocalWorld world) { public static World toWorld(final LocalWorld world) {
return ((BukkitWorld) world).getWorld(); return ((BukkitWorld) world).getWorld();
} }
public static BukkitEntity toLocalEntity(Entity e) { public static BukkitEntity toLocalEntity(Entity e) {
switch (e.getType()) { switch (e.getType()) {
case EXPERIENCE_ORB: case EXPERIENCE_ORB:
return new BukkitExpOrb(toLocation(e.getLocation()), e.getUniqueId(), ((ExperienceOrb)e).getExperience()); return new BukkitExpOrb(toLocation(e.getLocation()), e.getUniqueId(), ((ExperienceOrb)e).getExperience());
case PAINTING: case PAINTING:
Painting paint = (Painting) e; Painting paint = (Painting) e;
return new BukkitPainting(toLocation(e.getLocation()), paint.getArt(), paint.getFacing(), e.getUniqueId()); return new BukkitPainting(toLocation(e.getLocation()), paint.getArt(), paint.getFacing(), e.getUniqueId());
case DROPPED_ITEM: case DROPPED_ITEM:
return new BukkitItem(toLocation(e.getLocation()), ((Item)e).getItemStack(), e.getUniqueId()); return new BukkitItem(toLocation(e.getLocation()), ((Item)e).getItemStack(), e.getUniqueId());
default: default:
return new BukkitEntity(toLocation(e.getLocation()), e.getType(), e.getUniqueId()); return new BukkitEntity(toLocation(e.getLocation()), e.getType(), e.getUniqueId());
} }
} }
public static BaseBlock toBlock(LocalWorld world, ItemStack itemStack) throws WorldEditException { public static BaseBlock toBlock(LocalWorld world, ItemStack itemStack) throws WorldEditException {
final int typeId = itemStack.getTypeId(); final int typeId = itemStack.getTypeId();
switch (typeId) { switch (typeId) {
case ItemID.INK_SACK: case ItemID.INK_SACK:
final Dye materialData = (Dye) itemStack.getData(); final Dye materialData = (Dye) itemStack.getData();
if (materialData.getColor() == DyeColor.BROWN) { if (materialData.getColor() == DyeColor.BROWN) {
return new BaseBlock(BlockID.COCOA_PLANT, -1); return new BaseBlock(BlockID.COCOA_PLANT, -1);
} }
break; break;
case ItemID.HEAD: case ItemID.HEAD:
return new SkullBlock(0, (byte) itemStack.getDurability()); return new SkullBlock(0, (byte) itemStack.getDurability());
default: default:
final BaseBlock baseBlock = BlockType.getBlockForItem(typeId, itemStack.getDurability()); final BaseBlock baseBlock = BlockType.getBlockForItem(typeId, itemStack.getDurability());
if (baseBlock != null) { if (baseBlock != null) {
return baseBlock; return baseBlock;
} }
break; break;
} }
if (world.isValidBlockType(typeId)) { if (world.isValidBlockType(typeId)) {
return new BaseBlock(typeId, -1); return new BaseBlock(typeId, -1);
} }
throw new NotABlockException(typeId); throw new NotABlockException(typeId);
} }
} }

View File

@ -1,436 +1,436 @@
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
// $Id$ // $Id$
/* /*
* This file is a part of WorldEdit. * This file is a part of WorldEdit.
* Copyright (c) sk89q <http://www.sk89q.com> * Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldEdit team and contributors * Copyright (c) the WorldEdit team and contributors
* *
* This program is free software: you can redistribute it and/or modify it under the * 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 * terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY * 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 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public License along with * You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>. * this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
import com.sk89q.jnbt.*; import com.sk89q.jnbt.*;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.TileEntityBlock; import com.sk89q.worldedit.blocks.TileEntityBlock;
import com.sk89q.worldedit.world.DataException; import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.foundation.Block; import com.sk89q.worldedit.foundation.Block;
import net.minecraft.server.v1_7_R2.*; import net.minecraft.server.v1_7_R2.*;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.craftbukkit.v1_7_R2.CraftWorld; import org.bukkit.craftbukkit.v1_7_R2.CraftWorld;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.*; import java.util.*;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**
* A blind handler of blocks with TileEntity data that directly access Minecraft's * A blind handler of blocks with TileEntity data that directly access Minecraft's
* classes through CraftBukkit. * classes through CraftBukkit.
* </p> * </p>
* Usage of this class may break terribly in the future, and therefore usage should * Usage of this class may break terribly in the future, and therefore usage should
* be trapped in a handler for {@link Throwable}. * be trapped in a handler for {@link Throwable}.
*/ */
public class DefaultNmsBlock extends NmsBlock { public class DefaultNmsBlock extends NmsBlock {
private static final Logger logger = WorldEdit.logger; private static final Logger logger = WorldEdit.logger;
private static Field compoundMapField; private static Field compoundMapField;
private static final Field nmsBlock_isTileEntityField; // The field is deobfuscated but the method isn't. No idea why. private static final Field nmsBlock_isTileEntityField; // The field is deobfuscated but the method isn't. No idea why.
private NBTTagCompound nbtData = null; private NBTTagCompound nbtData = null;
static { static {
Field field; Field field;
try { try {
field = net.minecraft.server.v1_7_R2.Block.class.getDeclaredField("isTileEntity"); field = net.minecraft.server.v1_7_R2.Block.class.getDeclaredField("isTileEntity");
field.setAccessible(true); field.setAccessible(true);
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException e) {
// logger.severe("Could not find NMS block tile entity field!"); // logger.severe("Could not find NMS block tile entity field!");
field = null; field = null;
} }
nmsBlock_isTileEntityField = field; nmsBlock_isTileEntityField = field;
} }
public static boolean verify() { public static boolean verify() {
return nmsBlock_isTileEntityField != null; return nmsBlock_isTileEntityField != null;
} }
/** /**
* Create a new instance with a given type ID, data value, and previous * Create a new instance with a given type ID, data value, and previous
* {@link TileEntityBlock}-implementing object. * {@link TileEntityBlock}-implementing object.
* *
* @param type block type ID * @param type block type ID
* @param data data value * @param data data value
* @param tileEntityBlock tile entity block * @param tileEntityBlock tile entity block
*/ */
public DefaultNmsBlock(int type, int data, TileEntityBlock tileEntityBlock) { public DefaultNmsBlock(int type, int data, TileEntityBlock tileEntityBlock) {
super(type, data); super(type, data);
nbtData = (NBTTagCompound) fromNative(tileEntityBlock.getNbtData()); nbtData = (NBTTagCompound) fromNative(tileEntityBlock.getNbtData());
} }
/** /**
* Create a new instance with a given type ID, data value, and raw * Create a new instance with a given type ID, data value, and raw
* {@link NBTTagCompound} copy. * {@link NBTTagCompound} copy.
* *
* @param type block type ID * @param type block type ID
* @param data data value * @param data data value
* @param nbtData raw NBT data * @param nbtData raw NBT data
*/ */
public DefaultNmsBlock(int type, int data, NBTTagCompound nbtData) { public DefaultNmsBlock(int type, int data, NBTTagCompound nbtData) {
super(type, data); super(type, data);
this.nbtData = nbtData; this.nbtData = nbtData;
} }
/** /**
* Build a {@link NBTTagCompound} that has valid coordinates. * Build a {@link NBTTagCompound} that has valid coordinates.
* *
* @param pt coordinates to set * @param pt coordinates to set
* @return the tag compound * @return the tag compound
*/ */
private NBTTagCompound getNmsData(Vector pt) { private NBTTagCompound getNmsData(Vector pt) {
if (nbtData == null) { if (nbtData == null) {
return null; return null;
} }
nbtData.set("x", new NBTTagInt(pt.getBlockX())); nbtData.set("x", new NBTTagInt(pt.getBlockX()));
nbtData.set("y", new NBTTagInt(pt.getBlockY())); nbtData.set("y", new NBTTagInt(pt.getBlockY()));
nbtData.set("z", new NBTTagInt(pt.getBlockZ())); nbtData.set("z", new NBTTagInt(pt.getBlockZ()));
return nbtData; return nbtData;
} }
@Override @Override
public boolean hasNbtData() { public boolean hasNbtData() {
return nbtData != null; return nbtData != null;
} }
@Override @Override
public String getNbtId() { public String getNbtId() {
if (nbtData == null) { if (nbtData == null) {
return ""; return "";
} }
return nbtData.getString("id"); return nbtData.getString("id");
} }
@Override @Override
public CompoundTag getNbtData() { public CompoundTag getNbtData() {
if (nbtData == null) { if (nbtData == null) {
return new CompoundTag(getNbtId(), return new CompoundTag(getNbtId(),
new HashMap<String, Tag>()); new HashMap<String, Tag>());
} }
return (CompoundTag) toNative(nbtData); return (CompoundTag) toNative(nbtData);
} }
@Override @Override
public void setNbtData(CompoundTag tag) throws DataException { public void setNbtData(CompoundTag tag) throws DataException {
if (tag == null) { if (tag == null) {
this.nbtData = null; this.nbtData = null;
} }
this.nbtData = (NBTTagCompound) fromNative(tag); this.nbtData = (NBTTagCompound) fromNative(tag);
} }
/** /**
* Build an instance from the given information. * Build an instance from the given information.
* *
* @param world world to get the block from * @param world world to get the block from
* @param position position to get the block at * @param position position to get the block at
* @param type type ID of block * @param type type ID of block
* @param data data value of block * @param data data value of block
* @return the block, or null * @return the block, or null
*/ */
public static DefaultNmsBlock get(World world, Vector position, int type, int data) { public static DefaultNmsBlock get(World world, Vector position, int type, int data) {
if (!hasTileEntity(type)) { if (!hasTileEntity(type)) {
return null; return null;
} }
TileEntity te = ((CraftWorld) world).getHandle().getTileEntity( TileEntity te = ((CraftWorld) world).getHandle().getTileEntity(
position.getBlockX(), position.getBlockY(), position.getBlockZ()); position.getBlockX(), position.getBlockY(), position.getBlockZ());
if (te != null) { if (te != null) {
NBTTagCompound tag = new NBTTagCompound(); NBTTagCompound tag = new NBTTagCompound();
te.b(tag); // Load data te.b(tag); // Load data
return new DefaultNmsBlock(type, data, tag); return new DefaultNmsBlock(type, data, tag);
} }
return null; return null;
} }
/** /**
* Set an instance or a {@link TileEntityBlock} to the given position. * Set an instance or a {@link TileEntityBlock} to the given position.
* *
* @param world world to set the block in * @param world world to set the block in
* @param position position to set the block at * @param position position to set the block at
* @param block the block to set * @param block the block to set
* @return true if tile entity data was copied to the world * @return true if tile entity data was copied to the world
*/ */
public static boolean set(World world, Vector position, BaseBlock block) { public static boolean set(World world, Vector position, BaseBlock block) {
NBTTagCompound data = null; NBTTagCompound data = null;
if (!hasTileEntity(world.getBlockTypeIdAt(position.getBlockX(), position.getBlockY(), position.getBlockZ()))) { if (!hasTileEntity(world.getBlockTypeIdAt(position.getBlockX(), position.getBlockY(), position.getBlockZ()))) {
return false; return false;
} }
if (block instanceof DefaultNmsBlock) { if (block instanceof DefaultNmsBlock) {
DefaultNmsBlock nmsProxyBlock = (DefaultNmsBlock) block; DefaultNmsBlock nmsProxyBlock = (DefaultNmsBlock) block;
data = nmsProxyBlock.getNmsData(position); data = nmsProxyBlock.getNmsData(position);
} else if (block instanceof TileEntityBlock) { } else if (block instanceof TileEntityBlock) {
DefaultNmsBlock nmsProxyBlock = new DefaultNmsBlock( DefaultNmsBlock nmsProxyBlock = new DefaultNmsBlock(
block.getId(), block.getData(), block); block.getId(), block.getData(), block);
data = nmsProxyBlock.getNmsData(position); data = nmsProxyBlock.getNmsData(position);
} }
if (data != null) { if (data != null) {
TileEntity te = ((CraftWorld) world).getHandle().getTileEntity( TileEntity te = ((CraftWorld) world).getHandle().getTileEntity(
position.getBlockX(), position.getBlockY(), position.getBlockZ()); position.getBlockX(), position.getBlockY(), position.getBlockZ());
if (te != null) { if (te != null) {
te.a(data); // Load data te.a(data); // Load data
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* Tries to set a block 'safely', as in setting the block data to the location, and * Tries to set a block 'safely', as in setting the block data to the location, and
* then triggering physics only at the end. * then triggering physics only at the end.
* *
* @param world world to set the block in * @param world world to set the block in
* @param position position to set the block at * @param position position to set the block at
* @param block the block to set * @param block the block to set
* @param notifyAdjacent true to notify physics and what not * @param notifyAdjacent true to notify physics and what not
* @return true if block id or data was changed * @return true if block id or data was changed
*/ */
public static boolean setSafely(BukkitWorld world, Vector position, public static boolean setSafely(BukkitWorld world, Vector position,
Block block, boolean notifyAdjacent) { Block block, boolean notifyAdjacent) {
int x = position.getBlockX(); int x = position.getBlockX();
int y = position.getBlockY(); int y = position.getBlockY();
int z = position.getBlockZ(); int z = position.getBlockZ();
CraftWorld craftWorld = ((CraftWorld) world.getWorld()); CraftWorld craftWorld = ((CraftWorld) world.getWorld());
// TileEntity te = craftWorld.getHandle().getTileEntity(x, y, z); // TileEntity te = craftWorld.getHandle().getTileEntity(x, y, z);
// craftWorld.getHandle().tileEntityList.remove(te); // craftWorld.getHandle().tileEntityList.remove(te);
boolean changed = craftWorld.getHandle().setTypeAndData(x, y, z, getNmsBlock(block.getId()), block.getData(), 0); boolean changed = craftWorld.getHandle().setTypeAndData(x, y, z, getNmsBlock(block.getId()), block.getData(), 0);
if (block instanceof BaseBlock) { if (block instanceof BaseBlock) {
world.copyToWorld(position, (BaseBlock) block); world.copyToWorld(position, (BaseBlock) block);
} }
changed = craftWorld.getHandle().setData(x, y, z, block.getData(), 0) || changed; changed = craftWorld.getHandle().setData(x, y, z, block.getData(), 0) || changed;
if (changed && notifyAdjacent) { if (changed && notifyAdjacent) {
craftWorld.getHandle().notify(x, y, z); craftWorld.getHandle().notify(x, y, z);
craftWorld.getHandle().update(x, y, z, getNmsBlock(block.getId())); craftWorld.getHandle().update(x, y, z, getNmsBlock(block.getId()));
} }
return changed; return changed;
} }
public static boolean hasTileEntity(int type) { public static boolean hasTileEntity(int type) {
net.minecraft.server.v1_7_R2.Block nmsBlock = getNmsBlock(type); net.minecraft.server.v1_7_R2.Block nmsBlock = getNmsBlock(type);
if (nmsBlock == null) { if (nmsBlock == null) {
return false; return false;
} }
try { try {
return nmsBlock_isTileEntityField.getBoolean(nmsBlock); // Once we have the field stord, gets are fast return nmsBlock_isTileEntityField.getBoolean(nmsBlock); // Once we have the field stord, gets are fast
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
return false; return false;
} }
} }
public static net.minecraft.server.v1_7_R2.Block getNmsBlock(int type) { public static net.minecraft.server.v1_7_R2.Block getNmsBlock(int type) {
return net.minecraft.server.v1_7_R2.Block.e(type); return net.minecraft.server.v1_7_R2.Block.e(type);
} }
/** /**
* Converts from a non-native NMS NBT structure to a native WorldEdit NBT * Converts from a non-native NMS NBT structure to a native WorldEdit NBT
* structure. * structure.
* *
* @param foreign non-native NMS NBT structure * @param foreign non-native NMS NBT structure
* @return native WorldEdit NBT structure * @return native WorldEdit NBT structure
*/ */
private static Tag toNative(NBTBase foreign) { private static Tag toNative(NBTBase foreign) {
// temporary fix since mojang removed names from tags // temporary fix since mojang removed names from tags
// our nbt spec will need to be updated to theirs // our nbt spec will need to be updated to theirs
return toNative(NBTBase.getTagName(foreign.getTypeId()), foreign); return toNative(NBTBase.getTagName(foreign.getTypeId()), foreign);
} }
/** /**
* Converts from a non-native NMS NBT structure to a native WorldEdit NBT * Converts from a non-native NMS NBT structure to a native WorldEdit NBT
* structure. * structure.
* *
* @param foreign non-native NMS NBT structure * @param foreign non-native NMS NBT structure
* @param name name for the tag, if it has one * @param name name for the tag, if it has one
* @return native WorldEdit NBT structure * @return native WorldEdit NBT structure
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static Tag toNative(String name, NBTBase foreign) { private static Tag toNative(String name, NBTBase foreign) {
if (foreign == null) { if (foreign == null) {
return null; return null;
} }
if (foreign instanceof NBTTagCompound) { if (foreign instanceof NBTTagCompound) {
Map<String, Tag> values = new HashMap<String, Tag>(); Map<String, Tag> values = new HashMap<String, Tag>();
Collection<Object> foreignKeys = null; Collection<Object> foreignKeys = null;
if (compoundMapField == null) { if (compoundMapField == null) {
try { try {
// Method name may change! // Method name may change!
foreignKeys = ((NBTTagCompound) foreign).c(); foreignKeys = ((NBTTagCompound) foreign).c();
} catch (Throwable t) { } catch (Throwable t) {
try { try {
logger.warning("WorldEdit: Couldn't get NBTTagCompound.c(), " + logger.warning("WorldEdit: Couldn't get NBTTagCompound.c(), " +
"so we're going to try to get at the 'map' field directly from now on"); "so we're going to try to get at the 'map' field directly from now on");
if (compoundMapField == null) { if (compoundMapField == null) {
compoundMapField = NBTTagCompound.class.getDeclaredField("map"); compoundMapField = NBTTagCompound.class.getDeclaredField("map");
compoundMapField.setAccessible(true); compoundMapField.setAccessible(true);
} }
} catch (Throwable e) { } catch (Throwable e) {
// Can't do much beyond this // Can't do much beyond this
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
} }
if (compoundMapField != null) { if (compoundMapField != null) {
try { try {
foreignKeys = ((HashMap<Object, Object>) compoundMapField.get(foreign)).keySet(); foreignKeys = ((HashMap<Object, Object>) compoundMapField.get(foreign)).keySet();
} catch (Throwable e) { } catch (Throwable e) {
// Can't do much beyond this // Can't do much beyond this
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
for (Object obj : foreignKeys) { for (Object obj : foreignKeys) {
String key = (String) obj; String key = (String) obj;
NBTBase base = (NBTBase) ((NBTTagCompound) foreign).get(key); NBTBase base = (NBTBase) ((NBTTagCompound) foreign).get(key);
values.put(key, toNative(key, base)); values.put(key, toNative(key, base));
} }
return new CompoundTag(name, values); return new CompoundTag(name, values);
} else if (foreign instanceof NBTTagByte) { } else if (foreign instanceof NBTTagByte) {
return new ByteTag(name, ((NBTTagByte) foreign).f()); // getByte return new ByteTag(name, ((NBTTagByte) foreign).f()); // getByte
} else if (foreign instanceof NBTTagByteArray) { } else if (foreign instanceof NBTTagByteArray) {
return new ByteArrayTag(name, return new ByteArrayTag(name,
((NBTTagByteArray) foreign).c()); // data ((NBTTagByteArray) foreign).c()); // data
} else if (foreign instanceof NBTTagDouble) { } else if (foreign instanceof NBTTagDouble) {
return new DoubleTag(name, return new DoubleTag(name,
((NBTTagDouble) foreign).g()); // getDouble ((NBTTagDouble) foreign).g()); // getDouble
} else if (foreign instanceof NBTTagFloat) { } else if (foreign instanceof NBTTagFloat) {
return new FloatTag(name, ((NBTTagFloat) foreign).h()); // getFloat return new FloatTag(name, ((NBTTagFloat) foreign).h()); // getFloat
} else if (foreign instanceof NBTTagInt) { } else if (foreign instanceof NBTTagInt) {
return new IntTag(name, ((NBTTagInt) foreign).d()); // getInt return new IntTag(name, ((NBTTagInt) foreign).d()); // getInt
} else if (foreign instanceof NBTTagIntArray) { } else if (foreign instanceof NBTTagIntArray) {
return new IntArrayTag(name, return new IntArrayTag(name,
((NBTTagIntArray) foreign).c()); // data ((NBTTagIntArray) foreign).c()); // data
} else if (foreign instanceof NBTTagList) { } else if (foreign instanceof NBTTagList) {
try { try {
return transmorgifyList(name, (NBTTagList) foreign); return transmorgifyList(name, (NBTTagList) foreign);
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException e) {
} catch (SecurityException e) { } catch (SecurityException e) {
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {} } catch (IllegalAccessException e) {}
return new ListTag(name, ByteTag.class, new ArrayList<ByteTag>()); return new ListTag(name, ByteTag.class, new ArrayList<ByteTag>());
} else if (foreign instanceof NBTTagLong) { } else if (foreign instanceof NBTTagLong) {
return new LongTag(name, ((NBTTagLong) foreign).c()); // getLong return new LongTag(name, ((NBTTagLong) foreign).c()); // getLong
} else if (foreign instanceof NBTTagShort) { } else if (foreign instanceof NBTTagShort) {
return new ShortTag(name, ((NBTTagShort) foreign).e()); // getShort return new ShortTag(name, ((NBTTagShort) foreign).e()); // getShort
} else if (foreign instanceof NBTTagString) { } else if (foreign instanceof NBTTagString) {
return new StringTag(name, return new StringTag(name,
((NBTTagString) foreign).a_()); // data ((NBTTagString) foreign).a_()); // data
} else if (foreign instanceof NBTTagEnd) { } else if (foreign instanceof NBTTagEnd) {
return new EndTag(); return new EndTag();
} else { } else {
throw new IllegalArgumentException("Don't know how to make native " throw new IllegalArgumentException("Don't know how to make native "
+ foreign.getClass().getCanonicalName()); + foreign.getClass().getCanonicalName());
} }
} }
private static ListTag transmorgifyList(String name, NBTTagList foreign) private static ListTag transmorgifyList(String name, NBTTagList foreign)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
List<Tag> values = new ArrayList<Tag>(); List<Tag> values = new ArrayList<Tag>();
int type = foreign.d(); int type = foreign.d();
Field listField = NBTTagList.class.getDeclaredField("list"); Field listField = NBTTagList.class.getDeclaredField("list");
listField.setAccessible(true); listField.setAccessible(true);
List foreignList; List foreignList;
foreignList = (List) listField.get(foreign); foreignList = (List) listField.get(foreign);
for (int i = 0; i < foreign.size(); i++) { for (int i = 0; i < foreign.size(); i++) {
NBTBase element = (NBTBase) foreignList.get(i); NBTBase element = (NBTBase) foreignList.get(i);
values.add(toNative(null, element)); // list elements shouldn't have names values.add(toNative(null, element)); // list elements shouldn't have names
} }
Class<? extends Tag> cls = NBTConstants.getClassFromType(type); Class<? extends Tag> cls = NBTConstants.getClassFromType(type);
return new ListTag(name, cls, values); return new ListTag(name, cls, values);
} }
/** /**
* Converts a WorldEdit-native NBT structure to a NMS structure. * Converts a WorldEdit-native NBT structure to a NMS structure.
* *
* @param foreign structure to convert * @param foreign structure to convert
* @return non-native structure * @return non-native structure
*/ */
private static NBTBase fromNative(Tag foreign) { private static NBTBase fromNative(Tag foreign) {
if (foreign == null) { if (foreign == null) {
return null; return null;
} }
if (foreign instanceof CompoundTag) { if (foreign instanceof CompoundTag) {
NBTTagCompound tag = new NBTTagCompound(); NBTTagCompound tag = new NBTTagCompound();
for (Map.Entry<String, Tag> entry : ((CompoundTag) foreign) for (Map.Entry<String, Tag> entry : ((CompoundTag) foreign)
.getValue().entrySet()) { .getValue().entrySet()) {
tag.set(entry.getKey(), fromNative(entry.getValue())); tag.set(entry.getKey(), fromNative(entry.getValue()));
} }
return tag; return tag;
} else if (foreign instanceof ByteTag) { } else if (foreign instanceof ByteTag) {
return new NBTTagByte(((ByteTag) foreign).getValue()); return new NBTTagByte(((ByteTag) foreign).getValue());
} else if (foreign instanceof ByteArrayTag) { } else if (foreign instanceof ByteArrayTag) {
return new NBTTagByteArray(((ByteArrayTag) foreign).getValue()); return new NBTTagByteArray(((ByteArrayTag) foreign).getValue());
} else if (foreign instanceof DoubleTag) { } else if (foreign instanceof DoubleTag) {
return new NBTTagDouble(((DoubleTag) foreign).getValue()); return new NBTTagDouble(((DoubleTag) foreign).getValue());
} else if (foreign instanceof FloatTag) { } else if (foreign instanceof FloatTag) {
return new NBTTagFloat(((FloatTag) foreign).getValue()); return new NBTTagFloat(((FloatTag) foreign).getValue());
} else if (foreign instanceof IntTag) { } else if (foreign instanceof IntTag) {
return new NBTTagInt(((IntTag) foreign).getValue()); return new NBTTagInt(((IntTag) foreign).getValue());
} else if (foreign instanceof IntArrayTag) { } else if (foreign instanceof IntArrayTag) {
return new NBTTagIntArray(((IntArrayTag) foreign).getValue()); return new NBTTagIntArray(((IntArrayTag) foreign).getValue());
} else if (foreign instanceof ListTag) { } else if (foreign instanceof ListTag) {
NBTTagList tag = new NBTTagList(); NBTTagList tag = new NBTTagList();
ListTag foreignList = (ListTag) foreign; ListTag foreignList = (ListTag) foreign;
for (Tag t : foreignList.getValue()) { for (Tag t : foreignList.getValue()) {
tag.add(fromNative(t)); tag.add(fromNative(t));
} }
return tag; return tag;
} else if (foreign instanceof LongTag) { } else if (foreign instanceof LongTag) {
return new NBTTagLong(((LongTag) foreign).getValue()); return new NBTTagLong(((LongTag) foreign).getValue());
} else if (foreign instanceof ShortTag) { } else if (foreign instanceof ShortTag) {
return new NBTTagShort(((ShortTag) foreign).getValue()); return new NBTTagShort(((ShortTag) foreign).getValue());
} else if (foreign instanceof StringTag) { } else if (foreign instanceof StringTag) {
return new NBTTagString(((StringTag) foreign).getValue()); return new NBTTagString(((StringTag) foreign).getValue());
} else if (foreign instanceof EndTag) { } else if (foreign instanceof EndTag) {
try { try {
Method tagMaker = NBTBase.class.getDeclaredMethod("createTag", byte.class); Method tagMaker = NBTBase.class.getDeclaredMethod("createTag", byte.class);
tagMaker.setAccessible(true); tagMaker.setAccessible(true);
return (NBTBase) tagMaker.invoke(null, (byte) 0); return (NBTBase) tagMaker.invoke(null, (byte) 0);
} catch (Exception e) { } catch (Exception e) {
return null; return null;
} }
} else { } else {
throw new IllegalArgumentException("Don't know how to make NMS " throw new IllegalArgumentException("Don't know how to make NMS "
+ foreign.getClass().getCanonicalName()); + foreign.getClass().getCanonicalName());
} }
} }
public static boolean isValidBlockType(int type) throws NoClassDefFoundError { public static boolean isValidBlockType(int type) throws NoClassDefFoundError {
return type == 0 || (type >= 1 && net.minecraft.server.v1_7_R2.Block.e(type) != null); return type == 0 || (type >= 1 && net.minecraft.server.v1_7_R2.Block.e(type) != null);
} }
} }

View File

@ -1,76 +1,76 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import org.bukkit.BlockChangeDelegate; import org.bukkit.BlockChangeDelegate;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
/** /**
* Proxy class to catch calls to set blocks. * Proxy class to catch calls to set blocks.
* *
* @author sk89q * @author sk89q
*/ */
public class EditSessionBlockChangeDelegate implements BlockChangeDelegate { public class EditSessionBlockChangeDelegate implements BlockChangeDelegate {
private EditSession editSession; private EditSession editSession;
public EditSessionBlockChangeDelegate(EditSession editSession) { public EditSessionBlockChangeDelegate(EditSession editSession) {
this.editSession = editSession; this.editSession = editSession;
} }
public boolean setRawTypeId(int x, int y, int z, int typeId) { public boolean setRawTypeId(int x, int y, int z, int typeId) {
try { try {
return editSession.setBlock(new Vector(x, y, z), new BaseBlock(typeId)); return editSession.setBlock(new Vector(x, y, z), new BaseBlock(typeId));
} catch (MaxChangedBlocksException ex) { } catch (MaxChangedBlocksException ex) {
return false; return false;
} }
} }
public boolean setRawTypeIdAndData(int x, int y, int z, int typeId, int data) { public boolean setRawTypeIdAndData(int x, int y, int z, int typeId, int data) {
try { try {
return editSession.setBlock(new Vector(x, y, z), new BaseBlock(typeId, data)); return editSession.setBlock(new Vector(x, y, z), new BaseBlock(typeId, data));
} catch (MaxChangedBlocksException ex) { } catch (MaxChangedBlocksException ex) {
return false; return false;
} }
} }
public boolean setTypeId(int x, int y, int z, int typeId) { public boolean setTypeId(int x, int y, int z, int typeId) {
return setRawTypeId(x, y, z, typeId); return setRawTypeId(x, y, z, typeId);
} }
public boolean setTypeIdAndData(int x, int y, int z, int typeId, int data) { public boolean setTypeIdAndData(int x, int y, int z, int typeId, int data) {
return setRawTypeIdAndData(x, y, z, typeId, data); return setRawTypeIdAndData(x, y, z, typeId, data);
} }
public int getTypeId(int x, int y, int z) { public int getTypeId(int x, int y, int z) {
return editSession.getBlockType(new Vector(x, y, z)); return editSession.getBlockType(new Vector(x, y, z));
} }
public int getHeight() { public int getHeight() {
return editSession.getWorld().getMaxY() + 1; return editSession.getWorld().getMaxY() + 1;
} }
public boolean isEmpty(int x, int y, int z) { public boolean isEmpty(int x, int y, int z) {
return editSession.getBlockType(new Vector(x, y, z)) == BlockID.AIR; return editSession.getBlockType(new Vector(x, y, z)) == BlockID.AIR;
} }
} }

View File

@ -1,42 +1,42 @@
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import org.bukkit.World; import org.bukkit.World;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.foundation.Block; import com.sk89q.worldedit.foundation.Block;
public abstract class NmsBlock extends BaseBlock { public abstract class NmsBlock extends BaseBlock {
protected NmsBlock(int type) { protected NmsBlock(int type) {
super(type); super(type);
} }
protected NmsBlock(int type, int data) { protected NmsBlock(int type, int data) {
super(type, data); super(type, data);
} }
public static boolean verify() { public static boolean verify() {
return false; return false;
} }
public static NmsBlock get(World world, Vector vector, int type, int data) { public static NmsBlock get(World world, Vector vector, int type, int data) {
return null; return null;
} }
public static boolean set(World world, Vector vector, Block block) { public static boolean set(World world, Vector vector, Block block) {
return false; return false;
} }
public static boolean setSafely(World world, Vector vector, Block block, boolean notify) { public static boolean setSafely(World world, Vector vector, Block block, boolean notify) {
return false; return false;
} }
public static boolean hasTileEntity(int type) { public static boolean hasTileEntity(int type) {
return false; return false;
} }
public static boolean isValidBlockType(int type) { public static boolean isValidBlockType(int type) {
return false; return false;
} }
} }

View File

@ -1,51 +1,51 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.sk89q.worldedit.SessionCheck; import com.sk89q.worldedit.SessionCheck;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
/** /**
* Used to remove expired sessions in Bukkit. * Used to remove expired sessions in Bukkit.
* *
* @author sk89q * @author sk89q
*/ */
public class SessionTimer implements Runnable { public class SessionTimer implements Runnable {
private WorldEdit worldEdit; private WorldEdit worldEdit;
private SessionCheck checker; private SessionCheck checker;
public SessionTimer(WorldEdit worldEdit, final Server server) { public SessionTimer(WorldEdit worldEdit, final Server server) {
this.worldEdit = worldEdit; this.worldEdit = worldEdit;
this.checker = new SessionCheck() { this.checker = new SessionCheck() {
public boolean isOnlinePlayer(String name) { public boolean isOnlinePlayer(String name) {
Player player = server.getPlayer(name); Player player = server.getPlayer(name);
return player != null && player.isOnline(); return player != null && player.isOnline();
} }
}; };
} }
public void run() { public void run() {
worldEdit.flushExpiredSessions(checker); worldEdit.flushExpiredSessions(checker);
} }
} }

View File

@ -1,42 +1,42 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
public class WorldEditAPI { public class WorldEditAPI {
private WorldEditPlugin plugin; private WorldEditPlugin plugin;
public WorldEditAPI(WorldEditPlugin plugin) { public WorldEditAPI(WorldEditPlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
/** /**
* Get the session for a player. * Get the session for a player.
* *
* @param player * @param player
* @return * @return
*/ */
public LocalSession getSession(Player player) { public LocalSession getSession(Player player) {
return plugin.getWorldEdit().getSession( return plugin.getWorldEdit().getSession(
new BukkitPlayer(plugin, plugin.getServerInterface(), player)); new BukkitPlayer(plugin, plugin.getServerInterface(), player));
} }
} }

View File

@ -1,178 +1,178 @@
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2012 sk89q <http://www.sk89q.com> * Copyright (C) 2012 sk89q <http://www.sk89q.com>
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
// $Id$ // $Id$
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.event.Event.Result; import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import com.sk89q.util.StringUtil; import com.sk89q.util.StringUtil;
import com.sk89q.worldedit.LocalPlayer; import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalWorld; import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldVector; import com.sk89q.worldedit.WorldVector;
/** /**
* Handles all events thrown in relation to a Player * Handles all events thrown in relation to a Player
*/ */
public class WorldEditListener implements Listener { public class WorldEditListener implements Listener {
private WorldEditPlugin plugin; private WorldEditPlugin plugin;
private boolean ignoreLeftClickAir = false; private boolean ignoreLeftClickAir = false;
/** /**
* Called when a player plays an animation, such as an arm swing * Called when a player plays an animation, such as an arm swing
* *
* @param event Relevant event details * @param event Relevant event details
*/ */
/** /**
* Construct the object; * Construct the object;
* *
* @param plugin * @param plugin
*/ */
public WorldEditListener(WorldEditPlugin plugin) { public WorldEditListener(WorldEditPlugin plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
/** /**
* Called when a player leaves a server * Called when a player leaves a server
* *
* @param event Relevant event details * @param event Relevant event details
*/ */
@EventHandler @EventHandler
public void onPlayerQuit(PlayerQuitEvent event) { public void onPlayerQuit(PlayerQuitEvent event) {
plugin.getWorldEdit().markExpire(plugin.wrapPlayer(event.getPlayer())); plugin.getWorldEdit().markExpire(plugin.wrapPlayer(event.getPlayer()));
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onGamemode(PlayerGameModeChangeEvent event) { public void onGamemode(PlayerGameModeChangeEvent event) {
// this will automatically refresh their sesssion, we don't have to do anything // this will automatically refresh their sesssion, we don't have to do anything
WorldEdit.getInstance().getSession(plugin.wrapPlayer(event.getPlayer())); WorldEdit.getInstance().getSession(plugin.wrapPlayer(event.getPlayer()));
} }
/** /**
* Called when a player attempts to use a command * Called when a player attempts to use a command
* *
* @param event Relevant event details * @param event Relevant event details
*/ */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
String[] split = event.getMessage().split(" "); String[] split = event.getMessage().split(" ");
if (split.length > 0) { if (split.length > 0) {
split = plugin.getWorldEdit().commandDetection(split); split = plugin.getWorldEdit().commandDetection(split);
split[0] = "/" + split[0]; split[0] = "/" + split[0];
} }
final String newMessage = StringUtil.joinString(split, " "); final String newMessage = StringUtil.joinString(split, " ");
if (!newMessage.equals(event.getMessage())) { if (!newMessage.equals(event.getMessage())) {
event.setMessage(newMessage); event.setMessage(newMessage);
plugin.getServer().getPluginManager().callEvent(event); plugin.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {
if (event.getMessage().length() > 0) { if (event.getMessage().length() > 0) {
plugin.getServer().dispatchCommand(event.getPlayer(), plugin.getServer().dispatchCommand(event.getPlayer(),
event.getMessage().substring(1)); event.getMessage().substring(1));
} }
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
/** /**
* Called when a player interacts * Called when a player interacts
* *
* @param event Relevant event details * @param event Relevant event details
*/ */
@EventHandler @EventHandler
public void onPlayerInteract(PlayerInteractEvent event) { public void onPlayerInteract(PlayerInteractEvent event) {
if (event.useItemInHand() == Result.DENY) { if (event.useItemInHand() == Result.DENY) {
return; return;
} }
final LocalPlayer player = plugin.wrapPlayer(event.getPlayer()); final LocalPlayer player = plugin.wrapPlayer(event.getPlayer());
final LocalWorld world = player.getWorld(); final LocalWorld world = player.getWorld();
final WorldEdit we = plugin.getWorldEdit(); final WorldEdit we = plugin.getWorldEdit();
Action action = event.getAction(); Action action = event.getAction();
if (action == Action.LEFT_CLICK_BLOCK) { if (action == Action.LEFT_CLICK_BLOCK) {
final Block clickedBlock = event.getClickedBlock(); final Block clickedBlock = event.getClickedBlock();
final WorldVector pos = new WorldVector(world, clickedBlock.getX(), final WorldVector pos = new WorldVector(world, clickedBlock.getX(),
clickedBlock.getY(), clickedBlock.getZ()); clickedBlock.getY(), clickedBlock.getZ());
if (we.handleBlockLeftClick(player, pos)) { if (we.handleBlockLeftClick(player, pos)) {
event.setCancelled(true); event.setCancelled(true);
} }
if (we.handleArmSwing(player)) { if (we.handleArmSwing(player)) {
event.setCancelled(true); event.setCancelled(true);
} }
if (!ignoreLeftClickAir) { if (!ignoreLeftClickAir) {
final int taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { final int taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
ignoreLeftClickAir = false; ignoreLeftClickAir = false;
} }
}, 2); }, 2);
if (taskId != -1) { if (taskId != -1) {
ignoreLeftClickAir = true; ignoreLeftClickAir = true;
} }
} }
} else if (action == Action.LEFT_CLICK_AIR) { } else if (action == Action.LEFT_CLICK_AIR) {
if (ignoreLeftClickAir) { if (ignoreLeftClickAir) {
return; return;
} }
if (we.handleArmSwing(player)) { if (we.handleArmSwing(player)) {
event.setCancelled(true); event.setCancelled(true);
} }
} else if (action == Action.RIGHT_CLICK_BLOCK) { } else if (action == Action.RIGHT_CLICK_BLOCK) {
final Block clickedBlock = event.getClickedBlock(); final Block clickedBlock = event.getClickedBlock();
final WorldVector pos = new WorldVector(world, clickedBlock.getX(), final WorldVector pos = new WorldVector(world, clickedBlock.getX(),
clickedBlock.getY(), clickedBlock.getZ()); clickedBlock.getY(), clickedBlock.getZ());
if (we.handleBlockRightClick(player, pos)) { if (we.handleBlockRightClick(player, pos)) {
event.setCancelled(true); event.setCancelled(true);
} }
if (we.handleRightClick(player)) { if (we.handleRightClick(player)) {
event.setCancelled(true); event.setCancelled(true);
} }
} else if (action == Action.RIGHT_CLICK_AIR) { } else if (action == Action.RIGHT_CLICK_AIR) {
if (we.handleRightClick(player)) { if (we.handleRightClick(player)) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }

View File

@ -1,430 +1,419 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import java.io.File; import com.sk89q.util.yaml.YAMLProcessor;
import java.io.FileNotFoundException; import com.sk89q.wepif.PermissionsResolverManager;
import java.io.FileOutputStream; import com.sk89q.worldedit.*;
import java.io.IOException; import com.sk89q.worldedit.bukkit.selections.CuboidSelection;
import java.io.InputStream; import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection;
import java.util.Enumeration; import com.sk89q.worldedit.bukkit.selections.Selection;
import java.util.jar.JarEntry; import com.sk89q.worldedit.extent.inventory.BlockBag;
import java.util.jar.JarFile; import com.sk89q.worldedit.regions.CuboidRegion;
import java.util.logging.Handler; import com.sk89q.worldedit.regions.Polygonal2DRegion;
import java.util.zip.ZipEntry; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import com.sk89q.util.yaml.YAMLProcessor; import java.io.*;
import com.sk89q.wepif.PermissionsResolverManager; import java.util.Enumeration;
import com.sk89q.worldedit.EditSession; import java.util.jar.JarEntry;
import com.sk89q.worldedit.IncompleteRegionException; import java.util.jar.JarFile;
import com.sk89q.worldedit.LocalPlayer; import java.util.logging.Handler;
import com.sk89q.worldedit.LocalSession; import java.util.zip.ZipEntry;
import com.sk89q.worldedit.ServerInterface;
import com.sk89q.worldedit.WorldEdit; /**
import com.sk89q.worldedit.WorldEditOperation; * Plugin for Bukkit.
import com.sk89q.worldedit.extent.inventory.BlockBag; *
import com.sk89q.worldedit.bukkit.selections.CuboidSelection; * @author sk89q
import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection; */
import com.sk89q.worldedit.bukkit.selections.Selection; public class WorldEditPlugin extends JavaPlugin {
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Polygonal2DRegion; /**
import com.sk89q.worldedit.regions.Region; * The name of the CUI's plugin channel registration
import com.sk89q.worldedit.regions.RegionSelector; */
public static final String CUI_PLUGIN_CHANNEL = "WECUI";
/**
* Plugin for Bukkit. /**
* * The server interface that all server-related API goes through.
* @author sk89q */
*/ private BukkitServerInterface server;
public class WorldEditPlugin extends JavaPlugin { /**
* Main WorldEdit instance.
/** */
* The name of the CUI's plugin channel registration private WorldEdit controller;
*/ /**
public static final String CUI_PLUGIN_CHANNEL = "WECUI"; * Deprecated API.
*/
/** private WorldEditAPI api;
* The server interface that all server-related API goes through.
*/ /**
private BukkitServerInterface server; * Holds the configuration for WorldEdit.
/** */
* Main WorldEdit instance. private BukkitConfiguration config;
*/
private WorldEdit controller; /**
/** * Called on plugin enable.
* Deprecated API. */
*/ @Override
private WorldEditAPI api; public void onEnable() {
final String pluginYmlVersion = getDescription().getVersion();
/** final String manifestVersion = WorldEdit.getVersion();
* Holds the configuration for WorldEdit.
*/ if (!manifestVersion.equalsIgnoreCase(pluginYmlVersion)) {
private BukkitConfiguration config; WorldEdit.setVersion(manifestVersion + " (" + pluginYmlVersion + ")");
}
/**
* Called on plugin enable. // Make the data folders that WorldEdit uses
*/ getDataFolder().mkdirs();
@Override File targetDir = new File(getDataFolder() + File.separator + "nmsblocks");
public void onEnable() { targetDir.mkdir();
final String pluginYmlVersion = getDescription().getVersion(); copyNmsBlockClasses(targetDir);
final String manifestVersion = WorldEdit.getVersion();
// Create the default configuration file
if (!manifestVersion.equalsIgnoreCase(pluginYmlVersion)) { createDefaultConfiguration("config.yml");
WorldEdit.setVersion(manifestVersion + " (" + pluginYmlVersion + ")");
} // Set up configuration and such, including the permissions
// resolver
// Make the data folders that WorldEdit uses config = new BukkitConfiguration(new YAMLProcessor(new File(getDataFolder(), "config.yml"), true), this);
getDataFolder().mkdirs(); PermissionsResolverManager.initialize(this);
File targetDir = new File(getDataFolder() + File.separator + "nmsblocks");
targetDir.mkdir(); // Load the configuration
copyNmsBlockClasses(targetDir); config.load();
// Create the default configuration file // Setup interfaces
createDefaultConfiguration("config.yml"); server = new BukkitServerInterface(this, getServer());
controller = new WorldEdit(server, config);
// Set up configuration and such, including the permissions WorldEdit.logger.setParent(Bukkit.getLogger());
// resolver api = new WorldEditAPI(this);
config = new BukkitConfiguration(new YAMLProcessor(new File(getDataFolder(), "config.yml"), true), this); getServer().getMessenger().registerIncomingPluginChannel(this, CUI_PLUGIN_CHANNEL, new CUIChannelListener(this));
PermissionsResolverManager.initialize(this); getServer().getMessenger().registerOutgoingPluginChannel(this, CUI_PLUGIN_CHANNEL);
// Now we can register events!
// Load the configuration getServer().getPluginManager().registerEvents(new WorldEditListener(this), this);
config.load();
getServer().getScheduler().runTaskTimerAsynchronously(this,
// Setup interfaces new SessionTimer(controller, getServer()), 120, 120);
server = new BukkitServerInterface(this, getServer()); }
controller = new WorldEdit(server, config);
WorldEdit.logger.setParent(Bukkit.getLogger()); private void copyNmsBlockClasses(File target) {
api = new WorldEditAPI(this); try {
getServer().getMessenger().registerIncomingPluginChannel(this, CUI_PLUGIN_CHANNEL, new CUIChannelListener(this)); JarFile jar = new JarFile(getFile());
getServer().getMessenger().registerOutgoingPluginChannel(this, CUI_PLUGIN_CHANNEL); @SuppressWarnings("rawtypes")
// Now we can register events! Enumeration entries = jar.entries();
getServer().getPluginManager().registerEvents(new WorldEditListener(this), this); while (entries.hasMoreElements()) {
JarEntry jarEntry = (JarEntry) entries.nextElement();
getServer().getScheduler().runTaskTimerAsynchronously(this, if (!jarEntry.getName().startsWith("nmsblocks") || jarEntry.isDirectory()) continue;
new SessionTimer(controller, getServer()), 120, 120);
} File file = new File(target + File.separator + jarEntry.getName().replace("nmsblocks", ""));
if (file.exists()) continue;
private void copyNmsBlockClasses(File target) {
try { InputStream is = jar.getInputStream(jarEntry);
JarFile jar = new JarFile(getFile()); FileOutputStream fos = new FileOutputStream(file);
@SuppressWarnings("rawtypes")
Enumeration entries = jar.entries(); fos = new FileOutputStream(file);
while (entries.hasMoreElements()) { byte[] buf = new byte[8192];
JarEntry jarEntry = (JarEntry) entries.nextElement(); int length = 0;
if (!jarEntry.getName().startsWith("nmsblocks") || jarEntry.isDirectory()) continue; while ((length = is.read(buf)) > 0) {
fos.write(buf, 0, length);
File file = new File(target + File.separator + jarEntry.getName().replace("nmsblocks", "")); }
if (file.exists()) continue; fos.close();
is.close();
InputStream is = jar.getInputStream(jarEntry); }
FileOutputStream fos = new FileOutputStream(file); } catch (Throwable e) {}
}
fos = new FileOutputStream(file);
byte[] buf = new byte[8192]; /**
int length = 0; * Called on plugin disable.
while ((length = is.read(buf)) > 0) { */
fos.write(buf, 0, length); @Override
} public void onDisable() {
fos.close(); controller.clearSessions();
is.close(); for (Handler h : controller.commandLogger.getHandlers()) {
} h.close();
} catch (Throwable e) {} }
} config.unload();
server.unregisterCommands();
/** this.getServer().getScheduler().cancelTasks(this);
* Called on plugin disable. }
*/
@Override /**
public void onDisable() { * Loads and reloads all configuration.
controller.clearSessions(); */
for (Handler h : controller.commandLogger.getHandlers()) { protected void loadConfiguration() {
h.close(); config.unload();
} config.load();
config.unload(); getPermissionsResolver().load();
server.unregisterCommands(); }
this.getServer().getScheduler().cancelTasks(this);
} /**
* Create a default configuration file from the .jar.
/** *
* Loads and reloads all configuration. * @param name
*/ */
protected void loadConfiguration() { protected void createDefaultConfiguration(String name) {
config.unload(); File actual = new File(getDataFolder(), name);
config.load(); if (!actual.exists()) {
getPermissionsResolver().load(); InputStream input =
} null;
try {
/** JarFile file = new JarFile(getFile());
* Create a default configuration file from the .jar. ZipEntry copy = file.getEntry("defaults/" + name);
* if (copy == null) throw new FileNotFoundException();
* @param name input = file.getInputStream(copy);
*/ } catch (IOException e) {
protected void createDefaultConfiguration(String name) { getLogger().severe("Unable to read default configuration: " + name);
File actual = new File(getDataFolder(), name); }
if (!actual.exists()) { if (input != null) {
InputStream input = FileOutputStream output = null;
null;
try { try {
JarFile file = new JarFile(getFile()); output = new FileOutputStream(actual);
ZipEntry copy = file.getEntry("defaults/" + name); byte[] buf = new byte[8192];
if (copy == null) throw new FileNotFoundException(); int length = 0;
input = file.getInputStream(copy); while ((length = input.read(buf)) > 0) {
} catch (IOException e) { output.write(buf, 0, length);
getLogger().severe("Unable to read default configuration: " + name); }
}
if (input != null) { getLogger().info("Default configuration file written: " + name);
FileOutputStream output = null; } catch (IOException e) {
e.printStackTrace();
try { } finally {
output = new FileOutputStream(actual); try {
byte[] buf = new byte[8192]; if (input != null) {
int length = 0; input.close();
while ((length = input.read(buf)) > 0) { }
output.write(buf, 0, length); } catch (IOException e) {}
}
try {
getLogger().info("Default configuration file written: " + name); if (output != null) {
} catch (IOException e) { output.close();
e.printStackTrace(); }
} finally { } catch (IOException e) {}
try { }
if (input != null) { }
input.close(); }
} }
} catch (IOException e) {}
/**
try { * Called on WorldEdit command.
if (output != null) { */
output.close(); @Override
} public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd,
} catch (IOException e) {} 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();
* Called on WorldEdit command.
*/ controller.handleCommand(wrapCommandSender(sender), split);
@Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, return true;
String commandLabel, String[] args) { }
// Add the command to the array because the underlying command handling /**
// code of WorldEdit expects it * Gets the session for the player.
String[] split = new String[args.length + 1]; *
System.arraycopy(args, 0, split, 1, args.length); * @param player
split[0] = "/" + cmd.getName(); * @return
*/
controller.handleCommand(wrapCommandSender(sender), split); public LocalSession getSession(Player player) {
return controller.getSession(wrapPlayer(player));
return true; }
}
/**
/** * Gets the session for the player.
* Gets the session for the player. *
* * @param player
* @param player * @return
* @return */
*/ public EditSession createEditSession(Player player) {
public LocalSession getSession(Player player) { LocalPlayer wePlayer = wrapPlayer(player);
return controller.getSession(wrapPlayer(player)); LocalSession session = controller.getSession(wePlayer);
} BlockBag blockBag = session.getBlockBag(wePlayer);
/** EditSession editSession = controller.getEditSessionFactory()
* Gets the session for the player. .getEditSession(wePlayer.getWorld(), session.getBlockChangeLimit(), blockBag, wePlayer);
* editSession.enableQueue();
* @param player
* @return return editSession;
*/ }
public EditSession createEditSession(Player player) {
LocalPlayer wePlayer = wrapPlayer(player); /**
LocalSession session = controller.getSession(wePlayer); * Remember an edit session.
BlockBag blockBag = session.getBlockBag(wePlayer); *
* @param player
EditSession editSession = controller.getEditSessionFactory() * @param editSession
.getEditSession(wePlayer.getWorld(), session.getBlockChangeLimit(), blockBag, wePlayer); */
editSession.enableQueue(); public void remember(Player player, EditSession editSession) {
LocalPlayer wePlayer = wrapPlayer(player);
return editSession; LocalSession session = controller.getSession(wePlayer);
}
session.remember(editSession);
/** editSession.flushQueue();
* Remember an edit session.
* controller.flushBlockBag(wePlayer, editSession);
* @param player }
* @param editSession
*/ /**
public void remember(Player player, EditSession editSession) { * Wrap an operation into an EditSession.
LocalPlayer wePlayer = wrapPlayer(player); *
LocalSession session = controller.getSession(wePlayer); * @param player
* @param op
session.remember(editSession); * @throws Throwable
editSession.flushQueue(); */
public void perform(Player player, WorldEditOperation op)
controller.flushBlockBag(wePlayer, editSession); throws Throwable {
} LocalPlayer wePlayer = wrapPlayer(player);
LocalSession session = controller.getSession(wePlayer);
/**
* Wrap an operation into an EditSession. EditSession editSession = createEditSession(player);
* try {
* @param player op.run(session, wePlayer, editSession);
* @param op } finally {
* @throws Throwable remember(player, editSession);
*/ }
public void perform(Player player, WorldEditOperation op) }
throws Throwable {
LocalPlayer wePlayer = wrapPlayer(player); /**
LocalSession session = controller.getSession(wePlayer); * Get the API.
*
EditSession editSession = createEditSession(player); * @return
try { */
op.run(session, wePlayer, editSession); @Deprecated
} finally { public WorldEditAPI getAPI() {
remember(player, editSession); return api;
} }
}
/**
/** * Returns the configuration used by WorldEdit.
* Get the API. *
* * @return
* @return */
*/ public BukkitConfiguration getLocalConfiguration() {
@Deprecated return config;
public WorldEditAPI getAPI() { }
return api;
} /**
* Get the permissions resolver in use.
/** *
* Returns the configuration used by WorldEdit. * @return
* */
* @return public PermissionsResolverManager getPermissionsResolver() {
*/ return PermissionsResolverManager.getInstance();
public BukkitConfiguration getLocalConfiguration() { }
return config;
} /**
* Used to wrap a Bukkit Player as a LocalPlayer.
/** *
* Get the permissions resolver in use. * @param player
* * @return
* @return */
*/ public BukkitPlayer wrapPlayer(Player player) {
public PermissionsResolverManager getPermissionsResolver() { return new BukkitPlayer(this, this.server, player);
return PermissionsResolverManager.getInstance(); }
}
public LocalPlayer wrapCommandSender(CommandSender sender) {
/** if (sender instanceof Player) {
* Used to wrap a Bukkit Player as a LocalPlayer. return wrapPlayer((Player) sender);
* }
* @param player
* @return return new BukkitCommandSender(this, this.server, sender);
*/ }
public BukkitPlayer wrapPlayer(Player player) {
return new BukkitPlayer(this, this.server, player); /**
} * Get the server interface.
*
public LocalPlayer wrapCommandSender(CommandSender sender) { * @return
if (sender instanceof Player) { */
return wrapPlayer((Player) sender); public ServerInterface getServerInterface() {
} return server;
}
return new BukkitCommandSender(this, this.server, sender);
} /**
* Get WorldEdit.
/** *
* Get the server interface. * @return
* */
* @return public WorldEdit getWorldEdit() {
*/ return controller;
public ServerInterface getServerInterface() { }
return server;
} /**
* Gets the region selection for the player.
/** *
* Get WorldEdit. * @param player
* * @return the selection or null if there was none
* @return */
*/ public Selection getSelection(Player player) {
public WorldEdit getWorldEdit() { if (player == null) {
return controller; throw new IllegalArgumentException("Null player not allowed");
} }
if (!player.isOnline()) {
/** throw new IllegalArgumentException("Offline player not allowed");
* Gets the region selection for the player. }
*
* @param player LocalSession session = controller.getSession(wrapPlayer(player));
* @return the selection or null if there was none RegionSelector selector = session.getRegionSelector(BukkitUtil.getLocalWorld(player.getWorld()));
*/
public Selection getSelection(Player player) { try {
if (player == null) { Region region = selector.getRegion();
throw new IllegalArgumentException("Null player not allowed"); World world = ((BukkitWorld) session.getSelectionWorld()).getWorld();
}
if (!player.isOnline()) { if (region instanceof CuboidRegion) {
throw new IllegalArgumentException("Offline player not allowed"); return new CuboidSelection(world, selector, (CuboidRegion) region);
} } else if (region instanceof Polygonal2DRegion) {
return new Polygonal2DSelection(world, selector, (Polygonal2DRegion) region);
LocalSession session = controller.getSession(wrapPlayer(player)); } else {
RegionSelector selector = session.getRegionSelector(BukkitUtil.getLocalWorld(player.getWorld())); return null;
}
try { } catch (IncompleteRegionException e) {
Region region = selector.getRegion(); return null;
World world = ((BukkitWorld) session.getSelectionWorld()).getWorld(); }
}
if (region instanceof CuboidRegion) {
return new CuboidSelection(world, selector, (CuboidRegion) region); /**
} else if (region instanceof Polygonal2DRegion) { * Sets the region selection for a player.
return new Polygonal2DSelection(world, selector, (Polygonal2DRegion) region); *
} else { * @param player
return null; * @param selection
} */
} catch (IncompleteRegionException e) { public void setSelection(Player player, Selection selection) {
return null; if (player == null) {
} throw new IllegalArgumentException("Null player not allowed");
} }
if (!player.isOnline()) {
/** throw new IllegalArgumentException("Offline player not allowed");
* Sets the region selection for a player. }
* if (selection == null) {
* @param player throw new IllegalArgumentException("Null selection not allowed");
* @param selection }
*/
public void setSelection(Player player, Selection selection) { LocalSession session = controller.getSession(wrapPlayer(player));
if (player == null) { RegionSelector sel = selection.getRegionSelector();
throw new IllegalArgumentException("Null player not allowed"); session.setRegionSelector(BukkitUtil.getLocalWorld(player.getWorld()), sel);
} session.dispatchCUISelection(wrapPlayer(player));
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));
}
}

View File

@ -1,67 +1,67 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit.selections; package com.sk89q.worldedit.bukkit.selections;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitUtil; import com.sk89q.worldedit.bukkit.BukkitUtil;
import com.sk89q.worldedit.regions.*; import com.sk89q.worldedit.regions.*;
public class CuboidSelection extends RegionSelection { public class CuboidSelection extends RegionSelection {
protected CuboidRegion cuboid; protected CuboidRegion cuboid;
public CuboidSelection(World world, Location pt1, Location pt2) { public CuboidSelection(World world, Location pt1, Location pt2) {
this(world, BukkitUtil.toVector(pt1), BukkitUtil.toVector(pt2)); this(world, BukkitUtil.toVector(pt1), BukkitUtil.toVector(pt2));
} }
public CuboidSelection(World world, Vector pt1, Vector pt2) { public CuboidSelection(World world, Vector pt1, Vector pt2) {
super(world); super(world);
// Validate input // Validate input
if (pt1 == null) { if (pt1 == null) {
throw new IllegalArgumentException("Null point 1 not permitted"); throw new IllegalArgumentException("Null point 1 not permitted");
} }
if (pt2 == null) { if (pt2 == null) {
throw new IllegalArgumentException("Null point 2 not permitted"); throw new IllegalArgumentException("Null point 2 not permitted");
} }
// Create new selector // Create new selector
CuboidRegionSelector sel = new CuboidRegionSelector(BukkitUtil.getLocalWorld(world)); CuboidRegionSelector sel = new CuboidRegionSelector(BukkitUtil.getLocalWorld(world));
// set up selector // set up selector
sel.selectPrimary(pt1); sel.selectPrimary(pt1);
sel.selectSecondary(pt2); sel.selectSecondary(pt2);
// set up CuboidSelection // set up CuboidSelection
cuboid = sel.getIncompleteRegion(); cuboid = sel.getIncompleteRegion();
// set up RegionSelection // set up RegionSelection
setRegionSelector(sel); setRegionSelector(sel);
setRegion(cuboid); setRegion(cuboid);
} }
public CuboidSelection(World world, RegionSelector sel, CuboidRegion region) { public CuboidSelection(World world, RegionSelector sel, CuboidRegion region) {
super(world, sel, region); super(world, sel, region);
this.cuboid = region; this.cuboid = region;
} }
} }

View File

@ -1,62 +1,62 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit.selections; package com.sk89q.worldedit.bukkit.selections;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import com.sk89q.worldedit.LocalWorld; import com.sk89q.worldedit.LocalWorld;
import org.bukkit.World; import org.bukkit.World;
import com.sk89q.worldedit.BlockVector2D; import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.bukkit.BukkitUtil; import com.sk89q.worldedit.bukkit.BukkitUtil;
import com.sk89q.worldedit.regions.*; import com.sk89q.worldedit.regions.*;
public class Polygonal2DSelection extends RegionSelection { public class Polygonal2DSelection extends RegionSelection {
protected Polygonal2DRegion poly2d; protected Polygonal2DRegion poly2d;
public Polygonal2DSelection(World world, RegionSelector sel, Polygonal2DRegion region) { public Polygonal2DSelection(World world, RegionSelector sel, Polygonal2DRegion region) {
super(world, sel, region); super(world, sel, region);
this.poly2d = region; this.poly2d = region;
} }
public Polygonal2DSelection(World world, List<BlockVector2D> points, int minY, int maxY) { public Polygonal2DSelection(World world, List<BlockVector2D> points, int minY, int maxY) {
super(world); super(world);
LocalWorld lWorld = BukkitUtil.getLocalWorld(world); LocalWorld lWorld = BukkitUtil.getLocalWorld(world);
// Validate input // Validate input
minY = Math.min(Math.max(0, minY), world.getMaxHeight()); minY = Math.min(Math.max(0, minY), world.getMaxHeight());
maxY = Math.min(Math.max(0, maxY), world.getMaxHeight()); maxY = Math.min(Math.max(0, maxY), world.getMaxHeight());
// Create and set up new selector // Create and set up new selector
Polygonal2DRegionSelector sel = new Polygonal2DRegionSelector(lWorld, points, minY, maxY); Polygonal2DRegionSelector sel = new Polygonal2DRegionSelector(lWorld, points, minY, maxY);
// set up CuboidSelection // set up CuboidSelection
poly2d = sel.getIncompleteRegion(); poly2d = sel.getIncompleteRegion();
// set up RegionSelection // set up RegionSelection
setRegionSelector(sel); setRegionSelector(sel);
setRegion(poly2d); setRegion(poly2d);
} }
public List<BlockVector2D> getNativePoints() { public List<BlockVector2D> getNativePoints() {
return Collections.unmodifiableList(poly2d.getPoints()); return Collections.unmodifiableList(poly2d.getPoints());
} }
} }

View File

@ -1,106 +1,106 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit.selections; package com.sk89q.worldedit.bukkit.selections;
import static com.sk89q.worldedit.bukkit.BukkitUtil.toLocation; import static com.sk89q.worldedit.bukkit.BukkitUtil.toLocation;
import static com.sk89q.worldedit.bukkit.BukkitUtil.toVector; import static com.sk89q.worldedit.bukkit.BukkitUtil.toVector;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.regions.RegionSelector;
public abstract class RegionSelection implements Selection { public abstract class RegionSelection implements Selection {
private World world; private World world;
private RegionSelector selector; private RegionSelector selector;
private Region region; private Region region;
public RegionSelection(World world) { public RegionSelection(World world) {
this.world = world; this.world = world;
} }
public RegionSelection(World world, RegionSelector selector, Region region) { public RegionSelection(World world, RegionSelector selector, Region region) {
this.world = world; this.world = world;
this.region = region; this.region = region;
this.selector = selector; this.selector = selector;
} }
protected Region getRegion() { protected Region getRegion() {
return region; return region;
} }
protected void setRegion(Region region) { protected void setRegion(Region region) {
this.region = region; this.region = region;
} }
public RegionSelector getRegionSelector() { public RegionSelector getRegionSelector() {
return selector; return selector;
} }
protected void setRegionSelector(RegionSelector selector) { protected void setRegionSelector(RegionSelector selector) {
this.selector = selector; this.selector = selector;
} }
public Location getMinimumPoint() { public Location getMinimumPoint() {
return toLocation(world, region.getMinimumPoint()); return toLocation(world, region.getMinimumPoint());
} }
public Vector getNativeMinimumPoint() { public Vector getNativeMinimumPoint() {
return region.getMinimumPoint(); return region.getMinimumPoint();
} }
public Location getMaximumPoint() { public Location getMaximumPoint() {
return toLocation(world, region.getMaximumPoint()); return toLocation(world, region.getMaximumPoint());
} }
public Vector getNativeMaximumPoint() { public Vector getNativeMaximumPoint() {
return region.getMaximumPoint(); return region.getMaximumPoint();
} }
public World getWorld() { public World getWorld() {
return world; return world;
} }
public int getArea() { public int getArea() {
return region.getArea(); return region.getArea();
} }
public int getWidth() { public int getWidth() {
return region.getWidth(); return region.getWidth();
} }
public int getHeight() { public int getHeight() {
return region.getHeight(); return region.getHeight();
} }
public int getLength() { public int getLength() {
return region.getLength(); return region.getLength();
} }
public boolean contains(Location pt) { public boolean contains(Location pt) {
if (!pt.getWorld().equals(world)) { if (!pt.getWorld().equals(world)) {
return false; return false;
} }
return region.contains(toVector(pt)); return region.contains(toVector(pt));
} }
} }

View File

@ -1,105 +1,105 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit.selections; package com.sk89q.worldedit.bukkit.selections;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.regions.RegionSelector;
public interface Selection { public interface Selection {
/** /**
* Get the lower point of a region. * Get the lower point of a region.
* *
* @return min. point * @return min. point
*/ */
public Location getMinimumPoint(); public Location getMinimumPoint();
/** /**
* Get the lower point of a region. * Get the lower point of a region.
* *
* @return min. point * @return min. point
*/ */
public Vector getNativeMinimumPoint(); public Vector getNativeMinimumPoint();
/** /**
* Get the upper point of a region. * Get the upper point of a region.
* *
* @return max. point * @return max. point
*/ */
public Location getMaximumPoint(); public Location getMaximumPoint();
/** /**
* Get the upper point of a region. * Get the upper point of a region.
* *
* @return max. point * @return max. point
*/ */
public Vector getNativeMaximumPoint(); public Vector getNativeMaximumPoint();
/** /**
* Get the region selector. This is for internal use. * Get the region selector. This is for internal use.
* *
* @return * @return
*/ */
public RegionSelector getRegionSelector(); public RegionSelector getRegionSelector();
/** /**
* Get the world. * Get the world.
* *
* @return * @return
*/ */
public World getWorld(); public World getWorld();
/** /**
* Get the number of blocks in the region. * Get the number of blocks in the region.
* *
* @return number of blocks * @return number of blocks
*/ */
public int getArea(); public int getArea();
/** /**
* Get X-size. * Get X-size.
* *
* @return width * @return width
*/ */
public int getWidth(); public int getWidth();
/** /**
* Get Y-size. * Get Y-size.
* *
* @return height * @return height
*/ */
public int getHeight(); public int getHeight();
/** /**
* Get Z-size. * Get Z-size.
* *
* @return length * @return length
*/ */
public int getLength(); public int getLength();
/** /**
* Returns true based on whether the region contains the point, * Returns true based on whether the region contains the point,
* *
* @param pt * @param pt
* @return * @return
*/ */
public boolean contains(Location pt); public boolean contains(Location pt);
} }

View File

@ -1,72 +1,72 @@
# #
# WorldEdit's configuration file # WorldEdit's configuration file
# #
# About editing this file: # About editing this file:
# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If # - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If
# you use an editor like Notepad++ (recommended for Windows users), you # you use an editor like Notepad++ (recommended for Windows users), you
# must configure it to "replace tabs with spaces." In Notepad++, this can # must configure it to "replace tabs with spaces." In Notepad++, this can
# be changed in Settings > Preferences > Language Menu. # be changed in Settings > Preferences > Language Menu.
# - Don't get rid of the indents. They are indented so some entries are # - Don't get rid of the indents. They are indented so some entries are
# in categories (like "max-blocks-changed" is in the "limits" # in categories (like "max-blocks-changed" is in the "limits"
# category. # category.
# - If you want to check the format of this file before putting it # - If you want to check the format of this file before putting it
# into WorldEdit, paste it into http://yaml-online-parser.appspot.com/ # into WorldEdit, paste it into http://yaml-online-parser.appspot.com/
# and see if it gives "ERROR:". # and see if it gives "ERROR:".
# - Lines starting with # are commentsand so they are ignored. # - Lines starting with # are commentsand so they are ignored.
# #
limits: limits:
allow-extra-data-values: false allow-extra-data-values: false
max-blocks-changed: max-blocks-changed:
default: -1 default: -1
maximum: -1 maximum: -1
max-polygonal-points: max-polygonal-points:
default: -1 default: -1
maximum: 20 maximum: 20
max-radius: -1 max-radius: -1
max-super-pickaxe-size: 5 max-super-pickaxe-size: 5
max-brush-radius: 5 max-brush-radius: 5
butcher-radius: butcher-radius:
default: -1 default: -1
maximum: -1 maximum: -1
disallowed-blocks: [6, 7, 14, 15, 16, 26, 27, 28, 29, 39, 31, 32, 33, 34, 36, 37, 38, 39, 40, 46, 50, 51, 56, 59, 69, 73, 74, 75, 76, 77, 81, 83] disallowed-blocks: [6, 7, 14, 15, 16, 26, 27, 28, 29, 39, 31, 32, 33, 34, 36, 37, 38, 39, 40, 46, 50, 51, 56, 59, 69, 73, 74, 75, 76, 77, 81, 83]
use-inventory: use-inventory:
enable: false enable: false
allow-override: true allow-override: true
creative-mode-overrides: false creative-mode-overrides: false
logging: logging:
log-commands: false log-commands: false
file: worldedit.log file: worldedit.log
super-pickaxe: super-pickaxe:
drop-items: true drop-items: true
many-drop-items: false many-drop-items: false
snapshots: snapshots:
directory: directory:
navigation-wand: navigation-wand:
item: 345 item: 345
max-distance: 100 max-distance: 100
scripting: scripting:
timeout: 3000 timeout: 3000
dir: craftscripts dir: craftscripts
saving: saving:
dir: schematics dir: schematics
files: files:
allow-symbolic-links: false allow-symbolic-links: false
history: history:
size: 15 size: 15
expiration: 10 expiration: 10
wand-item: 271 wand-item: 271
shell-save-type: shell-save-type:
no-double-slash: false no-double-slash: false
no-op-permissions: false no-op-permissions: false
debug: false debug: false

View File

@ -1,16 +1,16 @@
package com.sk89q.worldedit.masks; package com.sk89q.worldedit.masks;
import com.sk89q.worldedit.LocalPlayer; import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
/** /**
* @deprecated Switch to {@link com.sk89q.worldedit.function.mask.AbstractMask} * @deprecated Switch to {@link com.sk89q.worldedit.function.mask.AbstractMask}
*/ */
@Deprecated @Deprecated
public abstract class AbstractMask implements Mask { public abstract class AbstractMask implements Mask {
@Override @Override
public void prepare(LocalSession session, LocalPlayer player, Vector target) { public void prepare(LocalSession session, LocalPlayer player, Vector target) {
} }
} }

View File

@ -1,52 +1,52 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.masks; package com.sk89q.worldedit.masks;
import java.util.Set; import java.util.Set;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
/** /**
* A filter that matches blocks based on block types. * A filter that matches blocks based on block types.
* *
* @deprecated replaced by {@link #BlockMask} * @deprecated replaced by {@link #BlockMask}
* @author sk89q * @author sk89q
*/ */
@Deprecated @Deprecated
public class BlockTypeMask extends BlockMask { public class BlockTypeMask extends BlockMask {
public BlockTypeMask() { public BlockTypeMask() {
super(); super();
} }
public BlockTypeMask(Set<Integer> types) { public BlockTypeMask(Set<Integer> types) {
super(); super();
for (int type : types) { for (int type : types) {
add(type); add(type);
} }
} }
public BlockTypeMask(int type) { public BlockTypeMask(int type) {
this(); this();
add(type); add(type);
} }
public void add(int type) { public void add(int type) {
add(new BaseBlock(type)); add(new BaseBlock(type));
} }
} }

View File

@ -1,84 +1,84 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.masks; package com.sk89q.worldedit.masks;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalPlayer; import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.function.mask.MaskIntersection; import com.sk89q.worldedit.function.mask.MaskIntersection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* @deprecated See {@link MaskIntersection} * @deprecated See {@link MaskIntersection}
*/ */
@Deprecated @Deprecated
public class CombinedMask extends AbstractMask { public class CombinedMask extends AbstractMask {
private final List<Mask> masks = new ArrayList<Mask>(); private final List<Mask> masks = new ArrayList<Mask>();
public CombinedMask() { public CombinedMask() {
} }
public CombinedMask(Mask mask) { public CombinedMask(Mask mask) {
add(mask); add(mask);
} }
public CombinedMask(Mask ...mask) { public CombinedMask(Mask ...mask) {
for (Mask m : mask) { for (Mask m : mask) {
add(m); add(m);
} }
} }
public CombinedMask(List<Mask> masks) { public CombinedMask(List<Mask> masks) {
this.masks.addAll(masks); this.masks.addAll(masks);
} }
public void add(Mask mask) { public void add(Mask mask) {
masks.add(mask); masks.add(mask);
} }
public boolean remove(Mask mask) { public boolean remove(Mask mask) {
return masks.remove(mask); return masks.remove(mask);
} }
public boolean has(Mask mask) { public boolean has(Mask mask) {
return masks.contains(mask); return masks.contains(mask);
} }
@Override @Override
public void prepare(LocalSession session, LocalPlayer player, Vector target) { public void prepare(LocalSession session, LocalPlayer player, Vector target) {
for (Mask mask : masks) { for (Mask mask : masks) {
mask.prepare(session, player, target); mask.prepare(session, player, target);
} }
} }
@Override @Override
public boolean matches(EditSession editSession, Vector pos) { public boolean matches(EditSession editSession, Vector pos) {
for (Mask mask : masks) { for (Mask mask : masks) {
if (!mask.matches(editSession, pos)) { if (!mask.matches(editSession, pos)) {
return false; return false;
} }
} }
return true; return true;
} }
} }

View File

@ -1,35 +1,35 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.masks; package com.sk89q.worldedit.masks;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
/** /**
* @deprecated See {@link com.sk89q.worldedit.function.mask.ExistingBlockMask} * @deprecated See {@link com.sk89q.worldedit.function.mask.ExistingBlockMask}
*/ */
@Deprecated @Deprecated
public class ExistingBlockMask extends AbstractMask { public class ExistingBlockMask extends AbstractMask {
@Override @Override
public boolean matches(EditSession editSession, Vector pos) { public boolean matches(EditSession editSession, Vector pos) {
return editSession.getBlockType(pos) != BlockID.AIR; return editSession.getBlockType(pos) != BlockID.AIR;
} }
} }

View File

@ -1,54 +1,54 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.masks; package com.sk89q.worldedit.masks;
import java.util.Set; import java.util.Set;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
/** /**
* A block type mask that only matches blocks that are not in the list. * A block type mask that only matches blocks that are not in the list.
* *
* @author sk89q * @author sk89q
*/ */
@Deprecated @Deprecated
public class InvertedBlockTypeMask extends BlockTypeMask { public class InvertedBlockTypeMask extends BlockTypeMask {
public InvertedBlockTypeMask() { public InvertedBlockTypeMask() {
} }
/** /**
* @param types * @param types
*/ */
public InvertedBlockTypeMask(Set<Integer> types) { public InvertedBlockTypeMask(Set<Integer> types) {
super(types); super(types);
} }
/** /**
* @param type * @param type
*/ */
public InvertedBlockTypeMask(int type) { public InvertedBlockTypeMask(int type) {
super(type); super(type);
} }
@Override @Override
public boolean matches(EditSession editSession, Vector pos) { public boolean matches(EditSession editSession, Vector pos) {
return !super.matches(editSession, pos); return !super.matches(editSession, pos);
} }
} }

View File

@ -1,53 +1,53 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.masks; package com.sk89q.worldedit.masks;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalPlayer; import com.sk89q.worldedit.LocalPlayer;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
/** /**
* @deprecated Use {@link com.sk89q.worldedit.function.mask.Mask} * @deprecated Use {@link com.sk89q.worldedit.function.mask.Mask}
*/ */
@Deprecated @Deprecated
public interface Mask { public interface Mask {
/** /**
* Called one time before each edit session. * Called one time before each edit session.
* *
* @param session * @param session
* @param player * @param player
* @param target target of the brush, null if not a brush mask * @param target target of the brush, null if not a brush mask
*/ */
void prepare(LocalSession session, LocalPlayer player, Vector target); void prepare(LocalSession session, LocalPlayer player, Vector target);
/** /**
* Given a block position, this method returns true if the block at * Given a block position, this method returns true if the block at
* that position matches the filter. Block information is not provided * that position matches the filter. Block information is not provided
* as getting a BaseBlock has unneeded overhead in most block querying * as getting a BaseBlock has unneeded overhead in most block querying
* situations (enumerating a chest's contents is a waste, for example). * situations (enumerating a chest's contents is a waste, for example).
* *
* @param editSession * @param editSession
* @param pos * @param pos
* @return * @return
*/ */
boolean matches(EditSession editSession, Vector pos); boolean matches(EditSession editSession, Vector pos);
} }

View File

@ -1,41 +1,41 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.masks; package com.sk89q.worldedit.masks;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
/** /**
* @deprecated See {@link com.sk89q.worldedit.function.mask.RegionMask} * @deprecated See {@link com.sk89q.worldedit.function.mask.RegionMask}
*/ */
@Deprecated @Deprecated
public class RegionMask extends AbstractMask { public class RegionMask extends AbstractMask {
private final Region region; private final Region region;
public RegionMask(Region region) { public RegionMask(Region region) {
this.region = region.clone(); this.region = region.clone();
} }
@Override @Override
public boolean matches(EditSession editSession, Vector pos) { public boolean matches(EditSession editSession, Vector pos) {
return region.contains(pos); return region.contains(pos);
} }
} }

View File

@ -1,16 +1,16 @@
package com.sk89q.worldedit.masks; package com.sk89q.worldedit.masks;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockType; import com.sk89q.worldedit.blocks.BlockType;
/** /**
* @deprecated See {@link com.sk89q.worldedit.function.mask.SolidBlockMask} * @deprecated See {@link com.sk89q.worldedit.function.mask.SolidBlockMask}
*/ */
@Deprecated @Deprecated
public class SolidBlockMask extends AbstractMask { public class SolidBlockMask extends AbstractMask {
@Override @Override
public boolean matches(EditSession editSession, Vector pos) { public boolean matches(EditSession editSession, Vector pos) {
return !BlockType.canPassThrough(editSession.getBlockType(pos), editSession.getBlockData(pos)); return !BlockType.canPassThrough(editSession.getBlockType(pos), editSession.getBlockData(pos));
} }
} }

View File

@ -1,75 +1,75 @@
// $Id$ // $Id$
/* /*
* WorldEdit * WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors * Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.patterns; package com.sk89q.worldedit.patterns;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
/** /**
* Pattern that repeats the clipboard. * Pattern that repeats the clipboard.
* *
* @author sk89q * @author sk89q
*/ */
public class ClipboardPattern implements Pattern { public class ClipboardPattern implements Pattern {
/** /**
* Clipboard. * Clipboard.
*/ */
private CuboidClipboard clipboard; private CuboidClipboard clipboard;
/** /**
* Size of the clipboard. * Size of the clipboard.
*/ */
private Vector size; private Vector size;
/** /**
* Construct the object. * Construct the object.
* *
* @param clipboard * @param clipboard
*/ */
public ClipboardPattern(CuboidClipboard clipboard) { public ClipboardPattern(CuboidClipboard clipboard) {
this.clipboard = clipboard; this.clipboard = clipboard;
this.size = clipboard.getSize(); this.size = clipboard.getSize();
} }
/** /**
* Get next block. * Get next block.
* *
* @param pos * @param pos
* @return * @return
*/ */
public BaseBlock next(Vector pos) { public BaseBlock next(Vector pos) {
return next(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); return next(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ());
} }
/** /**
* Get next block. * Get next block.
* *
* @param x * @param x
* @param y * @param y
* @param z * @param z
* @return * @return
*/ */
public BaseBlock next(int x, int y, int z) { public BaseBlock next(int x, int y, int z) {
int xp = Math.abs(x) % size.getBlockX(); int xp = Math.abs(x) % size.getBlockX();
int yp = Math.abs(y) % size.getBlockY(); int yp = Math.abs(y) % size.getBlockY();
int zp = Math.abs(z) % size.getBlockZ(); int zp = Math.abs(z) % size.getBlockZ();
return clipboard.getPoint(new Vector(xp, yp, zp)); return clipboard.getPoint(new Vector(xp, yp, zp));
} }
} }