diff --git a/.github/CONTRIBUTING.MD b/.github/CONTRIBUTING.MD new file mode 100644 index 00000000..6bd4afd0 --- /dev/null +++ b/.github/CONTRIBUTING.MD @@ -0,0 +1,49 @@ +## Contributing to ArmorStandEditor + +We are happy that you are willing to contribute. Usually, we are very lenient with all PRs, but there are still some guidelines you can follow to make the approval process go smoother. + +- Do you run a server and have experience in Development? Take a look at our ["Help Wanted"](https://github.com/Wolfieheart/ArmorStandEditor/labels/help%20wanted) and ["BUG-0: Pending Investigation"](https://github.com/Wolfieheart/ArmorStandEditor/labels/BUG-0%3A%20Pending%20Investigation) Issues, where you can find issues that need extra testing and investigation. +- Do you speak multiple languages? If so, we always welcome contributions for our Language Files/Translations + +## Contributing Code? +Code Contributions are always welcomed and are made via GitHub's Pull Request System. Make a Personal Fork of the ArmorStandEditor repository (this) and open it in your IDE of Choice. +You can ask for any information/help on your idea/contribution to the [ASE Discord](https://discord.com/invite/aUf4AWAKmr) in the #development channel. + +- Please make sure to read our [License](https://github.com/Wolfieheart/ArmorStandEditor/blob/master/LICENSE.md) before contributing. If you do not agree with the terms and conditions of our license, please do not contribute any code. +- By making a pull request, you represent that you have the right to waive copyright and related rights to your contribution, and agree that all copyright and related rights in your contributions are waived, and you acknowledge that we have the copyright to use and modify your contribution under our [License](https://github.com/Wolfieheart/ArmorStandEditor/blob/master/LICENSE.md) for perpetuity. + +## Making Any Changes +- Create a personal fork (not an org fork) of the ArmorStandEditor repository (this). + - Name your branch something relevant (i.e: /dev/\/\) + - Work off the Development Branch unless already Merged into Main - This will therefore allow Developments to be merged together to 1 big branch + - To create a branch in Git; + - `git branch relevantBranchName` + - Then checkout the new branch with `git checkout relevantBranchName` + - Check for unnecessary whitespace with `git diff --check` before committing. + - Please follow the below for Commits: + - `[CORE]` annotation for New Features, Bug Fixes, Performance Improvements etc. + - `[CI]` annotation for changes related to Continuous Integration + - `[DOC]` annotation for Documenting - Either code or fixing the wiki + - `[LANG]` annotation for new languages/updated translations + - `[MISC]` annotation for anything that does not fit the above requirements + +## Code requirements +- You must use Tabs (Size 4 Spaces). +- Keep your environment in Java 17. GitHub handles building all of this into Java 17 and 18, but keep in mind that, while you will be able to use modern language features that way (like patterns), some standard library methods added after jdk 11 (the minimum supported version: 55.0 for certain plugins) will not work and cause "cannot find symbol" errors when building (like String.isBlank). +- Avoid Wildcard Imports (Preferred, but is allowed. Let me know if this can't be avoided on Discord.) +- Don't run IDE Formatters over entire class files, unless it's a new class-file you're implementing + - This is done to avoid us changing the lines everytime, each IDE is different, so we don't have a constant here and there. + - This also keeps file compares on GitHub simple. +- Reflection should be a last resort. +- Do not use NMS or CraftBukkit Code. Bukkit/Spigot API calls only. + + +## Contributing translations +Translations of ArmorStandEditor's Base Language File [English (US)](https://github.com/Wolfieheart/ArmorStandEditor/blob/master/src/main/resources/lang/en_US.yml) are welcomed and can be done following the Code Guidelines outlined above. + +- Do not work on the en_US.yml base file, this gets overwritten when the plugin gets enabled. Please create a new language file +- Language files are stored in `resources/lang/.yml` + - Usually Name_Here points to Language Code and Land Code (ex: nl_BE.yml). + - Examples can be found [here](https://www.fincher.org/Utilities/CountryLanguageList.shtml). +- Change the formatting codes at the start of a file as desired. +- Please add your language/translation on the Discord, so we know that you added it. We will handle the rest by working off your branch such as adding it to the Metrics tool and adding it to the update routine. diff --git a/.github/ISSUE_TEMPLATE/behaviour-bug.yml b/.github/ISSUE_TEMPLATE/behaviour-bug.yml new file mode 100644 index 00000000..37bd340d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/behaviour-bug.yml @@ -0,0 +1,55 @@ +name: Behavior Bug or other issue +description: Report issues with the plugin or other behavior related issues. +labels: ["bug", "BUG-0: Pending Investigation"] +title: "[Bug]: " +body: + - type: markdown + attributes: + value: | + Before reporting a crash here, please make sure you are on the latest version of the Plugin. + Forks of the plugin receive no support here. If you are using a fork, please make sure that this issue also happens when using the latest release. + + - type: textarea + attributes: + label: Expected behavior + description: What you expected to see. + validations: + required: true + - type: textarea + attributes: + label: Observed/Actual behavior + description: What you actually saw. + validations: + required: true + - type: textarea + attributes: + label: Steps/models to reproduce + description: This may include a build schematic, a video, or detailed instructions to help reconstruct the issue. + validations: + required: true + - type: textarea + attributes: + label: Plugin list + description: All plugins running on the server. + validations: + required: true + - type: textarea + attributes: + label: Plugin Version + description: What version of the Plugin are you using for this? As of 1.18, you can get this via /ase version. + validations: + required: true + - type: textarea + attributes: + label: Server Version + description: What Server Backend are you using? Put your output of /version ingame here + validations: + required: true + - type: textarea + attributes: + label: Other + description: | + Please include other helpful information below. + The more information we receive, the quicker and more effective we can be at finding the solution to the issue. + validations: + required: false \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature-request.yml b/.github/ISSUE_TEMPLATE/feature-request.yml new file mode 100644 index 00000000..93d8b651 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature-request.yml @@ -0,0 +1,46 @@ +name: Feature Request +description: Suggest an idea for ArmorStandEditor +labels: ["NF-0: Pending Investigation"] +body: + - type: markdown + attributes: + value: | + Thank you for filling out a feature request for ArmorStandEditor! Please be as detailed as possible so that we may consider and review the request easier. + We ask that you search all the issues to avoid a duplicate feature request. If one exists, please reply if you have anything to add. + + - type: textarea + attributes: + label: Is your feature request related to a problem? + description: Please give some context for this request. Why do you want it added? + validations: + required: true + - type: textarea + attributes: + label: Describe the solution you'd like. + description: A clear and concise description of what you want. + validations: + required: true + - type: textarea + attributes: + label: Describe alternatives you've considered. + description: List any alternatives you might have tried to get the feature you want. + validations: + required: true + + - type: checkboxes + attributes: + label: Agreements + description: Please agree to the following. Failure to check these will result in your issue being marked CLOSED and INVALID. + options: + - label: I have searched for and ensured there isn't already an open issue regarding this. + required: true + - label: I have ensured the feature I'm requesting isn't already in the latest ArmorStandEditor Build. + required: true + + + - type: textarea + attributes: + label: Other + description: Add any other context or screenshots about the feature request below. + validations: + required: false diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..2c4ac4c7 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,18 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + # Maintain dependencies for GitHub Actions + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + + # Maintain dependencies for maven + - package-ecosystem: "maven" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..dbfa411d --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,32 @@ + +#### Description: + + +---- +### [CORE] Changes +*Changes to the core of the plugin - Performance Fixes, Bug Fixes, New Features, New Permission Nodes, New Config Options etc.* + + + + +---- +### [CI] Changes +*Changes relating to the Continuous Integration of other Plugin APIs, Github Workflows, Issue Templates etc.* + + +---- +### [DOC] Changes +*Changes relating to plugin Documentation - See the Wiki for more info* + + +---- +### [MISC] Changes +*Changes that does not fit in the above list* + + + +____ +- [ ] I have tested this pull request for defects on a server. + + +By making this pull request, I represent that I have the right to waive copyright and related rights to my contribution, and agree that all copyright and related rights in my contributions are waived, and I acknowledge that the ArmorStandEditor Project Owners have the copyright to use and modify my contribution under the ArmorStandEditor [License](https://github.com/Wolfieheart/ArmorStandEditor/blob/master/LICENSE.md) for perpetuity. \ No newline at end of file diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 00000000..a5dda050 --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,19 @@ +daysUntilStale: 60 +daysUntilClose: 7 +exemptLabels: + - "Build: Devel" + - "bug" + - "NF-0: Accepted" + - "NF-2: Implementation - In Progress" + - "NF-4: Rebase Required" + - "BUG-1: Reproduced" + - "Work in Progress" +staleLabel: "Stale" +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +closeComment: > + This issue has been automatically closed because it has not had activity in + a long time. If the issue still applies to the most recent supported + version, please open a new issue referencing this original issue. diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml new file mode 100644 index 00000000..7485c970 --- /dev/null +++ b/.github/workflows/maven-publish.yml @@ -0,0 +1,63 @@ +# This workflow will build a Java project with Maven +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven + +name: Java CI with Maven +on: [push, pull_request] + +jobs: + compile: + if: "!contains(github.event.head_commit.message, 'ci-skip') || !contains(github.event.head_commit.message, 'CI-SKIP') || !contains(github.event.head_commit.message, 'CI SKIP') || !contains(github.event.head_commit.message, 'ci skip') " + runs-on: ubuntu-latest + strategy: + matrix: + java: ['21'] + steps: + # 1. Check out the current working tree + - name: Checkout ArmorStandEditor Repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + + # 2. Setup Java JDK + - name: Set up JDK Environments + uses: actions/setup-java@v4 + with: + java-version: ${{ matrix.java }} + distribution: 'zulu' + + # 3. Setup local Maven package cache to speed up building + - name: Cache SonarCloud packages + uses: actions/cache@v4 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + + - name: Cache Maven packages + uses: actions/cache@v4 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-m2 + + # 4. Build via Maven + - name: Build and analyze + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=wolfieheart_ArmorStandEditor + + #5: Create a Clean Package - and Verify it + - name: Clean package + run: mvn -B clean package + + - name: Clean Verify + run: mvn -B clean verify + + #6 Upload Artifacts (Debug Purposes) + - name: Upload Artifact for Debugging + uses: actions/upload-artifact@v4.5.0 + with: + name: artifact + path: /home/runner/work/ArmorStandEditor/ArmorStandEditor/target/armorstandeditor-*-*.jar + if-no-files-found: error diff --git a/.github/workflows/nightly-build.yml b/.github/workflows/nightly-build.yml new file mode 100644 index 00000000..68926461 --- /dev/null +++ b/.github/workflows/nightly-build.yml @@ -0,0 +1,136 @@ +name: Nightly ASE Build of Main (CI/CD) + +on: + schedule: + - cron: "0 23 * * *" + +jobs: + nightly-build-java21: + runs-on: ubuntu-latest + strategy: + matrix: + java_version: ['21'] + + steps: + # Checkout the repository + - name: Checkout ArmorStandEditor + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # Set up the Java Development Kit (JDK) + - name: Setup JDK ${{ matrix.java_version }} + uses: actions/setup-java@v4.7.0 + with: + java-version: ${{ matrix.java_version }} + distribution: 'zulu' + + # Cache SonarCloud for analysis + - name: Cache SonarCloud for Analysis + uses: actions/cache@v4.2.0 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + + # Cache Maven packages to speed up build + - name: Cache the Maven Packages to speed up build + uses: actions/cache@v4.2.0 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-m2 + + # Build and analyze the project using Maven and SonarCloud + - name: Build and analyze via Maven + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=wolfieheart_ArmorStandEditor + + # Clean and verify the build + - name: Clean Verify + run: mvn -B clean verify + + # Get the current date and time + - name: Get Current Date and Time + id: date + run: echo "DATE=$(date +'%Y-%m-%d_%H-%M-%S')" >> $GITHUB_ENV + + # Rename the artifact file with the current date and time + - name: Rename Artifact + run: | + ARTIFACT_PATH=$(find /home/runner/work/ArmorStandEditor/ArmorStandEditor/target/ -name 'armorstandeditor-*-*.jar') + mv $ARTIFACT_PATH "${ARTIFACT_PATH%.jar}-${{ env.DATE }}-Java21.jar" + + # Upload the renamed artifact for debugging + - name: Upload Artifact for Debugging + uses: actions/upload-artifact@v4 + with: + name: artifact + path: /home/runner/work/ArmorStandEditor/ArmorStandEditor/target/armorstandeditor-*-*-Java21.jar + if-no-files-found: error + retention-days: 1 + overwrite: true + +# nightly-build-java17: +# runs-on: ubuntu-latest +# strategy: +# matrix: +# java_version: ['17'] + +# steps: +# # Checkout the repository +# - name: Checkout ArmorStandEditor +# uses: actions/checkout@v4 +# with: +# fetch-depth: 0 +# + # Set up the Java Development Kit (JDK) +# - name: Setup JDK ${{ matrix.java_version }} +# uses: actions/setup-java@v4.2.1 +# with: +# java-version: ${{ matrix.java_version }} +# distribution: 'temurin' + + # Cache SonarCloud for analysis +# - name: Cache SonarCloud for Analysis +# uses: actions/cache@v4.0.2 +# with: +# path: ~/.sonar/cache +# key: ${{ runner.os }}-sonar +# restore-keys: ${{ runner.os }}-sonar + +# - name: Cache the Maven Packages to speed up build +# uses: actions/cache@v4.0.2 +# with: +# path: ~/.m2 +# key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} +# restore-keys: ${{ runner.os }}-m2 + +# - name: Build and analyze via Maven +# env: +# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any +# SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} +# run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=wolfieheart_ArmorStandEditor + +# - name: Clean Verify +# run: mvn -B clean verify + +# - name: Get Current Date and Time +# id: date +# run: echo "DATE=$(date +'%Y-%m-%d_%H-%M-%S')" >> $GITHUB_ENV + +# - name: Rename Artifact +# run: | +# ARTIFACT_PATH=$(find /home/runner/work/ArmorStandEditor/ArmorStandEditor/target/ -name 'armorstandeditor-*-*.jar') +# mv $ARTIFACT_PATH "${ARTIFACT_PATH%.jar}-${{ env.DATE }}-Java17.jar" + +# - name: Upload Artifact for Debugging +# uses: actions/upload-artifact@v4 +# with: +# name: artifact +# path: /home/runner/work/ArmorStandEditor/ArmorStandEditor/target/armorstandeditor-*-*-Java17.jar +# if-no-files-found: error +# retention-days: 1 +# overwrite: true diff --git a/.github/workflows/todo.yml b/.github/workflows/todo.yml new file mode 100644 index 00000000..eb8bb073 --- /dev/null +++ b/.github/workflows/todo.yml @@ -0,0 +1,12 @@ +name: "Run TODO to Issue" +on: ["push"] +jobs: + build: + runs-on: "ubuntu-latest" + steps: + - uses: "actions/checkout@v4" + - name: "TODO to Issue" + uses: "alstr/todo-to-issue-action@v5" + with: + AUTO_ASSIGN: true + IDENTIFIERS: '[{"name": "TODO", "labels": ["help wanted"]}, {"name": "FIXME", "labels": ["bug"]}]' diff --git a/.gitignore b/.gitignore index e6ebc35e..548981ba 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,12 @@ .idea/ target/ -*.iml \ No newline at end of file +*.iml +/bin/ +/.project +/.classpath +/.settings/ +/src/main/java/META-INF/*.MF +/src/main/java/META-INF/ +/TODO-LIST.MD +/dependency-reduced-pom.xml +.mvn/.develocity/ diff --git a/API-Example-Plugin/pom.xml b/API-Example-Plugin/pom.xml new file mode 100644 index 00000000..0259c210 --- /dev/null +++ b/API-Example-Plugin/pom.xml @@ -0,0 +1,115 @@ + + 4.0.0 + io.github.rypofalem.apiexample + armorstandeditor-apitest + jar + 1.21-47 + armorstandeditor-apitest + s://maven.apache.org + + + 17 + UTF-8 + 3.0.1 + wolfieheart + https://sonarcloud.io + + + + + Wolfieheart + Wolfieheart + https://github.com/Wolfieheart + + + RypoFalem + RypoFalem + https://github.com/RypoFalem + + + + + + + spigot-repo + https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + + + paper-repo + https://repo.papermc.io/repository/maven-public/ + + + jitpack.io + https://jitpack.io + + + + + + + org.spigotmc + spigot-api + 1.20.1-R0.1-SNAPSHOT + provided + + + dev.folia + folia-api + 1.19.4-R0.1-SNAPSHOT + provided + + + com.github.wolfieheart + armorstandeditor + 1.20.2-44.1 + provided + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + compile + package + + attach-artifact + + + + + ${project.build.directory}/${project.artifactId}.jar + jar + optional + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.12.0 + + 17 + 17 + + + + org.apache.maven.plugins + maven-release-plugin + ${maven-release-plugin.version} + + [ci skip] || [CI SKIP] || [CI-SKIP] + @{project.version} + + + + + diff --git a/API-Example-Plugin/src/main/java/io/github/rypofalem/apiexample/ASEventTester.java b/API-Example-Plugin/src/main/java/io/github/rypofalem/apiexample/ASEventTester.java new file mode 100644 index 00000000..06e6d50b --- /dev/null +++ b/API-Example-Plugin/src/main/java/io/github/rypofalem/apiexample/ASEventTester.java @@ -0,0 +1,94 @@ +/* + * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package io.github.rypofalem.apiexample; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerSwapHandItemsEvent; + +public class ASEventTester implements Listener { + + Player player; + + //ArmorStandRenameEvent + @EventHandler + public void renameArmorStand(PlayerInteractAtEntityEvent ASRenameEvent) { + player = ASRenameEvent.getPlayer(); + ASRenameEvent.setCancelled(true); + if (ASRenameEvent.isCancelled()) { + player.sendMessage("ArmorStandRenameEvent has been cancelled"); + } else { + player.sendMessage("ArmorStandRenameEvent has not been cancelled. Continuing...."); + } + } + + //ArmorStandManipEvent + @EventHandler + public void manipulateArmorStand(PlayerInteractAtEntityEvent ASManipEvent) { + player = ASManipEvent.getPlayer(); + ASManipEvent.setCancelled(true); + if (ASManipEvent.isCancelled()) { + player.sendMessage("ArmorStandManipulationEvent has been cancelled"); + } else { + player.sendMessage("ArmorStandManipulationEvent has not been cancelled. Continuing...."); + } + } + + //ArmorStandTargetedEvent + @EventHandler + public void targetEvent(PlayerSwapHandItemsEvent targetASEvent) { + player = targetASEvent.getPlayer(); + targetASEvent.setCancelled(true); + if (targetASEvent.isCancelled()) { + player.sendMessage("ArmorStandTargetedEvent has been cancelled"); + } else { + player.sendMessage("ArmorStandTargetedEvent has not been cancelled. Continuing...."); + } + } + + //PlayerOpenMenuEvent + //onArmorStandDamage EntityDamageByEntityEvent event + @EventHandler + public void playerOpeningMenuEvent(EntityDamageByEntityEvent ASEDamageMenuOpenEvent) { + player = (Player) ASEDamageMenuOpenEvent.getDamager(); + ASEDamageMenuOpenEvent.setCancelled(true); + if (ASEDamageMenuOpenEvent.isCancelled()) { + player.sendMessage("PlayerOpenMenuEvent has been cancelled"); + } else { + player.sendMessage("PlayerOpenMenuEvent has not been cancelled. Continuing...."); + } + } + + //Also PlayerOpenMenuEvent when RightClicking/Interacting + @EventHandler + public void playerOpeningMenuRightClickEvent(PlayerInteractEvent ASERightClickMenuOpenEvent) { + player = ASERightClickMenuOpenEvent.getPlayer(); + ASERightClickMenuOpenEvent.setCancelled(true); + if (ASERightClickMenuOpenEvent.isCancelled()) { + player.sendMessage("PlayerOpenMenuEvent has been cancelled"); + } else { + player.sendMessage("PlayerOpenMenuEvent has not been cancelled. Continuing...."); + } + } +} diff --git a/API-Example-Plugin/src/main/java/io/github/rypofalem/apiexample/ArmorStandEditorAPITest.java b/API-Example-Plugin/src/main/java/io/github/rypofalem/apiexample/ArmorStandEditorAPITest.java new file mode 100644 index 00000000..7d366781 --- /dev/null +++ b/API-Example-Plugin/src/main/java/io/github/rypofalem/apiexample/ArmorStandEditorAPITest.java @@ -0,0 +1,33 @@ +/* + * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package io.github.rypofalem.apiexample; + +import org.bukkit.plugin.java.JavaPlugin; + +public class ArmorStandEditorAPITest extends JavaPlugin { + + @Override + public void onEnable() { + this.getLogger().info("[ArmorStandEditor] API Testing Plugin v1.20.0-43 - Enable"); + this.getServer().getPluginManager().registerEvents(new ASEventTester(), this); + this.getServer().getPluginManager().registerEvents(new IFEventTester(), this); + } + +} diff --git a/API-Example-Plugin/src/main/java/io/github/rypofalem/apiexample/IFEventTester.java b/API-Example-Plugin/src/main/java/io/github/rypofalem/apiexample/IFEventTester.java new file mode 100644 index 00000000..d80bf182 --- /dev/null +++ b/API-Example-Plugin/src/main/java/io/github/rypofalem/apiexample/IFEventTester.java @@ -0,0 +1,77 @@ +/* + * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package io.github.rypofalem.apiexample; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerSwapHandItemsEvent; + +public class IFEventTester implements Listener { + Player player; + + //ItemFrameGlowEvent + @EventHandler + public void manipulateArmorStand(PlayerInteractAtEntityEvent IFGlowEvent) { + player = IFGlowEvent.getPlayer(); + IFGlowEvent.setCancelled(true); + if (IFGlowEvent.isCancelled()) { + player.sendMessage("ItemFrameGlowEvent has been cancelled"); + } else { + player.sendMessage("ItemFrameGlowEvent has not been cancelled. Continuing...."); + } + } + + @EventHandler + public void manipulateItemFrame(EntityDamageByEntityEvent IFManipulationLeftClickEvent) { + player = (Player) IFManipulationLeftClickEvent.getDamager(); + IFManipulationLeftClickEvent.setCancelled(true); + if (IFManipulationLeftClickEvent.isCancelled()) { + player.sendMessage("ItemFrameManipulatedEvent has been cancelled"); + } else { + player.sendMessage("ItemFrameManipulatedEvent has not been cancelled. Continuing...."); + } + } + + @EventHandler + public void manipulateItemFrameRightClick(PlayerInteractAtEntityEvent IFManipulationRightClickEvent) { + player = IFManipulationRightClickEvent.getPlayer(); + IFManipulationRightClickEvent.setCancelled(true); + if (IFManipulationRightClickEvent.isCancelled()) { + player.sendMessage("ItemFrameManipulatedEvent has been cancelled"); + } else { + player.sendMessage("ItemFrameManipulatedEvent has not been cancelled. Continuing...."); + } + } + + @EventHandler + public void targetEvent(PlayerSwapHandItemsEvent targetIFEvent) { + player = targetIFEvent.getPlayer(); + targetIFEvent.setCancelled(true); + if (targetIFEvent.isCancelled()) { + player.sendMessage("ItemFrameTargetedEvent has been cancelled"); + } else { + player.sendMessage("ItemFrameTargetedEvent has not been cancelled. Continuing...."); + } + } + +} diff --git a/API-Example-Plugin/src/main/resources/plugin.yml b/API-Example-Plugin/src/main/resources/plugin.yml new file mode 100644 index 00000000..54da7b77 --- /dev/null +++ b/API-Example-Plugin/src/main/resources/plugin.yml @@ -0,0 +1,7 @@ +name: ArmorStandEditor-APITester +main: io.github.rypofalem.apiexample.ArmorStandEditorAPITest +version: 1.21-47 +api-version: "1.13" +website: https://www.spigotmc.org/resources/94503/ +authors: [Wolfstorm, Pinnkk] +description: Allows players to edit data of armorstands without any commands. diff --git a/ArmorStandEditorHeader.png b/ArmorStandEditorHeader.png new file mode 100644 index 00000000..9ef4aa78 Binary files /dev/null and b/ArmorStandEditorHeader.png differ diff --git a/LICENSE.md b/LICENSE.md index 23cb7903..f288702d 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,281 +1,622 @@ GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 + Version 3, 29 June 2007 - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of this License. - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. END OF TERMS AND CONDITIONS @@ -287,15 +628,15 @@ free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least +state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. - {description} - Copyright (C) {year} {fullname} + + Copyright (C) - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or + 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, @@ -303,37 +644,31 @@ the "copyright" line and a pointer to where the full notice is found. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + You should have received a copy of the GNU General Public License + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - {signature of Ty Coon}, 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index d582ef68..095c49ad 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,113 @@ -# ArmorStandEditor -Bukkit plugin to allow players to edit armorstands without commands. +
-Read the [wiki](https://github.com/RypoFalem/ArmorStandEditor/wiki) for more info. + + +[![Build Status](https://github.com/Wolfst0rm/ArmorStandEditor/actions/workflows/maven-publish.yml/badge.svg?style=flat)](https://github.com/Wolfst0rm/ArmorStandEditor/actions/workflows/maven-publish.yml) +[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=wolfieheart_ArmorStandEditor&metric=sqale_rating&style=flat)](https://sonarcloud.io/summary/new_code?id=wolfieheart_ArmorStandEditor) +[![](https://jitpack.io/v/Wolfieheart/ArmorStandEditor.svg)](https://jitpack.io/#Wolfieheart/ArmorStandEditor) +[![CodeFactor](https://www.codefactor.io/repository/github/wolfieheart/armorstandeditor/badge?style=flat)](https://www.codefactor.io/repository/github/wolfieheart/armorstandeditor) +[![Scanned with Sonarcloud](https://img.shields.io/badge/Scanned%20With-Sonarcloud-orange?style=flat&logo=sonarcloud)](https://sonarcloud.io/summary/new_code?id=Wolfst0rm_ArmorStandEditor) +[![wakatime](https://wakatime.com/badge/github/Wolfst0rm/ArmorStandEditor.svg?style=flat)](https://wakatime.com/badge/github/Wolfst0rm/ArmorStandEditor) +[![Compatibility/GetBukkit](https://img.shields.io/badge/Compatability-Paper%2C%20Spigot%2C%20Bukkit%20etc.%20(GetBukkit.org)-yellowgreen?style=flat)](https://getbukkit.org/) +[![License](https://img.shields.io/badge/Licence-GNU%20Public%20V3%20-red?style=flat)](https://github.com/Wolfst0rm/ArmorStandEditor/LICENSE.md) +[![Support Discord](https://dcbadge.vercel.app/api/server/3BbJKWpTCj?style=flat)](https://discord.gg/3BbJKWpTCj) + +ArmorStandEditor is a plugin for [Spigot](https://www.spigotmc.org/) / [Paper, All related forks](https://papermc.io/downloads/paper) / [Folia etc.](https://github.com/PaperMC/Folia) to allow players in survival to easily edit armor stand pose and attributes. + +
+ +## Downloads +Downloads for Version 1.17 and higher can be obtained from the [download page](https://www.spigotmc.org/resources/armorstandeditor-reborn.94503/) or our [release tracker](https://github.com/Wolfst0rm/ArmorStandEditor/releases) here on GitHub. +For versions older than 1.17, then please use [the original versions download page](https://www.spigotmc.org/resources/armor-stand-editor-dead.7688/). + +The Latest Downloads Shortcut Links: +* [ArmorStandEditor-Last (Unstable)](https://github.com/Wolfst0rm/ArmorStandEditor/actions) + - **Use these at your own risk. Limited Support is provided for testing purposes** +* 1.20(.1) - Now Available. + * [Github](https://github.com/Wolfieheart/ArmorStandEditor/releases/tag/1.20.1-43.1) + * [Spigot](https://www.spigotmc.org/resources/armorstandeditor-reborn.94503/update?update=507126) + * [Hangar](https://hangar.papermc.io/Wolfieheart/ArmorStandEditor-Reborn/versions/1.20.1-43) + * [Modrinth](https://modrinth.com/plugin/armorstandeditor-reborn/version/NuCQHkBx) +* 1.19 to 1.19.4 + * [Github](https://github.com/Wolfieheart/ArmorStandEditor/releases/tag/1.19.2-38) + * [Spigot](https://www.spigotmc.org/resources/armorstandeditor-reborn.94503/download?version=472773) + * [Modrinth](https://modrinth.com/plugin/armorstandeditor-reborn/version/1.19.2-38) +* [1.18 to 1.18.2](https://github.com/Wolfieheart/ArmorStandEditor/releases/tag/1.18.2-34.2) +* [1.17 to 1.17.1](https://github.com/Wolfieheart/ArmorStandEditor/releases/tag/1.17.1-30) +* [1.16 to 1.16.5](https://www.spigotmc.org/resources/armor-stand-editor-dead.7688/download?version=342891) +* [1.14 to 1.14.4](https://www.spigotmc.org/resources/armor-stand-editor-dead.7688/download?version=299267) +* [1.13 to 1.13.2](https://www.spigotmc.org/resources/armor-stand-editor-dead.7688/download?version=235185) +* [1.11 to 1.11.2](https://www.spigotmc.org/resources/armor-stand-editor-dead.7688/download?version=152723) +* [1.10 to 1.10.2](https://www.spigotmc.org/resources/armor-stand-editor-dead.7688/download?version=124213) +* [1.9 to 1.9.4](https://www.spigotmc.org/resources/armor-stand-editor-dead.7688/download?version=92457) +* [1.8](https://www.spigotmc.org/resources/armor-stand-editor-dead.7688/download?version=29676) + +**NOTE:** The 1.17 Versions introduce NMS Version Checks and will not load on versions older than 1.13. + +It will also advise that if you are on 1.13 to 1.16, that you update to 1.17.x or Higher. This will be +subject to change in the future. The minimum enforced API Version is 1.13. + +## Features +* Editing ArmorStands with no commands required +* Rotation of all ArmorStand Parts along each axis +* Rotation of entire ArmorStand after Placement. Supported by Crouching and Scrolling, so you never have to open the menu +* Finer Adjustment to allow for Fine-Tuning of Positions. +* Adjust the Vulnerability State of your ArmorStand +* Coarser Adjustments to allow you to quickly to get to the intended position +* Toggles for: Disabling Slots, Invisibility, Gravity, Base Plates, Size (Normal and Small) +* Copying and Pasting ArmorStand Settings between ArmorStandEditor in a Survival Friendly way +* Storage of Copied Settings in one of 9 available slots. +* Naming of ArmorStands through the use of Vanilla Name tags, with colored name support +* Multiple Language Support through the use of community translations +* Respects multiple protection plugins: WorldGuard, Towny, GriefPrevention, PlotSquared etc. +* Targeting of an ArmorStand by pressing F with the tool in your hand +* Toggle for Vulnerability of the ArmorStand (New in 1.20) +* Ability to get Player Heads via a Command (New in 1.20) +* Glowing ArmorStand to signify Targeting and Slot Disables through the use of Scoreboards. +* Folia Support (as of 1.19.4) + +## Support +Support for ArmorStandEditor is provided: +* For API-Versions Higher than 1.13 +* For Latest Release and Unstable versions of the Plugin + +If there are issues with the plugin on the latest release, you can report them [here](https://github.com/Wolfst0rm/ArmorStandEditor/issues/new?assignees=&labels=P1%3A+To+Be+Tested&template=behaviour-bug.yml). +If there are new feature requests, you can ask them to be implemented [here](https://github.com/Wolfst0rm/ArmorStandEditor/issues/new?assignees=&labels=&template=feature-request.yml). + +**NOTE:** Bugs are also first tested to ensure that they can be reproduced according to the reported steps. If they can not, we will ask for more info. + +## Adding ArmorStandEditor as a Dependency +ArmorStandEditor has an API and is supported through [Jitpack](https://jitpack.io/#Wolfieheart/ArmorStandEditor). The Source Code for that API can be found [here](https://github.com/Wolfieheart/ArmorStandEditor/src/main/java/io/github/rypofalem/armorstandeditor/api). +You can find an example plugin [here](https://github.com/Wolfieheart/ArmorStandEditor/API-Example-Plugin/src/main/java/io/github/rypofalem/apiexample). It contains very basic tests and examples of what you could do with such an API. + +For Maven Users, if you want to interact directly, you need to add the following to your pom.xml file: +```XML + + jitpack.io + https://jitpack.io + +``` +```XML + + com.github.Wolfieheart + ArmorStandEditor + latest + +``` + + +## Credits / Special Thanks +
+ +![JetBrains Logo (Main) logo](https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.svg) + +[JetBrains](https://www.jetbrains.com/), creators of IntelliJ Idea, who are supporting ArmorStandEditor with one of their [Open Source Licenses](https://www.jetbrains.com/opensource/). IntelliJ Idea is the IDE recommended for working with ArmorStandEditor. + +RypoFalem for the original version of this plugin. Thank you for all your hard work (Archived on this repository on the branch [Original-Version](https://github.com/Wolfst0rm/ArmorStandEditor/tree/Original-Version) ) + +Anyone who has contributed to this project with tests, issues, code reviews etc. Thank you! + +[![Shamblecraft](https://media.discordapp.net/attachments/1017882838739189760/1129352283054940160/logo_trans.png)](https://namemc.com/server/mc.shamblecraft.net) + +Shamblecraft for using the plugin originally and giving me the idea to maintain it. +
diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 00000000..1e41e00b --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,2 @@ +jdk: + - openjdk17 \ No newline at end of file diff --git a/pom.xml b/pom.xml index 624f982f..6cfae377 100644 --- a/pom.xml +++ b/pom.xml @@ -1,47 +1,327 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 io.github.rypofalem.armorstandeditor armorstandeditor jar - 1.16-25 + 1.21.4-48.1 armorstandeditor - http://maven.apache.org + https://maven.apache.org + 21 UTF-8 + 3.1.1 + wolfieheart + https://sonarcloud.io + + + Wolfieheart + Wolfieheart + https://github.com/Wolfieheart + + + RypoFalem + RypoFalem + https://github.com/RypoFalem + + + + + + paper-repo + https://repo.papermc.io/repository/maven-public/ + + + + sk89q-repo + https://maven.enginehub.org/repo/ + + + + sonatype + https://oss.sonatype.org/content/groups/public/ + + + sonatype snapshots + https://s01.oss.sonatype.org/content/groups/public/ + + + sonatype-oss-snapshots1 + https://s01.oss.sonatype.org/content/repositories/snapshots/ + + + + glaremasters repo + https://repo.glaremasters.me/repository/towny/ + + + glaremasters + https://repo.glaremasters.me/repository/bloodshot/ + + + + jeff-media-public + https://repo.jeff-media.com/public/ + + + + jitpack.io + https://jitpack.io + + + + bg-repo + https://repo.bg-software.com/repository/api/ + + - spigot-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + codemc-repo + https://repo.codemc.org/repository/maven-public/ + + + + com.intellectualsites.bom + bom-1.18.x + 1.31 + import + pom + + + + - + + + io.papermc.paper + paper-api + 1.21.4-R0.1-SNAPSHOT + provided + + + adventure-api + net.kyori + + + + - org.spigotmc - spigot-api - 1.16.1-R0.1-SNAPSHOT + net.kyori + adventure-api + 4.17.0 + provided + + + + dev.folia + folia-api + 1.20.4-R0.1-SNAPSHOT + provided + + + adventure-api + net.kyori + + + + + + com.sk89q.worldguard + worldguard-bukkit + 7.1.0-SNAPSHOT + provided + + + + com.intellectualsites.plotsquared + plotsquared-core + 7.3.8 + provided + + + adventure + * + + + * + net.kyori + + + + + com.intellectualsites.plotsquared + plotsquared-bukkit + 7.4.1 + provided + + + plotsquared-core + * + + + * + net.kyori + + + + + + com.github.TechFortress + GriefPrevention + 17.0.0 + provided + + + + com.palmergames.bukkit.towny + towny + 0.101.0.5 + provided + + + + com.jeff_media + SpigotUpdateChecker + 3.0.4 + compile + + + + com.bgsoftware + SuperiorSkyblockAPI + 2024.1 + provided + + + + com.griefdefender + api + 2.1.0-SNAPSHOT + provided + + + * + net.kyori + + + + + + com.github.angeschossen + LandsAPI + 7.11.10 + provided + + + + world.bentobox + bentobox + 1.23.2 + provided + + + + com.github.LoneDev6 + api-itemsadder + 3.6.1 + provided + + + + + org.projectlombok + lombok + 1.18.34 provided + + + org.openrewrite.maven + rewrite-maven-plugin + 5.47.3 + + + org.openrewrite.java.format.AutoFormat + org.openrewrite.java.recipes.FindRecipes + org.openrewrite.java.OrderImports + org.openrewrite.java.ShortenFullyQualifiedTypeReferences + org.openrewrite.java.RemoveUnusedImports + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + compile + package + + attach-artifact + + + + + ${project.build.directory}/${project.artifactId}.jar + jar + optional + + + + + + org.apache.maven.plugins maven-compiler-plugin + 3.13.0 + + ${java.version} + ${java.version} + + + + org.apache.maven.plugins + maven-shade-plugin 3.6.0 + + + package + + shade + + + + + com.jeff_media.updatechecker + io.github.rypofalem.armorstandeditor.updatechecker + + + + + + + + org.apache.maven.plugins + maven-release-plugin + ${maven-release-plugin.version} - 1.8 - 1.8 + [ci skip] || [CI SKIP] || [CI-SKIP] + @{project.version} - diff --git a/renovate.json b/renovate.json new file mode 100644 index 00000000..f45d8f11 --- /dev/null +++ b/renovate.json @@ -0,0 +1,5 @@ +{ + "extends": [ + "config:base" + ] +} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/ArmorStandEditorPlugin.java b/src/main/java/io/github/rypofalem/armorstandeditor/ArmorStandEditorPlugin.java index 1727343e..2eb6840a 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/ArmorStandEditorPlugin.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/ArmorStandEditorPlugin.java @@ -1,6 +1,6 @@ /* * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016 RypoFalem + * Copyright (C) 2016-2023 RypoFalem * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -19,139 +19,765 @@ package io.github.rypofalem.armorstandeditor; +import com.jeff_media.updatechecker.UpdateCheckSource; +import com.jeff_media.updatechecker.UpdateChecker; +import com.jeff_media.updatechecker.UserAgentBuilder; + +import io.github.rypofalem.armorstandeditor.Metrics.*; import io.github.rypofalem.armorstandeditor.language.Language; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; + +import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.Plugin; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.Team; import java.io.File; +import java.util.*; +import java.util.logging.Level; + +public class ArmorStandEditorPlugin extends JavaPlugin { + + //!!! DO NOT REMOVE THESE UNDER ANY CIRCUMSTANCES - Required for BStats and UpdateChecker !!! + public static final int SPIGOT_RESOURCE_ID = 94503; //Used for Update Checker + private static final int PLUGIN_ID = 12668; //Used for BStats Metrics + private Debug debug = new Debug(this); + + private NamespacedKey iconKey; + private static ArmorStandEditorPlugin instance; + private Language lang; + + //Server Version Detection: Paper or Spigot and Invalid NMS Version + String nmsVersion; + String languageFolderLocation = "lang/"; + String warningMCVer = "Minecraft Version: "; + public boolean hasSpigot = false; + public boolean hasPaper = false; + public boolean hasFolia = false; + String nmsVersionNotLatest = null; + + String aseVersion; + public static final String SEPARATOR_FIELD = "================================"; + + public PlayerEditorManager editorManager; + + //Output for Updates + boolean opUpdateNotification = false; + boolean runTheUpdateChecker = false; + double updateCheckerInterval; + + //Edit Tool Information + Material editTool; + String toolType; + int editToolData = Integer.MIN_VALUE; + boolean requireToolData = false; + boolean requireToolName = false; + String editToolName = null; + boolean requireToolLore = false; + List editToolLore = null; + boolean enablePerWorld = false; + List allowedWorldList = null; + boolean allowCustomModelData = false; + Integer customModelDataInt = Integer.MIN_VALUE; + double maxScaleValue; + double minScaleValue; + + //GUI Settings + boolean requireSneaking = false; + boolean sendToActionBar = true; + + //Armor Stand Specific Settings + double coarseRot; + double fineRot; + boolean glowItemFrames = false; + boolean invisibleItemFrames = true; + boolean armorStandVisibility = true; + + //Misc Options + boolean allowedToRetrieveOwnPlayerHead = false; + boolean adminOnlyNotifications = false; + + //Glow Entity Colors + public Scoreboard scoreboard; + public Team team; + List asTeams = new ArrayList<>(); + String lockedTeam = "ASLocked"; + String inUseTeam = "AS-InUse"; + + //Debugging Options.... Not Exposed + boolean debugFlag; + + private static ArmorStandEditorPlugin plugin; + + public ArmorStandEditorPlugin() { + instance = this; + } + + @Override + public void onEnable() { + + if (!Scheduler.isFolia()) + scoreboard = Objects.requireNonNull(this.getServer().getScoreboardManager()).getMainScoreboard(); + + // Get ASEs Version Number from the config.... + aseVersion = this.getConfig().getString("version"); + + //Load Messages in Console + getLogger().info("======= ArmorStandEditor ======="); + getLogger().info("Plugin Version: v" + aseVersion); + + //Spigot Check + hasSpigot = getHasSpigot(); + hasPaper = getHasPaper(); + hasFolia = Scheduler.isFolia(); + + //Get NMS Version + if (hasPaper || hasFolia) { + nmsVersion = getServer().getMinecraftVersion(); + + // Check if the Minecraft version is supported + if (nmsVersion.contains("1.21")) { + getLogger().log(Level.INFO, warningMCVer + "{0}", nmsVersion); + getLogger().info("ArmorStandEditor is compatible with this version of Minecraft. Loading continuing."); + } else if (nmsVersion.contains("1.17") || nmsVersion.contains("1.18") || nmsVersion.contains("1.19") || nmsVersion.contains("1.20")) { + getLogger().log(Level.WARNING, warningMCVer + "{0}", nmsVersion); + getLogger().warning("ArmorStandEditor is compatible with this version of Minecraft, but it is not the latest supported version."); + getLogger().warning("Loading continuing, but please consider updating to the latest version."); + } else { + getLogger().log(Level.WARNING, warningMCVer + "{0}", nmsVersion); + getLogger().warning("ArmorStandEditor is not compatible with this version of Minecraft. Please update to at least version 1.17. Loading failed."); + getServer().getPluginManager().disablePlugin(this); + getLogger().info(SEPARATOR_FIELD); + } + } else { // Spigot Detected + nmsVersion = getNmsVersion(); + // Check if the Minecraft version is supported + if (nmsVersion.compareTo("v1_17") < 0) { + getLogger().log(Level.WARNING, warningMCVer + "{0}", nmsVersion); + getLogger().warning("ArmorStandEditor is not compatible with this version of Minecraft. Please update to at least version 1.17. Loading failed."); + getServer().getPluginManager().disablePlugin(this); + getLogger().info(SEPARATOR_FIELD); + return; + } + + //Also Warn People to Update if using nmsVersion lower than latest + if (nmsVersion.compareTo("v1_21") < 0) { + getLogger().log(Level.WARNING, warningMCVer + "{0}", nmsVersion); + getLogger().warning("ArmorStandEditor is compatible with this version of Minecraft, but it is not the latest supported version."); + getLogger().warning("Loading continuing, but please consider updating to the latest version."); + } else { + getLogger().log(Level.INFO, warningMCVer + "{0}", nmsVersion); + getLogger().info("ArmorStandEditor is compatible with this version of Minecraft. Loading continuing."); + } + + } + + + //If Paper and Spigot are both FALSE - Disable the plugin + if (!hasPaper && !hasSpigot) { + getLogger().severe("This plugin requires either Paper, Spigot or one of its forks to run. This is not an error, please do not report this!"); + getServer().getPluginManager().disablePlugin(this); + getLogger().info(SEPARATOR_FIELD); + return; + } else { + if (hasSpigot) { + getLogger().log(Level.INFO, "SpigotMC: {0}", hasSpigot); + } else { + getLogger().log(Level.INFO, "PaperMC: {0}", hasPaper); + } + } + getServer().getPluginManager().enablePlugin(this); + + asTeams.add(lockedTeam); + asTeams.add(inUseTeam); + + if (!hasFolia) { + scoreboard = Objects.requireNonNull(this.getServer().getScoreboardManager()).getMainScoreboard(); + registerScoreboards(scoreboard); + } else { + getServer().getLogger().warning("Scoreboards currently do not work on Folia. Scoreboard Coloring will not work"); + } + + + getLogger().info(SEPARATOR_FIELD); + + //saveResource doesn't accept File.separator on Windows, need to hardcode unix separator "/" instead + updateConfig("", "config.yml"); + updateConfig(languageFolderLocation, "de_DE.yml"); + updateConfig(languageFolderLocation, "es_ES.yml"); + updateConfig(languageFolderLocation, "fr_FR.yml"); + updateConfig(languageFolderLocation, "ja_JP.yml"); + updateConfig(languageFolderLocation, "nl_NL.yml"); + updateConfig(languageFolderLocation, "pl_PL.yml"); + updateConfig(languageFolderLocation, "pt_BR.yml"); + updateConfig(languageFolderLocation, "ro_RO.yml"); + updateConfig(languageFolderLocation, "ru_RU.yml"); + updateConfig(languageFolderLocation, "test_NA.yml"); + updateConfig(languageFolderLocation, "uk_UA.yml"); + updateConfig(languageFolderLocation, "zh_CN.yml"); + + //English is the default language and needs to be unaltered to so that there is always a backup message string + saveResource("lang/en_US.yml", true); + lang = new Language(getConfig().getString("lang"), this); + + //Rotation + coarseRot = getConfig().getDouble("coarse"); + fineRot = getConfig().getDouble("fine"); + + // Scale Values for Size + maxScaleValue = getConfig().getDouble("maxScaleValue"); + minScaleValue = getConfig().getDouble("minScaleValue"); + + //Set Tool to be used in game + toolType = getConfig().getString("tool"); + if (toolType != null) { + editTool = Material.getMaterial(toolType); //Ignore Warning + } else { + getLogger().severe("Unable to get Tool for Use with Plugin. Unable to continue!"); + getLogger().info(SEPARATOR_FIELD); + getServer().getPluginManager().disablePlugin(this); + return; + } + + //Do we require a custom tool name? + requireToolName = getConfig().getBoolean("requireToolName", false); + if (requireToolName) { + editToolName = getConfig().getString("toolName", null); + if (editToolName != null) editToolName = ChatColor.translateAlternateColorCodes('&', editToolName); + } + + //Custom Model Data + allowCustomModelData = getConfig().getBoolean("allowCustomModelData", false); + + if (allowCustomModelData) { + customModelDataInt = getConfig().getInt("customModelDataInt", Integer.MIN_VALUE); + } + + //ArmorStandVisibility Node + armorStandVisibility = getConfig().getBoolean("armorStandVisibility", true); + + //Is there NBT Required for the tool + requireToolData = getConfig().getBoolean("requireToolData", false); + + if (requireToolData) { + editToolData = getConfig().getInt("toolData", Integer.MIN_VALUE); + } + + requireToolLore = getConfig().getBoolean("requireToolLore", false); + + if (requireToolLore) { + editToolLore = getConfig().getList("toolLore", null); + } + + enablePerWorld = getConfig().getBoolean("enablePerWorldSupport", false); + if (enablePerWorld) { + allowedWorldList = getConfig().getList("allowed-worlds", null); + if (allowedWorldList != null && allowedWorldList.get(0).equals("*")) { + allowedWorldList = getServer().getWorlds().stream().map(World::getName).toList(); + } + } + + //Require Sneaking - Wolfst0rm/ArmorStandEditor#17 + requireSneaking = getConfig().getBoolean("requireSneaking", false); + + //Send Messages to Action Bar + sendToActionBar = getConfig().getBoolean("sendMessagesToActionBar", true); + + //All ItemFrame Stuff + glowItemFrames = getConfig().getBoolean("glowingItemFrame", true); + invisibleItemFrames = getConfig().getBoolean("invisibleItemFrames", true); + + //Add ability to enable ot Disable the running of the Updater + runTheUpdateChecker = getConfig().getBoolean("runTheUpdateChecker", true); + + //Add Ability to check for UpdatePerms that Notify Ops - https://github.com/Wolfieheart/ArmorStandEditor/issues/86 + opUpdateNotification = getConfig().getBoolean("opUpdateNotification", true); + updateCheckerInterval = getConfig().getDouble("updateCheckerInterval", 24); + + //Ability to get Player Heads via a command + allowedToRetrieveOwnPlayerHead = getConfig().getBoolean("allowedToRetrieveOwnPlayerHead", true); + + adminOnlyNotifications = getConfig().getBoolean("adminOnlyNotifications", true); + + debugFlag = getConfig().getBoolean("debugFlag", false); + if (debugFlag) { + getServer().getLogger().log(Level.INFO, "[ArmorStandEditor-Debug] ArmorStandEditor Debug Mode is now ENABLED! Use this ONLY for testing Purposes. If you can see this and you have debug disabled, please report it as a bug!"); + } + + //Run UpdateChecker - Reports out to Console on Startup ONLY! + if (!hasFolia && runTheUpdateChecker) { + + if (opUpdateNotification) { + runUpdateCheckerWithOPNotifyOnJoinEnabled(); + } else { + runUpdateCheckerConsoleUpdateCheck(); + } + + } + + //Get Metrics from bStats + getMetrics(); + + editorManager = new PlayerEditorManager(this); + CommandEx execute = new CommandEx(this); + + //CommandExecution and TabCompletion + Objects.requireNonNull(getCommand("ase")).setExecutor(execute); + Objects.requireNonNull(getCommand("ase")).setTabCompleter(execute); + + getServer().getPluginManager().registerEvents(editorManager, this); + + } + + private void runUpdateCheckerConsoleUpdateCheck() { + if (getArmorStandEditorVersion().contains(".x")) { + getLogger().warning("Note from the development team: "); + getLogger().warning("It appears that you are using the development version of ArmorStandEditor"); + getLogger().warning("This version can be unstable and is not recommended for Production Environments."); + getLogger().warning("Please, report bugs to: https://github.com/Wolfieheart/ArmorStandEditor. "); + getLogger().warning("This warning is intended to be displayed when using a Dev build and is NOT A BUG!"); + getLogger().info("Update Checker does not work on Development Builds."); + } else { + new UpdateChecker(this, UpdateCheckSource.SPIGET, "" + SPIGOT_RESOURCE_ID + "") + .setDownloadLink("https://www.spigotmc.org/resources/armorstandeditor-reborn.94503/") + .setChangelogLink("https://www.spigotmc.org/resources/armorstandeditor-reborn.94503/history") + .setColoredConsoleOutput(true) + .setUserAgent(new UserAgentBuilder().addPluginNameAndVersion().addServerVersion()) + .checkEveryXHours(updateCheckerInterval) + .checkNow(); + } + } + + private void runUpdateCheckerWithOPNotifyOnJoinEnabled() { + if (getArmorStandEditorVersion().contains(".x")) { + getLogger().warning("Note from the development team: "); + getLogger().warning("It appears that you are using the development version of ArmorStandEditor"); + getLogger().warning("This version can be unstable and is not recommended for Production Environments."); + getLogger().warning("Please, report bugs to: https://github.com/Wolfieheart/ArmorStandEditor . "); + getLogger().warning("This warning is intended to be displayed when using a Dev build and is NOT A BUG!"); + getLogger().info("Update Checker does not work on Development Builds."); + } else { + new UpdateChecker(this, UpdateCheckSource.SPIGET, "" + SPIGOT_RESOURCE_ID + "") + .setDownloadLink("https://www.spigotmc.org/resources/armorstandeditor-reborn.94503/") + .setChangelogLink("https://www.spigotmc.org/resources/armorstandeditor-reborn.94503/history") + .setColoredConsoleOutput(true) + .setNotifyOpsOnJoin(true) + .setUserAgent(new UserAgentBuilder().addPluginNameAndVersion().addServerVersion()) + .checkEveryXHours(updateCheckerInterval) + .checkNow(); + } + } + + //Implement Glow Effects for Wolfstorm/ArmorStandEditor-Issues#5 - Add Disable Slots with Different Glow than Default + private void registerScoreboards(Scoreboard scoreboard) { + for (String teamToBeRegistered : asTeams) { + scoreboard.registerNewTeam(teamToBeRegistered); + team = scoreboard.getTeam(teamToBeRegistered); + if (team != null) { + if (teamToBeRegistered == lockedTeam) { + getServer().getLogger().info("Registering Scoreboards required for Glowing Effects when Disabling Slots..."); + scoreboard.getTeam(teamToBeRegistered).setColor(ChatColor.RED); + } + } else { + getServer().getLogger().info("Scoreboard for Team '" + teamToBeRegistered + "' Already exists. Continuing to load"); + } + + } + } + + private void unregisterScoreboards(Scoreboard scoreboard) { + getLogger().info("Removing Scoreboards required for Glowing Effects when Disabling Slots..."); + for (String teamToBeRegistered : asTeams) { + team = scoreboard.getTeam(teamToBeRegistered); + if (team != null) { + team.unregister(); + } else { + getServer().getLogger().severe("Team '" + teamToBeRegistered + "' already appears to be removed. Avoid manual removal to prevent errors!"); + } + } + + + } + + private void updateConfig(String folder, String config) { + if (!new File(getDataFolder() + File.separator + folder + config).exists()) { + saveResource(folder + config, false); + } + } + + @Override + public void onDisable() { + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + if (player.getOpenInventory().getTopInventory().getHolder() == editorManager.getMenuHolder()) player.closeInventory(); + } + + if (!hasFolia) { + scoreboard = Objects.requireNonNull(this.getServer().getScoreboardManager()).getMainScoreboard(); + unregisterScoreboards(scoreboard); + } + } + + public String getNmsVersion() { + // return this.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + if (getHasPaper() || getHasFolia()){ + return this.getMinecraftVersion(); + } else { + return this.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + } + } + + public boolean getHasSpigot() { + try { + Class.forName("org.spigotmc.CustomTimingsHandler"); + nmsVersionNotLatest = "SpigotMC ASAP."; + return true; + } catch (ClassNotFoundException e) { + nmsVersionNotLatest = ""; + return false; + } + } + + public boolean getHasPaper() { + try { + Class.forName("com.destroystokyo.paper.PaperConfig"); + nmsVersionNotLatest = "PaperMC ASAP."; + return true; + } catch (ClassNotFoundException e) { + nmsVersionNotLatest = ""; + return false; + } + } + + public boolean getHasFolia() { + return Scheduler.isFolia(); + } + + //Will be useful for later..... + public String getMinecraftVersion() { + return this.nmsVersion; + } + + public String getArmorStandEditorVersion() { + return getConfig().getString("version"); + } + + public boolean getArmorStandVisibility() { + return getConfig().getBoolean("armorStandVisibility"); + } + + public boolean getItemFrameVisibility() { + return getConfig().getBoolean("invisibleItemFrames"); + } + + public Language getLang() { + return lang; + } + + public boolean getAllowCustomModelData() { + return this.getConfig().getBoolean("allowCustomModelData"); + } + + public Material getEditTool() { + return this.editTool; + } + + public boolean getRunTheUpdateChecker() { + return this.getConfig().getBoolean("runTheUpdateChecker"); + } + + public Integer getCustomModelDataInt() { + return this.getConfig().getInt("customModelDataInt"); + } + + //New in 1.20-43: Allow the ability to get a player head from a command - ENABLED VIA CONFIG ONLY! + public boolean getallowedToRetrieveOwnPlayerHead() { + return this.getConfig().getBoolean("allowedToRetrieveOwnPlayerHead"); + } + + public boolean getAdminOnlyNotifications() { + return this.getConfig().getBoolean("adminOnlyNotifications"); + } + + public boolean isEditTool(ItemStack itemStk) { + if (itemStk == null) { + return false; + } + if (editTool != itemStk.getType()) { + return false; + } + + ItemMeta itemMeta = itemStk.getItemMeta(); + if (itemMeta == null) return false; + + //FIX: Depreciated Stack for getDurability + if (requireToolData) { + Damageable d1 = (Damageable) itemMeta; //Get the Damageable Options for itemStk + if (d1 != null) { //We do this to prevent NullPointers + if (d1.getDamage() != (short) editToolData) { + return false; + } + } + } + + if (requireToolName && editToolName != null) { + if (!itemStk.hasItemMeta()) { + return false; + } + + //Get the name of the Edit Tool - If Null, return false + String itemName = itemMeta.getDisplayName(); + + //If the name of the Edit Tool is not the Name specified in Config then Return false + if (!itemName.equals(editToolName)) { + return false; + } + + } + + if (requireToolLore && editToolLore != null) { + + //If the ItemStack does not have Metadata then we return false + if (!itemStk.hasItemMeta()) { + return false; + } + + //Get the lore of the Item and if it is null - Return False + List itemLore = itemMeta.getLore(); + + //If the Item does not have Lore - Return False + boolean hasTheItemLore = itemMeta.hasLore(); + if (!hasTheItemLore) { + return false; + } + + //Get the localised ListString of editToolLore + List listStringOfEditToolLore = (List) editToolLore; + + //Return False if itemLore on the item does not match what we expect in the config. + if (!itemLore.equals(listStringOfEditToolLore)) { + return false; + } + + } + + if (allowCustomModelData && customModelDataInt != null) { + //If the ItemStack does not have Metadata then we return false + if (!itemStk.hasItemMeta()) { + return false; + } + Integer itemCustomModel = itemMeta.getCustomModelData(); + return itemCustomModel.equals(customModelDataInt); + } + return true; + } + + public void performReload() { + + //Unregister Scoreboard before before performing the reload + if (!hasFolia) { + scoreboard = Objects.requireNonNull(this.getServer().getScoreboardManager()).getMainScoreboard(); + unregisterScoreboards(scoreboard); + } + + //Perform Reload + reloadConfig(); + + //Re-Register Scoreboards + if (!hasFolia) registerScoreboards(scoreboard); + + //Reload Config File + reloadConfig(); + + //Set Language + lang = new Language(getConfig().getString("lang"), this); + + + //Rotation + coarseRot = getConfig().getDouble("coarse"); + fineRot = getConfig().getDouble("fine"); + + // Scale Values for Size + maxScaleValue = getConfig().getDouble("maxScaleValue"); + minScaleValue = getConfig().getDouble("minScaleValue"); + + //Set Tool to be used in game + toolType = getConfig().getString("tool"); + if (toolType != null) { + editTool = Material.getMaterial(toolType); //Ignore Warning + } + + //Do we require a custom tool name? + requireToolName = getConfig().getBoolean("requireToolName", false); + if (requireToolName) { + editToolName = getConfig().getString("toolName", null); + if (editToolName != null) editToolName = ChatColor.translateAlternateColorCodes('&', editToolName); + } + + //Custom Model Data + allowCustomModelData = getConfig().getBoolean("allowCustomModelData", false); + + if (allowCustomModelData) { + customModelDataInt = getConfig().getInt("customModelDataInt", Integer.MIN_VALUE); + } + + //ArmorStandVisibility Node + armorStandVisibility = getConfig().getBoolean("armorStandVisibility", true); + + //Is there NBT Required for the tool + requireToolData = getConfig().getBoolean("requireToolData", false); + + if (requireToolData) { + editToolData = getConfig().getInt("toolData", Integer.MIN_VALUE); + } + + requireToolLore = getConfig().getBoolean("requireToolLore", false); + + if (requireToolLore) { + editToolLore = getConfig().getList("toolLore", null); + } + + + enablePerWorld = getConfig().getBoolean("enablePerWorldSupport", false); + if (enablePerWorld) { + allowedWorldList = getConfig().getList("allowed-worlds", null); + if (allowedWorldList != null && allowedWorldList.get(0).equals("*")) { + allowedWorldList = getServer().getWorlds().stream().map(World::getName).toList(); + } + } + + //Require Sneaking - Wolfst0rm/ArmorStandEditor#17 + requireSneaking = getConfig().getBoolean("requireSneaking", false); + + //Send Messages to Action Bar + sendToActionBar = getConfig().getBoolean("sendMessagesToActionBar", true); + + //All ItemFrame Stuff + glowItemFrames = getConfig().getBoolean("glowingItemFrame", true); + invisibleItemFrames = getConfig().getBoolean("invisibleItemFrames", true); + + //Add ability to enable ot Disable the running of the Updater + runTheUpdateChecker = getConfig().getBoolean("runTheUpdateChecker", true); + + //Ability to get Player Heads via a command + allowedToRetrieveOwnPlayerHead = getConfig().getBoolean("allowedToRetrieveOwnPlayerHead", true); + adminOnlyNotifications = getConfig().getBoolean("adminOnlyNotifications", true); + + //Add Ability to check for UpdatePerms that Notify Ops - https://github.com/Wolfieheart/ArmorStandEditor/issues/86 + opUpdateNotification = getConfig().getBoolean("opUpdateNotification", true); + updateCheckerInterval = getConfig().getDouble("updateCheckerInterval", 24); + + + // Add Debug Reload + debugFlag = getConfig().getBoolean("debugFlag", false); + if (debugFlag) { + getServer().getLogger().log(Level.INFO, "[ArmorStandEditor-Debug] ArmorStandEditor Debug Mode is now ENABLED! Use this ONLY for testing Purposes. If you can see this and you have debug disabled, please report it as a bug!"); + } + + + //Run UpdateChecker - Reports out to Console on Startup ONLY! + if (!hasFolia && runTheUpdateChecker) { + + if (opUpdateNotification) { + runUpdateCheckerWithOPNotifyOnJoinEnabled(); + } else { + runUpdateCheckerConsoleUpdateCheck(); + } + + } + } + + public static ArmorStandEditorPlugin instance() { + return instance; + } + + //Metrics/bStats Support + private void getMetrics() { + + Metrics metrics = new Metrics(this, PLUGIN_ID); + + //RequireToolLore Metric + metrics.addCustomChart(new SimplePie("tool_lore_enabled", () -> getConfig().getString("requireToolLore"))); + + //RequireToolData + metrics.addCustomChart(new SimplePie("tool_data_enabled", () -> getConfig().getString("requireToolData"))); + + //Send Messages to ActionBar + metrics.addCustomChart(new SimplePie("action_bar_messages", () -> getConfig().getString("sendMessagesToActionBar"))); + + //Check for Sneaking + metrics.addCustomChart(new SimplePie("require_sneaking", () -> getConfig().getString("requireSneaking"))); + + //Language is used + metrics.addCustomChart(new DrilldownPie("language_used", () -> { + Map> map = new HashMap<>(); + Map entry = new HashMap<>(); + + String languageUsed = getConfig().getString("lang"); + assert languageUsed != null; + + if (languageUsed.startsWith("nl")) { + map.put("Dutch", entry); + } else if (languageUsed.startsWith("de")) { + map.put("German", entry); + } else if (languageUsed.startsWith("es")) { + map.put("Spanish", entry); + } else if (languageUsed.startsWith("fr")) { + map.put("French", entry); + } else if (languageUsed.startsWith("ja")) { + map.put("Japanese", entry); + } else if (languageUsed.startsWith("pl")) { + map.put("Polish", entry); + } else if (languageUsed.startsWith("ru")) { //See PR# 41 by KPidS + map.put("Russian", entry); + } else if (languageUsed.startsWith("ro")) { + map.put("Romanian", entry); + } else if (languageUsed.startsWith("uk")) { + map.put("Ukrainian", entry); + } else if (languageUsed.startsWith("zh")) { + map.put("Chinese", entry); + } else if (languageUsed.startsWith("pt")) { + map.put("Brazilian", entry); + } else { + map.put("English", entry); + } + return map; + })); + + //ArmorStandInvis Config + metrics.addCustomChart(new SimplePie("armor_stand_invisibility_usage", () -> getConfig().getString("armorStandVisibility"))); + + //ArmorStandInvis Config + metrics.addCustomChart(new SimplePie("itemframe_invisibility_used", () -> getConfig().getString("invisibleItemFrames"))); + + //Add tracking to see who is using Custom Naming in BStats + metrics.addCustomChart(new SimplePie("custom_toolname_enabled", () -> getConfig().getString("requireToolName"))); + + metrics.addCustomChart(new SimplePie("using_the_update_checker", () -> getConfig().getString("runTheUpdateChecker"))); + metrics.addCustomChart(new SimplePie("op_updates", () -> getConfig().getString("opUpdateNotification"))); + + + } + + public NamespacedKey getIconKey() { + if (iconKey == null) iconKey = new NamespacedKey(this, "command_icon"); + return iconKey; + } + + public double getMinScaleValue() { + return minScaleValue; + } + + public double getMaxScaleValue() { + return maxScaleValue; + } -public class ArmorStandEditorPlugin extends JavaPlugin{ - private NamespacedKey iconKey; - private static ArmorStandEditorPlugin instance; - private CommandEx execute; - private Language lang; - public boolean hasSpigot; - public PlayerEditorManager editorManager; - public Material editTool = Material.FLINT; - boolean requireToolData = false; - boolean sendToActionBar = true; - int editToolData = Integer.MIN_VALUE; - boolean requireToolLore = false; - String editToolLore = null; - boolean debug = false; //weather or not to broadcast messages via print(String message) - double coarseRot; - double fineRot; - - public ArmorStandEditorPlugin(){ - instance = this; - } - - @Override - public void onEnable(){ - //saveResource doesn't accept File.seperator on windows, need to hardcode unix seperator "/" instead - updateConfig("", "config.yml"); - updateConfig("lang/", "test_NA.yml"); - updateConfig("lang/", "nl_NL.yml"); - updateConfig("lang/", "uk_UA.yml"); - updateConfig("lang/", "zh.yml"); - updateConfig("lang/", "fr_FR.yml"); - updateConfig("lang/", "ro_RO.yml"); - updateConfig("lang/", "ja_JP.yml"); - updateConfig("lang/", "de_DE.yml"); - //English is the default language and needs to be unaltered to so that there is always a backup message string - saveResource("lang/en_US.yml", true); - lang = new Language(getConfig().getString("lang"), this); - - coarseRot = getConfig().getDouble("coarse"); - fineRot = getConfig().getDouble("fine"); - String toolType = getConfig().getString("tool", "FLINT"); - editTool = Material.getMaterial(toolType); - requireToolData = getConfig().getBoolean("requireToolData", false); - if(requireToolData) editToolData = getConfig().getInt("toolData", Integer.MIN_VALUE); - requireToolLore = getConfig().getBoolean("requireToolLore", false); - if(requireToolLore) editToolLore= getConfig().getString("toolLore", null); - debug = getConfig().getBoolean("debug", true); - sendToActionBar = getConfig().getBoolean("sendMessagesToActionBar", true); - - editorManager = new PlayerEditorManager(this); - execute = new CommandEx(this); - getCommand("ase").setExecutor(execute); - getServer().getPluginManager().registerEvents(editorManager, this); - - hasSpigot = true; - try { - Class.forName("org.spigotmc.package-info", false, this.getClassLoader()); - } catch (ClassNotFoundException e) { - hasSpigot = false; - } - } - - private void updateConfig(String folder, String config) { - if(!new File(getDataFolder() + File.separator + folder + config).exists()){ - saveResource(folder + config, false); - } - } - - @Override - public void onDisable(){ - for(Player player : Bukkit.getServer().getOnlinePlayers()){ - if(player.getOpenInventory().getTopInventory().getHolder() == editorManager.getMenuHolder()) player.closeInventory(); - } - } - - public void log(String message){ - this.getServer().getLogger().info("ArmorStandEditor: " + message); - } - - public void print(String message){ - if(debug){ - this.getServer().broadcastMessage(message); - log(message); - } - } - - public String listPlugins(){ - Plugin[] plugins = getServer().getPluginManager().getPlugins(); - StringBuilder list = new StringBuilder(); - for(Plugin p : plugins){ - if(p!=null){ - list.append(" :").append(p.getName()).append(" ").append(p.getDescription().getVersion()).append(": "); - } - } - return list.toString(); - } - - public static ArmorStandEditorPlugin instance(){ - return instance; - } - - public Language getLang(){ - return lang; - } - - public boolean isEditTool(ItemStack item){ - if(item == null) return false; - if(editTool != item.getType()) return false; - if(requireToolData && item.getDurability() != (short)editToolData) return false; - if(requireToolLore && editToolLore != null){ - if(!item.hasItemMeta()) return false; - if(!item.getItemMeta().hasLore()) return false; - if(item.getItemMeta().getLore().isEmpty()) return false; - if(!item.getItemMeta().getLore().get(0).equals(editToolLore)) return false; - } - return true; - } - - public NamespacedKey getIconKey() { - if(iconKey == null) iconKey = new NamespacedKey(this, "command_icon"); - return iconKey; - } + /** + * For debugging ASE - Do not use this outside of Development or stuff + */ + public boolean isDebug() { + return debugFlag; + } } -//todo: -//Access to "DisabledSlots" data (probably simplified just a toggle enable/disable) -//Access to the "Marker" switch (so you can make the hitbox super small) \ No newline at end of file diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java b/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java index da4eb697..badd7569 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/CommandEx.java @@ -1,6 +1,6 @@ /* * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016 RypoFalem + * Copyright (C) 2016-2023 RypoFalem * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -19,160 +19,563 @@ package io.github.rypofalem.armorstandeditor; +import com.jeff_media.updatechecker.UpdateCheckSource; +import com.jeff_media.updatechecker.UpdateChecker; + import io.github.rypofalem.armorstandeditor.modes.AdjustmentMode; import io.github.rypofalem.armorstandeditor.modes.Axis; import io.github.rypofalem.armorstandeditor.modes.EditMode; +import io.github.rypofalem.armorstandeditor.Debug; + import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; import org.bukkit.Sound; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; +import org.bukkit.attribute.Attribute; +import org.bukkit.command.*; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Entity; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +public class CommandEx implements CommandExecutor, TabCompleter { + ArmorStandEditorPlugin plugin; + final String LISTMODE = ChatColor.YELLOW + "/ase mode <" + Util.getEnumList(EditMode.class) + ">"; + final String LISTAXIS = ChatColor.YELLOW + "/ase axis <" + Util.getEnumList(Axis.class) + ">"; + final String LISTADJUSTMENT = ChatColor.YELLOW + "/ase adj <" + Util.getEnumList(AdjustmentMode.class) + ">"; + final String LISTSLOT = ChatColor.YELLOW + "/ase slot <1-9>"; + final String HELP = ChatColor.YELLOW + "/ase help or /ase ?"; + final String VERSION = ChatColor.YELLOW + "/ase version"; + final String UPDATE = ChatColor.YELLOW + "/ase update"; + final String RELOAD = ChatColor.YELLOW + "/ase reload"; + final String GIVECUSTOMMODEL = ChatColor.YELLOW + "/ase give"; + final String GIVEPLAYERHEAD = ChatColor.YELLOW + "/ase playerhead"; + final String GETARMORSTATS = ChatColor.YELLOW + "/ase stats"; + private Debug debug; + + public CommandEx(ArmorStandEditorPlugin armorStandEditorPlugin) { + + this.plugin = armorStandEditorPlugin; + this.debug = new Debug(armorStandEditorPlugin); + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + + if (sender instanceof ConsoleCommandSender) { //Fix to Support #267 + debug.log("Sender is CONSOLE!"); + if (args.length == 0) { + sender.sendMessage(VERSION); + sender.sendMessage(HELP); + sender.sendMessage(RELOAD); + return true; + } else { + switch (args[0].toLowerCase()) { + case "reload" -> commandReloadConsole(sender); + case "help", "?" -> commandHelpConsole(sender); + case "version" -> commandVersionConsole(sender); + default -> { + sender.sendMessage(plugin.getLang().getMessage("noconsolecom", "warn")); + } + } + return true; + } + + } + + if (sender instanceof Player player && !getPermissionBasic(player)) { + debug.log("Sender is Player but asedit.basic is" + getPermissionBasic(player)); + sender.sendMessage(plugin.getLang().getMessage("nopermoption", "warn", "basic")); + return true; + } else { + Player player = (Player) sender; + + debug.log("Sender is Player and asedit.basic is " + getPermissionBasic(player)); + if (args.length == 0) { + player.sendMessage(LISTMODE); + player.sendMessage(LISTAXIS); + player.sendMessage(LISTSLOT); + player.sendMessage(LISTADJUSTMENT); + player.sendMessage(VERSION); + player.sendMessage(UPDATE); + player.sendMessage(HELP); + player.sendMessage(RELOAD); + player.sendMessage(GIVECUSTOMMODEL); + player.sendMessage(GIVEPLAYERHEAD); + player.sendMessage(GETARMORSTATS); + return true; + } + switch (args[0].toLowerCase()) { + case "mode" -> commandMode(player, args); + case "axis" -> commandAxis(player, args); + case "adj" -> commandAdj(player, args); + case "slot" -> commandSlot(player, args); + case "help", "?" -> commandHelp(player); + case "version" -> commandVersion(player); + case "update" -> commandUpdate(player); + case "give" -> commandGive(player); + case "playerhead" -> commandGivePlayerHead(player); + case "reload" -> commandReload(player); + case "stats" -> commandStats(player); + default -> { + sender.sendMessage(LISTMODE); + sender.sendMessage(LISTAXIS); + sender.sendMessage(LISTSLOT); + sender.sendMessage(LISTADJUSTMENT); + sender.sendMessage(VERSION); + sender.sendMessage(UPDATE); + sender.sendMessage(HELP); + sender.sendMessage(RELOAD); + sender.sendMessage(GIVECUSTOMMODEL); + sender.sendMessage(GIVEPLAYERHEAD); + sender.sendMessage(GETARMORSTATS); + } + } + return true; + } + } + + // Implemented to fix: + // https://github.com/Wolfieheart/ArmorStandEditor-Issues/issues/35 & + // https://github.com/Wolfieheart/ArmorStandEditor-Issues/issues/30 - See Remarks OTHER + private void commandGive(Player player) { + if (plugin.getAllowCustomModelData() || checkPermission(player, "give", true)) { + ItemStack stack = new ItemStack(plugin.getEditTool()); //Only Support EditTool at the MOMENT + ItemMeta meta = stack.getItemMeta(); + Objects.requireNonNull(meta).setCustomModelData(plugin.getCustomModelDataInt()); + meta.setUnbreakable(true); + meta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE); + stack.setItemMeta(meta); + player.getInventory().addItem(stack); + player.sendMessage(plugin.getLang().getMessage("give", "info")); + } else { + player.sendMessage(plugin.getLang().getMessage("nogive", "warn")); + } + } + + private void commandGivePlayerHead(Player player) { + if (player.hasPermission("asedit.head")) { + debug.log("Creating a player head for the OfflinePlayer '" + player.getDisplayName() + "'"); + OfflinePlayer offlinePlayer = player.getPlayer(); + ItemStack item = new ItemStack(Material.PLAYER_HEAD, 1, (short) 3); + SkullMeta meta = (SkullMeta) item.getItemMeta(); + meta.setOwningPlayer(offlinePlayer); + item.setItemMeta(meta); + player.getInventory().addItem(item); + player.sendMessage(plugin.getLang().getMessage("playerhead", "info")); + } else { + player.sendMessage(plugin.getLang().getMessage("playerheaderror", "warn")); + } + } + + private void commandSlot(Player player, String[] args) { + + if (args.length <= 1) { + player.sendMessage(plugin.getLang().getMessage("noslotnumcom", "warn")); + player.sendMessage(LISTSLOT); + } + + if (args.length > 1) { + try { + byte slot = (byte) (Byte.parseByte(args[1]) - 0b1); + if (slot >= 0 && slot < 9) { + debug.log("Player has chosen slot: " + slot); + plugin.editorManager.getPlayerEditor(player.getUniqueId()).setCopySlot(slot); + } else { + player.sendMessage(LISTSLOT); + } + + } catch (NumberFormatException nfe) { + player.sendMessage(LISTSLOT); + } + } + } + + private void commandAdj(Player player, String[] args) { + if (args.length <= 1) { + player.sendMessage(plugin.getLang().getMessage("noadjcom", "warn")); + player.sendMessage(LISTADJUSTMENT); + } + + if (args.length > 1) { + for (AdjustmentMode adj : AdjustmentMode.values()) { + if (adj.toString().toLowerCase().contentEquals(args[1].toLowerCase())) { + plugin.editorManager.getPlayerEditor(player.getUniqueId()).setAdjMode(adj); + return; + } + } + player.sendMessage(LISTADJUSTMENT); + } + } + + private void commandAxis(Player player, String[] args) { + if (args.length <= 1) { + player.sendMessage(plugin.getLang().getMessage("noaxiscom", "warn")); + player.sendMessage(LISTAXIS); + } + + if (args.length > 1) { + for (Axis axis : Axis.values()) { + if (axis.toString().toLowerCase().contentEquals(args[1].toLowerCase())) { + debug.log("Player '" + player.getDisplayName() + "' sets the axis to " + axis); + plugin.editorManager.getPlayerEditor(player.getUniqueId()).setAxis(axis); + return; + } + } + player.sendMessage(LISTAXIS); + } + } + + private void commandMode(Player player, String[] args) { + if (args.length <= 1) { + player.sendMessage(plugin.getLang().getMessage("nomodecom", "warn")); + player.sendMessage(LISTMODE); + } + + if (args.length > 1) { + for (EditMode mode : EditMode.values()) { + if (mode.toString().toLowerCase().contentEquals(args[1].toLowerCase())) { + if (args[1].equals("invisible") && !(checkPermission(player, "togglearmorstandvisibility", true) || plugin.getArmorStandVisibility())) return; + if (args[1].equals("itemframe") && !(checkPermission(player, "toggleitemframevisibility", true) || plugin.getItemFrameVisibility())) return; + plugin.editorManager.getPlayerEditor(player.getUniqueId()).setMode(mode); + debug.log("Player '" + player.getDisplayName() + "' chose the mode: " + mode); + return; + } + } + } + } + + private void commandHelp(Player player) { + player.closeInventory(); + player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1f, 1f); + player.sendMessage(plugin.getLang().getMessage("help", "info", plugin.editTool.name())); + player.sendMessage(""); + player.sendMessage(plugin.getLang().getMessage("helptips", "info")); + player.sendMessage(""); + player.sendRawMessage(plugin.getLang().getMessage("helpurl", "")); + player.sendRawMessage(plugin.getLang().getMessage("helpdiscord", "")); + } + + private void commandHelpConsole(CommandSender sender) { + sender.sendMessage(plugin.getLang().getMessage("help", "info", plugin.editTool.name())); + sender.sendMessage(""); + sender.sendMessage(plugin.getLang().getMessage("helptips", "info")); + sender.sendMessage(""); + sender.sendMessage(plugin.getLang().getMessage("helpurl", "info")); + sender.sendMessage(plugin.getLang().getMessage("helpdiscord", "info")); + } + + private void commandUpdate(Player player) { + if (!(checkPermission(player, "update", true))) return; + + //Only Run if the Update Command Works + debug.log("Current ArmorStandEditor Version is: " + plugin.getArmorStandEditorVersion()); + if (plugin.getArmorStandEditorVersion().contains(".x")) { + debug.log("Plugin version is DEVELOPMENT"); + player.sendMessage(ChatColor.YELLOW + "[ArmorStandEditor] Update Checker will not work on Development Versions."); + player.sendMessage(ChatColor.YELLOW + "[ArmorStandEditor] Report all bugs to: https://github.com/Wolfieheart/ArmorStandEditor/issues"); + } else { + if (!plugin.getHasFolia() && plugin.getRunTheUpdateChecker()) { + debug.log("Plugin is on Server: Paper/Spigot or a fork thereof."); + new UpdateChecker(plugin, UpdateCheckSource.SPIGOT, "" + ArmorStandEditorPlugin.SPIGOT_RESOURCE_ID).checkNow(player); //Runs Update Check + } else if (plugin.getHasFolia()) { + debug.log("Plugin is on Folia"); + player.sendMessage(ChatColor.YELLOW + "[ArmorStandEditor] Update Checker does not currently work on Folia."); + player.sendMessage(ChatColor.YELLOW + "[ArmorStandEditor] Report all bugs to: https://github.com/Wolfieheart/ArmorStandEditor/issues"); + } else { + player.sendMessage(ChatColor.YELLOW + "[ArmorStandEditor] Update Checker is not enabled on this server"); + } + } + } + + private void commandVersion(Player player) { + debug.log("Player '" + player.getDisplayName() + "' permission check for asedit.update: " + getPermissionUpdate(player)); + if (!(getPermissionUpdate(player))) return; + String verString = plugin.getArmorStandEditorVersion(); + player.sendMessage(ChatColor.YELLOW + "[ArmorStandEditor] Version: " + verString); + } + + private void commandVersionConsole(CommandSender sender) { + String verString = plugin.getArmorStandEditorVersion(); + sender.sendMessage(ChatColor.YELLOW + "[ArmorStandEditor] Version: " + verString); + } + + private void commandReload(Player player) { + debug.log("Player '" + player.getDisplayName() + "' permission check for asedit.reload: " + getPermissionReload(player)); + + if (!(getPermissionReload(player))) return; + debug.log("Performing reload of config.yml"); + plugin.performReload(); + player.sendMessage(plugin.getLang().getMessage("reloaded", "")); + } + + private void commandReloadConsole(CommandSender sender) { + debug.log("Console has decided to reload the plugin...."); + plugin.performReload(); + sender.sendMessage(plugin.getLang().getMessage("reloaded", "info")); + } + + private void commandStats(Player player) { + debug.log("Player '" + player.getDisplayName() + "' permission check for asedit.stats: " + getPermissionStats(player)); + + if (getPermissionStats(player)) { + for (Entity e : player.getNearbyEntities(1, 1, 1)) { + if (e instanceof ArmorStand as) { + + //Calculation TIME - Might move this out later, but is OK here for now + double sizeAttribute; + + double headX = as.getHeadPose().getX(); + headX = Math.toDegrees(headX); + headX = Math.rint(headX); + + double headY = as.getHeadPose().getY(); + headY = Math.toDegrees(headY); + headY = Math.rint(headY); + + double headZ = as.getHeadPose().getZ(); + headZ = Math.toDegrees(headZ); + headZ = Math.rint(headZ); + + //Body + double bodyX = as.getBodyPose().getX(); + bodyX = Math.toDegrees(bodyX); + bodyX = Math.rint(bodyX); + + double bodyY = as.getBodyPose().getY(); + bodyY = Math.toDegrees(bodyY); + bodyY = Math.rint(bodyY); + + double bodyZ = as.getBodyPose().getZ(); + bodyZ = Math.toDegrees(bodyZ); + bodyZ = Math.rint(bodyZ); + + //Arms + double rightArmY = as.getRightArmPose().getY(); + rightArmY = Math.toDegrees(rightArmY); + rightArmY = Math.rint(rightArmY); + + double rightArmZ = as.getRightArmPose().getZ(); + rightArmZ = Math.toDegrees(rightArmZ); + rightArmZ = Math.rint(rightArmZ); + + double rightArmX = as.getRightArmPose().getX(); + rightArmX = Math.toDegrees(rightArmX); + rightArmX = Math.rint(rightArmX); + + double leftArmX = as.getLeftArmPose().getX(); + leftArmX = Math.toDegrees(leftArmX); + leftArmX = Math.rint(leftArmX); + + double leftArmY = as.getLeftArmPose().getY(); + leftArmY = Math.toDegrees(leftArmY); + leftArmY = Math.rint(leftArmY); + + double leftArmZ = as.getLeftArmPose().getZ(); + leftArmZ = Math.toDegrees(leftArmZ); + leftArmZ = Math.rint(leftArmZ); + + //Legs + double rightLegX = as.getRightLegPose().getX(); + rightLegX = Math.toDegrees(rightLegX); + rightLegX = Math.rint(rightLegX); + + double rightLegY = as.getRightLegPose().getY(); + rightLegY = Math.toDegrees(rightLegY); + rightLegY = Math.rint(rightLegY); + + double rightLegZ = as.getRightLegPose().getZ(); + rightLegZ = Math.toDegrees(rightLegZ); + rightArmX = Math.rint(rightLegZ); + + double leftLegX = as.getLeftLegPose().getX(); + leftLegX = Math.toDegrees(leftLegX); + leftLegX = Math.rint(leftLegX); + + double leftLegY = as.getLeftLegPose().getY(); + leftLegY = Math.toDegrees(leftLegY); + leftLegY = Math.rint(leftLegY); + + double leftLegZ = as.getLeftLegPose().getZ(); + leftLegZ = Math.toDegrees(leftLegZ); + leftLegZ = Math.rint(leftLegZ); + + if (plugin.getNmsVersion().compareTo("1.21.4") >= 0 || plugin.getNmsVersion().compareTo("v1_21_R3") >= 0) { + sizeAttribute = Objects.requireNonNull(as.getAttribute(Attribute.SCALE)).getBaseValue(); + } else { + sizeAttribute = 0; + } + + //Coordinates + float locationX = (float) as.getLocation().getX(); + float locationY = (float) as.getLocation().getY(); + float locationZ = (float) as.getLocation().getZ(); + + //Toggles + boolean isVisible = as.isVisible(); + boolean armsVisible = as.hasArms(); + boolean basePlateVisible = as.hasBasePlate(); + boolean isVulnerable = as.isInvulnerable(); + boolean hasGravity = as.hasGravity(); + boolean isSmall = as.isSmall(); + boolean isGlowing = as.isGlowing(); + boolean isLocked = plugin.scoreboard.getTeam(plugin.lockedTeam).hasEntry(as.getUniqueId().toString()); + + player.sendMessage(ChatColor.YELLOW + "----------- Armor Stand Statistics -----------"); + player.sendMessage(ChatColor.YELLOW + plugin.getLang().getMessage("stats")); + player.sendMessage(ChatColor.YELLOW + "Head: " + ChatColor.AQUA + headX + " / " + headY + " / " + headZ); + player.sendMessage(ChatColor.YELLOW + "Body: " + ChatColor.AQUA + bodyX + " / " + bodyY + " / " + bodyZ); + player.sendMessage(ChatColor.YELLOW + "Right Arm: " + ChatColor.AQUA + rightArmX + " / " + rightArmY + " / " + rightArmZ); + player.sendMessage(ChatColor.YELLOW + "Left Arm: " + ChatColor.AQUA + leftArmX + " / " + leftArmY + " / " + leftArmZ); + player.sendMessage(ChatColor.YELLOW + "Right Leg: " + ChatColor.AQUA + rightLegX + " / " + rightLegY + " / " + rightLegZ); + player.sendMessage(ChatColor.YELLOW + "Left Leg: " + ChatColor.AQUA + leftLegX + " / " + leftLegY + " / " + leftLegZ); + player.sendMessage(ChatColor.YELLOW + "Coordinates: " + ChatColor.AQUA + " X: " + locationX + " / Y: " + locationY + " / Z: " + locationZ); + player.sendMessage(ChatColor.YELLOW + "Is Visible: " + ChatColor.AQUA + isVisible + ". " + ChatColor.YELLOW + "Arms Visible: " + ChatColor.AQUA + armsVisible + ". " + ChatColor.YELLOW + "Base Plate Visible: " + ChatColor.AQUA + basePlateVisible); + player.sendMessage(ChatColor.YELLOW + "Is Vulnerable: " + ChatColor.AQUA + isVulnerable + ". " + ChatColor.YELLOW + "Affected by Gravity: " + ChatColor.AQUA + hasGravity); + if (plugin.getNmsVersion().compareTo("1.21.4") >= 0 || plugin.getNmsVersion().compareTo("v1_21_R3") >= 0) { + player.sendMessage(ChatColor.YELLOW + "Size: " + ChatColor.AQUA + sizeAttribute + "/" + plugin.getMaxScaleValue() + ". " + ChatColor.YELLOW + "Is Glowing: " + ChatColor.AQUA + isGlowing + ". " + ChatColor.YELLOW + "Is Locked: " + ChatColor.AQUA + isLocked); + } else { + player.sendMessage(ChatColor.YELLOW + "Is Small: " + ChatColor.AQUA + isSmall + ". " + ChatColor.YELLOW + "Is Glowing: " + ChatColor.AQUA + isGlowing + ". " + ChatColor.YELLOW + "Is Locked: " + ChatColor.AQUA + isLocked); + } + player.sendMessage(ChatColor.YELLOW + "----------------------------------------------"); + + } + } + } else { + player.sendMessage(plugin.getLang().getMessage("norangeforstats", "warn")); + } + } + + + private boolean checkPermission(Player player, String permName, boolean sendMessageOnInvalidation) { + if (permName.equalsIgnoreCase("paste")) { + permName = "copy"; + } + if (player.hasPermission("asedit." + permName.toLowerCase())) { + return true; + } else { + if (sendMessageOnInvalidation) { + player.sendMessage(plugin.getLang().getMessage("noperm", "warn")); + } + return false; + } + } + + private boolean getPermissionBasic(Player player) { + return checkPermission(player, "basic", false); + } + + private boolean getPermissionGive(Player player) { + return checkPermission(player, "give", false); + } + + private boolean getPermissionUpdate(Player player) { + return checkPermission(player, "update", false); + } + + private boolean getPermissionReload(Player player) { + return checkPermission(player, "reload", false); + } + + private boolean getPermissionPlayerHead(Player player) { + return checkPermission(player, "head", false); + } + + private boolean getPermissionStats(Player player) { + return checkPermission(player, "stats", false); + } + + //REFACTOR COMPLETION + @Override + public List onTabComplete(CommandSender sender, Command command, String label, String[] args) { + List argList = new ArrayList<>(); + Player player = (Player) sender; + + if (isCommandValid(command.getName())) { + + if (args.length == 1) { + argList.add("mode"); + argList.add("axis"); + argList.add("adj"); + argList.add("slot"); + argList.add("help"); + argList.add("?"); + + //Will Only work with permissions + if (getPermissionGive(player)) { + argList.add("give"); + } + if (getPermissionUpdate(player)) { + argList.add("update"); + } + if (getPermissionReload(player)) { + argList.add("reload"); + } + if (getPermissionPlayerHead(player) || plugin.getallowedToRetrieveOwnPlayerHead()) { + argList.add("playerhead"); + } + + if (getPermissionStats(player)) { + argList.add("stats"); + } + } + + if (args.length == 2 && args[0].equalsIgnoreCase("mode")) { + argList.addAll(getModeOptions()); + } + + if (args.length == 2 && args[0].equalsIgnoreCase("axis")) { + argList.addAll(getAxisOptions()); + } + + if (args.length == 2 && args[0].equalsIgnoreCase("slot")) { + argList.addAll(getSlotOptions()); + } + + if (args.length == 2 && args[0].equalsIgnoreCase("adj")) { + argList.addAll(getAdjOptions()); + } + + return argList.stream().filter(a -> a.startsWith(args[0])).toList(); + } + + return Collections.emptyList(); + } + + private boolean isCommandValid(String commandName) { + return commandName.equalsIgnoreCase("ase") || + commandName.equalsIgnoreCase("armorstandeditor") || + commandName.equalsIgnoreCase("asedit"); + } + + private List getModeOptions() { + return List.of( + "None", "Invisible", "ShowArms", "Gravity", "BasePlate", + "Size", "Copy", "Paste", "Head", "Body", "LeftArm", + "RightArm", "LeftLeg", "RightLeg", "Placement", + "DisableSlots", "Rotate", "Equipment", "Reset", + "ItemFrame", "ItemFrameGlow", "Vulnerability", "ArmorStandGlow" + ); + } + + private List getAxisOptions() { + return List.of("X", "Y", "Z"); + } + + private List getSlotOptions() { + return List.of("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); + } + + private List getAdjOptions() { + return List.of("Coarse", "Fine"); + } -public class CommandEx implements CommandExecutor{ - ArmorStandEditorPlugin plugin; - final String LISTMODE = ChatColor.GREEN + "/ase mode <" + Util.getEnumList(EditMode.class) + ">"; - final String LISTAXIS = ChatColor.GREEN + "/ase axis <" + Util.getEnumList(Axis.class) + ">"; - final String LISTADJUSTMENT = ChatColor.GREEN + "/ase adj <" + Util.getEnumList(AdjustmentMode.class) + ">"; - final String LISTSLOT = ChatColor.GREEN + "/ase slot <1-9>"; - final String HELP = ChatColor.GREEN + "/ase help"; - - public CommandEx(ArmorStandEditorPlugin armorStandEditorPlugin) { - this.plugin = armorStandEditorPlugin; - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if(!(sender instanceof Player - && checkPermission((Player)sender,"basic",true))){ - sender.sendMessage(plugin.getLang().getMessage("noperm", "warn")); - return true; - } - - Player player = (Player) sender; - if(args.length == 0){ - player.sendMessage(LISTMODE); - player.sendMessage(LISTAXIS); - player.sendMessage(LISTSLOT); - player.sendMessage(LISTADJUSTMENT); - return true; - } - switch(args[0].toLowerCase()){ - case "mode": commandMode(player, args); - break; - case "axis": commandAxis(player, args); - break; - case "adj": commandAdj(player, args); - break; - case "slot": commandSlot(player, args); - break; - case "help": - case "?": commandHelp(player); - break; - default: - sender.sendMessage(LISTMODE); - sender.sendMessage(LISTAXIS); - sender.sendMessage(LISTSLOT); - sender.sendMessage(LISTADJUSTMENT); - sender.sendMessage(HELP); - } - return true; - } - - private void commandSlot(Player player, String[] args) { - - if(args.length <=1){ - player.sendMessage(plugin.getLang().getMessage("noslotnumcom", "warn")); - player.sendMessage(LISTSLOT); - } - - if(args.length > 1){ - try{ - byte slot = (byte) (Byte.parseByte(args[1]) - 0b1); - if(slot >= 0 && slot < 9){ - plugin.editorManager.getPlayerEditor(player.getUniqueId()).setCopySlot(slot); - }else{ - player.sendMessage(LISTSLOT); - } - - }catch(NumberFormatException nfe){ - player.sendMessage(LISTSLOT); - } - } - } - - private void commandAdj(Player player, String[] args) { - if(args.length <=1){ - player.sendMessage(plugin.getLang().getMessage("noadjcom", "warn")); - player.sendMessage(LISTADJUSTMENT ); - } - - if(args.length > 1){ - for(AdjustmentMode adj : AdjustmentMode.values()){ - if(adj.toString().toLowerCase().contentEquals(args[1].toLowerCase())){ - plugin.editorManager.getPlayerEditor(player.getUniqueId()).setAdjMode(adj); - return; - } - } - player.sendMessage(LISTADJUSTMENT); - } - } - - private void commandAxis(Player player, String[] args) { - if(args.length <=1){ - player.sendMessage(plugin.getLang().getMessage("noaxiscom", "warn")); - player.sendMessage(LISTAXIS); - } - - if(args.length > 1){ - for(Axis axis : Axis.values()){ - if(axis.toString().toLowerCase().contentEquals(args[1].toLowerCase())){ - plugin.editorManager.getPlayerEditor(player.getUniqueId()).setAxis(axis); - return; - } - } - player.sendMessage(LISTAXIS); - } - } - - private void commandMode(Player player, String[] args) { - if(args.length <=1){ - player.sendMessage(plugin.getLang().getMessage("nomodecom", "warn")); - player.sendMessage(LISTMODE); - } - - if(args.length > 1){ - for(EditMode mode : EditMode.values()){ - if(mode.toString().toLowerCase().contentEquals(args[1].toLowerCase())){ - if(args[1].equals("invisible") && !checkPermission(player, "invisible",true)) return; - plugin.editorManager.getPlayerEditor(player.getUniqueId()).setMode(mode); - return; - } - } - } - } - - private void commandHelp(Player player){ - player.closeInventory(); - player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1f, 1f); - player.sendMessage(plugin.getLang().getMessage("help", "info", plugin.editTool.name())); - player.sendMessage(""); - player.sendMessage(plugin.getLang().getMessage("helptips", "info")); - player.sendMessage(""); - player.sendRawMessage(plugin.getLang().getMessage("helpurl", "")); - } - - private boolean checkPermission(Player player, String permName, boolean sendMessageOnInvalidation){ - if(permName.toLowerCase().equals("paste")){ - permName = "copy"; - } - if(player.hasPermission("asedit." + permName.toLowerCase())){ - return true; - }else{ - if(sendMessageOnInvalidation){ - player.sendMessage(plugin.getLang().getMessage("noperm", "warn")); - } - return false; - } - } -} \ No newline at end of file +} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/Debug.java b/src/main/java/io/github/rypofalem/armorstandeditor/Debug.java new file mode 100644 index 00000000..9cb447e6 --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/Debug.java @@ -0,0 +1,21 @@ +package io.github.rypofalem.armorstandeditor; + +import org.bukkit.Bukkit; + +import java.util.logging.Level; + +public class Debug { + + private boolean debugTurnedOn; + private ArmorStandEditorPlugin plugin; + + public Debug(ArmorStandEditorPlugin plugin) { + this.plugin = plugin; + } + + public void log(String msg) { + debugTurnedOn = plugin.isDebug(); + if (!debugTurnedOn) return; + Bukkit.getServer().getLogger().log(Level.INFO, "[ArmorStandEditor-Debug] " + msg); + } +} \ No newline at end of file diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/Metrics.java b/src/main/java/io/github/rypofalem/armorstandeditor/Metrics.java new file mode 100644 index 00000000..a842cfab --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/Metrics.java @@ -0,0 +1,881 @@ +/* + * This Metrics class was auto-generated and can be copied into your project if you are + * not using a build tool like Gradle or Maven for dependency management. + * + * IMPORTANT: You are not allowed to modify this class, except changing the package. + * + * Disallowed modifications include but are not limited to: + * - Remove the option for users to opt-out + * - Change the frequency for data submission + * - Obfuscate the code (every obfuscator should allow you to make an exception for specific files) + * - Reformat the code (if you use a linter, add an exception) + * + * Violations will result in a ban of your plugin and account from bStats. + */ +package io.github.rypofalem.armorstandeditor; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.stream.Collectors; +import java.util.zip.GZIPOutputStream; +import javax.net.ssl.HttpsURLConnection; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +public class Metrics { + + private final Plugin plugin; + + private final MetricsBase metricsBase; + + /** + * Creates a new Metrics instance. + * + * @param plugin Your plugin instance. + * @param serviceId The id of the service. It can be found at What is my plugin id? + */ + public Metrics(JavaPlugin plugin, int serviceId) { + this.plugin = plugin; + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (!config.isSet("serverUuid")) { + config.addDefault("enabled", true); + config.addDefault("serverUuid", UUID.randomUUID().toString()); + config.addDefault("logFailedRequests", false); + config.addDefault("logSentData", false); + config.addDefault("logResponseStatusText", false); + // Inform the server owners about bStats + config + .options() + .header( + "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" + + "many people use their plugin and their total player count. It's recommended to keep bStats\n" + + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" + + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" + + "anonymous.") + .copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + // Load the data + boolean enabled = config.getBoolean("enabled", true); + String serverUUID = config.getString("serverUuid"); + boolean logErrors = config.getBoolean("logFailedRequests", false); + boolean logSentData = config.getBoolean("logSentData", false); + boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); + metricsBase = + new MetricsBase( + "bukkit", + serverUUID, + serviceId, + enabled, + this::appendPlatformData, + this::appendServiceData, + submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), + plugin::isEnabled, + (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), + (message) -> this.plugin.getLogger().log(Level.INFO, message), + logErrors, + logSentData, + logResponseStatusText); + } + + /** Shuts down the underlying scheduler service. */ + public void shutdown() { + metricsBase.shutdown(); + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + metricsBase.addCustomChart(chart); + } + + private void appendPlatformData(JsonObjectBuilder builder) { + builder.appendField("playerAmount", getPlayerAmount()); + builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); + builder.appendField("bukkitVersion", Bukkit.getVersion()); + builder.appendField("bukkitName", Bukkit.getName()); + builder.appendField("javaVersion", System.getProperty("java.version")); + builder.appendField("osName", System.getProperty("os.name")); + builder.appendField("osArch", System.getProperty("os.arch")); + builder.appendField("osVersion", System.getProperty("os.version")); + builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); + } + + private void appendServiceData(JsonObjectBuilder builder) { + builder.appendField("pluginVersion", plugin.getDescription().getVersion()); + } + + private int getPlayerAmount() { + try { + // Around MC 1.8 the return type was changed from an array to a collection, + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + return onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + // Just use the new method if the reflection failed + return Bukkit.getOnlinePlayers().size(); + } + } + + public static class MetricsBase { + + /** The version of the Metrics class. */ + public static final String METRICS_VERSION = "3.0.2"; + + private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; + + private final ScheduledExecutorService scheduler; + + private final String platform; + + private final String serverUuid; + + private final int serviceId; + + private final Consumer appendPlatformDataConsumer; + + private final Consumer appendServiceDataConsumer; + + private final Consumer submitTaskConsumer; + + private final Supplier checkServiceEnabledSupplier; + + private final BiConsumer errorLogger; + + private final Consumer infoLogger; + + private final boolean logErrors; + + private final boolean logSentData; + + private final boolean logResponseStatusText; + + private final Set customCharts = new HashSet<>(); + + private final boolean enabled; + + /** + * Creates a new MetricsBase class instance. + * + * @param platform The platform of the service. + * @param serviceId The id of the service. + * @param serverUuid The server uuid. + * @param enabled Whether or not data sending is enabled. + * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all platform-specific data. + * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all service-specific data. + * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be + * used to delegate the data collection to a another thread to prevent errors caused by + * concurrency. Can be {@code null}. + * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. + * @param errorLogger A consumer that accepts log message and an error. + * @param infoLogger A consumer that accepts info log messages. + * @param logErrors Whether or not errors should be logged. + * @param logSentData Whether or not the sent data should be logged. + * @param logResponseStatusText Whether or not the response status text should be logged. + */ + public MetricsBase( + String platform, + String serverUuid, + int serviceId, + boolean enabled, + Consumer appendPlatformDataConsumer, + Consumer appendServiceDataConsumer, + Consumer submitTaskConsumer, + Supplier checkServiceEnabledSupplier, + BiConsumer errorLogger, + Consumer infoLogger, + boolean logErrors, + boolean logSentData, + boolean logResponseStatusText) { + ScheduledThreadPoolExecutor scheduler = + new ScheduledThreadPoolExecutor(1, task -> new Thread(task, "bStats-Metrics")); + // We want delayed tasks (non-periodic) that will execute in the future to be + // cancelled when the scheduler is shutdown. + // Otherwise, we risk preventing the server from shutting down even when + // MetricsBase#shutdown() is called + scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + this.scheduler = scheduler; + this.platform = platform; + this.serverUuid = serverUuid; + this.serviceId = serviceId; + this.enabled = enabled; + this.appendPlatformDataConsumer = appendPlatformDataConsumer; + this.appendServiceDataConsumer = appendServiceDataConsumer; + this.submitTaskConsumer = submitTaskConsumer; + this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; + this.errorLogger = errorLogger; + this.infoLogger = infoLogger; + this.logErrors = logErrors; + this.logSentData = logSentData; + this.logResponseStatusText = logResponseStatusText; + checkRelocation(); + if (enabled) { + // WARNING: Removing the option to opt-out will get your plugin banned from + // bStats + startSubmitting(); + } + } + + public void addCustomChart(CustomChart chart) { + this.customCharts.add(chart); + } + + public void shutdown() { + scheduler.shutdown(); + } + + private void startSubmitting() { + final Runnable submitTask = + () -> { + if (!enabled || !checkServiceEnabledSupplier.get()) { + // Submitting data or service is disabled + scheduler.shutdown(); + return; + } + if (submitTaskConsumer != null) { + submitTaskConsumer.accept(this::submitData); + } else { + this.submitData(); + } + }; + // Many servers tend to restart at a fixed time at xx:00 which causes an uneven + // distribution of requests on the + // bStats backend. To circumvent this problem, we introduce some randomness into + // the initial and second delay. + // WARNING: You must not modify and part of this Metrics class, including the + // submit delay or frequency! + // WARNING: Modifying this code will get your plugin banned on bStats. Just + // don't do it! + long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); + long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); + scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); + scheduler.scheduleAtFixedRate( + submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); + } + + private void submitData() { + final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); + appendPlatformDataConsumer.accept(baseJsonBuilder); + final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); + appendServiceDataConsumer.accept(serviceJsonBuilder); + JsonObjectBuilder.JsonObject[] chartData = + customCharts.stream() + .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) + .filter(Objects::nonNull) + .toArray(JsonObjectBuilder.JsonObject[]::new); + serviceJsonBuilder.appendField("id", serviceId); + serviceJsonBuilder.appendField("customCharts", chartData); + baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); + baseJsonBuilder.appendField("serverUUID", serverUuid); + baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); + JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); + scheduler.execute( + () -> { + try { + // Send the data + sendData(data); + } catch (Exception e) { + // Something went wrong! :( + if (logErrors) { + errorLogger.accept("Could not submit bStats metrics data", e); + } + } + }); + } + + private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { + if (logSentData) { + infoLogger.accept("Sent bStats metrics data: " + data.toString()); + } + String url = String.format(REPORT_URL, platform); + HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("User-Agent", "Metrics-Service/1"); + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = + new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + if (logResponseStatusText) { + infoLogger.accept("Sent data to bStats and received response: " + builder); + } + } + + /** Checks that the class was properly relocated. */ + private void checkRelocation() { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null + || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this + // little "trick" ... :D + final String defaultPackage = + new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); + final String examplePackage = + new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure no one just copy & pastes the example and uses the wrong + // package names + if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) + || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + /** + * Gzips the given string. + * + * @param str The string to gzip. + * @return The gzipped string. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + } + + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } + } + + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public abstract static class CustomChart { + + private final String chartId; + + protected CustomChart(String chartId) { + if (chartId == null) { + throw new IllegalArgumentException("chartId must not be null"); + } + this.chartId = chartId; + } + + public JsonObjectBuilder.JsonObject getRequestJsonObject( + BiConsumer errorLogger, boolean logErrors) { + JsonObjectBuilder builder = new JsonObjectBuilder(); + builder.appendField("chartId", chartId); + try { + JsonObjectBuilder.JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + builder.appendField("data", data); + } catch (Throwable t) { + if (logErrors) { + errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return builder.build(); + } + + protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; + } + + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } + } + + /** + * An extremely simple JSON builder. + * + *

While this class is neither feature-rich nor the most performant one, it's sufficient enough + * for its use-case. + */ + public static class JsonObjectBuilder { + + private StringBuilder builder = new StringBuilder(); + + private boolean hasAtLeastOneField = false; + + public JsonObjectBuilder() { + builder.append("{"); + } + + /** + * Appends a null field to the JSON. + * + * @param key The key of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendNull(String key) { + appendFieldUnescaped(key, "null"); + return this; + } + + /** + * Appends a string field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String value) { + if (value == null) { + throw new IllegalArgumentException("JSON value must not be null"); + } + appendFieldUnescaped(key, "\"" + escape(value) + "\""); + return this; + } + + /** + * Appends an integer field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int value) { + appendFieldUnescaped(key, String.valueOf(value)); + return this; + } + + /** + * Appends an object to the JSON. + * + * @param key The key of the field. + * @param object The object. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject object) { + if (object == null) { + throw new IllegalArgumentException("JSON object must not be null"); + } + appendFieldUnescaped(key, object.toString()); + return this; + } + + /** + * Appends a string array to the JSON. + * + * @param key The key of the field. + * @param values The string array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values) + .map(value -> "\"" + escape(value) + "\"") + .collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an integer array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an object array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends a field to the object. + * + * @param key The key of the field. + * @param escapedValue The escaped value of the field. + */ + private void appendFieldUnescaped(String key, String escapedValue) { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + if (key == null) { + throw new IllegalArgumentException("JSON key must not be null"); + } + if (hasAtLeastOneField) { + builder.append(","); + } + builder.append("\"").append(escape(key)).append("\":").append(escapedValue); + hasAtLeastOneField = true; + } + + /** + * Builds the JSON string and invalidates this builder. + * + * @return The built JSON string. + */ + public JsonObject build() { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + JsonObject object = new JsonObject(builder.append("}").toString()); + builder = null; + return object; + } + + /** + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ + private static String escape(String value) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"') { + builder.append("\\\""); + } else if (c == '\\') { + builder.append("\\\\"); + } else if (c <= '\u000F') { + builder.append("\\u000").append(Integer.toHexString(c)); + } else if (c <= '\u001F') { + builder.append("\\u00").append(Integer.toHexString(c)); + } else { + builder.append(c); + } + } + return builder.toString(); + } + + /** + * A super simple representation of a JSON object. + * + *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not + * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, + * JsonObject)}. + */ + public static class JsonObject { + + private final String value; + + private JsonObject(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + } + } +} \ No newline at end of file diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditor.java b/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditor.java index 82b565dd..7538b1a5 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditor.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditor.java @@ -1,6 +1,6 @@ /* * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016 RypoFalem + * Copyright (C) 2016-2023 RypoFalem * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -16,405 +16,735 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - package io.github.rypofalem.armorstandeditor; +import io.github.rypofalem.armorstandeditor.menu.SizeMenu; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; + +import io.github.rypofalem.armorstandeditor.api.*; import io.github.rypofalem.armorstandeditor.menu.EquipmentMenu; import io.github.rypofalem.armorstandeditor.menu.Menu; +import io.github.rypofalem.armorstandeditor.menu.PresetArmorPosesMenu; + +//Do not optimize these..... This will no work properly import io.github.rypofalem.armorstandeditor.modes.AdjustmentMode; import io.github.rypofalem.armorstandeditor.modes.ArmorStandData; import io.github.rypofalem.armorstandeditor.modes.Axis; import io.github.rypofalem.armorstandeditor.modes.CopySlots; import io.github.rypofalem.armorstandeditor.modes.EditMode; +import io.github.rypofalem.armorstandeditor.Debug; -import java.util.ArrayList; -import java.util.UUID; - -import net.md_5.bungee.api.ChatMessageType; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; +import org.bukkit.*; +import org.bukkit.attribute.Attribute; import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.ItemFrame; import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import org.bukkit.scoreboard.Team; import org.bukkit.util.EulerAngle; +import java.util.ArrayList; +import java.util.UUID; + public class PlayerEditor { - public ArmorStandEditorPlugin plugin; - private UUID uuid; - EditMode eMode; - AdjustmentMode adjMode; - CopySlots copySlots; - Axis axis; - double eulerAngleChange; - double degreeAngleChange; - double movChange; - Menu chestMenu; - ArmorStand target; - ArrayList targetList = null; - int targetIndex = 0; - EquipmentMenu equipMenu; - long lastCancelled = 0; - - public PlayerEditor(UUID uuid, ArmorStandEditorPlugin plugin){ - this.uuid =uuid; - this.plugin = plugin; - eMode = EditMode.NONE; - adjMode = AdjustmentMode.COARSE; - axis = Axis.X; - copySlots = new CopySlots(); - eulerAngleChange = getManager().coarseAdj; - degreeAngleChange = eulerAngleChange /Math.PI * 180; - movChange = getManager().coarseMov; - chestMenu = new Menu(this); - } - - public void setMode(EditMode editMode){ - this.eMode = editMode; - sendMessage("setmode", editMode.toString().toLowerCase()); - } - - public void setAxis(Axis axis){ - this.axis = axis; - sendMessage("setaxis", axis.toString().toLowerCase()); - } - - public void setAdjMode(AdjustmentMode adjMode){ - this.adjMode = adjMode; - if(adjMode == AdjustmentMode.COARSE){ - eulerAngleChange = getManager().coarseAdj; - movChange = getManager().coarseMov; - }else{ - eulerAngleChange = getManager().fineAdj; - movChange = getManager().fineMov; - } - degreeAngleChange = eulerAngleChange /Math.PI * 180; - sendMessage("setadj", adjMode.toString().toLowerCase()); - } - - public void setCopySlot(byte slot){ - copySlots.changeSlots(slot); - sendMessage("setslot" , String.valueOf((slot + 1))); - } - - public void editArmorStand(ArmorStand armorStand) { - if(!getPlayer().hasPermission("asedit.basic")) return; - armorStand = attemptTarget(armorStand); - switch(eMode){ - case LEFTARM: armorStand.setLeftArmPose(subEulerAngle(armorStand.getLeftArmPose())); - break; - case RIGHTARM: armorStand.setRightArmPose(subEulerAngle(armorStand.getRightArmPose())); - break; - case BODY: armorStand.setBodyPose(subEulerAngle(armorStand.getBodyPose())); - break; - case HEAD: armorStand.setHeadPose(subEulerAngle(armorStand.getHeadPose())); - break; - case LEFTLEG: armorStand.setLeftLegPose(subEulerAngle(armorStand.getLeftLegPose())); - break; - case RIGHTLEG: armorStand.setRightLegPose(subEulerAngle(armorStand.getRightLegPose())); - break; - case SHOWARMS: toggleArms(armorStand); - break; - case SIZE: toggleSize(armorStand); - break; - case INVISIBLE: toggleVisible(armorStand); - break; - case BASEPLATE: togglePlate(armorStand); - break; - case GRAVITY: toggleGravity(armorStand); - break; - case COPY: copy(armorStand); - break; - case PASTE: paste(armorStand); - break; - case PLACEMENT: move(armorStand); - break; - case ROTATE: rotate(armorStand); - break; - case DISABLESLOTS: toggleDisableSlots(armorStand); - break; - case EQUIPMENT: openEquipment(armorStand); - break; - case RESET: resetPosition(armorStand); - break; - case NONE: sendMessage("nomode", null); break; - } - } - - private void resetPosition(ArmorStand armorStand) { - armorStand.setHeadPose(new EulerAngle(0,0,0)); - armorStand.setBodyPose(new EulerAngle(0,0,0)); - armorStand.setLeftArmPose(new EulerAngle(0,0,0)); - armorStand.setRightArmPose(new EulerAngle(0,0,0)); - armorStand.setLeftLegPose(new EulerAngle(0,0,0)); - armorStand.setRightLegPose(new EulerAngle(0,0,0)); - } - - private void openEquipment(ArmorStand armorStand) { - equipMenu = new EquipmentMenu(this, armorStand); - equipMenu.open(); - } - - public void reverseEditArmorStand(ArmorStand armorStand){ - if(!getPlayer().hasPermission("asedit.basic")) return; - armorStand = attemptTarget(armorStand); - switch(eMode){ - case LEFTARM: armorStand.setLeftArmPose(addEulerAngle(armorStand.getLeftArmPose())); - break; - case RIGHTARM: armorStand.setRightArmPose(addEulerAngle(armorStand.getRightArmPose())); - break; - case BODY: armorStand.setBodyPose(addEulerAngle(armorStand.getBodyPose())); - break; - case HEAD: armorStand.setHeadPose(addEulerAngle(armorStand.getHeadPose())); - break; - case LEFTLEG: armorStand.setLeftLegPose(addEulerAngle(armorStand.getLeftLegPose())); - break; - case RIGHTLEG: armorStand.setRightLegPose(addEulerAngle(armorStand.getRightLegPose())); - break; - case PLACEMENT: reverseMove(armorStand); - break; - case ROTATE: reverseRotate(armorStand); - break; - default: editArmorStand(armorStand); - } - } - - private void move(ArmorStand armorStand) { - Location loc = armorStand.getLocation(); - switch(axis){ - case X: loc.add(movChange, 0, 0); - break; - case Y: loc.add(0, movChange, 0); - break; - case Z: loc.add(0, 0, movChange); - break; - } - armorStand.teleport(loc); - } - - private void reverseMove(ArmorStand armorStand) { - Location loc = armorStand.getLocation(); - switch(axis){ - case X: loc.subtract(movChange, 0, 0); - break; - case Y: loc.subtract(0, movChange, 0); - break; - case Z: loc.subtract(0, 0, movChange); - break; - } - armorStand.teleport(loc); - } - - private void rotate(ArmorStand armorStand){ - Location loc = armorStand.getLocation(); - float yaw = loc.getYaw(); - loc.setYaw((yaw + 180 + (float)degreeAngleChange)%360 - 180); - armorStand.teleport(loc); - } - - private void reverseRotate(ArmorStand armorStand){ - Location loc = armorStand.getLocation(); - float yaw = loc.getYaw(); - loc.setYaw((yaw + 180 - (float)degreeAngleChange)%360 - 180); - armorStand.teleport(loc); - } - - private void copy(ArmorStand armorStand) { - copySlots.copyDataToSlot(armorStand); - sendMessage("copied" , "" + (copySlots.currentSlot + 1)); - setMode(EditMode.PASTE); - } - - private void paste(ArmorStand armorStand){ - ArmorStandData data = copySlots.getDataToPaste(); - if(data == null ) return; - armorStand.setHeadPose(data.headPos); - armorStand.setBodyPose(data.bodyPos); - armorStand.setLeftArmPose(data.leftArmPos); - armorStand.setRightArmPose(data.rightArmPos); - armorStand.setLeftLegPose(data.leftLegPos); - armorStand.setRightLegPose(data.rightLegPos); - armorStand.setSmall(data.size); - armorStand.setGravity(data.gravity); - armorStand.setBasePlate(data.basePlate); - armorStand.setArms(data.showArms); - armorStand.setVisible(data.visible); - if(this.getPlayer().getGameMode() == GameMode.CREATIVE){ - armorStand.getEquipment().setHelmet(data.head); - armorStand.getEquipment().setChestplate(data.body); - armorStand.getEquipment().setLeggings(data.legs); - armorStand.getEquipment().setBoots(data.feetsies); - armorStand.getEquipment().setItemInMainHand(data.rightHand); - armorStand.getEquipment().setItemInOffHand(data.leftHand); - } - sendMessage("pasted", ""+ (copySlots.currentSlot + 1)); - } - - private void toggleDisableSlots(ArmorStand armorStand) { - //TODO - } - - private void toggleGravity(ArmorStand armorStand) { - armorStand.setGravity(!armorStand.hasGravity()); - String state = armorStand.hasGravity() ? "on" : "off"; - sendMessage("setgravity", state); - } - - void togglePlate(ArmorStand armorStand) { - armorStand.setBasePlate(!armorStand.hasBasePlate()); - } - - void toggleArms(ArmorStand armorStand){ - armorStand.setArms(!armorStand.hasArms()); - } - - void toggleVisible(ArmorStand armorStand){ - if(!getPlayer().hasPermission("asedit.invisible")) return; - armorStand.setVisible(!armorStand.isVisible()); - } - - void toggleSize(ArmorStand armorStand){ - armorStand.setSmall(!armorStand.isSmall()); - } - - void cycleAxis(int i) { - int index = axis.ordinal(); - index += i; - index = index % Axis.values().length; - while(index < 0){ - index += Axis.values().length; - } - setAxis(Axis.values()[index]); - } - - private EulerAngle addEulerAngle(EulerAngle angle) { - switch(axis){ - case X: angle = angle.setX(Util.addAngle(angle.getX(), eulerAngleChange)); - break; - case Y: angle = angle.setY(Util.addAngle(angle.getY(), eulerAngleChange)); - break; - case Z: angle = angle.setZ(Util.addAngle(angle.getZ(), eulerAngleChange)); - break; - default: - break; - } - return angle; - } - - private EulerAngle subEulerAngle(EulerAngle angle) { - switch(axis){ - case X: angle = angle.setX(Util.subAngle(angle.getX(), eulerAngleChange)); - break; - case Y: angle = angle.setY(Util.subAngle(angle.getY(), eulerAngleChange)); - break; - case Z: angle = angle.setZ(Util.subAngle(angle.getZ(), eulerAngleChange)); - break; - default: - break; - } - return angle; - } - - public void setTarget(ArrayList armorStands){ - if(armorStands == null || armorStands.isEmpty()){ - target = null; - targetList = null; - sendMessage("notarget", null); - return; - } - - if(targetList == null){ - targetList = armorStands; - targetIndex = 0; - sendMessage("target", null); - } else{ - boolean same = targetList.size() == armorStands.size(); - if(same) for(ArmorStand as : armorStands){ - same = targetList.contains(as); - if(!same) break; - } - - if(same){ - targetIndex = ++targetIndex % targetList.size(); - }else{ - targetList = armorStands; - targetIndex = 0; - sendMessage("target", null); - } - } - target = targetList.get(targetIndex); - highlight(target); - } - - ArmorStand attemptTarget(ArmorStand armorStand){ - if(target == null - || !target.isValid() - || target.getWorld() != getPlayer().getWorld() - || target.getLocation().distanceSquared(getPlayer().getLocation()) > 100) - return armorStand; - armorStand = target; - highlight(armorStand); - return armorStand; - } - - void sendMessage(String path, String format, String option){ - String message = plugin.getLang().getMessage(path, format, option); - if(plugin.sendToActionBar){ - if(ArmorStandEditorPlugin.instance().hasSpigot){ - plugin.getServer().getPlayer(getUUID()).spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(message)); - } else{ - String rawText = plugin.getLang().getRawMessage(path, format, option); - String command = String.format("title %s actionbar %s", plugin.getServer().getPlayer(getUUID()).getName(), rawText); - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); - } - } else{ - plugin.getServer().getPlayer(getUUID()).sendMessage(message); - } - } - - void sendMessage(String path, String option){ - sendMessage(path, "info", option); - } - - private void highlight(ArmorStand armorStand){ - armorStand.removePotionEffect(PotionEffectType.GLOWING); - armorStand.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 15, 1, false, false)); - } - - public PlayerEditorManager getManager(){ - return plugin.editorManager; - } - - public Player getPlayer(){ - return plugin.getServer().getPlayer(getUUID()); - } - - public UUID getUUID() { - return uuid; - } - - public void openMenu() { - if(!isMenuCancelled()){ - plugin.getServer().getScheduler().runTaskLater(plugin, new OpenMenuTask(), 1).getTaskId(); - } - } - - public void cancelOpenMenu() { - lastCancelled = getManager().getTime(); - } - - boolean isMenuCancelled(){ - return getManager().getTime() - lastCancelled < 2; - } - - private class OpenMenuTask implements Runnable{ - - @Override - public void run() { - if(isMenuCancelled()) return; - chestMenu.openMenu(); - } - } -} \ No newline at end of file + public ArmorStandEditorPlugin plugin; + private Debug debug; + Team team; + private UUID uuid; + public UUID armorStandInUseId; + UUID armorStandID; + EditMode eMode; + AdjustmentMode adjMode; + CopySlots copySlots; + Axis axis; + double eulerAngleChange; + double degreeAngleChange; + double movChange; + Menu chestMenu; + ArmorStand target; + ArrayList targetList = null; + + //NEW: ItemFrame Stuff + ItemFrame frameTarget; + ArrayList frameTargetList = null; + int targetIndex = 0; + int frameTargetIndex = 0; + EquipmentMenu equipMenu; + PresetArmorPosesMenu presetPoseMenu; + SizeMenu sizeModificationMenu; + long lastCancelled = 0; + + public PlayerEditor(UUID uuid, ArmorStandEditorPlugin plugin) { + this.uuid = uuid; + this.plugin = plugin; + this.debug = new Debug(plugin); + eMode = EditMode.NONE; + adjMode = AdjustmentMode.COARSE; + axis = Axis.X; + copySlots = new CopySlots(); + eulerAngleChange = getManager().coarseAdj; + degreeAngleChange = eulerAngleChange / Math.PI * 180; + movChange = getManager().coarseMov; + chestMenu = new Menu(this); + } + + public void setMode(EditMode editMode) { + this.eMode = editMode; + debug.log("EditMode is: " + editMode.toString().toLowerCase()); + sendMessage("setmode", editMode.toString().toLowerCase()); + } + + public void setAxis(Axis axis) { + this.axis = axis; + debug.log("Axis is: " + axis.toString().toLowerCase()); + sendMessage("setaxis", axis.toString().toLowerCase()); + } + + public void setAdjMode(AdjustmentMode adjMode) { + this.adjMode = adjMode; + if (adjMode == AdjustmentMode.COARSE) { + eulerAngleChange = getManager().coarseAdj; + movChange = getManager().coarseMov; + } else { + eulerAngleChange = getManager().fineAdj; + movChange = getManager().fineMov; + } + degreeAngleChange = eulerAngleChange / Math.PI * 180; + debug.log("AdjMode is: " +adjMode.toString().toLowerCase()); + sendMessage("setadj", adjMode.toString().toLowerCase()); + } + + public void setCopySlot(byte slot) { + copySlots.changeSlots(slot); + debug.log("Copy Slot set to: "+ (slot + 1)); + sendMessage("setslot", String.valueOf((slot + 1))); + } + + public void editArmorStand(ArmorStand armorStand) { + if (getPlayer().hasPermission("asedit.basic")) { + + armorStand = attemptTarget(armorStand); + switch (eMode) { + case LEFTARM: + armorStand.setLeftArmPose(subEulerAngle(armorStand.getLeftArmPose())); + break; + case RIGHTARM: + armorStand.setRightArmPose(subEulerAngle(armorStand.getRightArmPose())); + break; + case BODY: + armorStand.setBodyPose(subEulerAngle(armorStand.getBodyPose())); + break; + case HEAD: + armorStand.setHeadPose(subEulerAngle(armorStand.getHeadPose())); + break; + case LEFTLEG: + armorStand.setLeftLegPose(subEulerAngle(armorStand.getLeftLegPose())); + break; + case RIGHTLEG: + armorStand.setRightLegPose(subEulerAngle(armorStand.getRightLegPose())); + break; + case SHOWARMS: + toggleArms(armorStand); + break; + case SIZE: + chooseSize(armorStand); + break; + case INVISIBLE: + toggleVisible(armorStand); + break; + case BASEPLATE: + togglePlate(armorStand); + break; + case GRAVITY: + toggleGravity(armorStand); + break; + case COPY: + copy(armorStand); + break; + case PASTE: + paste(armorStand); + break; + case PLACEMENT: + move(armorStand); + break; + case ROTATE: + rotate(armorStand); + break; + case DISABLESLOTS: + toggleDisableSlots(armorStand); + break; + case VULNERABILITY: + toggleInvulnerability(armorStand); + break; + case EQUIPMENT: + openEquipment(armorStand); + break; + case RESET: + resetPosition(armorStand); + break; + case GLOWING: + toggleGlowing(armorStand); + break; + case PRESET: + choosePreset(armorStand); + break; + case NONE: + default: + sendMessage("nomode", null); + break; + + } + } else return; + } + + public void editItemFrame(ItemFrame itemFrame) { + if (getPlayer().hasPermission("asedit.toggleitemframevisibility") || plugin.invisibleItemFrames) { + + //Generate a new ArmorStandManipulationEvent and call it out. + ItemFrameManipulatedEvent event = new ItemFrameManipulatedEvent(itemFrame, getPlayer()); + Bukkit.getPluginManager().callEvent(event); // Bukkit handles the call out + if (event.isCancelled()) return; //do nothing if cancelled + + switch (eMode) { + case ITEMFRAME: + toggleItemFrameVisible(itemFrame); + break; + case RESET: + itemFrame.setVisible(true); + break; + case NONE: + default: + sendMessage("nomodeif", null); + break; + } + } else return; + } + + private void openEquipment(ArmorStand armorStand) { + if (!getPlayer().hasPermission("asedit.equipment")) return; + + // Dont allow Editing the ArmorStand if the Stand is on the AS-InUse Team + // Means No 2 Players can edit the Equipment at the same time + if(!plugin.hasFolia){ + team = plugin.scoreboard.getTeam(plugin.inUseTeam); + armorStandInUseId = armorStand.getUniqueId(); + + debug.log("Is ArmorStand currently in use by another player?: " + team.hasEntry(armorStandInUseId.toString())); + + if(team != null && !team.hasEntry(armorStandInUseId.toString())){ + debug.log("ArmorStand Not on a Team and Player '" + getPlayer().getDisplayName() + "' has triggered to Open the Equipment Menu, Adding to In Use Team"); + team.addEntry(armorStandInUseId.toString()); + getPlayer().closeInventory(); + equipMenu = new EquipmentMenu(this, armorStand); + equipMenu.openMenu(); + } else { + sendMessage("asinuse", "warn"); + } + } else { + debug.log("ArmorStand Not on a Team and Player '" + getPlayer().getDisplayName() + "' has triggered to Open the Equipment Menu. Folia."); + getPlayer().closeInventory(); + equipMenu = new EquipmentMenu(this, armorStand); + equipMenu.openMenu(); + } + } + + private void choosePreset(ArmorStand armorStand) { + if (!getPlayer().hasPermission("asedit.basic")) return; + debug.log("Player '" + getPlayer().getDisplayName() + "' has triggered the Preset Poses Menu"); + getPlayer().closeInventory(); + presetPoseMenu = new PresetArmorPosesMenu(this, armorStand); + presetPoseMenu.openMenu(); + } + + //Size Menu Refactor + private void chooseSize(ArmorStand armorStand){ + if(!getPlayer().hasPermission("asedit.togglesize")){ + sendMessage("nopermoption", "warn", "size"); + return; + } else { + if (plugin.getNmsVersion().compareTo("1.21.4") >= 0 || plugin.getNmsVersion().compareTo("v1_21_R3") >= 0) { + //NOTE: New Sizing Menu ONLY WORKS IN 1.21.3 and HIGHER + debug.log("Player '" + getPlayer().getDisplayName() + "' has triggered the AS Attribute Size Menu"); + getPlayer().closeInventory(); + sizeModificationMenu = new SizeMenu(this, armorStand); + sizeModificationMenu.openMenu(); + } else { + armorStand.setSmall(!armorStand.isSmall()); + } + + } + } + + public void reverseEditArmorStand(ArmorStand armorStand) { + if (!getPlayer().hasPermission("asedit.basic")) return; + + //Generate a new ArmorStandManipulationEvent and call it out. + ArmorStandManipulatedEvent event = new ArmorStandManipulatedEvent(armorStand, getPlayer()); + Bukkit.getPluginManager().callEvent(event); // Bukkit handles the call out //TODO: Folia Refactor + if (event.isCancelled()) return; //do nothing if cancelled + + armorStand = attemptTarget(armorStand); + switch (eMode) { + case LEFTARM: + armorStand.setLeftArmPose(addEulerAngle(armorStand.getLeftArmPose())); + break; + case RIGHTARM: + armorStand.setRightArmPose(addEulerAngle(armorStand.getRightArmPose())); + break; + case BODY: + armorStand.setBodyPose(addEulerAngle(armorStand.getBodyPose())); + break; + case HEAD: + armorStand.setHeadPose(addEulerAngle(armorStand.getHeadPose())); + break; + case LEFTLEG: + armorStand.setLeftLegPose(addEulerAngle(armorStand.getLeftLegPose())); + break; + case RIGHTLEG: + armorStand.setRightLegPose(addEulerAngle(armorStand.getRightLegPose())); + break; + case PLACEMENT: + reverseMove(armorStand); + break; + case ROTATE: + reverseRotate(armorStand); + break; + default: + editArmorStand(armorStand); + } + } + + private void move(ArmorStand armorStand) { + if (!getPlayer().hasPermission("asedit.movement")) return; + + //Generate a new ArmorStandManipulationEvent and call it out. + ArmorStandManipulatedEvent event = new ArmorStandManipulatedEvent(armorStand, getPlayer()); + Bukkit.getPluginManager().callEvent(event); // Bukkit handles the call out //TODO: Folia Refactor + if (event.isCancelled()) return; //do nothing if cancelled + + Location loc = armorStand.getLocation(); + switch (axis) { + case X: + loc.add(movChange, 0, 0); + break; + case Y: + loc.add(0, movChange, 0); + break; + case Z: + loc.add(0, 0, movChange); + break; + } + debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY()+ ", " + loc.getZ() + ", near player " + getPlayer().getDisplayName()); + Scheduler.teleport(armorStand, loc); + } + + private void reverseMove(ArmorStand armorStand) { + if (!getPlayer().hasPermission("asedit.movement")) return; + Location loc = armorStand.getLocation(); + switch (axis) { + case X: + loc.subtract(movChange, 0, 0); + break; + case Y: + loc.subtract(0, movChange, 0); + break; + case Z: + loc.subtract(0, 0, movChange); + break; + } + debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY()+ ", " + loc.getZ() + ", near player " + getPlayer().getDisplayName()); + Scheduler.teleport(armorStand, loc); + } + + private void rotate(ArmorStand armorStand) { + if (!getPlayer().hasPermission("asedit.rotation")) return; + Location loc = armorStand.getLocation(); + float yaw = loc.getYaw(); + loc.setYaw((yaw + 180 + (float) degreeAngleChange) % 360 - 180); + debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY()+ ", " + loc.getZ() + ", near player " + getPlayer().getDisplayName()); + Scheduler.teleport(armorStand, loc); + } + + private void reverseRotate(ArmorStand armorStand) { + if (!getPlayer().hasPermission("asedit.rotation")) return; + Location loc = armorStand.getLocation(); + float yaw = loc.getYaw(); + loc.setYaw((yaw + 180 - (float) degreeAngleChange) % 360 - 180); + debug.log("Armorstand will be teleported to: " + loc.getX() + ", " + loc.getY()+ ", " + loc.getZ() + ", near player " + getPlayer().getDisplayName()); + Scheduler.teleport(armorStand, loc); + } + + private void copy(ArmorStand armorStand) { + if (getPlayer().hasPermission("asedit.copy")) { + copySlots.copyDataToSlot(armorStand); + debug.log("ArmorStand Items, Stats and Attributes has been copied to " + (copySlots.currentSlot + 1) + ", near player " + getPlayer().getDisplayName()); + sendMessage("copied", "" + (copySlots.currentSlot + 1)); + setMode(EditMode.PASTE); + } else { + sendMessage("nopermoption", "warn", "copy"); + } + + } + + private void paste(ArmorStand armorStand) { + if (getPlayer().hasPermission("asedit.paste")) { + ArmorStandData data = copySlots.getDataToPaste(); + debug.log("Pasting ArmorStand Attributes and Settings from: " + (copySlots.currentSlot + 1) + ", near player " + getPlayer().getDisplayName()); + if (data == null) return; + armorStand.setHeadPose(data.headPos); + armorStand.setBodyPose(data.bodyPos); + armorStand.setLeftArmPose(data.leftArmPos); + armorStand.setRightArmPose(data.rightArmPos); + armorStand.setLeftLegPose(data.leftLegPos); + armorStand.setRightLegPose(data.rightLegPos); + + if (plugin.getNmsVersion().compareTo("1.21.4") >= 0 || plugin.getNmsVersion().compareTo("v1_21_R3") >= 0) { + armorStand.getAttribute(Attribute.SCALE).setBaseValue(data.attributeScale); + } else { + armorStand.setSmall(data.size); + } + + armorStand.setGravity(data.gravity); + armorStand.setBasePlate(data.basePlate); + armorStand.setArms(data.showArms); + armorStand.setVisible(data.visible); + + //Only Paste the Items on the stand if in Creative Mode + // - Do not run elsewhere for good fecking reason! + if (this.getPlayer().getGameMode() == GameMode.CREATIVE) { + armorStand.getEquipment().setHelmet(data.head); + armorStand.getEquipment().setChestplate(data.body); + armorStand.getEquipment().setLeggings(data.legs); + armorStand.getEquipment().setBoots(data.feetsies); + armorStand.getEquipment().setItemInMainHand(data.rightHand); + armorStand.getEquipment().setItemInOffHand(data.leftHand); + } + sendMessage("pasted", "" + (copySlots.currentSlot + 1)); + } else { + sendMessage("nopermoption", "warn", "paste"); + } + } + + private void resetPosition(ArmorStand armorStand) { + if (getPlayer().hasPermission("asedit.reset")) { + debug.log("Resetting ArmorStand near the Player " + getPlayer().getDisplayName()); + armorStand.setHeadPose(new EulerAngle(0, 0, 0)); + armorStand.setBodyPose(new EulerAngle(0, 0, 0)); + armorStand.setLeftArmPose(new EulerAngle(0, 0, 0)); + armorStand.setRightArmPose(new EulerAngle(0, 0, 0)); + armorStand.setLeftLegPose(new EulerAngle(0, 0, 0)); + armorStand.setRightLegPose(new EulerAngle(0, 0, 0)); + } else { + sendMessage("nopermoption", "warn", "reset"); + } + } + + private void toggleDisableSlots(ArmorStand armorStand) { + if (!getPlayer().hasPermission("asedit.disableSlots")) { + sendMessage("nopermoption", "warn", "disableslots"); + } else { + debug.log("Adding DisabledSlots on ArmorStand near the Player " + getPlayer().getDisplayName()); + if (armorStand.hasEquipmentLock(EquipmentSlot.HAND, ArmorStand.LockType.REMOVING_OR_CHANGING)) { //Adds a lock to every slot or removes it + team = Scheduler.isFolia() ? null : plugin.scoreboard.getTeam(plugin.lockedTeam); + armorStandID = armorStand.getUniqueId(); + + for (final EquipmentSlot slot : EquipmentSlot.values()) { // UNLOCKED + armorStand.removeEquipmentLock(slot, ArmorStand.LockType.REMOVING_OR_CHANGING); + armorStand.removeEquipmentLock(slot, ArmorStand.LockType.ADDING); + } + getPlayer().playSound(getPlayer().getLocation(), Sound.ENTITY_ITEM_BREAK, SoundCategory.PLAYERS, 1.0f, 1.0f); + + if (team != null) { + team.removeEntry(armorStandID.toString()); + armorStand.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 50, 1, false, false)); //300 Ticks = 15 seconds + } + + + } else { + debug.log("Removing DisabledSlots on ArmorStand near the Player " + getPlayer().getDisplayName()); + for (final EquipmentSlot slot : EquipmentSlot.values()) { //LOCKED + armorStand.addEquipmentLock(slot, ArmorStand.LockType.REMOVING_OR_CHANGING); + armorStand.addEquipmentLock(slot, ArmorStand.LockType.ADDING); + } + getPlayer().playSound(getPlayer().getLocation(), Sound.ITEM_ARMOR_EQUIP_IRON, SoundCategory.PLAYERS, 1.0f, 1.0f); + if (team != null) { + team.addEntry(armorStandID.toString()); + armorStand.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 50, 1, false, false)); //300 Ticks = 15 seconds + } + } + + sendMessage("disabledslots", null); + } + + } + + private void toggleInvulnerability(ArmorStand armorStand) { //See NewFeature-Request #256 for more info + if (getPlayer().hasPermission("asedit.toggleInvulnerability")) { + debug.log("Making an ArmorStand vulnerable/invulnerable (set armorStand.isInvulnerable() = '"+ !armorStand.isInvulnerable() +"') near player: " + getPlayer().getDisplayName()); + armorStand.setInvulnerable(!armorStand.isInvulnerable()); + sendMessage("toggleinvulnerability", String.valueOf(armorStand.isInvulnerable())); + } else { + sendMessage("nopermoption", "warn", "vulnerability"); + } + } + + + private void toggleGravity(ArmorStand armorStand) { + if (getPlayer().hasPermission("asedit.togglegravity")) { + debug.log("Toggling the Gravity of an ArmorStand near player: " + getPlayer().getDisplayName()); + armorStand.setGravity(!armorStand.hasGravity()); + sendMessage("setgravity", String.valueOf(armorStand.hasGravity()));//Fix for Wolfst0rm/ArmorStandEditor-Issues#6: Translation of On/Off Keys are broken + } else { + sendMessage("nopermoption", "warn", "gravity"); + } + } + + void togglePlate(ArmorStand armorStand) { + if (getPlayer().hasPermission("asedit.togglebaseplate")) { + debug.log("Toggling the Baseplate of an ArmorStand near player: " + getPlayer().getDisplayName()); + armorStand.setBasePlate(!armorStand.hasBasePlate()); + } else { + sendMessage("nopermoption", "warn", "baseplate"); + } + + } + + void toggleGlowing(ArmorStand armorStand) { + if (getPlayer().hasPermission("asedit.togglearmorstandglow")) { + debug.log("Toggling the Glowing Ability of an ArmorStand near player: " + getPlayer().getDisplayName()); + //Will only make it glow white - Not something we can do like with Locking. Do not request this! + //Otherwise, this simple function becomes a mess to maintain. As you would need a Team generated with each + //Color and I ain't going to impose that on servers. + armorStand.setGlowing(!armorStand.isGlowing()); + } else { + sendMessage("nopermoption", "warn", "armorstandglow"); + } + } + + void toggleArms(ArmorStand armorStand) { + if (getPlayer().hasPermission("asedit.togglearms")) { + debug.log("Toggling the Showing of Arms of an ArmorStand near player: " + getPlayer().getDisplayName()); + armorStand.setArms(!armorStand.hasArms()); + } else { + sendMessage("nopermoption", "warn", "showarms"); + } + } + + void toggleVisible(ArmorStand armorStand) { + if (getPlayer().hasPermission("asedit.togglearmorstandvisibility") || plugin.getArmorStandVisibility()) { + debug.log("Toggling the Visiblity of an ArmorStand near player: " + getPlayer().getDisplayName()); + armorStand.setVisible(!armorStand.isVisible()); + } else { //Throw No Permission Message + sendMessage("nopermoption", "warn", "armorstandvisibility"); + } + } + + void toggleItemFrameVisible(ItemFrame itemFrame) { + if (getPlayer().hasPermission("asedit.toggleitemframevisibility") || plugin.invisibleItemFrames) { //Option to use perms or Config + debug.log("Toggling the Visibility of an ItemFrame near player: " + getPlayer().getDisplayName()); + itemFrame.setVisible(!itemFrame.isVisible()); + } else { + sendMessage("nopermoption", "warn", "itemframevisibility"); + } + } + + + void cycleAxis(int i) { + int index = axis.ordinal(); + index += i; + index = index % Axis.values().length; + while (index < 0) { + index += Axis.values().length; + } + setAxis(Axis.values()[index]); + } + + private EulerAngle addEulerAngle(EulerAngle angle) { + switch (axis) { + case X: + angle = angle.setX(Util.addAngle(angle.getX(), eulerAngleChange)); + break; + case Y: + angle = angle.setY(Util.addAngle(angle.getY(), eulerAngleChange)); + break; + case Z: + angle = angle.setZ(Util.addAngle(angle.getZ(), eulerAngleChange)); + break; + default: + break; + } + return angle; + } + + private EulerAngle subEulerAngle(EulerAngle angle) { + switch (axis) { + case X: + angle = angle.setX(Util.subAngle(angle.getX(), eulerAngleChange)); + break; + case Y: + angle = angle.setY(Util.subAngle(angle.getY(), eulerAngleChange)); + break; + case Z: + angle = angle.setZ(Util.subAngle(angle.getZ(), eulerAngleChange)); + break; + default: + break; + } + return angle; + } + + + public void setTarget(ArrayList armorStands) { + if (armorStands == null || armorStands.isEmpty()) { + target = null; + targetList = null; + sendMessage("notarget", "armorstand"); + } else { + if (targetList == null) { + targetList = armorStands; + targetIndex = 0; + sendMessage("target", null); + } else { + boolean same = targetList.size() == armorStands.size(); + if (same) for (ArmorStand as : armorStands) { + same = targetList.contains(as); + if (!same) break; + } + + if (same) { + targetIndex = ++targetIndex % targetList.size(); + } else { + targetList = armorStands; + targetIndex = 0; + sendMessage("target", null); + } + } + + //API: ArmorStandTargetedEvent + ArmorStandTargetedEvent e = new ArmorStandTargetedEvent(targetList.get(targetIndex), getPlayer()); + Bukkit.getPluginManager().callEvent(e); //TODO: Folia Refactor + if (e.isCancelled()) return; + + target = targetList.get(targetIndex); + highlight(target); //NOTE: If Targeted and Locked, it displays the TEAM Color Glow: RED + // Otherwise, its unlocked and will display WHITE as its not in a team by default + + } + } + + + public void setFrameTarget(ArrayList itemFrames) { + if (itemFrames == null || itemFrames.isEmpty()) { + frameTarget = null; + frameTargetList = null; + sendMessage("notarget", "itemframe"); + } else { + + if (frameTargetList == null) { + frameTargetList = itemFrames; + frameTargetIndex = 0; + sendMessage("frametarget", null); + } else { + boolean same = frameTargetList.size() == itemFrames.size(); + if (same) for (final ItemFrame itemf : itemFrames) { + same = frameTargetList.contains(itemf); + if (!same) break; + } + + if (same) { + frameTargetIndex = ++frameTargetIndex % frameTargetList.size(); + } else { + frameTargetList = itemFrames; + frameTargetIndex = 0; + sendMessage("frametarget", null); + } + + //API: ItemFrameTargetedEvent + ItemFrameTargetedEvent e = new ItemFrameTargetedEvent(frameTargetList.get(frameTargetIndex), getPlayer()); + Bukkit.getPluginManager().callEvent(e); //TODO: Folia Refactor + if (e.isCancelled()) return; + + frameTarget = frameTargetList.get(frameTargetIndex); + } + } + } + + + ArmorStand attemptTarget(ArmorStand armorStand) { + if (target == null + || !target.isValid() + || target.getWorld() != getPlayer().getWorld() + || target.getLocation().distanceSquared(getPlayer().getLocation()) > 100) + return armorStand; + armorStand = target; + return armorStand; + } + + void sendMessage(String path, String format, String option) { + String message = plugin.getLang().getMessage(path, format, option); + if (plugin.sendToActionBar) { + if (ArmorStandEditorPlugin.instance().getHasPaper() || ArmorStandEditorPlugin.instance().getHasSpigot()) { //Paper and Spigot having the same Interaction for sendToActionBar + plugin.getServer().getPlayer(getUUID()).spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(message)); + } else { + String rawText = plugin.getLang().getRawMessage(path, format, option); + String command = "minecraft:title %s actionbar %s".formatted(plugin.getServer().getPlayer(getUUID()).getName(), rawText); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); + } + } else { + plugin.getServer().getPlayer(getUUID()).sendMessage(message); + } + } + + void sendMessage(String path, String option) { + sendMessage(path, "info", option); + } + + private void highlight(ArmorStand armorStand) { + armorStand.removePotionEffect(PotionEffectType.GLOWING); + armorStand.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 50, 1, false, false)); //300 Ticks = 15 seconds + } + + public PlayerEditorManager getManager() { + return plugin.editorManager; + } + + public Player getPlayer() { + return plugin.getServer().getPlayer(getUUID()); + } + + public UUID getUUID() { + return uuid; + } + + public void openMenu() { + if (!isMenuCancelled()) { + Scheduler.runTaskLater(plugin, new OpenMenuTask(), 1); + } + } + + public void cancelOpenMenu() { + lastCancelled = getManager().getTime(); + } + + boolean isMenuCancelled() { + return getManager().getTime() - lastCancelled < 2; + } + + private class OpenMenuTask implements Runnable { + + @Override + public void run() { + if (isMenuCancelled()) return; + + //API: PlayerOpenMenuEvent + PlayerOpenMenuEvent event = new PlayerOpenMenuEvent(getPlayer()); + Bukkit.getPluginManager().callEvent(event); //TODO: Folia Refactor + if (event.isCancelled()) return; + + chestMenu.openMenu(); + } + } +} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java b/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java index 27b2e4ca..708ad9d1 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/PlayerEditorManager.java @@ -1,6 +1,6 @@ /* * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016 RypoFalem + * Copyright (C) 2016-2023 RypoFalem * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -19,11 +19,18 @@ package io.github.rypofalem.armorstandeditor; +import com.google.common.collect.ImmutableList; + +import io.github.rypofalem.armorstandeditor.Debug; +import io.github.rypofalem.armorstandeditor.api.ArmorStandRenameEvent; +import io.github.rypofalem.armorstandeditor.api.ItemFrameGlowEvent; import io.github.rypofalem.armorstandeditor.menu.ASEHolder; +import io.github.rypofalem.armorstandeditor.protections.*; + import org.bukkit.*; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.*; import org.bukkit.event.*; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; @@ -33,6 +40,7 @@ import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.persistence.PersistentDataType; +import org.bukkit.scoreboard.Team; import org.bukkit.util.Vector; import java.util.ArrayList; @@ -41,269 +49,488 @@ import java.util.UUID; //Manages PlayerEditors and Player Events related to editing armorstands -public class PlayerEditorManager implements Listener{ - private ArmorStandEditorPlugin plugin; - private HashMap players; - private ASEHolder menuHolder = new ASEHolder(); //Inventory holder that owns the main ase menu inventories for the plugin - private ASEHolder equipmentHolder = new ASEHolder(); //Inventory holder that owns the equipment menu - double coarseAdj; - double fineAdj; - double coarseMov; - double fineMov; - private boolean ignoreNextInteract = false; - private TickCounter counter; - - - PlayerEditorManager(ArmorStandEditorPlugin plugin){ - this.plugin = plugin; - players = new HashMap<>(); - coarseAdj = Util.FULLCIRCLE / plugin.coarseRot; - fineAdj = Util.FULLCIRCLE / plugin.fineRot; - coarseMov = 1; - fineMov = .03125; // 1/32 - counter = new TickCounter(); - Bukkit.getServer().getScheduler().runTaskTimer(plugin, counter, 0, 1); - } - - @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled=false) - void onArmorStandDamage(EntityDamageByEntityEvent event){ - if(!(event.getDamager() instanceof Player))return; - Player player = (Player) event.getDamager(); - if(!plugin.isEditTool(player.getInventory().getItemInMainHand())) return; - if(!(event.getEntity() instanceof ArmorStand)){ - event.setCancelled(true); - getPlayerEditor(player.getUniqueId()).openMenu(); - return; - } - ArmorStand as = (ArmorStand)event.getEntity(); - getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); - event.setCancelled(true); - if(canEdit(player, as)) applyLeftTool(player, as); - } - - @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled=false) - void onArmorStandInteract(PlayerInteractAtEntityEvent event){ - if(ignoreNextInteract) return; - if(event.getHand() != EquipmentSlot.HAND) return; - Player player = event.getPlayer(); - if(!(event.getRightClicked() instanceof ArmorStand)) return; - final ArmorStand as = (ArmorStand)event.getRightClicked(); - - if(!canEdit(player, as)) return; - if(plugin.isEditTool(player.getInventory().getItemInMainHand())){ - getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); - event.setCancelled(true); - applyRightTool(player, as); - return; - } - - //Attempt rename - if(player.getInventory().getItemInMainHand().getType() == Material.NAME_TAG && player.hasPermission("asedit.rename")){ - ItemStack nameTag = player.getInventory().getItemInMainHand(); - final String name; - if(nameTag.getItemMeta() != null && nameTag.getItemMeta().hasDisplayName()){ - name = nameTag.getItemMeta().getDisplayName().replace('&', ChatColor.COLOR_CHAR); - } else { - name = null; - } - - if(name == null){ - as.setCustomName(null); - as.setCustomNameVisible(false); - event.setCancelled(true); - } else if(!name.equals("")){ // nametag is not blank - event.setCancelled(true); - - if((player.getGameMode() != GameMode.CREATIVE)){ - if(nameTag.getAmount() > 1){ - nameTag.setAmount(nameTag.getAmount() - 1); - }else{ - nameTag = new ItemStack(Material.AIR); - } - player.getInventory().setItemInMainHand(nameTag); - } - - //minecraft will set the name after this event even if the event is cancelled. - //change it 1 tick later to apply formatting without it being overwritten - Bukkit.getScheduler().runTaskLater(plugin, () -> { - as.setCustomName(name); - as.setCustomNameVisible(true); - }, 1); - } - } - } - - @EventHandler (priority = EventPriority.LOW, ignoreCancelled=true) - public void onSwitchHands(PlayerSwapHandItemsEvent event){ - if(!plugin.isEditTool(event.getOffHandItem())) return; //event assumes they are already switched - event.setCancelled(true); - Player player = event.getPlayer(); - getPlayerEditor(event.getPlayer().getUniqueId()).setTarget(getTargets(player)); - } - - private ArrayList getTargets(Player player){ - Location eyeLaser = player.getEyeLocation(); - Vector direction = player.getLocation().getDirection(); - ArrayList armorStands = new ArrayList<>(); - - final double STEPSIZE = .5; - final Vector STEP = direction.multiply(STEPSIZE); - final double RANGE = 10; - final double LASERRADIUS = .3; - List nearbyEntities = player.getNearbyEntities(RANGE, RANGE, RANGE); - if(nearbyEntities.isEmpty()) return null; - - for(double i = 0; i nearby = (List) player.getWorld().getNearbyEntities(eyeLaser, LASERRADIUS, LASERRADIUS, LASERRADIUS); - if(!nearby.isEmpty()){ - boolean endLaser = false; - for(Entity e : nearby){ - if(e instanceof ArmorStand){ - if(canEdit(player, (ArmorStand)e)){ - armorStands.add((ArmorStand)e); - endLaser = true; - } - } - } - if(endLaser) break; - } - if(eyeLaser.getBlock().getType().isSolid()) break; - eyeLaser.add(STEP); - } - return armorStands; - } - - boolean canEdit(Player player, ArmorStand as){ - ignoreNextInteract = true; - ArrayList events = new ArrayList<>(); - events.add(new PlayerInteractEntityEvent(player, as, EquipmentSlot.HAND)); - events.add(new PlayerInteractAtEntityEvent(player, as, as.getLocation().toVector(), EquipmentSlot.HAND)); - //events.add(new PlayerArmorStandManipulateEvent(player, as, player.getEquipment().getItemInMainHand(), as.getItemInHand(), EquipmentSlot.HAND)); - for(Event event : events){ - if(!(event instanceof Cancellable)) continue; - try{ - plugin.getServer().getPluginManager().callEvent(event); - } catch(IllegalStateException ise){ - ise.printStackTrace(); - ignoreNextInteract = false; - return false; //Something went wrong, don't allow edit just in case - } - if(((Cancellable)event).isCancelled()){ - ignoreNextInteract = false; - return false; - } - } - ignoreNextInteract = false; - return true; - } - - void applyLeftTool(Player player, ArmorStand as){ - getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); - getPlayerEditor(player.getUniqueId()).editArmorStand(as); - } - - void applyRightTool(Player player, ArmorStand as){ - getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); - getPlayerEditor(player.getUniqueId()).reverseEditArmorStand(as); - } - - @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled=false) - void onRightClickTool(PlayerInteractEvent e){ - if( !(e.getAction() == Action.LEFT_CLICK_AIR - || e.getAction() == Action.RIGHT_CLICK_AIR - || e.getAction() == Action.LEFT_CLICK_BLOCK - || e.getAction() == Action.RIGHT_CLICK_BLOCK)) return; - Player player = e.getPlayer(); - if(!plugin.isEditTool(player.getInventory().getItemInMainHand())) return; - e.setCancelled(true); - getPlayerEditor(player.getUniqueId()).openMenu(); - } - - @EventHandler (priority = EventPriority.NORMAL, ignoreCancelled=true) - void onScrollNCrouch(PlayerItemHeldEvent e){ - Player player = e.getPlayer(); - if(!player.isSneaking()) return; - if(!plugin.isEditTool(player.getInventory().getItem(e.getPreviousSlot()))) return; - - e.setCancelled(true); - if(e.getNewSlot() == e.getPreviousSlot() +1 || (e.getNewSlot() == 0 && e.getPreviousSlot() == 8)){ - getPlayerEditor(player.getUniqueId()).cycleAxis(1); - }else if(e.getNewSlot() == e.getPreviousSlot() - 1 || (e.getNewSlot() == 8 && e.getPreviousSlot() == 0)){ - getPlayerEditor(player.getUniqueId()).cycleAxis(-1); - } - } - - @EventHandler (priority = EventPriority.LOWEST, ignoreCancelled=false) - void onPlayerMenuSelect(InventoryClickEvent e){ - if(e.getInventory().getHolder() == null) return; - if(!(e.getInventory().getHolder() instanceof ASEHolder)) return; - if(e.getInventory().getHolder() == menuHolder){ - e.setCancelled(true); - ItemStack item = e.getCurrentItem(); - if(item!= null && item.hasItemMeta()){ - Player player = (Player) e.getWhoClicked(); - String command = item.getItemMeta().getPersistentDataContainer().get(plugin.getIconKey(), PersistentDataType.STRING); - if(command != null){ - player.performCommand(command); - return; - } - } - } - if(e.getInventory().getHolder() == equipmentHolder){ - ItemStack item = e.getCurrentItem(); - if(item == null) return; - if(item.getItemMeta() == null ) return; - if(item.getItemMeta().getPersistentDataContainer().has(plugin.getIconKey(), PersistentDataType.STRING)){ - e.setCancelled(true); - } - } - } - - @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled=true) - void onPlayerMenuClose(InventoryCloseEvent e){ - if(e.getInventory().getHolder() == null) return; - if(!(e.getInventory().getHolder() instanceof ASEHolder)) return; - if(e.getInventory().getHolder() == equipmentHolder){ - PlayerEditor pe = players.get(e.getPlayer().getUniqueId()); - pe.equipMenu.equipArmorstand(); - } - } - - @EventHandler (priority = EventPriority.MONITOR) - void onPlayerLogOut(PlayerQuitEvent e){ - removePlayerEditor(e.getPlayer().getUniqueId()); - } - - public PlayerEditor getPlayerEditor(UUID uuid){ - return players.containsKey(uuid) ? players.get(uuid) : addPlayerEditor(uuid); - } - - PlayerEditor addPlayerEditor(UUID uuid){ - PlayerEditor pe = new PlayerEditor(uuid, plugin); - players.put(uuid, pe); - return pe; - } - - private void removePlayerEditor(UUID uuid){ - players.remove(uuid); - } - - public ASEHolder getMenuHolder() { - return menuHolder; - } - - public ASEHolder getEquipmentHolder() { - return equipmentHolder; - } - - long getTime(){ - return counter.ticks; - } - - class TickCounter implements Runnable{ - long ticks = 0; //I am optimistic - @Override - public void run() {ticks++;} - public long getTime() {return ticks;} - } -} \ No newline at end of file +public class PlayerEditorManager implements Listener { + private Debug debug; + private ArmorStandEditorPlugin plugin; + private HashMap players; + private ASEHolder menuHolder = new ASEHolder(); //Inventory holder that owns the main ase menu inventories for the plugin + private ASEHolder equipmentHolder = new ASEHolder(); //Inventory holder that owns the equipment menu + private ASEHolder presetHolder = new ASEHolder(); //Inventory Holder that owns the PresetArmorStand Post Menu + private ASEHolder sizeMenuHolder = new ASEHolder(); //Inventory Holder that owns the PresetArmorStand Post Menu + double coarseAdj; + double fineAdj; + double coarseMov; + double fineMov; + private boolean ignoreNextInteract = false; + private TickCounter counter; + private ArrayList as = null; + private ArrayList itemF = null; + private Integer noSize = 0; + Team team; + + // Instantiate protections used to determine whether a player may edit an armor stand or item frame + //NOTE: GriefPreventionProtection is Depreciated as of v1.19.3-40 + private final List protections = ImmutableList.of( + new GriefDefenderProtection(), + new GriefPreventionProtection(), + new LandsProtection(), + new PlotSquaredProtection(), + new SkyblockProtection(), + new TownyProtection(), + new WorldGuardProtection(), + new itemAdderProtection(), + new BentoBoxProtection()); + + PlayerEditorManager(ArmorStandEditorPlugin plugin) { + this.plugin = plugin; + this.debug = new Debug(plugin); + players = new HashMap<>(); + coarseAdj = Util.FULL_CIRCLE / plugin.coarseRot; + fineAdj = Util.FULL_CIRCLE / plugin.fineRot; + coarseMov = 1; + fineMov = .03125; // 1/32 + counter = new TickCounter(); + Scheduler.runTaskTimer(plugin, counter, 1, 1); + } + + @EventHandler(priority = EventPriority.LOWEST) + void onArmorStandDamage(EntityDamageByEntityEvent event) { + if (!(event.getDamager() instanceof Player)) return; + Player player = (Player) event.getDamager(); + if (!plugin.isEditTool(player.getInventory().getItemInMainHand())) return; + if (!((event.getEntity() instanceof ArmorStand) || event.getEntity() instanceof ItemFrame)) { + event.setCancelled(true); + debug.log("Open Menu Called for Player: " + player.getDisplayName()); + getPlayerEditor(player.getUniqueId()).openMenu(); + return; + } + if (event.getEntity() instanceof ArmorStand) { + debug.log("Player '" + player.getDisplayName() + "' has left clicked the ArmorStand"); + ArmorStand as = (ArmorStand) event.getEntity(); + getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); + event.setCancelled(true); + if (canEdit(player, as)) + applyLeftTool(player, as); + } else if (event.getEntity() instanceof ItemFrame) { + debug.log(" Player '" + player.getDisplayName() + "' has rght clicked on an ItemFrame"); + ItemFrame itemf = (ItemFrame) event.getEntity(); + getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); + event.setCancelled(true); + if (canEdit(player, itemf)) applyLeftTool(player, itemf); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + void onArmorStandInteract(PlayerInteractAtEntityEvent event) { + if (ignoreNextInteract) return; + if (event.getHand() != EquipmentSlot.HAND) return; + Player player = event.getPlayer(); + if (!((event.getRightClicked() instanceof ArmorStand) || event.getRightClicked() instanceof ItemFrame)) return; + + if (event.getRightClicked() instanceof ArmorStand) { + debug.log("Player '" + player.getDisplayName() + "' has right clicked on an ArmorStand"); + ArmorStand as = (ArmorStand) event.getRightClicked(); + + if (!canEdit(player, as)) return; + if (plugin.isEditTool(player.getInventory().getItemInMainHand())) { + getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); + event.setCancelled(true); + applyRightTool(player, as); + return; + } + + + //Attempt rename + if (player.getInventory().getItemInMainHand().getType() == Material.NAME_TAG && player.hasPermission("asedit.rename")) { + ItemStack nameTag = player.getInventory().getItemInMainHand(); + String name; + String name2; + if (nameTag.getItemMeta() != null && nameTag.getItemMeta().hasDisplayName()) { + name = nameTag.getItemMeta().getDisplayName().replace('&', ChatColor.COLOR_CHAR); + } else { + name = null; + } + + //API: ArmorStandRenameEvent + ArmorStandRenameEvent e = new ArmorStandRenameEvent(as, player, name); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled()) return; + + if (name == null) { + as.setCustomName(null); + as.setCustomNameVisible(false); + event.setCancelled(true); + } else if (name.startsWith("" + ChatColor.COLOR_CHAR + "") && !player.hasPermission("asedit.rename.color")) { + event.setCancelled(true); + player.sendMessage(plugin.getLang().getMessage("renamestopped")); + } else if (!name.equals("")) { // nametag is not blank + event.setCancelled(true); + + if ((player.getGameMode() != GameMode.CREATIVE)) { + if (nameTag.getAmount() > 1) { + nameTag.setAmount(nameTag.getAmount() - 1); + } else { + nameTag = new ItemStack(Material.AIR); + } + player.getInventory().setItemInMainHand(nameTag); + } + + //minecraft will set the name after this event even if the event is cancelled. + //change it 1 tick later to apply formatting without it being overwritten + Scheduler.runTaskLater(plugin, () -> { + as.setCustomName(name); + as.setCustomNameVisible(true); + }, 1); + } + } + } else if (event.getRightClicked() instanceof ItemFrame) { + ItemFrame itemFrame = (ItemFrame) event.getRightClicked(); + + if (!canEdit(player, itemFrame)) return; + if (plugin.isEditTool(player.getInventory().getItemInMainHand())) { + getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); + if (!itemFrame.getItem().getType().equals(Material.AIR)) { + event.setCancelled(true); + } + applyRightTool(player, itemFrame); + return; + } + + if (player.getInventory().getItemInMainHand().getType().equals(Material.GLOW_INK_SAC) //attempt glowing + && player.hasPermission("asedit.basic") + && plugin.glowItemFrames && player.isSneaking()) { + + ItemFrameGlowEvent e = new ItemFrameGlowEvent(itemFrame, player); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled()) return; + + ItemStack glowSacs = player.getInventory().getItemInMainHand(); + ItemStack contents = null; + Rotation rotation = null; + if (itemFrame.getItem().getType() != Material.AIR) { + contents = itemFrame.getItem(); //save item + rotation = itemFrame.getRotation(); // save item rotation + } + Location itemFrameLocation = itemFrame.getLocation(); + BlockFace facing = itemFrame.getFacing(); + + if (player.getGameMode() != GameMode.CREATIVE) { + if (glowSacs.getAmount() > 1) { + glowSacs.setAmount(glowSacs.getAmount() - 1); + } else glowSacs = new ItemStack(Material.AIR); + } + + itemFrame.remove(); + GlowItemFrame glowFrame = (GlowItemFrame) player.getWorld().spawnEntity(itemFrameLocation, EntityType.GLOW_ITEM_FRAME); + glowFrame.setFacingDirection(facing); + if (contents != null) { + glowFrame.setItem(contents); + glowFrame.setRotation(rotation); + } + + } + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + void onArmorStandBreak(EntityDamageByEntityEvent event) { // Fixes issue #309 + if (!(event.getDamager() instanceof Player)) return; // If the damager is not a player, ignore. + if (!(event.getEntity() instanceof ArmorStand)) return; // If the damaged entity is not an ArmorStand, ignore. + + if (event.getEntity() instanceof ArmorStand entityAS) { + // Check if the ArmorStand is invulnerable and if the damager is a player. + if (entityAS.isInvulnerable() && event.getDamager() instanceof Player p) { + // Check if the player is in Creative mode. + if (p.getGameMode() == GameMode.CREATIVE) { + // If the player is in Creative mode and the ArmorStand is invulnerable, + // cancel the event to prevent breaking the ArmorStand. + p.sendMessage(plugin.getLang().getMessage("unabledestroycreative")); + event.setCancelled(true); // Cancel the event to prevent ArmorStand destruction. + } + } + } + + if (event.getEntity() instanceof ArmorStand entityAS && entityAS.isDead()) { + //TODO: Find a more permanent fix for "Once you destroy that armor stand, the armor stand will keep it's name and colour given by the name tag." THIS IS A TEMP SOLUTION FOR NOW. + event.getEntity().setCustomName(null); + event.getEntity().setCustomNameVisible(false); + event.setCancelled(false); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onSwitchHands(PlayerSwapHandItemsEvent event) { + debug.log("PlayerSwapHandItemsEvent trigger for Player: " + event.getPlayer().getDisplayName()); + if (!plugin.isEditTool(event.getOffHandItem())) return; //event assumes they are already switched + event.setCancelled(true); + Player player = event.getPlayer(); + + as = getTargets(player); //Get All ArmorStand closest to player + itemF = getFrameTargets(player); //Get ItemFrame Closest to Player + + + // Check for null and empty lists + if (as != null && itemF != null && !as.isEmpty() && !itemF.isEmpty()) { + getPlayerEditor(player.getUniqueId()).sendMessage("doubletarget", "warn"); + } else if (as != null && !as.isEmpty()) { + getPlayerEditor(player.getUniqueId()).setTarget(as); + } else if (itemF != null && !itemF.isEmpty()) { + getPlayerEditor(player.getUniqueId()).setFrameTarget(itemF); + } else { + getPlayerEditor(player.getUniqueId()).sendMessage("nodoubletarget", "warn"); + } + } + + private ArrayList getTargets(Player player) { + Location eyeLaser = player.getEyeLocation(); + Vector direction = player.getLocation().getDirection(); + ArrayList armorStands = new ArrayList<>(); + + double STEPSIZE = .5; + Vector STEP = direction.multiply(STEPSIZE); + double RANGE = 10; + double LASERRADIUS = .3; + List nearbyEntities = player.getNearbyEntities(RANGE, RANGE, RANGE); + if (nearbyEntities.isEmpty()) return null; + + for (double i = 0; i < RANGE; i += STEPSIZE) { + List nearby = (List) player.getWorld().getNearbyEntities(eyeLaser, LASERRADIUS, LASERRADIUS, LASERRADIUS); + if (!nearby.isEmpty()) { + boolean endLaser = false; + for (Entity e : nearby) { + if (e instanceof ArmorStand stand) { + armorStands.add(stand); + endLaser = true; + } + } + + if (endLaser) break; + } + if (eyeLaser.getBlock().getType().isSolid()) break; + eyeLaser.add(STEP); + } + return armorStands; + } + + private ArrayList getFrameTargets(Player player) { + Location eyeLaser = player.getEyeLocation(); + Vector direction = player.getLocation().getDirection(); + ArrayList itemFrames = new ArrayList<>(); + + double STEPSIZE = .5; + Vector STEP = direction.multiply(STEPSIZE); + double RANGE = 10; + double LASERRADIUS = .3; + List nearbyEntities = player.getNearbyEntities(RANGE, RANGE, RANGE); + if (nearbyEntities.isEmpty()) return null; + + for (double i = 0; i < RANGE; i += STEPSIZE) { + List nearby = (List) player.getWorld().getNearbyEntities(eyeLaser, LASERRADIUS, LASERRADIUS, LASERRADIUS); + if (!nearby.isEmpty()) { + boolean endLaser = false; + for (Entity e : nearby) { + if (e instanceof ItemFrame frame) { + itemFrames.add(frame); + endLaser = true; + } + } + + if (endLaser) break; + } + if (eyeLaser.getBlock().getType().isSolid()) break; + eyeLaser.add(STEP); + } + + return itemFrames; + } + + + boolean canEdit(Player player, Entity entity) { + //Get the Entity being checked for editing + Block block = entity.getLocation().getBlock(); + + // Check if all protections allow this edit, if one fails, don't allow edit + return protections.stream().allMatch(protection -> protection.checkPermission(block, player)); + } + + void applyLeftTool(Player player, ArmorStand as) { + debug.log("Applying Left Tool on ArmorStand for Player: " + player.getDisplayName()); + getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); + getPlayerEditor(player.getUniqueId()).editArmorStand(as); + } + + void applyLeftTool(Player player, ItemFrame itemf) { + debug.log("Applying Left Tool on ItemFrame for Player: " + player.getDisplayName()); + getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); + getPlayerEditor(player.getUniqueId()).editItemFrame(itemf); + } + + void applyRightTool(Player player, ItemFrame itemf) { + debug.log("Applying Right Tool on ItemFrame for Player: " + player.getDisplayName()); + getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); + getPlayerEditor(player.getUniqueId()).editItemFrame(itemf); + } + + void applyRightTool(Player player, ArmorStand as) { + debug.log("Applying Right Tool on ArmorStand for Player: " + player.getDisplayName()); + getPlayerEditor(player.getUniqueId()).cancelOpenMenu(); + getPlayerEditor(player.getUniqueId()).reverseEditArmorStand(as); + } + + //Unused? + @EventHandler(priority = EventPriority.LOWEST) + void onRightClickTool(PlayerInteractEvent e) { + if (!(e.getAction() == Action.LEFT_CLICK_AIR + || e.getAction() == Action.RIGHT_CLICK_AIR + || e.getAction() == Action.LEFT_CLICK_BLOCK + || e.getAction() == Action.RIGHT_CLICK_BLOCK)) return; + debug.log("Ran on Right Click Tool Event."); + Player player = e.getPlayer(); + if (!plugin.isEditTool(player.getInventory().getItemInMainHand())) return; + if (plugin.requireSneaking && !player.isSneaking()) return; + if (!player.hasPermission("asedit.basic")) return; + if (plugin.enablePerWorld && (!plugin.allowedWorldList.contains(player.getWorld().getName()))) { + //Implementation for Per World ASE + getPlayerEditor(player.getUniqueId()).sendMessage("notincorrectworld", "warn"); + e.setCancelled(true); + return; + } + e.setCancelled(true); + debug.log("Open Menu Called for Player: " + player.getDisplayName()); + getPlayerEditor(player.getUniqueId()).openMenu(); + } + + @EventHandler(priority = EventPriority.NORMAL) + void onScrollNCrouch(PlayerItemHeldEvent e) { + Player player = e.getPlayer(); + if (!player.isSneaking()) return; + if (!plugin.isEditTool(player.getInventory().getItem(e.getPreviousSlot()))) return; + + e.setCancelled(true); + if (e.getNewSlot() == e.getPreviousSlot() + 1 || (e.getNewSlot() == 0 && e.getPreviousSlot() == 8)) { + getPlayerEditor(player.getUniqueId()).cycleAxis(1); + } else if (e.getNewSlot() == e.getPreviousSlot() - 1 || (e.getNewSlot() == 8 && e.getPreviousSlot() == 0)) { + getPlayerEditor(player.getUniqueId()).cycleAxis(-1); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + void onPlayerMenuSelect(InventoryClickEvent e) { + if (e.getInventory().getHolder() == null) return; + if (!(e.getInventory().getHolder() instanceof ASEHolder)) return; + if (e.getInventory().getHolder() == menuHolder) { + e.setCancelled(true); + ItemStack item = e.getCurrentItem(); + if (item != null && item.hasItemMeta()) { + Player player = (Player) e.getWhoClicked(); + String command = item.getItemMeta().getPersistentDataContainer().get(plugin.getIconKey(), PersistentDataType.STRING); + if (command != null) { + player.performCommand(command); + return; + } + } + } + if (e.getInventory().getHolder() == equipmentHolder) { + ItemStack item = e.getCurrentItem(); + if (item == null) return; + if (item.getItemMeta() == null) return; + if (item.getItemMeta().getPersistentDataContainer().has(plugin.getIconKey(), PersistentDataType.STRING)) { + e.setCancelled(true); + } + } + + if (e.getInventory().getHolder() == presetHolder) { + e.setCancelled(true); + ItemStack item = e.getCurrentItem(); + if (item != null && item.hasItemMeta()) { + Player player = (Player) e.getWhoClicked(); + String itemName = item.getItemMeta().getDisplayName(); + PlayerEditor pe = players.get(player.getUniqueId()); + pe.presetPoseMenu.handlePresetPose(itemName, player); + } + } + + if (e.getInventory().getHolder() == sizeMenuHolder) { + e.setCancelled(true); + ItemStack item = e.getCurrentItem(); + if (item != null && item.hasItemMeta()) { + Player player = (Player) e.getWhoClicked(); + String itemName = item.getItemMeta().getDisplayName(); + PlayerEditor pe = players.get(player.getUniqueId()); + pe.sizeModificationMenu.handleAttributeScaling(itemName, player); + } + } + } + + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + void onPlayerMenuClose(InventoryCloseEvent e) { + if (e.getInventory().getHolder() == null) return; + if (!(e.getInventory().getHolder() instanceof ASEHolder)) return; + if (e.getInventory().getHolder() == equipmentHolder) { + PlayerEditor pe = players.get(e.getPlayer().getUniqueId()); + pe.equipMenu.equipArmorstand(); + + // Remove the In Use Lock + if(!Scheduler.isFolia()){ + team = plugin.scoreboard.getTeam(plugin.inUseTeam); + if (team != null) { + team.removeEntry(pe.armorStandInUseId.toString()); + } + } + } + } + + @EventHandler(priority = EventPriority.MONITOR) + void onPlayerLogOut(PlayerQuitEvent e) { + removePlayerEditor(e.getPlayer().getUniqueId()); + } + + public PlayerEditor getPlayerEditor(UUID uuid) { + return players.containsKey(uuid) ? players.get(uuid) : addPlayerEditor(uuid); + } + + PlayerEditor addPlayerEditor(UUID uuid) { + PlayerEditor pe = new PlayerEditor(uuid, plugin); + players.put(uuid, pe); + return pe; + } + + private void removePlayerEditor(UUID uuid) { + players.remove(uuid); + } + + public ASEHolder getMenuHolder() { + return menuHolder; + } + + public ASEHolder getEquipmentHolder() { + return equipmentHolder; + } + + public ASEHolder getSizeMenuHolder() { + return sizeMenuHolder; + } + + public ASEHolder getPresetHolder() { + return presetHolder; + } + + long getTime() { + return counter.ticks; + } + + + class TickCounter implements Runnable { + long ticks = 0; //I am optimistic + + @Override + public void run() { + ticks++; + } + + public long getTime() { + return ticks; + } + } +} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/Scheduler.java b/src/main/java/io/github/rypofalem/armorstandeditor/Scheduler.java new file mode 100644 index 00000000..b2014351 --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/Scheduler.java @@ -0,0 +1,108 @@ +/* + * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.github.rypofalem.armorstandeditor; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.plugin.Plugin; + +import java.util.function.Consumer; + +public class Scheduler { + + private static Boolean IS_FOLIA = null; + private static Object GLOBAL_REGION_SCHEDULER = null; + + public static T callMethod(Class clazz, Object object, String methodName, Class[] parameterTypes, Object... args) { + try { + return (T) clazz.getDeclaredMethod(methodName, parameterTypes).invoke(object, args); + } catch (Throwable t) { + throw new IllegalStateException(t); + } + } + + public static T callMethod(Object object, String methodName, Class[] parameterTypes, Object... args) { + return callMethod(object.getClass(), object, methodName, parameterTypes, args); + } + + public static T callMethod(Class clazz, String methodName) { + return callMethod(clazz, null, methodName, new Class[]{}); + } + + private static boolean methodExist(Class clazz, String methodName, Class... parameterTypes) { + try { + clazz.getDeclaredMethod(methodName, parameterTypes); + return true; + } catch (Throwable ignored) { + } + return false; + } + + public static Boolean isFolia() { + try { + Class.forName("io.papermc.paper.threadedregions.ThreadedRegionizer"); + } + catch (Exception e) { + return false; + } + return true; + } + + public static Object getGlobalRegionScheduler() { + if (GLOBAL_REGION_SCHEDULER == null) { + GLOBAL_REGION_SCHEDULER = callMethod(Bukkit.class, "getGlobalRegionScheduler"); + } + return GLOBAL_REGION_SCHEDULER; + } + + public static void runTask(Plugin plugin, Runnable runnable) { + if (isFolia()) { + Object globalRegionScheduler = getGlobalRegionScheduler(); + callMethod(globalRegionScheduler, "run", new Class[]{Plugin.class, Consumer.class}, plugin, (Consumer) (task) -> runnable.run()); + return; + } + Bukkit.getScheduler().runTask(plugin, runnable); + } + + public static void runTaskTimer(Plugin plugin, Runnable runnable, long initialDelayTicks, long periodTicks) { + if (isFolia()) { + Object globalRegionScheduler = getGlobalRegionScheduler(); + callMethod(globalRegionScheduler, "runAtFixedRate", new Class[]{Plugin.class, Consumer.class, long.class, long.class}, + plugin, (Consumer) (task) -> runnable.run(), initialDelayTicks, periodTicks); + return; + } + Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, runnable, initialDelayTicks, periodTicks); + } + + public static void runTaskLater(Plugin plugin, Runnable runnable, long delayedTicks) { + if (isFolia()) { + Object globalRegionScheduler = getGlobalRegionScheduler(); + callMethod(globalRegionScheduler, "runDelayed", new Class[]{Plugin.class, Consumer.class, long.class}, + plugin, (Consumer) (task) -> runnable.run(), delayedTicks); + return; + } + Bukkit.getScheduler().runTaskLater(plugin, runnable, delayedTicks); + } + + public static void teleport(Entity entity, Location location) { + if (isFolia()) callMethod(Entity.class, entity, "teleportAsync", new Class[]{Location.class}, location); + else entity.teleport(location); + } +} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/Util.java b/src/main/java/io/github/rypofalem/armorstandeditor/Util.java index 9fb944d7..3c77e847 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/Util.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/Util.java @@ -1,6 +1,6 @@ /* * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016 RypoFalem + * Copyright (C) 2016-2023 RypoFalem * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -20,51 +20,50 @@ package io.github.rypofalem.armorstandeditor; public abstract class Util { - - public static final double FULLCIRCLE = Math.PI*2; - - public static > String getEnumList(Class enumType){ - return getEnumList(enumType, " | "); - } - public static > String getEnumList(Class enumType, String delimiter){ - StringBuilder list = new StringBuilder(); - boolean put =false; - for(Enum e : enumType.getEnumConstants()){ - list.append(e.toString()).append(delimiter); - put = true; - } - if(put) list = new StringBuilder(list.substring(0, list.length() - delimiter.length())); - return list.toString(); - } - - public static double addAngle(double current, double angleChange) { - current += angleChange; - current = fixAngle(current, angleChange); - return current; - } + public static final double FULL_CIRCLE = Math.PI * 2; - public static double subAngle(double current, double angleChange){ - current -= angleChange; - current = fixAngle(current, angleChange); - return current; - } + public static > String getEnumList(Class enumType) { + return getEnumList(enumType, " | "); + } - //clamps angle to 0 if it exceeds 2PI rad (360 degrees), is closer to 0 than angleChange value, or is closer to 2PI rad than 2PI rad - angleChange value. - private static double fixAngle(double angle, double angleChange){ - if(angle > FULLCIRCLE){ - return 0; - } - if(angle > 0 && angle < angleChange){ - if(angle < angleChange/2){ - return 0; - } - } - if(angle > FULLCIRCLE-angle){ - if(angle > FULLCIRCLE - (angleChange/2)){ - return 0; - } - } - return angle; - } + public static > String getEnumList(Class enumType, String delimiter) { + StringBuilder list = new StringBuilder(); + boolean put = false; + for (Enum e : enumType.getEnumConstants()) { + list.append(e.toString()).append(delimiter); + put = true; + } + if (put) list = new StringBuilder(list.substring(0, list.length() - delimiter.length())); + return list.toString(); + } + + public static double addAngle(double current, double angleChange) { + current += angleChange; + current = fixAngle(current, angleChange); + return current; + } + + public static double subAngle(double current, double angleChange) { + current -= angleChange; + current = fixAngle(current, angleChange); + return current; + } + + //clamps angle to 0 if it exceeds 2PI rad (360 degrees), is closer to 0 than angleChange value, or is closer to 2PI rad than 2PI rad - angleChange value. + private static double fixAngle(double angle, double angleChange) { + if (angle > FULL_CIRCLE) { + return 0; + } + + if (angle > 0 && angle < angleChange && angle < angleChange / 2) { + return 0; + } + + if (angle > FULL_CIRCLE - angle && angle > FULL_CIRCLE - (angleChange / 2)) { + return 0; + } + + return angle; + } } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandEvent.java b/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandEvent.java new file mode 100644 index 00000000..e82445c1 --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandEvent.java @@ -0,0 +1,36 @@ +/* + * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package io.github.rypofalem.armorstandeditor.api; + +import lombok.Getter; + +import org.bukkit.entity.ArmorStand; +import org.bukkit.event.Event; + +public abstract class ArmorStandEvent extends Event { + + @Getter + protected final ArmorStand armorStand; + + public ArmorStandEvent(ArmorStand armorStand) { + this.armorStand = armorStand; + } + +} \ No newline at end of file diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandManipulatedEvent.java b/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandManipulatedEvent.java new file mode 100644 index 00000000..9df80d7a --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandManipulatedEvent.java @@ -0,0 +1,54 @@ +/* + * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.github.rypofalem.armorstandeditor.api; + +import lombok.Getter; +import lombok.Setter; + +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class ArmorStandManipulatedEvent extends ArmorStandEvent implements Cancellable { + + @Getter + @Setter + private boolean cancelled = false; + + @Getter + protected final Player player; + + public ArmorStandManipulatedEvent(ArmorStand armorStand, Player player) { + super(armorStand); + this.player = player; + } + + /* Generated for Bukkit */ + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlerList() { + return (handlers); + } + + @Override + public HandlerList getHandlers() { + return (handlers); + } +} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandRenameEvent.java b/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandRenameEvent.java new file mode 100644 index 00000000..5b243872 --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandRenameEvent.java @@ -0,0 +1,59 @@ +/* + * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.github.rypofalem.armorstandeditor.api; + +import lombok.Getter; +import lombok.Setter; + +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class ArmorStandRenameEvent extends ArmorStandEvent implements Cancellable { + + @Getter + @Setter + private boolean cancelled = false; + @Getter + @Setter + protected String name; + + @Getter + protected final Player player; + + public ArmorStandRenameEvent(ArmorStand armorStand, Player player, String name) { + super(armorStand); + this.player = player; + this.name = name; + } + + /* Generated for Bukkit */ + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlerList() { + return (handlers); + } + + @Override + public HandlerList getHandlers() { + return (handlers); + } + +} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandTargetedEvent.java b/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandTargetedEvent.java new file mode 100644 index 00000000..196a039e --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/api/ArmorStandTargetedEvent.java @@ -0,0 +1,54 @@ +/* + * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package io.github.rypofalem.armorstandeditor.api; + +import lombok.Getter; +import lombok.Setter; + +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class ArmorStandTargetedEvent extends ArmorStandEvent implements Cancellable { + @Getter + @Setter + private boolean cancelled = false; + + @Getter + protected final Player player; + + public ArmorStandTargetedEvent(ArmorStand armorStand, Player player) { + super(armorStand); + this.player = player; + } + + /* Generated for Bukkit */ + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlerList() { + return (handlers); + } + + @Override + public HandlerList getHandlers() { + return (handlers); + } +} \ No newline at end of file diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameEvent.java b/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameEvent.java new file mode 100644 index 00000000..d6358613 --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameEvent.java @@ -0,0 +1,36 @@ +/* + * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package io.github.rypofalem.armorstandeditor.api; + +import lombok.Getter; + +import org.bukkit.entity.ItemFrame; +import org.bukkit.event.Event; + +public abstract class ItemFrameEvent extends Event { + + @Getter + protected final ItemFrame itemFrame; + + public ItemFrameEvent(ItemFrame itemFrame) { + this.itemFrame = itemFrame; + } + +} \ No newline at end of file diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameGlowEvent.java b/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameGlowEvent.java new file mode 100644 index 00000000..7f5cdc97 --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameGlowEvent.java @@ -0,0 +1,35 @@ +package io.github.rypofalem.armorstandeditor.api; + +import lombok.Getter; +import lombok.Setter; + +import org.bukkit.entity.ItemFrame; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class ItemFrameGlowEvent extends ItemFrameEvent implements Cancellable { + @Getter + @Setter + private boolean cancelled = false; + + @Getter + protected final Player player; + + public ItemFrameGlowEvent(ItemFrame itemFrame, Player player) { + super(itemFrame); + this.player = player; + } + + /* Generated for Bukkit */ + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlerList() { + return (handlers); + } + + @Override + public HandlerList getHandlers() { + return (handlers); + } +} \ No newline at end of file diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameManipulatedEvent.java b/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameManipulatedEvent.java new file mode 100644 index 00000000..9c80c077 --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameManipulatedEvent.java @@ -0,0 +1,55 @@ +/* + * ItemFrameEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.github.rypofalem.armorstandeditor.api; + +import lombok.Getter; +import lombok.Setter; + +import org.bukkit.entity.ItemFrame; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class ItemFrameManipulatedEvent extends ItemFrameEvent implements Cancellable { + + @Getter + @Setter + private boolean cancelled = false; + + @Getter + protected final Player player; + + public ItemFrameManipulatedEvent(ItemFrame itemFrame, Player player) { + super(itemFrame); + this.player = player; + } + + /* Generated for Bukkit */ + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlerList() { + return (handlers); + } + + @Override + public HandlerList getHandlers() { + return (handlers); + } +} + diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameTargetedEvent.java b/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameTargetedEvent.java new file mode 100644 index 00000000..1c9c162c --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/api/ItemFrameTargetedEvent.java @@ -0,0 +1,54 @@ +/* + * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package io.github.rypofalem.armorstandeditor.api; + +import lombok.Getter; +import lombok.Setter; + +import org.bukkit.entity.ItemFrame; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class ItemFrameTargetedEvent extends ItemFrameEvent implements Cancellable { + @Getter + @Setter + private boolean cancelled = false; + + @Getter + protected final Player player; + + public ItemFrameTargetedEvent(ItemFrame itemFrame, Player player) { + super(itemFrame); + this.player = player; + } + + /* Generated for Bukkit */ + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlerList() { + return (handlers); + } + + @Override + public HandlerList getHandlers() { + return (handlers); + } +} diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/api/PlayerOpenMenuEvent.java b/src/main/java/io/github/rypofalem/armorstandeditor/api/PlayerOpenMenuEvent.java new file mode 100644 index 00000000..908b6693 --- /dev/null +++ b/src/main/java/io/github/rypofalem/armorstandeditor/api/PlayerOpenMenuEvent.java @@ -0,0 +1,52 @@ +/* + * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes + * Copyright (C) 2016-2023 RypoFalem + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.github.rypofalem.armorstandeditor.api; + +import lombok.Getter; +import lombok.Setter; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class PlayerOpenMenuEvent extends Event implements Cancellable { + @Getter + @Setter + private boolean cancelled = false; + + @Getter + protected final Player player; + + public PlayerOpenMenuEvent(Player player) { + this.player = player; + } + + /* Generated for Bukkit */ + private static final HandlerList handlers = new HandlerList(); + + public static HandlerList getHandlerList() { + return (handlers); + } + + @Override + public HandlerList getHandlers() { + return (handlers); + } +} \ No newline at end of file diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/language/Language.java b/src/main/java/io/github/rypofalem/armorstandeditor/language/Language.java index 7a35c548..16b6e783 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/language/Language.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/language/Language.java @@ -1,6 +1,6 @@ /* * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016 RypoFalem + * Copyright (C) 2016-2023 RypoFalem * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -17,18 +17,19 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + package io.github.rypofalem.armorstandeditor.language; import io.github.rypofalem.armorstandeditor.ArmorStandEditorPlugin; + import org.bukkit.ChatColor; import org.bukkit.configuration.file.YamlConfiguration; import java.io.*; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class Language { - final String DEFAULTLANG = "en_US.yml"; + final String DEFAULT_LANG = "en_US.yml"; private YamlConfiguration langConfig = null; private YamlConfiguration defConfig = null; private File langFile = null; @@ -40,11 +41,11 @@ public Language(String langFileName, ArmorStandEditorPlugin plugin) { } public void reloadLang(String langFileName) { - if (langFileName == null) langFileName = DEFAULTLANG; + if (langFileName == null) langFileName = DEFAULT_LANG; File langFolder = new File(plugin.getDataFolder().getPath() + File.separator + "lang"); langFile = new File(langFolder, langFileName); - InputStream input = plugin.getResource("lang" + "/" + DEFAULTLANG); //getResource doesn't accept File.seperator on windows, need to hardcode unix seperator "/" instead + InputStream input = plugin.getResource("lang" + "/" + DEFAULT_LANG); //getResource doesn't accept File.seperator on windows, need to hardcode unix seperator "/" instead assert input != null; Reader defaultLangStream = new InputStreamReader(input, StandardCharsets.UTF_8); defConfig = YamlConfiguration.loadConfiguration(defaultLangStream); @@ -88,14 +89,14 @@ public String getMessage(String path) { return getMessage(path, "info"); } - public String getRawMessage(String path, String format, String option){ + public String getRawMessage(String path, String format, String option) { String message = ChatColor.stripColor(getMessage(path, format, option)); format = getFormat(format); ChatColor color = ChatColor.WHITE; String bold = "" , italic = "" , underlined = "" , obfuscated = "" , strikethrough = ""; - for(int i = 0; i < format.length(); i++){ + for (int i = 0; i < format.length(); i++) { ChatColor code = ChatColor.getByChar(format.charAt(i)); - switch(code) { + switch (code) { case MAGIC: obfuscated = ", \"obfuscated\": true"; break; @@ -114,11 +115,11 @@ public String getRawMessage(String path, String format, String option){ default: color = !code.isColor() ? color : code; } } - return String.format("{\"text\":\"%s\", \"color\":\"%s\"%s%s%s%s%s}", message, color.name().toLowerCase(), + return "{\"text\":\"%s\", \"color\":\"%s\"%s%s%s%s%s}".formatted(message, color.name().toLowerCase(), obfuscated, bold, strikethrough, underlined, italic); } - private String getFormat(String format){ + private String getFormat(String format) { format = getString(format); return format == null ? "" : format; } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/menu/ASEHolder.java b/src/main/java/io/github/rypofalem/armorstandeditor/menu/ASEHolder.java index 2f8dedb8..c5d341cd 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/menu/ASEHolder.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/menu/ASEHolder.java @@ -1,6 +1,6 @@ /* * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016 RypoFalem + * Copyright (C) 2016-2023 RypoFalem * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -25,9 +25,9 @@ public class ASEHolder implements InventoryHolder { - @Override - public Inventory getInventory() { - return null; - } + @Override + public Inventory getInventory() { + return null; + } } diff --git a/src/main/java/io/github/rypofalem/armorstandeditor/menu/EquipmentMenu.java b/src/main/java/io/github/rypofalem/armorstandeditor/menu/EquipmentMenu.java index 8e17626d..baa7232d 100644 --- a/src/main/java/io/github/rypofalem/armorstandeditor/menu/EquipmentMenu.java +++ b/src/main/java/io/github/rypofalem/armorstandeditor/menu/EquipmentMenu.java @@ -1,6 +1,6 @@ /* * ArmorStandEditor: Bukkit plugin to allow editing armor stand attributes - * Copyright (C) 2016 RypoFalem + * Copyright (C) 2016-2023 RypoFalem * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -19,7 +19,9 @@ package io.github.rypofalem.armorstandeditor.menu; +import io.github.rypofalem.armorstandeditor.Debug; import io.github.rypofalem.armorstandeditor.PlayerEditor; + import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.ArmorStand; @@ -33,85 +35,100 @@ import java.util.ArrayList; public class EquipmentMenu { - Inventory menuInv; - private PlayerEditor pe; - private ArmorStand armorstand; - static String name = "ArmorStand Equipment"; - ItemStack helmet, chest, pants, feetsies, rightHand, leftHand; - - public EquipmentMenu(PlayerEditor pe, ArmorStand as){ - this.pe = pe; - this.armorstand = as; - name = pe.plugin.getLang().getMessage("equiptitle", "menutitle"); - menuInv = Bukkit.createInventory(pe.getManager().getEquipmentHolder(), 18, name); - } - - private void fillInventory(){ - menuInv.clear(); - EntityEquipment equipment = armorstand.getEquipment(); - assert equipment != null; - ItemStack helmet = equipment.getHelmet(); - ItemStack chest = equipment.getChestplate(); - ItemStack pants = equipment.getLeggings(); - ItemStack feetsies = equipment.getBoots(); - ItemStack rightHand = equipment.getItemInMainHand(); - ItemStack leftHand = equipment.getItemInOffHand(); - equipment.clear(); - - ItemStack disabledIcon = new ItemStack(Material.BARRIER); - ItemMeta meta = disabledIcon.getItemMeta(); - meta.setDisplayName(pe.plugin.getLang().getMessage("disabled", "warn")); //equipslot.msg