Compare commits

..
16 Commits
Author SHA1 Message Date
NotAlexNoyle c67e16fbbf Update canonical Gitea link 2026-10-27 22:27:58 -04:00
NotAlexNoyle 5be4051a71 Exclude CODEOWNERS from language statistics 2026-10-27 08:25:16 -04:00
NotAlexNoyle 2249a4d393 Add CODEOWNERS (one staff approval) 2026-10-27 08:25:16 -04:00
NotAlexNoyle 1077a204cf Update regions.yml 2026-09-14 01:49:53 -04:00
NotAlexNoyle 7477ce5db5 Fix warzone creepers 2026-09-14 00:53:45 -04:00
NotAlexNoyle e8c1ea6459 Remove WGamemode-OG flag 2026-08-19 07:42:59 -04:00
NotAlexNoyle bdc08756cc Fix shop flags 2026-07-29 10:38:26 -04:00
NotAlexNoyle 66b4ffbb92 Update flags for QuickShop-OG 2026-07-22 08:33:21 -04:00
NotAlexNoyle 03dcdf5e82 Update worldguard flags 2026-07-16 19:48:39 -04:00
NotAlexNoyle b8a3272994 Fix /rg bypass 2026-06-17 05:37:07 -04:00
NotAlexNoyle 38c1d84f9e Fix hunger 2026-06-15 10:08:44 -04:00
NotAlexNoyle 9ee9d70730 Update configs 2026-06-07 09:19:49 -04:00
NotAlexNoyle cf8bca82ab FireFight-OG compatibility 2026-05-31 09:45:45 -04:00
NotAlexNoyle 46ae6c9c5e Use live TrueOG Network config files 2026-04-01 06:41:33 -04:00
NotAlexNoyle c7f1ae25d2 Update gradle to 8.14.3 2025-09-25 03:39:32 -04:00
NotAlexNoyle 58690eede0 Rebase 2025-01-01 23:50:04 -05:00
127 changed files with 3262 additions and 2722 deletions

No files matched your search

+2 -33
View File
@@ -1,34 +1,3 @@
* text=auto eol=lf
# Force Batch files to CRLF
*.bat eol=crlf -text
*.java diff=java
# Java sources
*.java text diff=java
*.kt text diff=java
*.gradle text diff=java
*.gradle.kts text diff=java
# These files are text and should be normalized (Convert crlf => lf)
*.css text diff=css
*.df text
*.htm text diff=html
*.html text diff=html
*.js text
*.jsp text
*.jspf text
*.jspx text
*.properties text
*.tld text
*.tag text
*.tagx text
*.xml text
# These files are binary and should be left untouched
# (binary is a macro for -text -diff)
*.class binary
*.dll binary
*.ear binary
*.jar binary
*.so binary
*.war binary
*.jks binary
.gitea/CODEOWNERS linguist-detectable=false
+3
View File
@@ -0,0 +1,3 @@
# Pull requests request review from the eligible staff team(s).
# One approval from either an Admin or Developer satisfies branch protection.
* @trueog/Admins @trueog/Developers
+8
View File
@@ -0,0 +1,8 @@
language: java
dist: trusty
jdk:
- oraclejdk11
notifications:
email: false
before_install: chmod +x gradlew
script: ./gradlew build -S
-25
View File
@@ -1,30 +1,5 @@
# Changelog
## 7.0.12
* Fix a change in the default behavior of explosion flag handling.
## 7.0.11
* Add support for MC 1.21.
* Add wind-charge-burst flag which is checked along with `use` (for the interaction) or `pvp` (for the knockback).
* Add breeze-charge-explosion flag for breeze charges (i.e. from the mob, not player wind charges).
* Add moisture-change flag and config options.
* Fix an error if a player logged in to an unloaded world.
* Fix chest boat usage always being counted as ride.
* Consider potions thrown by mobs as mob-damage.
* Workaround spigot no longer sending block change events when a book is placed on a lectern.
* Improve accuracy of target blocks in blacklist/build-perms events.
## 7.0.10
* Add support for MC 1.20.5 and 1.20.6, drop support for other 1.20 versions
## 7.0.9
* Add support for MC 1.20, drop support for MC 1.19
* Made entities spawned via the `/summon` command get treated as plugin-spawned entities
* Add sniffer egg trample protection options
## 7.0.8
* Add support for MC 1.19
* Add skulk-growth flag and config option
+5 -2
View File
@@ -1,8 +1,11 @@
Compiling
=========
You can compile WorldGuard as long as you have some version of Java greater than or equal to 21 installed.
Gradle will download JDK 21 specifically if needed, but it needs some version of Java to bootstrap from.
You can compile WorldGuard as long as you have some version of Java greater than or equal to 17 installed. Gradle will download JDK 17 specifically if needed,
but it needs some version of Java to bootstrap from.
Note that if you have JRE 17 installed, Gradle will currently attempt to use that to compile, which will not work. It is easiest to uninstall JRE 16 and
replace it with JDK 17.
The build process uses Gradle, which you do *not* need to download. WorldGuard is a multi-module project with three modules:
+15 -4
View File
@@ -2,7 +2,17 @@
<img src="worldguard-logo.svg" alt="WorldGuard" width="400" />
</h1>
WorldGuard lets you and players guard areas of land against griefers and undesirables, as well as tweak and disable various gameplay features of Minecraft.
A fork of [WorldGuard](https://github.com/EngineHub/WorldGuard) 7.0.8 maintained by [TrueOG Network](https://true-og.net) for 1.19.4. WorldGuard lets you and players guard areas of land against griefers and undesirables, as well as tweak and disable various gameplay features of Minecraft.
## Changes over WorldGuard:
- Gradle 8.0.2 -> 8.14.3.
- `build` copies the shaded jar to `build/libs/WorldGuard-<version>.jar` via `copyjar.sh`.
- Ships the live TrueOG Network `config.yml`, `config_world.yml`, and `worlds/world/regions.yml` as defaults. The world regions file is created on first run alongside the main config.
- New region flag `creeper-block-damage` (default allow). Set it to deny with `creeper-explosion` allowed to keep creeper blasts from breaking blocks while still damaging entities. This is how the spawn warzone is configured.
- Bucket use no longer plays the deny effect when a partner plugin's `safe-fluids` flag allows the action (FireFight-OG compatibility).
## Upstream description:
* Block creeper and wither block damage, falling damage, etc.
* Disable fire spread, lava fire spread, ice formation, Endermen picking up blocks, etc.
@@ -24,7 +34,7 @@ Compiling
---------
The project is written for Java 17 and our build process makes use of
[Gradle](http://gradle.org).
[Gradle](http://gradle.org). Run `./gradlew build` and pick up the plugin jar from `build/libs/`.
Dependencies are automatically handled by Gradle.
@@ -40,8 +50,9 @@ Submissions must be licensed under the GNU Lesser General Public License v3.
Links
-----
* [Homepage](https://enginehub.org/worldguard)
* [TrueOG fork](https://git.trueog.net/trueog/WorldGuard)
* [Homepage](http://enginehub.org/worldguard)
* [Discord](https://discord.gg/enginehub)
* [Issue tracker](https://github.com/EngineHub/WorldGuard/issues)
* [Continuous integration](https://builds.enginehub.org) [![Build Status](https://ci.enginehub.org/app/rest/builds/buildType:bt11,branch:master/statusIcon.svg)](http://ci.enginehub.org/viewType.html?buildTypeId=bt11&guest=1)
* [Continuous integration](http://builds.enginehub.org) [![Build Status](https://ci.enginehub.org/app/rest/builds/buildType:bt11,branch:master/statusIcon.svg)](http://ci.enginehub.org/viewType.html?buildTypeId=bt11&guest=1)
* [End-user documentation](https://worldguard.enginehub.org/en/latest/)
-29
View File
@@ -1,29 +0,0 @@
plugins {
`kotlin-dsl`
}
repositories {
gradlePluginPortal()
}
dependencies {
implementation(gradleApi())
implementation(libs.licenser)
implementation(libs.grgit)
implementation(libs.shadow)
implementation(libs.jfrog.buildinfo)
implementation(libs.gson)
constraints {
val asmVersion = "[${libs.versions.minimumAsm.get()},)"
implementation("org.ow2.asm:asm:$asmVersion") {
because("Need Java 21 support in shadow")
}
implementation("org.ow2.asm:asm-commons:$asmVersion") {
because("Need Java 21 support in shadow")
}
implementation("org.vafer:jdependency:[${libs.versions.minimumJdependency.get()},)") {
because("Need Java 21 support in shadow")
}
}
}
-9
View File
@@ -1,9 +0,0 @@
dependencyResolutionManagement {
versionCatalogs {
create("libs") {
from(files("../gradle/libs.versions.toml"))
}
}
}
rootProject.name = "build-logic"
@@ -1,32 +0,0 @@
import org.jfrog.gradle.plugin.artifactory.dsl.ArtifactoryPluginConvention
import org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask
plugins {
id("com.jfrog.artifactory")
}
val ARTIFACTORY_CONTEXT_URL = "artifactory_contextUrl"
val ARTIFACTORY_USER = "artifactory_user"
val ARTIFACTORY_PASSWORD = "artifactory_password"
if (!project.hasProperty(ARTIFACTORY_CONTEXT_URL)) ext[ARTIFACTORY_CONTEXT_URL] = "http://localhost"
if (!project.hasProperty(ARTIFACTORY_USER)) ext[ARTIFACTORY_USER] = "guest"
if (!project.hasProperty(ARTIFACTORY_PASSWORD)) ext[ARTIFACTORY_PASSWORD] = ""
configure<ArtifactoryPluginConvention> {
setContextUrl("${project.property(ARTIFACTORY_CONTEXT_URL)}")
clientConfig.publisher.run {
repoKey = when {
"${project.version}".contains("SNAPSHOT") -> "libs-snapshot-local"
else -> "libs-release-local"
}
username = "${project.property(ARTIFACTORY_USER)}"
password = "${project.property(ARTIFACTORY_PASSWORD)}"
isMaven = true
isIvy = false
}
}
tasks.named<ArtifactoryTask>("artifactoryPublish") {
isSkip = true
}
@@ -1,10 +0,0 @@
plugins {
id("com.jfrog.artifactory")
}
// Artifactory eagerly evaluates publications, so this must run after all changes to artifacts are done
afterEvaluate {
tasks.named<org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask>("artifactoryPublish") {
publications("maven")
}
}
@@ -1,65 +0,0 @@
import buildlogic.getLibrary
import buildlogic.stringyLibs
plugins {
id("eclipse")
id("idea")
id("checkstyle")
id("buildlogic.common")
}
tasks
.withType<JavaCompile>()
.matching { it.name == "compileJava" || it.name == "compileTestJava" }
.configureEach {
val disabledLint = listOf(
"processing", "path", "fallthrough", "serial", "overloads",
)
options.release.set(21)
options.compilerArgs.addAll(listOf("-Xlint:all") + disabledLint.map { "-Xlint:-$it" })
options.isDeprecation = true
options.encoding = "UTF-8"
options.compilerArgs.add("-parameters")
//options.compilerArgs.add("-Werror")
}
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "10.16.0"
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
}
dependencies {
"compileOnly"(stringyLibs.getLibrary("jsr305"))
"testImplementation"(platform(stringyLibs.getLibrary("junit-bom")))
"testImplementation"(stringyLibs.getLibrary("junit-jupiter-api"))
"testImplementation"(stringyLibs.getLibrary("junit-jupiter-params"))
"testRuntimeOnly"(stringyLibs.getLibrary("junit-jupiter-engine"))
}
// Java 8 turns on doclint which we fail
tasks.withType<Javadoc>().configureEach {
options.encoding = "UTF-8"
(options as StandardJavadocDocletOptions).apply {
//addBooleanOption("Werror", true)
addBooleanOption("Xdoclint:all", true)
addBooleanOption("Xdoclint:-missing", true)
tags(
"apiNote:a:API Note:",
"implSpec:a:Implementation Requirements:",
"implNote:a:Implementation Note:"
)
}
}
configure<JavaPluginExtension> {
withJavadocJar()
withSourcesJar()
}
tasks.named("check").configure {
dependsOn("checkstyleMain", "checkstyleTest")
}
@@ -1,69 +0,0 @@
import buildlogic.getLibrary
import buildlogic.stringyLibs
import org.gradle.plugins.ide.idea.model.IdeaModel
plugins {
id("org.cadixdev.licenser")
}
group = rootProject.group
version = rootProject.version
repositories {
mavenCentral()
maven {
name = "EngineHub"
url = uri("https://maven.enginehub.org/repo/")
}
}
configurations.all {
resolutionStrategy {
cacheChangingModulesFor(1, TimeUnit.DAYS)
}
}
plugins.withId("java") {
the<JavaPluginExtension>().toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
}
dependencies {
for (conf in listOf("implementation", "api")) {
if (!configurations.names.contains(conf)) {
continue
}
add(conf, platform(stringyLibs.getLibrary("log4j-bom")).map {
val dep = create(it)
dep.because("Mojang provides Log4j")
dep
})
constraints {
add(conf, stringyLibs.getLibrary("guava")) {
because("Mojang provides Guava")
}
add(conf, stringyLibs.getLibrary("gson")) {
because("Mojang provides Gson")
}
add(conf, stringyLibs.getLibrary("fastutil")) {
because("Mojang provides FastUtil")
}
}
}
}
license {
header(rootProject.file("HEADER.txt"))
include("**/*.java")
include("**/*.kt")
}
plugins.withId("idea") {
configure<IdeaModel> {
module {
isDownloadSources = true
isDownloadJavadoc = true
}
}
}
@@ -1,23 +0,0 @@
plugins {
id("java")
id("maven-publish")
id("buildlogic.common-java")
id("buildlogic.artifactory-sub")
}
ext["internalVersion"] = "$version+${rootProject.ext["gitCommitHash"]}"
publishing {
publications {
register<MavenPublication>("maven") {
versionMapping {
usage("java-api") {
fromResolutionOf("runtimeClasspath")
}
usage("java-runtime") {
fromResolutionResult()
}
}
}
}
}
@@ -1,179 +0,0 @@
plugins {
id("java-base")
id("maven-publish")
id("com.github.johnrengelman.shadow")
id("com.jfrog.artifactory")
id("buildlogic.common")
id("buildlogic.artifactory-sub")
}
// A horrible hack because `softwareComponentFactory` has to be gotten via plugin
// gradle why
internal open class LibsConfigPluginHack @Inject constructor(
private val softwareComponentFactory: SoftwareComponentFactory
) : Plugin<Project> {
override fun apply(project: Project) {
val libsComponents = softwareComponentFactory.adhoc("libs")
project.components.add(libsComponents)
}
}
configurations {
create("shade")
}
group = "${rootProject.group}.worldguard-libs"
val relocations = mapOf(
"org.enginehub.squirrelid" to "com.sk89q.worldguard.util.profile",
)
tasks.register<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar>("jar") {
configurations = listOf(project.configurations["shade"])
archiveClassifier.set("")
// Yeet module-info's
exclude("module-info.class")
dependencies {
exclude(dependency("com.google.guava:guava"))
exclude(dependency("com.google.code.gson:gson"))
exclude(dependency("com.google.errorprone:error_prone_annotations"))
exclude(dependency("com.google.guava:failureaccess"))
exclude(dependency("org.checkerframework:checker-qual"))
exclude(dependency("org.jetbrains:annotations"))
exclude(dependency("org.apache.logging.log4j:log4j-api"))
exclude(dependency("com.google.code.findbugs:jsr305"))
exclude {
it.moduleGroup == "org.jetbrains.kotlin"
}
}
relocations.forEach { (from, to) ->
relocate(from, to)
}
}
val altConfigFiles = { artifactType: String ->
val deps = configurations["shade"].incoming.dependencies
.filterIsInstance<ModuleDependency>()
.map { it.copy() }
.map { dependency ->
val category = dependency.attributes.getAttribute(Category.CATEGORY_ATTRIBUTE)?.name
if (category == Category.REGULAR_PLATFORM || category == Category.ENFORCED_PLATFORM) {
return@map dependency
}
try {
dependency.artifact {
name = dependency.name
type = artifactType
extension = "jar"
classifier = artifactType
}
} catch (e: Exception) {
throw RuntimeException("Failed to add artifact to dependency: $dependency", e)
}
dependency
}
files(configurations.detachedConfiguration(*deps.toTypedArray())
.resolvedConfiguration.lenientConfiguration.artifacts
.filter { it.classifier == artifactType }
.map { zipTree(it.file) })
}
tasks.register<Jar>("sourcesJar") {
from({
altConfigFiles("sources")
})
// Yeet module-info's
exclude("module-info.java")
relocations.forEach { (from, to) ->
val filePattern = Regex("(.*)${from.replace('.', '/')}((?:/|$).*)")
val textPattern = Regex.fromLiteral(from)
eachFile {
filter {
it.replaceFirst(textPattern, to)
}
path = path.replaceFirst(filePattern, "$1${to.replace('.', '/')}$2")
}
}
archiveClassifier.set("sources")
}
tasks.named("assemble").configure {
dependsOn("jar", "sourcesJar")
}
project.apply<LibsConfigPluginHack>()
val libsComponent = project.components["libs"] as AdhocComponentWithVariants
val apiElements = project.configurations.register("apiElements") {
isVisible = false
description = "API elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_API))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR))
attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 21)
}
outgoing.artifact(tasks.named("jar"))
}
val runtimeElements = project.configurations.register("runtimeElements") {
isVisible = false
description = "Runtime elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR))
attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 21)
}
outgoing.artifact(tasks.named("jar"))
}
val sourcesElements = project.configurations.register("sourcesElements") {
isVisible = false
description = "Source elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.DOCUMENTATION))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(DocsType.DOCS_TYPE_ATTRIBUTE, project.objects.named(DocsType.SOURCES))
}
outgoing.artifact(tasks.named("sourcesJar"))
}
libsComponent.addVariantsFromConfiguration(apiElements.get()) {
mapToMavenScope("compile")
}
libsComponent.addVariantsFromConfiguration(runtimeElements.get()) {
mapToMavenScope("runtime")
}
libsComponent.addVariantsFromConfiguration(sourcesElements.get()) {
mapToMavenScope("runtime")
}
configure<PublishingExtension> {
publications {
register<MavenPublication>("maven") {
from(libsComponent)
}
}
}
if (project != project(":worldguard-libs:core")) {
evaluationDependsOn(":worldguard-libs:core")
configurations["shade"].shouldResolveConsistentlyWith(project(":worldguard-libs:core").configurations["shade"])
}
@@ -1,39 +0,0 @@
plugins {
id("com.github.johnrengelman.shadow")
id("buildlogic.core-and-platform")
}
tasks.named<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar>("shadowJar") {
archiveClassifier.set("dist")
dependencies {
include(project(":worldguard-libs:core"))
include(project(":worldguard-core"))
relocate("org.flywaydb", "com.sk89q.worldguard.internal.flywaydb") {
include(dependency("org.flywaydb:flyway-core"))
}
exclude("com.google.code.findbugs:jsr305")
}
exclude("GradleStart**")
exclude(".cache")
exclude("LICENSE*")
exclude("META-INF/maven/**")
minimize()
}
val javaComponent = components["java"] as AdhocComponentWithVariants
// I don't think we want this published (it's the shadow jar)
javaComponent.withVariantsFromConfiguration(configurations["shadowRuntimeElements"]) {
skip()
}
afterEvaluate {
tasks.named<Jar>("jar") {
val version = project(":worldguard-core").version
inputs.property("version", version)
val attributes = mutableMapOf(
"Implementation-Version" to version,
"WorldGuard-Version" to version,
)
manifest.attributes(attributes)
}
}
@@ -1,24 +0,0 @@
package buildlogic
import org.gradle.api.Project
import org.gradle.api.artifacts.MinimalExternalModuleDependency
import org.gradle.api.artifacts.VersionCatalog
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.api.artifacts.VersionConstraint
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.gradle.api.provider.Provider
import org.gradle.kotlin.dsl.getByType
val Project.ext: ExtraPropertiesExtension
get() = extensions.getByType()
val Project.stringyLibs: VersionCatalog
get() = extensions.getByType<VersionCatalogsExtension>().named("libs")
fun VersionCatalog.getLibrary(name: String): Provider<MinimalExternalModuleDependency> = findLibrary(name).orElseThrow {
error("Library $name not found in version catalog")
}
fun VersionCatalog.getVersion(name: String): VersionConstraint = findVersion(name).orElseThrow {
error("Version $name not found in version catalog")
}
+15 -6
View File
@@ -1,17 +1,26 @@
import org.ajoberstar.grgit.Grgit
plugins {
id("buildlogic.common")
id("buildlogic.artifactory-root")
}
logger.lifecycle("""
*******************************************
You are building WorldGuard!
If you encounter trouble:
1) Try running 'build' in a separate Gradle run
2) Use gradlew and not gradle
3) If you still need help, ask on Discord! https://discord.gg/enginehub
Output files will be in [subproject]/build/libs
*******************************************
""")
applyRootArtifactoryConfig()
if (!project.hasProperty("gitCommitHash")) {
apply(plugin = "org.ajoberstar.grgit")
ext["gitCommitHash"] = try {
extensions.getByName<Grgit>("grgit").head()?.abbreviatedId
Grgit.open(mapOf("currentDir" to project.rootDir))?.head()?.abbreviatedId
} catch (e: Exception) {
logger.warn("Error getting commit hash", e)
"no.git.id"
}
}
}
+17
View File
@@ -0,0 +1,17 @@
plugins {
`kotlin-dsl`
kotlin("jvm") version embeddedKotlinVersion
}
repositories {
mavenCentral()
gradlePluginPortal()
}
dependencies {
implementation(gradleApi())
implementation("gradle.plugin.org.cadixdev.gradle:licenser:0.6.1")
implementation("org.ajoberstar.grgit:grgit-gradle:4.1.1")
implementation("gradle.plugin.com.github.johnrengelman:shadow:7.1.2")
implementation("org.jfrog.buildinfo:build-info-extractor-gradle:4.27.1")
}
@@ -0,0 +1,40 @@
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.named
import org.jfrog.gradle.plugin.artifactory.dsl.ArtifactoryPluginConvention
import org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask
private const val ARTIFACTORY_CONTEXT_URL = "artifactory_contextUrl"
private const val ARTIFACTORY_USER = "artifactory_user"
private const val ARTIFACTORY_PASSWORD = "artifactory_password"
fun Project.applyRootArtifactoryConfig() {
if (!project.hasProperty(ARTIFACTORY_CONTEXT_URL)) ext[ARTIFACTORY_CONTEXT_URL] = "http://localhost"
if (!project.hasProperty(ARTIFACTORY_USER)) ext[ARTIFACTORY_USER] = "guest"
if (!project.hasProperty(ARTIFACTORY_PASSWORD)) ext[ARTIFACTORY_PASSWORD] = ""
apply(plugin = "com.jfrog.artifactory")
configure<ArtifactoryPluginConvention> {
setContextUrl("${project.property(ARTIFACTORY_CONTEXT_URL)}")
clientConfig.publisher.run {
repoKey = when {
"${project.version}".contains("SNAPSHOT") -> "libs-snapshot-local"
else -> "libs-release-local"
}
username = "${project.property(ARTIFACTORY_USER)}"
password = "${project.property(ARTIFACTORY_PASSWORD)}"
isMaven = true
isIvy = false
}
}
tasks.named<ArtifactoryTask>("artifactoryPublish") {
isSkip = true
}
}
fun Project.applyCommonArtifactoryConfig() {
tasks.named<ArtifactoryTask>("artifactoryPublish") {
publications("maven")
}
}
+38
View File
@@ -0,0 +1,38 @@
import org.cadixdev.gradle.licenser.LicenseExtension
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.jvm.toolchain.JavaLanguageVersion
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.repositories
import org.gradle.kotlin.dsl.the
fun Project.applyCommonConfiguration() {
group = rootProject.group
version = rootProject.version
repositories {
mavenCentral()
maven { url = uri("https://maven.enginehub.org/repo/") }
maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots/") }
}
configurations.all {
resolutionStrategy {
cacheChangingModulesFor(5, "MINUTES")
}
}
plugins.withId("java") {
the<JavaPluginExtension>().toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
apply(plugin = "org.cadixdev.licenser")
configure<LicenseExtension> {
header(rootProject.file("HEADER.txt"))
include("**/*.java")
include("**/*.kt")
}
}
@@ -1,86 +0,0 @@
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.plugins.quality.CheckstyleExtension
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.api.tasks.testing.Test
import org.gradle.external.javadoc.StandardJavadocDocletOptions
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.withType
fun Project.applyCommonJavaConfiguration(sourcesJar: Boolean, javaRelease: Int = 8, banSlf4j: Boolean = true) {
applyCommonConfiguration()
apply(plugin = "eclipse")
apply(plugin = "idea")
apply(plugin = "checkstyle")
tasks
.withType<JavaCompile>()
.matching { it.name == "compileJava" || it.name == "compileTestJava" }
.configureEach {
val disabledLint = listOf(
"processing", "path", "fallthrough", "serial"
)
options.release.set(javaRelease)
options.compilerArgs.addAll(listOf("-Xlint:all") + disabledLint.map { "-Xlint:-$it" })
options.isDeprecation = true
options.encoding = "UTF-8"
options.compilerArgs.add("-parameters")
}
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "9.1"
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
}
dependencies {
"compileOnly"("com.google.code.findbugs:jsr305:${Versions.FINDBUGS}")
"testImplementation"("org.junit.jupiter:junit-jupiter-api:${Versions.JUNIT}")
"testImplementation"("org.junit.jupiter:junit-jupiter-params:${Versions.JUNIT}")
"testImplementation"("org.mockito:mockito-core:${Versions.MOCKITO}")
"testImplementation"("org.mockito:mockito-junit-jupiter:${Versions.MOCKITO}")
"testRuntimeOnly"("org.junit.jupiter:junit-jupiter-engine:${Versions.JUNIT}")
}
// Java 8 turns on doclint which we fail
tasks.withType<Javadoc>().configureEach {
options.encoding = "UTF-8"
(options as StandardJavadocDocletOptions).apply {
addStringOption("Xdoclint:none", "-quiet")
tags(
"apiNote:a:API Note:",
"implSpec:a:Implementation Requirements:",
"implNote:a:Implementation Note:"
)
}
}
configure<JavaPluginExtension> {
disableAutoTargetJvm()
withJavadocJar()
if (sourcesJar) {
withSourcesJar()
}
}
if (banSlf4j) {
configurations["compileClasspath"].apply {
resolutionStrategy.componentSelection {
withModule("org.slf4j:slf4j-api") {
reject("No SLF4J allowed on compile classpath")
}
}
}
}
tasks.named("check").configure {
dependsOn("checkstyleMain", "checkstyleTest")
}
}
+12
View File
@@ -0,0 +1,12 @@
import org.gradle.api.Project
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.the
val Project.ext: ExtraPropertiesExtension
get() = extensions.getByType()
val Project.sourceSets: SourceSetContainer
get() = the<JavaPluginConvention>().sourceSets
+171
View File
@@ -0,0 +1,171 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.attributes.Bundling
import org.gradle.api.attributes.Category
import org.gradle.api.attributes.DocsType
import org.gradle.api.attributes.LibraryElements
import org.gradle.api.attributes.Usage
import org.gradle.api.attributes.java.TargetJvmVersion
import org.gradle.api.component.AdhocComponentWithVariants
import org.gradle.api.component.SoftwareComponentFactory
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.invoke
import org.gradle.kotlin.dsl.named
import org.gradle.kotlin.dsl.register
import javax.inject.Inject
fun Project.applyLibrariesConfiguration() {
applyCommonConfiguration()
apply(plugin = "java-base")
apply(plugin = "maven-publish")
apply(plugin = "com.github.johnrengelman.shadow")
apply(plugin = "com.jfrog.artifactory")
configurations {
create("shade")
}
group = "${rootProject.group}.worldguard-libs"
val relocations = mapOf(
"org.enginehub.squirrelid" to "com.sk89q.worldguard.util.profile"
)
tasks.register<ShadowJar>("jar") {
configurations = listOf(project.configurations["shade"])
archiveClassifier.set("")
dependencies {
exclude(dependency("com.google.code.findbugs:jsr305"))
}
relocations.forEach { (from, to) ->
relocate(from, to)
}
}
val altConfigFiles = { artifactType: String ->
val deps = configurations["shade"].incoming.dependencies
.filterIsInstance<ModuleDependency>()
.map { it.copy() }
.map { dependency ->
dependency.artifact {
name = dependency.name
type = artifactType
extension = "jar"
classifier = artifactType
}
dependency
}
files(configurations.detachedConfiguration(*deps.toTypedArray())
.resolvedConfiguration.lenientConfiguration.artifacts
.filter { it.classifier == artifactType }
.map { zipTree(it.file) })
}
tasks.register<Jar>("sourcesJar") {
from({
altConfigFiles("sources")
})
relocations.forEach { (from, to) ->
val filePattern = Regex("(.*)${from.replace('.', '/')}((?:/|$).*)")
val textPattern = Regex.fromLiteral(from)
eachFile {
filter {
it.replaceFirst(textPattern, to)
}
path = path.replaceFirst(filePattern, "$1${to.replace('.', '/')}$2")
}
}
archiveClassifier.set("sources")
}
tasks.named("assemble").configure {
dependsOn("jar", "sourcesJar")
}
project.apply<LibsConfigPluginHack>()
val libsComponent = project.components["libs"] as AdhocComponentWithVariants
val apiElements = project.configurations.register("apiElements") {
isVisible = false
description = "API elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_API))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR))
attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 8)
}
outgoing.artifact(tasks.named("jar"))
}
val runtimeElements = project.configurations.register("runtimeElements") {
isVisible = false
description = "Runtime elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR))
attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 8)
}
outgoing.artifact(tasks.named("jar"))
}
val sourcesElements = project.configurations.register("sourcesElements") {
isVisible = false
description = "Source elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.DOCUMENTATION))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(DocsType.DOCS_TYPE_ATTRIBUTE, project.objects.named(DocsType.SOURCES))
}
outgoing.artifact(tasks.named("sourcesJar"))
}
libsComponent.addVariantsFromConfiguration(apiElements.get()) {
mapToMavenScope("compile")
}
libsComponent.addVariantsFromConfiguration(runtimeElements.get()) {
mapToMavenScope("runtime")
}
libsComponent.addVariantsFromConfiguration(sourcesElements.get()) {
mapToMavenScope("runtime")
}
configure<PublishingExtension> {
publications {
register<MavenPublication>("maven") {
from(libsComponent)
}
}
}
applyCommonArtifactoryConfig()
}
internal open class LibsConfigPluginHack @Inject constructor(
private val softwareComponentFactory: SoftwareComponentFactory
) : Plugin<Project> {
override fun apply(project: Project) {
val libsComponents = softwareComponentFactory.adhoc("libs")
project.components.add(libsComponents)
}
}
+113
View File
@@ -0,0 +1,113 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.Project
import org.gradle.api.component.AdhocComponentWithVariants
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.plugins.quality.CheckstyleExtension
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.api.tasks.testing.Test
import org.gradle.external.javadoc.StandardJavadocDocletOptions
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.named
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.withType
import org.gradle.kotlin.dsl.the
fun Project.applyPlatformAndCoreConfiguration() {
applyCommonConfiguration()
apply(plugin = "java")
apply(plugin = "eclipse")
apply(plugin = "idea")
apply(plugin = "maven-publish")
apply(plugin = "checkstyle")
apply(plugin = "com.jfrog.artifactory")
ext["internalVersion"] = "$version+${rootProject.ext["gitCommitHash"]}"
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "10.3"
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
}
dependencies {
"compileOnly"("com.google.code.findbugs:jsr305:3.0.2")
"testCompileOnly"("com.google.code.findbugs:jsr305:3.0.2")
"testImplementation"("org.junit.jupiter:junit-jupiter-api:${Versions.JUNIT}")
"testImplementation"("org.junit.jupiter:junit-jupiter-params:${Versions.JUNIT}")
"testImplementation"("org.mockito:mockito-core:${Versions.MOCKITO}")
"testImplementation"("org.mockito:mockito-junit-jupiter:${Versions.MOCKITO}")
"testRuntimeOnly"("org.junit.jupiter:junit-jupiter-engine:${Versions.JUNIT}")
}
// Java 8 turns on doclint which we fail
tasks.withType<Javadoc>().configureEach {
(options as StandardJavadocDocletOptions).apply {
addStringOption("Xdoclint:none", "-quiet")
tags(
"apiNote:a:API Note:",
"implSpec:a:Implementation Requirements:",
"implNote:a:Implementation Note:"
)
}
}
the<JavaPluginExtension>().withJavadocJar()
if (name == "worldguard-core" || name == "worldguard-bukkit") {
the<JavaPluginExtension>().withSourcesJar()
}
tasks.named("check").configure {
dependsOn("checkstyleMain", "checkstyleTest")
}
configure<PublishingExtension> {
publications {
register<MavenPublication>("maven") {
from(components["java"])
versionMapping {
usage("java-api") {
fromResolutionOf("runtimeClasspath")
}
usage("java-runtime") {
fromResolutionResult()
}
}
}
}
}
applyCommonArtifactoryConfig()
}
fun Project.applyShadowConfiguration() {
apply(plugin = "com.github.johnrengelman.shadow")
tasks.named<ShadowJar>("shadowJar") {
archiveClassifier.set("dist")
dependencies {
include(project(":worldguard-libs:core"))
//include(project(":worldguard-libs:${project.name.replace("worldguard-", "")}"))
include(project(":worldguard-core"))
relocate("org.flywaydb", "com.sk89q.worldguard.internal.flywaydb") {
include(dependency("org.flywaydb:flyway-core:3.0"))
}
exclude("com.google.code.findbugs:jsr305")
}
exclude("GradleStart**")
exclude(".cache")
exclude("LICENSE*")
}
val javaComponent = components["java"] as AdhocComponentWithVariants
javaComponent.withVariantsFromConfiguration(configurations["shadowRuntimeElements"]) {
skip()
}
}
+10
View File
@@ -0,0 +1,10 @@
object Versions {
// const val PISTON = "0.4.3"
// const val AUTO_VALUE = "1.6.5"
const val WORLDEDIT = "7.2.12"
const val JUNIT = "5.9.1"
const val MOCKITO = "4.9.0"
const val SQUIRRELID = "0.3.2"
const val GUAVA = "31.1-jre"
const val FINDBUGS = "3.0.2"
}
+1
View File
@@ -7,6 +7,7 @@
<allow pkg="javax"/>
<allow pkg="org.junit"/>
<allow pkg="org.hamcrest"/>
<allow pkg="org.mockito"/>
<allow pkg="junit.framework"/>
<allow pkg="com.sk89q"/>
<allow pkg="com.google.common"/>
Executable
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
VERSION="$1"
# Ensure the target directory exists
mkdir -p build/libs
# Copy and rename the jar, using $VERSION in the final filename
cp worldguard-bukkit/build/libs/*-dist.jar "build/libs/WorldGuard-${VERSION}.jar"
+1 -3
View File
@@ -1,4 +1,2 @@
group=com.sk89q.worldguard
version=7.1.0-SNAPSHOT
org.gradle.parallel=true
version=7.0.8
-2
View File
@@ -1,2 +0,0 @@
#This file is generated by updateDaemonJvm
toolchainVersion=21
-66
View File
@@ -1,66 +0,0 @@
[versions]
worldedit = "7.3.0"
# Minimum versions we apply to make dependencies support newer Java
minimumAsm = "9.7"
minimumJdependency = "2.10"
minimumTinyRemapper = "0.8.11"
# lang-version = ""
[libraries]
licenser = "gradle.plugin.org.cadixdev.gradle:licenser:0.6.1"
grgit = "org.ajoberstar.grgit:grgit-gradle:5.2.2"
shadow = "com.github.johnrengelman:shadow:8.1.1"
jfrog-buildinfo = "org.jfrog.buildinfo:build-info-extractor-gradle:5.2.0"
squirrelid = "org.enginehub:squirrelid:0.3.2"
autoService = "com.google.auto.service:auto-service:1.1.1"
jsr305 = "com.google.code.findbugs:jsr305:3.0.2"
jetbrains-annotations = "org.jetbrains:annotations:24.1.0"
junit-bom = "org.junit:junit-bom:5.10.2"
junit-jupiter-api.module = "org.junit.jupiter:junit-jupiter-api"
junit-jupiter-params.module = "org.junit.jupiter:junit-jupiter-params"
junit-jupiter-engine.module = "org.junit.jupiter:junit-jupiter-engine"
spigot = "org.spigotmc:spigot-api:1.21-R0.1-SNAPSHOT"
paperApi = "io.papermc.paper:paper-api:1.21-R0.1-SNAPSHOT"
paperLib = "io.papermc:paperlib:1.0.8"
dummypermscompat = "com.sk89q:dummypermscompat:1.10"
bstats-bukkit = "org.bstats:bstats-bukkit:2.2.1"
prtree = "org.khelekore:prtree:1.5.0"
flyway-core = "org.flywaydb:flyway-core:3.0"
commandbook = "com.sk89q:commandbook:2.3"
hamcrest-library = "org.hamcrest:hamcrest-library:2.2"
# Mojang-provided libraries, CHECK AGAINST MINECRAFT for versions
guava = "com.google.guava:guava:32.1.3-jre!!"
log4j-bom = "org.apache.logging.log4j:log4j-bom:2.22.1!!"
gson = "com.google.code.gson:gson:2.10.1!!"
fastutil = "it.unimi.dsi:fastutil:8.5.12!!"
# Bukkit-provided libraries, CHECK AGAINST SPIGOT for versions
# Note that we need to balance support for older MC versus working at all on newer ones, so the exact versions here
# may not be the same as the ones in the latest Bukkit API.
snakeyaml = "org.yaml:snakeyaml:2.0"
[libraries.worldedit-core]
module = "com.sk89q.worldedit:worldedit-core"
version.ref = "worldedit"
[libraries.worldedit-bukkit]
module = "com.sk89q.worldedit:worldedit-bukkit"
version.ref = "worldedit"
[libraries.worldedit-libs-ap]
module = "com.sk89q.worldedit.worldedit-libs:ap"
version.ref = "worldedit"
Binary file not shown.
+1 -2
View File
@@ -1,7 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+12 -17
View File
@@ -83,8 +83,10 @@ done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -131,13 +133,10 @@ location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
@@ -145,7 +144,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -153,7 +152,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -198,15 +197,11 @@ if "$cygwin" || "$msys" ; then
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
Vendored
+92 -92
View File
@@ -1,92 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+3 -29
View File
@@ -1,33 +1,7 @@
pluginManagement {
repositories {
gradlePluginPortal()
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
logger.lifecycle("""
*******************************************
You are building WorldGuard!
If you encounter trouble:
1) Read COMPILING.md if you haven't yet
2) Try running 'build' in a separate Gradle run
3) Use gradlew and not gradle
4) If you still need help, ask on Discord! https://discord.gg/enginehub
Output files will be in [subproject]/build/libs
*******************************************
""")
rootProject.name = "worldguard"
includeBuild("build-logic")
include("worldguard-libs")
include("worldguard-libs:core")
listOf("bukkit", "core").forEach {
include("worldguard-$it")
}
include("worldguard-core")
//include("worldguard-libs:bukkit")
include("worldguard-bukkit")
+47 -35
View File
@@ -2,40 +2,33 @@ import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
`java-library`
id("buildlogic.platform")
}
val localImplementation = configurations.create("localImplementation") {
description = "Dependencies used locally, but provided by the runtime Bukkit implementation"
isCanBeConsumed = false
isCanBeResolved = false
applyPlatformAndCoreConfiguration()
applyShadowConfiguration()
repositories {
maven {
name = "paper"
url = uri("https://repo.papermc.io/repository/maven-public/")
}
}
configurations {
compileClasspath.get().extendsFrom(create("shadeOnly"))
}
configurations["compileOnly"].extendsFrom(localImplementation)
configurations["testImplementation"].extendsFrom(localImplementation)
dependencies {
"api"(project(":worldguard-core"))
"api"(libs.worldedit.bukkit) { isTransitive = false }
"compileOnly"(libs.commandbook) { isTransitive = false }
// Technically this is api, but everyone should already have some form of the bukkit API
// Avoid pulling in another one, especially one so outdated.
"localImplementation"(libs.spigot) {
"compileOnly"("io.papermc.paper:paper-api:1.19.3-R0.1-SNAPSHOT")
"runtimeOnly"("org.spigotmc:spigot-api:1.19.3-R0.1-SNAPSHOT") {
exclude("junit", "junit")
}
"compileOnly"(libs.jetbrains.annotations) {
because("Resolving Spigot annotations")
}
"testCompileOnly"(libs.jetbrains.annotations) {
because("Resolving Spigot annotations")
}
"compileOnly"(libs.paperApi) {
exclude("org.slf4j", "slf4j-api")
exclude("junit", "junit")
}
"implementation"(libs.paperLib)
"implementation"(libs.bstats.bukkit)
"api"("com.sk89q.worldedit:worldedit-bukkit:${Versions.WORLDEDIT}") { isTransitive = false }
"implementation"("com.google.guava:guava:${Versions.GUAVA}")
"compileOnly"("com.sk89q:commandbook:2.3") { isTransitive = false }
"shadeOnly"("io.papermc:paperlib:1.0.8")
"shadeOnly"("org.bstats:bstats-bukkit:3.0.1")
}
tasks.named<Copy>("processResources") {
@@ -46,14 +39,28 @@ tasks.named<Copy>("processResources") {
}
}
tasks.named<Jar>("jar") {
val projectVersion = project.version
inputs.property("projectVersion", projectVersion)
manifest {
attributes("Implementation-Version" to projectVersion)
}
}
tasks.named<ShadowJar>("shadowJar") {
configurations = listOf(project.configurations["shadeOnly"], project.configurations["runtimeClasspath"])
dependencies {
include(dependency(":worldguard-core"))
include(dependency("org.bstats:"))
include(dependency("io.papermc:paperlib"))
relocate("org.bstats", "com.sk89q.worldguard.bukkit.bstats")
relocate("io.papermc.lib", "com.sk89q.worldguard.bukkit.paperlib")
relocate("org.bstats", "com.sk89q.worldguard.bukkit.bstats") {
include(dependency("org.bstats:"))
}
relocate ("io.papermc.lib", "com.sk89q.worldguard.bukkit.paperlib") {
include(dependency("io.papermc:paperlib"))
}
relocate ("co.aikar.timings.lib", "com.sk89q.worldguard.bukkit.timingslib") {
include(dependency("co.aikar:minecraft-timings"))
}
}
}
@@ -61,8 +68,13 @@ tasks.named("assemble").configure {
dependsOn("shadowJar")
}
configure<PublishingExtension> {
publications.named<MavenPublication>("maven") {
from(components["java"])
}
tasks.register("runCopyJarScript", Exec::class) {
group = "build"
description = "Runs the copyjar.sh script after build completion."
workingDir(rootDir)
commandLine("sh", "copyjar.sh", project.version.toString())
}
tasks.named("build") {
finalizedBy("runCopyJarScript")
}
@@ -67,6 +67,7 @@ public class BukkitConfigurationManager extends YamlConfigurationManager {
public void copyDefaults() {
// Create the default configuration file
plugin.createDefaultConfiguration(new File(plugin.getDataFolder(), "config.yml"), "config.yml");
plugin.createDefaultConfiguration(new File(plugin.getDataFolder(), "worlds/world/regions.yml"), "world/regions.yml");
}
@Override
@@ -55,6 +55,23 @@ public class BukkitUtil {
return item.getDurability() & 0x3F;
}
/**
* Get a blacklist target for the given block.
*
* @param block the block
* @param effectiveMaterial The effective material, if different
* @return a target
*/
public static Target createTarget(Block block, Material effectiveMaterial) {
checkNotNull(block);
checkNotNull(block.getType());
if (block.getType() == effectiveMaterial) {
return createTarget(block.getType());
} else {
return createTarget(effectiveMaterial);
}
}
/**
* Get a blacklist target for the given block.
*
@@ -215,7 +215,6 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
blockEnderDragonPortalCreation = getBoolean("mobs.block-enderdragon-portal-creation", false);
blockFireballExplosions = getBoolean("mobs.block-fireball-explosions", false);
blockFireballBlockDamage = getBoolean("mobs.block-fireball-block-damage", false);
blockWindChargeExplosions = getBoolean("mobs.block-windcharge-explosions", false);
antiWolfDumbness = getBoolean("mobs.anti-wolf-dumbness", false);
allowTamedSpawns = getBoolean("mobs.allow-tamed-spawns", true);
disableEndermanGriefing = getBoolean("mobs.disable-enderman-griefing", false);
@@ -257,8 +256,6 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
disableCreatureTurtleEggTrampling = getBoolean("turtle-egg.disable-creature-trampling", false);
disablePlayerTurtleEggTrampling = getBoolean("turtle-egg.disable-player-trampling", false);
disableCreatureSnifferEggTrampling = getBoolean("sniffer-egg.disable-creature-trampling", false);
disablePlayerSnifferEggTrampling = getBoolean("sniffer-egg.disable-player-trampling", false);
disallowedLightningBlocks = new HashSet<>(convertLegacyBlocks(getStringList("weather.prevent-lightning-strike-blocks", null)));
preventLightningFire = getBoolean("weather.disable-lightning-strike-fire", false);
@@ -283,7 +280,6 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
disableSculkGrowth = getBoolean("dynamics.disable-sculk-growth", false);
disableCropGrowth = getBoolean("dynamics.disable-crop-growth", false);
disableSoilDehydration = getBoolean("dynamics.disable-soil-dehydration", false);
disableSoilMoistureChange = getBoolean("dynamics.disable-soil-moisture-change", false);
disableCoralBlockFade = getBoolean("dynamics.disable-coral-block-fade", false);
disableCopperBlockFade = getBoolean("dynamics.disable-copper-block-fade", false);
allowedSnowFallOver = new HashSet<>(convertLegacyBlocks(getStringList("dynamics.snow-fall-blocks", null)));
@@ -266,7 +266,7 @@ public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
if (radius > 0) {
BlockVector3 spawnLoc = BukkitAdapter.asBlockVector(bWorld.getSpawnLocation());
return new ProtectedCuboidRegion("__spawn_protection__",
spawnLoc.subtract(radius, 0, radius).withY(world.getMinimumPoint().y()),
spawnLoc.subtract(radius, 0, radius).withY(world.getMinimumPoint().getY()),
spawnLoc.add(radius, 0, radius).withY(world.getMaxY()));
}
}
@@ -65,7 +65,6 @@ import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.worldguard.commands.GeneralCommands;
import com.sk89q.worldguard.commands.ProtectionCommands;
import com.sk89q.worldguard.commands.ToggleCommands;
import com.sk89q.worldguard.domains.registry.SimpleDomainRegistry;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.registry.SimpleFlagRegistry;
@@ -213,7 +212,6 @@ public class WorldGuardPlugin extends JavaPlugin {
});
((SimpleFlagRegistry) WorldGuard.getInstance().getFlagRegistry()).setInitialized(true);
((SimpleDomainRegistry) WorldGuard.getInstance().getDomainRegistry()).setInitialized(true);
// Enable metrics
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID); // bStats plugin id
@@ -96,7 +96,7 @@ public class BlacklistListener extends AbstractListener {
event.filter(target -> {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(target),
createTarget(target.getBlock())), false, false)) {
createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false)) {
return false;
} else if (!wcfg.getBlacklist().check(
new ItemDestroyWithBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(target),
@@ -124,7 +124,7 @@ public class BlacklistListener extends AbstractListener {
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
event.filter(target -> wcfg.getBlacklist().check(new BlockPlaceBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock())), false, false));
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false));
}
@EventHandler(ignoreCancelled = true)
@@ -143,7 +143,7 @@ public class BlacklistListener extends AbstractListener {
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
event.filter(target -> wcfg.getBlacklist().check(new BlockInteractBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock())), false, false));
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false));
}
@EventHandler(ignoreCancelled = true)
@@ -35,10 +35,6 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.potion.PotionType;
import java.util.ArrayList;
import java.util.List;
/**
* Handles blocked potions.
@@ -54,50 +50,43 @@ public class BlockedPotionsListener extends AbstractListener {
super(plugin);
}
private PotionEffectType getBlockedEffectByArrow(Arrow arrow, BukkitWorldConfiguration wcfg) {
List<PotionEffect> effects = new ArrayList<>();
PotionType potionType = arrow.getBasePotionType();
if (potionType != null) {
effects.addAll(potionType.getPotionEffects());
}
effects.addAll(arrow.getCustomEffects());
for (PotionEffect potionEffect : effects) {
if (wcfg.blockPotions.contains(potionEffect.getType())) {
return potionEffect.getType();
}
}
return null;
}
@EventHandler
public void onProjectile(DamageEntityEvent event) {
if (!(event.getOriginalEvent() instanceof EntityDamageByEntityEvent originalEvent)) {
return;
}
if (!Entities.isPotionArrow(originalEvent.getDamager())) {
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
PotionEffectType blockedEffect = null;
if (originalEvent.getDamager() instanceof SpectralArrow) {
if (wcfg.blockPotions.contains(PotionEffectType.GLOWING)) {
blockedEffect = PotionEffectType.GLOWING;
}
} else if (originalEvent.getDamager() instanceof Arrow arrow) {
blockedEffect = getBlockedEffectByArrow(arrow, wcfg);
}
if (blockedEffect != null) {
Player player = event.getCause().getFirstPlayer();
if (player != null) {
if (getPlugin().hasPermission(player, "worldguard.override.potions")) {
return;
if (event.getOriginalEvent() instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent originalEvent = (EntityDamageByEntityEvent) event.getOriginalEvent();
if (Entities.isPotionArrow(originalEvent.getDamager())) { // should take care of backcompat
BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
PotionEffectType blockedEffect = null;
if (originalEvent.getDamager() instanceof SpectralArrow) {
if (wcfg.blockPotions.contains(PotionEffectType.GLOWING)) {
blockedEffect = PotionEffectType.GLOWING;
}
} else if (originalEvent.getDamager() instanceof Arrow) {
Arrow tippedArrow = (Arrow) originalEvent.getDamager();
PotionEffectType baseEffect = tippedArrow.getBasePotionData().getType().getEffectType();
if (wcfg.blockPotions.contains(baseEffect)) {
blockedEffect = baseEffect;
} else {
for (PotionEffect potionEffect : tippedArrow.getCustomEffects()) {
if (wcfg.blockPotions.contains(potionEffect.getType())) {
blockedEffect = potionEffect.getType();
break;
}
}
}
}
if (blockedEffect != null) {
Player player = event.getCause().getFirstPlayer();
if (player != null) {
if (getPlugin().hasPermission(player, "worldguard.override.potions")) {
return;
}
player.sendMessage(ChatColor.RED + "Sorry, arrows with "
+ blockedEffect.getName() + " are presently disabled.");
}
event.setCancelled(true);
}
player.sendMessage(ChatColor.RED + "Sorry, arrows with "
+ blockedEffect.getName() + " are presently disabled.");
}
event.setCancelled(true);
}
}
@@ -115,20 +104,25 @@ public class BlockedPotionsListener extends AbstractListener {
if (!wcfg.blockPotions.isEmpty()) {
PotionEffectType blockedEffect = null;
if (!(item.getItemMeta() instanceof PotionMeta meta)) {
return;
PotionMeta meta;
if (item.getItemMeta() instanceof PotionMeta) {
meta = ((PotionMeta) item.getItemMeta());
} else {
return; // ok...?
}
// Find the first blocked effect
List<PotionEffect> effects = new ArrayList<>();
if (meta.getBasePotionType() != null) {
effects.addAll(meta.getBasePotionType().getPotionEffects());
PotionEffectType baseEffect = meta.getBasePotionData().getType().getEffectType();
if (wcfg.blockPotions.contains(baseEffect)) {
blockedEffect = baseEffect;
}
effects.addAll(meta.getCustomEffects());
for (PotionEffect potionEffect : effects) {
if (wcfg.blockPotions.contains(potionEffect.getType())) {
blockedEffect = potionEffect.getType();
break;
if (blockedEffect == null && meta.hasCustomEffects()) {
for (PotionEffect effect : meta.getCustomEffects()) {
if (wcfg.blockPotions.contains(effect.getType())) {
blockedEffect = effect.getType();
break;
}
}
}
@@ -101,14 +101,12 @@ public class BuildPermissionListener extends AbstractListener {
if (rootCause instanceof Player) {
final Player player = (Player) rootCause;
final Material material = event.getEffectiveMaterial();
boolean blocked = event.filter(loc -> {
String blacklistName = loc.getBlock().getType().name().toLowerCase();
return hasBuildPermission(player, "block." + blacklistName + ".interact") ||
hasBuildPermission(player, "block.interact." + blacklistName);
}, true);
if (blocked && !event.isSilent()) {
if (!hasBuildPermission(player, "block." + material.name().toLowerCase() + ".interact")
&& !hasBuildPermission(player, "block.interact." + material.name().toLowerCase())) {
tellErrorMessage(player, event.getWorld());
event.setCancelled(true);
}
}
}
@@ -22,6 +22,7 @@ package com.sk89q.worldguard.bukkit.listener;
import static com.sk89q.worldguard.bukkit.cause.Cause.create;
import com.destroystokyo.paper.event.entity.EntityZapEvent;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.cause.Cause;
import com.sk89q.worldguard.bukkit.event.DelegateEvent;
@@ -44,13 +45,15 @@ import com.sk89q.worldguard.bukkit.util.Blocks;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.worldguard.bukkit.util.Materials;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import io.papermc.lib.PaperLib;
import io.papermc.paper.event.player.PlayerOpenSignEvent;
import org.bukkit.Bukkit;
import org.bukkit.Effect;
import org.bukkit.ExplosionResult;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
@@ -67,8 +70,6 @@ import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Waterlogged;
import org.bukkit.block.data.type.Dispenser;
import org.bukkit.entity.AreaEffectCloud;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.BreezeWindCharge;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
@@ -82,7 +83,6 @@ import org.bukkit.entity.Painting;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.entity.WindCharge;
import org.bukkit.entity.minecart.HopperMinecart;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
@@ -116,10 +116,8 @@ import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.EntityKnockbackByEntityEvent;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.entity.EntityTameEvent;
import org.bukkit.event.entity.EntityUnleashEvent;
@@ -152,6 +150,7 @@ import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.util.Vector;
@@ -182,11 +181,9 @@ public class EventAbstractionListener extends AbstractListener {
public void registerEvents() {
super.registerEvents();
PluginManager pm = getPlugin().getServer().getPluginManager();
if (PaperLib.isPaper()) {
PluginManager pm = getPlugin().getServer().getPluginManager();
pm.registerEvents(new EventAbstractionListener.PaperListener(), getPlugin());
} else {
pm.registerEvents(new EventAbstractionListener.SpigotListener(), getPlugin());
}
}
@@ -226,8 +223,8 @@ public class EventAbstractionListener extends AbstractListener {
Events.fireToCancel(event, new BreakBlockEvent(event, create(event.getPlayer()), previousState.getLocation(), previousState.getType()));
}
ItemStack itemStack = event.getItemInHand();
if (!event.isCancelled() && itemStack.getType() != Material.AIR) {
if (!event.isCancelled()) {
ItemStack itemStack = new ItemStack(event.getBlockPlaced().getType(), 1);
Events.fireToCancel(event, new UseItemEvent(event, create(event.getPlayer()), event.getPlayer().getWorld(), itemStack));
}
@@ -331,10 +328,10 @@ public class EventAbstractionListener extends AbstractListener {
// Fire two events: one as BREAK and one as PLACE
if (toType != Material.AIR && fromType != Material.AIR) {
BreakBlockEvent breakDelegate = new BreakBlockEvent(event, cause, block);
setDelegateEventMaterialOptions(breakDelegate, fromType, toType);
BreakBlockEvent breakDelagate = new BreakBlockEvent(event, cause, block);
setDelegateEventMaterialOptions(breakDelagate, fromType, toType);
boolean denied;
if (!(denied = Events.fireToCancel(event, breakDelegate))) {
if (!(denied = Events.fireToCancel(event, breakDelagate))) {
PlaceBlockEvent placeDelegate = new PlaceBlockEvent(event, cause, block.getLocation(), toType);
setDelegateEventMaterialOptions(placeDelegate, fromType, toType);
denied = Events.fireToCancel(event, placeDelegate);
@@ -362,29 +359,10 @@ public class EventAbstractionListener extends AbstractListener {
}
private static <T extends EntityEvent & Cancellable> void handleKnockback(T event, Entity damager) {
final DamageEntityEvent eventToFire = new DamageEntityEvent(event, create(damager), event.getEntity());
if (damager instanceof BreezeWindCharge) {
eventToFire.getRelevantFlags().add(Flags.BREEZE_WIND_CHARGE);
} else if (damager instanceof WindCharge) {
eventToFire.getRelevantFlags().add(Flags.WIND_CHARGE_BURST);
}
Events.fireToCancel(event, eventToFire);
}
@SuppressWarnings("UnstableApiUsage")
@EventHandler(ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
Entity entity = event.getEntity();
if (event.getExplosionResult() == ExplosionResult.TRIGGER_BLOCK) {
UseBlockEvent useEvent = new UseBlockEvent(event, create(entity), event.getLocation().getWorld(), event.blockList(), Material.AIR);
useEvent.getRelevantFlags().add(Entities.getExplosionFlag(entity));
useEvent.setSilent(true);
Events.fireBulkEventToCancel(event, useEvent);
} else if (event.getExplosionResult() == ExplosionResult.DESTROY || event.getExplosionResult() == ExplosionResult.DESTROY_WITH_DECAY) {
Events.fireBulkEventToCancel(event, new BreakBlockEvent(event, create(entity), event.getLocation().getWorld(), event.blockList(), Material.AIR));
}
Events.fireBulkEventToCancel(event, new BreakBlockEvent(event, create(entity), event.getLocation().getWorld(), event.blockList(), Material.AIR));
if (entity instanceof Creeper) {
Cause.untrackParentCause(entity);
}
@@ -481,9 +459,7 @@ public class EventAbstractionListener extends AbstractListener {
switch (event.getAction()) {
case PHYSICAL:
if (event.useInteractedBlock() != Result.DENY) {
if (clicked.getType() == Material.FARMLAND ||
clicked.getType() == Material.TURTLE_EGG ||
clicked.getType() == Material.SNIFFER_EGG) {
if (clicked.getType() == Material.FARMLAND || clicked.getType() == Material.TURTLE_EGG) {
BreakBlockEvent breakDelagate = new BreakBlockEvent(event, cause, clicked);
breakDelagate.setSilent(true);
breakDelagate.getRelevantFlags().add(Flags.TRAMPLE_BLOCKS);
@@ -509,7 +485,7 @@ public class EventAbstractionListener extends AbstractListener {
firedEvent.setSilent(true);
}
interactDebounce.debounce(clicked, event.getPlayer(), event, firedEvent);
if (event.useInteractedBlock() == Result.DENY && !firedEvent.isSilent()) {
if (event.useInteractedBlock() == Result.DENY) {
playDenyEffect(player, clicked.getLocation().add(0, 1, 0));
}
}
@@ -603,7 +579,7 @@ public class EventAbstractionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBlockFertilize(BlockFertilizeEvent event) {
if (event.getBlocks().isEmpty()) return;
if (event.getBlocks().isEmpty()) return;
Cause cause = create(event.getPlayer(), event.getBlock());
Events.fireToCancel(event, new PlaceBlockEvent(event, cause, event.getBlock().getWorld(), event.getBlocks()));
}
@@ -629,7 +605,9 @@ public class EventAbstractionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
if (Events.fireToCancel(event, new PlaceBlockEvent(event, create(event.getPlayer()), event.getBlock()))) {
Events.fireToCancel(event, new UseBlockEvent(event, create(event.getPlayer()), event.getBlock()));
if (event.isCancelled()) {
playDenyEffect(event.getPlayer(), event.getBlock().getLocation().add(0.5, 0.5, 0.5));
}
}
@@ -663,7 +641,7 @@ public class EventAbstractionListener extends AbstractListener {
Events.fireToCancel(event, new PlaceBlockEvent(event, create(player), blockAffected.getLocation(), blockMaterial).setAllowed(allowed));
Events.fireToCancel(event, new UseItemEvent(event, create(player), player.getWorld(), item).setAllowed(allowed));
if (event.isCancelled()) {
if (event.isCancelled() && !isOverridingFlagAllow("safe-fluids", blockAffected.getLocation())) {
playDenyEffect(event.getPlayer(), blockAffected.getLocation().add(0.5, 0.5, 0.5));
}
}
@@ -683,11 +661,23 @@ public class EventAbstractionListener extends AbstractListener {
Events.fireToCancel(event, new BreakBlockEvent(event, create(player), blockAffected).setAllowed(allowed));
Events.fireToCancel(event, new UseItemEvent(event, create(player), player.getWorld(), item).setAllowed(allowed));
if (event.isCancelled()) {
if (event.isCancelled() && !isOverridingFlagAllow("safe-fluids", blockAffected.getLocation())) {
playDenyEffect(event.getPlayer(), blockAffected.getLocation().add(0.5, 0.5, 0.5));
}
}
// Lets partner plugins (e.g. FireFight-OG) suppress WG's deny effect when a
// higher-priority listener will re-allow the action via a registered StateFlag.
private static boolean isOverridingFlagAllow(String flagName, Location location) {
Flag<?> flag = WorldGuard.getInstance().getFlagRegistry().get(flagName);
if (!(flag instanceof StateFlag)) {
return false;
}
ApplicableRegionSet set = WorldGuard.getInstance().getPlatform().getRegionContainer()
.createQuery().getApplicableRegions(BukkitAdapter.adapt(location));
return set.testState(null, (StateFlag) flag);
}
// TODO: Handle EntityPortalEnterEvent
//-------------------------------------------------------------------------
@@ -769,7 +759,7 @@ public class EventAbstractionListener extends AbstractListener {
if (event.isCancelled() && remover instanceof Player) {
playDenyEffect((Player) remover, event.getEntity().getLocation());
}
} else if (event.getCause() == HangingBreakEvent.RemoveCause.EXPLOSION) {
} else if (event.getCause() == HangingBreakEvent.RemoveCause.EXPLOSION){
DestroyEntityEvent destroyEntityEvent = new DestroyEntityEvent(event, Cause.unknown(), event.getEntity());
destroyEntityEvent.getRelevantFlags().add(Flags.OTHER_EXPLOSION);
if (event.getEntity() instanceof ItemFrame) {
@@ -914,19 +904,11 @@ public class EventAbstractionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onEntityCombust(EntityCombustEvent event) {
if (event instanceof EntityCombustByBlockEvent combustByBlockEvent) {
if (event instanceof EntityCombustByBlockEvent) {
// at the time of writing, spigot is throwing null for the event's combuster. this causes lots of issues downstream.
// whenever (i mean if ever) it is fixed, use getCombuster again instead of the current block
Block combuster = combustByBlockEvent.getCombuster();
Events.fireToCancel(event, new DamageEntityEvent(event,
create(combuster == null ? event.getEntity().getLocation().getBlock() : combuster), event.getEntity()));
Events.fireToCancel(event, new DamageEntityEvent(event, create(event.getEntity().getLocation().getBlock()), event.getEntity()));
} else if (event instanceof EntityCombustByEntityEvent) {
if (event.getEntity() instanceof Arrow) {
// this only happens from the Flame enchant. igniting arrows in other ways (eg with lava) doesn't even
// throw the combust event, not even the CombustByBlock event... they're also very buggy and don't even
// show as lit on the client consistently
return;
}
Events.fireToCancel(event, new DamageEntityEvent(event, create(((EntityCombustByEntityEvent) event).getCombuster()), event.getEntity()));
}
}
@@ -1042,6 +1024,7 @@ public class EventAbstractionListener extends AbstractListener {
// Fire item interaction event
Events.fireToCancel(event, new UseItemEvent(event, cause, world, potion.getItem()));
// Fire entity interaction event
if (!event.isCancelled()) {
int blocked = 0;
@@ -1053,11 +1036,8 @@ public class EventAbstractionListener extends AbstractListener {
? new DamageEntityEvent(event, cause, affected) :
new UseEntityEvent(event, cause, affected);
// Consider extra relevant flags
// Consider the potion splash flag
delegate.getRelevantFlags().add(Flags.POTION_SPLASH);
if (potion.getShooter() instanceof LivingEntity shooter && !(shooter instanceof Player) && affected instanceof Player) {
delegate.getRelevantFlags().add(Flags.MOB_DAMAGE);
}
if (Events.fireAndTestCancel(delegate)) {
event.setIntensity(affected, 0);
@@ -1123,9 +1103,9 @@ public class EventAbstractionListener extends AbstractListener {
public void onLingeringApply(AreaEffectCloudApplyEvent event) {
AreaEffectCloud entity = event.getEntity();
List<PotionEffect> effects = new ArrayList<>();
List<PotionEffect> baseEffectTypes = entity.getBasePotionType() == null ? null : entity.getBasePotionType().getPotionEffects();
if (baseEffectTypes != null) {
effects.addAll(baseEffectTypes);
PotionEffectType baseEffectType = entity.getBasePotionData().getType().getEffectType();
if (baseEffectType != null) {
effects.add(new PotionEffect(baseEffectType, 0, 0));
}
if (entity.hasCustomEffects()) {
effects.addAll(entity.getCustomEffects());
@@ -1139,7 +1119,7 @@ public class EventAbstractionListener extends AbstractListener {
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) {
public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event){
onPlayerInteractEntity(event);
}
@@ -1210,7 +1190,7 @@ public class EventAbstractionListener extends AbstractListener {
if (item != null && item.getType() == Material.END_CRYSTAL) { /*&& placed.getType() == Material.BEDROCK) {*/ // in vanilla you can only place them on bedrock but who knows what plugins will add
// may be overprotective as a result, but better than being underprotective
Events.fireToCancel(event, new SpawnEntityEvent(event, cause, placed.getLocation().add(0.5, 0, 0.5), EntityType.END_CRYSTAL));
Events.fireToCancel(event, new SpawnEntityEvent(event, cause, placed.getLocation().add(0.5, 0, 0.5), EntityType.ENDER_CRYSTAL));
return;
}
@@ -1250,9 +1230,9 @@ public class EventAbstractionListener extends AbstractListener {
useBlockEvent.setAllowed(true);
}
Events.fireToCancel(originalEvent, useBlockEvent);
} else if (holder instanceof DoubleChest doubleChest) {
InventoryHolder left = PaperLib.isPaper() ? doubleChest.getLeftSide(false) : doubleChest.getLeftSide();
InventoryHolder right = PaperLib.isPaper() ? doubleChest.getRightSide(false) : doubleChest.getRightSide();
} else if (holder instanceof DoubleChest) {
InventoryHolder left = ((DoubleChest) holder).getLeftSide();
InventoryHolder right = ((DoubleChest) holder).getRightSide();
if (left instanceof Chest) {
Events.fireToCancel(originalEvent, new UseBlockEvent(originalEvent, cause, ((Chest) left).getBlock()));
}
@@ -1298,31 +1278,10 @@ public class EventAbstractionListener extends AbstractListener {
}
}
private static class PaperListener implements Listener {
private class PaperListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onEntityTransform(EntityZapEvent event) {
Events.fireToCancel(event, new DamageEntityEvent(event, create(event.getBolt()), event.getEntity()));
}
@EventHandler(ignoreCancelled = true)
public void onSignOpen(PlayerOpenSignEvent event) {
if (event.getCause() == PlayerOpenSignEvent.Cause.INTERACT) {
// other cases are handled by other events
Events.fireToCancel(event, new UseBlockEvent(event, create(event.getPlayer()), event.getSign().getBlock()));
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityKnockbackByEntity(com.destroystokyo.paper.event.entity.EntityKnockbackByEntityEvent event) {
handleKnockback(event, event.getHitBy());
}
}
@SuppressWarnings("removal")
private static class SpigotListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onEntityKnockbackByEntity(EntityKnockbackByEntityEvent event) {
handleKnockback(event, event.getSourceEntity());
}
}
}
@@ -25,6 +25,7 @@ import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.session.Session;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.AbstractHorse;
@@ -33,13 +34,14 @@ import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityMountEvent;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.plugin.PluginManager;
import org.bukkit.util.Vector;
import org.spigotmc.event.entity.EntityMountEvent;
public class PlayerMoveListener extends AbstractListener {
@@ -52,10 +54,13 @@ public class PlayerMoveListener extends AbstractListener {
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().usePlayerMove) {
PluginManager pm = getPlugin().getServer().getPluginManager();
pm.registerEvents(this, getPlugin());
if (PaperLib.isSpigot()) {
pm.registerEvents(new EntityMountListener(), getPlugin());
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
LocalPlayer player = getPlugin().wrapPlayer(event.getPlayer());
@@ -147,14 +152,16 @@ public class PlayerMoveListener extends AbstractListener {
session.uninitialize(localPlayer);
}
@EventHandler
public void onEntityMount(EntityMountEvent event) {
Entity entity = event.getEntity();
if (entity instanceof Player) {
LocalPlayer player = getPlugin().wrapPlayer((Player) entity);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
if (null != session.testMoveTo(player, BukkitAdapter.adapt(event.getMount().getLocation()), MoveType.EMBARK, true)) {
event.setCancelled(true);
private class EntityMountListener implements Listener {
@EventHandler
public void onEntityMount(EntityMountEvent event) {
Entity entity = event.getEntity();
if (entity instanceof Player) {
LocalPlayer player = getPlugin().wrapPlayer((Player) entity);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
if (null != session.testMoveTo(player, BukkitAdapter.adapt(event.getMount().getLocation()), MoveType.EMBARK, true)) {
event.setCancelled(true);
}
}
}
}
@@ -69,7 +69,7 @@ public class RegionFlagsListener extends AbstractListener {
}
}
if (event.getCause().find(EntityType.SNOW_GOLEM) != null) {
if (event.getCause().find(EntityType.SNOWMAN) != null) {
event.filter(testState(query, Flags.SNOWMAN_TRAILS), false);
}
@@ -94,13 +94,15 @@ public class RegionFlagsListener extends AbstractListener {
if (event.getCause().find(EntityType.CREEPER) != null) { // Creeper
event.filter(testState(query, Flags.CREEPER_EXPLOSION), config.explosionFlagCancellation);
// Strips blocks from the blast without cancelling it, so entity damage still lands.
event.filter(testState(query, Flags.CREEPER_BLOCK_DAMAGE), false);
}
if (event.getCause().find(EntityType.ENDER_DRAGON) != null) { // Enderdragon
event.filter(testState(query, Flags.ENDERDRAGON_BLOCK_DAMAGE), config.explosionFlagCancellation);
}
if (event.getCause().find(EntityType.END_CRYSTAL) != null) { // EnderCrystal
if (event.getCause().find(EntityType.ENDER_CRYSTAL) != null) { // EnderCrystal
event.filter(testState(query, Flags.OTHER_EXPLOSION), config.explosionFlagCancellation);
}
@@ -61,7 +61,6 @@ import org.bukkit.entity.Tameable;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerTakeLecternBookEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
@@ -174,7 +173,7 @@ public class RegionProtectionListener extends AbstractListener {
/* Flint and steel, fire charge, etc. */
if (Materials.isFire(type)) {
Block block = event.getCause().getFirstBlock();
boolean fire = block != null && Materials.isFire(block.getType());
boolean fire = block != null && Materials.isFire(type);
boolean lava = block != null && Materials.isLava(block.getType());
List<StateFlag> flags = new ArrayList<>();
flags.add(Flags.BLOCK_PLACE);
@@ -219,7 +218,7 @@ public class RegionProtectionListener extends AbstractListener {
String what;
/* TNT */
if (event.getCause().find(EntityType.TNT, EntityType.TNT_MINECART) != null) {
if (event.getCause().find(EntityType.PRIMED_TNT, EntityType.MINECART_TNT) != null) {
canBreak = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.BLOCK_BREAK, Flags.TNT));
what = "use dynamite";
@@ -245,13 +244,13 @@ public class RegionProtectionListener extends AbstractListener {
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
final Material type = event.getEffectiveMaterial();
final RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
final RegionAssociable associable = createRegionAssociable(event.getCause());
event.filter((Predicate<Location>) target -> {
boolean canUse;
String what;
final Material type = target.getBlock().getType();
/* Saplings, etc. */
if (Materials.isConsideredBuildingIfUsed(type)) {
@@ -411,15 +410,13 @@ public class RegionProtectionListener extends AbstractListener {
canUse = event.getRelevantFlags().isEmpty() || query.queryState(BukkitAdapter.adapt(target), associable, combine(event)) != State.DENY;
what = "use that";
/* Paintings, item frames, etc. */
} else if (Entities.isConsideredBuildingIfUsed(entity)
// weird case since sneak+interact is chest access and not ride
|| type == EntityType.CHEST_BOAT && event.getOriginalEvent() instanceof InventoryOpenEvent) {
} else if (Entities.isConsideredBuildingIfUsed(entity)) {
if ((type == EntityType.ITEM_FRAME || type == EntityType.GLOW_ITEM_FRAME)
&& event.getCause().getFirstPlayer() != null
&& ((ItemFrame) entity).getItem().getType() != Material.AIR) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.ITEM_FRAME_ROTATE));
what = "change that";
} else if (Entities.isMinecart(type) || type == EntityType.CHEST_BOAT) {
} else if (Entities.isMinecart(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.CHEST_ACCESS));
what = "open that";
} else {
@@ -56,7 +56,6 @@ import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.MoistureChangeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
@@ -471,6 +470,7 @@ public class WorldGuardBlockListener extends AbstractListener {
public void onBlockForm(BlockFormEvent event) {
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
@@ -521,18 +521,6 @@ public class WorldGuardBlockListener extends AbstractListener {
return;
}
}
if (Materials.isUnwaxedCopper(event.getBlock().getType())) {
if (wcfg.disableCopperBlockFade) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.COPPER_FADE))) {
event.setCancelled(true);
return;
}
}
}
/*
@@ -709,6 +697,16 @@ public class WorldGuardBlockListener extends AbstractListener {
event.setCancelled(true);
return;
}
} else if (Materials.isUnwaxedCopper(event.getBlock().getType())) {
if (wcfg.disableCopperBlockFade) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.COPPER_FADE))) {
event.setCancelled(true);
return;
}
}
}
@@ -727,24 +725,4 @@ public class WorldGuardBlockListener extends AbstractListener {
}
}
/**
* Called when the moisture level of a block changes
*/
@EventHandler(ignoreCancelled = true)
public void onMoistureChange(MoistureChangeEvent event) {
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.disableSoilMoistureChange) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.MOISTURE_CHANGE))) {
event.setCancelled(true);
}
}
}
}
@@ -44,7 +44,6 @@ import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.AbstractWindCharge;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EnderCrystal;
@@ -61,7 +60,6 @@ import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.WindCharge;
import org.bukkit.entity.Wither;
import org.bukkit.entity.WitherSkull;
import org.bukkit.entity.Wolf;
@@ -122,10 +120,6 @@ public class WorldGuardEntityListener extends AbstractListener {
event.setCancelled(true);
return;
}
if (block.getType() == Material.SNIFFER_EGG && wcfg.disableCreatureSnifferEggTrampling) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH)
@@ -313,17 +307,13 @@ public class WorldGuardEntityListener extends AbstractListener {
return;
}
}
if (event.getDamager() instanceof Fireball fireball) {
if (event.getDamager() instanceof Fireball) {
Fireball fireball = (Fireball) event.getDamager();
if (fireball instanceof WitherSkull) {
if (wcfg.blockWitherSkullExplosions) {
event.setCancelled(true);
return;
}
} else if (fireball instanceof AbstractWindCharge) {
if (wcfg.blockWindChargeExplosions) {
event.setCancelled(true);
return;
}
} else {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
@@ -332,7 +322,7 @@ public class WorldGuardEntityListener extends AbstractListener {
}
if (wcfg.useRegions) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
if (!query.testState(localPlayer.getLocation(), localPlayer, Entities.getExplosionFlag(event.getDamager())) && wcfg.explosionFlagCancellation) {
if (!query.testState(localPlayer.getLocation(), localPlayer, Flags.GHAST_FIREBALL) && wcfg.explosionFlagCancellation) {
event.setCancelled(true);
return;
}
@@ -489,11 +479,6 @@ public class WorldGuardEntityListener extends AbstractListener {
event.blockList().clear();
return;
}
} else if (ent instanceof AbstractWindCharge) {
if (wcfg.blockWindChargeExplosions) {
event.setCancelled(true);
return;
}
} else {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
@@ -504,10 +489,10 @@ public class WorldGuardEntityListener extends AbstractListener {
return;
}
}
if (wcfg.useRegions && !(ent instanceof WindCharge)) {
// allow wither skull blocking since there is no dedicated flag atm
if (wcfg.useRegions) {
for (Block block : event.blockList()) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.testState(BukkitAdapter.adapt(block.getLocation()), null, Entities.getExplosionFlag(ent))) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation())).testState(null, Flags.GHAST_FIREBALL)) {
event.blockList().clear();
if (wcfg.explosionFlagCancellation) event.setCancelled(true);
return;
@@ -525,8 +510,8 @@ public class WorldGuardEntityListener extends AbstractListener {
}
if (wcfg.useRegions) {
for (Block block : event.blockList()) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.testState(BukkitAdapter.adapt(block.getLocation()), null, Flags.WITHER_DAMAGE)) {
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(block.getLocation()),
(RegionAssociable) null, Flags.WITHER_DAMAGE))) {
event.blockList().clear();
event.setCancelled(true);
return;
@@ -541,8 +526,7 @@ public class WorldGuardEntityListener extends AbstractListener {
}
if (wcfg.useRegions) {
for (Block block : event.blockList()) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.testState(BukkitAdapter.adapt(block.getLocation()), null, Flags.OTHER_EXPLOSION)) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation())).testState(null, Flags.OTHER_EXPLOSION)) {
event.blockList().clear();
if (wcfg.explosionFlagCancellation) event.setCancelled(true);
return;
@@ -551,6 +535,7 @@ public class WorldGuardEntityListener extends AbstractListener {
}
}
if (wcfg.signChestProtection) {
for (Block block : event.blockList()) {
if (wcfg.isChestProtected(BukkitAdapter.adapt(block.getLocation()))) {
@@ -597,17 +582,12 @@ public class WorldGuardEntityListener extends AbstractListener {
event.setCancelled(true);
return;
}
} else if (event.getEntityType() == EntityType.TNT
|| event.getEntityType() == EntityType.TNT_MINECART) {
} else if (event.getEntityType() == EntityType.PRIMED_TNT
|| event.getEntityType() == EntityType.MINECART_TNT) {
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
} else if (event instanceof AbstractWindCharge) {
if (wcfg.blockWindChargeExplosions) {
event.setCancelled(true);
return;
}
}
}
@@ -623,7 +603,7 @@ public class WorldGuardEntityListener extends AbstractListener {
WorldConfiguration wcfg = getWorldConfig(event.getEntity().getWorld());
// allow spawning of creatures from plugins
if (!wcfg.blockPluginSpawning && Entities.isPluginSpawning(event.getSpawnReason())) {
if (!wcfg.blockPluginSpawning && event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM) {
return;
}
@@ -307,10 +307,6 @@ public class WorldGuardPlayerListener extends AbstractListener {
event.setCancelled(true);
return;
}
if (type == Material.SNIFFER_EGG && wcfg.disablePlayerSnifferEggTrampling) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGHEST)
@@ -350,11 +346,6 @@ public class WorldGuardPlayerListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerTeleport(PlayerTeleportEvent event) {
if (event.getTo() == null) {
// The target location for PlayerTeleportEvents can be null.
// Those events will be ignored by the server, so we can ignore them too.
return;
}
Player player = event.getPlayer();
if (com.sk89q.worldguard.bukkit.util.Entities.isNPC(player)) return;
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
@@ -54,7 +54,7 @@ public class InventoryMoveItemEventDebounce extends AbstractEventDebounce<Key> {
if (holder instanceof BlockState blockState) {
return new BlockMaterialKey(blockState);
} else if (holder instanceof DoubleChest doubleChest) {
InventoryHolder left = PaperLib.isPaper() ? doubleChest.getLeftSide(false) : doubleChest.getLeftSide();
InventoryHolder left = doubleChest.getLeftSide();
if (left instanceof Chest chest) {
return new BlockMaterialKey(chest);
} else {
@@ -19,21 +19,15 @@
package com.sk89q.worldguard.bukkit.util;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import org.bukkit.entity.Allay;
import org.bukkit.entity.Ambient;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.BreezeWindCharge;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EnderCrystal;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Flying;
import org.bukkit.entity.Hanging;
import org.bukkit.entity.LivingEntity;
@@ -49,14 +43,10 @@ import org.bukkit.entity.Steerable;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Vehicle;
import org.bukkit.entity.WindCharge;
import org.bukkit.entity.Wither;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.projectiles.ProjectileSource;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public final class Entities {
@@ -136,8 +126,8 @@ public final class Entities {
*/
public static boolean isMinecart(EntityType type) {
return switch(type) {
case MINECART, CHEST_MINECART, COMMAND_BLOCK_MINECART, FURNACE_MINECART,
HOPPER_MINECART, SPAWNER_MINECART, TNT_MINECART -> true;
case MINECART, MINECART_CHEST, MINECART_COMMAND, MINECART_FURNACE,
MINECART_HOPPER, MINECART_MOB_SPAWNER, MINECART_TNT -> true;
default -> false;
};
}
@@ -240,38 +230,4 @@ public final class Entities {
public static boolean isAoECloud(EntityType type) {
return type == EntityType.AREA_EFFECT_CLOUD;
}
/**
* Check whether the spawn reason should be considered as a "plugin spawning".
* This is true for custom creations or the summon command.
*
* @param spawnReason the reason
* @return true if considered plugin spawning
*/
public static boolean isPluginSpawning(CreatureSpawnEvent.SpawnReason spawnReason) {
return switch (spawnReason) {
case CUSTOM, COMMAND -> true;
default -> false;
};
}
/**
* Get the explosion flag relevant for an entity type.
* @param entity the entity
* @return the relevant StateFlag or OTHER_EXPLOSION if none is matching
*/
public static @Nonnull StateFlag getExplosionFlag(Entity entity) {
return switch (entity) {
case BreezeWindCharge breezeWindCharge -> Flags.BREEZE_WIND_CHARGE;
case WindCharge windCharge -> Flags.WIND_CHARGE_BURST;
case Firework firework -> Flags.FIREWORK_DAMAGE;
case Fireball fireball -> Flags.GHAST_FIREBALL;
case Wither wither -> Flags.WITHER_DAMAGE;
case Creeper creeper -> Flags.CREEPER_EXPLOSION;
case TNTPrimed tnt -> Flags.TNT;
case ExplosiveMinecart minecart -> Flags.TNT;
case EnderDragon dragon -> Flags.ENDERDRAGON_BLOCK_DAMAGE;
case null, default -> Flags.OTHER_EXPLOSION;
};
}
}
@@ -53,9 +53,9 @@ public final class Materials {
private static final Set<PotionEffectType> DAMAGE_EFFECTS = new HashSet<>();
private static void putMaterialTag(Tag<Material> tag, Integer value) {
if (tag == null) return;
tag.getValues().forEach(mat -> MATERIAL_FLAGS.put(mat, value));
}
private static Tag<Material> SIGNS_TAG;
static {
ENTITY_ITEMS.put(EntityType.PAINTING, Material.PAINTING);
@@ -63,26 +63,22 @@ public final class Materials {
ENTITY_ITEMS.put(EntityType.SNOWBALL, Material.SNOWBALL);
ENTITY_ITEMS.put(EntityType.FIREBALL, Material.FIRE_CHARGE);
ENTITY_ITEMS.put(EntityType.ENDER_PEARL, Material.ENDER_PEARL);
ENTITY_ITEMS.put(EntityType.EXPERIENCE_BOTTLE, Material.EXPERIENCE_BOTTLE);
ENTITY_ITEMS.put(EntityType.THROWN_EXP_BOTTLE, Material.EXPERIENCE_BOTTLE);
ENTITY_ITEMS.put(EntityType.ITEM_FRAME, Material.ITEM_FRAME);
ENTITY_ITEMS.put(EntityType.GLOW_ITEM_FRAME, Material.GLOW_ITEM_FRAME);
ENTITY_ITEMS.put(EntityType.TNT, Material.TNT);
ENTITY_ITEMS.put(EntityType.FIREWORK_ROCKET, Material.FIREWORK_ROCKET);
ENTITY_ITEMS.put(EntityType.COMMAND_BLOCK_MINECART, Material.COMMAND_BLOCK_MINECART);
ENTITY_ITEMS.put(EntityType.PRIMED_TNT, Material.TNT);
ENTITY_ITEMS.put(EntityType.FIREWORK, Material.FIREWORK_ROCKET);
ENTITY_ITEMS.put(EntityType.MINECART_COMMAND, Material.COMMAND_BLOCK_MINECART);
ENTITY_ITEMS.put(EntityType.BOAT, Material.OAK_BOAT);
ENTITY_ITEMS.put(EntityType.MINECART, Material.MINECART);
ENTITY_ITEMS.put(EntityType.CHEST_MINECART, Material.CHEST_MINECART);
ENTITY_ITEMS.put(EntityType.FURNACE_MINECART, Material.FURNACE_MINECART);
ENTITY_ITEMS.put(EntityType.TNT_MINECART, Material.TNT_MINECART);
ENTITY_ITEMS.put(EntityType.HOPPER_MINECART, Material.HOPPER_MINECART);
ENTITY_ITEMS.put(EntityType.POTION, Material.POTION);
ENTITY_ITEMS.put(EntityType.MINECART_CHEST, Material.CHEST_MINECART);
ENTITY_ITEMS.put(EntityType.MINECART_FURNACE, Material.FURNACE_MINECART);
ENTITY_ITEMS.put(EntityType.MINECART_TNT, Material.TNT_MINECART);
ENTITY_ITEMS.put(EntityType.MINECART_HOPPER, Material.HOPPER_MINECART);
ENTITY_ITEMS.put(EntityType.SPLASH_POTION, Material.POTION);
ENTITY_ITEMS.put(EntityType.EGG, Material.EGG);
ENTITY_ITEMS.put(EntityType.ARMOR_STAND, Material.ARMOR_STAND);
ENTITY_ITEMS.put(EntityType.END_CRYSTAL, Material.END_CRYSTAL);
// preset some tags to a default value, override some of them:
putMaterialTag(Tag.DOORS, MODIFIED_ON_RIGHT);
putMaterialTag(Tag.TRAPDOORS, MODIFIED_ON_RIGHT);
ENTITY_ITEMS.put(EntityType.ENDER_CRYSTAL, Material.END_CRYSTAL);
MATERIAL_FLAGS.put(Material.AIR, 0);
MATERIAL_FLAGS.put(Material.STONE, 0);
@@ -104,7 +100,7 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.DETECTOR_RAIL, 0);
MATERIAL_FLAGS.put(Material.STICKY_PISTON, 0);
MATERIAL_FLAGS.put(Material.COBWEB, 0);
MATERIAL_FLAGS.put(Material.SHORT_GRASS, 0);
MATERIAL_FLAGS.put(Material.GRASS, 0);
MATERIAL_FLAGS.put(Material.DEAD_BUSH, 0);
MATERIAL_FLAGS.put(Material.PISTON, 0);
MATERIAL_FLAGS.put(Material.PISTON_HEAD, 0);
@@ -154,6 +150,12 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.CAKE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.REPEATER, MODIFIED_ON_RIGHT);
// MATERIAL_FLAGS.put(Material.STAINED_GLASS, 0);
MATERIAL_FLAGS.put(Material.ACACIA_TRAPDOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BIRCH_TRAPDOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DARK_OAK_TRAPDOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.JUNGLE_TRAPDOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.OAK_TRAPDOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.SPRUCE_TRAPDOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.INFESTED_STONE, 0);
MATERIAL_FLAGS.put(Material.INFESTED_STONE_BRICKS, 0);
MATERIAL_FLAGS.put(Material.INFESTED_MOSSY_STONE_BRICKS, 0);
@@ -225,6 +227,11 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.IRON_TRAPDOOR, 0);
MATERIAL_FLAGS.put(Material.RED_SANDSTONE, 0);
MATERIAL_FLAGS.put(Material.RED_SANDSTONE_STAIRS, 0);
MATERIAL_FLAGS.put(Material.SPRUCE_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BIRCH_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.JUNGLE_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.ACACIA_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DARK_OAK_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DIRT_PATH, 0);
MATERIAL_FLAGS.put(Material.CHORUS_PLANT, 0);
@@ -240,7 +247,7 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.PURPUR_SLAB, 0);
MATERIAL_FLAGS.put(Material.STRUCTURE_BLOCK, MODIFIED_ON_LEFT | MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.REPEATING_COMMAND_BLOCK, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.CHAIN_COMMAND_BLOCK, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.CHAIN_COMMAND_BLOCK , MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.MAGMA_BLOCK, 0);
MATERIAL_FLAGS.put(Material.NETHER_WART_BLOCK, 0);
@@ -634,7 +641,7 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.PUFFERFISH_BUCKET, 0);
MATERIAL_FLAGS.put(Material.SALMON, 0);
MATERIAL_FLAGS.put(Material.SALMON_BUCKET, 0);
MATERIAL_FLAGS.put(Material.TURTLE_SCUTE, 0);
MATERIAL_FLAGS.put(Material.SCUTE, 0);
MATERIAL_FLAGS.put(Material.SPLASH_POTION, 0);
MATERIAL_FLAGS.put(Material.TURTLE_HELMET, 0);
MATERIAL_FLAGS.put(Material.TRIDENT, 0);
@@ -670,6 +677,7 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.CRIMSON_FUNGUS, 0);
MATERIAL_FLAGS.put(Material.CRIMSON_NYLIUM, 0);
MATERIAL_FLAGS.put(Material.CRIMSON_ROOTS, 0);
MATERIAL_FLAGS.put(Material.CRIMSON_TRAPDOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.CRYING_OBSIDIAN, 0);
MATERIAL_FLAGS.put(Material.GILDED_BLACKSTONE, 0);
MATERIAL_FLAGS.put(Material.LODESTONE, 0);
@@ -710,6 +718,7 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.WARPED_FUNGUS_ON_A_STICK, 0);
MATERIAL_FLAGS.put(Material.WARPED_NYLIUM, 0);
MATERIAL_FLAGS.put(Material.WARPED_ROOTS, 0);
MATERIAL_FLAGS.put(Material.WARPED_TRAPDOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.WARPED_WART_BLOCK, 0);
MATERIAL_FLAGS.put(Material.WEEPING_VINES, 0);
MATERIAL_FLAGS.put(Material.WEEPING_VINES_PLANT, 0);
@@ -811,70 +820,20 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.ECHO_SHARD, 0);
MATERIAL_FLAGS.put(Material.REINFORCED_DEEPSLATE, 0);
MATERIAL_FLAGS.put(Material.BAMBOO_MOSAIC, 0);
MATERIAL_FLAGS.put(Material.BAMBOO_BLOCK, 0);
MATERIAL_FLAGS.put(Material.STRIPPED_BAMBOO_BLOCK, 0);
MATERIAL_FLAGS.put(Material.SUSPICIOUS_SAND, 0);
MATERIAL_FLAGS.put(Material.SUSPICIOUS_GRAVEL, 0);
MATERIAL_FLAGS.put(Material.PITCHER_PLANT, 0);
MATERIAL_FLAGS.put(Material.CHISELED_BOOKSHELF, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DECORATED_POT, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BRUSH, 0);
MATERIAL_FLAGS.put(Material.SNIFFER_EGG, 0);
MATERIAL_FLAGS.put(Material.CALIBRATED_SCULK_SENSOR, 0);
MATERIAL_FLAGS.put(Material.PIGLIN_HEAD, 0);
MATERIAL_FLAGS.put(Material.PIGLIN_WALL_HEAD, 0);
MATERIAL_FLAGS.put(Material.TORCHFLOWER_SEEDS, 0);
MATERIAL_FLAGS.put(Material.TORCHFLOWER_CROP, 0);
MATERIAL_FLAGS.put(Material.PITCHER_CROP, 0);
MATERIAL_FLAGS.put(Material.PINK_PETALS, 0);
MATERIAL_FLAGS.put(Material.PITCHER_POD, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_UPGRADE_SMITHING_TEMPLATE, 0);
// 1.19.3: Try to register those things
try {
SIGNS_TAG = Tag.ALL_SIGNS;
MATERIAL_FLAGS.put(Material.ARMADILLO_SCUTE, 0);
MATERIAL_FLAGS.put(Material.WOLF_ARMOR, 0);
// 1.21
MATERIAL_FLAGS.put(Material.CHISELED_TUFF, 0);
MATERIAL_FLAGS.put(Material.POLISHED_TUFF, 0);
MATERIAL_FLAGS.put(Material.TUFF_BRICKS, 0);
MATERIAL_FLAGS.put(Material.CHISELED_TUFF_BRICKS, 0);
MATERIAL_FLAGS.put(Material.HEAVY_CORE, 0);
MATERIAL_FLAGS.put(Material.CHISELED_COPPER, 0);
MATERIAL_FLAGS.put(Material.EXPOSED_CHISELED_COPPER, 0);
MATERIAL_FLAGS.put(Material.WEATHERED_CHISELED_COPPER, 0);
MATERIAL_FLAGS.put(Material.OXIDIZED_CHISELED_COPPER, 0);
MATERIAL_FLAGS.put(Material.WAXED_CHISELED_COPPER, 0);
MATERIAL_FLAGS.put(Material.WAXED_EXPOSED_CHISELED_COPPER, 0);
MATERIAL_FLAGS.put(Material.WAXED_WEATHERED_CHISELED_COPPER, 0);
MATERIAL_FLAGS.put(Material.WAXED_OXIDIZED_CHISELED_COPPER, 0);
MATERIAL_FLAGS.put(Material.CRAFTER, 0);
MATERIAL_FLAGS.put(Material.FLOW_BANNER_PATTERN, 0);
MATERIAL_FLAGS.put(Material.GUSTER_BANNER_PATTERN, 0);
MATERIAL_FLAGS.put(Material.COPPER_GRATE, 0);
MATERIAL_FLAGS.put(Material.WEATHERED_COPPER_GRATE, 0);
MATERIAL_FLAGS.put(Material.EXPOSED_COPPER_GRATE, 0);
MATERIAL_FLAGS.put(Material.OXIDIZED_COPPER_GRATE, 0);
MATERIAL_FLAGS.put(Material.WAXED_COPPER_GRATE, 0);
MATERIAL_FLAGS.put(Material.WAXED_WEATHERED_COPPER_GRATE, 0);
MATERIAL_FLAGS.put(Material.WAXED_EXPOSED_COPPER_GRATE, 0);
MATERIAL_FLAGS.put(Material.WAXED_OXIDIZED_COPPER_GRATE, 0);
MATERIAL_FLAGS.put(Material.COPPER_BULB, 0);
MATERIAL_FLAGS.put(Material.WEATHERED_COPPER_BULB, 0);
MATERIAL_FLAGS.put(Material.EXPOSED_COPPER_BULB, 0);
MATERIAL_FLAGS.put(Material.OXIDIZED_COPPER_BULB, 0);
MATERIAL_FLAGS.put(Material.WAXED_COPPER_BULB, 0);
MATERIAL_FLAGS.put(Material.WAXED_WEATHERED_COPPER_BULB, 0);
MATERIAL_FLAGS.put(Material.WAXED_EXPOSED_COPPER_BULB, 0);
MATERIAL_FLAGS.put(Material.WAXED_OXIDIZED_COPPER_BULB, 0);
MATERIAL_FLAGS.put(Material.TRIAL_SPAWNER, 0);
MATERIAL_FLAGS.put(Material.TRIAL_KEY, 0);
MATERIAL_FLAGS.put(Material.OMINOUS_TRIAL_KEY, 0);
MATERIAL_FLAGS.put(Material.VAULT, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.OMINOUS_BOTTLE, 0);
MATERIAL_FLAGS.put(Material.BREEZE_ROD, 0);
MATERIAL_FLAGS.put(Material.WIND_CHARGE, 0);
MATERIAL_FLAGS.put(Material.BAMBOO_MOSAIC, 0);
MATERIAL_FLAGS.put(Material.BAMBOO_BLOCK, 0);
MATERIAL_FLAGS.put(Material.STRIPPED_BAMBOO_BLOCK, 0);
} catch (NoSuchFieldError ignored) {
SIGNS_TAG = Tag.SIGNS;
}
// Generated via tag
putMaterialTag(Tag.WOODEN_DOORS, MODIFIED_ON_RIGHT);
putMaterialTag(Tag.WOODEN_TRAPDOORS, MODIFIED_ON_RIGHT);
putMaterialTag(Tag.SHULKER_BOXES, MODIFIED_ON_RIGHT);
putMaterialTag(Tag.ITEMS_BOATS, 0);
putMaterialTag(Tag.BANNERS, 0);
@@ -890,9 +849,10 @@ public final class Materials {
putMaterialTag(Tag.BUTTONS, MODIFIED_ON_RIGHT);
putMaterialTag(Tag.FLOWER_POTS, MODIFIED_ON_RIGHT);
putMaterialTag(Tag.WALLS, 0);
putMaterialTag(Tag.ALL_SIGNS, 0);
putMaterialTag(SIGNS_TAG, 0);
putMaterialTag(Tag.SMALL_FLOWERS, 0);
putMaterialTag(Tag.BEDS, MODIFIED_ON_RIGHT);
putMaterialTag(Tag.ITEMS_MUSIC_DISCS, 0);
putMaterialTag(Tag.ITEMS_BANNERS, 0);
putMaterialTag(Tag.FENCE_GATES, MODIFIED_ON_RIGHT);
putMaterialTag(Tag.FENCES, 0);
@@ -909,10 +869,6 @@ public final class Materials {
putMaterialTag(Tag.CANDLE_CAKES, MODIFIED_ON_RIGHT);
putMaterialTag(Tag.CAULDRONS, MODIFIED_ON_RIGHT);
// 1.20
putMaterialTag(Tag.ITEMS_TRIM_TEMPLATES, 0);
putMaterialTag(Tag.ITEMS_DECORATED_POT_SHERDS, 0);
Stream.concat(Stream.concat(
Tag.CORAL_BLOCKS.getValues().stream(),
Tag.CORALS.getValues().stream()),
@@ -926,30 +882,28 @@ public final class Materials {
// Check for missing items/blocks
for (Material material : Material.values()) {
//noinspection deprecation
if (material.isLegacy()) continue;
// Add spawn eggs
if (isSpawnEgg(material)) {
MATERIAL_FLAGS.put(material, 0);
}
if (material.name().startsWith("MUSIC_DISC_")) {
MATERIAL_FLAGS.put(material, 0);
}
if (!MATERIAL_FLAGS.containsKey(material)) {
logger.fine("Missing material definition for " + (material.isBlock() ? "block " : "item ") + material.name());
}
}
// DAMAGE_EFFECTS.add(PotionEffectType.SPEED);
DAMAGE_EFFECTS.add(PotionEffectType.SLOWNESS);
// DAMAGE_EFFECTS.add(PotionEffectType.HASTE);
DAMAGE_EFFECTS.add(PotionEffectType.MINING_FATIGUE);
// DAMAGE_EFFECTS.add(PotionEffectType.STRENGTH);
// DAMAGE_EFFECTS.add(PotionEffectType.INSTANT_HEALTH);
DAMAGE_EFFECTS.add(PotionEffectType.INSTANT_DAMAGE);
// DAMAGE_EFFECTS.add(PotionEffectType.JUMP_BOOST);
DAMAGE_EFFECTS.add(PotionEffectType.NAUSEA);
DAMAGE_EFFECTS.add(PotionEffectType.SLOW);
// DAMAGE_EFFECTS.add(PotionEffectType.FAST_DIGGING);
DAMAGE_EFFECTS.add(PotionEffectType.SLOW_DIGGING);
// DAMAGE_EFFECTS.add(PotionEffectType.INCREASE_DAMAGE);
// DAMAGE_EFFECTS.add(PotionEffectType.HEAL);
DAMAGE_EFFECTS.add(PotionEffectType.HARM);
// DAMAGE_EFFECTS.add(PotionEffectType.JUMP);
DAMAGE_EFFECTS.add(PotionEffectType.CONFUSION);
// DAMAGE_EFFECTS.add(PotionEffectType.REGENERATION);
// DAMAGE_EFFECTS.add(PotionEffectType.RESISTANCE);
// DAMAGE_EFFECTS.add(PotionEffectType.DAMAGE_RESISTANCE);
// DAMAGE_EFFECTS.add(PotionEffectType.FIRE_RESISTANCE);
// DAMAGE_EFFECTS.add(PotionEffectType.WATER_BREATHING);
// DAMAGE_EFFECTS.add(PotionEffectType.INVISIBILITY);
@@ -972,11 +926,6 @@ public final class Materials {
DAMAGE_EFFECTS.add(PotionEffectType.BAD_OMEN);
// DAMAGE_EFFECTS.add(PotionEffectType.HERO_OF_THE_VILLAGE);
DAMAGE_EFFECTS.add(PotionEffectType.DARKNESS);
DAMAGE_EFFECTS.add(PotionEffectType.TRIAL_OMEN);
DAMAGE_EFFECTS.add(PotionEffectType.WIND_CHARGED);
DAMAGE_EFFECTS.add(PotionEffectType.WEAVING);
DAMAGE_EFFECTS.add(PotionEffectType.OOZING);
DAMAGE_EFFECTS.add(PotionEffectType.INFESTED);
}
private Materials() {
@@ -1018,11 +967,13 @@ public final class Materials {
* @return the block material
*/
public static Material getBucketBlockMaterial(Material type) {
return switch (type) {
case LAVA_BUCKET -> Material.LAVA;
case WATER_BUCKET -> Material.WATER;
default -> Material.WATER;
};
switch (type) {
case LAVA_BUCKET:
return Material.LAVA;
case WATER_BUCKET:
default:
return Material.WATER;
}
}
/**
@@ -1162,8 +1113,6 @@ public final class Materials {
|| material == Material.BARREL
|| material == Material.BLAST_FURNACE
|| material == Material.SMOKER
|| material == Material.CHISELED_BOOKSHELF
|| material == Material.CRAFTER
|| Tag.ITEMS_CHEST_BOATS.isTagged(material)
|| Tag.SHULKER_BOXES.isTagged(material);
}
@@ -1175,13 +1124,11 @@ public final class Materials {
public static EntityType getEntitySpawnEgg(Material material) {
return switch (material) {
case ALLAY_SPAWN_EGG -> EntityType.ALLAY;
case ARMADILLO_SPAWN_EGG -> EntityType.ARMADILLO;
case AXOLOTL_SPAWN_EGG -> EntityType.AXOLOTL;
case SPIDER_SPAWN_EGG -> EntityType.SPIDER;
case BAT_SPAWN_EGG -> EntityType.BAT;
case BEE_SPAWN_EGG -> EntityType.BEE;
case BLAZE_SPAWN_EGG -> EntityType.BLAZE;
case BOGGED_SPAWN_EGG -> EntityType.BOGGED;
case BREEZE_SPAWN_EGG -> EntityType.BREEZE;
case CAT_SPAWN_EGG -> EntityType.CAT;
case CAMEL_SPAWN_EGG -> EntityType.CAMEL;
case CAVE_SPIDER_SPAWN_EGG -> EntityType.CAVE_SPIDER;
@@ -1209,7 +1156,7 @@ public final class Materials {
case IRON_GOLEM_SPAWN_EGG -> EntityType.IRON_GOLEM;
case LLAMA_SPAWN_EGG -> EntityType.LLAMA;
case MAGMA_CUBE_SPAWN_EGG -> EntityType.MAGMA_CUBE;
case MOOSHROOM_SPAWN_EGG -> EntityType.MOOSHROOM;
case MOOSHROOM_SPAWN_EGG -> EntityType.MUSHROOM_COW;
case MULE_SPAWN_EGG -> EntityType.MULE;
case OCELOT_SPAWN_EGG -> EntityType.OCELOT;
case PANDA_SPAWN_EGG -> EntityType.PANDA;
@@ -1229,9 +1176,7 @@ public final class Materials {
case SKELETON_HORSE_SPAWN_EGG -> EntityType.SKELETON_HORSE;
case SKELETON_SPAWN_EGG -> EntityType.SKELETON;
case SLIME_SPAWN_EGG -> EntityType.SLIME;
case SNIFFER_SPAWN_EGG -> EntityType.SNIFFER;
case SNOW_GOLEM_SPAWN_EGG -> EntityType.SNOW_GOLEM;
case SPIDER_SPAWN_EGG -> EntityType.SPIDER;
case SNOW_GOLEM_SPAWN_EGG -> EntityType.SNOWMAN;
case SQUID_SPAWN_EGG -> EntityType.SQUID;
case STRAY_SPAWN_EGG -> EntityType.STRAY;
case STRIDER_SPAWN_EGG -> EntityType.STRIDER;
@@ -1315,15 +1260,15 @@ public final class Materials {
*/
public static boolean isUseFlagApplicable(Material material) {
if (Tag.BUTTONS.isTagged(material)
|| Tag.DOORS.isTagged(material)
|| Tag.TRAPDOORS.isTagged(material)
|| Tag.WOODEN_DOORS.isTagged(material)
|| Tag.WOODEN_TRAPDOORS.isTagged(material)
|| Tag.FENCE_GATES.isTagged(material)
|| Tag.PRESSURE_PLATES.isTagged(material)) {
return true;
}
return switch (material) {
case LEVER, LECTERN, ENCHANTING_TABLE, BELL, LOOM,
CARTOGRAPHY_TABLE, STONECUTTER, GRINDSTONE, VAULT -> true;
CARTOGRAPHY_TABLE, STONECUTTER, GRINDSTONE -> true;
default -> false;
};
}
@@ -1375,8 +1320,7 @@ public final class Materials {
|| type == Material.DRAGON_EGG
|| Tag.FLOWER_POTS.isTagged(type)
|| Tag.CANDLES.isTagged(type)
|| Tag.CANDLE_CAKES.isTagged(type)
|| Tag.ALL_SIGNS.isTagged(type);
|| Tag.CANDLE_CAKES.isTagged(type);
}
/**
@@ -1406,13 +1350,15 @@ public final class Materials {
* @return true if equippable armor
*/
public static boolean isArmor(Material type) {
if (Tag.ITEMS_HEAD_ARMOR.isTagged(type) || Tag.ITEMS_CHEST_ARMOR.isTagged(type) ||
Tag.ITEMS_LEG_ARMOR.isTagged(type) || Tag.ITEMS_FOOT_ARMOR.isTagged(type) ||
Tag.ITEMS_SKULLS.isTagged(type)) {
return true;
}
return switch (type) {
case CARVED_PUMPKIN, ELYTRA -> true;
case LEATHER_HELMET, LEATHER_CHESTPLATE, LEATHER_LEGGINGS, LEATHER_BOOTS,
CHAINMAIL_HELMET, CHAINMAIL_CHESTPLATE, CHAINMAIL_LEGGINGS, CHAINMAIL_BOOTS,
IRON_HELMET, IRON_CHESTPLATE, IRON_LEGGINGS, IRON_BOOTS,
DIAMOND_HELMET, DIAMOND_CHESTPLATE, DIAMOND_LEGGINGS, DIAMOND_BOOTS,
GOLDEN_HELMET, GOLDEN_CHESTPLATE, GOLDEN_LEGGINGS, GOLDEN_BOOTS,
NETHERITE_HELMET, NETHERITE_CHESTPLATE, NETHERITE_LEGGINGS, NETHERITE_BOOTS,
TURTLE_HELMET, ELYTRA ->
true;
default -> false;
};
}
@@ -1487,17 +1433,9 @@ public final class Materials {
case YELLOW_DYE:
case GLOW_INK_SAC:
case INK_SAC:
return Tag.ALL_SIGNS.isTagged(targetMaterial);
return SIGNS_TAG.isTagged(targetMaterial);
case HONEYCOMB:
return isUnwaxedCopper(targetMaterial) || Tag.ALL_SIGNS.isTagged(targetMaterial);
case BRUSH:
return switch (targetMaterial) {
case SUSPICIOUS_GRAVEL, SUSPICIOUS_SAND -> true;
default -> false;
};
case WRITTEN_BOOK:
case WRITABLE_BOOK:
return targetMaterial == Material.LECTERN;
return isUnwaxedCopper(targetMaterial);
default:
return false;
}
@@ -1506,18 +1444,27 @@ public final class Materials {
public static boolean isFire(Material type) {
return type == Material.FIRE || type == Material.SOUL_FIRE;
}
public static boolean isWaxedCopper(Material type) {
// copied from the MaterialTags class in Paper
return type.name().startsWith("WAXED_") && type.name().contains("COPPER");
}
public static boolean isUnwaxedCopper(Material type) {
// copied from the MaterialTags class in Paper
return switch (type) {
case COPPER_BLOCK, CHISELED_COPPER, COPPER_DOOR, COPPER_TRAPDOOR, COPPER_GRATE, COPPER_BULB -> true;
default -> type.name().startsWith("EXPOSED_") || type.name().startsWith("WEATHERED_") ||
type.name().startsWith("OXIDIZED_") || type.name().startsWith("CUT_COPPER");
case WAXED_COPPER_BLOCK, WAXED_EXPOSED_COPPER, WAXED_WEATHERED_COPPER, WAXED_OXIDIZED_COPPER,
WAXED_CUT_COPPER, WAXED_EXPOSED_CUT_COPPER, WAXED_WEATHERED_CUT_COPPER,
WAXED_OXIDIZED_CUT_COPPER, WAXED_CUT_COPPER_STAIRS, WAXED_EXPOSED_CUT_COPPER_STAIRS,
WAXED_WEATHERED_CUT_COPPER_STAIRS, WAXED_OXIDIZED_CUT_COPPER_STAIRS, WAXED_CUT_COPPER_SLAB,
WAXED_EXPOSED_CUT_COPPER_SLAB, WAXED_WEATHERED_CUT_COPPER_SLAB, WAXED_OXIDIZED_CUT_COPPER_SLAB ->
true;
default -> false;
};
}
public static boolean isUnwaxedCopper(Material type) {
return switch (type) {
case COPPER_BLOCK, EXPOSED_COPPER, WEATHERED_COPPER, OXIDIZED_COPPER, CUT_COPPER,
EXPOSED_CUT_COPPER, WEATHERED_CUT_COPPER, OXIDIZED_CUT_COPPER, CUT_COPPER_STAIRS,
EXPOSED_CUT_COPPER_STAIRS, WEATHERED_CUT_COPPER_STAIRS, OXIDIZED_CUT_COPPER_STAIRS,
CUT_COPPER_SLAB, EXPOSED_CUT_COPPER_SLAB, WEATHERED_CUT_COPPER_SLAB, OXIDIZED_CUT_COPPER_SLAB ->
true;
default -> false;
};
}
@@ -0,0 +1,12 @@
#
# WorldGuard regions file
#
# WARNING: THIS FILE IS AUTOMATICALLY GENERATED. If you modify this file by
# hand, be aware that A SINGLE MISTYPED CHARACTER CAN CORRUPT THE FILE. If
# WorldGuard is unable to parse the file, your regions will FAIL TO LOAD and
# the contents of this file will reset. Please use a YAML validator such as
# http://yaml-online-parser.appspot.com (for smaller files).
#
# REMEMBER TO KEEP PERIODICAL BACKUPS.
#
regions: {}
@@ -1,5 +1,9 @@
#
# WorldGuard's configuration file
# WorldGuard's main configuration file
#
# This is the global configuration file. Anything placed into here will
# be applied to all worlds. However, each world has its own configuration
# file to allow you to replace most settings in here for that world only.
#
# About editing this file:
# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If
@@ -12,11 +16,167 @@
# - If you want to check the format of this file before putting it
# into WorldGuard, paste it into http://yaml-online-parser.appspot.com/
# and see if it gives "ERROR:".
# - Lines starting with # are commentsand so they are ignored.
#
# WARNING:
# Remember to check the compatibility spreadsheet for WorldGuard to see
# if any features are currently broken in your version of Bukkit.
# - Lines starting with # are comments and so they are ignored.
#
# -- This should be automatically replaced by the plugin in-game --
regions:
uuid-migration:
perform-on-next-start: false
keep-names-that-lack-uuids: true
use-creature-spawn-event: true
disable-bypass-by-default: true
announce-bypass-status: true
use-paper-entity-origin: true
enable: true
invincibility-removes-mobs: true
cancel-chat-without-recipients: true
nether-portal-protection: true
fake-player-build-override: true
explosion-flags-block-entity-damage: true
high-frequency-flags: true
protect-against-liquid-flow: true
wand: minecraft:leather
max-claim-volume: 30000
claim-only-inside-existing-regions: false
set-parent-on-claim: ''
location-flags-only-inside-regions: false
max-region-count-per-player:
default: 7
auto-invincible: false
auto-invincible-group: false
auto-no-drowning-group: false
use-player-move-event: true
use-player-teleports: true
use-particle-effects: true
disable-permission-cache: false
security:
deop-everyone-on-join: true
block-in-game-op-command: true
host-keys-allow-forge-clients: true
host-keys: {}
summary-on-start: true
op-permissions: false
build-permission-nodes:
enable: false
deny-message: '&cERROR: &6You don''t have permission to do that here.'
event-handling:
block-entity-spawns-with-untraceable-cause: false
interaction-whitelist: []
emit-block-use-at-feet: []
ignore-hopper-item-move-events: false
break-hoppers-on-denied-move: false
protection:
item-durability: true
remove-infinite-stacks: true
disable-xp-orb-drops: false
use-max-priority-association: true
gameplay:
block-potions: []
block-potions-overly-reliably: false
disable-conduit-effects: false
default:
pumpkin-scuba: false
disable-health-regain: false
physics:
no-physics-gravel: false
no-physics-sand: false
vine-like-rope-ladders: false
allow-portal-anywhere: false
disable-water-damage-blocks: []
ignition:
block-tnt: false
block-tnt-block-damage: false
block-lighter: false
fire:
disable-lava-fire-spread: false
disable-all-fire-spread: false
disable-fire-spread-blocks: []
lava-spread-blocks: []
mobs:
block-creeper-explosions: false
block-creeper-block-damage: false
block-wither-explosions: false
block-wither-block-damage: false
block-wither-skull-explosions: false
block-wither-skull-block-damage: false
block-enderdragon-block-damage: false
block-enderdragon-portal-creation: false
block-fireball-explosions: false
block-fireball-block-damage: false
anti-wolf-dumbness: true
allow-tamed-spawns: true
disable-enderman-griefing: false
disable-snowman-trails: false
block-painting-destroy: false
block-item-frame-destroy: false
block-armor-stand-destroy: false
block-plugin-spawning: true
block-above-ground-slimes: false
block-other-explosions: false
block-zombie-door-destruction: false
block-vehicle-entry: false
block-creature-spawn: []
player-damage:
disable-fall-damage: false
disable-lava-damage: false
disable-fire-damage: false
disable-lightning-damage: false
disable-drowning-damage: false
disable-suffocation-damage: false
disable-contact-damage: false
teleport-on-suffocation: false
disable-void-damage: false
teleport-on-void-falling: false
reset-fall-on-void-teleport: false
disable-explosion-damage: false
disable-mob-damage: false
disable-death-messages: false
crops:
disable-creature-trampling: false
disable-player-trampling: false
turtle-egg:
disable-creature-trampling: false
disable-player-trampling: false
weather:
prevent-lightning-strike-blocks: []
disable-lightning-strike-fire: false
disable-thunderstorm: false
disable-weather: false
disable-pig-zombification: false
disable-villager-witchification: false
disable-powered-creepers: false
always-raining: false
always-thundering: false
dynamics:
disable-mushroom-spread: false
disable-ice-melting: false
disable-snow-melting: false
disable-snow-formation: false
disable-ice-formation: false
disable-leaf-decay: false
disable-grass-growth: false
disable-mycelium-spread: false
disable-vine-growth: false
disable-rock-growth: false
disable-sculk-growth: false
disable-crop-growth: false
disable-soil-dehydration: false
disable-coral-block-fade: false
disable-copper-block-fade: false
snow-fall-blocks: []
blacklist:
use-as-whitelist: false
logging:
console:
enable: true
database:
enable: false
dsn: jdbc:mysql://localhost:3306/minecraft
user: root
pass: ''
table: blacklist_events
file:
enable: false
path: worldguard/logs/%Y-%m-%d.log
open-files: 10
custom-metrics-charts: false
@@ -1,21 +1,13 @@
#
# WorldGuard's configuration file.
# WorldGuard's world configuration file
#
# This is the a per-world configuration file. It only affects one
# corresponding world.
# This is a world configuration file. Anything placed into here will only
# affect this world. If you don't put anything in this file, then the
# settings will be inherited from the main configuration file.
#
# About editing this file:
# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If
# you use an editor like Notepad++ (recommended for Windows users), you
# must configure it to "replace tabs with spaces." In Notepad++, this can
# be changed in Settings > Preferences > Language Menu.
# - Don't get rid of the indents. They are indented so some entries are
# in categories (like "enforce-single-session" is in the "protection"
# category.
# - If you want to check the format of this file before putting it
# into WorldGuard, paste it into http://yaml-online-parser.appspot.com/
# and see if it gives "ERROR:".
# - Lines starting with # are comments and so they are ignored.
# If you see {} below, that means that there are NO entries in this file.
# Remove the {} and add your own entries.
#
# -- This should be automatically replaced by the plugin in-game --
regions:
titles-always-use-default-times: true
File diff suppressed because it is too large. Load diff
@@ -3,4 +3,4 @@ main: com.sk89q.worldguard.bukkit.WorldGuardPlugin
version: "${internalVersion}"
depend: [WorldEdit]
softdepend: [CommandBook]
api-version: "1.21"
api-version: 1.19
+10 -41
View File
@@ -1,51 +1,20 @@
import org.cadixdev.gradle.licenser.LicenseExtension
plugins {
`java-library`
id("buildlogic.core-and-platform")
}
applyPlatformAndCoreConfiguration()
dependencies {
constraints {
"implementation"(libs.snakeyaml) {
because("Bukkit provides SnakeYaml")
}
}
"api"(project(":worldguard-libs:core"))
"api"(libs.worldedit.core)
"implementation"(libs.flyway.core)
"implementation"(libs.snakeyaml)
"implementation"(libs.guava)
"compileOnlyApi"(libs.jsr305)
"implementation"(libs.gson)
"api"("com.sk89q.worldedit:worldedit-core:${Versions.WORLDEDIT}")
"implementation"("org.flywaydb:flyway-core:3.0")
"implementation"("org.yaml:snakeyaml:1.33")
"implementation"("com.google.guava:guava:${Versions.GUAVA}")
"compileOnly"(libs.worldedit.libs.ap)
"annotationProcessor"(libs.worldedit.libs.ap)
// ensure this is on the classpath for the AP
"annotationProcessor"(libs.guava)
"compileOnly"(libs.autoService) {
because("Needed to resolve annotations in Piston")
}
"testImplementation"(libs.hamcrest.library)
"compileOnly"("com.google.code.findbugs:jsr305:${Versions.FINDBUGS}")
"testImplementation"("org.hamcrest:hamcrest-library:2.2")
}
tasks.compileJava {
tasks.withType<JavaCompile>().configureEach {
dependsOn(":worldguard-libs:build")
options.compilerArgs.add("-Aarg.name.key.prefix=")
}
configure<LicenseExtension> {
exclude {
it.file.startsWith(project.layout.buildDirectory.get().asFile)
}
}
configure<PublishingExtension> {
publications.named<MavenPublication>("maven") {
artifactId = the<BasePluginExtension>().archivesName.get()
from(components["java"])
}
}
}
@@ -24,8 +24,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldguard.domains.registry.DomainRegistry;
import com.sk89q.worldguard.domains.registry.SimpleDomainRegistry;
import com.sk89q.worldguard.util.profile.cache.HashMapCache;
import com.sk89q.worldguard.util.profile.cache.ProfileCache;
import com.sk89q.worldguard.util.profile.cache.SQLiteCache;
@@ -57,7 +55,6 @@ public final class WorldGuard {
private WorldGuardPlatform platform;
private final SimpleFlagRegistry flagRegistry = new SimpleFlagRegistry();
private final SimpleDomainRegistry domainRegistry = new SimpleDomainRegistry();
private final Supervisor supervisor = new SimpleSupervisor();
private ProfileCache profileCache;
private ProfileService profileService;
@@ -119,16 +116,6 @@ public final class WorldGuard {
return this.flagRegistry;
}
/**
* Get the domain registry.
*
* @return the domain registry
*/
public DomainRegistry getDomainRegistry() {
return this.domainRegistry;
}
/**
* Get the supervisor.
*
@@ -95,9 +95,9 @@ public class DatabaseHandler implements LoggerHandler {
stmt.setString(1, eventType.name());
stmt.setString(2, worldName);
stmt.setString(3, player != null ? player.getName() : "");
stmt.setInt(4, pos.x());
stmt.setInt(5, pos.y());
stmt.setInt(6, pos.z());
stmt.setInt(4, pos.getBlockX());
stmt.setInt(5, pos.getBlockY());
stmt.setInt(6, pos.getBlockZ());
stmt.setString(7, item);
stmt.setInt(8, (int)(System.currentTimeMillis() / 1000));
stmt.setString(9, comment);
@@ -221,7 +221,7 @@ public class FileHandler implements LoggerHandler {
* @return The position's coordinates in human-readable form
*/
private String getCoordinates(BlockVector3 pos) {
return "@" + pos.x() + "," + pos.y() + "," + pos.z();
return "@" + pos.getBlockX() + "," + pos.getBlockY() + "," + pos.getBlockZ();
}
private void logEvent(BlacklistEvent event, String text, Target target, BlockVector3 pos, String comment) {
@@ -1,111 +0,0 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.commands;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldguard.LocalPlayer;
import javax.annotation.Nullable;
import java.util.Map;
public abstract class CommandInputContext<T extends Exception> {
protected final Actor sender;
protected final String input;
protected Map<String, Object> context;
protected CommandInputContext(Actor sender, String input, Map<String, Object> values) {
this.sender = sender;
this.input = input;
this.context = values;
}
public void put(String name, Object value) {
context.put(name, value);
}
public Actor getSender() {
return sender;
}
public String getUserInput() {
return input;
}
/**
* Gets the CommandSender as a player.
*
* @return Player
* @throws T if the sender is not a player
*/
public LocalPlayer getPlayerSender() throws T {
if (sender.isPlayer() && sender instanceof LocalPlayer) {
return (LocalPlayer) sender;
} else {
throw createException("Not a player");
}
}
public Integer getUserInputAsInt() throws T {
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
throw createException("Not a number: " + input);
}
}
public Double getUserInputAsDouble() throws T {
try {
return Double.parseDouble(input);
} catch (NumberFormatException e) {
throw createException("Not a number: " + input);
}
}
protected abstract T createException(String str);
/**
* Get an object from the context by key name.
* May return null if the object does not exist in the context.
*
* @param name key name of the object
* @return the object matching the key, or null
*/
@Nullable
public Object get(String name) {
return get(name, null);
}
/**
* Get an object from the context by key name.
* Will only return null if
* a) you provide null as the default
* b) the key has explicity been set to null
*
* @param name key name of the object
* @return the object matching the key
*/
@Nullable
public Object get(String name, Object defaultValue) {
Object obj;
return (((obj = context.get(name)) != null) || context.containsKey(name)
? obj : defaultValue);
}
}
@@ -70,7 +70,7 @@ public class GeneralCommands {
// Keep track of this
included = true;
} else if (!args.hasFlag('s')) {
} else {
player.print("God enabled by " + sender.getDisplayName() + ".");
}
@@ -79,7 +79,7 @@ public class GeneralCommands {
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included) {
if (!included && args.hasFlag('s')) {
sender.print("Players now have god mode.");
}
}
@@ -113,7 +113,7 @@ public class GeneralCommands {
// Keep track of this
included = true;
} else if (!args.hasFlag('s')) {
} else {
player.print("God disabled by " + sender.getDisplayName() + ".");
}
@@ -122,7 +122,7 @@ public class GeneralCommands {
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included) {
if (!included && args.hasFlag('s')) {
sender.print("Players no longer have god mode.");
}
}
@@ -158,7 +158,7 @@ public class GeneralCommands {
// Keep track of this
included = true;
} else if (!args.hasFlag('s')) {
} else {
player.print("Healed by " + sender.getDisplayName() + ".");
}
@@ -166,7 +166,7 @@ public class GeneralCommands {
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included) {
if (!included && args.hasFlag('s')) {
sender.print("Players healed.");
}
}
@@ -199,7 +199,7 @@ public class GeneralCommands {
// Keep track of this
included = true;
} else if (!args.hasFlag('s')) {
} else {
player.print("Slain by " + sender.getDisplayName() + ".");
}
@@ -207,7 +207,7 @@ public class GeneralCommands {
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included) {
if (!included && args.hasFlag('s')) {
sender.print("Players slain.");
}
}
@@ -378,7 +378,7 @@ class FlagHelperBox extends PaginationBox {
if (currVal == null) {
currVal = getInheritedValue(region, flag);
}
String display = currVal == null ? regName : currVal.id();
String display = currVal == null ? regName : currVal.getId();
appendValueText(builder, flag, display, null);
}
@@ -25,27 +25,16 @@ import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.worldedit.command.util.AsyncCommandBuilder;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.formatting.component.ErrorFormat;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.event.ClickEvent;
import com.sk89q.worldedit.util.formatting.text.event.HoverEvent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldedit.util.auth.AuthorizationException;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.domains.registry.DomainFactory;
import com.sk89q.worldguard.domains.registry.DomainRegistry;
import com.sk89q.worldguard.internal.permission.RegionPermissionModel;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.util.DomainInputResolver;
import com.sk89q.worldguard.protection.util.DomainInputResolver.UserLocatorPolicy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.Callable;
public class MemberCommands extends RegionCommandsBase {
@@ -78,8 +67,6 @@ public class MemberCommands extends RegionCommandsBase {
DomainInputResolver resolver = new DomainInputResolver(
WorldGuard.getInstance().getProfileService(), args.getParsedPaddedSlice(1, 0));
resolver.setLocatorPolicy(args.hasFlag('n') ? UserLocatorPolicy.NAME_ONLY : UserLocatorPolicy.UUID_ONLY);
resolver.setActor(sender);
resolver.setRegion(region);
final String description = String.format("Adding members to the region '%s' on '%s'", region.getId(), world.getName());
@@ -114,8 +101,7 @@ public class MemberCommands extends RegionCommandsBase {
DomainInputResolver resolver = new DomainInputResolver(
WorldGuard.getInstance().getProfileService(), args.getParsedPaddedSlice(1, 0));
resolver.setLocatorPolicy(args.hasFlag('n') ? UserLocatorPolicy.NAME_ONLY : UserLocatorPolicy.UUID_ONLY);
resolver.setActor(sender);
resolver.setRegion(region);
final String description = String.format("Adding owners to the region '%s' on '%s'", region.getId(), world.getName());
AsyncCommandBuilder.wrap(checkedAddOwners(sender, manager, region, world, resolver), sender)
@@ -188,8 +174,6 @@ public class MemberCommands extends RegionCommandsBase {
DomainInputResolver resolver = new DomainInputResolver(
WorldGuard.getInstance().getProfileService(), args.getParsedPaddedSlice(1, 0));
resolver.setLocatorPolicy(args.hasFlag('n') ? UserLocatorPolicy.NAME_ONLY : UserLocatorPolicy.UUID_AND_NAME);
resolver.setActor(sender);
resolver.setRegion(region);
callable = resolver;
}
@@ -233,8 +217,6 @@ public class MemberCommands extends RegionCommandsBase {
DomainInputResolver resolver = new DomainInputResolver(
WorldGuard.getInstance().getProfileService(), args.getParsedPaddedSlice(1, 0));
resolver.setLocatorPolicy(args.hasFlag('n') ? UserLocatorPolicy.NAME_ONLY : UserLocatorPolicy.UUID_AND_NAME);
resolver.setActor(sender);
resolver.setRegion(region);
callable = resolver;
}
@@ -59,7 +59,7 @@ import com.sk89q.worldguard.protection.FlagValueCalculator;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.FlagContext;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormatException;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
@@ -160,7 +160,7 @@ public final class RegionCommands extends RegionCommandsBase {
region = checkRegionFromSelection(sender, id);
}
RegionAdder task = new RegionAdder(manager, region, sender);
RegionAdder task = new RegionAdder(manager, region);
task.addOwnersFromCommand(args, 2);
final String description = String.format("Adding region '%s'", region.getId());
@@ -214,7 +214,7 @@ public final class RegionCommands extends RegionCommandsBase {
region.copyFrom(existing);
RegionAdder task = new RegionAdder(manager, region, sender);
RegionAdder task = new RegionAdder(manager, region);
final String description = String.format("Updating region '%s'", region.getId());
AsyncCommandBuilder.wrap(task, sender)
@@ -587,7 +587,7 @@ public final class RegionCommands extends RegionCommandsBase {
// the [value] part throws an error.
try {
groupValue = groupFlag.parseInput(FlagContext.create().setSender(sender).setInput(group).setObject("region", existing).build());
} catch (InvalidFlagFormatException e) {
} catch (InvalidFlagFormat e) {
throw new CommandException(e.getMessage());
}
@@ -598,7 +598,7 @@ public final class RegionCommands extends RegionCommandsBase {
// Set the flag if [value] was given even if [-g group] was given as well
try {
value = setFlag(existing, foundFlag, sender, value).toString();
} catch (InvalidFlagFormatException e) {
} catch (InvalidFlagFormat e) {
throw new CommandException(e.getMessage());
}
@@ -32,12 +32,15 @@ import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Polygonal2DRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.regions.selector.Polygonal2DRegionSelector;
import com.sk89q.worldedit.util.formatting.component.ErrorFormat;
import com.sk89q.worldedit.util.formatting.component.SubtleFormat;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.event.ClickEvent;
import com.sk89q.worldedit.util.formatting.text.event.HoverEvent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldedit.util.formatting.text.format.TextDecoration;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
@@ -45,7 +48,7 @@ import com.sk89q.worldguard.internal.permission.RegionPermissionModel;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.FlagContext;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormatException;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
@@ -305,8 +308,8 @@ class RegionCommandsBase {
// Detect the type of region from WorldEdit
if (selection instanceof Polygonal2DRegion) {
Polygonal2DRegion polySel = (Polygonal2DRegion) selection;
int minY = polySel.getMinimumPoint().y();
int maxY = polySel.getMaximumPoint().y();
int minY = polySel.getMinimumPoint().getBlockY();
int maxY = polySel.getMaximumPoint().getBlockY();
return new ProtectedPolygonalRegion(id, polySel.getPoints(), minY, maxY);
} else if (selection instanceof CuboidRegion) {
BlockVector3 min = selection.getMinimumPoint();
@@ -345,7 +348,7 @@ class RegionCommandsBase {
if (region instanceof GlobalProtectedRegion) {
return;
}
int height = region.getMaximumPoint().y() - region.getMinimumPoint().y();
int height = region.getMaximumPoint().getBlockY() - region.getMinimumPoint().getBlockY();
if (height <= 2) {
sender.printDebug("(Warning: The height of the region was " + (height + 1) + " block(s).)");
}
@@ -415,9 +418,9 @@ class RegionCommandsBase {
* @param flag the flag
* @param sender the sender
* @param value the value
* @throws InvalidFlagFormatException thrown if the value is invalid
* @throws InvalidFlagFormat thrown if the value is invalid
*/
protected static <V> V setFlag(ProtectedRegion region, Flag<V> flag, Actor sender, String value) throws InvalidFlagFormatException {
protected static <V> V setFlag(ProtectedRegion region, Flag<V> flag, Actor sender, String value) throws InvalidFlagFormat {
V val = flag.parseInput(FlagContext.create().setSender(sender).setInput(value).setObject("region", region).build());
region.setFlag(flag, val);
return val;
@@ -20,7 +20,6 @@
package com.sk89q.worldguard.commands.task;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.managers.RegionManager;
@@ -40,7 +39,6 @@ public class RegionAdder implements Callable<ProtectedRegion> {
private final RegionManager manager;
private final ProtectedRegion region;
private final Actor actor;
@Nullable
private String[] ownersInput;
private UserLocatorPolicy locatorPolicy = UserLocatorPolicy.UUID_ONLY;
@@ -48,26 +46,15 @@ public class RegionAdder implements Callable<ProtectedRegion> {
/**
* Create a new instance.
*
* @param manager the manager
* @param manager the manage
* @param region the region
*/
public RegionAdder(RegionManager manager, ProtectedRegion region) {
this(manager, region, null);
}
/**
* Create a new instance.
* @param manager the manager
* @param region the region
* @param actor the actor
*/
public RegionAdder(RegionManager manager, ProtectedRegion region, Actor actor) {
checkNotNull(manager);
checkNotNull(region);
this.manager = manager;
this.region = region;
this.actor = actor;
}
/**
@@ -88,9 +75,6 @@ public class RegionAdder implements Callable<ProtectedRegion> {
if (ownersInput != null) {
DomainInputResolver resolver = new DomainInputResolver(WorldGuard.getInstance().getProfileService(), ownersInput);
resolver.setLocatorPolicy(locatorPolicy);
resolver.setActor(actor);
resolver.setRegion(region);
DefaultDomain domain = resolver.call();
region.getOwners().addAll(domain);
}
@@ -101,7 +101,6 @@ public abstract class WorldConfiguration {
public boolean blockEnderDragonPortalCreation;
public boolean blockFireballExplosions;
public boolean blockFireballBlockDamage;
public boolean blockWindChargeExplosions;
public boolean blockOtherExplosions;
public boolean blockEntityPaintingDestroy;
public boolean blockEntityItemFrameDestroy;
@@ -140,8 +139,6 @@ public abstract class WorldConfiguration {
public boolean disablePlayerCropTrampling;
public boolean disableCreatureTurtleEggTrampling;
public boolean disablePlayerTurtleEggTrampling;
public boolean disableCreatureSnifferEggTrampling;
public boolean disablePlayerSnifferEggTrampling;
public boolean preventLightningFire;
public Set<String> disallowedLightningBlocks;
public boolean disableThunder;
@@ -167,7 +164,6 @@ public abstract class WorldConfiguration {
public boolean disableEndermanGriefing;
public boolean disableSnowmanTrails;
public boolean disableSoilDehydration;
public boolean disableSoilMoistureChange;
public boolean disableCoralBlockFade;
public boolean disableCopperBlockFade;
public Set<String> allowedSnowFallOver;
@@ -1,108 +0,0 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.domains;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.domains.registry.CustomDomainContext;
import com.sk89q.worldguard.domains.registry.InvalidDomainFormatException;
import com.sk89q.worldguard.util.ChangeTracked;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
public abstract class CustomDomain implements Domain, ChangeTracked {
private static final Pattern VALID_NAME = Pattern.compile("^[a-z0-9\\-]{1,40}$");
private final String name;
private boolean dirty;
public CustomDomain(String name) {
if (name == null ||!isValidName(name)) {
throw new IllegalArgumentException("Invalid Domain name used.");
}
this.name = name;
}
/**
* Get the name of the domain resolver.
*
* @return The name of the domain
*/
public String getName() {
return name;
}
/**
* Parse a given input to fill the context of the CustomDomain.
*
* @param context the {@link CustomDomainContext}
* @throws InvalidDomainFormatException Raised if the input is invalid
*/
public abstract void parseInput(CustomDomainContext context) throws InvalidDomainFormatException;
/**
* Convert a raw type that was loaded (from a YAML file, for example)
* into the custom domain.
*
* @param o The object
*/
public abstract void unmarshal(Object o);
/**
* Convert the current Domain to a storable foramt
*
* @return The marshalled type
*/
public abstract Object marshal();
/**
* Test whether a flag name is valid.
*
* @param name The flag name
* @return Whether the name is valid
*/
public static boolean isValidName(String name) {
checkNotNull(name, "name");
// g is already reserved by the group domain
return VALID_NAME.matcher(name).matches() && !name.equalsIgnoreCase("g");
}
@Override
public boolean contains(LocalPlayer player) {
return contains(player.getUniqueId());
}
@Override
public int size() {
return 1;
}
@Override
public boolean isDirty() {
return dirty;
}
@Override
public void setDirty(boolean dirty) {
this.dirty = dirty;
}
}
@@ -22,6 +22,8 @@ package com.sk89q.worldguard.domains;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sk89q.worldguard.util.profile.Profile;
import com.sk89q.worldguard.util.profile.cache.ProfileCache;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.event.ClickEvent;
@@ -29,19 +31,14 @@ import com.sk89q.worldedit.util.formatting.text.event.HoverEvent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.util.ChangeTracked;
import com.sk89q.worldguard.util.profile.Profile;
import com.sk89q.worldguard.util.profile.cache.ProfileCache;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -53,9 +50,6 @@ public class DefaultDomain implements Domain, ChangeTracked {
private PlayerDomain playerDomain = new PlayerDomain();
private GroupDomain groupDomain = new GroupDomain();
private final Map<String, CustomDomain> customDomains = new ConcurrentHashMap<>();
private boolean customDomainsChanged = false;
/**
* Create a new domain.
*/
@@ -70,7 +64,6 @@ public class DefaultDomain implements Domain, ChangeTracked {
public DefaultDomain(DefaultDomain existing) {
setPlayerDomain(existing.getPlayerDomain());
setGroupDomain(existing.getGroupDomain());
setCustomDomains(existing.customDomains);
}
/**
@@ -111,72 +104,6 @@ public class DefaultDomain implements Domain, ChangeTracked {
this.groupDomain = new GroupDomain(groupDomain);
}
/**
* Add new custom domains
*
* @param customDomain a domain
*/
public void addCustomDomain(CustomDomain customDomain) {
checkNotNull(customDomain);
this.customDomains.put(customDomain.getName(), customDomain);
this.customDomainsChanged = true;
}
/**
* Remove a custom domain matched by the name
*
* @param name the name
*/
public void removeCustomDomain(String name) {
checkNotNull(name);
if (this.customDomains.remove(name) != null) {
this.customDomainsChanged = true;
}
}
/**
* Remove a custom domain
*
* @param customDomain a domain
*/
public void removeCustomDomain(CustomDomain customDomain) {
checkNotNull(customDomain);
if (this.customDomains.remove(customDomain.getName()) != null) {
this.customDomainsChanged = true;
}
}
/**
* Set the api domains to a specified value
*
* @param customDomains the domains
*/
public void setCustomDomains(Map<String, CustomDomain> customDomains) {
checkNotNull(customDomains);
this.customDomains.clear();
this.customDomains.putAll(customDomains);
this.customDomainsChanged = true;
}
/**
* Get all api domains
*
* @return a unmodifiable copy of the domains
*/
public Collection<CustomDomain> getCustomDomains() {
return Collections.unmodifiableCollection(this.customDomains.values());
}
/**
* Get the api domain specified by its name
*
* @param name the name of the domain
* @return the custom domain
*/
public @Nullable CustomDomain getCustomDomain(String name) {
return this.customDomains.get(name);
}
/**
* Add the given player to the domain, identified by the player's name.
*
@@ -248,9 +175,6 @@ public class DefaultDomain implements Domain, ChangeTracked {
for (String group : other.getGroups()) {
addGroup(group);
}
for (CustomDomain domain : other.getCustomDomains()) {
addCustomDomain(domain);
}
}
/**
@@ -269,9 +193,6 @@ public class DefaultDomain implements Domain, ChangeTracked {
for (String group : other.getGroups()) {
removeGroup(group);
}
for (CustomDomain domain : other.getCustomDomains()) {
removeCustomDomain(domain.getName());
}
}
/**
@@ -321,12 +242,12 @@ public class DefaultDomain implements Domain, ChangeTracked {
@Override
public boolean contains(LocalPlayer player) {
return playerDomain.contains(player) || groupDomain.contains(player) || customDomains.values().stream().anyMatch(d -> d.contains(player));
return playerDomain.contains(player) || groupDomain.contains(player);
}
@Override
public boolean contains(UUID uniqueId) {
return playerDomain.contains(uniqueId) || customDomains.values().stream().anyMatch(d -> d.contains(uniqueId));
return playerDomain.contains(uniqueId);
}
@Override
@@ -336,7 +257,7 @@ public class DefaultDomain implements Domain, ChangeTracked {
@Override
public int size() {
return groupDomain.size() + playerDomain.size() + customDomains.size();
return groupDomain.size() + playerDomain.size();
}
@Override
@@ -354,6 +275,7 @@ public class DefaultDomain implements Domain, ChangeTracked {
}
public String toPlayersString(@Nullable ProfileCache cache) {
StringBuilder str = new StringBuilder();
List<String> output = new ArrayList<>();
for (String name : playerDomain.getPlayers()) {
@@ -377,7 +299,13 @@ public class DefaultDomain implements Domain, ChangeTracked {
}
output.sort(String.CASE_INSENSITIVE_ORDER);
return String.join(", ", output);
for (Iterator<String> it = output.iterator(); it.hasNext();) {
str.append(it.next());
if (it.hasNext()) {
str.append(", ");
}
}
return str.toString();
}
public String toGroupsString() {
@@ -392,20 +320,25 @@ public class DefaultDomain implements Domain, ChangeTracked {
return str.toString();
}
public String toCustomDomainsString() {
List<String> output = new ArrayList<>();
for (CustomDomain customDomain : customDomains.values()) {
output.add(customDomain.getName() + ":" + customDomain.toString());
}
output.sort(String.CASE_INSENSITIVE_ORDER);
return String.join(", ", output);
}
public String toUserFriendlyString() {
return toUserFriendlyString(null);
StringBuilder str = new StringBuilder();
if (playerDomain.size() > 0) {
str.append(toPlayersString());
}
if (groupDomain.size() > 0) {
if (str.length() > 0) {
str.append("; ");
}
str.append(toGroupsString());
}
return str.toString();
}
public String toUserFriendlyString(@Nullable ProfileCache cache) {
public String toUserFriendlyString(ProfileCache cache) {
StringBuilder str = new StringBuilder();
if (playerDomain.size() > 0) {
@@ -419,12 +352,6 @@ public class DefaultDomain implements Domain, ChangeTracked {
str.append(toGroupsString());
}
if (!customDomains.isEmpty()) {
if (str.length() > 0) {
str.append("; ");
}
str.append(toCustomDomainsString());
}
return str.toString();
}
@@ -440,12 +367,6 @@ public class DefaultDomain implements Domain, ChangeTracked {
}
builder.append(toGroupsComponent());
}
if (!customDomains.isEmpty()) {
if (playerDomain.size() > 0 || groupDomain.size() > 0) {
builder.append(TextComponent.of("; "));
}
builder.append(toCustomDomainsComponent());
}
return builder.build();
}
@@ -521,39 +442,21 @@ public class DefaultDomain implements Domain, ChangeTracked {
return builder.build();
}
private Component toCustomDomainsComponent() {
final TextComponent.Builder builder = TextComponent.builder("");
for (Iterator<CustomDomain> it = customDomains.values().iterator(); it.hasNext(); ) {
CustomDomain domain = it.next();
builder.append(TextComponent.of(domain.getName() + ":", TextColor.LIGHT_PURPLE))
.append(TextComponent.of(domain.toString(), TextColor.GOLD));
if (it.hasNext()) {
builder.append(TextComponent.of(", "));
}
}
return builder.build().hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("CustomDomain")));
}
@Override
public boolean isDirty() {
return playerDomain.isDirty() || groupDomain.isDirty() ||
customDomainsChanged || customDomains.values().stream().anyMatch(ChangeTracked::isDirty);
return playerDomain.isDirty() || groupDomain.isDirty();
}
@Override
public void setDirty(boolean dirty) {
playerDomain.setDirty(dirty);
groupDomain.setDirty(dirty);
customDomainsChanged = dirty;
customDomains.values().forEach(d -> d.setDirty(dirty));
}
@Override
public String toString() {
return "{players=" + playerDomain +
", groups=" + groupDomain +
", custom=" + customDomains +
'}';
}
@@ -1,98 +0,0 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.domains.registry;
import com.google.common.collect.Maps;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldguard.commands.CommandInputContext;
import javax.annotation.Nullable;
import java.util.Map;
public final class CustomDomainContext extends CommandInputContext<InvalidDomainFormatException> {
private CustomDomainContext(Actor sender, String input, Map<String, Object> values) {
super(sender, input, values);
}
public static CustomDomainContext.CustomDomainContextBuilder create() {
return new CustomDomainContext.CustomDomainContextBuilder();
}
/**
* Create a copy of this CustomDomainContext, with optional substitutions for values
*
* <p>If any supplied variable is null, it will be ignored.
* If a map is supplied, it will override this CustomDomainContext's values of the same key,
* but unprovided keys will not be overriden and will be returned as shallow copies.</p>
*
* @param commandSender CommandSender for the new CustomDomainContext to run under
* @param s String of the user input for the new CustomDomainContext
* @param values map of values to override from the current CustomDomainContext
* @return a copy of this CustomDomainContext
*/
public CustomDomainContext copyWith(@Nullable Actor commandSender, @Nullable String s, @Nullable Map<String, Object> values) {
Map<String, Object> map = Maps.newHashMap();
map.putAll(context);
if (values != null) {
map.putAll(values);
}
return new CustomDomainContext(commandSender == null ? this.sender : commandSender, s == null ? this.input : s, map);
}
@Override
protected InvalidDomainFormatException createException(String str) {
return new InvalidDomainFormatException(str);
}
public static class CustomDomainContextBuilder {
private Actor sender;
private String input;
private Map<String, Object> map = Maps.newHashMap();
public CustomDomainContextBuilder setSender(Actor sender) {
this.sender = sender;
return this;
}
public CustomDomainContextBuilder setInput(String input) {
this.input = input;
return this;
}
public CustomDomainContextBuilder setObject(String key, Object value) {
this.map.put(key, value);
return this;
}
public boolean tryAddToMap(String key, Object value) {
if (map.containsKey(key)) return false;
this.map.put(key, value);
return true;
}
public CustomDomainContext build() {
return new CustomDomainContext(sender, input, map);
}
}
}
@@ -1,26 +0,0 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.domains.registry;
public class DomainConflictException extends RuntimeException {
public DomainConflictException(String message) {
super(message);
}
}
@@ -1,28 +0,0 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.domains.registry;
import com.sk89q.worldguard.domains.CustomDomain;
@FunctionalInterface
public interface DomainFactory<T extends CustomDomain> {
T create(String name);
}
@@ -1,94 +0,0 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.domains.registry;
import com.sk89q.worldguard.domains.CustomDomain;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
public interface DomainRegistry extends Iterable<DomainFactory<?>> {
/**
* Register a new Domain
*
* <p>There may be an appropiate time to register domains. if domains are
* registered outside this time, then an exception may be thrown.</p>
*
* @param domain The domain
* @throws DomainConflictException Thrown when already an existing domain exists with the same name
* @throws IllegalStateException If it is not the right time to register new domains
*/
void register(String name, DomainFactory<?> domain) throws DomainConflictException;
/**
* Register a collection of domains.
*
* <p>There may be an appropriate time to register domains. If domains are
* registered outside this time, then an exception may be thrown.</p>
*
* <p>If there is a domain conflict, then an error will be logged but
* no exception will be thrown.</p>
*
* @param domains a collection of domain factories
* @throws IllegalStateException If it is not the right time to register new domains
*/
void registerAll(Map<String, DomainFactory<?>> domains);
/**
* Get the domain by its name.
*
* @param name The name
* @return The domain, if it has been registered
*/
@Nullable
DomainFactory<?> get(String name);
/**
* Try to get a domain by its name
*/
@Nullable
CustomDomain createDomain(String name);
/**
* Get all domains keyed by the registered name
*
* @return All domains
*/
Map<String, DomainFactory<?>> getAll();
/**
* Unmarshal a raw map of values into a list of domains with their
* unmarshalled values.
*
* @param rawValues The raw values map
* @param createUnknown Whether "just in time" domains should be created for unknown domains
* @return The unmarshalled domain list
*/
Map<String, CustomDomain> unmarshal(Map<String, Object> rawValues, boolean createUnknown);
/**
* Get the number of registered domains.
*
* @return The number of registered domains
*/
int size();
}
@@ -1,28 +0,0 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.domains.registry;
public class InvalidDomainFormatException extends Exception {
private static final long serialVersionUID = 8101615074524004172L;
public InvalidDomainFormatException(String msg) {
super(msg);
}
}
@@ -1,166 +0,0 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.domains.registry;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.sk89q.worldguard.domains.CustomDomain;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.google.common.base.Preconditions.checkNotNull;
public class SimpleDomainRegistry implements DomainRegistry {
private static final Logger log = Logger.getLogger(SimpleDomainRegistry.class.getCanonicalName());
private final Object lock = new Object();
private final ConcurrentMap<String, DomainFactory<?>> domains = Maps.newConcurrentMap();
private boolean initialized = false;
public boolean isInitialized() {
return initialized;
}
public void setInitialized(boolean initialized) {
this.initialized = initialized;
}
@Override
public void register(String name, DomainFactory<?> domain) throws DomainConflictException {
synchronized (lock) {
if (initialized) {
throw new IllegalStateException("New domains cannot be registered at this time");
}
forceRegister(name, domain);
}
}
@Override
public void registerAll(Map<String, DomainFactory<?>> domains) {
synchronized (lock) {
for (Map.Entry<String, DomainFactory<?>> entry : domains.entrySet()) {
try {
register(entry.getKey(), entry.getValue());
} catch (DomainConflictException e) {
log.log(Level.WARNING, e.getMessage());
}
}
}
}
private <T extends DomainFactory<?>> T forceRegister(String name, T domain) throws DomainConflictException {
checkNotNull(domain, "domain");
checkNotNull(name, "name");
if (!CustomDomain.isValidName(name)) {
throw new IllegalArgumentException("Invalid Domain name used.");
}
synchronized (lock) {
if (domains.containsKey(name)) {
throw new DomainConflictException("A domain already exists by the name " + name);
}
domains.put(name, domain);
}
return domain;
}
@Nullable
@Override
public DomainFactory<?> get(String name) {
checkNotNull(name, "name");
return domains.get(name.toLowerCase());
}
@Nullable
@Override
public CustomDomain createDomain(String name) {
DomainFactory<?> factory = get(name);
if (factory == null) return null;
return factory.create(name);
}
@Override
public Map<String, DomainFactory<?>> getAll() {
return ImmutableMap.copyOf(domains);
}
private CustomDomain getOrCreate(String name, Object value, boolean createUnknown) {
CustomDomain customDomain = createDomain(name);
if (customDomain != null) {
customDomain.unmarshal(value);
return customDomain;
}
synchronized (lock) {
customDomain = createDomain(name); // Load again because the previous load was not synchronized
if (customDomain != null) {
customDomain.unmarshal(value);
return customDomain;
}
if (createUnknown) {
DomainFactory<UnknownDomain> unknownFactory = forceRegister(name, UnknownDomain.FACTORY);
if (unknownFactory != null) {
customDomain = unknownFactory.create(name);
if (customDomain != null) customDomain.unmarshal(value);
return customDomain;
}
}
}
return null;
}
public Map<String, CustomDomain> unmarshal(Map<String, Object> rawValues, boolean createUnknown) {
checkNotNull(rawValues, "rawValues");
Map<String, CustomDomain> domains = new HashMap<>();
for (Map.Entry<String, Object> entry : rawValues.entrySet()) {
try {
CustomDomain domain = getOrCreate(entry.getKey(), entry.getValue(), createUnknown);
domains.put(domain.getName(), domain);
} catch (Throwable e) {
log.log(Level.WARNING, "Failed to unmarshal domain for " + entry.getKey(), e);
}
}
return domains;
}
@Override
public int size() {
return domains.size();
}
@Override
public Iterator<DomainFactory<?>> iterator() {
return Iterators.unmodifiableIterator(domains.values().iterator());
}
}
@@ -1,88 +0,0 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.domains.registry;
import com.sk89q.worldguard.domains.CustomDomain;
import java.util.UUID;
public class UnknownDomain extends CustomDomain {
public static DomainFactory<UnknownDomain> FACTORY = UnknownDomain::new;
private boolean isDirty = false;
private Object o;
public UnknownDomain(String name) {
super(name);
}
@Override
public void parseInput(CustomDomainContext context) throws InvalidDomainFormatException {
throw new InvalidDomainFormatException("The plugin that registered this domain is not currently installed");
}
@Override
public void unmarshal(Object o) {
this.o = o;
}
@Override
public Object marshal() {
return o;
}
@Override
public boolean contains(UUID uniqueId) {
return false;
}
@Override
public boolean contains(String playerName) {
return false;
}
@Override
public int size() {
return 0;
}
@Override
public void clear() {
isDirty = true;
o = null;
}
@Override
public void setDirty(boolean dirty) {
isDirty = dirty;
}
@Override
public boolean isDirty() {
return isDirty;
}
@Override
public String toString() {
return "UnknownDomain{" +
"o=" + o +
'}';
}
}
@@ -176,14 +176,13 @@ public class RegionPermissionModel extends AbstractPermissionModel {
public boolean mayRemoveOwners(ProtectedRegion region) {
return hasPatternPermission("removeowner", region);
}
/**
* Checks to see if the given sender has permission to modify the given region
* using the region permission pattern.
*
* @param perm the name of the node
* @param region the region
* @return whether the actor has the permission
*/
private boolean hasPatternPermission(String perm, ProtectedRegion region) {
if (!(getSender() instanceof Player)) {
@@ -33,7 +33,7 @@ public class BooleanFlag extends Flag<Boolean> {
}
@Override
public Boolean parseInput(FlagContext context) throws InvalidFlagFormatException {
public Boolean parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
if (input.equalsIgnoreCase("true") || input.equalsIgnoreCase("yes")
@@ -45,7 +45,7 @@ public class BooleanFlag extends Flag<Boolean> {
|| input.equalsIgnoreCase("0")) {
return false;
} else {
throw new InvalidFlagFormatException("Not a yes/no value: " + input);
throw new InvalidFlagFormat("Not a yes/no value: " + input);
}
}
@@ -33,7 +33,7 @@ public class CommandStringFlag extends Flag<String> {
}
@Override
public String parseInput(FlagContext context) throws InvalidFlagFormatException {
public String parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
input = input.trim();
if (!input.startsWith("/")) {
@@ -33,7 +33,7 @@ public class DoubleFlag extends NumberFlag<Double> {
}
@Override
public Double parseInput(FlagContext context) throws InvalidFlagFormatException {
public Double parseInput(FlagContext context) throws InvalidFlagFormat {
return context.getUserInputAsDouble();
}
@@ -40,12 +40,12 @@ public class EntityTypeFlag extends Flag<EntityType> {
}
@Override
public EntityType parseInput(FlagContext context) throws InvalidFlagFormatException {
public EntityType parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
input = input.trim();
EntityType entityType = unmarshal(input);
if (entityType == null) {
throw new InvalidFlagFormatException("Unknown entity type: " + input);
throw new InvalidFlagFormat("Unknown entity type: " + input);
}
return entityType;
}
@@ -57,6 +57,6 @@ public class EntityTypeFlag extends Flag<EntityType> {
@Override
public Object marshal(EntityType o) {
return o.id();
return o.getId();
}
}
@@ -74,12 +74,12 @@ public class EnumFlag<T extends Enum<T>> extends Flag<T> {
}
@Override
public T parseInput(FlagContext context) throws InvalidFlagFormatException {
public T parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
try {
return findValue(input);
} catch (IllegalArgumentException e) {
throw new InvalidFlagFormatException("Unknown value '" + input + "' in "
throw new InvalidFlagFormat("Unknown value '" + input + "' in "
+ enumClass.getName());
}
}
@@ -181,9 +181,9 @@ public abstract class Flag<T> {
*
* @param context the {@link FlagContext}
* @return The coerced type
* @throws InvalidFlagFormatException Raised if the input is invalid
* @throws InvalidFlagFormat Raised if the input is invalid
*/
public abstract T parseInput(FlagContext context) throws InvalidFlagFormatException;
public abstract T parseInput(FlagContext context) throws InvalidFlagFormat;
/**
* Convert a raw type that was loaded (from a YAML file, for example)
@@ -21,28 +21,106 @@ package com.sk89q.worldguard.protection.flags;
import com.google.common.collect.Maps;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.commands.CommandInputContext;
import javax.annotation.Nullable;
import java.util.Map;
public final class FlagContext extends CommandInputContext<InvalidFlagFormatException> {
import javax.annotation.Nullable;
public final class FlagContext {
private final Actor sender;
private final String input;
private Map<String, Object> context;
private FlagContext(Actor sender, String input, Map<String, Object> values) {
super(sender, input, values);
this.sender = sender;
this.input = input;
this.context = values;
}
public static FlagContext.FlagContextBuilder create() {
public static FlagContextBuilder create() {
return new FlagContextBuilder();
}
public void put(String name, Object value) {
context.put(name, value);
}
public Actor getSender() {
return sender;
}
public String getUserInput() {
return input;
}
/**
* Gets the CommandSender as a player.
*
* @return Player
* @throws InvalidFlagFormat if the sender is not a player
*/
public LocalPlayer getPlayerSender() throws InvalidFlagFormat {
if (sender.isPlayer() && sender instanceof LocalPlayer) {
return (LocalPlayer) sender;
} else {
throw new InvalidFlagFormat("Not a player");
}
}
public Integer getUserInputAsInt() throws InvalidFlagFormat {
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
throw new InvalidFlagFormat("Not a number: " + input);
}
}
public Double getUserInputAsDouble() throws InvalidFlagFormat {
try {
return Double.parseDouble(input);
} catch (NumberFormatException e) {
throw new InvalidFlagFormat("Not a number: " + input);
}
}
/**
* Get an object from the context by key name.
* May return null if the object does not exist in the context.
*
* @param name key name of the object
* @return the object matching the key, or null
*/
@Nullable
public Object get(String name) {
return get(name, null);
}
/**
* Get an object from the context by key name.
* Will only return null if
* a) you provide null as the default
* b) the key has explicity been set to null
*
* @param name key name of the object
* @return the object matching the key
*/
@Nullable
public Object get(String name, Object defaultValue) {
Object obj;
return (((obj = context.get(name)) != null) || context.containsKey(name)
? obj : defaultValue);
}
/**
* Create a copy of this FlagContext, with optional substitutions for values
*
* <p>If any supplied variable is null, it will be ignored.
* If any supplied variable is null, it will be ignored.
* If a map is supplied, it will override this FlagContext's values of the same key,
* but unprovided keys will not be overriden and will be returned as shallow copies.</p>
* but unprovided keys will not be overriden and will be returned as shallow copies.
*
* @param commandSender CommandSender for the new FlagContext to run under
* @param s String of the user input for the new FlagContext
@@ -58,11 +136,6 @@ public final class FlagContext extends CommandInputContext<InvalidFlagFormatExce
return new FlagContext(commandSender == null ? this.sender : commandSender, s == null ? this.input : s, map);
}
@Override
protected InvalidFlagFormatException createException(String str) {
return new InvalidFlagFormatException(str);
}
public static class FlagContextBuilder {
private Actor sender;
private String input;
@@ -74,7 +74,6 @@ public final class Flags {
public static final StateFlag FIREWORK_DAMAGE = register(new StateFlag("firework-damage", false));
public static final StateFlag USE_ANVIL = register(new StateFlag("use-anvil", false));
public static final StateFlag USE_DRIPLEAF = register(new StateFlag("use-dripleaf", false));
public static final StateFlag WIND_CHARGE_BURST = register(new StateFlag("wind-charge-burst", false));
// These flags are similar to the ones above (used in tandem with BUILD),
// but their defaults are set to TRUE because it is more user friendly.
@@ -92,9 +91,9 @@ public final class Flags {
public static final StateFlag MOB_DAMAGE = register(new StateFlag("mob-damage", true));
public static final StateFlag CREEPER_EXPLOSION = register(new StateFlag("creeper-explosion", true));
public static final StateFlag ENDERDRAGON_BLOCK_DAMAGE = register(new StateFlag("enderdragon-block-damage", true));
public static final StateFlag CREEPER_BLOCK_DAMAGE = register(new StateFlag("creeper-block-damage", true));
public static final StateFlag GHAST_FIREBALL = register(new StateFlag("ghast-fireball", true));
public static final StateFlag OTHER_EXPLOSION = register(new StateFlag("other-explosion", true));
public static final StateFlag BREEZE_WIND_CHARGE = register(new StateFlag("breeze-charge-explosion", true));
public static final StateFlag WITHER_DAMAGE = register(new StateFlag("wither-damage", true));
public static final StateFlag ENDER_BUILD = register(new StateFlag("enderman-grief", true));
public static final StateFlag SNOWMAN_TRAILS = register(new StateFlag("snowman-trails", true));
@@ -130,7 +129,6 @@ public final class Flags {
public static final StateFlag COPPER_FADE = register(new StateFlag("copper-fade", true));
public static final StateFlag WATER_FLOW = register(new StateFlag("water-flow", true));
public static final StateFlag LAVA_FLOW = register(new StateFlag("lava-flow", true));
public static final StateFlag MOISTURE_CHANGE = register(new StateFlag("moisture-change", true));
public static final RegistryFlag<WeatherType> WEATHER_LOCK = register(new RegistryFlag<>("weather-lock", WeatherType.REGISTRY));
public static final StringFlag TIME_LOCK = register(new StringFlag("time-lock"));
@@ -40,12 +40,12 @@ public class GameModeTypeFlag extends Flag<GameMode> {
}
@Override
public GameMode parseInput(FlagContext context) throws InvalidFlagFormatException {
public GameMode parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
input = input.trim();
GameMode gamemode = unmarshal(input);
if (gamemode == null) {
throw new InvalidFlagFormatException("Unknown game mode: " + input);
throw new InvalidFlagFormat("Unknown game mode: " + input);
}
return gamemode;
}
@@ -57,6 +57,6 @@ public class GameModeTypeFlag extends Flag<GameMode> {
@Override
public Object marshal(GameMode o) {
return o.id();
return o.getId();
}
}
@@ -33,7 +33,7 @@ public class IntegerFlag extends NumberFlag<Integer> {
}
@Override
public Integer parseInput(FlagContext context) throws InvalidFlagFormatException {
public Integer parseInput(FlagContext context) throws InvalidFlagFormat {
return context.getUserInputAsInt();
}
@@ -19,10 +19,6 @@
package com.sk89q.worldguard.protection.flags;
/**
* @deprecated replaced by {@link InvalidFlagFormatException}. Will be removed in WorldGuard 8
*/
@Deprecated(forRemoval = true)
public class InvalidFlagFormat extends Exception {
private static final long serialVersionUID = 8101615074524004172L;
@@ -1,28 +0,0 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.flags;
public class InvalidFlagFormatException extends InvalidFlagFormat {
private static final long serialVersionUID = 8101615074524004172L;
public InvalidFlagFormatException(String msg) {
super(msg);
}
}
@@ -41,7 +41,7 @@ public class LocationFlag extends Flag<Location> {
}
@Override
public Location parseInput(FlagContext context) throws InvalidFlagFormatException {
public Location parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
Player player = context.getPlayerSender();
@@ -76,7 +76,7 @@ public class LocationFlag extends Flag<Location> {
player.printDebug("WARNING: Flag location is outside of region.");
} else {
// no permission
throw new InvalidFlagFormatException("You can't set that flag outside of the region boundaries.");
throw new InvalidFlagFormat("You can't set that flag outside of the region boundaries.");
}
}
// clamp height to world limits
@@ -86,7 +86,7 @@ public class LocationFlag extends Flag<Location> {
}
return loc;
}
throw new InvalidFlagFormatException("Expected 'here' or x,y,z.");
throw new InvalidFlagFormat("Expected 'here' or x,y,z.");
}
@Override
@@ -137,9 +137,9 @@ public class LocationFlag extends Flag<Location> {
return null;
}
}
vec.put("x", position.x());
vec.put("y", position.y());
vec.put("z", position.z());
vec.put("x", position.getX());
vec.put("y", position.getY());
vec.put("z", position.getZ());
vec.put("yaw", o.getYaw());
vec.put("pitch", o.getPitch());
return vec;
@@ -70,7 +70,7 @@ public class MapFlag<K, V> extends Flag<Map<K, V>> {
}
@Override
public Map<K, V> parseInput(final FlagContext context) throws InvalidFlagFormatException {
public Map<K, V> parseInput(final FlagContext context) throws InvalidFlagFormat {
final String input = context.getUserInput();
if (input.isEmpty()) {
@@ -83,7 +83,7 @@ public class MapFlag<K, V> extends Flag<Map<K, V>> {
final char split = str.indexOf('=') == -1 ? ':' : '=';
final String[] keyVal = str.split(String.valueOf(split));
if (keyVal.length != 2) {
throw new InvalidFlagFormatException("Input must be in a 'key:value,key1=value1' format. Either ':' or '=' can be used.");
throw new InvalidFlagFormat("Input must be in a 'key:value,key1=value1' format. Either ':' or '=' can be used.");
}
final FlagContext key = context.copyWith(null, keyVal[0], null);
@@ -44,10 +44,10 @@ public class RegistryFlag<T extends Keyed> extends Flag<T> {
}
@Override
public T parseInput(FlagContext context) throws InvalidFlagFormatException {
public T parseInput(FlagContext context) throws InvalidFlagFormat {
final String key = context.getUserInput().trim().toLowerCase(Locale.ROOT);
return Optional.ofNullable(registry.get(key))
.orElseThrow(() -> new InvalidFlagFormatException("Unknown " + registry.getName() + ": " + key));
.orElseThrow(() -> new InvalidFlagFormat("Unknown " + registry.getName() + ": " + key));
}
public Registry<T> getRegistry() {
@@ -61,6 +61,6 @@ public class RegistryFlag<T extends Keyed> extends Flag<T> {
@Override
public Object marshal(T o) {
return o.id();
return o.getId();
}
}
@@ -58,7 +58,7 @@ public class SetFlag<T> extends Flag<Set<T>> {
}
@Override
public Set<T> parseInput(FlagContext context) throws InvalidFlagFormatException {
public Set<T> parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
if (input.isEmpty()) {
return Sets.newHashSet();
@@ -78,7 +78,7 @@ public class StateFlag extends Flag<StateFlag.State> {
}
@Override
public State parseInput(FlagContext context) throws InvalidFlagFormatException {
public State parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
if (input.equalsIgnoreCase("allow")) {
@@ -88,7 +88,7 @@ public class StateFlag extends Flag<StateFlag.State> {
} else if (input.equalsIgnoreCase("none")) {
return null;
} else {
throw new InvalidFlagFormatException("Expected none/allow/deny but got '" + input + "'");
throw new InvalidFlagFormat("Expected none/allow/deny but got '" + input + "'");
}
}
@@ -57,7 +57,7 @@ public class StringFlag extends Flag<String> {
}
@Override
public String parseInput(FlagContext context) throws InvalidFlagFormatException {
public String parseInput(FlagContext context) throws InvalidFlagFormat {
String lines = context.getUserInput().replaceAll("(?<!\\\\)\\\\n", "\n").replaceAll("\\\\\\\\n", "\\\\n");
// Add color codes
lines = CommandUtils.replaceColorMacros(lines);
@@ -48,7 +48,7 @@ public class TimestampFlag extends Flag<Instant> {
}
@Override
public Instant parseInput(FlagContext context) throws InvalidFlagFormatException {
public Instant parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
if ("now".equalsIgnoreCase(input)) {
return Instant.now();
@@ -61,10 +61,10 @@ public class TimestampFlag extends Flag<Instant> {
} else if (parsed instanceof ZonedDateTime) {
return ((ZonedDateTime) parsed).toInstant();
} else {
throw new InvalidFlagFormatException("Unrecognized input.");
throw new InvalidFlagFormat("Unrecognized input.");
}
} catch (DateTimeParseException ignored) {
throw new InvalidFlagFormatException("Expected 'now' or ISO 8601 formatted input.");
throw new InvalidFlagFormat("Expected 'now' or ISO 8601 formatted input.");
}
}
}
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff. Show more