Compare commits

..

3 Commits

Author SHA1 Message Date
Auxilor
55fc6d762f Updated folia scheduler 2023-05-09 13:48:57 +01:00
Auxilor
b9c5eb2b4e Merge branch 'master' into folia
# Conflicts:
#	eco-core/core-plugin/build.gradle
2023-05-09 13:00:09 +01:00
Auxilor
393d0031c7 Added folia support 2023-03-12 12:11:12 +00:00
49 changed files with 326 additions and 631 deletions

View File

@@ -135,14 +135,6 @@ public interface Eco {
@NotNull @NotNull
Logger createLogger(@NotNull EcoPlugin plugin); Logger createLogger(@NotNull EcoPlugin plugin);
/**
* Get NOOP logger.
*
* @return The logger.
*/
@NotNull
Logger getNOOPLogger();
/** /**
* Create a PAPI integration. * Create a PAPI integration.
* *
@@ -178,7 +170,7 @@ public interface Eco {
* @return The PluginCommandBase implementation * @return The PluginCommandBase implementation
*/ */
@NotNull @NotNull
PluginCommandBase createPluginCommand(@NotNull PluginCommandBase parentDelegate, PluginCommandBase createPluginCommand(@NotNull CommandBase parentDelegate,
@NotNull EcoPlugin plugin, @NotNull EcoPlugin plugin,
@NotNull String name, @NotNull String name,
@NotNull String permission, @NotNull String permission,
@@ -401,6 +393,15 @@ public interface Eco {
@NotNull @NotNull
ServerProfile getServerProfile(); ServerProfile getServerProfile();
/**
* Unload a player profile from memory.
* <p>
* This will not save the profile first.
*
* @param uuid The uuid.
*/
void unloadPlayerProfile(@NotNull UUID uuid);
/** /**
* Create dummy entity - never spawned, exists purely in code. * Create dummy entity - never spawned, exists purely in code.
* *

View File

@@ -126,7 +126,7 @@ public abstract class EcoPlugin extends JavaPlugin implements PluginLike, Regist
/** /**
* The logger for the plugin. * The logger for the plugin.
*/ */
private Logger logger; private final Logger logger;
/** /**
* If the server is running an outdated version of the plugin. * If the server is running an outdated version of the plugin.
@@ -164,11 +164,6 @@ public abstract class EcoPlugin extends JavaPlugin implements PluginLike, Regist
*/ */
private final ListMap<LifecyclePosition, Runnable> afterLoad = new ListMap<>(); private final ListMap<LifecyclePosition, Runnable> afterLoad = new ListMap<>();
/**
* The tasks to run on task creation.
*/
private final ListMap<LifecyclePosition, Runnable> createTasks = new ListMap<>();
/** /**
* Create a new plugin. * Create a new plugin.
* <p> * <p>
@@ -430,18 +425,7 @@ public abstract class EcoPlugin extends JavaPlugin implements PluginLike, Regist
this.loadPluginCommands().forEach(PluginCommand::register); this.loadPluginCommands().forEach(PluginCommand::register);
// Run preliminary reload to resolve load order issues this.getScheduler().runLater(this::afterLoad, 1);
this.getScheduler().runLater(() -> {
Logger before = this.getLogger();
// Temporary silence logger.
this.logger = Eco.get().getNOOPLogger();
this.reload(false);
this.logger = before;
}, 1);
this.getScheduler().runLater(this::afterLoad, 2);
if (this.isSupportingExtensions()) { if (this.isSupportingExtensions()) {
this.getExtensionLoader().loadExtensions(); this.getExtensionLoader().loadExtensions();
@@ -617,30 +601,14 @@ public abstract class EcoPlugin extends JavaPlugin implements PluginLike, Regist
* Reload the plugin. * Reload the plugin.
*/ */
public final void reload() { public final void reload() {
this.reload(true);
}
/**
* Reload the plugin.
*
* @param cancelTasks If tasks should be cancelled.
*/
public final void reload(final boolean cancelTasks) {
this.getConfigHandler().updateConfigs(); this.getConfigHandler().updateConfigs();
if (cancelTasks) { this.getScheduler().cancelAll();
this.getScheduler().cancelAll();
}
this.getConfigHandler().callUpdate(); this.getConfigHandler().callUpdate();
this.getConfigHandler().callUpdate(); // Call twice to fix issues this.getConfigHandler().callUpdate(); // Call twice to fix issues
this.handleLifecycle(this.onReload, this::handleReload); this.handleLifecycle(this.onReload, this::handleReload);
if (cancelTasks) {
this.handleLifecycle(this.createTasks, this::createTasks);
}
for (Extension extension : this.extensionLoader.getLoadedExtensions()) { for (Extension extension : this.extensionLoader.getLoadedExtensions()) {
extension.handleReload(); extension.handleReload();
} }
@@ -754,15 +722,6 @@ public abstract class EcoPlugin extends JavaPlugin implements PluginLike, Regist
} }
/**
* The plugin-specific code to create tasks.
* <p>
* Override when needed.
*/
protected void createTasks() {
}
/** /**
* The plugin-specific code to be executed after the server is up. * The plugin-specific code to be executed after the server is up.
* <p> * <p>
@@ -1191,16 +1150,6 @@ public abstract class EcoPlugin extends JavaPlugin implements PluginLike, Regist
return this.getMetadataValueFactory().create(value); return this.getMetadataValueFactory().create(value);
} }
/**
* Get if all {@link com.willfp.eco.core.data.keys.PersistentDataKey}'s for this
* plugin should be saved locally (via data.yml.) even if eco is using a database.
*
* @return If using local storage.
*/
public boolean isUsingLocalStorage() {
return this.configYml.isUsingLocalStorage();
}
@Override @Override
@NotNull @NotNull
public final String getID() { public final String getID() {

View File

@@ -26,7 +26,7 @@ public class Prerequisite {
*/ */
public static final Prerequisite HAS_PAPER = new Prerequisite( public static final Prerequisite HAS_PAPER = new Prerequisite(
() -> ClassUtils.exists("com.destroystokyo.paper.event.block.BeaconEffectEvent"), () -> ClassUtils.exists("com.destroystokyo.paper.event.block.BeaconEffectEvent"),
"Requires server to be running paper (or a fork)" "Requires server to be running paper"
); );
/** /**
@@ -69,7 +69,7 @@ public class Prerequisite {
@Deprecated(since = "6.49.0", forRemoval = true) @Deprecated(since = "6.49.0", forRemoval = true)
public static final Prerequisite HAS_BUNGEECORD = new Prerequisite( public static final Prerequisite HAS_BUNGEECORD = new Prerequisite(
() -> ClassUtils.exists("net.md_5.bungee.api.event.ServerConnectedEvent"), () -> ClassUtils.exists("net.md_5.bungee.api.event.ServerConnectedEvent"),
"Requires server to be running BungeeCord (or a fork)" "Requires server to be running BungeeCord"
); );
/** /**
@@ -80,7 +80,15 @@ public class Prerequisite {
@Deprecated(since = "6.49.0", forRemoval = true) @Deprecated(since = "6.49.0", forRemoval = true)
public static final Prerequisite HAS_VELOCITY = new Prerequisite( public static final Prerequisite HAS_VELOCITY = new Prerequisite(
() -> ClassUtils.exists("com.velocitypowered.api.event.player.ServerConnectedEvent"), () -> ClassUtils.exists("com.velocitypowered.api.event.player.ServerConnectedEvent"),
"Requires server to be running Velocity (or a fork)" "Requires server to be running Velocity"
);
/**
* Requires the server to be running an implementation of Folia.
*/
public static final Prerequisite HAS_FOLIA = new Prerequisite(
() -> ClassUtils.exists("io.papermc.paper.threadedregions.scheduler.RegionisedScheduler"),
"Requires server to be running Folia!"
); );
/** /**

View File

@@ -9,11 +9,6 @@ import org.jetbrains.annotations.NotNull;
* Default plugin config.yml. * Default plugin config.yml.
*/ */
public class ConfigYml extends BaseConfig { public class ConfigYml extends BaseConfig {
/**
* The use local storage key.
*/
public static final String KEY_USES_LOCAL_STORAGE = "use-local-storage";
/** /**
* Config.yml. * Config.yml.
* *
@@ -57,13 +52,4 @@ public class ConfigYml extends BaseConfig {
final boolean removeUnused) { final boolean removeUnused) {
super(name, plugin, removeUnused, ConfigType.YAML); super(name, plugin, removeUnused, ConfigType.YAML);
} }
/**
* Get if the plugin is using local storage.
*
* @return The prefix.
*/
public boolean isUsingLocalStorage() {
return this.getBool(KEY_USES_LOCAL_STORAGE);
}
} }

View File

@@ -4,7 +4,6 @@ import com.willfp.eco.core.config.interfaces.Config;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -50,11 +49,6 @@ public final class PersistentDataKeyType<T> {
*/ */
public static final PersistentDataKeyType<Config> CONFIG = new PersistentDataKeyType<>("CONFIG"); public static final PersistentDataKeyType<Config> CONFIG = new PersistentDataKeyType<>("CONFIG");
/**
* Big Decimal.
*/
public static final PersistentDataKeyType<BigDecimal> BIG_DECIMAL = new PersistentDataKeyType<>("BIG_DECIMAL");
/** /**
* The name of the key type. * The name of the key type.
*/ */

View File

@@ -142,26 +142,6 @@ public interface MenuBuilder extends PageBuilder {
return this.onRender((player, menu) -> menu.setState(player, Page.MAX_PAGE_KEY, pages.apply(player))); return this.onRender((player, menu) -> menu.setState(player, Page.MAX_PAGE_KEY, pages.apply(player)));
} }
/**
* Set the default page.
*
* @param page The page.
* @return The builder.
*/
default MenuBuilder defaultPage(final int page) {
return this.maxPages(player -> page);
}
/**
* Set the default page dynamically for a player.
*
* @param page The default page.
* @return The builder.
*/
default MenuBuilder defaultPage(@NotNull final Function<Player, Integer> page) {
return this.onOpen((player, menu) -> menu.setState(player, Page.PAGE_KEY, page.apply(player)));
}
/** /**
* Add a menu close handler. * Add a menu close handler.
* *

View File

@@ -76,15 +76,6 @@ public abstract class CustomSlot implements Slot {
return delegate; return delegate;
} }
@Override
public boolean shouldRenderOnClick() {
if (delegate == null) {
throw new IllegalStateException("Custom Slot was not initialized!");
}
return delegate.shouldRenderOnClick();
}
@Override @Override
public final int getRows() { public final int getRows() {
return Slot.super.getRows(); return Slot.super.getRows();

View File

@@ -92,15 +92,6 @@ public interface Slot extends GUIComponent {
return false; return false;
} }
/**
* If the slot should re-render the menu if clicked.
*
* @return If the slot should re-render.
*/
default boolean shouldRenderOnClick() {
return true;
}
@Override @Override
default int getRows() { default int getRows() {
return 1; return 1;

View File

@@ -17,13 +17,6 @@ import java.util.function.Supplier;
* @param <T> The type of integration. * @param <T> The type of integration.
*/ */
public class IntegrationRegistry<T extends Integration> extends Registry<T> { public class IntegrationRegistry<T extends Integration> extends Registry<T> {
/**
* Create a new integration registry.
*/
public IntegrationRegistry() {
super();
}
@Override @Override
public @NotNull T register(@NotNull final T element) { public @NotNull T register(@NotNull final T element) {
return executeSafely(() -> super.register(element), element); return executeSafely(() -> super.register(element), element);

View File

@@ -1,6 +1,7 @@
package com.willfp.eco.core.items; package com.willfp.eco.core.items;
import com.willfp.eco.core.Eco; import com.willfp.eco.core.Eco;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey; import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -54,7 +55,7 @@ public class CustomItem implements TestableItem {
*/ */
Eco.get().getEcoPlugin().getScheduler().runLater(() -> { Eco.get().getEcoPlugin().getScheduler().runLater(() -> {
if (!matches(getItem())) { if (!matches(getItem())) {
Eco.get().getEcoPlugin().getLogger().severe("Item with key " + key + " is invalid!"); Bukkit.getLogger().severe("Item with key " + key + " is invalid!");
} }
}, 1); }, 1);
} }

View File

@@ -150,7 +150,7 @@ public class DefaultMap<K, V> implements Map<K, V> {
*/ */
@NotNull @NotNull
public static <K, K1, V> DefaultMap<K, Map<K1, V>> createNestedMap() { public static <K, K1, V> DefaultMap<K, Map<K1, V>> createNestedMap() {
return new DefaultMap<>(HashMap::new); return new DefaultMap<>(new HashMap<>());
} }
/** /**
@@ -163,6 +163,6 @@ public class DefaultMap<K, V> implements Map<K, V> {
*/ */
@NotNull @NotNull
public static <K, K1, V> DefaultMap<K, ListMap<K1, V>> createNestedListMap() { public static <K, K1, V> DefaultMap<K, ListMap<K1, V>> createNestedListMap() {
return new DefaultMap<>(ListMap::new); return new DefaultMap<>(new ListMap<>());
} }
} }

View File

@@ -9,6 +9,7 @@ import com.willfp.eco.core.items.Items;
import com.willfp.eco.core.recipe.recipes.CraftingRecipe; import com.willfp.eco.core.recipe.recipes.CraftingRecipe;
import com.willfp.eco.core.recipe.recipes.ShapedCraftingRecipe; import com.willfp.eco.core.recipe.recipes.ShapedCraftingRecipe;
import com.willfp.eco.util.NamespacedKeyUtils; import com.willfp.eco.util.NamespacedKeyUtils;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey; import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -126,8 +127,8 @@ public final class Recipes {
} }
if (builder.isAir()) { if (builder.isAir()) {
plugin.getLogger().warning("Crafting recipe " + plugin.getID() + ":" + key + " consists only"); Bukkit.getLogger().warning("Crafting recipe " + plugin.getID() + ":" + key + " consists only");
plugin.getLogger().warning("of air or invalid items! It will not be registered."); Bukkit.getLogger().warning("of air or invalid items! It will not be registered.");
return null; return null;
} }

View File

@@ -149,10 +149,6 @@ public class Registry<T extends Registrable> implements Iterable<T> {
* @param locker The locker. * @param locker The locker.
*/ */
public void lock(@Nullable final Object locker) { public void lock(@Nullable final Object locker) {
if (this.isLocked && this.locker != locker) {
throw new IllegalArgumentException("Registry is already locked with a different locker!");
}
this.locker = locker; this.locker = locker;
isLocked = true; isLocked = true;
} }
@@ -166,8 +162,6 @@ public class Registry<T extends Registrable> implements Iterable<T> {
if (this.locker != locker) { if (this.locker != locker) {
throw new IllegalArgumentException("Cannot unlock registry!"); throw new IllegalArgumentException("Cannot unlock registry!");
} }
this.locker = null;
isLocked = false; isLocked = false;
} }

View File

@@ -1,6 +1,8 @@
package com.willfp.eco.core.scheduling; package com.willfp.eco.core.scheduling;
import com.willfp.eco.core.EcoPlugin; import com.willfp.eco.core.EcoPlugin;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -14,9 +16,13 @@ public interface Scheduler {
* @param runnable The lambda to run. * @param runnable The lambda to run.
* @param ticksLater The amount of ticks to wait before execution. * @param ticksLater The amount of ticks to wait before execution.
* @return The created {@link BukkitTask}. * @return The created {@link BukkitTask}.
* @deprecated Does not work with Folia.
*/ */
BukkitTask runLater(@NotNull Runnable runnable, @Deprecated(since = "6.53.0", forRemoval = true)
long ticksLater); default BukkitTask runLater(@NotNull Runnable runnable,
long ticksLater) {
return runLater(new Location(Bukkit.getWorlds().get(0), 0, 0, 0), (int) ticksLater, runnable);
}
/** /**
* Run the task after a specified tick delay. * Run the task after a specified tick delay.
@@ -26,10 +32,12 @@ public interface Scheduler {
* @param runnable The lambda to run. * @param runnable The lambda to run.
* @param ticksLater The amount of ticks to wait before execution. * @param ticksLater The amount of ticks to wait before execution.
* @return The created {@link BukkitTask}. * @return The created {@link BukkitTask}.
* @deprecated Does not work with Folia.
*/ */
@Deprecated(since = "6.53.0", forRemoval = true)
default BukkitTask runLater(long ticksLater, default BukkitTask runLater(long ticksLater,
@NotNull Runnable runnable) { @NotNull Runnable runnable) {
return runLater(runnable, ticksLater); return runLater(new Location(Bukkit.getWorlds().get(0), 0, 0, 0), (int) ticksLater, runnable);
} }
/** /**
@@ -39,10 +47,14 @@ public interface Scheduler {
* @param delay The amount of ticks to wait before the first execution. * @param delay The amount of ticks to wait before the first execution.
* @param repeat The amount of ticks to wait between executions. * @param repeat The amount of ticks to wait between executions.
* @return The created {@link BukkitTask}. * @return The created {@link BukkitTask}.
* @deprecated Does not work with Folia.
*/ */
BukkitTask runTimer(@NotNull Runnable runnable, @Deprecated(since = "6.53.0", forRemoval = true)
long delay, default BukkitTask runTimer(@NotNull Runnable runnable,
long repeat); long delay,
long repeat) {
return runTimer(new Location(Bukkit.getWorlds().get(0), 0, 0, 0), (int) delay, (int) repeat, runnable);
}
/** /**
* Run the task repeatedly on a timer. * Run the task repeatedly on a timer.
@@ -53,11 +65,13 @@ public interface Scheduler {
* @param delay The amount of ticks to wait before the first execution. * @param delay The amount of ticks to wait before the first execution.
* @param repeat The amount of ticks to wait between executions. * @param repeat The amount of ticks to wait between executions.
* @return The created {@link BukkitTask}. * @return The created {@link BukkitTask}.
* @deprecated Does not work with Folia.
*/ */
@Deprecated(since = "6.53.0", forRemoval = true)
default BukkitTask runTimer(long delay, default BukkitTask runTimer(long delay,
long repeat, long repeat,
@NotNull Runnable runnable) { @NotNull Runnable runnable) {
return runTimer(runnable, delay, repeat); return runTimer(new Location(Bukkit.getWorlds().get(0), 0, 0, 0), (int) delay, (int) repeat, runnable);
} }
/** /**
@@ -67,10 +81,14 @@ public interface Scheduler {
* @param delay The amount of ticks to wait before the first execution. * @param delay The amount of ticks to wait before the first execution.
* @param repeat The amount of ticks to wait between executions. * @param repeat The amount of ticks to wait between executions.
* @return The created {@link BukkitTask}. * @return The created {@link BukkitTask}.
* @deprecated Does not work with Folia.
*/ */
BukkitTask runAsyncTimer(@NotNull Runnable runnable, @Deprecated(since = "6.53.0", forRemoval = true)
long delay, default BukkitTask runAsyncTimer(@NotNull Runnable runnable,
long repeat); long delay,
long repeat) {
return runTimerAsync((int) delay, (int) repeat, runnable);
}
/** /**
* Run the task repeatedly and asynchronously on a timer. * Run the task repeatedly and asynchronously on a timer.
@@ -81,11 +99,13 @@ public interface Scheduler {
* @param delay The amount of ticks to wait before the first execution. * @param delay The amount of ticks to wait before the first execution.
* @param repeat The amount of ticks to wait between executions. * @param repeat The amount of ticks to wait between executions.
* @return The created {@link BukkitTask}. * @return The created {@link BukkitTask}.
* @deprecated Does not work with Folia.
*/ */
@Deprecated(since = "6.53.0", forRemoval = true)
default BukkitTask runAsyncTimer(long delay, default BukkitTask runAsyncTimer(long delay,
long repeat, long repeat,
@NotNull Runnable runnable) { @NotNull Runnable runnable) {
return runAsyncTimer(runnable, delay, repeat); return runTimerAsync((int) delay, (int) repeat, runnable);
} }
/** /**
@@ -93,28 +113,28 @@ public interface Scheduler {
* *
* @param runnable The lambda to run. * @param runnable The lambda to run.
* @return The created {@link BukkitTask}. * @return The created {@link BukkitTask}.
* @deprecated Does not work with Folia.
*/ */
BukkitTask run(@NotNull Runnable runnable); @Deprecated(since = "6.53.0", forRemoval = true)
default BukkitTask run(@NotNull Runnable runnable) {
return run(new Location(Bukkit.getWorlds().get(0), 0, 0, 0), runnable);
}
/** /**
* Run the task asynchronously. * Schedule the task to be run repeatedly on a timer.
*
* @param runnable The lambda to run.
* @return The created {@link BukkitTask}.
*/
BukkitTask runAsync(@NotNull Runnable runnable);
/**
* Schedule the task to be ran repeatedly on a timer.
* *
* @param runnable The lambda to run. * @param runnable The lambda to run.
* @param delay The amount of ticks to wait before the first execution. * @param delay The amount of ticks to wait before the first execution.
* @param repeat The amount of ticks to wait between executions. * @param repeat The amount of ticks to wait between executions.
* @return The id of the task. * @return The id of the task.
* @deprecated Not needed.
*/ */
int syncRepeating(@NotNull Runnable runnable, @Deprecated(since = "6.53.0", forRemoval = true)
long delay, default int syncRepeating(@NotNull Runnable runnable,
long repeat); long delay,
long repeat) {
return runTimer(runnable, delay, repeat).getTaskId();
}
/** /**
* Schedule the task to be ran repeatedly on a timer. * Schedule the task to be ran repeatedly on a timer.
@@ -125,15 +145,73 @@ public interface Scheduler {
* @param delay The amount of ticks to wait before the first execution. * @param delay The amount of ticks to wait before the first execution.
* @param repeat The amount of ticks to wait between executions. * @param repeat The amount of ticks to wait between executions.
* @return The id of the task. * @return The id of the task.
* @deprecated Not needed.
*/ */
@Deprecated(since = "6.53.0", forRemoval = true)
default int syncRepeating(long delay, default int syncRepeating(long delay,
long repeat, long repeat,
@NotNull Runnable runnable) { @NotNull Runnable runnable) {
return syncRepeating(runnable, delay, repeat); return runTimer(runnable, delay, repeat).getTaskId();
} }
/** /**
* Cancel all running tasks from the linked {@link EcoPlugin}. * Cancel all running tasks from the linked {@link EcoPlugin}.
*/ */
void cancelAll(); void cancelAll();
/**
* Run a task asynchronously.
*
* @param task The lambda to run.
* @return The created {@link BukkitTask}.
*/
BukkitTask runAsync(@NotNull Runnable task);
/**
* Run a task.
*
* @param location The location.
* @param task The task.
* @return The created {@link BukkitTask}.
*/
BukkitTask run(@NotNull Location location,
@NotNull Runnable task);
/**
* Run a task after a delay.
*
* @param location The location.
* @param ticksLater The delay.
* @param task The task.
* @return The created {@link BukkitTask}.
*/
BukkitTask runLater(@NotNull Location location,
int ticksLater,
@NotNull Runnable task);
/**
* Run a task on a timer.
*
* @param location The location.
* @param delay The delay.
* @param repeat The repeat delay.
* @param task The task.
* @return The created {@link BukkitTask}.
*/
BukkitTask runTimer(@NotNull Location location,
int delay,
int repeat,
@NotNull Runnable task);
/**
* Run a task asynchronously on a timer.
*
* @param delay The delay.
* @param repeat The repeat delay.
* @param task The task.
* @return The created {@link BukkitTask}.
*/
BukkitTask runTimerAsync(int delay,
int repeat,
@NotNull Runnable task);
} }

View File

@@ -268,7 +268,7 @@ public final class NumberUtils {
* @deprecated Use {@link #evaluateExpression(String, PlaceholderContext)} instead. * @deprecated Use {@link #evaluateExpression(String, PlaceholderContext)} instead.
*/ */
@Deprecated(since = "6.56.0", forRemoval = true) @Deprecated(since = "6.56.0", forRemoval = true)
@SuppressWarnings({"removal", "DeprecatedIsStillUsed"}) @SuppressWarnings("removal")
public static double evaluateExpression(@NotNull final String expression, public static double evaluateExpression(@NotNull final String expression,
@NotNull final com.willfp.eco.core.math.MathContext context) { @NotNull final com.willfp.eco.core.math.MathContext context) {
return evaluateExpression(expression, context.toPlaceholderContext()); return evaluateExpression(expression, context.toPlaceholderContext());

View File

@@ -10,8 +10,6 @@ import com.willfp.eco.core.Eco;
import com.willfp.eco.core.integrations.placeholder.PlaceholderManager; import com.willfp.eco.core.integrations.placeholder.PlaceholderManager;
import com.willfp.eco.core.placeholder.context.PlaceholderContext; import com.willfp.eco.core.placeholder.context.PlaceholderContext;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.JoinConfiguration;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
@@ -786,127 +784,6 @@ public final class StringUtils {
return result.toString(); return result.toString();
} }
/**
* Line wrap a list of strings while preserving formatting.
*
* @param input The input list.
* @param lineLength The length of each line.
* @return The wrapped list.
*/
@NotNull
public static List<String> lineWrap(@NotNull final List<String> input,
final int lineLength) {
return lineWrap(input, lineLength, true);
}
/**
* Line wrap a list of strings while preserving formatting.
*
* @param input The input list.
* @param lineLength The length of each line.
* @param preserveMargin If the string has a margin, add it to the next line.
* @return The wrapped list.
*/
@NotNull
public static List<String> lineWrap(@NotNull final List<String> input,
final int lineLength,
final boolean preserveMargin) {
return input.stream()
.flatMap(line -> lineWrap(line, lineLength, preserveMargin).stream())
.toList();
}
/**
* Line wrap a string while preserving formatting.
*
* @param input The input list.
* @param lineLength The length of each line.
* @return The wrapped list.
*/
@NotNull
public static List<String> lineWrap(@NotNull final String input,
final int lineLength) {
return lineWrap(input, lineLength, true);
}
/**
* Line wrap a string while preserving formatting.
*
* @param input The input string.
* @param lineLength The length of each line.
* @param preserveMargin If the string has a margin, add it to the start of each line.
* @return The wrapped string.
*/
@NotNull
public static List<String> lineWrap(@NotNull final String input,
final int lineLength,
final boolean preserveMargin) {
int margin = preserveMargin ? getMargin(input) : 0;
TextComponent space = Component.text(" ");
Component asComponent = toComponent(input);
// The component contains the text as its children, so the child components
// are accessed like this:
List<TextComponent> children = new ArrayList<>();
if (asComponent instanceof TextComponent) {
children.add((TextComponent) asComponent);
}
for (Component child : asComponent.children()) {
children.add((TextComponent) child);
}
// Start by splitting the component into individual characters.
List<TextComponent> letters = new ArrayList<>();
for (TextComponent child : children) {
for (char c : child.content().toCharArray()) {
letters.add(Component.text(c).mergeStyle(child));
}
}
List<Component> lines = new ArrayList<>();
List<TextComponent> currentLine = new ArrayList<>();
boolean isFirstLine = true;
for (TextComponent letter : letters) {
if (currentLine.size() > lineLength && letter.content().isBlank()) {
lines.add(Component.join(JoinConfiguration.noSeparators(), currentLine));
currentLine.clear();
isFirstLine = false;
} else {
// Add margin if starting a new line.
if (currentLine.isEmpty() && !isFirstLine) {
if (preserveMargin) {
for (int i = 0; i < margin; i++) {
currentLine.add(space);
}
}
}
currentLine.add(letter);
}
}
// Push last line.
lines.add(Component.join(JoinConfiguration.noSeparators(), currentLine));
// Convert back to legacy strings.
return lines.stream().map(StringUtils::toLegacy)
.collect(Collectors.toList());
}
/**
* Get a string's margin.
*
* @param input The input string.
* @return The margin.
*/
public static int getMargin(@NotNull final String input) {
return input.indexOf(input.trim());
}
/** /**
* Options for formatting. * Options for formatting.
*/ */

View File

@@ -8,7 +8,7 @@ package com.willfp.eco.core.map
* @see ListMap * @see ListMap
*/ */
@Suppress("RedundantOverride") @Suppress("RedundantOverride")
class MutableListMap<K : Any, V> : ListMap<K, V>() { class MutableListMap<K : Any, V : Any> : ListMap<K, V>() {
/** /**
* Override with enforced MutableList type. * Override with enforced MutableList type.
*/ */
@@ -18,7 +18,7 @@ class MutableListMap<K : Any, V> : ListMap<K, V>() {
/** /**
* Override with enforced MutableList type. * Override with enforced MutableList type.
*/ */
override fun getOrDefault(key: K, defaultValue: MutableList<V>): MutableList<V> { override fun getOrDefault(key: K, defaultValue: MutableList<V>?): MutableList<V> {
return super.getOrDefault(key, defaultValue) return super.getOrDefault(key, defaultValue)
} }
} }
@@ -29,12 +29,6 @@ class MutableListMap<K : Any, V> : ListMap<K, V>() {
fun <K : Any, V : Any> defaultMap(defaultValue: V) = fun <K : Any, V : Any> defaultMap(defaultValue: V) =
DefaultMap<K, V>(defaultValue) DefaultMap<K, V>(defaultValue)
/**
* @see DefaultMap
*/
fun <K : Any, V : Any> defaultMap(defaultValue: () -> V) =
DefaultMap<K, V>(defaultValue())
/** /**
* @see ListMap * @see ListMap
*/ */
@@ -44,13 +38,11 @@ fun <K : Any, V : Any> listMap() =
/** /**
* @see DefaultMap.createNestedMap * @see DefaultMap.createNestedMap
*/ */
fun <K : Any, K1 : Any, V> nestedMap() = fun <K : Any, K1 : Any, V : Any> nestedMap() =
DefaultMap.createNestedMap<K, K1, V>() DefaultMap.createNestedMap<K, K1, V>()
/** /**
* @see DefaultMap.createNestedListMap * @see DefaultMap.createNestedListMap
*/ */
fun <K : Any, K1 : Any, V> nestedListMap() = fun <K : Any, K1 : Any, V : Any> nestedListMap() =
DefaultMap<K, MutableListMap<K1, V>>() { DefaultMap<K, MutableListMap<K1, V>>(MutableListMap())
MutableListMap()
}

View File

@@ -15,5 +15,5 @@ fun <T> create2DList(rows: Int, columns: Int): MutableList<MutableList<T>> =
ListUtils.create2DList(rows, columns) ListUtils.create2DList(rows, columns)
/** @see ListUtils.toSingletonList */ /** @see ListUtils.toSingletonList */
fun <T> T?.toSingletonList(): List<T> = fun <T> T.toSingletonList(): List<T> =
ListUtils.toSingletonList(this) ListUtils.toSingletonList(this)

View File

@@ -2,32 +2,6 @@
package com.willfp.eco.util package com.willfp.eco.util
import com.willfp.eco.core.placeholder.context.PlaceholderContext
/** @see NumberUtils.toNumeral */ /** @see NumberUtils.toNumeral */
fun Number.toNumeral(): String = fun Number.toNumeral(): String =
NumberUtils.toNumeral(this.toInt()) NumberUtils.toNumeral(this.toInt())
/** @see NumberUtils.fromNumeral */
fun String.parseNumeral(): Int =
NumberUtils.fromNumeral(this)
/** @see NumberUtils.randInt */
fun randInt(min: Int, max: Int) =
NumberUtils.randInt(min, max)
/** @see NumberUtils.randFloat */
fun randDouble(min: Double, max: Double) =
NumberUtils.randFloat(min, max)
/** @see NumberUtils.randFloat */
fun randFloat(min: Float, max: Float) =
NumberUtils.randFloat(min.toDouble(), max.toDouble()).toFloat()
/** @see NumberUtils.evaluateExpression */
fun evaluateExpression(expression: String) =
NumberUtils.evaluateExpression(expression)
/** @see NumberUtils.evaluateExpression */
fun evaluateExpression(expression: String, context: PlaceholderContext) =
NumberUtils.evaluateExpression(expression, context)

View File

@@ -69,15 +69,3 @@ fun Any?.toNiceString(): String =
/** @see StringUtils.replaceQuickly */ /** @see StringUtils.replaceQuickly */
fun String.replaceQuickly(target: String, replacement: String): String = fun String.replaceQuickly(target: String, replacement: String): String =
StringUtils.replaceQuickly(this, target, replacement) StringUtils.replaceQuickly(this, target, replacement)
/** @see StringUtils.lineWrap */
fun String.lineWrap(width: Int, preserveMargin: Boolean = true): List<String> =
StringUtils.lineWrap(this, width, preserveMargin)
/** @see StringUtils.lineWrap */
fun List<String>.lineWrap(width: Int, preserveMargin: Boolean = true): List<String> =
StringUtils.lineWrap(this, width, preserveMargin)
/** @see StringUtils.getMargin */
val String.margin: Int
get() = StringUtils.getMargin(this)

View File

@@ -8,12 +8,10 @@ import org.bukkit.command.TabCompleter
class DelegatedBukkitCommand( class DelegatedBukkitCommand(
private val delegate: EcoPluginCommand private val delegate: EcoPluginCommand
) : Command( ) : Command(delegate.name), TabCompleter, PluginIdentifiableCommand {
delegate.name, private var _aliases: List<String>? = null
delegate.description ?: "", private var _description: String? = null
"/${delegate.name}",
delegate.aliases
), TabCompleter, PluginIdentifiableCommand {
override fun execute(sender: CommandSender, label: String, args: Array<out String>?): Boolean { override fun execute(sender: CommandSender, label: String, args: Array<out String>?): Boolean {
return delegate.onCommand(sender, this, label, args) return delegate.onCommand(sender, this, label, args)
} }
@@ -38,4 +36,16 @@ class DelegatedBukkitCommand(
override fun getPlugin() = delegate.plugin override fun getPlugin() = delegate.plugin
override fun getPermission() = delegate.permission override fun getPermission() = delegate.permission
override fun getDescription() = _description ?: delegate.description ?: ""
override fun getAliases(): List<String> = _aliases ?: delegate.aliases
override fun setDescription(description: String): Command {
this._description = description
return this
}
override fun setAliases(aliases: List<String>): Command {
this._aliases = aliases
return this
}
} }

View File

@@ -7,7 +7,7 @@ import com.willfp.eco.core.command.PluginCommandBase
import org.bukkit.Bukkit import org.bukkit.Bukkit
class EcoPluginCommand( class EcoPluginCommand(
private val parentDelegate: PluginCommandBase, parentDelegate: CommandBase,
plugin: EcoPlugin, plugin: EcoPlugin,
name: String, name: String,
permission: String, permission: String,
@@ -39,9 +39,6 @@ class EcoPluginCommand(
Eco.get().syncCommands() Eco.get().syncCommands()
} }
override fun getAliases(): List<String> = parentDelegate.aliases
override fun getDescription(): String? = parentDelegate.description
} }
class EcoSubcommand( class EcoSubcommand(

View File

@@ -14,4 +14,4 @@ class EcoRunnableFactory(private val plugin: EcoPlugin) : RunnableFactory {
} }
} }
} }
} }

View File

@@ -34,6 +34,4 @@ open class EcoSlot(
} }
override fun getActionableSlot(player: Player, menu: Menu): EcoSlot = this override fun getActionableSlot(player: Player, menu: Menu): EcoSlot = this
override fun shouldRenderOnClick() = handlers.values.any { it.isNotEmpty() }
} }

View File

@@ -6,7 +6,6 @@ import com.willfp.eco.core.gui.slot.functional.CaptiveFilter
import com.willfp.eco.core.gui.slot.functional.SlotHandler import com.willfp.eco.core.gui.slot.functional.SlotHandler
import com.willfp.eco.core.gui.slot.functional.SlotProvider import com.willfp.eco.core.gui.slot.functional.SlotProvider
import com.willfp.eco.core.gui.slot.functional.SlotUpdater import com.willfp.eco.core.gui.slot.functional.SlotUpdater
import com.willfp.eco.core.map.listMap
import org.bukkit.entity.Player import org.bukkit.entity.Player
import org.bukkit.event.inventory.ClickType import org.bukkit.event.inventory.ClickType
import java.util.function.Predicate import java.util.function.Predicate
@@ -16,14 +15,14 @@ class EcoSlotBuilder(private val provider: SlotProvider) : SlotBuilder {
private var captiveFromEmpty = false private var captiveFromEmpty = false
private var updater: SlotUpdater = SlotUpdater { player, menu, _ -> provider.provide(player, menu) } private var updater: SlotUpdater = SlotUpdater { player, menu, _ -> provider.provide(player, menu) }
private val handlers = listMap<ClickType, SlotHandler>() private val handlers = mutableMapOf<ClickType, MutableList<SlotHandler>>()
private var captiveFilter = private var captiveFilter =
CaptiveFilter { _, _, _ -> true } CaptiveFilter { _, _, _ -> true }
private var notCaptiveFor: (Player) -> Boolean = { _ -> false} private var notCaptiveFor: (Player) -> Boolean = { _ -> false}
override fun onClick(type: ClickType, action: SlotHandler): SlotBuilder { override fun onClick(type: ClickType, action: SlotHandler): SlotBuilder {
handlers[type] += action handlers.computeIfAbsent(type) { mutableListOf() } += action
return this return this
} }

View File

@@ -1,10 +0,0 @@
package com.willfp.eco.internal.logging
import java.util.logging.LogRecord
import java.util.logging.Logger
object NOOPLogger : Logger("eco_noop", null as String?) {
override fun log(record: LogRecord?) {
return
}
}

View File

@@ -1,51 +0,0 @@
package com.willfp.eco.internal.scheduling
import com.willfp.eco.core.EcoPlugin
import com.willfp.eco.core.scheduling.Scheduler
import org.bukkit.Bukkit
import org.bukkit.scheduler.BukkitTask
class EcoScheduler(private val plugin: EcoPlugin) : Scheduler {
override fun runLater(
runnable: Runnable,
ticksLater: Long
): BukkitTask {
return Bukkit.getScheduler().runTaskLater(plugin, runnable, ticksLater)
}
override fun runTimer(
runnable: Runnable,
delay: Long,
repeat: Long
): BukkitTask {
return Bukkit.getScheduler().runTaskTimer(plugin, runnable, delay, repeat)
}
override fun runAsyncTimer(
runnable: Runnable,
delay: Long,
repeat: Long
): BukkitTask {
return Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, runnable, delay, repeat)
}
override fun run(runnable: Runnable): BukkitTask {
return Bukkit.getScheduler().runTask(plugin, runnable)
}
override fun runAsync(runnable: Runnable): BukkitTask {
return Bukkit.getScheduler().runTaskAsynchronously(plugin, runnable)
}
override fun syncRepeating(
runnable: Runnable,
delay: Long,
repeat: Long
): Int {
return Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, runnable, delay, repeat)
}
override fun cancelAll() {
Bukkit.getScheduler().cancelTasks(plugin)
}
}

View File

@@ -0,0 +1,33 @@
package com.willfp.eco.internal.scheduling
import com.willfp.eco.core.EcoPlugin
import com.willfp.eco.core.scheduling.Scheduler
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.scheduler.BukkitTask
class EcoSchedulerSpigot(private val plugin: EcoPlugin) : Scheduler {
override fun runLater(location: Location, ticksLater: Int, task: Runnable): BukkitTask {
return Bukkit.getScheduler().runTaskLater(plugin, task, ticksLater.toLong())
}
override fun runTimer(location: Location, delay: Int, repeat: Int, task: Runnable): BukkitTask {
return Bukkit.getScheduler().runTaskTimer(plugin, task, delay.toLong(), repeat.toLong())
}
override fun run(location: Location, task: Runnable): BukkitTask {
return Bukkit.getScheduler().runTask(plugin, task)
}
override fun runAsync(task: Runnable): BukkitTask {
return Bukkit.getScheduler().runTaskAsynchronously(plugin, task)
}
override fun runTimerAsync(delay: Int, repeat: Int, task: Runnable): BukkitTask {
return Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, task, delay.toLong(), repeat.toLong())
}
override fun cancelAll() {
Bukkit.getScheduler().cancelTasks(plugin)
}
}

View File

@@ -0,0 +1,6 @@
group = "com.willfp"
version = rootProject.version
dependencies {
compileOnly("dev.folia:folia-api:1.19.4-R0.1-SNAPSHOT")
}

View File

@@ -0,0 +1,49 @@
package com.willfp.eco.internal.scheduling
import com.willfp.eco.core.EcoPlugin
import com.willfp.eco.core.scheduling.Scheduler
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.scheduler.BukkitTask
import java.util.concurrent.TimeUnit
class EcoSchedulerFolia(private val plugin: EcoPlugin) : Scheduler {
override fun runLater(runnable: Runnable, ticksLater: Long): BukkitTask {
Bukkit.getGlobalRegionScheduler().runDelayed(plugin, { runnable.run() }, ticksLater)
}
override fun runLater(location: Location, ticksLater: Int, task: Runnable): BukkitTask {
Bukkit.getRegionScheduler().runDelayed(plugin, location, { task.run() }, ticksLater.toLong())
}
override fun runTimer(delay: Long, repeat: Long, runnable: Runnable): BukkitTask {
Bukkit.getGlobalRegionScheduler().runAtFixedRate(plugin, { runnable.run() }, delay, repeat)
}
override fun runTimer(location: Location, delay: Int, repeat: Int, task: Runnable): BukkitTask {
Bukkit.getRegionScheduler().runAtFixedRate(plugin, location, { task.run() }, delay.toLong(), repeat.toLong())
}
override fun run(runnable: Runnable): BukkitTask {
Bukkit.getGlobalRegionScheduler().run(plugin) { runnable.run() }
}
override fun run(location: Location, task: Runnable): BukkitTask {
Bukkit.getRegionScheduler().run(plugin, location) { task.run() }
}
override fun runAsync(task: Runnable): BukkitTask {
Bukkit.getAsyncScheduler().runNow(plugin) { task.run() }
}
override fun runTimerAsync(delay: Int, repeat: Int, task: Runnable): BukkitTask {
Bukkit.getAsyncScheduler()
.runAtFixedRate(plugin, { task.run() }, delay * 50L, repeat * 50L, TimeUnit.MILLISECONDS)
}
override fun cancelAll() {
Bukkit.getScheduler().cancelTasks(plugin)
Bukkit.getAsyncScheduler().cancelTasks(plugin)
Bukkit.getGlobalRegionScheduler().cancelTasks(plugin)
}
}

View File

@@ -4,6 +4,7 @@ import com.willfp.eco.core.Eco
import com.willfp.eco.core.EcoPlugin import com.willfp.eco.core.EcoPlugin
import com.willfp.eco.core.PluginLike import com.willfp.eco.core.PluginLike
import com.willfp.eco.core.PluginProps import com.willfp.eco.core.PluginProps
import com.willfp.eco.core.Prerequisite
import com.willfp.eco.core.command.CommandBase import com.willfp.eco.core.command.CommandBase
import com.willfp.eco.core.command.PluginCommandBase import com.willfp.eco.core.command.PluginCommandBase
import com.willfp.eco.core.config.ConfigType import com.willfp.eco.core.config.ConfigType
@@ -37,10 +38,10 @@ import com.willfp.eco.internal.gui.menu.renderedInventory
import com.willfp.eco.internal.gui.slot.EcoSlotBuilder import com.willfp.eco.internal.gui.slot.EcoSlotBuilder
import com.willfp.eco.internal.integrations.PAPIExpansion import com.willfp.eco.internal.integrations.PAPIExpansion
import com.willfp.eco.internal.logging.EcoLogger import com.willfp.eco.internal.logging.EcoLogger
import com.willfp.eco.internal.logging.NOOPLogger
import com.willfp.eco.internal.placeholder.PlaceholderParser import com.willfp.eco.internal.placeholder.PlaceholderParser
import com.willfp.eco.internal.proxy.EcoProxyFactory import com.willfp.eco.internal.proxy.EcoProxyFactory
import com.willfp.eco.internal.scheduling.EcoScheduler import com.willfp.eco.internal.scheduling.EcoSchedulerFolia
import com.willfp.eco.internal.scheduling.EcoSchedulerSpigot
import com.willfp.eco.internal.spigot.data.DataYml import com.willfp.eco.internal.spigot.data.DataYml
import com.willfp.eco.internal.spigot.data.KeyRegistry import com.willfp.eco.internal.spigot.data.KeyRegistry
import com.willfp.eco.internal.spigot.data.ProfileHandler import com.willfp.eco.internal.spigot.data.ProfileHandler
@@ -102,7 +103,7 @@ class EcoImpl : EcoSpigotPlugin(), Eco {
) )
override fun createScheduler(plugin: EcoPlugin) = override fun createScheduler(plugin: EcoPlugin) =
EcoScheduler(plugin) if (Prerequisite.HAS_FOLIA.isMet) EcoSchedulerFolia(plugin) else EcoSchedulerSpigot(plugin)
override fun createEventManager(plugin: EcoPlugin) = override fun createEventManager(plugin: EcoPlugin) =
EcoEventManager(plugin) EcoEventManager(plugin)
@@ -126,9 +127,6 @@ class EcoImpl : EcoSpigotPlugin(), Eco {
override fun createLogger(plugin: EcoPlugin) = override fun createLogger(plugin: EcoPlugin) =
EcoLogger(plugin) EcoLogger(plugin)
override fun getNOOPLogger() =
NOOPLogger
override fun createPAPIIntegration(plugin: EcoPlugin) { override fun createPAPIIntegration(plugin: EcoPlugin) {
PAPIExpansion(plugin) PAPIExpansion(plugin)
} }
@@ -188,7 +186,7 @@ class EcoImpl : EcoSpigotPlugin(), Eco {
} }
override fun createPluginCommand( override fun createPluginCommand(
parentDelegate: PluginCommandBase, parentDelegate: CommandBase,
plugin: EcoPlugin, plugin: EcoPlugin,
name: String, name: String,
permission: String, permission: String,
@@ -262,7 +260,6 @@ class EcoImpl : EcoSpigotPlugin(), Eco {
override fun addNewPlugin(plugin: EcoPlugin) { override fun addNewPlugin(plugin: EcoPlugin) {
loadedEcoPlugins[plugin.name.lowercase()] = plugin loadedEcoPlugins[plugin.name.lowercase()] = plugin
loadedEcoPlugins[plugin.id] = plugin
} }
override fun getLoadedPlugins(): List<String> = override fun getLoadedPlugins(): List<String> =
@@ -286,6 +283,9 @@ class EcoImpl : EcoSpigotPlugin(), Eco {
override fun loadPlayerProfile(uuid: UUID) = override fun loadPlayerProfile(uuid: UUID) =
profileHandler.load(uuid) profileHandler.load(uuid)
override fun unloadPlayerProfile(uuid: UUID) =
profileHandler.unloadPlayer(uuid)
override fun createDummyEntity(location: Location): Entity = override fun createDummyEntity(location: Location): Entity =
getProxy(DummyEntityFactoryProxy::class.java).createDummyEntity(location) getProxy(DummyEntityFactoryProxy::class.java).createDummyEntity(location)

View File

@@ -112,7 +112,6 @@ import com.willfp.eco.internal.spigot.integrations.mcmmo.McmmoIntegrationImpl
import com.willfp.eco.internal.spigot.integrations.multiverseinventories.MultiverseInventoriesIntegration import com.willfp.eco.internal.spigot.integrations.multiverseinventories.MultiverseInventoriesIntegration
import com.willfp.eco.internal.spigot.integrations.placeholder.PlaceholderIntegrationPAPI import com.willfp.eco.internal.spigot.integrations.placeholder.PlaceholderIntegrationPAPI
import com.willfp.eco.internal.spigot.integrations.price.PriceFactoryPlayerPoints import com.willfp.eco.internal.spigot.integrations.price.PriceFactoryPlayerPoints
import com.willfp.eco.internal.spigot.integrations.price.PriceFactoryRoyaleEconomy
import com.willfp.eco.internal.spigot.integrations.price.PriceFactoryUltraEconomy import com.willfp.eco.internal.spigot.integrations.price.PriceFactoryUltraEconomy
import com.willfp.eco.internal.spigot.integrations.shop.ShopDeluxeSellwands import com.willfp.eco.internal.spigot.integrations.shop.ShopDeluxeSellwands
import com.willfp.eco.internal.spigot.integrations.shop.ShopEconomyShopGUI import com.willfp.eco.internal.spigot.integrations.shop.ShopEconomyShopGUI
@@ -128,7 +127,6 @@ import com.willfp.eco.internal.spigot.recipes.stackhandlers.ShapedCraftingRecipe
import com.willfp.eco.internal.spigot.recipes.stackhandlers.ShapelessCraftingRecipeStackHandler import com.willfp.eco.internal.spigot.recipes.stackhandlers.ShapelessCraftingRecipeStackHandler
import com.willfp.eco.util.ClassUtils import com.willfp.eco.util.ClassUtils
import me.TechsCode.UltraEconomy.UltraEconomy import me.TechsCode.UltraEconomy.UltraEconomy
import me.qKing12.RoyaleEconomy.MultiCurrency.MultiCurrencyHandler
import net.kyori.adventure.platform.bukkit.BukkitAudiences import net.kyori.adventure.platform.bukkit.BukkitAudiences
import net.milkbowl.vault.economy.Economy import net.milkbowl.vault.economy.Economy
import org.bukkit.Bukkit import org.bukkit.Bukkit
@@ -221,6 +219,8 @@ abstract class EcoSpigotPlugin : EcoPlugin() {
this.logger.info("No conflicts found!") this.logger.info("No conflicts found!")
} }
CollatedRunnable(this)
CustomItemsManager.registerProviders() // Do it again here CustomItemsManager.registerProviders() // Do it again here
// Register events for ShopSellEvent // Register events for ShopSellEvent
@@ -251,15 +251,14 @@ abstract class EcoSpigotPlugin : EcoPlugin() {
Eco.get().adventure?.close() Eco.get().adventure?.close()
} }
override fun createTasks() { override fun handleReload() {
CollatedRunnable(this) CollatedRunnable(this)
this.scheduler.runLater(3) { this.scheduler.runLater(3) {
profileHandler.migrateIfNeeded() profileHandler.migrateIfNeeded()
} }
ProfileSaver(this, profileHandler).startTicking() ProfileSaver(this, profileHandler)
this.scheduler.runTimer( this.scheduler.runTimer(
{ getProxy(PacketHandlerProxy::class.java).clearDisplayFrames() }, { getProxy(PacketHandlerProxy::class.java).clearDisplayFrames() },
this.configYml.getInt("display-frame-ttl").toLong(), this.configYml.getInt("display-frame-ttl").toLong(),
@@ -360,11 +359,6 @@ abstract class EcoSpigotPlugin : EcoPlugin() {
} }
}, },
IntegrationLoader("PlayerPoints") { Prices.registerPriceFactory(PriceFactoryPlayerPoints()) }, IntegrationLoader("PlayerPoints") { Prices.registerPriceFactory(PriceFactoryPlayerPoints()) },
IntegrationLoader("RoyaleEconomy") {
for (currency in MultiCurrencyHandler.getCurrencies()) {
Prices.registerPriceFactory(PriceFactoryRoyaleEconomy(currency))
}
},
// Placeholder // Placeholder
IntegrationLoader("PlaceholderAPI") { PlaceholderManager.addIntegration(PlaceholderIntegrationPAPI()) }, IntegrationLoader("PlaceholderAPI") { PlaceholderManager.addIntegration(PlaceholderIntegrationPAPI()) },
@@ -389,7 +383,7 @@ abstract class EcoSpigotPlugin : EcoPlugin() {
GUIListener(this), GUIListener(this),
ArrowDataListener(this), ArrowDataListener(this),
ArmorChangeEventListeners(this), ArmorChangeEventListeners(this),
DataListener(this, profileHandler), DataListener(this),
PlayerBlockListener(this), PlayerBlockListener(this),
ServerLocking ServerLocking
) )

View File

@@ -1,5 +1,6 @@
package com.willfp.eco.internal.spigot.data package com.willfp.eco.internal.spigot.data
import com.willfp.eco.core.Eco
import com.willfp.eco.core.EcoPlugin import com.willfp.eco.core.EcoPlugin
import com.willfp.eco.util.PlayerUtils import com.willfp.eco.util.PlayerUtils
import org.bukkit.event.EventHandler import org.bukkit.event.EventHandler
@@ -10,14 +11,11 @@ import org.bukkit.event.player.PlayerLoginEvent
import org.bukkit.event.player.PlayerQuitEvent import org.bukkit.event.player.PlayerQuitEvent
class DataListener( class DataListener(
private val plugin: EcoPlugin, private val plugin: EcoPlugin
private val handler: ProfileHandler
) : Listener { ) : Listener {
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
fun onLeave(event: PlayerQuitEvent) { fun onLeave(event: PlayerQuitEvent) {
val profile = handler.accessLoadedProfile(event.player.uniqueId) ?: return Eco.get().unloadPlayerProfile(event.player.uniqueId)
handler.saveKeysFor(event.player.uniqueId, profile.data.keys)
handler.unloadPlayer(event.player.uniqueId)
} }
@EventHandler @EventHandler
@@ -29,6 +27,6 @@ class DataListener(
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
fun onLogin(event: PlayerLoginEvent) { fun onLogin(event: PlayerLoginEvent) {
handler.unloadPlayer(event.player.uniqueId) Eco.get().unloadPlayerProfile(event.player.uniqueId)
} }
} }

View File

@@ -1,6 +1,5 @@
package com.willfp.eco.internal.spigot.data package com.willfp.eco.internal.spigot.data
import com.willfp.eco.core.EcoPlugin
import com.willfp.eco.core.data.PlayerProfile import com.willfp.eco.core.data.PlayerProfile
import com.willfp.eco.core.data.Profile import com.willfp.eco.core.data.Profile
import com.willfp.eco.core.data.ServerProfile import com.willfp.eco.core.data.ServerProfile
@@ -12,8 +11,7 @@ import java.util.concurrent.ConcurrentHashMap
abstract class EcoProfile( abstract class EcoProfile(
val data: MutableMap<PersistentDataKey<*>, Any>, val data: MutableMap<PersistentDataKey<*>, Any>,
val uuid: UUID, val uuid: UUID,
private val handler: DataHandler, private val handler: DataHandler
private val localHandler: DataHandler
) : Profile { ) : Profile {
override fun <T : Any> write(key: PersistentDataKey<T>, value: T) { override fun <T : Any> write(key: PersistentDataKey<T>, value: T) {
this.data[key] = value this.data[key] = value
@@ -27,12 +25,7 @@ abstract class EcoProfile(
return this.data[key] as T return this.data[key] as T
} }
this.data[key] = if (key.isLocal) { this.data[key] = handler.read(uuid, key) ?: key.defaultValue
localHandler.read(uuid, key)
} else {
handler.read(uuid, key)
} ?: key.defaultValue
return read(key) return read(key)
} }
@@ -56,9 +49,8 @@ abstract class EcoProfile(
class EcoPlayerProfile( class EcoPlayerProfile(
data: MutableMap<PersistentDataKey<*>, Any>, data: MutableMap<PersistentDataKey<*>, Any>,
uuid: UUID, uuid: UUID,
handler: DataHandler, handler: DataHandler
localHandler: DataHandler ) : EcoProfile(data, uuid, handler), PlayerProfile {
) : EcoProfile(data, uuid, handler, localHandler), PlayerProfile {
override fun toString(): String { override fun toString(): String {
return "EcoPlayerProfile{uuid=$uuid}" return "EcoPlayerProfile{uuid=$uuid}"
} }
@@ -66,13 +58,9 @@ class EcoPlayerProfile(
class EcoServerProfile( class EcoServerProfile(
data: MutableMap<PersistentDataKey<*>, Any>, data: MutableMap<PersistentDataKey<*>, Any>,
handler: DataHandler, handler: DataHandler
localHandler: DataHandler ) : EcoProfile(data, serverProfileUUID, handler), ServerProfile {
) : EcoProfile(data, serverProfileUUID, handler, localHandler), ServerProfile {
override fun toString(): String { override fun toString(): String {
return "EcoServerProfile" return "EcoServerProfile"
} }
} }
private val PersistentDataKey<*>.isLocal: Boolean
get() = EcoPlugin.getPlugin(this.key.namespace)?.isUsingLocalStorage == true

View File

@@ -4,7 +4,6 @@ import com.willfp.eco.core.config.interfaces.Config
import com.willfp.eco.core.data.keys.PersistentDataKey import com.willfp.eco.core.data.keys.PersistentDataKey
import com.willfp.eco.core.data.keys.PersistentDataKeyType import com.willfp.eco.core.data.keys.PersistentDataKeyType
import org.bukkit.NamespacedKey import org.bukkit.NamespacedKey
import java.math.BigDecimal
object KeyRegistry { object KeyRegistry {
private val registry = mutableMapOf<NamespacedKey, PersistentDataKey<*>>() private val registry = mutableMapOf<NamespacedKey, PersistentDataKey<*>>()
@@ -45,9 +44,6 @@ object KeyRegistry {
PersistentDataKeyType.CONFIG -> if (default !is Config) { PersistentDataKeyType.CONFIG -> if (default !is Config) {
throw IllegalArgumentException("Invalid Data Type! Should be Config") throw IllegalArgumentException("Invalid Data Type! Should be Config")
} }
PersistentDataKeyType.BIG_DECIMAL -> if (default !is BigDecimal) {
throw IllegalArgumentException("Invalid Data Type! Should be BigDecimal")
}
else -> throw NullPointerException("Null value found!") else -> throw NullPointerException("Null value found!")
} }

View File

@@ -23,10 +23,8 @@ class ProfileHandler(
) { ) {
private val loaded = mutableMapOf<UUID, EcoProfile>() private val loaded = mutableMapOf<UUID, EcoProfile>()
private val localHandler = YamlDataHandler(plugin, this)
val handler: DataHandler = when (type) { val handler: DataHandler = when (type) {
HandlerType.YAML -> localHandler HandlerType.YAML -> YamlDataHandler(plugin, this)
HandlerType.MYSQL -> MySQLDataHandler(plugin, this) HandlerType.MYSQL -> MySQLDataHandler(plugin, this)
HandlerType.MONGO -> MongoDataHandler(plugin, this) HandlerType.MONGO -> MongoDataHandler(plugin, this)
} }
@@ -43,7 +41,7 @@ class ProfileHandler(
val data = mutableMapOf<PersistentDataKey<*>, Any>() val data = mutableMapOf<PersistentDataKey<*>, Any>()
val profile = if (uuid == serverProfileUUID) val profile = if (uuid == serverProfileUUID)
EcoServerProfile(data, handler, localHandler) else EcoPlayerProfile(data, uuid, handler, localHandler) EcoServerProfile(data, handler) else EcoPlayerProfile(data, uuid, handler)
loaded[uuid] = profile loaded[uuid] = profile
return profile return profile
@@ -58,19 +56,7 @@ class ProfileHandler(
} }
fun saveKeysFor(uuid: UUID, keys: Set<PersistentDataKey<*>>) { fun saveKeysFor(uuid: UUID, keys: Set<PersistentDataKey<*>>) {
val profile = accessLoadedProfile(uuid) ?: return handler.saveKeysFor(uuid, keys)
val map = mutableMapOf<PersistentDataKey<*>, Any>()
for (key in keys) {
map[key] = profile.data[key] ?: continue
}
handler.saveKeysFor(uuid, map)
// Don't save to local handler if it's the same handler.
if (localHandler != handler) {
localHandler.saveKeysFor(uuid, map)
}
} }
fun unloadPlayer(uuid: UUID) { fun unloadPlayer(uuid: UUID) {
@@ -79,10 +65,6 @@ class ProfileHandler(
fun save() { fun save() {
handler.save() handler.save()
if (localHandler != handler) {
localHandler.save()
}
} }
fun migrateIfNeeded() { fun migrateIfNeeded() {
@@ -165,8 +147,5 @@ class ProfileHandler(
fun initialize() { fun initialize() {
handler.initialize() handler.initialize()
if (localHandler != handler) {
localHandler.initialize()
}
} }
} }

View File

@@ -19,7 +19,7 @@ abstract class DataHandler(
/** /**
* Save a set of keys for a given UUID. * Save a set of keys for a given UUID.
*/ */
abstract fun saveKeysFor(uuid: UUID, keys: Map<PersistentDataKey<*>, Any>) abstract fun saveKeysFor(uuid: UUID, keys: Set<PersistentDataKey<*>>)
// Everything below this are methods that are only needed for certain implementations. // Everything below this are methods that are only needed for certain implementations.

View File

@@ -1,5 +1,6 @@
package com.willfp.eco.internal.spigot.data.storage package com.willfp.eco.internal.spigot.data.storage
import com.willfp.eco.core.data.Profile
import com.willfp.eco.core.data.keys.PersistentDataKey import com.willfp.eco.core.data.keys.PersistentDataKey
import com.willfp.eco.internal.spigot.EcoSpigotPlugin import com.willfp.eco.internal.spigot.EcoSpigotPlugin
import com.willfp.eco.internal.spigot.data.ProfileHandler import com.willfp.eco.internal.spigot.data.ProfileHandler
@@ -50,16 +51,18 @@ class MongoDataHandler(
} }
} }
override fun saveKeysFor(uuid: UUID, keys: Map<PersistentDataKey<*>, Any>) { override fun saveKeysFor(uuid: UUID, keys: Set<PersistentDataKey<*>>) {
val profile = handler.loadGenericProfile(uuid)
scope.launch { scope.launch {
for ((key, value) in keys) { for (key in keys) {
saveKey(uuid, key, value) saveKey(profile, uuid, key)
} }
} }
} }
private suspend fun <T : Any> saveKey(uuid: UUID, key: PersistentDataKey<T>, value: Any) { private suspend fun <T : Any> saveKey(profile: Profile, uuid: UUID, key: PersistentDataKey<T>) {
val data = value as T val data = profile.read(key)
doWrite(uuid, key, data) doWrite(uuid, key, data)
} }
@@ -97,18 +100,6 @@ class MongoDataHandler(
profile profile
} }
} }
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is MongoDataHandler
}
override fun hashCode(): Int {
return type.hashCode()
}
} }
private data class UUIDProfile( private data class UUIDProfile(

View File

@@ -21,7 +21,6 @@ import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.transactions.transaction import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.update
import java.math.BigDecimal
import java.util.UUID import java.util.UUID
import java.util.concurrent.Executors import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
@@ -85,9 +84,6 @@ class MySQLDataHandler(
PersistentDataKeyType.BOOLEAN -> data.getBoolOrNull(key.key.toString()) PersistentDataKeyType.BOOLEAN -> data.getBoolOrNull(key.key.toString())
PersistentDataKeyType.STRING_LIST -> data.getStringsOrNull(key.key.toString()) PersistentDataKeyType.STRING_LIST -> data.getStringsOrNull(key.key.toString())
PersistentDataKeyType.CONFIG -> data.getSubsectionOrNull(key.key.toString()) PersistentDataKeyType.CONFIG -> data.getSubsectionOrNull(key.key.toString())
PersistentDataKeyType.BIG_DECIMAL -> if (data.has(key.key.toString()))
BigDecimal(data.getString(key.key.toString())) else null
else -> null else -> null
} }
@@ -101,15 +97,16 @@ class MySQLDataHandler(
setData(uuid, data) setData(uuid, data)
} }
override fun saveKeysFor(uuid: UUID, keys: Map<PersistentDataKey<*>, Any>) { override fun saveKeysFor(uuid: UUID, keys: Set<PersistentDataKey<*>>) {
val profile = handler.loadGenericProfile(uuid)
executor.submit { executor.submit {
val data = getData(uuid) val data = getData(uuid)
for (key in keys) {
for ((key, value) in keys) { data.set(key.key.toString(), profile.read(key))
data.set(key.key.toString(), value)
} }
doSetData(uuid, data) setData(uuid, data)
} }
} }
@@ -139,14 +136,10 @@ class MySQLDataHandler(
private fun setData(uuid: UUID, config: Config) { private fun setData(uuid: UUID, config: Config) {
executor.submit { executor.submit {
doSetData(uuid, config) transaction(database) {
} table.update({ table.id eq uuid }) {
} it[dataColumn] = config.toPlaintext()
}
private fun doSetData(uuid: UUID, config: Config) {
transaction(database) {
table.update({ table.id eq uuid }) {
it[dataColumn] = config.toPlaintext()
} }
} }
} }
@@ -156,16 +149,4 @@ class MySQLDataHandler(
SchemaUtils.createMissingTablesAndColumns(table, withLogs = false) SchemaUtils.createMissingTablesAndColumns(table, withLogs = false)
} }
} }
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is MySQLDataHandler
}
override fun hashCode(): Int {
return type.hashCode()
}
} }

View File

@@ -5,10 +5,10 @@ import com.willfp.eco.internal.spigot.data.EcoProfile
import com.willfp.eco.internal.spigot.data.ProfileHandler import com.willfp.eco.internal.spigot.data.ProfileHandler
class ProfileSaver( class ProfileSaver(
private val plugin: EcoPlugin, plugin: EcoPlugin,
private val handler: ProfileHandler handler: ProfileHandler
) { ) {
fun startTicking() { init {
val interval = plugin.configYml.getInt("save-interval").toLong() val interval = plugin.configYml.getInt("save-interval").toLong()
plugin.scheduler.runTimer(20, interval) { plugin.scheduler.runTimer(20, interval) {

View File

@@ -5,7 +5,6 @@ import com.willfp.eco.core.data.keys.PersistentDataKeyType
import com.willfp.eco.internal.spigot.EcoSpigotPlugin import com.willfp.eco.internal.spigot.EcoSpigotPlugin
import com.willfp.eco.internal.spigot.data.ProfileHandler import com.willfp.eco.internal.spigot.data.ProfileHandler
import org.bukkit.NamespacedKey import org.bukkit.NamespacedKey
import java.math.BigDecimal
import java.util.UUID import java.util.UUID
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
@@ -28,9 +27,6 @@ class YamlDataHandler(
PersistentDataKeyType.BOOLEAN -> dataYml.getBoolOrNull("player.$uuid.${key.key}") as T? PersistentDataKeyType.BOOLEAN -> dataYml.getBoolOrNull("player.$uuid.${key.key}") as T?
PersistentDataKeyType.STRING_LIST -> dataYml.getStringsOrNull("player.$uuid.${key.key}") as T? PersistentDataKeyType.STRING_LIST -> dataYml.getStringsOrNull("player.$uuid.${key.key}") as T?
PersistentDataKeyType.CONFIG -> dataYml.getSubsectionOrNull("player.$uuid.${key.key}") as T? PersistentDataKeyType.CONFIG -> dataYml.getSubsectionOrNull("player.$uuid.${key.key}") as T?
PersistentDataKeyType.BIG_DECIMAL -> (if (dataYml.has(key.key.toString()))
BigDecimal(dataYml.getString(key.key.toString())) else null) as T?
else -> null else -> null
} }
@@ -41,25 +37,15 @@ class YamlDataHandler(
doWrite(uuid, key.key, value) doWrite(uuid, key.key, value)
} }
override fun saveKeysFor(uuid: UUID, keys: Map<PersistentDataKey<*>, Any>) { override fun saveKeysFor(uuid: UUID, keys: Set<PersistentDataKey<*>>) {
for ((key, value) in keys) { val profile = handler.loadGenericProfile(uuid)
doWrite(uuid, key.key, value)
for (key in keys) {
doWrite(uuid, key.key, profile.read(key))
} }
} }
private fun doWrite(uuid: UUID, key: NamespacedKey, value: Any) { private fun doWrite(uuid: UUID, key: NamespacedKey, value: Any) {
dataYml.set("player.$uuid.$key", value) dataYml.set("player.$uuid.$key", value)
} }
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is YamlDataHandler
}
override fun hashCode(): Int {
return type.hashCode()
}
} }

View File

@@ -44,10 +44,6 @@ class GUIListener(private val plugin: EcoPlugin) : Listener {
if (delegate is EcoSlot) { if (delegate is EcoSlot) {
delegate.handleInventoryClick(event, menu) delegate.handleInventoryClick(event, menu)
if (delegate.shouldRenderOnClick()) {
player.renderActiveMenu()
}
} else if (delegate === this) { } else if (delegate === this) {
return return
} else { } else {
@@ -55,6 +51,14 @@ class GUIListener(private val plugin: EcoPlugin) : Listener {
} }
} }
@EventHandler(
priority = EventPriority.HIGHEST
)
fun handleRender(event: InventoryClickEvent) {
val player = event.whoClicked as? Player ?: return
player.renderActiveMenu()
}
@EventHandler( @EventHandler(
priority = EventPriority.HIGH priority = EventPriority.HIGH
) )
@@ -90,8 +94,6 @@ class GUIListener(private val plugin: EcoPlugin) : Listener {
if (slot.isCaptive(player, menu)) { if (slot.isCaptive(player, menu)) {
if (!slot.isAllowedCaptive(player, menu, event.oldCursor)) { if (!slot.isAllowedCaptive(player, menu, event.oldCursor)) {
event.isCancelled = true event.isCancelled = true
} else {
player.renderActiveMenu()
} }
} else { } else {
event.isCancelled = true event.isCancelled = true
@@ -124,8 +126,6 @@ class GUIListener(private val plugin: EcoPlugin) : Listener {
if (slot.isCaptive(player, menu)) { if (slot.isCaptive(player, menu)) {
if (!slot.isAllowedCaptive(player, menu, event.currentItem)) { if (!slot.isAllowedCaptive(player, menu, event.currentItem)) {
event.isCancelled = true event.isCancelled = true
} else {
player.renderActiveMenu()
} }
} else { } else {
event.isCancelled = true event.isCancelled = true
@@ -141,6 +141,18 @@ class GUIListener(private val plugin: EcoPlugin) : Listener {
plugin.scheduler.run { MenuHandler.unregisterInventory(event.inventory) } plugin.scheduler.run { MenuHandler.unregisterInventory(event.inventory) }
} }
@EventHandler
fun forceRender(event: InventoryClickEvent) {
val player = event.whoClicked as? Player ?: return
player.renderActiveMenu()
}
@EventHandler
fun forceRender(event: InventoryDragEvent) {
val player = event.whoClicked as? Player ?: return
player.renderActiveMenu()
}
@EventHandler( @EventHandler(
priority = EventPriority.HIGHEST priority = EventPriority.HIGHEST
) )

View File

@@ -27,8 +27,7 @@ class AntigriefPvPManager: AntigriefIntegration {
override fun canInjure(player: Player, victim: LivingEntity): Boolean { override fun canInjure(player: Player, victim: LivingEntity): Boolean {
return when(victim) { return when(victim) {
is Player -> { is Player -> {
val defender = PvPlayer.get(victim) (PvPlayer.get(victim).isInCombat)}
(defender.hasPvPEnabled() && !defender.isNewbie || defender.isInCombat)}
else -> true else -> true
} }
} }

View File

@@ -1,54 +0,0 @@
package com.willfp.eco.internal.spigot.integrations.price
import com.willfp.eco.core.placeholder.context.PlaceholderContext
import com.willfp.eco.core.placeholder.context.PlaceholderContextSupplier
import com.willfp.eco.core.price.Price
import com.willfp.eco.core.price.PriceFactory
import com.willfp.eco.util.toSingletonList
import me.qKing12.RoyaleEconomy.MultiCurrency.Currency
import org.bukkit.entity.Player
import java.util.*
class PriceFactoryRoyaleEconomy(private val currency: Currency) : PriceFactory {
override fun getNames(): List<String> {
return currency.currencyId.lowercase().toSingletonList()
}
override fun create(baseContext: PlaceholderContext, function: PlaceholderContextSupplier<Double>): Price {
return PriceRoyaleEconomy(currency, baseContext) { function.get(it) }
}
private class PriceRoyaleEconomy(
private val currency: Currency,
private val baseContext: PlaceholderContext,
private val function: (PlaceholderContext) -> Double
) : Price {
private val multipliers = mutableMapOf<UUID, Double>()
override fun canAfford(player: Player, multiplier: Double): Boolean {
return currency.getAmount(player.uniqueId.toString()) >= getValue(player, multiplier)
}
override fun pay(player: Player, multiplier: Double) {
currency.removeAmount(player.uniqueId.toString(), getValue(player, multiplier))
}
override fun giveTo(player: Player, multiplier: Double) {
currency.addAmount(player.uniqueId.toString(), getValue(player, multiplier))
}
override fun getValue(player: Player, multiplier: Double): Double {
return function(baseContext.copyWithPlayer(player)) * getMultiplier(player) * multiplier
}
override fun getMultiplier(player: Player): Double {
return multipliers[player.uniqueId] ?: 1.0
}
override fun setMultiplier(player: Player, multiplier: Double) {
multipliers[player.uniqueId] = multiplier
}
}
}

View File

@@ -194,9 +194,5 @@ dependencies:
bootstrap: false bootstrap: false
- name: Denizen - name: Denizen
required: false
bootstrap: false
- name: RoyaleEconomy
required: false required: false
bootstrap: false bootstrap: false

View File

@@ -54,4 +54,3 @@ softdepend:
- UltraEconomy - UltraEconomy
- PlayerPoints - PlayerPoints
- Denizen - Denizen
- RoyaleEconomy

View File

@@ -1,3 +1,3 @@
version = 6.60.4 version = 6.57.2
plugin-name = eco plugin-name = eco
kotlin.code.style = official kotlin.code.style = official

Binary file not shown.

View File

@@ -20,4 +20,5 @@ include(":eco-core:core-nms:v1_19_R2")
include(":eco-core:core-nms:v1_19_R3") include(":eco-core:core-nms:v1_19_R3")
include(":eco-core:core-proxy") include(":eco-core:core-proxy")
include(":eco-core:core-plugin") include(":eco-core:core-plugin")
include(":eco-core:core-backend") include(":eco-core:core-backend")
include(":eco-core:core-folia")