Compare commits

..
Author SHA1 Message Date
Adrian3d04 17a2ff73b2 feat: Initial extension support 2022-08-18 15:32:06 +00:00
90 changed files with 1113 additions and 2295 deletions

No files matched your search

+13 -2
View File
@@ -1,2 +1,13 @@
github: 4drian3d
custom: https://paypal.me/4drian3d
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: https://paypal.me/4drian3d # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+5 -5
View File
@@ -8,10 +8,10 @@ jobs:
steps:
- name: Checkout Repository
uses: actions/checkout@v3
uses: actions/checkout@v2
- name: Set up JDK 17
uses: actions/setup-java@v3
uses: actions/setup-java@v2
with:
java-version: 17
distribution: 'temurin'
@@ -20,12 +20,12 @@ jobs:
- name: Build with Gradle
uses: nick-invision/retry@v2
with:
timeout_minutes: 10
timeout_minutes: 4
max_attempts: 2
command: gradle build
- name: Upload Artifacts
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: MiniPlaceholders
path: jar/MiniPlaceholders-*.jar
path: build/libs/MiniPlaceholders.jar
-1
View File
@@ -2,7 +2,6 @@
/.idea/
build/
bin/
jar/
# Visual Studio Code
+7 -82
View File
@@ -1,88 +1,13 @@
# MiniPlaceholders
[![WorkFlow](https://img.shields.io/github/actions/workflow/status/MiniPlaceholders/MiniPlaceholders/build.yml?style=flat-square)](https://github.com/MiniPlaceholders/MiniPlaceholders/actions)
![Latest Version](https://img.shields.io/github/v/release/MiniPlaceholders/MiniPlaceholders?style=flat-square)
[![Discord](https://img.shields.io/discord/899740810956910683?color=7289da&logo=Discord&label=Discord&style=flat-square)](https://discord.gg/5NMMzK5mAn)
![Modrinth Downloads](https://img.shields.io/modrinth/dt/HQyibRsN?logo=Modrinth&style=flat-square)
![GitHub Downloads](https://img.shields.io/github/downloads/MiniPlaceholders/MiniPlaceholders/total?logo=GitHub&style=flat-square)
MiniMessage Component-based Placeholders for PaperMC, Folia, Fabric, Sponge, Krypton and Velocity platforms
## Compatibility
- Paper 1.19.3, 1.19.4+
- Folia 1.19.4
- Velocity 3.1.2+
- Fabric 1.19.4+
- Sponge API 8, 9, 10
- Krypton
## Commands
MiniMessage Component-based Placeholders for PaperMC and Velocity platforms
## Commands:
### Velocity
- `/vminiplaceholders parse me "[message with placeholders]"`
- `/vminiplaceholders parse player [some-player] "[message with placeholders]"`
### Paper | Folia | Fabric | Krypton
- `/miniplaceholders <parse|help> player [some-player] "[message with placeholders]`
- `/miniplaceholders parse player [some-player] "[message with placeholders]"`
#### Example:
- `/miniplaceholders parse me "<player_xp>"`
- `/vminiplaceholders parse player 4drian3d "<player_name>"`
## User Usage
Check our user usage wiki [here](https://github.com/MiniPlaceholders/MiniPlaceholders/wiki/User-Getting-Started)
`/vminiplaceholders <parse|help> <me|player> <player-to-parse>`
### Paper
`/miniplaceholders <parse|help> <me|player> <player-to-parse>`
## API
Check the available javadocs [here](https://javadoc.jitpack.io/com/github/4drian3d/MiniPlaceholders/latest/javadoc/index.html)
Check the available [Javadocs](https://javadoc.io/doc/io.github.miniplaceholders/miniplaceholders-api)
Or check the [Developer Wiki](https://github.com/MiniPlaceholders/MiniPlaceholders/wiki/Developer-Getting-Started)
### Java
```java
class Main {
public static void registerExpansion() {
final Expansion expansion = Expansion.builder("my-expansion")
.filter(Player.class)
.audiencePlaceholder("name", (audience, ctx, queue) -> {
final Player player = (player) audience;
return Tag.selfClosingInserting(player.getName());
})
.globalPlaceholder("tps", (ctx, queue) ->
Tag.selfClosingInserting(Component.text(Bukkit.getTps()[0]))
).build;
expansion.register();
Player player;
final TagResolver playerResolver = MiniPlaceholders.getAudiencePlaceholders(player);
player.sendMessage(miniMessage().deserialize("Player Name: <my-expansion_name>", playerResolver));
}
}
```
### Kotlin
```kotlin
fun register() {
val expansion = expansion("my-expansion") {
audiencePlaceholder("name") { aud, _, _ ->
aud.getName().asClosingTag()
}
globalPlaceholder("tps") { _, _ ->
Component.text(Bukkit.getTps()[0]).asInsertingTag()
}
}
expansion.register()
val player: Player
val playerResolver = MiniPlaceholders.getAudiencePlaceholders(player)
player.sendMessage(miniMessage().deserialize("Player Name: <my-expansion_name>", playerResolver))
}
```
Or check the wiki [here](https://github.com/4drian3d/MiniPlaceholders/wiki)
+45 -17
View File
@@ -1,19 +1,23 @@
plugins {
id("miniplaceholders.base")
alias(libs.plugins.jmh)
id("miniplaceholders.publish")
id("me.champeau.jmh") version "0.6.6"
`maven-publish`
}
repositories {
mavenCentral()
}
dependencies {
compileOnly(libs.adventure.api)
compileOnly(libs.adventure.minimesssage)
compileOnly(libs.adventure.serializer.legacy)
compileOnly(projects.miniplaceholdersConnect)
testImplementation(platform(libs.junit.bom))
compileOnly("net.kyori:adventure-api:4.11.0")
compileOnly("net.kyori:adventure-text-minimessage:4.11.0")
compileOnly("net.kyori:adventure-text-serializer-legacy:4.11.0")
compileOnly(project(":miniplaceholders-connect"))
implementation("com.google.code.gson:gson:2.9.1")
testImplementation(platform("org.junit:junit-bom:5.8.1"))
testImplementation("org.junit.jupiter:junit-jupiter")
testImplementation(libs.adventure.api)
testImplementation(libs.adventure.minimesssage)
testImplementation(libs.adventure.serializer.plain)
testImplementation("net.kyori:adventure-api:4.11.0")
testImplementation("net.kyori:adventure-text-minimessage:4.11.0")
testImplementation("net.kyori:adventure-text-serializer-plain:4.11.0")
}
tasks {
@@ -32,18 +36,42 @@ jmh {
}
java {
withSourcesJar()
withJavadocJar()
toolchain.languageVersion.set(JavaLanguageVersion.of(17))
}
val projectGroup: String = project.group as String
val projectVersion: String = project.version as String
publishing {
publications {
create<MavenPublication>("maven") {
groupId = projectGroup
artifactId = project.name
version = projectVersion
from(components["java"])
}
}
}
tasks.withType<Javadoc> {
(options as StandardJavadocDocletOptions).links(
"https://jd.adventure.kyori.net/api/4.10.0/",
"https://jd.adventure.kyori.net/text-minimessage/4.11.0/"
)
}
tasks {
processResources {
filteringCharset = Charsets.UTF_8.name()
compileJava {
options.encoding = Charsets.UTF_8.name()
options.release.set(11)
}
javadoc {
options.encoding = Charsets.UTF_8.name()
(options as StandardJavadocDocletOptions).links(
"https://jd.advntr.dev/api/${libs.versions.adventure.get()}/",
"https://jd.advntr.dev/text-minimessage/${libs.versions.adventure.get()}/"
)
}
processResources {
filteringCharset = Charsets.UTF_8.name()
}
}
@@ -1,4 +1,4 @@
package io.github.miniplaceholders.jmh;
package me.dreamerzero.miniplaceholders;
import java.util.UUID;
@@ -1,4 +1,4 @@
package io.github.miniplaceholders.jmh;
package me.dreamerzero.miniplaceholders;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
@@ -9,8 +9,8 @@ import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import io.github.miniplaceholders.api.Expansion;
import io.github.miniplaceholders.api.MiniPlaceholders;
import me.dreamerzero.miniplaceholders.api.Expansion;
import me.dreamerzero.miniplaceholders.api.MiniPlaceholders;
@State(Scope.Benchmark)
public class PlaceholderBenchmark {
@@ -1,225 +0,0 @@
package io.github.miniplaceholders.api;
import io.github.miniplaceholders.api.placeholder.AudiencePlaceholder;
import io.github.miniplaceholders.api.placeholder.RelationalPlaceholder;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.text.minimessage.Context;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.ArgumentQueue;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import static io.github.miniplaceholders.api.utils.Conditions.nonNullOrEmptyString;
import static java.util.Objects.requireNonNull;
final class ExpansionImpl implements Expansion {
private static final Tags.Single[] EMPTY_SINGLE_AUDIENCE = new Tags.Single[0];
private static final Tags.Relational[] EMPTY_RELATIONAL_AUDIENCE = new Tags.Relational[0];
private final String name;
private final Tags.Single[] audiencePlaceholders;
private final Tags.Relational[] relationalPlaceholders;
private final TagResolver globalPlaceholders;
private final Class<? extends Audience> filterClass;
private final Predicate<Audience> predicateFilter;
ExpansionImpl(
@NotNull final String expansionName,
@Nullable final Collection<Tags.Single> audiencePlaceholders,
@Nullable final Collection<Tags.Relational> relationalPlaceholders,
@Nullable final TagResolver globalPlaceholders,
@Nullable final Class<? extends Audience> filterClass,
@Nullable final Predicate<Audience> predicateFilter){
this.name = expansionName+"-";
this.audiencePlaceholders = audiencePlaceholders != null
? audiencePlaceholders.toArray(EMPTY_SINGLE_AUDIENCE)
: EMPTY_SINGLE_AUDIENCE;
this.relationalPlaceholders = relationalPlaceholders != null
? relationalPlaceholders.toArray(EMPTY_RELATIONAL_AUDIENCE)
: EMPTY_RELATIONAL_AUDIENCE;
this.globalPlaceholders = globalPlaceholders;
this.filterClass = filterClass;
this.predicateFilter = predicateFilter;
}
@Override
public @NotNull String name(){
return this.name;
}
@Override
public @NotNull TagResolver audiencePlaceholders(@NotNull Audience audience) {
if (audiencePlaceholders.length == 0) return TagResolver.empty();
requireNonNull(audience, "the audience cannot be null");
if ((audience = expansionFilter(audience)) == null) return TagResolver.empty();
final TagResolver.Builder placeholders = TagResolver.builder();
for (final Tags.Single pl : this.audiencePlaceholders) {
placeholders.resolver(pl.of(audience));
}
return placeholders.build();
}
@SuppressWarnings("OverrideOnly")
private Audience expansionFilter(final Audience audience) {
if (audience == null || filterClass == null && predicateFilter == null) {
return audience;
}
final boolean eligible = filterClass != null && filterClass.isInstance(audience)
|| predicateFilter != null && predicateFilter.test(audience);
if (eligible) {
return audience;
}
if (audience instanceof final ForwardingAudience.Single forward) {
return expansionFilter(forward.audience());
}
return null;
}
@Override
public @NotNull TagResolver relationalPlaceholders(@NotNull Audience audience, @NotNull Audience otherAudience){
if (relationalPlaceholders.length == 0) return TagResolver.empty();
requireNonNull(audience, "the audience cannot be null");
requireNonNull(otherAudience, "the other audience cannot be null");
audience = expansionFilter(audience);
otherAudience = expansionFilter(otherAudience);
if (audience == null || otherAudience == null) {
return TagResolver.empty();
}
final TagResolver.Builder placeholders = TagResolver.builder();
for (final Tags.Relational pl : this.relationalPlaceholders) {
placeholders.resolver(pl.of(audience, otherAudience));
}
return placeholders.build();
}
@Override
public @NotNull TagResolver globalPlaceholders(){
return this.globalPlaceholders;
}
@Override
public void register() {
if (this.registered()) {
throw new IllegalStateException("Expansion" + this.name + "is already registered");
}
MiniPlaceholders.expansions.add(this);
}
@Override
public void unregister() {
if (!this.registered()) {
throw new IllegalStateException("Expansion " + this.name + " is not registered");
}
MiniPlaceholders.expansions.remove(this);
}
@Override
public boolean registered() {
return MiniPlaceholders.expansions.contains(this);
}
static final class Builder implements Expansion.Builder {
private final String expansionName;
private Set<Tags.Single> audiencePlaceholders;
private Set<Tags.Relational> relationalPlaceholders;
private TagResolver.Builder globalPlaceholders;
private Class<? extends Audience> filterClass;
private Predicate<Audience> predicateFilter;
Builder(@NotNull final String name){
this.expansionName = nonNullOrEmptyString(name, "Expansion name")
.toLowerCase(Locale.ROOT).concat("_");
}
@Override
public @NotNull Builder audiencePlaceholder(@NotNull final String key, @NotNull final AudiencePlaceholder audiencePlaceholder){
nonNullOrEmptyString(key, "Placeholder key");
requireNonNull(audiencePlaceholder, "the audience placeholder cannot be null");
if (this.audiencePlaceholders == null) this.audiencePlaceholders = new HashSet<>(5);
this.audiencePlaceholders.add(Tags.single(expansionName+key, audiencePlaceholder));
return this;
}
@Override
public @NotNull Builder relationalPlaceholder(@NotNull final String key, @NotNull final RelationalPlaceholder relationalPlaceholder){
nonNullOrEmptyString(key, "Placeholder key");
requireNonNull(relationalPlaceholder, "the relational placeholder cannot be null");
if (this.relationalPlaceholders == null) this.relationalPlaceholders = new HashSet<>(4);
this.relationalPlaceholders.add(Tags.relational(expansionName+"rel_"+key, relationalPlaceholder));
return this;
}
@Override
public @NotNull Builder globalPlaceholder(@NotNull final String key, @NotNull final BiFunction<ArgumentQueue, Context, Tag> function){
nonNullOrEmptyString(key, "Placeholder key");
requireNonNull(function, "the global placeholder cannot be null");
if(this.globalPlaceholders == null) this.globalPlaceholders = TagResolver.builder();
this.globalPlaceholders.tag(expansionName+key, function);
return this;
}
@Override
public @NotNull Builder globalPlaceholder(@NotNull final String key, @NotNull final Tag tag){
nonNullOrEmptyString(key, "Placeholder key");
requireNonNull(tag, "the tag cannot be null");
if(this.globalPlaceholders == null) this.globalPlaceholders = TagResolver.builder();
this.globalPlaceholders.tag(expansionName+key, tag);
return this;
}
@Override
public @NotNull Builder filter(@Nullable final Class<? extends Audience> clazz) {
this.filterClass = clazz;
return this;
}
@Override
public @NotNull Builder filter(@Nullable final Predicate<Audience> predicate){
this.predicateFilter = predicate;
return this;
}
@Override
public @NotNull Expansion build(){
return new ExpansionImpl(
this.expansionName,
this.audiencePlaceholders,
this.relationalPlaceholders,
this.globalPlaceholders != null ? this.globalPlaceholders.build() : TagResolver.empty(),
this.filterClass,
this.predicateFilter
);
}
}
@Override
public boolean equals(Object o){
if (this==o) return true;
if (o == null || o.getClass() != ExpansionImpl.class) return false;
return ((ExpansionImpl)o).name.equals(this.name);
}
@Override
public int hashCode(){
return Objects.hash(name.hashCode());
}
}
@@ -1,15 +0,0 @@
package io.github.miniplaceholders.api.enums;
/**Platforms on which MiniPlaceholders can be used */
public enum Platform {
/**Paper Platform */
PAPER,
/**Velocity Platform */
VELOCITY,
/**Krypton Platform */
KRYPTON,
/**Fabric Platform */
FABRIC,
/**Sponge Platform */
SPONGE
}
@@ -1,2 +0,0 @@
/**Plugin enums */
package io.github.miniplaceholders.api.enums;
@@ -1,4 +0,0 @@
/**
* MiniPlaceholders core package
*/
package io.github.miniplaceholders.api;
@@ -1,74 +0,0 @@
package io.github.miniplaceholders.api.utils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.function.Supplier;
/** Checks required for the correct operation of the expansions*/
public final class Conditions {
private Conditions() {}
/**
* Checks if a string is null or empty or consists of whitespace characters only.
*
* @param string the string
* @param name the name supplier
* @return the string if it is not null or empty
* @since 1.0.0
* @throws IllegalStateException if the provided string is empty
*/
public static String nonNullOrEmptyString(@Nullable String string, @NotNull Supplier<@NotNull String> name){
if (string == null)
throw new NullPointerException(name.get() + " cannot be null");
if (string.isBlank())
throw new IllegalStateException(name.get() + "cannot be an empty string");
return string;
}
/**
* Checks if a string is null or empty or consists of whitespace characters only.
*
* @param string the string
* @param name the name
* @return the string if it is not null or empty
* @since 2.2.0
* @throws IllegalStateException if the provided string is empty
*/
public static String nonNullOrEmptyString(@Nullable String string, @NotNull String name){
if (string == null)
throw new NullPointerException(name + " cannot be null");
if (string.isBlank())
throw new IllegalStateException(name + "cannot be an empty string");
return string;
}
/**
* Check if a string is empty or consists of whitespace characters only.
*
* @param string the string
* @param reason the reason supplier
* @return the string if it not empty
* @since 1.0.0
* @throws IllegalStateException if the provided string is empty
*/
public static String nonEmptyString(@NotNull String string, @NotNull Supplier<@NotNull String> reason){
if (string.isBlank()) throw new IllegalStateException(reason.get());
return string;
}
/**
* Check if a string is empty or consists of whitespace characters only.
*
* @param string the string
* @param reason the reason
* @return the string if it not empty
* @since 2.2.0
* @throws IllegalStateException if the provided string is empty
*/
public static String nonEmptyString(@NotNull String string, @NotNull String reason){
if (string.isBlank()) throw new IllegalStateException(reason);
return string;
}
}
@@ -1,7 +1,5 @@
package io.github.miniplaceholders.api;
package me.dreamerzero.miniplaceholders.api;
import io.github.miniplaceholders.api.placeholder.AudiencePlaceholder;
import io.github.miniplaceholders.api.placeholder.RelationalPlaceholder;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -9,6 +7,8 @@ import org.jetbrains.annotations.Nullable;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import me.dreamerzero.miniplaceholders.api.placeholder.AudiencePlaceholder;
import me.dreamerzero.miniplaceholders.api.placeholder.RelationalPlaceholder;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.builder.AbstractBuilder;
import net.kyori.adventure.text.minimessage.Context;
@@ -49,6 +49,7 @@ public interface Expansion {
* @return A TagResolver with variable placeholders of an Audience
* @since 1.0.0
*/
@Contract("null -> fail; !null -> !null")
@NotNull TagResolver audiencePlaceholders(final @NotNull Audience audience);
/**
@@ -62,6 +63,7 @@ public interface Expansion {
* @return A TagResolver with variable placeholders between 2 {@link Audience}s
* @since 1.0.0
*/
@Contract("_, null -> fail, null, _ -> fail; !null, !null -> !null")
@NotNull TagResolver relationalPlaceholders(final @NotNull Audience audience, final @NotNull Audience otherAudience);
/**
@@ -74,33 +76,16 @@ public interface Expansion {
/**
* Register this expansion
* @since 1.0.0
* @throws IllegalStateException if the expansion you are trying to register is already registered
* @see Expansion#registered()
*/
void register();
/**
* Unregisters this expansion
* @since 2.1.0
* @throws IllegalStateException if the expansion you are trying to unregister is not registered
* @see Expansion#registered()
*/
void unregister();
/**
* Get the registration status of this expansion
* @return true if the expansion is registered, otherwise false
* @since 2.1.0
*/
boolean registered();
/**
* Creates a new Expansion Builder
* @param name the expansion name
* @return a new expansion builder
* @since 1.0.0
*/
static @NotNull Expansion.Builder builder(final @NotNull String name){
public static @NotNull Expansion.Builder builder(final @NotNull String name){
return new ExpansionImpl.Builder(name);
}
@@ -126,7 +111,7 @@ public interface Expansion {
*
* @since 1.0.0
*/
interface Builder extends AbstractBuilder<Expansion> {
public static interface Builder extends AbstractBuilder<Expansion> {
/**
* Adds an audience placeholder
*
@@ -134,16 +119,16 @@ public interface Expansion {
*
* <p>The content of this Placeholder is cached
* and can mutate depending on when it is invoked</p>
*
* @param key the placeholder key, cannot be an empty or black string
* @param audiencePlaceholder the single placeholder
* @return the {@link Builder} itself
* @since 1.0.0
*/
@Contract("null, _ -> fail; _, null -> fail; !null, !null -> this")
@NotNull Builder audiencePlaceholder(final @NotNull String key, final @NotNull AudiencePlaceholder audiencePlaceholder);
/**
* Adds a Relational Placeholder based on two audiences
* Adds an Relational Placeholder based on two audiences
*
* <p>This type of placeholder allows you to create
* components based on a 2-audiences relationship,
@@ -153,12 +138,12 @@ public interface Expansion {
*
* <p>The content of this Placeholder is cached
* and can mutate depending on when it is invoked</p>
*
* @param key the placeholder key, cannot be an empty or black string
* @param relationalPlaceholder the relational placeholder
* @return the {@link Builder} itself
* @since 1.0.0
*/
@Contract("null, _ -> fail; _, null -> fail; !null, !null -> this")
@NotNull Builder relationalPlaceholder(final @NotNull String key, final @NotNull RelationalPlaceholder relationalPlaceholder);
/**
@@ -171,17 +156,19 @@ public interface Expansion {
* @return the {@link Builder} itself
* @since 1.0.0
*/
@Contract("null, _ -> fail; _, null -> fail; !null, !null -> this")
@NotNull Builder globalPlaceholder(final @NotNull String key, final @NotNull BiFunction<@NotNull ArgumentQueue, @NotNull Context, @Nullable Tag> function);
/**
* Adds a global placeholder
*
* <p>This placeholder is not cached and is immutable</p>
* <p>This placeholder is not cached and is inmutable</p>
* @param key the placeholder key, cannot be an empty or black string
* @param tag the tag of this placeholder
* @return the {@link Builder} itself
* @since 1.1.0
*/
@Contract("null, _ -> fail; _, null -> fail; !null, !null -> this")
@NotNull Builder globalPlaceholder(final @NotNull String key, final @NotNull Tag tag);
/**
@@ -193,7 +180,6 @@ public interface Expansion {
*
* <p>This eliminates the need to perform a manual
* <pre>if(!(audience instanceof Player)) return TagResolver.empty();</pre>
*
* @param clazz the class to filter
* @return the {@link Builder} itself
* @since 1.0.0
@@ -205,17 +191,15 @@ public interface Expansion {
* Filters the audiences that this expansion can receive through a Predicate
* <p>Example:</p>
* <pre>
* Expansion.builder("example")
* .filter(aud -> aud instanceof Player player{@literal &&} isInProtectedServer(player)
* Expansion.builder("example").filter(Player.class).filter(aud -> isInProtectedServer((Player)aud))
* .audiencePlaceholder("hello", (aud, queue, ctx) -> Tag.selfInsertingClosing(Component.text("you are in protected server")))
* .build();
* </pre>
*
* @param predicate the check to realize
* @return the {@link Builder} itself
* @since 1.0.0
*/
@Contract("_ -> this")
@NotNull Builder filter(final @Nullable Predicate<@NotNull Audience> predicate);
@NotNull Builder filter(final @Nullable Predicate<Audience> predicate);
}
}
@@ -0,0 +1,202 @@
package me.dreamerzero.miniplaceholders.api;
import java.util.Collection;
import java.util.HashSet;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import me.dreamerzero.miniplaceholders.api.placeholder.AudiencePlaceholder;
import me.dreamerzero.miniplaceholders.api.placeholder.RelationalPlaceholder;
import me.dreamerzero.miniplaceholders.api.utils.Conditions;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.minimessage.Context;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.ArgumentQueue;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
final class ExpansionImpl implements Expansion {
private final String name;
private final Tags.Single[] audiencePlaceholders;
private final Tags.Relational[] relationalPlaceholders;
private final TagResolver globalPlaceholders;
private final Class<? extends Audience> filterClass;
private final Predicate<Audience> predicateFilter;
ExpansionImpl(
@NotNull final String expansionName,
@Nullable final Collection<Tags.Single> audiencePlaceholders,
@Nullable final Collection<Tags.Relational> relationalPlaceholders,
@Nullable final TagResolver globalPlaceholders,
@Nullable final Class<? extends Audience> filterClass,
@Nullable final Predicate<Audience> predicateFilter){
this.name = expansionName+"-";
this.audiencePlaceholders = audiencePlaceholders != null
? audiencePlaceholders.toArray(Tags.Single[]::new)
: new Tags.Single[0];
this.relationalPlaceholders = relationalPlaceholders != null
? relationalPlaceholders.toArray(Tags.Relational[]::new)
: new Tags.Relational[0];
this.globalPlaceholders = globalPlaceholders == null
? TagResolver.empty()
: globalPlaceholders;
this.filterClass = filterClass;
this.predicateFilter = predicateFilter;
}
@Override
public String name(){
return this.name;
}
@Override
public @NotNull TagResolver audiencePlaceholders(@NotNull final Audience audience){
if(audiencePlaceholders.length == 0) return TagResolver.empty();
Objects.requireNonNull(audience, () -> "the audience cannot be null");
if(this.singleFilter(audience)) return TagResolver.empty();
final TagResolver.Builder placeholders = TagResolver.builder();
for(final Tags.Single pl : this.audiencePlaceholders){
placeholders.resolver(pl.of(audience));
}
return placeholders.build();
}
private boolean singleFilter(final Audience audience){
return filterClass != null && !filterClass.isInstance(audience)
|| predicateFilter != null && predicateFilter.test(audience);
}
@Override
public @NotNull TagResolver relationalPlaceholders(@NotNull final Audience audience, @NotNull final Audience otherAudience){
if(relationalPlaceholders.length == 0) return TagResolver.empty();
Objects.requireNonNull(audience, () -> "the audience cannot be null");
Objects.requireNonNull(otherAudience, () -> "the other audience cannot be null");
if(this.relationalFilter(audience, otherAudience)) return TagResolver.empty();
final TagResolver.Builder placeholders = TagResolver.builder();
for(final Tags.Relational pl : this.relationalPlaceholders){
placeholders.resolver(pl.of(audience, otherAudience));
}
return placeholders.build();
}
private boolean relationalFilter(final Audience audience, final Audience otherAudience){
return filterClass != null && (!filterClass.isInstance(audience) || !filterClass.isInstance(otherAudience))
|| predicateFilter != null && (!predicateFilter.test(audience) || !predicateFilter.test(otherAudience));
}
@Override
public @NotNull TagResolver globalPlaceholders(){
return this.globalPlaceholders;
}
@Override
public void register(){
MiniPlaceholders.expansions.add(this);
}
static final class Builder implements Expansion.Builder {
private final String expansionName;
private Set<Tags.Single> audiencePlaceholders;
private Set<Tags.Relational> relationalPlaceholders;
private TagResolver.Builder globalPlaceholders;
private Class<? extends Audience> filterClass;
private Predicate<Audience> predicateFilter;
Builder(@NotNull final String name){
this.expansionName = Conditions.nonNullOrEmptyString(name, () -> "expansion name")
.toLowerCase(Locale.ROOT).concat("_");
}
@Override
public Builder audiencePlaceholder(@NotNull final String key, @NotNull final AudiencePlaceholder audiencePlaceholder){
Conditions.nonNullOrEmptyString(key, () -> "placeholder key");
Objects.requireNonNull(audiencePlaceholder, () -> "the audience placeholder cannot be null");
if(this.audiencePlaceholders == null) this.audiencePlaceholders = new HashSet<>(5);
this.audiencePlaceholders.add(Tags.single(expansionName+key, audiencePlaceholder));
return this;
}
@Override
public Builder relationalPlaceholder(@NotNull final String key, @NotNull final RelationalPlaceholder relationalPlaceholder){
Conditions.nonNullOrEmptyString(key, () -> "placeholder key");
Objects.requireNonNull(relationalPlaceholder, () -> "the relational placeholder cannot be null");
if(this.relationalPlaceholders == null) this.relationalPlaceholders = new HashSet<>(4);
this.relationalPlaceholders.add(Tags.relational(expansionName+"rel_"+key, relationalPlaceholder));
return this;
}
@Override
public Builder globalPlaceholder(@NotNull final String key, @NotNull final BiFunction<ArgumentQueue, Context, Tag> function){
Conditions.nonNullOrEmptyString(key, () -> "placeholder key");
Objects.requireNonNull(function, () -> "the global placeholder cannot be null");
if(this.globalPlaceholders == null) this.globalPlaceholders = TagResolver.builder();
this.globalPlaceholders.tag(expansionName+key, function);
return this;
}
@Override
public Builder globalPlaceholder(@NotNull final String key, @NotNull final Tag tag){
Conditions.nonNullOrEmptyString(key, () -> "placeholder key");
Objects.requireNonNull(tag, () -> "the tag cannot be null");
if(this.globalPlaceholders == null) this.globalPlaceholders = TagResolver.builder();
this.globalPlaceholders.tag(expansionName+key, tag);
return this;
}
@Override
public Builder filter(@Nullable final Class<? extends Audience> clazz) {
this.filterClass = clazz;
return this;
}
@Override
public Builder filter(@Nullable final Predicate<Audience> predicate){
this.predicateFilter = predicate;
return this;
}
@Override
public @NotNull Expansion build(){
return new ExpansionImpl(
this.expansionName,
this.audiencePlaceholders,
this.relationalPlaceholders,
this.globalPlaceholders != null ? this.globalPlaceholders.build() : null,
this.filterClass,
this.predicateFilter
);
}
}
@Override
public boolean equals(Object o){
if(this==o) return true;
if(o == null || o.getClass() != ExpansionImpl.class) return false;
return ((ExpansionImpl)o).name.equals(this.name);
}
@Override
public int hashCode(){
return Objects.hash(name.hashCode());
}
}
@@ -1,19 +1,18 @@
package io.github.miniplaceholders.api;
package me.dreamerzero.miniplaceholders.api;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import io.github.miniplaceholders.api.enums.Platform;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import io.github.miniplaceholders.connect.InternalPlatform;
import me.dreamerzero.miniplaceholders.api.enums.Platform;
import me.dreamerzero.miniplaceholders.api.utils.Resolvers;
import me.dreamerzero.miniplaceholders.connect.InternalPlatform;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.jetbrains.annotations.Nullable;
import static io.github.miniplaceholders.api.utils.Resolvers.applyIfNotEmpty;
import static java.util.Objects.requireNonNull;
/**
* MiniPlaceholders
@@ -28,8 +27,8 @@ import static java.util.Objects.requireNonNull;
* @since 1.0.0
*/
public final class MiniPlaceholders {
private MiniPlaceholders() {}
static final Set<Expansion> expansions = ConcurrentHashMap.newKeySet();
private MiniPlaceholders(){}
static final Set<Expansion> expansions = Collections.synchronizedSet(new HashSet<>());
/**
* Get the platform
@@ -37,13 +36,9 @@ public final class MiniPlaceholders {
* @since 1.0.0
*/
public static @NotNull Platform getPlatform() {
return switch (InternalPlatform.platform()) {
case PAPER -> Platform.PAPER;
case VELOCITY -> Platform.VELOCITY;
case KRYPTON -> Platform.KRYPTON;
case FABRIC -> Platform.FABRIC;
case SPONGE -> Platform.SPONGE;
};
return InternalPlatform.platform() == InternalPlatform.PAPER
? Platform.PAPER
: Platform.VELOCITY;
}
/**
@@ -52,7 +47,7 @@ public final class MiniPlaceholders {
* <pre>TagResolver resolver = MiniPlaceholders.getGlobalPlaceholders();
* Component messageParsed = MiniMessage.miniMessage().deserialize({@link String}, resolver);</pre>
*
* @return global placeholders independent of any audience
* @return global placeholders independient of any audience
* @see TagResolver
* @since 1.0.0
*/
@@ -76,19 +71,21 @@ public final class MiniPlaceholders {
* @return {@link TagResolver} with placeholders based on an audience
* @since 1.0.0
*/
@Contract("null -> fail, !null -> !null")
public static @NotNull TagResolver getAudiencePlaceholders(final @NotNull Audience audience) {
requireNonNull(audience, "audience cannot be null");
Objects.requireNonNull(audience, () -> "audience cannot be null");
final TagResolver.Builder resolvers = TagResolver.builder();
for (Expansion expansion : expansions) {
final TagResolver resolver = expansion.audiencePlaceholders(audience);
applyIfNotEmpty(resolver, resolvers);
if (resolver != TagResolver.empty())
resolvers.resolver(resolver);
}
return resolvers.build();
}
/**
* Get the relational placeholders based on two audiences
* Get the relationals placeholders based on two audiences
*
* <pre>TagResolver resolver = MiniPlaceholders.getRelationalPlaceholders({@link Audience}, {@link Audience});
* Component messageParsed = MiniMessage.miniMessage().deserialize({@link String}, resolver);</pre>
@@ -98,13 +95,14 @@ public final class MiniPlaceholders {
* @return placeholders based on two audiences
* @since 1.0.0
*/
@Contract("_, null -> fail; null, _ -> fail; !null, !null -> !null")
public static @NotNull TagResolver getRelationalPlaceholders(final @NotNull Audience audience, final @NotNull Audience otherAudience) {
requireNonNull(audience, "audience cannot be null");
requireNonNull(otherAudience, "otherAudience cannot be null");
Objects.requireNonNull(audience, () -> "audience cannot be null");
Objects.requireNonNull(otherAudience, () -> "otherAudience cannot be null");
final TagResolver.Builder builder = TagResolver.builder();
for (final Expansion expansion : expansions) {
applyIfNotEmpty(
Resolvers.applyIfNotEmpty(
expansion.relationalPlaceholders(audience, otherAudience),
builder
);
@@ -131,20 +129,21 @@ public final class MiniPlaceholders {
* @return {@link TagResolver} with placeholders based on an audience and the global placeholders
* @since 1.1.0
*/
@Contract("_, null -> fail; null, _ -> fail; !null, !null -> !null")
public static @NotNull TagResolver getAudienceGlobalPlaceholders(final @NotNull Audience audience) {
requireNonNull(audience, "audience cannot be null");
Objects.requireNonNull(audience, () -> "audience cannot be null");
final TagResolver.Builder builder = TagResolver.builder();
for (final Expansion expansion : expansions) {
applyIfNotEmpty(expansion.audiencePlaceholders(audience), builder);
applyIfNotEmpty(expansion.globalPlaceholders(), builder);
Resolvers.applyIfNotEmpty(expansion.audiencePlaceholders(audience), builder);
Resolvers.applyIfNotEmpty(expansion.globalPlaceholders(), builder);
}
return builder.build();
}
/**
* Get the relational placeholders based on two audiences, based on the first audience,
* Get the relationals placeholders based on two audiences, based on the first audience,
* and the global placeholders
*
* <pre>
@@ -164,23 +163,24 @@ public final class MiniPlaceholders {
* @return the placeholders based on two audiences, placeholders based on the first audience and the global placeholders
* @since 1.1.0
*/
@Contract("_, null -> fail; null, _ -> fail; !null, !null -> !null")
public static @NotNull TagResolver getRelationalGlobalPlaceholders(final @NotNull Audience audience, final @NotNull Audience otherAudience) {
requireNonNull(audience, "audience cannot be null");
requireNonNull(otherAudience, "otherAudience cannot be null");
Objects.requireNonNull(audience, () -> "audience cannot be null");
Objects.requireNonNull(otherAudience, () -> "otherAudience cannot be null");
final TagResolver.Builder builder = TagResolver.builder();
for (final Expansion expansion : expansions) {
applyIfNotEmpty(expansion.audiencePlaceholders(audience), builder);
applyIfNotEmpty(expansion.relationalPlaceholders(audience, otherAudience), builder);
applyIfNotEmpty(expansion.globalPlaceholders(), builder);
Resolvers.applyIfNotEmpty(expansion.audiencePlaceholders(audience), builder);
Resolvers.applyIfNotEmpty(expansion.relationalPlaceholders(audience, otherAudience), builder);
Resolvers.applyIfNotEmpty(expansion.globalPlaceholders(), builder);
}
return builder.build();
}
/**
* Get the amount of expansion registered
* @return the amount of expansions registered
* Get the ammount of expansion registered
* @return the ammount of expansions registered
* @since 1.0.0
*/
public static int getExpansionCount(){
@@ -188,25 +188,14 @@ public final class MiniPlaceholders {
}
/**
* Get a specific expansion by name
* <p>The name of each expansion is set when the expansion is created</p>
* <pre>
* Expansion expansion = Expansion.builder("example").build();
* expansion.register();
*
* assertThat(MiniPlaceholders.getExpansionByName("example")).isNotNull();
* </pre>
* @param name the name of the required expansion
* @return the required expansion, if not present, will return null
* @see Expansion#builder(String)
* @since 2.1.0
* Set the platform
* @param platform the platform
* @deprecated dont use this, INTERNAL
* @since 1.0.0
*/
public static @Nullable Expansion getExpansionByName(final @NotNull String name) {
for (final Expansion expansion : expansions) {
if (Objects.equals(expansion.name(), name)) {
return expansion;
}
}
return null;
@Deprecated(forRemoval = true, since = "1.1.0")
@org.jetbrains.annotations.ApiStatus.Internal
public static void setPlatform(Platform platform){
throw new UnsupportedOperationException("Cannot set platform twice");
}
}
@@ -1,12 +1,12 @@
package io.github.miniplaceholders.api;
package me.dreamerzero.miniplaceholders.api;
import java.util.Objects;
import io.github.miniplaceholders.api.placeholder.AudiencePlaceholder;
import io.github.miniplaceholders.api.placeholder.RelationalPlaceholder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import me.dreamerzero.miniplaceholders.api.placeholder.AudiencePlaceholder;
import me.dreamerzero.miniplaceholders.api.placeholder.RelationalPlaceholder;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.minimessage.Context;
import net.kyori.adventure.text.minimessage.ParsingException;
@@ -0,0 +1,18 @@
package me.dreamerzero.miniplaceholders.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import me.dreamerzero.miniplaceholders.api.enums.Platform;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Extension {
String name();
Platform[] platform();
String version() default "";
}
@@ -0,0 +1,63 @@
package me.dreamerzero.miniplaceholders.api.annotation.processor;
import com.google.gson.Gson;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import me.dreamerzero.miniplaceholders.api.annotation.Extension;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Set;
@SupportedAnnotationTypes({"me.dreamerzero.miniplaceholders.api.annotation.Extension"})
public class ExtensionAnnotationProcessor extends AbstractProcessor {
private ProcessingEnvironment environment;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
this.environment = processingEnv;
}
@Override
public synchronized boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
for (Element element : roundEnv.getElementsAnnotatedWith(Extension.class)) {
if (element.getKind() != ElementKind.CLASS) {
return false;
}
Extension extension = element.getAnnotation(Extension.class);
Name name = ((TypeElement) element).getQualifiedName();
try {
FileObject object = environment.getFiler()
.createResource(StandardLocation.CLASS_OUTPUT, "", "miniplaceholders-extension.json");
try (Writer writer = new BufferedWriter(object.openWriter())) {
new Gson().toJson(new ProcessedExtension(
extension.name(),
extension.version(),
name.toString(),
extension.platform()),
writer);
}
} catch (IOException e) {
environment.getMessager().printMessage(Diagnostic.Kind.ERROR, "Cannot generate extension file");
}
}
return false;
}
}
@@ -0,0 +1,30 @@
package me.dreamerzero.miniplaceholders.api.annotation.processor;
import me.dreamerzero.miniplaceholders.api.enums.Platform;
public final class ProcessedExtension {
private final String name;
private final String version;
private final Platform[] platforms;
private final String clazz;
ProcessedExtension(String name, String version, String clazz, Platform... platforms) {
this.name = name;
this.version = version;
this.platforms = platforms;
this.clazz = clazz;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public Platform[] getPlatforms() {
return platforms;
}
public String getClazz() {
return this.clazz;
}
}
@@ -0,0 +1,9 @@
package me.dreamerzero.miniplaceholders.api.enums;
/**Platforms on which MiniPlaceholders can be used */
public enum Platform {
/**Paper Platform */
PAPER,
/**Velocity Platform */
VELOCITY
}
@@ -0,0 +1,2 @@
/**Plugin enums */
package me.dreamerzero.miniplaceholders.api.enums;
@@ -0,0 +1,4 @@
/**
* MiniPlaceholders core package
*/
package me.dreamerzero.miniplaceholders.api;
@@ -1,4 +1,4 @@
package io.github.miniplaceholders.api.placeholder;
package me.dreamerzero.miniplaceholders.api.placeholder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -1,4 +1,4 @@
package io.github.miniplaceholders.api.placeholder;
package me.dreamerzero.miniplaceholders.api.placeholder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -1,4 +1,4 @@
/**
* Placeholders available based on information obtained from Audiences
*/
package io.github.miniplaceholders.api.placeholder;
package me.dreamerzero.miniplaceholders.api.placeholder;
@@ -1,4 +1,4 @@
package io.github.miniplaceholders.api.utils;
package me.dreamerzero.miniplaceholders.api.utils;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
@@ -0,0 +1,37 @@
package me.dreamerzero.miniplaceholders.api.utils;
import java.util.function.Supplier;
/** Checks required for the correct operation of the expansions*/
public final class Conditions {
private Conditions(){}
/**
* Checks if a string is null or empty or consists of whitespace characters only
* @param string the string
* @param name the name supplier
* @return the string if it is not null or empty
* @since 1.0.0
*/
public static String nonNullOrEmptyString(String string, Supplier<String> name){
if(string == null)
throw new NullPointerException("the " + name.get() + " cannot be null");
if(string.isBlank())
throw new IllegalStateException("the " + name.get() + "cannot be an empty string");
return string;
}
/**
* Check if a string is empty or consists of whitespace characters only
* @param string the string
* @param reason the reason supplier
* @return the string if it not empty
* @since 1.0.0
*/
public static String nonEmptyString(String string, Supplier<String> reason){
if(string.isBlank())
throw new IllegalStateException(reason.get());
return string;
}
}
@@ -1,9 +1,10 @@
package io.github.miniplaceholders.api.utils;
package me.dreamerzero.miniplaceholders.api.utils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static net.kyori.adventure.text.minimessage.MiniMessage.miniMessage;
@@ -11,31 +12,30 @@ import static net.kyori.adventure.text.minimessage.MiniMessage.miniMessage;
* Legacy utils
*/
public final class LegacyUtils {
private LegacyUtils() {
}
private LegacyUtils(){}
/**
* Legacy serializer with hex support
* <p>Use this as the last available alternative,
* it is recommended to use MiniMessage instead of this serializer</p>
*
* Use this as the last available alternative,
* it is recommended to use MiniMessage instead of this serializer
*/
public static final LegacyComponentSerializer LEGACY_HEX_SERIALIZER = LegacyComponentSerializer.builder()
.character('&')
.hexColors()
.build();
.character('&')
.hexColors()
.build();
/**
* Parse a string with possible legacy symbols
*
* @param string the string
* @return a parsed string
* @since 1.0.0
*/
public static @NotNull Component parsePossibleLegacy(@Nullable String string) {
if (string == null || string.isBlank()) return Component.empty();
if (string.indexOf('&') != 0) {
if(string == null || string.isBlank()) return Component.empty();
if(string.indexOf('&') != 0){
return miniMessage().deserialize(
miniMessage().serialize(LEGACY_HEX_SERIALIZER.deserialize(string))
miniMessage().serialize(LEGACY_HEX_SERIALIZER.deserialize(string))
);
} else {
return miniMessage().deserialize(string);
@@ -1,4 +1,4 @@
package io.github.miniplaceholders.api.utils;
package me.dreamerzero.miniplaceholders.api.utils;
import org.jetbrains.annotations.NotNull;
@@ -1,9 +1,9 @@
package io.github.miniplaceholders.api.utils;
package me.dreamerzero.miniplaceholders.api.utils;
import io.github.miniplaceholders.api.placeholder.AudiencePlaceholder;
import io.github.miniplaceholders.api.placeholder.RelationalPlaceholder;
import org.jetbrains.annotations.NotNull;
import me.dreamerzero.miniplaceholders.api.placeholder.AudiencePlaceholder;
import me.dreamerzero.miniplaceholders.api.placeholder.RelationalPlaceholder;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.tag.Tag;
@@ -2,4 +2,4 @@
* General Utilities
* Here you will find utilities that will help you in the development of expansions
*/
package io.github.miniplaceholders.api.utils;
package me.dreamerzero.miniplaceholders.api.utils;
+10 -9
View File
@@ -1,14 +1,15 @@
/** MiniPlaceholders API Module */
open module io.github.miniplaceholders.api {
module me.dreamerzero.miniplaceholders.api {
requires net.kyori.adventure;
requires net.kyori.adventure.text.minimessage;
requires net.kyori.examination.api;
requires net.kyori.adventure.text.minimessage;
requires static org.jetbrains.annotations;
requires io.github.miniplaceholders.connect;
requires net.kyori.adventure.text.serializer.legacy;
requires me.dreamerzero.miniplaceholders.connect;
requires java.base;
requires java.compiler;
requires com.google.gson;
exports io.github.miniplaceholders.api;
exports io.github.miniplaceholders.api.enums;
exports io.github.miniplaceholders.api.utils;
exports io.github.miniplaceholders.api.placeholder;
exports me.dreamerzero.miniplaceholders.api;
exports me.dreamerzero.miniplaceholders.api.enums;
exports me.dreamerzero.miniplaceholders.api.utils;
exports me.dreamerzero.miniplaceholders.api.placeholder;
}
@@ -0,0 +1 @@
me.dreamerzero.miniplaceholders.api.annotation.processor.ExtensionAnnotationProcessor
@@ -1,45 +0,0 @@
package io.github.miniplaceholders.test;
import io.github.miniplaceholders.api.Expansion;
import io.github.miniplaceholders.api.utils.TagsUtils;
import io.github.miniplaceholders.test.testobjects.TestAudienceHolder;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.tag.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.github.miniplaceholders.test.PlaceholderTest.assertContentEquals;
import static net.kyori.adventure.text.minimessage.MiniMessage.miniMessage;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ExpansionsTest {
@Test
@DisplayName("Expansion Equality")
void equalsExpansions(){
final Expansion firstExpansion = Expansion.builder("equals")
.audiencePlaceholder("test", TagsUtils.NULL_AUDIENCE_PLACEHOLDER)
.build();
final Expansion secondExpansion = Expansion.builder("equals")
.audiencePlaceholder("test", TagsUtils.NULL_AUDIENCE_PLACEHOLDER)
.build();
assertEquals(firstExpansion, secondExpansion);
}
@Test
void nullForwardedAudience() {
TestAudienceHolder audience = new TestAudienceHolder(null);
final Expansion expansion = Expansion.builder("test")
.filter(aud -> aud.toString().isBlank())
.audiencePlaceholder("testing", (aud, queue, ctx) -> Tag.selfClosingInserting(Component.text(aud.toString())))
.build();
Component result = assertDoesNotThrow(
() -> miniMessage().deserialize("<test_testing>", expansion.audiencePlaceholders(audience))
);
assertContentEquals(result, Component.text("<test_testing>"));
}
}
@@ -1,7 +0,0 @@
package io.github.miniplaceholders.test.testobjects;
import org.jetbrains.annotations.NotNull;
import net.kyori.adventure.audience.Audience;
public record TestAudience(@NotNull String name) implements Audience {}
@@ -1,11 +0,0 @@
package io.github.miniplaceholders.test.testobjects;
import net.kyori.adventure.audience.ForwardingAudience;
import org.jetbrains.annotations.NotNull;
public record TestAudienceHolder(TestAudience audience) implements ForwardingAudience.Single {
@Override
public @NotNull TestAudience audience() {
return audience;
}
}
@@ -0,0 +1,24 @@
package me.dreamerzero.miniplaceholders;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import me.dreamerzero.miniplaceholders.api.Expansion;
import me.dreamerzero.miniplaceholders.api.utils.TagsUtils;
class ExpansionsTest {
@Test
@DisplayName("Expansion Equality")
void equalsExpansions(){
final Expansion firstExpansion = Expansion.builder("equals")
.audiencePlaceholder("test", TagsUtils.NULL_AUDIENCE_PLACEHOLDER)
.build();
final Expansion secondExpansion = Expansion.builder("equals")
.audiencePlaceholder("test", TagsUtils.NULL_AUDIENCE_PLACEHOLDER)
.build();
assertEquals(firstExpansion, secondExpansion);
}
}
@@ -1,16 +1,16 @@
package io.github.miniplaceholders.test;
package me.dreamerzero.miniplaceholders;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import io.github.miniplaceholders.api.Expansion;
import io.github.miniplaceholders.api.MiniPlaceholders;
import io.github.miniplaceholders.api.utils.TagsUtils;
import me.dreamerzero.miniplaceholders.api.Expansion;
import me.dreamerzero.miniplaceholders.api.MiniPlaceholders;
import me.dreamerzero.miniplaceholders.api.utils.TagsUtils;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import static org.junit.jupiter.api.Assertions.*;
class MiniPlaceholdersTest {
@Test
@Disabled("Cannot correctly calculate the equity of 2 TagResolvers obtained in different ways")
@@ -30,16 +30,4 @@ class MiniPlaceholdersTest {
)
);
}
@Test
void registrationTest() {
Expansion expansion = Expansion.builder("testregistration")
.build();
expansion.register();
assertTrue(expansion.registered());
assertThrows(IllegalStateException.class, expansion::register);
assertDoesNotThrow(expansion::unregister);
}
}
@@ -1,15 +1,13 @@
package io.github.miniplaceholders.test;
package me.dreamerzero.miniplaceholders;
import static net.kyori.adventure.text.minimessage.MiniMessage.miniMessage;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import io.github.miniplaceholders.test.testobjects.TestAudience;
import io.github.miniplaceholders.test.testobjects.TestAudienceHolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import io.github.miniplaceholders.api.Expansion;
import io.github.miniplaceholders.api.MiniPlaceholders;
import me.dreamerzero.miniplaceholders.api.Expansion;
import me.dreamerzero.miniplaceholders.api.MiniPlaceholders;
import me.dreamerzero.miniplaceholders.testobjects.TestAudience;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
@@ -25,15 +23,12 @@ class PlaceholderTest {
TestAudience player = new TestAudience("4drian3d");
Expansion expansion = Expansion.builder("example")
.audiencePlaceholder("name", (aud, queue, ctx) -> {
TestAudience audience = (TestAudience) aud;
return Tag.selfClosingInserting(Component.text(audience.name()));
}).build();
.audiencePlaceholder("name", (aud, queue, ctx) -> Tag.selfClosingInserting(Component.text(((TestAudience)aud).getName()))).build();
final Component expected = Component.text("Player Name: 4drian3d");
final Component result = miniMessage().deserialize("Player Name: <example_name>", expansion.audiencePlaceholders(player));
final Component result = MiniMessage.miniMessage().deserialize("Player Name: <example_name>", expansion.audiencePlaceholders(player));
assertContentEquals(expected, result);
assertEquals(expected, result);
}
@Test
@@ -64,7 +59,7 @@ class PlaceholderTest {
final Component expected = Component.text("Online players: 1305 | Servers: 7");
final Component actual = MiniMessage.miniMessage().deserialize("Online players: <global_players> | Servers: <global_servers>", expansion.globalPlaceholders());
assertContentEquals(expected, actual);
assertEquals(expected, actual);
}
@Test
@@ -85,7 +80,7 @@ class PlaceholderTest {
@DisplayName("Filtered Expansion")
void filteredExpansion(){
Expansion expansion = Expansion.builder("filter")
.audiencePlaceholder("name", (aud, queue, ctx) -> Tag.selfClosingInserting(Component.text(((TestAudience)aud).name())))
.audiencePlaceholder("name", (aud, queue, ctx) -> Tag.selfClosingInserting(Component.text(((TestAudience)aud).getName())))
.filter(TestAudience.class)
.build();
@@ -97,50 +92,13 @@ class PlaceholderTest {
Component playerExpected = Component.text("Player Name: TestPlayer04");
Component emptyExpected = Component.text("Player Name: <filter_name>");
assertContentEquals(playerExpected, MiniMessage.miniMessage().deserialize(string, expansion.audiencePlaceholders(player)));
assertContentEquals(emptyExpected, MiniMessage.miniMessage().deserialize(string, expansion.audiencePlaceholders(emptyAudience)));
assertEquals(playerExpected, MiniMessage.miniMessage().deserialize(string, expansion.audiencePlaceholders(player)));
assertEquals(emptyExpected, MiniMessage.miniMessage().deserialize(string, expansion.audiencePlaceholders(emptyAudience)));
}
@Test
@DisplayName("Empty Arguments")
void testEmptyArguments() {
final Expansion expansion = Expansion.builder("test")
.globalPlaceholder("testing", (queue, ctx) -> {
int arguments = 0;
while (queue.hasNext()) {
arguments++;
Tag.Argument argument = queue.pop();
assertTrue(argument.value().isBlank());
}
return Tag.selfClosingInserting(Component.text("Arguments: "+arguments));
})
.build();
Component parsed = miniMessage().deserialize("<test_testing::>", expansion.globalPlaceholders());
assertContentEquals(parsed, Component.text("Arguments: 2"));
}
@Test
@DisplayName("Forwarding Audience Parsing Test")
void forwardingAudienceTest() {
Expansion expansion = Expansion.builder("test")
.filter(TestAudience.class)
.audiencePlaceholder("testing", (audience, queue, ctx) -> {
TestAudience testAudience = (TestAudience) audience;
return Tag.selfClosingInserting(Component.text("Name: "+testAudience.name()));
}).build();
TestAudience testAudience = new TestAudience("4drian3d");
Audience forward = new TestAudienceHolder(testAudience);
Component parsed = miniMessage().deserialize("<test_testing>.", expansion.audiencePlaceholders(forward));
Component expected = Component.text("Name: 4drian3d.");
assertContentEquals(parsed, expected);
}
static void assertContentEquals(Component first, Component second){
void assertContentEquals(Component first, Component second){
String firstSerialized = PlainTextComponentSerializer.plainText().serialize(first);
String secondSerialized = PlainTextComponentSerializer.plainText().serialize(second);
@@ -148,7 +106,7 @@ class PlaceholderTest {
}
private boolean isEnemy(TestAudience a1, TestAudience a2){
return a1.name().equals("PlayerOne") && a2.name().equals("PlayerTwo");
return a1.getName().equals("PlayerOne") && a2.getName().equals("PlayerTwo");
}
}
@@ -1,4 +1,4 @@
package io.github.miniplaceholders.test;
package me.dreamerzero.miniplaceholders;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -8,15 +8,13 @@ import java.util.function.BiFunction;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import io.github.miniplaceholders.api.Expansion;
import io.github.miniplaceholders.api.MiniPlaceholders;
import io.github.miniplaceholders.api.utils.TagsUtils;
import me.dreamerzero.miniplaceholders.api.Expansion;
import me.dreamerzero.miniplaceholders.api.MiniPlaceholders;
import me.dreamerzero.miniplaceholders.api.utils.TagsUtils;
import net.kyori.adventure.text.minimessage.Context;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.ArgumentQueue;
//yea... it is intended xd
@SuppressWarnings("DataFlowIssue")
class ThrowableTest {
@Test
@DisplayName("Nullable Exception")
@@ -0,0 +1,16 @@
package me.dreamerzero.miniplaceholders.testobjects;
import org.jetbrains.annotations.NotNull;
import net.kyori.adventure.audience.Audience;
public final class TestAudience implements Audience {
private final String name;
public TestAudience(String name) {
this.name = name;
}
public @NotNull String getName(){
return this.name;
}
}
-19
View File
@@ -1,19 +0,0 @@
plugins {
`kotlin-dsl`
}
dependencies {
implementation(libs.plugin.shadow)
implementation(libs.plugin.kotlin)
implementation(libs.plugin.dokka)
}
repositories {
gradlePluginPortal()
}
kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
-15
View File
@@ -1,15 +0,0 @@
rootProject.name = "build-logic"
dependencyResolutionManagement {
@Suppress("UnstableApiUsage")
repositories {
gradlePluginPortal()
mavenCentral()
}
versionCatalogs {
register("libs") {
from(files("../gradle/libs.versions.toml"))
}
}
}
@@ -1,8 +0,0 @@
import org.gradle.api.Project
import org.gradle.configurationcache.extensions.capitalized
val Project.capitalizeName: String
get() = this.name.substring(17).capitalized()
val Project.simpleName: String
get() = this.name.substring(17)
@@ -1,9 +0,0 @@
plugins {
id("miniplaceholders.base")
}
tasks.jar {
manifest {
attributes("Automatic-Module-Name" to "io.github.miniplaceholders.${project.simpleName}")
}
}
@@ -1,23 +0,0 @@
import java.util.Date
plugins {
java
}
tasks {
compileJava {
options.encoding = Charsets.UTF_8.name()
options.release.set(17)
}
jar {
manifest {
attributes(
"Specification-Version" to project.version,
"Specification-Vendor" to "MiniPlaceholders",
"Implementation-Build-Date" to Date()
)
}
}
}
java.toolchain.languageVersion.set(JavaLanguageVersion.of(17))
@@ -1,80 +0,0 @@
plugins {
kotlin("jvm")
`java-library`
`maven-publish`
signing
id("org.jetbrains.dokka")
}
/*
val dokkaHtmlJar = tasks.register<Jar>("dokkaHtmlJar") {
dependsOn(tasks.dokkaHtml)
from(tasks.dokkaHtml.flatMap { it.outputDirectory })
archiveClassifier.set("javadoc")
}
publishing {
publications {
create<MavenPublication>("maven") {
artifact(tasks["dokkaHtmlJar"])
repositories {
maven {
credentials(PasswordCredentials::class)
val central = "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/"
val snapshots = "https://s01.oss.sonatype.org/content/repositories/snapshots/"
if (project.version.toString().endsWith("SNAPSHOT")) {
name = "SonatypeSnapshots"
setUrl(snapshots)
} else {
name = "OSSRH"
setUrl(central)
}
}
}
from(components["java"])
pom {
url.set("https://github.com/MiniPlaceholders/MiniPlaceholders")
licenses {
license {
name.set("GNU General Public License version 3 or later")
url.set("https://opensource.org/licenses/GPL-3.0")
}
}
scm {
connection.set("scm:git:https://github.com/MiniPlaceholders/MiniPlaceholders.git")
developerConnection.set("scm:git:ssh://git@github.com/MiniPlaceholders/MiniPlaceholders.git")
url.set("https://github.com/MiniPlaceholders/MiniPlaceholders")
}
developers {
developer {
id.set("4drian3d")
name.set("Adrian Gonzales")
email.set("adriangonzalesval@gmail.com")
}
}
issueManagement {
name.set("GitHub")
url.set("https://github.com/MiniPlaceholders/MiniPlaceholders/issues")
}
ciManagement {
name.set("GitHub Actions")
url.set("https://github.com/MiniPlaceholders/MiniPlaceholders/actions")
}
name.set(project.name)
description.set(project.description)
url.set("https://github.com/MiniPlaceholders/MiniPlaceholders")
}
}
}
}
signing {
useGpgCmd()
sign(configurations.archives.get())
sign(publishing.publications["maven"])
sign(tasks["dokkaHtmlJar"])
}
java {
withSourcesJar()
}*/
@@ -1,71 +0,0 @@
plugins {
`java-library`
`maven-publish`
signing
}
/*
publishing {
publications {
create<MavenPublication>("maven") {
repositories {
maven {
credentials(PasswordCredentials::class)
val central = "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/"
val snapshots = "https://s01.oss.sonatype.org/content/repositories/snapshots/"
if (project.version.toString().endsWith("SNAPSHOT")) {
name = "SonatypeSnapshots"
setUrl(snapshots)
} else {
name = "OSSRH"
setUrl(central)
}
}
}
from(components["java"])
pom {
url.set("https://github.com/MiniPlaceholders/MiniPlaceholders")
licenses {
license {
name.set("GNU General Public License version 3 or later")
url.set("https://opensource.org/licenses/GPL-3.0")
}
}
scm {
connection.set("scm:git:https://github.com/MiniPlaceholders/MiniPlaceholders.git")
developerConnection.set("scm:git:ssh://git@github.com/MiniPlaceholders/MiniPlaceholders.git")
url.set("https://github.com/MiniPlaceholders/MiniPlaceholders")
}
developers {
developer {
id.set("4drian3d")
name.set("Adrian Gonzales")
email.set("adriangonzalesval@gmail.com")
}
}
issueManagement {
name.set("GitHub")
url.set("https://github.com/MiniPlaceholders/MiniPlaceholders/issues")
}
ciManagement {
name.set("GitHub Actions")
url.set("https://github.com/MiniPlaceholders/MiniPlaceholders/actions")
}
name.set(project.name)
description.set(project.description)
url.set("https://github.com/MiniPlaceholders/MiniPlaceholders")
}
}
}
}
signing {
useGpgCmd()
sign(configurations.archives.get())
sign(publishing.publications["maven"])
}*/
java {
withSourcesJar()
}
@@ -1,21 +0,0 @@
plugins {
id("miniplaceholders.base")
id("com.github.johnrengelman.shadow")
}
tasks {
shadowJar {
archiveBaseName.set("MiniPlaceholders-${project.capitalizeName}")
archiveClassifier.set("")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
relocate("net.william278.desertwell", "io.github.miniplaceholders.libs.desertwell")
relocate("cloud.commandframework", "io.github.miniplaceholders.libs.cloud")
if (project.simpleName != "sponge") {
relocate("io.leangen.geantyref", "io.github.miniplaceholders.libs.geantyref")
}
destinationDirectory.set(file("${project.rootDir}/jar"))
}
build {
dependsOn(shadowJar)
}
}
+37 -3
View File
@@ -1,9 +1,43 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
kotlin("jvm") version "1.8.21" apply false
java
id("com.github.johnrengelman.shadow") version "7.1.2"
}
allprojects {
apply(plugin = "java")
group = "me.dreamerzero.miniplaceholders"
version = "1.2.0"
description = "MiniPlaceholders"
repositories {
mavenCentral()
}
}
dependencies {
shadow(project(":miniplaceholders-connect"))
shadow(project(":miniplaceholders-api"))
shadow(project(":miniplaceholders-common"))
shadow(project(":miniplaceholders-velocity"))
shadow(project(":miniplaceholders-paper", "reobf"))
}
subprojects {
repositories {
maven("https://papermc.io/repo/repository/maven-public/")
maven("https://repo.maven.apache.org/maven2/")
}
}
tasks {
delete {
delete("jar")
shadowJar {
archiveFileName.set("MiniPlaceholders.jar")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
configurations = listOf(project.configurations.shadow.get())
}
build {
dependsOn(shadowJar)
}
}
+20 -15
View File
@@ -1,22 +1,27 @@
plugins {
id("miniplaceholders.auto.module")
alias(libs.plugins.blossom)
id("net.kyori.blossom") version "1.3.1"
}
repositories {
maven("https://libraries.minecraft.net");
}
dependencies {
implementation(projects.miniplaceholdersApi)
implementation(libs.desertwell) {
exclude("org.json")
}
implementation(libs.cloud.core)
implementation(libs.cloud.extras) {
isTransitive = false
}
compileOnly(libs.adventure.api)
compileOnly(libs.adventure.minimesssage)
implementation(project(":miniplaceholders-api"))
compileOnly("net.kyori:adventure-api:4.11.0")
compileOnly("net.kyori:adventure-text-minimessage:4.11.0")
compileOnly("com.mojang:brigadier:1.0.18")
}
blossom{
replaceToken("{version}", project.version)
replaceTokenIn("src/main/java/io/github/miniplaceholders/common/PluginConstants.java")
blossom {
replaceToken("{version}", version)
replaceTokenIn("src/main/java/me/dreamerzero/miniplaceholders/common/PluginConstants.java")
}
tasks {
compileJava {
options.encoding = Charsets.UTF_8.name()
options.release.set(17)
}
}
@@ -1,198 +0,0 @@
package io.github.miniplaceholders.common;
import cloud.commandframework.ArgumentDescription;
import cloud.commandframework.Command;
import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.arguments.standard.StringArgument;
import cloud.commandframework.minecraft.extras.AudienceProvider;
import cloud.commandframework.minecraft.extras.MinecraftExceptionHandler;
import io.github.miniplaceholders.api.MiniPlaceholders;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.builder.AbstractBuilder;
import net.kyori.adventure.permission.PermissionChecker;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.util.TriState;
import net.william278.desertwell.about.AboutMenu;
import net.william278.desertwell.util.Version;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Supplier;
import static java.util.Objects.requireNonNull;
import static net.kyori.adventure.text.Component.newline;
import static net.kyori.adventure.text.Component.text;
import static net.kyori.adventure.text.format.NamedTextColor.RED;
import static net.kyori.adventure.text.minimessage.MiniMessage.miniMessage;
public final class PlaceholdersCommand<A extends Audience> {
private final Supplier<ArrayList<String>> playersSuggestions;
private final Function<String, Audience> toAudience;
private final BiPredicate<A, String> hasPermission;
private final String command;
private final CommandManager<A> commandManager;
private PlaceholdersCommand(
final Supplier<ArrayList<String>> playersSuggestions,
final Function<String, Audience> toAudience,
final BiPredicate<A, String> hasPermission,
final String command,
final CommandManager<A> commandManager
) {
this.playersSuggestions = playersSuggestions;
this.toAudience = toAudience;
this.hasPermission = hasPermission;
this.command = command;
this.commandManager = commandManager;
}
private static final Component TITLE = miniMessage().deserialize("<gradient:#4d8bff:#a4ff96>MiniPlaceholders</gradient>");
private static final Component HELP = text()
.append(newline(), miniMessage().deserialize(
"<gradient:aqua:white:aqua><st><b> </st> <title> <st><b> </st>", Placeholder.component("title", TITLE)))
.append(newline(), miniMessage().deserialize(
"<gradient:#9694ff:#5269ff>Commands:</gradient>"))
.append(newline(), miniMessage().deserialize(
"<gradient:aqua:#94d1ff>/miniplaceholders</gradient> <aqua>help</aqua>"))
.append(newline(), miniMessage().deserialize(
"<gradient:aqua:#94d1ff>/miniplaceholders</gradient> <aqua>parse</aqua> <#8fadff><player | me></#8fadff> <#99ffb6><player></#99ffb6>"))
.append(newline(), miniMessage().deserialize(
"<gradient:aqua:white:aqua><st><b> "))
.build();
private static final Component INFO = AboutMenu.builder()
.title(TITLE)
.description(text("MiniMessage Component-based Placeholders for Paper, Folia, Fabric, Velocity, Sponge and Krypton platforms"))
.credits("Author", AboutMenu.Credit.of("4drian3d").url("https://github.com/4drian3d"))
.credits("Contributors", AboutMenu.Credit.of("Sliman4"))
.buttons(
AboutMenu.Link.of("https://github.com/MiniPlaceholders/MiniPlaceholders/wiki/User-Getting-Started").text("Documentation").icon("⛏"),
AboutMenu.Link.of("https://discord.gg/5NMMzK5mAn").text("Discord").color(TextColor.color(0x7289da)).icon("⭐"),
AboutMenu.Link.of("https://modrinth.com/plugin/miniplaceholders").text("Downloads").color(TextColor.color(0xff496e)).icon("↓")
).version(Version.fromString(PluginConstants.VERSION))
.build()
.toComponent();
private Command.Builder<A> rootBuilder() {
return commandManager.commandBuilder(command);
}
public void register() {
new MinecraftExceptionHandler<A>()
.withDefaultHandlers()
.withDecorator(component -> Component.text().append(TITLE).appendSpace().append(component).build())
.apply(commandManager, AudienceProvider.nativeAudience());
commandManager.command(rootBuilder()
.permission(src -> {
if (hasPermission != null) {
return hasPermission.test(src, "miniplaceholders.command");
}
return src
.get(PermissionChecker.POINTER)
.map(checker -> checker.value("miniplaceholders.command"))
.orElse(TriState.FALSE) != TriState.FALSE;
})
.handler(handler -> handler.getSender().sendMessage(INFO)));
final CommandArgument<A, String> sourceArgument = StringArgument.<A>builder("source")
.single()
.withDefaultDescription(ArgumentDescription.of("The source from which the message will be parsed"))
.withSuggestionsProvider((ctx, st) -> {
final List<String> suggestions = playersSuggestions.get();
suggestions.add("me");
return suggestions;
})
.build();
final CommandArgument<A, String> stringArgument = StringArgument.<A>builder("message")
.greedy()
.withDefaultDescription(ArgumentDescription.of("Message to be parsed"))
.build();
commandManager.command(
rootBuilder().literal("parse")
.argument(sourceArgument)
.argument(stringArgument)
.permission("miniplaceholders.command.parse")
.handler(handler -> {
final String source = handler.get(sourceArgument);
final Audience objective = "me".equals(source)
? handler.getSender()
: toAudience.apply(source);
if (objective == null){
handler.getSender().sendMessage(text("You must specify a valid player", RED));
return;
}
final String toParse = handler.get(stringArgument);
final Component parsed = miniMessage().deserialize(
toParse,
MiniPlaceholders.getAudienceGlobalPlaceholders(objective)
);
handler.getSender().sendMessage(parsed);
})
);
commandManager.command(
rootBuilder().literal("help")
.permission("miniplaceholders.command.help")
.handler(handler -> handler.getSender().sendMessage(HELP))
);
}
public static <A extends Audience> Builder<A> builder() {
return new Builder<>();
}
public final static class Builder<A extends Audience> implements AbstractBuilder<PlaceholdersCommand<A>> {
private Supplier<ArrayList<String>> playersSuggestions;
private Function<String, Audience> toAudience;
private BiPredicate<A, String> hasPermission;
private String command;
private CommandManager<A> commandManager;
private Builder() {}
public Builder<A> playerSuggestions(final Supplier<@NotNull ArrayList<@NotNull String>> playersSuggestions) {
this.playersSuggestions = playersSuggestions;
return this;
}
public Builder<A> toAudience(final @NotNull Function<@NotNull String, @Nullable Audience> argumentToAudience) {
this.toAudience = argumentToAudience;
return this;
}
public Builder<A> hasPermissionCheck(final @NotNull BiPredicate<@NotNull A, @NotNull String> hasPermission) {
this.hasPermission = hasPermission;
return this;
}
public Builder<A> command(final String command) {
this.command = command;
return this;
}
public Builder<A> manager(CommandManager<A> commandManager) {
this.commandManager = commandManager;
return this;
}
@Override
public @NotNull PlaceholdersCommand<A> build() {
return new PlaceholdersCommand<>(
requireNonNull(playersSuggestions),
requireNonNull(toAudience),
hasPermission,
command,
commandManager
);
}
}
}
@@ -0,0 +1,143 @@
package me.dreamerzero.miniplaceholders.common;
import java.util.Collection;
import java.util.function.Function;
import java.util.function.Supplier;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.tree.LiteralCommandNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import me.dreamerzero.miniplaceholders.api.Expansion;
import me.dreamerzero.miniplaceholders.api.MiniPlaceholders;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.permission.PermissionChecker;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import static net.kyori.adventure.text.minimessage.MiniMessage.miniMessage;
public class PlaceholdersCommand<A> {
private final @NotNull Supplier<@NotNull Collection<@NotNull String>> playersSuggestions;
private final @NotNull Function<@NotNull String, @Nullable Audience> toAudience;
private Function<A, Audience> fromAToAudience = a -> Audience.empty();
private final Expansion commandExpansion = Expansion.builder("placeholders")
.globalPlaceholder("count", (queue, ctx) -> Tag.selfClosingInserting(Component.text(MiniPlaceholders.getExpansionCount())))
.globalPlaceholder("version", (queue, ctx) -> Tag.selfClosingInserting(Component.text(PluginConstants.VERSION)))
.build();
public PlaceholdersCommand(Supplier<Collection<String>> playersSuggestions, Function<@NotNull String, @Nullable Audience> toAudience){
this.playersSuggestions = playersSuggestions;
this.toAudience = toAudience;
}
public PlaceholdersCommand(Supplier<Collection<String>> playersSuggestions, Function<@NotNull String, @Nullable Audience> toAudience, Function<A, Audience> fromAToAudience){
this(playersSuggestions, toAudience);
this.fromAToAudience = fromAToAudience;
}
private static final Component HEADER = miniMessage().deserialize("<gradient:aqua:white:aqua>---------- <gradient:#4d8bff:#a4ff96>MiniPlaceholders</gradient> -----------</gradient>");
private static final Component FOOTER = miniMessage().deserialize("<gradient:aqua:white:aqua> --------------- ---------------</gradient>");
public LiteralArgumentBuilder<A> placeholderTestBuilder(String commandName){
return LiteralArgumentBuilder.<A>literal(commandName)
.requires(a -> getAudience(a).pointers().supports(PermissionChecker.POINTER))
.executes(cmd -> {
Audience source = getAudience(cmd.getSource());
if(source.pointers().get(PermissionChecker.POINTER).orElse(null).test("miniplaceholders.command")){
source.sendMessage(
Component.text()
.append(HEADER).append(Component.newline())
.append(miniMessage().deserialize("<gradient:aqua:#918fff>Placeholders Available:</gradient> <aqua><placeholders_count></aqua>", commandExpansion.globalPlaceholders())).append(Component.newline())
.append(FOOTER)
.build()
);
} else {
source.sendMessage(
Component.text()
.append(HEADER).append(Component.newline())
.append(miniMessage().deserialize("<gradient:red:dark_red>Version: <placeholders_version>", commandExpansion.globalPlaceholders())).append(Component.newline())
.append(FOOTER)
.build()
);
}
return 1;
})
.then(LiteralArgumentBuilder.<A>literal("help")
.executes(cmd -> {
getAudience(cmd.getSource()).sendMessage(
Component.text()
.append(HEADER).append(Component.newline())
.append(miniMessage().deserialize("<gradient:#9694ff:#5269ff>Commands:</gradient>")).append(Component.newline())
.append(miniMessage().deserialize("<gradient:aqua:#94d1ff>/miniplaceholders</gradient> <aqua>help</aqua>")).append(Component.newline())
.append(miniMessage().deserialize("<gradient:aqua:#94d1ff>/miniplaceholders</gradient> <aqua>parse</aqua> <color:#8fadff><player:me></color> <color:#99ffb6><player></color>")).append(Component.newline())
.append(FOOTER)
.build()
);
return 1;
})
)
.then(LiteralArgumentBuilder.<A>literal("parse")
.then(LiteralArgumentBuilder.<A>literal("me")
.then(RequiredArgumentBuilder.<A, String>argument("selfStringToParse", StringArgumentType.string())
.executes(cmd -> {
String stringToParse = cmd.getArgument("selfStringToParse", String.class);
Component parsed = this.parseGlobal(stringToParse, getAudience(cmd.getSource()));
getAudience(cmd.getSource()).sendMessage(parsed);
return 1;
})
)
)
.then(LiteralArgumentBuilder.<A>literal("player")
.then(RequiredArgumentBuilder.<A, String>argument("source", StringArgumentType.word())
.suggests((argument, builder) -> {
playersSuggestions.get().forEach(builder::suggest);
return builder.buildFuture();
})
.then(RequiredArgumentBuilder.<A, String>argument("playerStringToParse", StringArgumentType.string())
.executes(cmd -> {
Audience objetive = toAudience.apply(cmd.getArgument("source", String.class));
if(objetive == null){
getAudience(cmd.getSource()).sendMessage(Component.text("You must specify a valid player", NamedTextColor.RED));
return 1;
}
String stringToParse = cmd.getArgument("playerStringToParse", String.class);
Component parsed = this.parseGlobal(stringToParse, objetive);
getAudience(cmd.getSource()).sendMessage(parsed);
return 1;
})
)
)
)
);
}
public LiteralCommandNode<A> placeholderTestCommand(String command){
return this.placeholderTestBuilder(command).build();
}
private Component parseGlobal(String string, Audience audience){
return miniMessage().deserialize(
string,
TagResolver.resolver(
MiniPlaceholders.getGlobalPlaceholders(),
MiniPlaceholders.getAudiencePlaceholders(audience)
)
);
}
private Audience getAudience(A possibleAudience){
if(possibleAudience instanceof Audience audience){
return audience;
}
Audience audience = fromAToAudience.apply(possibleAudience);
return audience != null ? audience : Audience.empty();
}
}
@@ -1,4 +1,4 @@
package io.github.miniplaceholders.common;
package me.dreamerzero.miniplaceholders.common;
public interface PlaceholdersPlugin {
void loadDefaultExpansions();
@@ -1,4 +1,4 @@
package io.github.miniplaceholders.common;
package me.dreamerzero.miniplaceholders.common;
public final class PluginConstants {
public static final String VERSION = "{version}";
@@ -0,0 +1,24 @@
package me.dreamerzero.miniplaceholders.extension;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import me.dreamerzero.miniplaceholders.api.annotation.Extension;
public final class Loader {
private Loader() {}
public static Extension[] loadExtensions(Path extensionsPath) {
List<Extension> extensions = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(extensionsPath, (file) -> file.toString().endsWith(".jar"))) {
for (Path ext : stream) {
}
} catch(IOException e) {
}
}
}
+6 -2
View File
@@ -1,3 +1,7 @@
plugins {
id("miniplaceholders.base")
java.toolchain.languageVersion.set(JavaLanguageVersion.of(11))
tasks.compileJava {
options.encoding = Charsets.UTF_8.name()
options.release.set(11)
}
@@ -1,8 +1,8 @@
package io.github.miniplaceholders.connect;
package me.dreamerzero.miniplaceholders.connect;
public enum InternalPlatform {
PAPER, VELOCITY, KRYPTON, FABRIC, SPONGE;
PAPER, VELOCITY;
private static InternalPlatform actualPlatform;
+3 -2
View File
@@ -1,3 +1,4 @@
module io.github.miniplaceholders.connect {
exports io.github.miniplaceholders.connect;
module me.dreamerzero.miniplaceholders.connect {
//TODO: exports to
exports me.dreamerzero.miniplaceholders.connect;
}
-1
View File
@@ -1 +0,0 @@
/run
-60
View File
@@ -1,60 +0,0 @@
plugins {
id("miniplaceholders.auto.module")
id("fabric-loom")
alias(libs.plugins.shadow)
}
val shade: Configuration by configurations.creating
dependencies {
minecraft(libs.minecraft)
mappings(loom.officialMojangMappings())
modImplementation(libs.fabric.loader)
modImplementation(libs.fabric.api)
includeDependency(libs.adventure.platform.fabric)
includeDependency(libs.luckopermissionsapi)
includeDependency(libs.cloud.fabric)
includeDependency(libs.cloud.core)
includeDependency(libs.cloud.extras)
includeDependency(libs.desertwell)
shadeModule(projects.miniplaceholdersApi)
shadeModule(projects.miniplaceholdersCommon)
shadeModule(projects.miniplaceholdersConnect)
}
fun DependencyHandlerScope.shadeModule(module: ProjectDependency) {
shade(module) {
isTransitive = false
}
implementation(module) {
isTransitive = false
}
}
fun DependencyHandlerScope.includeDependency(dependency: Any) {
modImplementation(dependency)
include(dependency)
}
tasks {
processResources {
filteringCharset = Charsets.UTF_8.name()
filesMatching("fabric.mod.json") {
expand("version" to project.version)
}
}
remapJar {
inputFile.set(shadowJar.get().archiveFile)
archiveFileName.set("MiniPlaceholders-Fabric-${project.version}.jar")
destinationDirectory.set(file("${project.rootDir}/jar"))
}
shadowJar {
configurations = listOf(shade)
}
}
java {
withSourcesJar()
}
@@ -1,113 +0,0 @@
package io.github.miniplaceholders.fabric;
import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator;
import cloud.commandframework.fabric.FabricServerCommandManager;
import io.github.miniplaceholders.api.Expansion;
import io.github.miniplaceholders.common.PlaceholdersCommand;
import io.github.miniplaceholders.common.PlaceholdersPlugin;
import io.github.miniplaceholders.connect.InternalPlatform;
import me.lucko.fabric.api.permissions.v0.Permissions;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.packs.PackResources;
import net.minecraft.world.entity.Entity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class FabricMod implements ModInitializer, PlaceholdersPlugin {
private final Logger logger = LoggerFactory.getLogger("miniplaceholders");
private static final DecimalFormat MSPT_FORMAT = new DecimalFormat("###.###");
private final TickManager tickManager = new TickManager();
private MinecraftServer minecraftServer;
@Override
public void onInitialize() {
logger.info("Starting MiniPlaceholders Fabric");
InternalPlatform.platform(InternalPlatform.FABRIC);
ServerLifecycleEvents.SERVER_STARTING.register(minecraftServer -> {
this.minecraftServer = minecraftServer;
this.loadDefaultExpansions();
});
this.registerPlatformCommand();
}
@Override
public void loadDefaultExpansions() {
Expansion.builder("server")
.globalPlaceholder("name", Tag.selfClosingInserting(Component.text(this.minecraftServer.getServerModName())))
.globalPlaceholder("online", (queue, ctx) -> Tag.preProcessParsed(Integer.toString(this.minecraftServer.getPlayerCount())))
.globalPlaceholder("version", (ctx, queue) -> Tag.selfClosingInserting(Component.text(this.minecraftServer.getServerVersion())))
.globalPlaceholder("max_players", (ctx, queue) -> Tag.selfClosingInserting(Component.text(this.minecraftServer.getMaxPlayers())))
.globalPlaceholder("unique_joins", (queue, ctx) -> Tag.preProcessParsed(Integer.toString(this.minecraftServer.getProfileCache().load().size())))
.globalPlaceholder("tps_1m", (ctx, queue) -> Tag.preProcessParsed(tickManager.getTps1m().formattedAverage()))
.globalPlaceholder("tps_5m", (ctx, queue) -> Tag.preProcessParsed(tickManager.getTps5m().formattedAverage()))
//.globalPlaceholder("tps_15m", (ctx, queue) -> Tag.preProcessParsed(tickManager.getTps15m().formattedAverage()))
.globalPlaceholder("tick_count", (queue, ctx) -> Tag.selfClosingInserting(Component.text(this.minecraftServer.getTickCount())))
.globalPlaceholder("has_whitelist", (queue, ctx) -> Tag.preProcessParsed(Boolean.toString(this.minecraftServer.getPlayerList().isUsingWhitelist())))
.globalPlaceholder("total_chunks", (queue, ctx) -> {
int chunks = 0;
for (final ServerLevel level : this.minecraftServer.getAllLevels()) {
chunks += level.getChunkSource().getLoadedChunksCount();
}
return Tag.preProcessParsed(Integer.toString(chunks));
})
.globalPlaceholder("total_entities", (queue, ctx) -> {
int entities = 0;
for (final ServerLevel level : this.minecraftServer.getAllLevels()) {
for (final Entity ignored : level.getAllEntities()) {
entities++;
}
}
return Tag.preProcessParsed(Integer.toString(entities));
})
.globalPlaceholder("mspt", (queue, ctx) -> Tag.preProcessParsed(MSPT_FORMAT.format(this.minecraftServer.getAverageTickTime())))
.globalPlaceholder("datapack_list", (queue, ctx) ->
Tag.selfClosingInserting(this.minecraftServer.getResourceManager()
.listPacks()
.map(PackResources::packId)
.map(id -> Component.text()
.content("[")
.append(Component.text(id))
.append(Component.text("]"))
.build())
.collect(Component.toComponent(Component.space())))
)
.globalPlaceholder("datapack_count", (queue, ctx) ->
Tag.preProcessParsed(Long.toString(this.minecraftServer.getResourceManager()
.listPacks()
.count()))
)
.build()
.register();
}
@Override
public void registerPlatformCommand() {
final FabricServerCommandManager<CommandSourceStack> commandManager = new FabricServerCommandManager<>(
AsynchronousCommandExecutionCoordinator.simpleCoordinator(),
Function.identity(),
Function.identity()
);
PlaceholdersCommand.<CommandSourceStack>builder()
.hasPermissionCheck((source, permission) -> Permissions.check(source, permission, 4))
.toAudience(string -> this.minecraftServer.getPlayerList().getPlayerByName(string))
.playerSuggestions(() -> new ArrayList<>(List.of(this.minecraftServer.getPlayerNames())))
.manager(commandManager)
.command("miniplaceholders")
.build()
.register();
}
}
@@ -1,59 +0,0 @@
package io.github.miniplaceholders.fabric;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
/**
* Based on the MIT licensed Paper-Server patch "Further improve server tick loop".
*
* @author Daniel Ennis/Aikar
*/
final class RollingAverage {
private static final DecimalFormat TPS_FORMAT = new DecimalFormat("###.##");
static { TPS_FORMAT.setRoundingMode(RoundingMode.HALF_UP); }
private static final int TPS = 20;
private static final long SEC_IN_NANO = 1000000000;
private final int size;
private final BigDecimal[] samples;
private final long[] times;
private long time;
private BigDecimal total;
private int index = 0;
RollingAverage(final int size) {
this.size = size;
this.samples = new BigDecimal[size];
this.times = new long[size];
this.time = size * SEC_IN_NANO;
this.total = dec(TPS).multiply(dec(SEC_IN_NANO)).multiply(dec(size));
for (int i = 0; i < size; i++) {
this.samples[i] = dec(TPS);
this.times[i] = SEC_IN_NANO;
}
}
private static BigDecimal dec(final long t) {
return new BigDecimal(t);
}
void add(final BigDecimal x, final long t) {
this.time -= this.times[this.index];
this.total = this.total.subtract(this.samples[this.index].multiply(dec(this.times[this.index])));
this.samples[this.index] = x;
this.times[this.index] = t;
this.time += t;
this.total = this.total.add(x.multiply(dec(t)));
if (++this.index == this.size) {
this.index = 0;
}
}
double average() {
return this.total.divide(dec(this.time), 30, RoundingMode.HALF_UP).doubleValue();
}
String formattedAverage() {
return TPS_FORMAT.format(average());
}
}
@@ -1,45 +0,0 @@
package io.github.miniplaceholders.fabric;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import java.math.BigDecimal;
import java.math.RoundingMode;
final class TickManager {
private static final int TICK_DURATION = 20;
private static final BigDecimal TPS_BASE = new BigDecimal(1E9).multiply(new BigDecimal(TICK_DURATION));
private final RollingAverage tps1m = new RollingAverage(60);
private final RollingAverage tps5m = new RollingAverage(60 * 5);
private final RollingAverage tps15m = new RollingAverage(60 * 15);
private long lastStartTick = 0;
private long lastEndTick = 0;
TickManager() {
ServerTickEvents.START_SERVER_TICK.register(server -> this.lastStartTick = System.nanoTime());
ServerTickEvents.END_SERVER_TICK.register(server -> {
if (server.getTickCount() % TICK_DURATION == 0) {
final long diff = lastStartTick - lastEndTick;
final BigDecimal currentTps = TPS_BASE.divide(new BigDecimal(diff), 30, RoundingMode.HALF_UP);
this.tps1m.add(currentTps, diff);
this.tps5m.add(currentTps, diff);
this.tps15m.add(currentTps, diff);
this.lastEndTick = System.nanoTime();
}
});
}
public RollingAverage getTps1m() {
return tps1m;
}
public RollingAverage getTps5m() {
return tps5m;
}
public RollingAverage getTps15m() {
return tps15m;
}
}
-29
View File
@@ -1,29 +0,0 @@
{
"schemaVersion": 1,
"id": "miniplaceholders",
"version": "${version}",
"name": "MiniPlaceholders",
"description": "MiniMessage Component-based Placeholders for PaperMC, Fabric, Krypton and Velocity platforms",
"authors": [
"4drian3d"
],
"contact": {
"homepage": "https://github.com/MiniPlaceholders/MiniPlaceholders",
"sources": "https://github.com/MiniPlaceholders/MiniPlaceholders",
"issues": "https://github.com/MiniPlaceholders/MiniPlaceholders/issues"
},
"license": "GPL",
"environment": "server",
"entrypoints": {
"main": [
"io.github.miniplaceholders.fabric.FabricMod"
]
},
"depends": {
"fabricloader": ">=0.14.19",
"fabric": "*",
"java": ">=17",
"minecraft": ">=1.19.4",
"fabric-permissions-api-v0": "*"
}
}
-5
View File
@@ -1,5 +0,0 @@
group = io.github.miniplaceholders
version = 2.2.0
description = MiniMessage Component-based Placeholders for Paper, Folia, Fabric, Sponge, velocity and Krypton platforms
org.gradle.jvmargs=-Xmx2G
-78
View File
@@ -1,78 +0,0 @@
metadata.format.version = "1.1"
[versions]
velocity = "3.2.0-SNAPSHOT"
paper = "1.19.4-R0.1-SNAPSHOT"
krypton = "cbfaff4aa4"
minecraft = "1.19.4"
runtask = "2.1.0"
pluginyml = "0.5.3"
userdev = "1.5.5"
blossom = "1.3.1"
indra = "3.0.1"
shadow = "8.1.1"
jmh = "0.7.1"
dokka = "1.8.10"
cloud = "1.8.3"
adventure = "4.13.1"
adventurefabric = "5.8.0"
brigadier = "1.0.500"
kotlin="1.8.21"
fabric-api = "0.80.1+1.20"
fabric-loader = "0.14.19"
desertwell = "2.0.4"
[libraries]
velocity = { group = "com.velocitypowered", name = "velocity-api", version.ref = "velocity" }
paper = { group = "io.papermc.paper", name = "paper-api", version.ref = "paper" }
krypton-server = { group = "org.kryptonmc", name = "krypton-server", version.ref = "krypton" }
minecraft = { group = "com.mojang", name = "minecraft", version.ref = "minecraft" }
fabric-api = { group = "net.fabricmc.fabric-api", name = "fabric-api", version.ref = "fabric-api" }
fabric-loader = { group = "net.fabricmc", name = "fabric-loader", version.ref = "fabric-loader" }
luckopermissionsapi = { group = "me.lucko", name = "fabric-permissions-api", version = "0.2-SNAPSHOT" }
adventure-api = { group = "net.kyori", name = "adventure-api", version.ref = "adventure" }
adventure-minimesssage = { group = "net.kyori", name = "adventure-text-minimessage", version.ref = "adventure" }
adventure-platform-fabric = { group = "net.kyori", name = "adventure-platform-fabric", version.ref = "adventurefabric" }
adventure-serializer-legacy = { group = "net.kyori", name = "adventure-text-serializer-legacy", version.ref = "adventure" }
adventure-serializer-plain = { group = "net.kyori", name = "adventure-text-serializer-plain", version.ref = "adventure" }
cloud-core = { group = "cloud.commandframework", name = "cloud-core", version.ref = "cloud" }
cloud-annotations = { group = "cloud.commandframework", name = "cloud-annotations", version.ref = "cloud" }
cloud-velocity = { group = "cloud.commandframework", name = "cloud-velocity", version.ref = "cloud" }
cloud-paper = { group = "cloud.commandframework", name = "cloud-paper", version.ref = "cloud" }
cloud-fabric = { group = "cloud.commandframework", name = "cloud-fabric", version.ref = "cloud" }
cloud-sponge = { group = "cloud.commandframework", name = "cloud-sponge", version = "1.8.0-SNAPSHOT" }
cloud-extras = { group = "cloud.commandframework", name = "cloud-minecraft-extras", version.ref = "cloud" }
brigadier = { group = "com.mojang", name = "brigadier", version.ref = "brigadier" }
krypton-annotation = { group = "org.kryptonmc", name = "krypton-annotation-processor", version.ref = "krypton" }
plugin-shadow = { group = "com.github.johnrengelman", name = "shadow", version.ref = "shadow" }
plugin-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
plugin-indra-common = { module = "net.kyori:indra-common", version.ref = "indra" }
plugin-indra-spotless = { module = "net.kyori:indra-licenser-spotless", version.ref = "indra" }
plugin-dokka = "org.jetbrains.dokka:dokka-gradle-plugin:1.8.10"
desertwell = { group = "net.william278", name = "DesertWell", version.ref = "desertwell" }
junit-bom = "org.junit:junit-bom:5.9.3"
[plugins]
pluginyml = { id = "net.minecrell.plugin-yml.bukkit", version.ref = "pluginyml" }
userdev = { id = "io.papermc.paperweight.userdev", version.ref = "userdev" }
runpaper = { id = "xyz.jpenilla.run-paper", version.ref = "runtask" }
runvelocity = { id = "xyz.jpenilla.run-velocity", version.ref = "runtask" }
blossom = { id = "net.kyori.blossom", version.ref = "blossom" }
shadow = { id = "com.github.johnrengelman.shadow", version.ref = "shadow" }
jmh = { id = "me.champeau.jmh", version.ref = "jmh" }
dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" }
Binary file not shown.
+1 -2
View File
@@ -1,6 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
networkTimeout=10000
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+12 -23
View File
@@ -1,7 +1,7 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -32,10 +32,10 @@
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
@@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@@ -80,11 +80,14 @@ do
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -140,16 +143,12 @@ fi
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -194,10 +193,6 @@ if "$cygwin" || "$msys" ; then
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
@@ -210,12 +205,6 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
Vendored
+89 -92
View File
@@ -1,92 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+2
View File
@@ -0,0 +1,2 @@
jdk:
- openjdk17
-19
View File
@@ -1,19 +0,0 @@
plugins {
kotlin("jvm")
id("miniplaceholders.kotlin.publish")
}
dependencies {
compileOnly(kotlin("stdlib"))
compileOnly(libs.adventure.api)
compileOnly(libs.adventure.minimesssage)
compileOnlyApi(projects.miniplaceholdersApi)
}
kotlin {
explicitApi()
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
@@ -1,16 +0,0 @@
package io.github.miniplaceholders.kotlin
import io.github.miniplaceholders.api.Expansion
/**
* Create a new Expansion
*
* @param name the expansion name
* @param builder a builder-like function to create an Expansion from a builder
* @return a new expansion
* @since 1.4.0
* @see Expansion.builder
* @see Expansion.Builder.build
* */
public fun expansion(name: String, builder: Expansion.Builder.() -> Expansion.Builder): Expansion
= builder(Expansion.builder(name)).build()
@@ -1,25 +0,0 @@
package io.github.miniplaceholders.kotlin
import net.kyori.adventure.text.ComponentLike
import net.kyori.adventure.text.minimessage.tag.Tag
/**
* Converts a [ComponentLike] to a [Tag] of type selfClosingInserting
*
* @see Tag.selfClosingInserting
*/
public fun ComponentLike.asClosingTag(): Tag = Tag.selfClosingInserting(this)
/**
* Converts a [ComponentLike] to a [Tag] of type inserting
*
* @see Tag.inserting
*/
public fun ComponentLike.asInsertingTag(): Tag = Tag.inserting(this)
/**
* Converts a [ComponentLike] to a [Tag] of type preProcessParsed
*
* @see Tag.preProcessParsed
*/
public fun String.asPreProcessTag(): Tag = Tag.preProcessParsed(this)
@@ -1,32 +0,0 @@
package io.github.miniplaceholders.kotlin
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
/**
* Check if this TagResolver is an instance of TagResolver.empty(),
* that is, it will always return null
* @return true if the TagResolver is the same as TagResolver.empty(), else false
* @since 1.4.0
* @see TagResolver.empty
*/
public fun TagResolver.isEmpty(): Boolean = this == TagResolver.empty()
/**
* Checks if this TagResolver is not a TagResolver.empty()
* @return false if the TagResolver is the same as TagResolver.empty(), else true
* @since 1.4.0
* @see TagResolver.empty
*/
public fun TagResolver.isNotEmpty(): Boolean = this != TagResolver.empty()
/**
* Applies a TagResolver to a TagResolver.Builder in case it is not a TagResolver.empty()
* @param resolver the resolver to check
* @since 1.4.0
* @see TagResolver.isNotEmpty
*/
public fun TagResolver.Builder.applyIfNotEmpty(resolver: TagResolver) {
if (resolver.isNotEmpty()) {
resolver(resolver)
}
}
-27
View File
@@ -1,27 +0,0 @@
plugins {
kotlin("jvm")
kotlin("kapt")
alias(libs.plugins.shadow)
}
repositories {
maven("https://repo.kryptonmc.org/releases")
maven("https://s01.oss.sonatype.org/content/repositories/snapshots/")
maven("https://repo.kryptonmc.org/snapshots")
}
dependencies {
compileOnly(libs.krypton.server)
compileOnly(kotlin("stdlib"))
kapt(libs.krypton.annotation)
implementation(projects.miniplaceholdersCommon)
implementation(projects.miniplaceholdersApi)
implementation(projects.miniplaceholdersConnect)
implementation(projects.miniplaceholdersKotlinExt)
}
kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
@@ -1,85 +0,0 @@
package io.github.miniplaceholders.krypton
import com.google.inject.Inject
import io.github.miniplaceholders.api.utils.TagsUtils
import io.github.miniplaceholders.common.PlaceholdersCommand
import io.github.miniplaceholders.common.PlaceholdersPlugin
import io.github.miniplaceholders.common.PluginConstants
import io.github.miniplaceholders.connect.InternalPlatform
import io.github.miniplaceholders.kotlin.asClosingTag
import io.github.miniplaceholders.kotlin.expansion
import net.kyori.adventure.text.Component
import org.apache.logging.log4j.Logger
import org.kryptonmc.api.command.BrigadierCommand
import org.kryptonmc.api.command.CommandExecutionContext
import org.kryptonmc.api.event.Listener
import org.kryptonmc.api.event.server.ServerStartEvent
import org.kryptonmc.api.plugin.annotation.Plugin
import org.kryptonmc.krypton.KryptonServer
import org.kryptonmc.krypton.command.KryptonCommandMeta
@Plugin(
name = "MiniPlaceholders",
id = "miniplaceholders",
version = PluginConstants.VERSION,
authors = ["4drian3d"]
)
class KotlinKryptonPlugin @Inject constructor(
private val server: KryptonServer,
private val logger: Logger
) : PlaceholdersPlugin {
init {
InternalPlatform.platform(InternalPlatform.KRYPTON)
}
@Listener
@Suppress("UNUSED")
fun onServerStart(event: ServerStartEvent) {
logger.info("Starting MiniPlaceholders Krypton")
this.loadDefaultExpansions()
this.registerPlatformCommand()
}
override fun loadDefaultExpansions() {
expansion("server") {
globalPlaceholder("total_entities") { _, _ ->
var entityCount = 0
for ((_, value) in server.worldManager.worlds) {
entityCount += value.entities.size
}
Component.text(entityCount).asClosingTag()
}
globalPlaceholder("total_chunks") { _, _ ->
var chunkCount = 0
for ((_, value) in server.worldManager.worlds) {
chunkCount += value.chunks.size
}
Component.text(chunkCount).asClosingTag()
}
globalPlaceholder("name", TagsUtils.staticTag(server.platform.name))
globalPlaceholder("online") { queue, _ ->
if (queue.hasNext()) {
val worldName = queue.pop().value()
val players = server.players.filter { it.world.name == worldName }
return@globalPlaceholder Component.text(players.joinToString(", ")).asClosingTag()
}
Component.text(server.players.size).asClosingTag()
}
globalPlaceholder("version", TagsUtils.staticTag(server.platform.version))
globalPlaceholder("max_players", Component.text(server.config.maxPlayers).asClosingTag())
}.register()
}
override fun registerPlatformCommand() {
/*val command = PlaceholdersCommand.builder<CommandExecutionContext>()
.fromSourceToAudience { it.sender }
.playerSuggestions { server.players.map { it.name } }
.toAudience { server.getPlayer(it) }
.build()
val brigadierCMD = BrigadierCommand.of(command.asNode("miniplaceholders"))
val meta = KryptonCommandMeta.Builder("miniplaceholders").build()
server.commandManager.register(brigadierCMD, meta)*/
}
}
+29 -14
View File
@@ -1,25 +1,40 @@
plugins {
id("miniplaceholders.auto.module")
id("miniplaceholders.shadow")
alias(libs.plugins.runpaper)
id("net.minecrell.plugin-yml.bukkit") version "0.5.2"
id("io.papermc.paperweight.userdev") version "1.3.8"
id("xyz.jpenilla.run-paper") version "1.0.6"
}
dependencies {
compileOnly(libs.paper)
implementation(projects.miniplaceholdersCommon)
implementation(projects.miniplaceholdersApi)
implementation(projects.miniplaceholdersConnect)
implementation(libs.cloud.paper)
compileOnly(project(":miniplaceholders-common"))
compileOnly(project(":miniplaceholders-api"))
compileOnly(project(":miniplaceholders-connect"))
paperDevBundle("1.19.1-R0.1-SNAPSHOT")
}
val pluginVersion: String = version as String
bukkit {
name = "MiniPlaceholders"
main = "me.dreamerzero.miniplaceholders.paper.PaperPlugin"
apiVersion = "1.18"
website = "https://github.com/4drian3d/MiniPlaceholders"
authors = listOf("4drian3d")
version = pluginVersion
}
java.toolchain.languageVersion.set(JavaLanguageVersion.of(17))
tasks {
runServer {
minecraftVersion("1.19.4")
assemble {
dependsOn(reobfJar)
}
processResources {
filesMatching("paper-plugin.yml") {
expand("version" to project.version)
}
compileJava {
options.encoding = Charsets.UTF_8.name()
options.release.set(17)
}
runServer {
minecraftVersion("1.19.1")
}
}
@@ -1,42 +1,38 @@
package io.github.miniplaceholders.paper;
import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator;
import cloud.commandframework.paper.PaperCommandManager;
import io.github.miniplaceholders.api.Expansion;
import io.github.miniplaceholders.api.utils.TagsUtils;
import io.github.miniplaceholders.common.PlaceholdersCommand;
import io.github.miniplaceholders.common.PlaceholdersPlugin;
import io.github.miniplaceholders.connect.InternalPlatform;
import io.papermc.paper.datapack.Datapack;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.minimessage.tag.Tag;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permissible;
import org.bukkit.plugin.java.JavaPlugin;
package me.dreamerzero.miniplaceholders.paper;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.function.Function;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
public final class PaperPlugin extends JavaPlugin implements PlaceholdersPlugin {
private static final DecimalFormat TPS_FORMAT = new DecimalFormat("###.##");
private static final DecimalFormat MSPT_FORMAT = new DecimalFormat("###.###");
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
static {
InternalPlatform.platform(InternalPlatform.PAPER);
TPS_FORMAT.setRoundingMode(RoundingMode.HALF_UP);
MSPT_FORMAT.setRoundingMode(RoundingMode.HALF_UP);
}
import io.papermc.paper.datapack.Datapack;
import me.dreamerzero.miniplaceholders.api.Expansion;
import me.dreamerzero.miniplaceholders.api.utils.TagsUtils;
import me.dreamerzero.miniplaceholders.common.PlaceholdersCommand;
import me.dreamerzero.miniplaceholders.common.PlaceholdersPlugin;
import me.dreamerzero.miniplaceholders.connect.InternalPlatform;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.server.MinecraftServer;
public final class PaperPlugin extends JavaPlugin implements PlaceholdersPlugin, Listener {
private final DecimalFormat tpsFormat = new DecimalFormat("###.##");
private final DecimalFormat msptFormat = new DecimalFormat("###.###");
@Override
public void onEnable(){
this.getSLF4JLogger().info("Starting MiniPlaceholders Paper");
InternalPlatform.platform(InternalPlatform.PAPER);
this.getServer().getPluginManager().registerEvents(this, this);
tpsFormat.setRoundingMode(RoundingMode.HALF_UP);
msptFormat.setRoundingMode(RoundingMode.HALF_UP);
this.loadDefaultExpansions();
this.registerPlatformCommand();
}
@@ -49,28 +45,28 @@ public final class PaperPlugin extends JavaPlugin implements PlaceholdersPlugin
.globalPlaceholder("version", TagsUtils.staticTag(this.getServer().getVersion()))
.globalPlaceholder("max_players", (queue, ctx) -> TagsUtils.staticTag(Component.text(this.getServer().getMaxPlayers())))
.globalPlaceholder("unique_joins", (queue, ctx) -> TagsUtils.staticTag(Component.text(this.getServer().getOfflinePlayers().length)))
.globalPlaceholder("tps_1", (queue, ctx) -> TagsUtils.staticTag(TPS_FORMAT.format(this.getServer().getTPS()[0])))
.globalPlaceholder("tps_5", (queue, ctx) -> TagsUtils.staticTag(TPS_FORMAT.format(this.getServer().getTPS()[1])))
.globalPlaceholder("tps_15", (queue, ctx) -> TagsUtils.staticTag(TPS_FORMAT.format(this.getServer().getTPS()[2])))
.globalPlaceholder("tps_1", (queue, ctx) -> TagsUtils.staticTag(tpsFormat.format(this.getServer().getTPS()[0])))
.globalPlaceholder("tps_5", (queue, ctx) -> TagsUtils.staticTag(tpsFormat.format(this.getServer().getTPS()[1])))
.globalPlaceholder("tps_15", (queue, ctx) -> TagsUtils.staticTag(tpsFormat.format(this.getServer().getTPS()[2])))
.globalPlaceholder("has_whitelist", (queue, ctx) -> TagsUtils.staticTag(Component.text(this.getServer().hasWhitelist())))
.globalPlaceholder("total_chunks", (queue, ctx) -> {
int chunkCount = 0;
for (World world : this.getServer().getWorlds()){
for(World world : this.getServer().getWorlds()){
chunkCount += world.getLoadedChunks().length;
}
return TagsUtils.staticTag(Component.text(chunkCount));
})
.globalPlaceholder("total_entities", (queue, ctx) -> {
int entityCount = 0;
for (World world : this.getServer().getWorlds()){
for(World world : this.getServer().getWorlds()){
entityCount += world.getEntityCount();
}
return TagsUtils.staticTag(Component.text(entityCount));
})
.globalPlaceholder("mspt", (queue, ctx) -> TagsUtils.staticTag(MSPT_FORMAT.format(this.getServer().getAverageTickTime())))
.globalPlaceholder("mspt", (queue, ctx) -> TagsUtils.staticTag(msptFormat.format(this.getServer().getAverageTickTime())))
.globalPlaceholder("datapack_list", (queue, ctx) -> {
final TextComponent.Builder builder = Component.text();
for (Datapack datapack : this.getServer().getDatapackManager().getEnabledPacks()){
TextComponent.Builder builder = Component.text();
for(Datapack datapack : this.getServer().getDatapackManager().getEnabledPacks()){
builder.append(Component.text("[").append(Component.text(datapack.getName()).append(Component.text("] "))));
}
return Tag.selfClosingInserting(builder.build());
@@ -81,30 +77,16 @@ public final class PaperPlugin extends JavaPlugin implements PlaceholdersPlugin
}
@Override
@SuppressWarnings({"sonarlint(java:s1874)"})
@SuppressWarnings({"sonarlint(java:s1874)", "deprecation", /*TODO: replace with Java(536871800) */ "all"})
public void registerPlatformCommand() {
try {
PaperCommandManager<CommandSender> commandManager = new PaperCommandManager<>(
this,
AsynchronousCommandExecutionCoordinator.simpleCoordinator(),
Function.identity(),
Function.identity()
MinecraftServer.getServer()
.vanillaCommandDispatcher
.getDispatcher()
.register(new PlaceholdersCommand<>(
() -> this.getServer().getOnlinePlayers().stream().map(Player::getName).toList(),
(String st) -> this.getServer().getPlayer(st),
CommandSourceStack::getBukkitSender
).placeholderTestBuilder("miniplaceholders")
);
commandManager.registerBrigadier();
PlaceholdersCommand.<CommandSender>builder()
.playerSuggestions(() -> getServer().getOnlinePlayers()
.stream()
.map(Player::getName)
.collect(Collectors.toCollection(ArrayList::new)))
.toAudience(st -> getServer().getPlayer(st))
.hasPermissionCheck(Permissible::hasPermission)
.manager(commandManager)
.command("miniplaceholders")
.build()
.register();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -1,6 +0,0 @@
name: MiniPlaceholders
version: '${version}'
main: io.github.miniplaceholders.paper.PaperPlugin
description: MiniMessage Component-based Placeholders for PaperMC, Krypton and Velocity platforms
api-version: '1.19'
folia-supported: true
-7
View File
@@ -1,7 +0,0 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base"
],
"ignoreDeps": ["krypton", "krypton-api", "krypton-annotation-processor", "krypton-server"]
}
+9 -44
View File
@@ -1,51 +1,16 @@
@file:Suppress("UnstableApiUsage")
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")
pluginManagement {
repositories {
gradlePluginPortal()
maven("https://papermc.io/repo/repository/maven-public/")
}
}
rootProject.name = "miniplaceholders-parent"
pluginManagement {
includeBuild("build-logic")
repositories {
gradlePluginPortal()
mavenCentral()
maven("https://maven.fabricmc.net/")
maven("https://maven.quiltmc.org/repository/release/")
}
}
val modules = listOf("connect", "api", "common", "paper", "velocity")
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
maven("https://papermc.io/repo/repository/maven-public/")
maven("https://repo.maven.apache.org/maven2/")
maven("https://jitpack.io") {
mavenContent {
includeGroup("net.william278")
}
}
maven("https://oss.sonatype.org/content/repositories/snapshots")
maven("https://repo.jpenilla.xyz/snapshots/")
}
}
plugins {
id("fabric-loom") version "1.2.6"
id("org.spongepowered.gradle.plugin") version "2.1.1"
id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0"
}
arrayOf(
"connect",
"api",
"kotlin-ext",
"common",
"paper",
"velocity",
//"krypton",
"fabric",
"sponge"
).forEach {
modules.forEach {
include("miniplaceholders-$it")
project(":miniplaceholders-$it").projectDir = file(it)
}
-2
View File
@@ -1,2 +0,0 @@
# run-paper files
/run
-47
View File
@@ -1,47 +0,0 @@
import org.spongepowered.gradle.plugin.config.PluginLoaders
import org.spongepowered.plugin.metadata.model.PluginDependency
plugins {
id("miniplaceholders.auto.module")
id("miniplaceholders.shadow")
id("org.spongepowered.gradle.plugin")
}
dependencies {
implementation(projects.miniplaceholdersCommon)
implementation(projects.miniplaceholdersApi)
implementation(projects.miniplaceholdersConnect)
implementation(libs.cloud.sponge)
}
sponge {
apiVersion("8.1.0")
license("GPL-3")
loader {
name(PluginLoaders.JAVA_PLAIN)
version("1.0")
}
plugin("miniplaceholders") {
displayName("MiniPlaceholders")
entrypoint("io.github.miniplaceholders.sponge.SpongePlugin")
description(project.description)
links {
homepage("https://github.com/MiniPlaceholders/MiniPlaceholders")
source("https://github.com/MiniPlaceholders/MiniPlaceholders")
issues("https://github.com/MiniPlaceholders/MiniPlaceholders/issues")
}
contributor("4drian3d") {
description("Lead Developer")
}
dependency("spongeapi") {
loadOrder(PluginDependency.LoadOrder.AFTER)
optional(false)
}
}
}
tasks {
shadowJar {
exclude("io/leangen/geantyref/**")
}
}
@@ -1,116 +0,0 @@
package io.github.miniplaceholders.sponge;
import cloud.commandframework.execution.CommandExecutionCoordinator;
import cloud.commandframework.sponge.SpongeCommandManager;
import com.google.inject.Inject;
import io.github.miniplaceholders.api.Expansion;
import io.github.miniplaceholders.api.utils.TagsUtils;
import io.github.miniplaceholders.common.PlaceholdersCommand;
import io.github.miniplaceholders.common.PlaceholdersPlugin;
import io.github.miniplaceholders.connect.InternalPlatform;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.text.Component;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.Server;
import org.spongepowered.api.command.Command;
import org.spongepowered.api.command.CommandCause;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.lifecycle.RegisterCommandEvent;
import org.spongepowered.api.event.lifecycle.StartingEngineEvent;
import org.spongepowered.api.world.server.ServerWorld;
import org.spongepowered.plugin.PluginContainer;
import org.spongepowered.plugin.builtin.jvm.Plugin;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@Plugin("miniplaceholders")
public class SpongePlugin implements PlaceholdersPlugin {
@Inject
private PluginContainer pluginContainer;
@Inject
private Logger logger;
private Server server;
@Listener
public void onServerStart(final StartingEngineEvent<Server> event) {
this.server = event.engine();
logger.info("Starting MiniPlaceholders Sponge");
InternalPlatform.platform(InternalPlatform.SPONGE);
this.loadDefaultExpansions();
}
private final AtomicInteger registration = new AtomicInteger(0);
@Listener
public void onCommandRegister(final RegisterCommandEvent<Command.Parameterized> event) {
if (registration.getAndIncrement() == 0) {
this.registerPlatformCommand();
}
}
@Override
public void loadDefaultExpansions() {
Expansion.builder("server")
.globalPlaceholder("name", TagsUtils.staticTag("Sponge"))
.globalPlaceholder("online", (queue, ctx) -> TagsUtils.staticTag(Component.text(server.onlinePlayers().size())))
.globalPlaceholder("max_players", (queue, ctx) -> TagsUtils.staticTag(Component.text(server.maxPlayers())))
.globalPlaceholder("unique_joins", (queue, ctx) -> TagsUtils.staticTag(Component.text(server.userManager().streamAll().count())))
.globalPlaceholder("has_whitelist", (queue, ctx) -> TagsUtils.staticTag(Component.text(server.isWhitelistEnabled())))
.globalPlaceholder("total_chunks", (queue, ctx) -> {
int chunkCount = 0;
for (ServerWorld world : server.worldManager().worlds()){
chunkCount += world.entities().size();
}
return TagsUtils.staticTag(Component.text(chunkCount));
})
.globalPlaceholder("total_entities", (queue, ctx) -> {
int entityCount = 0;
for (ServerWorld world : server.worldManager().worlds()){
entityCount += world.entities().size();
}
return TagsUtils.staticTag(Component.text(entityCount));
})
.globalPlaceholder("mspt", (queue, ctx) -> TagsUtils.staticTag(Component.text(server.averageTickTime())))
.build()
.register();
}
@Override
public void registerPlatformCommand() {
final SpongeCommandManager<AudienceHolder> commandManager = new SpongeCommandManager<>(
pluginContainer,
CommandExecutionCoordinator.simpleCoordinator(),
AudienceHolder::cause,
AudienceHolder::new
);
PlaceholdersCommand.<AudienceHolder>builder()
.manager(commandManager)
.command("miniplaceholders")
.playerSuggestions(() -> server.onlinePlayers()
.stream()
.map(ServerPlayer::name)
.collect(Collectors.toCollection(ArrayList::new)))
.toAudience(st -> server.player(st).orElse(null))
.hasPermissionCheck((holder, permission) -> holder.cause.hasPermission(permission))
.build()
.register();
}
record AudienceHolder(@NotNull CommandCause cause) implements ForwardingAudience.Single {
@Override
public @NotNull Audience audience() {
return cause.audience();
}
}
}
-2
View File
@@ -1,2 +0,0 @@
#run velocity files
/run
+12 -17
View File
@@ -1,20 +1,15 @@
plugins {
id("miniplaceholders.shadow")
id("miniplaceholders.auto.module")
alias(libs.plugins.runvelocity)
}
dependencies {
compileOnly(libs.velocity)
annotationProcessor(libs.velocity)
implementation(projects.miniplaceholdersCommon)
implementation(projects.miniplaceholdersApi)
implementation(projects.miniplaceholdersConnect)
implementation(libs.cloud.velocity)
compileOnly("com.velocitypowered:velocity-api:3.1.2-SNAPSHOT")
annotationProcessor("com.velocitypowered:velocity-api:3.1.2-SNAPSHOT")
compileOnly(project(":miniplaceholders-common"))
compileOnly(project(":miniplaceholders-api"))
compileOnly(project(":miniplaceholders-connect"))
}
tasks {
runVelocity {
velocityVersion(libs.versions.velocity.get())
}
}
java.toolchain.languageVersion.set(JavaLanguageVersion.of(17))
tasks.compileJava {
options.encoding = Charsets.UTF_8.name()
options.release.set(17)
}
@@ -1,102 +0,0 @@
package io.github.miniplaceholders.velocity;
import cloud.commandframework.execution.CommandExecutionCoordinator;
import cloud.commandframework.velocity.CloudInjectionModule;
import cloud.commandframework.velocity.VelocityCommandManager;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import io.github.miniplaceholders.api.Expansion;
import io.github.miniplaceholders.api.utils.Components;
import io.github.miniplaceholders.api.utils.TagsUtils;
import io.github.miniplaceholders.common.PlaceholdersCommand;
import io.github.miniplaceholders.common.PlaceholdersPlugin;
import io.github.miniplaceholders.common.PluginConstants;
import io.github.miniplaceholders.connect.InternalPlatform;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.tag.Tag;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.function.Function;
import java.util.stream.Collectors;
@Plugin(
name = "MiniPlaceholders",
id = "miniplaceholders",
version = PluginConstants.VERSION,
authors = {"4drian3d"}
)
public final class VelocityPlugin implements PlaceholdersPlugin {
private final Logger logger;
private final ProxyServer proxy;
@Inject
private Injector injector;
@Inject
public VelocityPlugin(final Logger logger, final ProxyServer proxy) {
this.logger = logger;
this.proxy = proxy;
}
@Subscribe
public void onProxyInitialize(final ProxyInitializeEvent event) {
logger.info("Starting MiniPlaceholders Velocity");
InternalPlatform.platform(InternalPlatform.VELOCITY);
this.loadDefaultExpansions();
this.registerPlatformCommand();
}
@Override
public void loadDefaultExpansions() {
Expansion.builder("proxy")
.globalPlaceholder("online_players", (queue, ctx) -> {
if (queue.hasNext()) {
String server = queue.pop().value();
return Tag.selfClosingInserting(Component.text(proxy.getServer(server).map(sv -> sv.getPlayersConnected().size()).orElse(0)));
}
return Tag.selfClosingInserting(Component.text(proxy.getPlayerCount()));
})
.globalPlaceholder("server_count", (queue, ctx) -> Tag.selfClosingInserting(Component.text(proxy.getAllServers().size())))
.globalPlaceholder("is_player_online", (queue, ctx) -> {
String playerName = queue.popOr(() -> "you need to introduce an argument").value();
return TagsUtils.staticTag(proxy.getPlayer(playerName).isPresent() ? Components.YES_COMPONENT : Components.NO_COMPONENT);
})
.globalPlaceholder("version", TagsUtils.staticTag(proxy.getVersion().getVersion()))
.build()
.register();
}
@Override
public void registerPlatformCommand() {
injector = injector.createChildInjector(
new CloudInjectionModule<>(
CommandSource.class,
CommandExecutionCoordinator.simpleCoordinator(),
Function.identity(),
Function.identity()
)
);
final VelocityCommandManager<CommandSource> commandManager = injector.getInstance(
Key.get(new TypeLiteral<>() {})
);
PlaceholdersCommand.<CommandSource>builder()
.playerSuggestions(() -> proxy.getAllPlayers()
.stream()
.map(Player::getUsername)
.collect(Collectors.toCollection(ArrayList::new)))
.toAudience(st -> proxy.getPlayer(st).orElse(null))
.command("vminiplaceholders")
.manager(commandManager)
.build().register();
}
}
@@ -0,0 +1,79 @@
package me.dreamerzero.miniplaceholders.velocity;
import com.google.inject.Inject;
import com.velocitypowered.api.command.BrigadierCommand;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import org.slf4j.Logger;
import me.dreamerzero.miniplaceholders.api.Expansion;
import me.dreamerzero.miniplaceholders.api.utils.Components;
import me.dreamerzero.miniplaceholders.api.utils.TagsUtils;
import me.dreamerzero.miniplaceholders.common.PlaceholdersCommand;
import me.dreamerzero.miniplaceholders.common.PlaceholdersPlugin;
import me.dreamerzero.miniplaceholders.common.PluginConstants;
import me.dreamerzero.miniplaceholders.connect.InternalPlatform;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.tag.Tag;
@Plugin(
name = "MiniPlaceholders",
id = "miniplaceholders",
version = PluginConstants.VERSION,
authors = {"4drian3d"}
)
public final class VelocityPlugin implements PlaceholdersPlugin {
private final Logger logger;
private final ProxyServer proxy;
@Inject
public VelocityPlugin(final Logger logger, final ProxyServer proxy) {
this.logger = logger;
this.proxy = proxy;
}
@Subscribe
public void onProxyInitialize(final ProxyInitializeEvent event) {
logger.info("Starting MiniPlaceholders Velocity");
InternalPlatform.platform(InternalPlatform.VELOCITY);
this.loadDefaultExpansions();
this.registerPlatformCommand();
}
@Override
public void loadDefaultExpansions() {
Expansion.builder("proxy")
.globalPlaceholder("online_players", (queue, ctx) -> {
if(queue.hasNext()){
String server = queue.pop().value();
return Tag.selfClosingInserting(Component.text(proxy.getServer(server).map(sv -> sv.getPlayersConnected().size()).orElse(0)));
}
return Tag.selfClosingInserting(Component.text(proxy.getPlayerCount()));
})
.globalPlaceholder("server_count", (queue, ctx) -> Tag.selfClosingInserting(Component.text(proxy.getAllServers().size())))
.globalPlaceholder("is_player_online", (queue, ctx) -> {
String playerName = queue.popOr(() -> "you need to introduce an argument").value();
return TagsUtils.staticTag(proxy.getPlayer(playerName).isPresent() ? Components.YES_COMPONENT : Components.NO_COMPONENT);
})
.globalPlaceholder("version", TagsUtils.staticTag(proxy.getVersion().getVersion()))
.build()
.register();
}
@Override
public void registerPlatformCommand() {
final BrigadierCommand brigadierCMD = new BrigadierCommand(
new PlaceholdersCommand<CommandSource>(
() -> proxy.getAllPlayers().stream().map(Player::getUsername).toList(),
(String st) -> proxy.getPlayer(st).orElse(null))
.placeholderTestCommand("vminiplaceholders"));
proxy.getCommandManager().register(brigadierCMD);
}
}