diff --git a/labyrinth-common/pom.xml b/labyrinth-common/pom.xml index 753a8091..68a6a4d2 100644 --- a/labyrinth-common/pom.xml +++ b/labyrinth-common/pom.xml @@ -5,7 +5,7 @@ labyrinth com.github.the-h-team - 1.7.7 + 1.7.8 4.0.0 diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/api/LegacyCheckService.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/api/LegacyCheckService.java index ed76b36d..11a8eded 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/api/LegacyCheckService.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/api/LegacyCheckService.java @@ -1,11 +1,17 @@ package com.github.sanctum.labyrinth.api; +import com.github.sanctum.labyrinth.library.StringUtils; import org.bukkit.Bukkit; /** * Detects legacy server environments. */ public interface LegacyCheckService extends Service { + + default boolean isModded() { + return StringUtils.use(Bukkit.getServer().getName()).containsIgnoreCase("forge", "magma"); + } + /** * Check if the environment of the server is legacy. * diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/command/SubCommandList.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/command/SubCommandList.java index 41679816..f4976c82 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/command/SubCommandList.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/command/SubCommandList.java @@ -1,19 +1,35 @@ package com.github.sanctum.labyrinth.command; +import com.github.sanctum.labyrinth.LabyrinthProvider; +import com.github.sanctum.labyrinth.annotation.Ordinal; import com.github.sanctum.labyrinth.data.container.LabyrinthCollection; import com.github.sanctum.labyrinth.data.container.LabyrinthCollectionBase; import com.github.sanctum.labyrinth.data.container.LabyrinthList; +import com.github.sanctum.labyrinth.interfacing.OrdinalProcedure; +import com.github.sanctum.labyrinth.library.CommandUtils; import com.github.sanctum.labyrinth.library.StringUtils; import java.util.Arrays; import java.util.LinkedList; import java.util.List; +import java.util.Map; +import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.bukkit.command.Command; +import org.bukkit.command.CommandMap; import org.bukkit.command.CommandSender; +import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +/** + * A class designed for easy bukkit sub command flow. Append or remove sub labels to registered commands. + * + * @author Hempfest + */ public abstract class SubCommandList extends LabyrinthCollectionBase { protected final Crossover parent; @@ -22,10 +38,71 @@ protected SubCommandList(@NotNull Command parent) { this.parent = new Crossover(parent); } - public final String getCommand() { + /** + * Get the main command label this sub command belongs to. + * + * @return The main command this sub command is for. + */ + public final @NotNull String getCommand() { return parent.getLabel(); } + /** + * Get a sub command from this list by its label. + * + * @param label The label of the sub command. + * @return a sub command match or null if not found. + */ + public final @Nullable SubCommand getSubCommand(@NotNull String label) { + return stream().filter(s -> s.getLabel().equalsIgnoreCase(label)).findFirst().orElse(null); + } + + /** + * Register a sub command into this list. + * + * @param subCommand The command to register. + */ + public final void register(@NotNull SubCommand subCommand) { + if (subCommand.getCommand().equalsIgnoreCase(getCommand())) { + final Command parent = CommandUtils.getCommandByLabel(subCommand.getCommand()); + if (parent != null) { + final Plugin plugin = Optional.of((Plugin)JavaPlugin.getProvidingPlugin(parent.getClass())).orElseGet(() -> { + if (parent instanceof PluginCommand) { + return ((PluginCommand)parent).getPlugin(); + } else return LabyrinthProvider.getInstance().getPluginInstance(); + }); + CommandUtils.read(entry -> { + Map commandMappings = entry.getValue(); + CommandMap map = entry.getKey(); + commandMappings.remove(parent.getName()); + for (String alias : parent.getAliases()) { + if (commandMappings.containsKey(alias) && commandMappings.get(alias).getAliases().contains(alias)) { + commandMappings.remove(alias); + } + } + parent.unregister(map); + map.register(getCommand(), plugin.getName(), parent); + if (!contains(subCommand)) add(subCommand); + return this; + }); + } else throw new IllegalArgumentException("Command " + subCommand.getCommand() + " either not found or not loaded yet."); + } + } + + /** + * Unregister a sub command from this list. + * + * @param subCommand The command to unregister. + */ + public final void unregister(@NotNull SubCommand subCommand) { + if (subCommand.getCommand().equalsIgnoreCase(getCommand())) { + final Command parent = CommandUtils.getCommandByLabel(subCommand.getCommand()); + if (parent != null) { + if (contains(subCommand)) remove(subCommand); + } else throw new IllegalArgumentException("Command " + subCommand.getCommand() + " either not found or not loaded yet."); + } + } + class Crossover extends Command { private final Command command; diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/AddonLoader.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/AddonLoader.java index 04eb63af..5b78793b 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/AddonLoader.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/AddonLoader.java @@ -1,5 +1,6 @@ package com.github.sanctum.labyrinth.data; +import com.github.sanctum.labyrinth.LabyrinthProvider; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.io.File; @@ -13,6 +14,7 @@ import java.util.Optional; import java.util.jar.JarFile; import java.util.zip.ZipEntry; +import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; /** @@ -40,9 +42,10 @@ final class AddonClassLoader extends URLClassLoader { private AddonClassLoader(URL[] urls) { super(urls, javaPlugin.getClass().getClassLoader()); + Bukkit.getLogger().severe(javaPlugin.getClass().getClassLoader().getClass().getName()); } - final Class resolveClass(String name) throws ClassNotFoundException { + Class resolveClass(String name) throws ClassNotFoundException { return loadClass(name, true); } diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/ConfigurableNode.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/ConfigurableNode.java index e1ce504b..c8a389f9 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/ConfigurableNode.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/ConfigurableNode.java @@ -2,12 +2,8 @@ import com.github.sanctum.labyrinth.LabyrinthProvider; import com.github.sanctum.labyrinth.api.Service; -import com.github.sanctum.labyrinth.task.Schedule; import com.github.sanctum.labyrinth.task.TaskScheduler; -import com.google.gson.GsonBuilder; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -69,7 +65,7 @@ public String getString() { @Override public int getInt() { - return config.getInt(this.key); + return config.getInt(this.key); } @Override @@ -237,7 +233,7 @@ public boolean create() { if (config.getType() == FileType.JSON) { set(new Object()); } else { - ((YamlConfiguration)config).getConfig().createSection(this.key); + ((YamlConfiguration) config).getConfig().createSection(this.key); } save(); return false; @@ -286,17 +282,17 @@ public Set getKeys(boolean deep) { Set keys = new HashSet<>(); JsonConfiguration json = (JsonConfiguration) config; if (json.get(this.key) instanceof Map) { - Map map1 = (Map)json.get(this.key); + Map map1 = (Map) json.get(this.key); if (deep) { for (Map.Entry entry : map1.entrySet()) { if (entry.getValue() instanceof Map) { - Map map2 = (Map)entry.getValue(); + Map map2 = (Map) entry.getValue(); for (Map.Entry entry2 : map2.entrySet()) { if (entry2.getValue() instanceof Map) { - Map map3 = (Map)entry2.getValue(); + Map map3 = (Map) entry2.getValue(); for (Map.Entry entry3 : map3.entrySet()) { if (entry3.getValue() instanceof Map) { - Map map4 = (Map)entry2.getValue(); + Map map4 = (Map) entry2.getValue(); for (Map.Entry entry4 : map4.entrySet()) { keys.add(this.key + "." + entry.getKey() + "." + entry2.getKey() + "." + entry3.getKey() + "." + entry4.getKey()); } @@ -331,17 +327,17 @@ public Map getValues(boolean deep) { Map map = new HashMap<>(); JsonConfiguration json = (JsonConfiguration) config; if (json.get(this.key) instanceof Map) { - Map map1 = (Map)json.get(this.key); + Map map1 = (Map) json.get(this.key); if (deep) { for (Map.Entry entry : map1.entrySet()) { if (entry.getValue() instanceof Map) { - Map map2 = (Map)entry.getValue(); + Map map2 = (Map) entry.getValue(); for (Map.Entry entry2 : map2.entrySet()) { if (entry2.getValue() instanceof Map) { - Map map3 = (Map)entry2.getValue(); + Map map3 = (Map) entry2.getValue(); for (Map.Entry entry3 : map3.entrySet()) { if (entry3.getValue() instanceof Map) { - Map map4 = (Map)entry2.getValue(); + Map map4 = (Map) entry2.getValue(); for (Map.Entry entry4 : map4.entrySet()) { map.put(this.key + "." + entry.getKey() + "." + entry2.getKey() + "." + entry3.getKey() + "." + entry4.getKey(), entry4.getValue()); } @@ -359,13 +355,13 @@ public Map getValues(boolean deep) { } else { for (Map.Entry entry : map1.entrySet()) { if (entry.getValue() instanceof Map) { - Map map2 = (Map)entry.getValue(); + Map map2 = (Map) entry.getValue(); for (Map.Entry entry2 : map2.entrySet()) { if (entry2.getValue() instanceof Map) { - Map map3 = (Map)entry2.getValue(); + Map map3 = (Map) entry2.getValue(); for (Map.Entry entry3 : map3.entrySet()) { if (entry3.getValue() instanceof Map) { - Map map4 = (Map)entry2.getValue(); + Map map4 = (Map) entry2.getValue(); for (Map.Entry entry4 : map4.entrySet()) { map.put(this.key + "." + entry.getKey() + "." + entry2.getKey() + "." + entry3.getKey() + "." + entry4.getKey(), entry4.getValue()); } diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/service/AnnotationDiscovery.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/service/AnnotationDiscovery.java index be5b134f..fcb37a35 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/service/AnnotationDiscovery.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/data/service/AnnotationDiscovery.java @@ -15,7 +15,6 @@ import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; -import org.bukkit.Bukkit; import org.jetbrains.annotations.NotNull; /** @@ -24,7 +23,7 @@ * @param A type of annotation. * @param A listener to use. */ -public final class AnnotationDiscovery implements Iterable{ +public final class AnnotationDiscovery implements Iterable { private final int count; private final Class annotation; @@ -41,7 +40,8 @@ public final class AnnotationDiscovery implements Itera for (Method method : rClass.getDeclaredMethods()) { try { method.setAccessible(true); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } if (method.isAnnotationPresent(annotation)) { annotated++; } @@ -59,7 +59,8 @@ public final class AnnotationDiscovery implements Itera for (Method method : rClass.getDeclaredMethods()) { try { method.setAccessible(true); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } if (method.isAnnotationPresent(annotation)) { annotated++; } @@ -105,7 +106,7 @@ public AnnotationDiscovery filter(Predicate predicate) { * Filter the methods and only work with ones of interest. * * @param predicate The filtration. - * @param hard whether or not to breach accessibility. + * @param hard whether or not to breach accessibility. * @return The same annotation discovery object. */ public AnnotationDiscovery filter(Predicate predicate, boolean hard) { @@ -118,7 +119,8 @@ public AnnotationDiscovery filter(Predicate predicate, boo methods.addAll(Arrays.stream(this.rClass.getDeclaredMethods()).filter(m -> { try { m.setAccessible(true); - } catch (Exception ignored){} + } catch (Exception ignored) { + } return m.isAnnotationPresent(annotation) && predicate.test(m); }).collect(Collectors.toList())); } @@ -140,25 +142,25 @@ public boolean isPresent() { */ public void ifPresent(WideConsumer function) { if (isPresent()) { - for (Method m : methods) { + methods.forEach(m -> { for (Annotation a : m.getAnnotations()) { if (annotation.isAssignableFrom(a.annotationType())) { function.accept((T) a, m); } } - } + }); } } /** * Get information from the leading source objects located annotation. - * + *

* This method gives you access to an annotation and the source object itself. * - * @deprecated Use {@link AnnotationDiscovery#mapFromClass(AnnotativeConsumer)} instead! * @param function The function. - * @param The desired return value. + * @param The desired return value. * @return A value from an annotation. + * @deprecated Use {@link AnnotationDiscovery#mapFromClass(AnnotativeConsumer)} instead! */ @Deprecated public U map(AnnotativeConsumer function) { @@ -167,11 +169,11 @@ public U map(AnnotativeConsumer function) { /** * Get information from the leading source objects located annotation. - * + *

* This method gives you access to an annotation and the source object itself. * * @param function The function. - * @param The desired return value. + * @param The desired return value. * @return A value from an annotation. */ public U mapFromClass(AnnotativeConsumer function) { @@ -183,11 +185,11 @@ public U mapFromClass(AnnotativeConsumer function) { /** * Get information from the leading source objects methods found with the specified annotation. - * + *

* This method gives you access to an annotation and the source object itself. * * @param function The function. - * @param The desired return value. + * @param The desired return value. * @return A value from an annotation. */ public List mapFromMethods(AnnotativeConsumer function) { diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/ComponentCompliment.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/ComponentCompliment.java deleted file mode 100644 index 612dcf7a..00000000 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/ComponentCompliment.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.github.sanctum.labyrinth.formatting; - -/** - * @author Hempfest - */ -@Deprecated -public interface ComponentCompliment { - - @SuppressWarnings("EmptyMethod") - void apply(PaginatedList pagination, int page, int max); - -} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/ComponentDecoration.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/ComponentDecoration.java deleted file mode 100644 index b7ee8930..00000000 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/ComponentDecoration.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.github.sanctum.labyrinth.formatting; - -/** - * @author Hempfest - */ -@FunctionalInterface -@Deprecated -public interface ComponentDecoration { - - void apply(PaginatedList pagination, T object, int page, int max, int placement); - -} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/ComponentUtil.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/ComponentUtil.java index 68ae0a7c..7b68cfc8 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/ComponentUtil.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/ComponentUtil.java @@ -13,7 +13,7 @@ public static void addContent(BaseComponent component, String context) { if (component.getHoverEvent() == null) { component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(TextComponent.fromLegacyText(StringUtils.use(context).translate())))); } else { - component.getHoverEvent().addContent(new Text(StringUtils.use(context).translate())); + component.getHoverEvent().addContent(new Text(TextComponent.fromLegacyText(StringUtils.use(context).translate()))); } } diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/FinishingCompliment.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/FinishingCompliment.java deleted file mode 100644 index c593d839..00000000 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/FinishingCompliment.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.github.sanctum.labyrinth.formatting; - -/** - * @author Hempfest - */ -@Deprecated -public interface FinishingCompliment extends ComponentCompliment { - - void apply(PaginatedList pagination, int page, int max); - -} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/PaginatedList.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/PaginatedList.java deleted file mode 100644 index 852f72d2..00000000 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/PaginatedList.java +++ /dev/null @@ -1,205 +0,0 @@ -package com.github.sanctum.labyrinth.formatting; - -import com.github.sanctum.labyrinth.annotation.Experimental; -import com.github.sanctum.labyrinth.library.MathUtils; - -import java.util.Collection; -import java.util.Comparator; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/** - * Encapsulate a list of objects to be sorted and paginated. - * - * @deprecated Replaced by {@link com.github.sanctum.labyrinth.formatting.pagination.AbstractPaginatedCollection} - * @param the object type representative of this pagination operation - * @author Hempfest - */ -@Deprecated -@Experimental(dueTo = "This class will attempt to be replaced soon.", atRisk = true) -public class PaginatedList { - private List typeList; - private ComponentCompliment start; - private ComponentCompliment finish; - private ComponentDecoration decoration; - private int linesPerPage; - - public PaginatedList(List list) { - this.typeList = new LinkedList<>(new LinkedHashSet<>(list)); - } - - public PaginatedList(Set set) { - this.typeList = new LinkedList<>(set); - } - - /** - * Format/trim a given amount to a specific length format. - * - * @param amount the amount to format - * @param precision the math precision to stop the decimal placing at - * @return the newly formatted double - */ - public double format(Number amount, int precision) { - return MathUtils.use(amount).format(precision); - } - - /** - * Setup a comparator for this list's sorting procedure. - * - * @param comparable the comparing operation to run for the given object type - * @return this paginated list procedure - */ - public PaginatedList compare(Comparator comparable) { - this.typeList.sort(comparable); - return this; - } - - /** - * Provided the page number, total page count, object in queue and - * current paginated list instance; decorate any possible actions - * to take while iterating through the entries. - * - * @param decoration the primary execution to be ran for every entry given - * @return this paginated list procedure - */ - public PaginatedList decorate(ComponentDecoration decoration) { - this.decoration = decoration; - return this; - } - - /** - * Specify an amount of entries to be display per page. - *

- * Lower entry counts will result in larger page counts. - * - * @param linesPerPage the amount of entries per page to display - * @return this paginated list procedure - */ - public PaginatedList limit(int linesPerPage) { - this.linesPerPage = linesPerPage; - return this; - } - - /** - * Provided the page number and total page count, provide a starting - * sequence for the pagination. - * - * @param compliment the starting execution to be run once - * @return this paginated list procedure - */ - public PaginatedList start(StartingCompliment compliment) { - this.start = compliment; - return this; - } - - /** - * Provided the page number and total page count, - * describe a finishing sequence for the pagination. - * - * @param compliment the finishing execution to be run once - * @return this paginated list procedure - */ - public PaginatedList finish(FinishingCompliment compliment) { - this.finish = compliment; - return this; - } - - /** - * Provided the page number and total page count, describe a finishing - * sequence for the pagination (so the desired player can browse pages). - * - * @param builderConsumer the finishing execution to be run once - * @return this paginated list procedure - */ - public PaginatedList finish(Consumer builderConsumer) { - this.finish = (list, page, max) -> { - - PrintedPaginationBuilder builder = new PrintedPaginationBuilder(max).setPage(page); - - builderConsumer.accept(builder); - - builder.build(list); - - }; - return this; - } - - /** - * Separate unwanted elements from the list. - * - * @param predicate test that must succeed to include an element - * @return this paginated list procedure - */ - public PaginatedList filter(Predicate predicate) { - this.typeList = typeList.stream().filter(predicate).collect(Collectors.toList()); - return this; - } - - public int getTotalPageCount() { - int totalPageCount = 1; - if ((this.typeList.size() % linesPerPage) == 0) { - if (this.typeList.size() > 0) { - totalPageCount = this.typeList.size() / linesPerPage; - } - } else { - totalPageCount = (this.typeList.size() / linesPerPage) + 1; - } - return totalPageCount; - } - - public PaginatedList update(Collection list) { - this.typeList = new LinkedList<>(list); - return this; - } - - /** - * Run all prior sorting arrangements and sequence operations for a specified page. - * - * @param pageNum the page to to collect - * @return a list of collected objects from the sorting procedure - */ - public List get(int pageNum) { - LinkedList list = new LinkedList<>(); - int page = pageNum; - - int o = linesPerPage; - - int totalPageCount = getTotalPageCount(); - - if (page <= totalPageCount) { - - if (this.start != null) { - this.start.apply(this, pageNum, totalPageCount); - } - - if (!typeList.isEmpty()) { - int i1 = 0, k = 0; - page--; - LinkedList sorted_list = new LinkedList<>(this.typeList); - - for (T value : sorted_list) { - - k++; - if ((((page * o) + i1 + 1) == k) && (k != ((page * o) + o + 1))) { - i1++; - if (decoration != null) { - decoration.apply(this, value, pageNum, totalPageCount, k); - } - list.add(value); - } - } - if (this.finish != null) { - this.finish.apply(this, pageNum, totalPageCount); - } - } - // end line - } - return list; - } - -} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/PrintedPaginationBuilder.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/PrintedPaginationBuilder.java deleted file mode 100644 index f0226591..00000000 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/PrintedPaginationBuilder.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.github.sanctum.labyrinth.formatting; - -import com.github.sanctum.labyrinth.library.Mailer; -import com.github.sanctum.labyrinth.library.Message; -import com.github.sanctum.labyrinth.library.TextLib; -import net.md_5.bungee.api.chat.BaseComponent; -import org.bukkit.entity.Player; - -import java.util.LinkedList; -import java.util.List; - -public class PrintedPaginationBuilder { - - private final List toSend = new LinkedList<>(); - - private final int max; - - private String prefix = ""; - - private String suffix = ""; - - private int page; - - private Player player; - - - protected PrintedPaginationBuilder(int max) { - this.max = max; - } - - - public PrintedPaginationBuilder setPlayer(Player player) { - this.player = player; - return this; - } - - public PrintedPaginationBuilder setPage(int page) { - this.page = page; - return this; - } - - public PrintedPaginationBuilder setPrefix(String prefix) { - this.prefix = prefix; - return this; - } - - public PrintedPaginationBuilder setSuffix(String suffix) { - this.suffix = suffix; - return this; - } - - void build(PaginatedList list) { - TextLib component = TextLib.getInstance(); - int next = page + 1; - int last = Math.max(page - 1, 1); - if (!this.prefix.isEmpty()) { - Mailer.empty(player).chat(this.prefix).deploy(); - } - List toSend = new LinkedList<>(); - if (page == 1) { - if (page == max) { - toSend.add(component.textHoverable("", "&8« ", "&cYou are on the first page already.")); - toSend.add(component.textHoverable("&f<&7" + page + "&f/&7" + max + "&f>", "", "")); - toSend.add(component.textHoverable("", " &8»", "&cYou are already on the last page.")); - player.spigot().sendMessage(toSend.toArray(new BaseComponent[0])); - return; - } - toSend.add(component.textHoverable("", "&8« ", "&cYou are on the first page already.")); - toSend.add(component.textHoverable("&f<&7" + page + "&f/&7" + max + "&f>", "", "")); - toSend.add(component.execute(() -> list.get(next), component.textHoverable("", " &3»", "&aGoto the next page."))); - player.spigot().sendMessage(toSend.toArray(new BaseComponent[0])); - return; - } - if (page == max) { - toSend.add(component.execute(() -> list.get(last), component.textHoverable("", "&3« ", "&aGoto the previous page."))); - toSend.add(component.textHoverable("&f<&7" + page + "&f/&7" + max + "&f>", "", "")); - toSend.add(component.textHoverable("", " &8»", "&cYou are already on the last page.")); - player.spigot().sendMessage(toSend.toArray(new BaseComponent[0])); - return; - } - if (next <= max) { - toSend.add(component.execute(() -> list.get(last), component.textHoverable("", "&3« ", "&aGoto the previous page."))); - toSend.add(component.textHoverable("&f<&7" + page + "&f/&7" + max + "&f>", "", "")); - toSend.add(component.execute(() -> list.get(next), component.textHoverable("", " &3»", "&aGoto the next page."))); - player.spigot().sendMessage(toSend.toArray(new BaseComponent[0])); - } - if (!this.suffix.isEmpty()) { - Mailer.empty(this.player).chat(this.suffix).deploy(); - } - } -} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/StartingCompliment.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/StartingCompliment.java deleted file mode 100644 index 10305e3e..00000000 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/StartingCompliment.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.github.sanctum.labyrinth.formatting; - -/** - * @author Hempfest - */ -public interface StartingCompliment extends ComponentCompliment { - - void apply(PaginatedList pagination, int page, int max); - -} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/TablistInstance.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/TablistInstance.java index d7d5f94c..bebee865 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/TablistInstance.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/TablistInstance.java @@ -4,9 +4,6 @@ import com.github.sanctum.labyrinth.api.Service; import com.github.sanctum.labyrinth.api.TaskService; import com.github.sanctum.labyrinth.library.StringUtils; -import com.github.sanctum.labyrinth.task.Schedule; -import com.github.sanctum.labyrinth.task.Synchronous; -import com.github.sanctum.labyrinth.task.Task; import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -93,8 +90,8 @@ public interface TablistInstance { * Activate this tab list display instance and include custom meta within the task, alternating displays every x y (x being time and y being the unit.) * * @param consumer The meta to include. - * @param unit The time unit to use - * @param period The amount of time to use. + * @param unit The time unit to use + * @param period The amount of time to use. * @return true if the instance was activated, false if already running. */ boolean enable(Consumer consumer, TimeUnit unit, long period); @@ -200,7 +197,8 @@ public boolean remove(TabGroup group) { @Override public boolean enable() { - return enable(player1 -> {}, TimeUnit.MILLISECONDS, 40); + return enable(player1 -> { + }, TimeUnit.MILLISECONDS, 40); } @Override diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/string/ImageBreakdown.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/string/ImageBreakdown.java index 8030e3fa..fb52bdcf 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/string/ImageBreakdown.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/formatting/string/ImageBreakdown.java @@ -15,7 +15,7 @@ import org.jetbrains.annotations.NotNull; /** - * Newly improved by hemp with full rgb support depending on version. + * An object dedicated to converting imagery to pixel art. Improved upon by Hempfest allowing support for RGB. * * @author bobacadodl * @author Hempfest diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/Catchable.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/Catchable.java index 947d5786..5ed8bccc 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/Catchable.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/Catchable.java @@ -1,6 +1,13 @@ package com.github.sanctum.labyrinth.interfacing; -public interface Catchable { +import com.github.sanctum.labyrinth.api.Service; + +/** + * A non-linked snapshot initialization service. + * + * @param The type of snapshot. + */ +public interface Catchable extends Service { T getSnapshot(); diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/OrdinalElement.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/OrdinalElement.java index b54dcd67..ed5b1f4b 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/OrdinalElement.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/OrdinalElement.java @@ -29,4 +29,8 @@ public interface OrdinalElement { */ GenericOrdinalElement select(int ordinal, Object... args); + default GenericOrdinalElement toGeneric() { + return this instanceof GenericOrdinalElement ? (GenericOrdinalElement) this : null; + } + } diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/OrdinalProcedure.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/OrdinalProcedure.java index 45a0e731..1442e046 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/OrdinalProcedure.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/OrdinalProcedure.java @@ -14,9 +14,254 @@ * If the intended object for use contains no usage of {@link Ordinal} this utility has no use to you. * */ -public abstract class OrdinalProcedure { +public abstract class OrdinalProcedure { - OrdinalProcedure() {} + private E e; + private Iterable eI; + + protected OrdinalProcedure(E e) { + this.e = e; + } + + protected OrdinalProcedure(Iterable e) { + this.eI = e; + } + + /** + * Process all flagged ordinal's within every object. + * + * @return A list of processed elements. + */ + public OrdinalResult run() { + if (isIterable()) { + List> processed = new ArrayList<>(); + for (E o : eI) { + processed.add(run(o)); + } + return OrdinalResult.of(processed); + } else { + return OrdinalResult.of(run(e)); + } + } + + /** + * Process a specific ordinal + * + * @param ordinal The ordinal to process. + * @return A processed element. + */ + public OrdinalResult run(int ordinal) { + if (isIterable()) { + List> processed = new ArrayList<>(); + for (E o : eI) { + processed.add(run(o, ordinal)); + } + return OrdinalResult.of(processed); + } else { + return OrdinalResult.of(run(e, ordinal)); + } + } + + /** + * Process all ordinals within range (0 - specified) in order. + * + * @param ordinal The max ordinal range to process. + * @return A processed element. + */ + public OrdinalResult max(int ordinal) { + if (isIterable()) { + List> processed = new ArrayList<>(); + for (E o : eI) { + processed.add(max(o, ordinal)); + } + return OrdinalResult.of(processed); + } else { + return OrdinalResult.of(max(e, ordinal)); + } + } + + /** + * Process all ordinals within range (specified+) in order, ordinals lower than specified will not process. + * + * @param ordinal The max ordinal range to process. + * @return A processed element. + */ + public OrdinalResult min(int ordinal) { + if (isIterable()) { + List> processed = new ArrayList<>(); + for (E o : eI) { + processed.add(min(o, ordinal)); + } + return OrdinalResult.of(processed); + } else { + return OrdinalResult.of(min(e, ordinal)); + } + } + + /** + * Get a specific method from the sourced element using its declared ordinal. + * + * @param ordinal The ordinal to use. + * @return A generic ordinal containing synchronized information. + */ + public OrdinalResult get(int ordinal) { + if (isIterable()) { + List processed = new ArrayList<>(); + for (E o : eI) { + processed.add(get(o, ordinal)); + } + return OrdinalResult.of(processed); + } else { + return OrdinalResult.of(get(e, ordinal)); + } + } + + /** + * Get a specific method from the sourced element using its declared ordinal. + * + * @param ordinal The ordinal to use. + * @param args The object arguments to use if the method so requires. + * @return A generic ordinal containing synchronized information. + */ + public OrdinalResult get(int ordinal, Object... args) { + if (isIterable()) { + List processed = new ArrayList<>(); + for (E o : eI) { + processed.add(get(o, ordinal, args)); + } + return OrdinalResult.of(processed); + } else { + return OrdinalResult.of(get(e, ordinal, args)); + } + } + + public boolean isIterable() { + return eI != null; + } + + private OrdinalElement run(E element) { + AnnotationDiscovery discovery = AnnotationDiscovery.of(Ordinal.class, element).filter(true).sort(Comparator.comparingInt(value -> value.getAnnotation(Ordinal.class).value())); + for (Method m : discovery) { + try { + m.invoke(element); + } catch (Exception e) { + e.printStackTrace(); + } + } + return new ProcessedOrdinalElement<>(element); + } + + private OrdinalElement run(E element, int ordinal) { + AnnotationDiscovery discovery = AnnotationDiscovery.of(Ordinal.class, element).filter(true); + discovery.ifPresent((ord, method) -> { + if (ord.value() == ordinal) { + try { + method.invoke(element); + } catch (Exception e) { + if (e.getCause() != null) { + if (e.getCause().getMessage() == null) { + throw new OrdinalProcessException("Ordinal processing failed on #" + ordinal + " for object " + element.getClass().getTypeName(), e.getCause().getStackTrace()); + } else { + throw new OrdinalProcessException("Ordinal failure (#" + ordinal + ") @ " + element.getClass().getTypeName() + " : " + '"' + e.getCause().getMessage() + '"', e.getCause().getStackTrace()); + } + } else { + throw new OrdinalProcessException("Ordinal processing failed on #" + ordinal + " for object " + element.getClass().getSimpleName()); + } + } + } + }); + return new ProcessedOrdinalElement<>(element); + } + + private OrdinalElement max(E element, int ordinal) { + AnnotationDiscovery discovery = AnnotationDiscovery.of(Ordinal.class, element).filter(true).sort(Comparator.comparingInt(value -> value.getAnnotation(Ordinal.class).value())); + discovery.ifPresent((ord, method) -> { + if (ord.value() <= ordinal) { + try { + method.invoke(element); + } catch (Exception e) { + if (e.getCause() != null) { + if (e.getCause().getMessage() == null) { + throw new OrdinalProcessException("Ordinal processing failed on #" + ordinal + " for object " + element.getClass().getTypeName(), e.getCause().getStackTrace()); + } else { + throw new OrdinalProcessException("Ordinal failure (#" + ordinal + ") @ " + element.getClass().getTypeName() + " : " + '"' + e.getCause().getMessage() + '"', e.getCause().getStackTrace()); + } + } else { + throw new OrdinalProcessException("Ordinal processing failed on #" + ordinal + " for object " + element.getClass().getSimpleName()); + } + } + } + }); + return new ProcessedOrdinalElement<>(element); + } + + private OrdinalElement min(E element, int ordinal) { + AnnotationDiscovery discovery = AnnotationDiscovery.of(Ordinal.class, element).filter(true).sort(Comparator.comparingInt(value -> value.getAnnotation(Ordinal.class).value())); + discovery.ifPresent((ord, method) -> { + if (ord.value() >= ordinal) { + try { + method.invoke(element); + } catch (Exception e) { + if (e.getCause() != null) { + if (e.getCause().getMessage() == null) { + throw new OrdinalProcessException("Ordinal processing failed on #" + ordinal + " for object " + element.getClass().getTypeName(), e.getCause().getStackTrace()); + } else { + throw new OrdinalProcessException("Ordinal failure (#" + ordinal + ") @ " + element.getClass().getTypeName() + " : " + '"' + e.getCause().getMessage() + '"', e.getCause().getStackTrace()); + } + } else { + throw new OrdinalProcessException("Ordinal processing failed on #" + ordinal + " for object " + element.getClass().getSimpleName()); + } + } + } + }); + return new ProcessedOrdinalElement<>(element); + } + + private GenericOrdinalElement get(E element, int ordinal) { + AnnotationDiscovery discovery = AnnotationDiscovery.of(Ordinal.class, element).filter(true); + return discovery.methods().stream().filter(m -> m.getAnnotation(Ordinal.class).value() == ordinal).findFirst().map(method -> { + try { + return new GenericOrdinalElement(method.invoke(element)); + } catch (Exception exception) { + if (exception.getCause() != null) { + if (exception.getCause().getMessage() == null) { + throw new OrdinalProcessException("Ordinal processing failed on #" + ordinal + " for object " + element.getClass().getTypeName(), exception.getCause().getStackTrace()); + } else { + throw new OrdinalProcessException("Ordinal failure (#" + ordinal + ") @ " + element.getClass().getTypeName() + " : " + '"' + exception.getCause().getMessage() + '"', exception.getCause().getStackTrace()); + } + } else { + throw new OrdinalProcessException("Ordinal processing failed on #" + ordinal + " for object " + element.getClass().getSimpleName()); + } + } + }).orElseThrow(() -> new RuntimeException("Ordinal " + ordinal + " either not found or access failed.")); + } + + private GenericOrdinalElement get(E element, int ordinal, Object... args) { + AnnotationDiscovery discovery = AnnotationDiscovery.of(Ordinal.class, element).filter(true); + return discovery.methods().stream().filter(m -> m.getAnnotation(Ordinal.class).value() == ordinal).findFirst().map(method -> { + try { + return new GenericOrdinalElement(method.invoke(element, args)); + } catch (Exception exception) { + if (exception.getCause() != null) { + if (exception.getCause().getMessage() == null) { + throw new OrdinalProcessException("Ordinal processing failed on #" + ordinal + " for object " + element.getClass().getTypeName(), exception.getCause().getStackTrace()); + } else { + throw new OrdinalProcessException("Ordinal failure (#" + ordinal + ") @ " + element.getClass().getTypeName() + " : " + '"' + exception.getCause().getMessage() + '"', exception.getCause().getStackTrace()); + } + } else { + throw new OrdinalProcessException("Ordinal processing failed on #" + ordinal + " for object " + element.getClass().getSimpleName()); + } + } + }).orElseThrow(() -> new RuntimeException("Ordinal " + ordinal + " either not found or access failed.")); + } + + public static OrdinalProcedure of(E e) { + return new OrdinalProcedure(e) {}; + } + + public static OrdinalProcedure of(Iterable e) { + return new OrdinalProcedure(e) {}; + } /** * Process all flagged ordinal's within every object. diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/OrdinalResult.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/OrdinalResult.java new file mode 100644 index 00000000..f7af97e4 --- /dev/null +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/OrdinalResult.java @@ -0,0 +1,46 @@ +package com.github.sanctum.labyrinth.interfacing; + +import com.github.sanctum.labyrinth.library.TypeFlag; +import java.util.List; +import org.intellij.lang.annotations.MagicConstant; + +public interface OrdinalResult { + + default R cast(@MagicConstant(valuesFromClass = TypeFlag.class) TypeFlag flag) { + return flag.getType().cast(get().getElement()); + } + + OrdinalElement get(); + + List> getAll(); + + static OrdinalResult of(OrdinalElement e) { + return new OrdinalResult() { + @Override + public OrdinalElement get() { + return e; + } + + @Override + public List> getAll() { + return null; + } + + }; + } + + static > OrdinalResult of(List es) { + return new OrdinalResult() { + @Override + public OrdinalElement get() { + return null; + } + + @Override + public List> getAll() { + return (List>) es; + } + }; + } + +} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/WebResponse.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/WebResponse.java index 1930d1e2..5199f442 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/WebResponse.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/interfacing/WebResponse.java @@ -1,6 +1,7 @@ package com.github.sanctum.labyrinth.interfacing; import com.github.sanctum.labyrinth.LabyrinthProvider; +import com.github.sanctum.labyrinth.task.TaskScheduler; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -20,6 +21,7 @@ public interface WebResponse { static WebResponse download(ResourceCheck check, String output, String file, String type) { try { + TaskScheduler.of(check).scheduleAsync(); URL url = new URL("https://github.com/" + check.getAuthor() + "/" + check.getResource() + "/releases/download/" + check.getLatest() + "/" + check.getResource() + ".jar"); if (new File("downloads/" + output + "/" + file + "." + type).exists()) return () -> "Latest version already downloaded."; ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream()); diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/CommandUtils.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/CommandUtils.java index c78c4929..3086111f 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/CommandUtils.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/CommandUtils.java @@ -17,6 +17,7 @@ import java.util.function.Function; import org.bukkit.command.Command; import org.bukkit.command.CommandMap; +import org.bukkit.command.PluginCommand; import org.bukkit.command.SimpleCommandMap; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; @@ -87,11 +88,21 @@ public static Set getServerCommandListing() { /** * Get a Command object directly from the server command map by its label. * - * @param name label of the command + * @param label label of the command * @return Command object if found or null */ - public static @Nullable Command getCommandByLabel(@NotNull String name) { - return commands.get(name); + public static @Nullable Command getCommandByLabel(@NotNull String label) { + return commands.get(label); + } + + /** + * Get a sub command list for a given command by label. + * + * @param label label of the command. + * @return Sub command list if found or null. + */ + public static @Nullable SubCommandList getSubCommandList(@NotNull String label) { + return wrappers.get(label); } /** @@ -132,7 +143,11 @@ public static void register(@NotNull Command command) { public static void register(@NotNull SubCommand subCommand) { final Command parent = getCommandByLabel(subCommand.getCommand()); if (parent != null) { - final Plugin plugin = Optional.of((Plugin)JavaPlugin.getProvidingPlugin(parent.getClass())).orElse(LabyrinthProvider.getInstance().getPluginInstance()); + final Plugin plugin = Optional.of((Plugin)JavaPlugin.getProvidingPlugin(parent.getClass())).orElseGet(() -> { + if (parent instanceof PluginCommand) { + return ((PluginCommand)parent).getPlugin(); + } else return LabyrinthProvider.getInstance().getPluginInstance(); + }); SubCommandList wrapper = wrappers.computeIfAbsent(subCommand.getCommand(), s -> { SubCommandList w = new SubCommandList(parent){ @Ordinal(24) diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/DirectivePoint.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/DirectivePoint.java index a9a2696b..41f159b8 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/DirectivePoint.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/DirectivePoint.java @@ -3,6 +3,8 @@ import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.util.Vector; @@ -37,6 +39,28 @@ public float getCenteredPitch() { return pitch; } + public BlockFace toFace() { + switch (this) { + case North_East: + return BlockFace.NORTH_EAST; + case North: + return BlockFace.NORTH; + case North_West: + return BlockFace.NORTH_WEST; + case West: + return BlockFace.WEST; + case South_West: + return BlockFace.SOUTH_WEST; + case South: + return BlockFace.SOUTH; + case South_East: + return BlockFace.SOUTH_EAST; + case East: + return BlockFace.EAST; + } + return null; + } + public Chunk getChunk(Location start, int distanceInChunks) { double p = ((pitch + 90) * Math.PI) / 180; double ya = ((yaw + 90) * Math.PI) / 180; @@ -153,63 +177,50 @@ public static DirectivePoint getRight(DirectivePoint point) { } public static DirectivePoint get(Player p) { - DirectivePoint result = null; - float y = p.getLocation().getYaw(); + return get(p.getLocation()); + } + + static DirectivePoint get(Location loc) { + DirectivePoint result; + float y = loc.getYaw(); if (y < 0) { y += 360; } y %= 360; int i = (int) ((y + 8) / 22.5); - if (i == 0) { - result = DirectivePoint.South; - } - if (i == 1) { - result = DirectivePoint.South_West; - } - if (i == 2) { - result = DirectivePoint.South_West; - } - if (i == 3) { - result = DirectivePoint.South_West; - } - if (i == 4) { - result = DirectivePoint.West; - } - if (i == 5) { - result = DirectivePoint.North_West; - } - if (i == 6) { - result = DirectivePoint.North_West; - } - if (i == 7) { - result = DirectivePoint.North_West; - } - if (i == 8) { - result = DirectivePoint.North; - } - if (i == 9) { - result = DirectivePoint.North_East; - } - if (i == 10) { - result = DirectivePoint.North_East; - } - if (i == 11) { - result = DirectivePoint.North_East; - } - if (i == 12) { - result = DirectivePoint.East; - } - if (i == 13) { - result = DirectivePoint.South_East; - } - if (i == 14) { - result = DirectivePoint.South_East; - } - if (i == 15) { - result = DirectivePoint.South_East; - } - if (result == null) { - result = DirectivePoint.South; + switch (i) { + case 1: + case 2: + case 3: + result = DirectivePoint.South_West; + break; + case 4: + result = DirectivePoint.West; + break; + case 5: + case 6: + case 7: + result = DirectivePoint.North_West; + break; + case 8: + result = DirectivePoint.North; + break; + case 9: + case 10: + case 11: + result = DirectivePoint.North_East; + break; + case 12: + result = DirectivePoint.East; + break; + case 13: + case 14: + case 15: + result = DirectivePoint.South_East; + break; + default: + result = DirectivePoint.South; + break; } return result; } diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/Mailer.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/Mailer.java index f31f3081..1e309374 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/Mailer.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/Mailer.java @@ -124,7 +124,7 @@ public Deployable chat(@NotNull BaseComponent... components) { */ public Deployable action(@NotNull String text) { if (!this.prefix.isEmpty()) { - return new Mailable(this.sender, MailType.ACTION, prefix + " " + text); + return new Mailable(this.sender, MailType.ACTION, prefix.join() + " " + text); } return new Mailable(this.sender, MailType.ACTION, text); } diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/StringUtils.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/StringUtils.java index 305d6fae..b361bd10 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/StringUtils.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/library/StringUtils.java @@ -42,7 +42,7 @@ public final class StringUtils { * Here is where you specify either a regex for total completion results or a delimiter to separate * strings by. It is the premise for all string-based utility. * - * @param context the star context to provide for usage + * @param context the start context to provide for usage * @return a string utility */ public static StringUtils use(String context) { @@ -50,20 +50,35 @@ public static StringUtils use(String context) { } /** - * Check if the provided context exists (using case insensitive options) a target regex. + * Check if the provided context exists at the same time ignoring case sensitivity. + * + * @param regex The target regex to check for + * @return true if all provided character sequences are contained within the provided sub context. + */ + public boolean containsAnd(CharSequence... regex) { + for (CharSequence c : regex) { + if (!containsIgnoreCase(c)) { + return false; + } + } + return true; + } + + /** + * Check if the provided context exists (using case-insensitive options) a target regex. * * @param regex the target regex to check for - * @return true if the provided regex exists a case insensitive match from the target regex + * @return true if the provided sub context contains a case-insensitive match from the target regex */ public boolean containsIgnoreCase(CharSequence regex) { return Pattern.compile(Pattern.quote(regex.toString()), Pattern.CASE_INSENSITIVE).matcher(this.context).find(); } /** - * Check if the provided context exists (using case insensitive options) a target regex. + * Check if the provided context exists (using case-insensitive options) a target regex. * * @param regex the target regex to check for - * @return true if the provided regex exists a case insensitive match from the target regex + * @return true if the provided sub context contains a case-insensitive match from the target regex */ public boolean containsIgnoreCase(CharSequence... regex) { for (CharSequence sequence : regex) { @@ -77,67 +92,28 @@ public boolean containsIgnoreCase(CharSequence... regex) { public @NotNull ParsedTimeFormat parseTime() throws IllegalTimeFormatException { Pattern pattern = Pattern.compile("(\\d+)(d|hr|m|s)"); Matcher matcher = pattern.matcher(context); - long days = 0; - long hours = 0; - long minutes = 0; - long seconds = 0; + String days = null; + String hours = null; + String minutes = null; + String seconds = null; while (matcher.find()) { switch (matcher.group(2)) { case "d": - days = Long.parseLong(matcher.group(1)); + days = matcher.group(1); break; case "hr": - hours = Long.parseLong(matcher.group(1)); + hours = matcher.group(1); break; case "m": - minutes = Long.parseLong(matcher.group(1)); + minutes = matcher.group(1); break; case "s": - seconds = Long.parseLong(matcher.group(1)); + seconds = matcher.group(1); break; } } - if (days == 0 && hours == 0 && minutes == 0 && seconds == 0) throw new IllegalTimeFormatException("Time format cannot be empty!"); - long finalDays = days; - long finalHours = hours; - long finalMinutes = minutes; - long finalSeconds = seconds; - return new ParsedTimeFormat() { - @Override - public long getDays() { - return finalDays; - } - - @Override - public long getHours() { - return finalHours; - } - - @Override - public long getMinutes() { - return finalMinutes; - } - - @Override - public long getSeconds() { - return finalSeconds; - } - - @Override - public String toString() { - ZonedDateTime time = new Date().toInstant().atZone(ZoneId.systemDefault()); - String month = time.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH); - String year = String.valueOf(time.getYear()); - String day = String.valueOf(time.getDayOfMonth() + getDays()); - Date date = getDate(); - ZonedDateTime current = date.toInstant().atZone(ZoneId.systemDefault()); - String clock = current.getHour() + ":" + current.getMinute(); - // format 'Month day, year @ clock' - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - return month + " " + day + ", " + year + " @ " + clock + (calendar.get(Calendar.AM_PM) == Calendar.PM ? "pm" : "am"); - } - }; + if (days == null || hours == null || minutes == null || seconds == null) throw new IllegalTimeFormatException("Time format cannot be empty!"); + return ParsedTimeFormat.of(Long.parseLong(days), Long.parseLong(hours), Long.parseLong(minutes), Long.parseLong(seconds)); } /** diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Asynchronous.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Asynchronous.java deleted file mode 100644 index 9de05f5e..00000000 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Asynchronous.java +++ /dev/null @@ -1,281 +0,0 @@ -package com.github.sanctum.labyrinth.task; - -import com.github.sanctum.labyrinth.LabyrinthProvider; -import com.github.sanctum.labyrinth.api.LabyrinthAPI; -import com.github.sanctum.labyrinth.library.Applicable; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.IllegalPluginAccessException; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.Map; - -/** - * @deprecated A new library for this will be provided soon. - */ -@SuppressWarnings("UnusedReturnValue") -@Deprecated -public class Asynchronous { - - private final LabyrinthAPI labyrinthAPI = LabyrinthProvider.getInstance(); - private final BukkitRunnable runnable; - private Applicable apply = null; - private String cancel = null; - private boolean check; - private boolean fallback; - private boolean debug; - private Player p = null; - private Map map = null; - private Object o = null; - private TaskCancellation cancellation = null; - - protected Asynchronous(Applicable applicable) { - this.runnable = new BukkitRunnable() { - @Override - public void run() { - if (!labyrinthAPI.getConcurrentTaskIds().contains(getTaskId())) { - labyrinthAPI.getConcurrentTaskIds().add(getTaskId()); - } - try { - if (cancellation != null) { - cancellation.execute(new ScheduledTask(this)); - applicable.run(); - if (apply != null) { - apply.run(); - } - labyrinthAPI.getConcurrentTaskIds().remove(getTaskId()); - return; - } - if (cancel == null) { - if (fallback) { - if (Bukkit.getOnlinePlayers().size() == 0) { - this.cancel(); - return; - } - } - if (map != null) { - if (!map.containsKey(o)) { - this.cancel(); - if (debug) { - labyrinthAPI.getLogger().info("Closing un-used task, target player in-activity."); - } - return; - } - } - if (check) { - if (p == null || !p.isOnline()) { - if (debug) { - labyrinthAPI.getLogger().info("Closing un-used task, target player in-activity."); - } - this.cancel(); - return; - } - } - applicable.run(); - if (apply != null) { - apply.run(); - } - labyrinthAPI.getConcurrentTaskIds().remove(getTaskId()); - } else { - int count = Integer.parseInt(cancel); - count--; - cancel = String.valueOf(count); - if (fallback) { - if (Bukkit.getOnlinePlayers().size() == 0) { - this.cancel(); - return; - } - } - if (map != null) { - if (!map.containsKey(o)) { - this.cancel(); - if (debug) { - labyrinthAPI.getLogger().info("Closing un-used task, target player in-activity."); - } - return; - } - } - if (count > 0) { - if (check) { - if (p == null || !p.isOnline()) { - if (debug) { - labyrinthAPI.getLogger().info("Closing un-used task, target player in-activity."); - } - this.cancel(); - return; - } - } - applicable.run(); - if (apply != null) { - apply.run(); - } - labyrinthAPI.getConcurrentTaskIds().remove(getTaskId()); - } else { - if (debug) { - labyrinthAPI.getLogger().info("Closing task, max usage counter achieved."); - } - this.cancel(); - } - } - } catch (Exception e) { - if (debug) { - labyrinthAPI.getLogger().severe("Closing task, an exception occurred and was stopped. "); - e.printStackTrace(); - } - this.cancel(); - labyrinthAPI.getLogger().severe(e::getMessage); - } - } - }; - } - - public void cancelTask() { - if (!this.runnable.isCancelled()) { - this.runnable.cancel(); - } - } - - /** - * Automatically cancel the task in the absence of a specified player. - * - *

If the task is dependent on a target player you can use this - * for easy automatic task cleanup.

- * - * @param player the player to query - * @return this asynchronous task builder - */ - public Asynchronous cancelAfter(Player player) { - this.check = true; - this.p = player; - return this; - } - - /** - * Automatically cancel the task from a specified precondition. - *

- * This will simply cancel the task of your own will @ precondition. - * - * @param condition the condition to fire the cancellation - * @return this asynchronous task builder - */ - public Asynchronous cancelAfter(boolean condition) { - this.check = condition; - return this; - } - - /** - * Automatically cancel the task after a specified amount of executions - * - *

Will work in tandem with other cancellation preconditions. - * Use for easy automatic task cleanup.

- * - * @param count the amount of executions to run - * @return this asynchronous task builder - */ - public Asynchronous cancelAfter(int count) { - this.cancel = String.valueOf(count + 1); - return this; - } - - /** - * Define your own running logic for cancellations. - * - * @param cancellation the cancellation objective - * @return this asynchronous task builder - */ - public Asynchronous cancelAfter(TaskCancellation cancellation) { - this.cancellation = cancellation; - return this; - } - - /** - * Automatically cancel the task if a target object goes missing from a map. - * - * @param map the map to query keys from - * @param o the object to check for removal - * @return this asynchronous task builder - */ - public Asynchronous cancelAbsence(Map map, Object o) { - this.map = map; - this.o = o; - return this; - } - - /** - * Automatically cancel the task upon the instance of an empty server. - * - * @return this asynchronous task builder - */ - public Asynchronous cancelEmpty() { - this.fallback = true; - return this; - } - - /** - * Use this to print helpful exception/console information upon automatic - * task cancellations. - * - *

If the task throws an un-caught exception it is recommended this is used to display - * any possible source to possible problems that occur.

- * - * @return this asynchronous task builder - */ - public Asynchronous debug() { - this.debug = true; - return this; - } - - /** - * Use this to apply defined logic to the task as soon as it finishes. - * - *

The information passed here will have secondary importance and will be called - * directly after the initial task has executed one time for each time ran.

- * - * @param applicable the information to pass be it via Void or lambda reference - * @return this asynchronous task builder - */ - public Asynchronous applyAfter(Applicable applicable) { - this.apply = applicable; - return this; - } - - /** - * Run this scheduled task on the very next tick. - */ - public void run() { - try { - runnable.runTaskAsynchronously(labyrinthAPI.getPluginInstance()); - } catch (IllegalPluginAccessException ignored) { - } - } - - /** - * Run this scheduled task after a specified amount of ticks. - * - * @param interval the amount of in-game ticks to wait - */ - public void wait(int interval) { - try { - runnable.runTaskLaterAsynchronously(labyrinthAPI.getPluginInstance(), interval); - } catch (IllegalPluginAccessException ignored) { - } - } - - /** - * Run this scheduled task repeatedly unless otherwise cancelled. - * - *

The interval at which this task repeats is based off the delay you specify. - * Immediately after the delay finishes the task will run once and wait the specified "period" until re-cycling. - * Therefore running the delay > task > period , all over again.

- * - * @param delay the amount of time to wait before executing the task - * @param period the amount of time to wait to cycle the task - */ - public void repeat(int delay, int period) { - try { - runnable.runTaskTimerAsynchronously(labyrinthAPI.getPluginInstance(), delay, period); - } catch (IllegalPluginAccessException ignored) { - } - } - -} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/AsynchronousTaskChain.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/AsynchronousTaskChain.java index 27869f36..15fd5e79 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/AsynchronousTaskChain.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/AsynchronousTaskChain.java @@ -1,6 +1,7 @@ package com.github.sanctum.labyrinth.task; import com.github.sanctum.labyrinth.annotation.Ordinal; +import com.github.sanctum.labyrinth.formatting.string.RandomID; import java.util.Date; import java.util.Timer; import java.util.concurrent.TimeUnit; @@ -18,19 +19,21 @@ public AsynchronousTaskChain() { @Override public AsynchronousTaskChain run(final @NotNull Task task) { task.parent = this; - timer.schedule(task, 0); + timer.schedule(task.setAsync(true), 0); return this; } @Override public AsynchronousTaskChain run(final @NotNull Runnable data) { - Task task = new Task("key", Task.SINGULAR, this) { + Task task = new Task(new RandomID().generate(), Task.SINGULAR, this) { + private static final long serialVersionUID = 1024238305361097135L; + @Ordinal public void execute() { data.run(); } }; - timer.schedule(task, 0); + timer.schedule(task.setAsync(true), 0); return this; } @@ -38,20 +41,22 @@ public void execute() { public AsynchronousTaskChain wait(final @NotNull Task task, long delay) { task.parent = this; map.put(task.getKey(), task); - timer.schedule(task, delay); + timer.schedule(task.setAsync(true), delay); return this; } @Override public AsynchronousTaskChain wait(final @NotNull Runnable data, String key, long milli) { Task task = new Task(key, Task.SINGULAR, this) { + private static final long serialVersionUID = 5064153492626085962L; + @Ordinal public void execute() { data.run(); } }; map.put(key, task); - timer.schedule(task, milli); + timer.schedule(task.setAsync(true), milli); return this; } @@ -59,20 +64,22 @@ public void execute() { public AsynchronousTaskChain wait(final @NotNull Task task, @NotNull Date start) { task.parent = this; map.put(task.getKey(), task); - timer.schedule(task, start); + timer.schedule(task.setAsync(true), start); return this; } @Override public AsynchronousTaskChain wait(final @NotNull Runnable data, String key, @NotNull Date start) { Task task = new Task(key, Task.SINGULAR, this) { + private static final long serialVersionUID = -809723855257869160L; + @Ordinal public void execute() { data.run(); } }; map.put(key, task); - timer.schedule(task, start); + timer.schedule(task.setAsync(true), start); return this; } @@ -80,7 +87,7 @@ public void execute() { public AsynchronousTaskChain repeat(final @NotNull Task task, long delay, long period) { if (!map.containsKey(task.getKey())) { map.put(task.getKey(), task); - timer.scheduleAtFixedRate(task, delay, period); + timer.scheduleAtFixedRate(task.setAsync(true), delay, period); } return this; } @@ -89,13 +96,15 @@ public AsynchronousTaskChain repeat(final @NotNull Task task, long delay, long p public AsynchronousTaskChain repeat(final @NotNull Consumer consumer, @NotNull String key, long delay, long period) { if (!map.containsKey(key)) { Task task = new Task(key, Task.REPEATABLE, this) { + private static final long serialVersionUID = -9049322776279344996L; + @Ordinal public void execute() { consumer.accept(this); } }; map.put(key, task); - timer.scheduleAtFixedRate(task, delay, period); + timer.scheduleAtFixedRate(task.setAsync(true), delay, period); } return this; } @@ -105,7 +114,7 @@ public AsynchronousTaskChain repeat(final @NotNull Task task, @NotNull Date star task.parent = this; if (!map.containsKey(task.getKey())) { map.put(task.getKey(), task); - timer.scheduleAtFixedRate(task, start, period); + timer.scheduleAtFixedRate(task.setAsync(true), start, period); } return this; } @@ -114,13 +123,15 @@ public AsynchronousTaskChain repeat(final @NotNull Task task, @NotNull Date star public AsynchronousTaskChain repeat(final @NotNull Consumer consumer, @NotNull String key, @NotNull Date start, long period) { if (!map.containsKey(key)) { Task task = new Task(key, Task.REPEATABLE, this) { + private static final long serialVersionUID = 2087638843164641921L; + @Ordinal public void execute() { consumer.accept(this); } }; map.put(key, task); - timer.scheduleAtFixedRate(task, start, period); + timer.scheduleAtFixedRate(task.setAsync(true), start, period); } return this; } diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/LabyrinthTaskScheduler.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/CustomTaskScheduler.java similarity index 93% rename from labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/LabyrinthTaskScheduler.java rename to labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/CustomTaskScheduler.java index a9dcd242..c24efc92 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/LabyrinthTaskScheduler.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/CustomTaskScheduler.java @@ -3,12 +3,12 @@ import com.github.sanctum.labyrinth.library.Applicable; import org.jetbrains.annotations.NotNull; -final class LabyrinthTaskScheduler implements TaskScheduler { +final class CustomTaskScheduler implements TaskScheduler { private static final TaskMonitor manager = TaskMonitor.getLocalInstance(); - private final Applicable data; + private final Task data; - LabyrinthTaskScheduler(@NotNull Applicable data) { + CustomTaskScheduler(@NotNull Task data) { this.data = data; } @@ -36,6 +36,7 @@ final class LabyrinthTaskScheduler implements TaskScheduler { return manager.scheduleLaterAsync(data, key, delay); } + public @NotNull RenderedTask scheduleTimer(String key, long delay, long period) { return manager.scheduleTimer(data, key, delay, period); } diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/NormalTaskScheduler.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/NormalTaskScheduler.java new file mode 100644 index 00000000..58837db4 --- /dev/null +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/NormalTaskScheduler.java @@ -0,0 +1,71 @@ +package com.github.sanctum.labyrinth.task; + +import com.github.sanctum.labyrinth.library.Applicable; +import org.jetbrains.annotations.NotNull; + +final class NormalTaskScheduler implements TaskScheduler { + + private static final TaskMonitor manager = TaskMonitor.getLocalInstance(); + private final Runnable data; + + NormalTaskScheduler(@NotNull Runnable data) { + this.data = data; + } + + public @NotNull RenderedTask schedule() { + return manager.schedule(data); + } + + public @NotNull RenderedTask scheduleAsync() { + return manager.scheduleAsync(data); + } + + public @NotNull RenderedTask scheduleLater(long delay) { + return manager.scheduleLater(data, delay); + } + + public @NotNull RenderedTask scheduleLater(String key, long delay) { + return manager.scheduleLater(data, key, delay); + } + + public @NotNull RenderedTask scheduleLaterAsync(long delay) { + return manager.scheduleLaterAsync(data, delay); + } + + public @NotNull RenderedTask scheduleLaterAsync(String key, long delay) { + return manager.scheduleLaterAsync(data, key, delay); + } + + public @NotNull RenderedTask scheduleTimer(String key, long delay, long period) { + return manager.scheduleTimer(data, key, delay, period); + } + + public @NotNull RenderedTask scheduleTimerAsync(String key, long delay, long period) { + return manager.scheduleTimerAsync(data, key, delay, period); + } + + public @NotNull RenderedTask scheduleLater(long delay, TaskPredicate... flags) { + return manager.scheduleLater(data, delay, flags); + } + + public @NotNull RenderedTask scheduleLater(String key, long delay, TaskPredicate... flags) { + return manager.scheduleLater(data, key, delay, flags); + } + + public @NotNull RenderedTask scheduleLaterAsync(long delay, TaskPredicate... flags) { + return manager.scheduleLaterAsync(data, delay, flags); + } + + public @NotNull RenderedTask scheduleLaterAsync(String key, long delay, TaskPredicate... flags) { + return manager.scheduleLaterAsync(data, key, delay, flags); + } + + public @NotNull RenderedTask scheduleTimer(String key, long delay, long period, TaskPredicate... flags) { + return manager.scheduleTimer(data, key, delay, period, flags); + } + + public @NotNull RenderedTask scheduleTimerAsync(String key, long delay, long period, TaskPredicate... flags) { + return manager.scheduleTimerAsync(data, key, delay, period, flags); + } + +} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/RenderedTask.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/RenderedTask.java index f5fcad3b..e2b5f59f 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/RenderedTask.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/RenderedTask.java @@ -6,12 +6,9 @@ import com.github.sanctum.labyrinth.annotation.Ordinal; import com.github.sanctum.labyrinth.api.TaskService; import com.github.sanctum.labyrinth.formatting.string.RandomID; -import com.github.sanctum.labyrinth.interfacing.OrdinalProcedure; import com.github.sanctum.labyrinth.library.Applicable; import com.github.sanctum.labyrinth.library.TimeWatch; -import java.util.HashSet; import java.util.Objects; -import java.util.Set; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -47,7 +44,7 @@ default boolean isConcurrent() { return getId() != null; } - default @NotNull TaskScheduler next(@NotNull Applicable data) { + default @NotNull TaskScheduler next(@NotNull Runnable data) { return TaskScheduler.of(data); } @@ -77,15 +74,125 @@ enum Type { } - static @NotNull RenderedTask of(Applicable data, @MagicConstant(valuesFromClass = TaskService.class) int runtime) { + static @NotNull RenderedTask of(T data, @MagicConstant(valuesFromClass = TaskService.class) int runtime) { return new RenderedTask() { - private final Task task = new Task(new RandomID().generate()) { - @Ordinal - void execute() { - data.run(); + @Override + public int getRuntime() { + return runtime; + } + + @Override + public long getDelay() { + return 0; + } + + @Override + public long getPeriod() { + return 0; + } + + @Override + public boolean isRunning() { + return data != null && !data.isCancelled(); + } + + @Ordinal + public @NotNull Task getTask() { + return data; + } + + @Override + public @Nullable String getId() { + return null; + } + + @Override + public @NotNull Type getType() { + return Type.SINGULAR; + } + + @Override + public @NotNull TimeWatch getLastRendered() { + return TimeWatch.start(getTask().scheduledExecutionTime()); + } + + @Override + public @NotNull RenderedTask dependOn(@NotNull TaskPredicate intent) { + data.listen(intent); + return this; + } + }; + } + + static @NotNull RenderedTask of(T data, @Nullable String key, @MagicConstant(valuesFromClass = TaskService.class) int runtime, long delay, long period) { + return new RenderedTask() { + + @Override + public int getRuntime() { + return runtime; + } + + @Override + public boolean isRunning() { + return data != null && !data.isCancelled(); + } + + @Ordinal + public @NotNull Task getTask() { + return data; + } + + @Override + public @Nullable String getId() { + return key; + } + + @Override + public @NotNull Type getType() { + return isConcurrent() && getDelay() != 0 && getPeriod() != 0 ? Type.REPEATABLE : Type.DELAYED; + } + + @Override + public @NotNull TimeWatch getLastRendered() { + return TimeWatch.start(getTask().scheduledExecutionTime()); + } + + @Override + public @NotNull RenderedTask dependOn(@NotNull TaskPredicate intent) { + switch (getRuntime()) { + case 0: + TaskScheduler.of(() -> data.listen(intent)).schedule(); + break; + case 1: + TaskScheduler.of(() -> data.listen(intent)).scheduleAsync(); + break; + } + return this; + } + + @Override + public long getDelay() { + if (delay != -1) { + return delay; + } + return 0; + } + + @Override + public long getPeriod() { + if (period != -1) { + return period; } + return 0; + } + }; + } + static @NotNull RenderedTask of(Runnable data, @MagicConstant(valuesFromClass = TaskService.class) int runtime) { + return new RenderedTask() { + private final Task task = new Task(new RandomID().generate(), runtime, data) { + private static final long serialVersionUID = 87916092504686934L; }; @Override @@ -135,25 +242,10 @@ public boolean isRunning() { }; } - static @NotNull RenderedTask of(Applicable data, @Nullable String key, @MagicConstant(valuesFromClass = TaskService.class) int runtime, long delay, long period) { + static @NotNull RenderedTask of(Runnable data, @Nullable String key, @MagicConstant(valuesFromClass = TaskService.class) int runtime, long delay, long period) { return new RenderedTask() { - private final Set> flags = new HashSet<>(); - private final Task task = new Task(new RandomID().generate()) { - - @Ordinal - void execute() { - boolean stop = false; - for (TaskPredicate flag : flags) { - if (!flag.accept(this)) { - stop = true; - break; - } - } - if (!stop) { - data.run(); - } - } - + private final Task task = new Task(key != null ? key : new RandomID().generate(), runtime, data) { + private static final long serialVersionUID = 2948251326991055359L; }; @Override @@ -190,10 +282,10 @@ public boolean isRunning() { public @NotNull RenderedTask dependOn(@NotNull TaskPredicate intent) { switch (getRuntime()) { case 0: - TaskScheduler.of(() -> flags.add(intent)).schedule(); + TaskScheduler.of(() -> task.listen(intent)).schedule(); break; case 1: - TaskScheduler.of(() -> flags.add(intent)).scheduleAsync(); + TaskScheduler.of(() -> task.listen(intent)).scheduleAsync(); break; } return this; diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Schedule.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Schedule.java deleted file mode 100644 index 64cfe214..00000000 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Schedule.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.github.sanctum.labyrinth.task; - - -import com.github.sanctum.labyrinth.library.Applicable; -import org.bukkit.entity.Player; - -/** - * @deprecated Use {@link TaskScheduler} instead!! - */ -@Deprecated -public class Schedule { - - /** - * A basic builder for a synchronous specific task you wish to complete. - * - *

Execution Results: [run, wait, repeat, repeatReal, waitReal] - *

- * Pre-conditions: [{@link Synchronous#cancelEmpty()}, - * {@link Synchronous#cancelAfter(Player)}, - * {@link Synchronous#cancelAfter(int)}] - * - * @param applicable the applicable data to execute within the task via void or lambda reference - * @return a new synchronous task builder - */ - @Deprecated - public static Synchronous sync(Applicable applicable) { - return new Synchronous(applicable); - } - - /** - * A basic builder for an asynchronous specific task you wish to complete. - * - *

Execution Results: [run, wait, repeat] - *

- * Pre-conditions: [{@link Asynchronous#cancelAfter(Player)}, - * {@link Asynchronous#cancelAfter(int)}, - * {@link Asynchronous#cancelEmpty()}] - * - * @param applicable the applicable data to execute within the task via void or lambda reference - * @return a new synchronous task builder - */ - @Deprecated - public static Asynchronous async(Applicable applicable) { - return new Asynchronous(applicable); - } - -} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/ScheduledTask.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/ScheduledTask.java deleted file mode 100644 index 20cd4758..00000000 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/ScheduledTask.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.github.sanctum.labyrinth.task; - -import org.bukkit.scheduler.BukkitRunnable; - -@Deprecated -public class ScheduledTask { - - protected final BukkitRunnable runnable; - - protected ScheduledTask(BukkitRunnable runnable) { - this.runnable = runnable; - } - - public synchronized void cancel() { - this.runnable.cancel(); - } - - public synchronized boolean isCancelled() { - return this.runnable.isCancelled(); - } - - public synchronized int getId() { - return this.runnable.getTaskId(); - } - -} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Synchronous.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Synchronous.java deleted file mode 100644 index 09746f34..00000000 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Synchronous.java +++ /dev/null @@ -1,338 +0,0 @@ -package com.github.sanctum.labyrinth.task; - -import com.github.sanctum.labyrinth.LabyrinthProvider; -import com.github.sanctum.labyrinth.api.LabyrinthAPI; -import com.github.sanctum.labyrinth.library.Applicable; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.IllegalPluginAccessException; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.Map; - -/** - * @deprecated A new library for this will be provided soon. - */ -@Deprecated -public class Synchronous { - - private final LabyrinthAPI labyrinthAPI = LabyrinthProvider.getInstance(); - private final BukkitRunnable runnable; - private final Applicable initial; - private Applicable apply = null; - private Map map = null; - private Object o = null; - private boolean check; - private boolean debug; - private boolean fallback; - private String cancel = null; - private Player p = null; - private TaskCancellation cancellation = null; - - protected Synchronous(Applicable applicable) { - this.initial = applicable; - this.runnable = new BukkitRunnable() { - @Override - public void run() { - if (!labyrinthAPI.getConcurrentTaskIds().contains(getTaskId())) { - labyrinthAPI.getConcurrentTaskIds().add(getTaskId()); - } - try { - if (cancellation != null) { - cancellation.execute(new ScheduledTask(this)); - applicable.run(); - if (apply != null) { - apply.run(); - } - labyrinthAPI.getConcurrentTaskIds().remove(getTaskId()); - return; - } - if (cancel == null) { - if (fallback) { - if (Bukkit.getOnlinePlayers().size() == 0) { - cancelTask(); - return; - } - } - if (map != null) { - if (!map.containsKey(o)) { - cancelTask(); - if (debug) { - labyrinthAPI.getLogger().info("Closing un-used task, target player in-activity."); - } - return; - } - } - if (check) { - if (p == null || !p.isOnline()) { - if (debug) { - labyrinthAPI.getLogger().info("Closing un-used task, target player in-activity."); - } - cancelTask(); - return; - } - } - applicable.run(); - if (apply != null) { - apply.run(); - } - labyrinthAPI.getConcurrentTaskIds().remove(getTaskId()); - } else { - int count = Integer.parseInt(cancel); - count--; - cancel = String.valueOf(count); - if (fallback) { - if (Bukkit.getOnlinePlayers().size() == 0) { - cancelTask(); - return; - } - } - if (map != null) { - if (!map.containsKey(o)) { - cancelTask(); - if (debug) { - labyrinthAPI.getLogger().info("Closing un-used task, target object in-activity."); - } - return; - } - } - if (count > 0) { - if (check) { - if (p == null || !p.isOnline()) { - if (debug) { - labyrinthAPI.getLogger().info("Closing un-used task, target player in-activity."); - } - cancelTask(); - return; - } - } - applicable.run(); - if (apply != null) { - apply.run(); - } - labyrinthAPI.getConcurrentTaskIds().remove(getTaskId()); - } else { - if (debug) { - labyrinthAPI.getLogger().info("Closing task, max usage counter achieved."); - } - cancelTask(); - } - } - } catch (Exception e) { - if (debug) { - labyrinthAPI.getLogger().severe("Closing task, an exception occurred and was stopped."); - e.printStackTrace(); - } - cancelTask(); - labyrinthAPI.getLogger().severe(e::getMessage); - } - } - }; - } - - public boolean isRunning() { - try { - return !this.runnable.isCancelled(); - } catch (IllegalStateException ignored) { - return false; - } - } - - public void cancelTask() { - if (!this.runnable.isCancelled()) { - runnable.cancel(); - } - } - - /** - * Automatically cancel the task in the absence of a specified player. - *

- * If the task is dependent on a target player, you can use this - * for easy automatic task cleanup. - * - * @param p the player to query - * @return this synchronous task builder - */ - public Synchronous cancelAfter(Player p) { - this.check = true; - this.p = p; - return this; - } - - /** - * Automatically cancel the task from a specified precondition. - *

- * This will simply cancel the task of your own will @ precondition. - * - * @param condition the condition to fire the cancellation - * @return this synchronous task builder - */ - public Synchronous cancelAfter(boolean condition) { - this.check = condition; - return this; - } - - /** - * Automatically cancel the task after a specified amount of executions - * - *

Will work in tandem with other cancellation preconditions. - * Use for easy automatic task cleanup.

- * - * @param count the amount of executions to run - * @return this synchronous task builder - */ - public Synchronous cancelAfter(int count) { - this.cancel = String.valueOf(count + 1); - return this; - } - - /** - * Define your own running logic for cancellations. - * - * @param cancellation the cancellation objective - * @return this synchronous task builder - */ - public Synchronous cancelAfter(TaskCancellation cancellation) { - this.cancellation = cancellation; - return this; - } - - /** - * Automatically cancel the task if a target object goes missing from a map. - * - * @param map the map to query keys from - * @param o the object to check for removal - * @return this synchronous task builder - */ - public Synchronous cancelAbsence(Map map, Object o) { - this.map = map; - this.o = o; - return this; - } - - /** - * Automatically cancel the task upon the instance of an empty server. - * - * @return this synchronous task builder - */ - public Synchronous cancelEmpty() { - this.fallback = true; - return this; - } - - /** - * Use this to print helpful exception/console information upon automatic - * task cancellations. - * - *

If the task throws an un-caught exception it is recommended this is used to display - * any possible source to possible problems that occur.

- * - * @return this synchronous task builder - */ - public Synchronous debug() { - this.debug = true; - return this; - } - - /** - * Use this to apply defined logic to the task as soon as it finishes. - * - *

The information passed here will have secondary importance and will be called - * directly after the initial task has executed one time for each time ran.

- * - * @param applicable the information to pass be it via Void or lambda reference - * @return this synchronous task builder - */ - public Synchronous applyAfter(Applicable applicable) { - this.apply = applicable; - return this; - } - - /** - * Run this scheduled task on the very next tick. - */ - public void run() { - try { - runnable.runTask(labyrinthAPI.getPluginInstance()); - } catch (IllegalPluginAccessException ignored) { - } - } - - /** - * Run this scheduled task after a specified amount of ticks. - * - * @param interval the amount of in-game ticks to wait - */ - public void wait(int interval) { - try { - runnable.runTaskLater(labyrinthAPI.getPluginInstance(), interval); - } catch (IllegalPluginAccessException ignored) { - } - } - - /** - * Wait an interval of time before running this sync task. - *

- * This method uses 20 ticks = 1 second exactly, so if your - * delay logic is based on real time, use this method. - * - * @param interval real-time delay where 20 ticks = 1 second - */ - public void waitReal(int interval) { - Schedule.async(() -> Schedule.sync(initial).run()).debug().wait(interval); - } - - /** - * Run this scheduled task repeatedly unless otherwise cancelled. - * - *

The interval at which this task repeats is based off the delay you specify. - * Immediately after the delay finishes the task will run once and wait the specified "period" until re-cycling. - * Therefore running the delay > task > period , all over again.

- * - * @param delay the amount of time to wait before executing the task - * @param period the amount of time to wait to cycle the task - */ - public void repeat(int delay, int period) { - try { - runnable.runTaskTimer(labyrinthAPI.getPluginInstance(), delay, period); - } catch (IllegalPluginAccessException ignored) { - } - } - - /** - * Wait a delay of real time before running this sync task and - * repeat it every period elapsed until cancelled. - *

- * This method uses 20 ticks = 1 second exactly, so if your - * delay+repeat logic is based on real time, use this method. - * - * @param delay real-time delay where 20 ticks = 1 second - * @param period real-time period where 20 ticks = 1 second - */ - public void repeatReal(int delay, int period) { - Asynchronous schedule = Schedule.async(() -> Schedule.sync(initial).debug().wait(1)).debug(); - if (map != null) { - schedule.cancelAbsence(map, o); - } - if (this.cancel != null) { - if (check) { - schedule.cancelAfter(Integer.parseInt(this.cancel)); - } - } - if (this.cancellation != null) { - schedule.cancelAfter(this.cancellation); - } - if (this.p != null) { - schedule.cancelAfter(this.p); - } - if (this.check) { - schedule.cancelAfter(true); - } - if (apply != null) { - schedule.applyAfter(apply); - } - - schedule.repeat(delay, period); - } - -} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/SynchronousTaskChain.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/SynchronousTaskChain.java index 2096e38c..78a5174f 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/SynchronousTaskChain.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/SynchronousTaskChain.java @@ -25,25 +25,18 @@ public SynchronousTaskChain(Plugin host) { @Override public SynchronousTaskChain run(final @NotNull Task task) { task.parent = this; - timer.schedule(new Task("dummy-" + task.getKey()) { - @Ordinal - public void execute() { - if (task.isCancelled()) { - cancel(); - return; - } - Bukkit.getScheduler().runTask(host, () -> OrdinalProcedure.process(task, 0)); - } - }, 0); + timer.schedule(task, 0); return this; } @Override public SynchronousTaskChain run(final @NotNull Runnable data) { Task task = new Task("dummy", Task.SINGULAR, this) { + private static final long serialVersionUID = 8068952665686647490L; + @Ordinal public void execute() { - Bukkit.getScheduler().runTask(host, data); + data.run(); } }; timer.schedule(task, 0); @@ -53,27 +46,19 @@ public void execute() { @Override public SynchronousTaskChain wait(final @NotNull Task task, long delay) { task.parent = this; - Task t = new Task(task.getKey(), Task.SINGULAR, this) { - @Ordinal - public void execute() { - if (task.isCancelled()) { - cancel(); - return; - } - Bukkit.getScheduler().runTask(host, () -> OrdinalProcedure.process(task, 0)); - } - }; - timer.schedule(t, delay); - map.put(task.getKey(), t); + timer.schedule(task, delay); + map.put(task.getKey(), task); return this; } @Override public SynchronousTaskChain wait(final @NotNull Runnable data, String key, long milli) { Task task = new Task(key, Task.SINGULAR, this) { + private static final long serialVersionUID = 4057999550419202270L; + @Ordinal public void execute() { - Bukkit.getScheduler().runTask(host, data); + data.run(); } }; map.put(key, task); @@ -84,27 +69,19 @@ public void execute() { @Override public SynchronousTaskChain wait(final @NotNull Task task, @NotNull Date start) { task.parent = this; - Task t = new Task(task.getKey(), Task.SINGULAR, this) { - @Ordinal - public void execute() { - if (task.isCancelled()) { - cancel(); - return; - } - Bukkit.getScheduler().runTask(host, () -> OrdinalProcedure.process(task, 0)); - } - }; - map.put(task.getKey(), t); - timer.schedule(t, start); + map.put(task.getKey(), task); + timer.schedule(task, start); return this; } @Override public SynchronousTaskChain wait(final @NotNull Runnable data, String key, @NotNull Date start) { Task task = new Task(key, Task.SINGULAR, this) { + private static final long serialVersionUID = 3310911037523100957L; + @Ordinal public void execute() { - Bukkit.getScheduler().runTask(host, data); + data.run(); } }; map.put(key, task); @@ -115,25 +92,8 @@ public void execute() { @Override public SynchronousTaskChain repeat(final @NotNull Task task, long delay, long period) { if (!map.containsKey(task.getKey())) { - Task t = new Task(task.getKey(), Task.REPEATABLE, this) { - @Ordinal - public void execute() { - - if (!host.isEnabled()) { - this.cancel(); - return; - } - - if (task.isCancelled()) { - cancel(); - return; - } - - Bukkit.getScheduler().runTask(host, () -> OrdinalProcedure.process(task, 0)); - } - }; - map.put(task.getKey(), t); - timer.scheduleAtFixedRate(t, delay, period); + map.put(task.getKey(), task); + timer.scheduleAtFixedRate(task, delay, period); } return this; } @@ -142,14 +102,11 @@ public void execute() { public SynchronousTaskChain repeat(final @NotNull Consumer consumer, @NotNull String key, long delay, long period) { if (!map.containsKey(key)) { Task task = new Task(key, Task.REPEATABLE, this) { + private static final long serialVersionUID = 6685875459466218624L; + @Ordinal public void execute() { - if (!host.isEnabled()) { - this.cancel(); - return; - } - - Bukkit.getScheduler().runTask(host, () -> consumer.accept(this)); + consumer.accept(this); } }; map.put(key, task); @@ -162,24 +119,8 @@ public void execute() { public SynchronousTaskChain repeat(final @NotNull Task task, @NotNull Date start, long period) { task.parent = this; if (!map.containsKey(task.getKey())) { - Task t = new Task(task.getKey(), Task.REPEATABLE, this) { - @Ordinal - public void execute() { - if (!host.isEnabled()) { - this.cancel(); - return; - } - - if (task.isCancelled()) { - cancel(); - return; - } - - Bukkit.getScheduler().runTask(host, () -> OrdinalProcedure.process(task, 0)); - } - }; - map.put(task.getKey(), t); - timer.scheduleAtFixedRate(t, start, period); + map.put(task.getKey(), task); + timer.scheduleAtFixedRate(task, start, period); } return this; } @@ -188,13 +129,11 @@ public void execute() { public SynchronousTaskChain repeat(final @NotNull Consumer consumer, @NotNull String key, @NotNull Date start, long period) { if (!map.containsKey(key)) { Task task = new Task(key, Task.REPEATABLE, this) { + private static final long serialVersionUID = 4614422706913899876L; + @Ordinal public void execute() { - if (!host.isEnabled()) { - this.cancel(); - return; - } - Bukkit.getScheduler().runTask(host, () -> consumer.accept(this)); + consumer.accept(this); } }; map.put(key, task); diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Task.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Task.java index 6b5eb6dc..2611d1e8 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Task.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/Task.java @@ -1,11 +1,19 @@ package com.github.sanctum.labyrinth.task; +import com.github.sanctum.labyrinth.LabyrinthProvider; import com.github.sanctum.labyrinth.annotation.Note; +import com.github.sanctum.labyrinth.api.TaskService; +import com.github.sanctum.labyrinth.data.container.LabyrinthCollection; +import com.github.sanctum.labyrinth.data.container.LabyrinthList; import com.github.sanctum.labyrinth.interfacing.OrdinalProcedure; import com.github.sanctum.labyrinth.library.Applicable; import com.github.sanctum.labyrinth.library.TypeFlag; import java.util.TimerTask; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitScheduler; import org.intellij.lang.annotations.MagicConstant; +import org.jetbrains.annotations.NotNull; @Note("This class requires a void method with ordinal level 0") public abstract class Task extends TimerTask implements Applicable { @@ -15,26 +23,45 @@ public abstract class Task extends TimerTask implements Applicable { public static final int SINGULAR = 0; public static final int REPEATABLE = 1; private static final long serialVersionUID = 5781615452181138418L; + private static final Plugin host = LabyrinthProvider.getInstance().getPluginInstance(); protected TaskChain parent; + private final LabyrinthCollection> predicates = new LabyrinthList<>(); + private final BukkitScheduler bukkitScheduler = Bukkit.getScheduler(); + private final OrdinalProcedure procedure; private final String key; + private Runnable runnable; private final int type; + private boolean async; private boolean cancelled; - public Task(String key) { + public Task(String key, @MagicConstant(valuesFromClass = TaskService.class) int runtime) { this.type = SINGULAR; this.key = key; + this.parent = LabyrinthProvider.getInstance().getScheduler(runtime); + this.procedure = OrdinalProcedure.of(this); } - public Task(String key, @MagicConstant(intValues = {SINGULAR, REPEATABLE}) int type) { + public Task(String key, @MagicConstant(valuesFromClass = TaskService.class) int runtime, @NotNull Runnable runnable) { + this.type = SINGULAR; + this.key = key; + this.runnable = runnable; + this.parent = LabyrinthProvider.getInstance().getScheduler(runtime); + this.procedure = OrdinalProcedure.of(this); + } + + public Task(String key, @MagicConstant(intValues = {SINGULAR, REPEATABLE}) int type, @MagicConstant(valuesFromClass = TaskService.class) int runtime) { this.type = type; this.key = key; + this.parent = LabyrinthProvider.getInstance().getScheduler(runtime); + this.procedure = OrdinalProcedure.of(this); } public Task(String key, @MagicConstant(intValues = {SINGULAR, REPEATABLE}) int type, final TaskChain parent) { this.parent = parent; this.type = type; this.key = key; + this.procedure = OrdinalProcedure.of(this); } public final String getKey() { @@ -49,24 +76,39 @@ public final boolean isCancelled() { return cancelled; } + public final boolean isAsync() { + return async; + } + + public final Task setAsync(boolean async) { + this.async = async; + return this; + } + + public final void listen(TaskPredicate... predicate) { + for (TaskPredicate p : predicate) { + predicates.add((TaskPredicate) p); + } + } + @Override public final void run() { - OrdinalProcedure.process(this, 0); - if (type == 0) { - if (parent != null) { - parent.map.remove(getKey()); - } - } + if (host.isEnabled()) { + final Runnable r = runnable != null ? runnable : () -> procedure.run(0); + if (!predicates.isEmpty() && predicates.stream().anyMatch(p -> !p.accept(this))) return; + if (!isAsync()) bukkitScheduler.runTask(host, r); else r.run(); + if (type == Task.SINGULAR && parent != null) parent.map.remove(getKey()); + } else cancel(); } + /** + * @inheritDocs + */ @Override public final boolean cancel() { if (!cancelled) { - if (parent != null) { - parent.map.remove(this.key); - } - cancelled = true; - return super.cancel(); + if (parent != null) parent.map.remove(this.key); + return this.cancelled = super.cancel(); } return false; } diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/TaskCancellation.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/TaskCancellation.java deleted file mode 100644 index d39551a7..00000000 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/TaskCancellation.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.github.sanctum.labyrinth.task; - -/** - * An element describing custom cancellation instances within a task. - */ -@FunctionalInterface -@Deprecated -public interface TaskCancellation { - - void execute(ScheduledTask cancellationElement); - -} diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/TaskMonitor.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/TaskMonitor.java index cc946035..196b895d 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/TaskMonitor.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/TaskMonitor.java @@ -1,6 +1,7 @@ package com.github.sanctum.labyrinth.task; import com.github.sanctum.labyrinth.LabyrinthProvider; +import com.github.sanctum.labyrinth.api.LabyrinthAPI; import com.github.sanctum.labyrinth.api.TaskService; import com.github.sanctum.labyrinth.interfacing.OrdinalProcedure; import com.github.sanctum.labyrinth.library.Applicable; @@ -10,145 +11,268 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public final class TaskMonitor { +public class TaskMonitor { private static TaskMonitor instance; - private final TypeFlag[]> flagClass; - private final Map map = new HashMap<>(); + protected final TypeFlag[]> flagClass; + protected final Map map = new HashMap<>(); TaskMonitor() { this.flagClass = TypeFlag.get(); - map.put(0, LabyrinthProvider.getInstance().getScheduler(TaskService.SYNCHRONOUS)); - map.put(1, LabyrinthProvider.getInstance().getScheduler(TaskService.ASYNCHRONOUS)); + LabyrinthAPI api = LabyrinthProvider.getInstance(); + map.put(0, api.getScheduler(TaskService.SYNCHRONOUS)); + map.put(1, api.getScheduler(TaskService.ASYNCHRONOUS)); } public boolean shutdown() { - return map.get(0).shutdown() && map.get(1).shutdown(); + return map.get(TaskService.SYNCHRONOUS).shutdown() && map.get(TaskService.ASYNCHRONOUS).shutdown(); } public @Nullable Task get(@NotNull String key) { - return map.get(0).get(key) != null ? map.get(0).get(key) : map.get(1).get(key); + return map.get(TaskService.SYNCHRONOUS).get(key) != null ? map.get(TaskService.SYNCHRONOUS).get(key) : map.get(TaskService.ASYNCHRONOUS).get(key); } - public @NotNull RenderedTask schedule(Applicable data) { + public @NotNull RenderedTask schedule(Runnable data) { RenderedTask execution = RenderedTask.of(data, TaskService.SYNCHRONOUS); - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(0).run(task); + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).run(task); return execution; } - public @NotNull RenderedTask scheduleAsync(Applicable data) { + public @NotNull RenderedTask scheduleAsync(Runnable data) { RenderedTask execution = RenderedTask.of(data, TaskService.ASYNCHRONOUS); - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(1).run(task); + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).run(task); return execution; } - public @NotNull RenderedTask scheduleLater(Applicable data, long delay) { + public @NotNull RenderedTask scheduleLater(Runnable data, long delay) { RenderedTask execution = RenderedTask.of(data, null, TaskService.SYNCHRONOUS, delay * 50, -1); - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(0).wait(task, delay * 50); + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).wait(task, delay * 50); return execution; } - public @NotNull RenderedTask scheduleLater(Applicable data, String key, long delay) { + public @NotNull RenderedTask scheduleLater(Runnable data, String key, long delay) { RenderedTask execution = RenderedTask.of(data, key, TaskService.SYNCHRONOUS, delay * 50, -1); - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(0).wait(task, delay * 50); + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).wait(task, delay * 50); return execution; } - public @NotNull RenderedTask scheduleLaterAsync(Applicable data, long delay) { + public @NotNull RenderedTask scheduleLaterAsync(Runnable data, long delay) { RenderedTask execution = RenderedTask.of(data, null, TaskService.ASYNCHRONOUS, delay * 50, -1); - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(1).wait(task, delay * 50); + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).wait(task, delay * 50); return execution; } - public @NotNull RenderedTask scheduleLaterAsync(Applicable data, String key, long delay) { + public @NotNull RenderedTask scheduleLaterAsync(Runnable data, String key, long delay) { RenderedTask execution = RenderedTask.of(data, key, TaskService.ASYNCHRONOUS, delay * 50, -1); - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(1).wait(task, delay * 50); + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).wait(task, delay * 50); return execution; } - public @NotNull RenderedTask scheduleTimer(Applicable data, String key, long delay, long period) { + public @NotNull RenderedTask scheduleTimer(Runnable data, String key, long delay, long period) { RenderedTask execution = RenderedTask.of(data, key, TaskService.SYNCHRONOUS, delay * 50, period * 50); - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(0).repeat(task, delay * 50, period * 50); + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).repeat(task, delay * 50, period * 50); return execution; } - public @NotNull RenderedTask scheduleTimerAsync(Applicable data, String key, long delay, long period) { + public @NotNull RenderedTask scheduleTimerAsync(Runnable data, String key, long delay, long period) { RenderedTask execution = RenderedTask.of(data, key, TaskService.ASYNCHRONOUS, delay * 50, period * 50); - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(1).repeat(task, delay * 50, period * 50); + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).repeat(task, delay * 50, period * 50); return execution; } - public @NotNull RenderedTask scheduleLater(Applicable data, long delay, TaskPredicate... flags) { + public @NotNull RenderedTask scheduleLater(Runnable data, long delay, TaskPredicate... flags) { RenderedTask execution = RenderedTask.of(data, null, TaskService.SYNCHRONOUS, delay * 50, -1); execution.dependOn(TaskPredicate.reduceEmpty()); for (TaskPredicate flag : flagClass.cast(flags)) { execution.dependOn(flag); } - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(0).wait(task, delay * 50); + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).wait(task, delay * 50); return execution; } - public @NotNull RenderedTask scheduleLater(Applicable data, String key, long delay, TaskPredicate... flags) { + public @NotNull RenderedTask scheduleLater(Runnable data, String key, long delay, TaskPredicate... flags) { RenderedTask execution = RenderedTask.of(data, key, TaskService.SYNCHRONOUS, delay * 50, -1); execution.dependOn(TaskPredicate.reduceEmpty()); for (TaskPredicate flag : flagClass.cast(flags)) { execution.dependOn(flag); } - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(0).wait(task, delay * 50); + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).wait(task, delay * 50); return execution; } - public @NotNull RenderedTask scheduleLaterAsync(Applicable data, long delay, TaskPredicate... flags) { + public @NotNull RenderedTask scheduleLaterAsync(Runnable data, long delay, TaskPredicate... flags) { RenderedTask execution = RenderedTask.of(data, null, TaskService.ASYNCHRONOUS, delay * 50, -1); execution.dependOn(TaskPredicate.reduceEmpty()); for (TaskPredicate flag : flagClass.cast(flags)) { execution.dependOn(flag); } - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(1).wait(task, delay * 50); + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).wait(task, delay * 50); return execution; } - public @NotNull RenderedTask scheduleLaterAsync(Applicable data, String key, long delay, TaskPredicate... flags) { + public @NotNull RenderedTask scheduleLaterAsync(Runnable data, String key, long delay, TaskPredicate... flags) { RenderedTask execution = RenderedTask.of(data, key, TaskService.ASYNCHRONOUS, delay * 50, -1); execution.dependOn(TaskPredicate.reduceEmpty()); for (TaskPredicate flag : flagClass.cast(flags)) { execution.dependOn(flag); } - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(1).wait(task, delay * 50); + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).wait(task, delay * 50); return execution; } - public @NotNull RenderedTask scheduleTimer(Applicable data, String key, long delay, long period, TaskPredicate... flags) { + public @NotNull RenderedTask scheduleTimer(Runnable data, String key, long delay, long period, TaskPredicate... flags) { RenderedTask execution = RenderedTask.of(data, key, TaskService.SYNCHRONOUS, delay * 50, period * 50); execution.dependOn(TaskPredicate.reduceEmpty());execution.dependOn(TaskPredicate.reduceEmpty()); for (TaskPredicate flag : flagClass.cast(flags)) { execution.dependOn(flag); } - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(0).repeat(task, delay * 50, period * 50); + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).repeat(task, delay * 50, period * 50); return execution; } - public @NotNull RenderedTask scheduleTimerAsync(Applicable data, String key, long delay, long period, TaskPredicate... flags) { + public @NotNull RenderedTask scheduleTimerAsync(Runnable data, String key, long delay, long period, TaskPredicate... flags) { RenderedTask execution = RenderedTask.of(data, key, TaskService.ASYNCHRONOUS, delay * 50, period * 50); execution.dependOn(TaskPredicate.reduceEmpty());execution.dependOn(TaskPredicate.reduceEmpty()); for (TaskPredicate flag : flagClass.cast(flags)) { execution.dependOn(flag); } - Task task = OrdinalProcedure.select(execution, 0).cast(() -> Task.class); - map.get(1).repeat(task, delay * 50, period * 50); + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).repeat(task, delay * 50, period * 50); + return execution; + } + + public @NotNull RenderedTask schedule(Task data) { + RenderedTask execution = RenderedTask.of(data, TaskService.SYNCHRONOUS); + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).run(task); + return execution; + } + + public @NotNull RenderedTask scheduleAsync(Task data) { + RenderedTask execution = RenderedTask.of(data, TaskService.ASYNCHRONOUS); + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).run(task); + return execution; + } + + public @NotNull RenderedTask scheduleLater(Task data, long delay) { + RenderedTask execution = RenderedTask.of(data, null, TaskService.SYNCHRONOUS, delay * 50, -1); + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).wait(task, delay * 50); + return execution; + } + + public @NotNull RenderedTask scheduleLater(Task data, String key, long delay) { + RenderedTask execution = RenderedTask.of(data, key, TaskService.SYNCHRONOUS, delay * 50, -1); + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).wait(task, delay * 50); + return execution; + } + + public @NotNull RenderedTask scheduleLaterAsync(Task data, long delay) { + RenderedTask execution = RenderedTask.of(data, null, TaskService.ASYNCHRONOUS, delay * 50, -1); + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).wait(task, delay * 50); + return execution; + } + + public @NotNull RenderedTask scheduleLaterAsync(Task data, String key, long delay) { + RenderedTask execution = RenderedTask.of(data, key, TaskService.ASYNCHRONOUS, delay * 50, -1); + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).wait(task, delay * 50); + return execution; + } + + public @NotNull RenderedTask scheduleTimer(Task data, String key, long delay, long period) { + RenderedTask execution = RenderedTask.of(data, key, TaskService.SYNCHRONOUS, delay * 50, period * 50); + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).repeat(task, delay * 50, period * 50); + return execution; + } + + public @NotNull RenderedTask scheduleTimerAsync(Task data, String key, long delay, long period) { + RenderedTask execution = RenderedTask.of(data, key, TaskService.ASYNCHRONOUS, delay * 50, period * 50); + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).repeat(task, delay * 50, period * 50); + return execution; + } + + public @NotNull RenderedTask scheduleLater(Task data, long delay, TaskPredicate... flags) { + RenderedTask execution = RenderedTask.of(data, null, TaskService.SYNCHRONOUS, delay * 50, -1); + execution.dependOn(TaskPredicate.reduceEmpty()); + for (TaskPredicate flag : flagClass.cast(flags)) { + execution.dependOn(flag); + } + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).wait(task, delay * 50); + return execution; + } + + public @NotNull RenderedTask scheduleLater(Task data, String key, long delay, TaskPredicate... flags) { + RenderedTask execution = RenderedTask.of(data, key, TaskService.SYNCHRONOUS, delay * 50, -1); + execution.dependOn(TaskPredicate.reduceEmpty()); + for (TaskPredicate flag : flagClass.cast(flags)) { + execution.dependOn(flag); + } + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).wait(task, delay * 50); + return execution; + } + + public @NotNull RenderedTask scheduleLaterAsync(Task data, long delay, TaskPredicate... flags) { + RenderedTask execution = RenderedTask.of(data, null, TaskService.ASYNCHRONOUS, delay * 50, -1); + execution.dependOn(TaskPredicate.reduceEmpty()); + for (TaskPredicate flag : flagClass.cast(flags)) { + execution.dependOn(flag); + } + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).wait(task, delay * 50); + return execution; + } + + public @NotNull RenderedTask scheduleLaterAsync(Task data, String key, long delay, TaskPredicate... flags) { + RenderedTask execution = RenderedTask.of(data, key, TaskService.ASYNCHRONOUS, delay * 50, -1); + execution.dependOn(TaskPredicate.reduceEmpty()); + for (TaskPredicate flag : flagClass.cast(flags)) { + execution.dependOn(flag); + } + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).wait(task, delay * 50); + return execution; + } + + public @NotNull RenderedTask scheduleTimer(Task data, String key, long delay, long period, TaskPredicate... flags) { + RenderedTask execution = RenderedTask.of(data, key, TaskService.SYNCHRONOUS, delay * 50, period * 50); + execution.dependOn(TaskPredicate.reduceEmpty());execution.dependOn(TaskPredicate.reduceEmpty()); + for (TaskPredicate flag : flagClass.cast(flags)) { + execution.dependOn(flag); + } + Task task = execution.getTask(); + map.get(TaskService.SYNCHRONOUS).repeat(task, delay * 50, period * 50); + return execution; + } + + public @NotNull RenderedTask scheduleTimerAsync(Task data, String key, long delay, long period, TaskPredicate... flags) { + RenderedTask execution = RenderedTask.of(data, key, TaskService.ASYNCHRONOUS, delay * 50, period * 50); + execution.dependOn(TaskPredicate.reduceEmpty());execution.dependOn(TaskPredicate.reduceEmpty()); + for (TaskPredicate flag : flagClass.cast(flags)) { + execution.dependOn(flag); + } + Task task = execution.getTask(); + map.get(TaskService.ASYNCHRONOUS).repeat(task, delay * 50, period * 50); return execution; } @@ -174,4 +298,8 @@ public static TaskMonitor getLocalInstance() { return instance != null ? instance : (instance = new TaskMonitor()); } + public static void setInstance(@NotNull TaskMonitor monitor) { + instance = monitor; + } + } diff --git a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/TaskScheduler.java b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/TaskScheduler.java index c33dc439..aa78bc20 100644 --- a/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/TaskScheduler.java +++ b/labyrinth-common/src/main/java/com/github/sanctum/labyrinth/task/TaskScheduler.java @@ -33,8 +33,11 @@ public interface TaskScheduler { @NotNull RenderedTask scheduleTimerAsync(String key, long delay, long period, TaskPredicate... flags); static @NotNull TaskScheduler of(@NotNull Runnable runnable) { - return new LabyrinthTaskScheduler(runnable::run); + return new NormalTaskScheduler(runnable); } + static @NotNull TaskScheduler of(@NotNull Task task) { + return new CustomTaskScheduler(task); + } } diff --git a/labyrinth-gui/pom.xml b/labyrinth-gui/pom.xml index 66c47aa4..0b206713 100644 --- a/labyrinth-gui/pom.xml +++ b/labyrinth-gui/pom.xml @@ -5,7 +5,7 @@ labyrinth com.github.the-h-team - 1.7.7 + 1.7.8 4.0.0 diff --git a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/Menu.java b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/Menu.java index 38c478c4..c64f2bae 100644 --- a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/Menu.java +++ b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/Menu.java @@ -1,7 +1,6 @@ package com.github.sanctum.labyrinth.gui.unity.construct; import com.github.sanctum.labyrinth.LabyrinthProvider; -import com.github.sanctum.labyrinth.api.MenuRegistration; import com.github.sanctum.labyrinth.api.Service; import com.github.sanctum.labyrinth.api.TaskService; import com.github.sanctum.labyrinth.data.container.PersistentContainer; @@ -13,9 +12,10 @@ import com.github.sanctum.labyrinth.gui.unity.impl.OpeningElement; import com.github.sanctum.labyrinth.gui.unity.impl.PreProcessElement; import com.github.sanctum.labyrinth.library.NamespacedKey; -import com.github.sanctum.labyrinth.task.Asynchronous; +import com.github.sanctum.labyrinth.task.RenderedTask; import com.github.sanctum.labyrinth.task.Task; import com.github.sanctum.labyrinth.task.TaskMonitor; +import com.github.sanctum.labyrinth.task.TaskScheduler; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; @@ -390,6 +390,10 @@ public enum Property { */ public enum Type { + /** + * *NEW* This menu type represents that of a modded inventory space. + */ + MODDED, /** * This menu type represents that of a multi-paged inventory space. */ @@ -754,9 +758,9 @@ public void onClose(InventoryCloseEvent e) { Player p = (Player) e.getPlayer(); if (getProperties().contains(Property.LIVE_META) || getProperties().contains(Property.ANIMATED)) { - Asynchronous task = getInventory().getTask(p); + RenderedTask task = getInventory().getViewer(p).getTask(); if (task != null) { - task.cancelTask(); + task.getTask().cancel(); } Task t = TaskMonitor.getLocalInstance().get("Labyrinth:" + Menu.this.hashCode() + ";slide-" + p.getUniqueId()); if (t != null) { @@ -775,11 +779,11 @@ public void onClose(InventoryCloseEvent e) { } Inventory finalTarget = target; if (!getProperties().contains(Property.CACHEABLE)) { - LabyrinthProvider.getService(Service.TASK).getScheduler(TaskService.SYNCHRONOUS).wait(() -> { + TaskScheduler.of(() -> { if (finalTarget.getViewers().stream().noneMatch(v -> v instanceof Player)) { unRegisterHandlers(); } - }, getKey().orElse("dummy") + "-menu", 2); + }).scheduleLater(2); } } } diff --git a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/api/MenuDuplicationException.java b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/MenuDuplicationException.java similarity index 84% rename from labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/api/MenuDuplicationException.java rename to labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/MenuDuplicationException.java index f10e69ed..86d0905d 100644 --- a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/api/MenuDuplicationException.java +++ b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/MenuDuplicationException.java @@ -1,4 +1,4 @@ -package com.github.sanctum.labyrinth.api; +package com.github.sanctum.labyrinth.gui.unity.construct; public class MenuDuplicationException extends RuntimeException { diff --git a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/api/MenuNotCacheableException.java b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/MenuNotCacheableException.java similarity index 84% rename from labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/api/MenuNotCacheableException.java rename to labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/MenuNotCacheableException.java index 18571435..caedaf23 100644 --- a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/api/MenuNotCacheableException.java +++ b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/MenuNotCacheableException.java @@ -1,4 +1,4 @@ -package com.github.sanctum.labyrinth.api; +package com.github.sanctum.labyrinth.gui.unity.construct; public class MenuNotCacheableException extends RuntimeException { diff --git a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/api/MenuRegistration.java b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/MenuRegistration.java similarity index 97% rename from labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/api/MenuRegistration.java rename to labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/MenuRegistration.java index ee7c094f..5a9f1df2 100644 --- a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/api/MenuRegistration.java +++ b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/MenuRegistration.java @@ -1,6 +1,7 @@ -package com.github.sanctum.labyrinth.api; +package com.github.sanctum.labyrinth.gui.unity.construct; import com.github.sanctum.labyrinth.LabyrinthProvider; +import com.github.sanctum.labyrinth.api.Service; import com.github.sanctum.labyrinth.data.ServiceManager; import com.github.sanctum.labyrinth.data.ServiceType; import com.github.sanctum.labyrinth.data.container.ImmutableLabyrinthCollection; @@ -9,7 +10,6 @@ import com.github.sanctum.labyrinth.data.container.LabyrinthList; import com.github.sanctum.labyrinth.data.container.LabyrinthMap; import com.github.sanctum.labyrinth.data.service.Check; -import com.github.sanctum.labyrinth.gui.unity.construct.Menu; import com.github.sanctum.labyrinth.library.Deployable; import java.util.function.Supplier; import org.bukkit.plugin.Plugin; diff --git a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/PaginatedMenu.java b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/PaginatedMenu.java index be4bd45d..6bd2db67 100644 --- a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/PaginatedMenu.java +++ b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/PaginatedMenu.java @@ -1,6 +1,5 @@ package com.github.sanctum.labyrinth.gui.unity.construct; -import com.github.sanctum.labyrinth.task.Schedule; import com.github.sanctum.labyrinth.gui.unity.impl.InventoryElement; import com.github.sanctum.labyrinth.gui.unity.impl.PreProcessElement; import com.github.sanctum.labyrinth.task.TaskScheduler; diff --git a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/PrintableMenu.java b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/PrintableMenu.java index acd10be8..e817de19 100644 --- a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/PrintableMenu.java +++ b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/construct/PrintableMenu.java @@ -18,7 +18,7 @@ public PrintableMenu(Plugin host, String title, Rows rows, Type type, Property.. addElement(new InventoryElement.Printable(title, mechanics, this)); } else { LabyrinthProvider.getInstance().getLogger().severe("- No anvil mechanic service found!!"); - addElement(new InventoryElement.Normal(title, this)); + addElement(new InventoryElement.Printable(title, null, this)); } } diff --git a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/InventoryElement.java b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/InventoryElement.java index f9d03b8d..e58760dc 100644 --- a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/InventoryElement.java +++ b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/InventoryElement.java @@ -1,18 +1,19 @@ package com.github.sanctum.labyrinth.gui.unity.impl; +import com.github.sanctum.labyrinth.LabyrinthProvider; import com.github.sanctum.labyrinth.data.SimpleKeyedValue; import com.github.sanctum.labyrinth.data.container.ImmutableLabyrinthMap; import com.github.sanctum.labyrinth.data.container.LabyrinthCollection; import com.github.sanctum.labyrinth.data.container.LabyrinthEntryMap; -import com.github.sanctum.labyrinth.data.container.LabyrinthList; import com.github.sanctum.labyrinth.data.container.LabyrinthMap; import com.github.sanctum.labyrinth.data.service.AnvilMechanics; import com.github.sanctum.labyrinth.formatting.UniformedComponents; import com.github.sanctum.labyrinth.formatting.pagination.AbstractPaginatedCollection; +import com.github.sanctum.labyrinth.formatting.string.SpecialID; import com.github.sanctum.labyrinth.gui.unity.construct.Menu; +import com.github.sanctum.labyrinth.library.Mailer; import com.github.sanctum.labyrinth.library.StringUtils; -import com.github.sanctum.labyrinth.task.Asynchronous; -import com.github.sanctum.labyrinth.task.Schedule; +import com.github.sanctum.labyrinth.task.RenderedTask; import com.github.sanctum.labyrinth.task.TaskPredicate; import com.github.sanctum.labyrinth.task.TaskScheduler; import java.text.MessageFormat; @@ -39,7 +40,6 @@ public abstract class InventoryElement extends Menu.Element>> { - protected final Map tasks; protected final Set index; protected final Set> items; protected final boolean lazy; @@ -52,7 +52,6 @@ public abstract class InventoryElement extends Menu.Element(); this.menu = menu; - this.tasks = new HashMap<>(); this.index = new HashSet<>(); this.title = title; this.lazy = lazy; @@ -130,10 +129,6 @@ public Inventory getElement() { return this.inventory; } - public @Nullable Asynchronous getTask(Player player) { - return tasks.get(player); - } - public InventoryElement setContents(Iterable> elements) { items.clear(); elements.forEach(this::addItem); @@ -270,7 +265,8 @@ public boolean contains(ItemStack item) { ListElement list = (ListElement) getElement(e -> e instanceof ListElement); if (isAnimated()) { Animated inv = (Animated) this; - if (inv.getSlides().stream().anyMatch(s -> s.getAttachment().values().stream().anyMatch(it -> isSimilar(it.getElement(), item)))) return true; + if (inv.getSlides().stream().anyMatch(s -> s.getAttachment().values().stream().anyMatch(it -> isSimilar(it.getElement(), item)))) + return true; } return this.items.stream().map(ItemElement::getElement).anyMatch(i -> { if (getParent().getProperties().contains(Menu.Property.LIVE_META)) { @@ -386,7 +382,8 @@ public Slide(InventoryElement parent) { } public Slide set(int slot, ItemElement itemElement) throws IndexOutOfBoundsException { - if (slot >= parent.inventory.getSize() || slot < 0) throw new IndexOutOfBoundsException("Cannot modify item element beyond natural scope."); + if (slot >= parent.inventory.getSize() || slot < 0) + throw new IndexOutOfBoundsException("Cannot modify item element beyond natural scope."); items.put(slot, itemElement.setSlot(slot).setParent(parent)); return this; } @@ -597,62 +594,62 @@ public int getTotalPages() { @Override public synchronized void open(Player player) { - + MenuViewer viewer = getViewer(player); if (lazy) { // This area dictates that our inventory is "lazy" and needs to be instantiated - getViewer(player).setElement(null); + viewer.setElement(null); } if (this.menu.getProperties().contains(Menu.Property.LIVE_META)) { - getViewer(player).getElement().setMaxStackSize(1); - if (this.tasks.containsKey(player)) { - this.tasks.get(player).cancelTask(); + viewer.getElement().setMaxStackSize(1); + + if (viewer.getTask() != null) { + viewer.getTask().getTask().cancel(); } - this.tasks.put(player, Schedule.async(() -> Schedule.sync(() -> { - getViewer(player).getElement().clear(); + viewer.setTask(TaskScheduler.of(() -> { + viewer.getElement().clear(); BorderElement border = (BorderElement) getElement(e -> e instanceof BorderElement); if (border != null) { for (ItemElement element : border.getAttachment()) { Optional i = element.getSlot(); - i.ifPresent(integer -> getViewer(player).getElement().setItem(integer, element.getElement())); + i.ifPresent(integer -> viewer.getElement().setItem(integer, element.getElement())); } } - for (ItemElement element : getViewer(player).getPage().getAttachment()) { - if (!getViewer(player).getElement().contains(element.getElement())) { - getViewer(player).getElement().addItem(element.getElement()); + for (ItemElement element : viewer.getPage().getAttachment()) { + if (!viewer.getElement().contains(element.getElement())) { + viewer.getElement().addItem(element.getElement()); } } for (ItemElement element : items) { Optional in = element.getSlot(); - in.ifPresent(integer -> getViewer(player).getElement().setItem(integer, element.getElement())); + in.ifPresent(integer -> viewer.getElement().setItem(integer, element.getElement())); } FillerElement filler = (FillerElement) getElement(e -> e instanceof FillerElement); if (filler != null) { for (ItemElement el : filler.getAttachment()) { int slot = el.getSlot().orElse(0); - if (getViewer(player).getElement().getItem(slot) == null) { - getViewer(player).getElement().setItem(slot, el.getElement()); + if (viewer.getElement().getItem(slot) == null) { + viewer.getElement().setItem(slot, el.getElement()); } } } - }).run())); - this.tasks.get(player).repeat(0, 60); + }).scheduleTimer("Unity:" + SpecialID.builder().setLength(12).build(this) + ":" + player.getUniqueId(), 0, 60)); - Schedule.sync(() -> player.openInventory(getViewer(player).getElement())).run(); + TaskScheduler.of(() -> player.openInventory(viewer.getElement())).schedule(); } else { - for (ItemElement element : getViewer(player).getPage().getAttachment()) { - if (!getViewer(player).getElement().contains(element.getElement())) { - getViewer(player).getElement().addItem(element.getElement()); + for (ItemElement element : viewer.getPage().getAttachment()) { + if (!viewer.getElement().contains(element.getElement())) { + viewer.getElement().addItem(element.getElement()); } } for (ItemElement element : items) { Optional in = element.getSlot(); - in.ifPresent(integer -> getViewer(player).getElement().setItem(integer, element.getElement())); + in.ifPresent(integer -> viewer.getElement().setItem(integer, element.getElement())); } - player.openInventory(getViewer(player).getElement()); + player.openInventory(viewer.getElement()); } } @@ -674,45 +671,41 @@ public Set getViewers() { @Override public synchronized void open(Player player) { viewers.add(player); - + MenuViewer viewer = getViewer(player); if (lazy) { // This area dictates that our inventory is "lazy" and needs to be instantiated this.inventory = Bukkit.createInventory(null, this.menu.getSize().getSize(), StringUtils.use(MessageFormat.format(this.title, page, getTotalPages())).translate()); } if (this.menu.getProperties().contains(Menu.Property.LIVE_META)) { getElement().setMaxStackSize(1); - if (this.tasks.containsKey(player)) { - this.tasks.get(player).cancelTask(); + if (viewer.getTask() != null) { + viewer.getTask().getTask().cancel(); } - - if (this.tasks.size() < 1) { - this.tasks.put(player, Schedule.async(() -> { - Schedule.sync(() -> { - getElement().clear(); - for (ItemElement element : getGlobalSlot().getAttachment()) { - if (!getElement().contains(element.getElement())) { - getElement().addItem(element.getElement()); - } - } - for (ItemElement element : items) { - Optional in = element.getSlot(); - in.ifPresent(integer -> getElement().setItem(integer, element.getElement())); + if (getViewers().stream().map(this::getViewer).noneMatch(m -> m.getTask() != null)) { + viewer.setTask(TaskScheduler.of(() -> { + getElement().clear(); + for (ItemElement element : getGlobalSlot().getAttachment()) { + if (!getElement().contains(element.getElement())) { + getElement().addItem(element.getElement()); } - }).run(); - })); - this.tasks.get(player).repeat(0, 60); + } + for (ItemElement element : items) { + Optional in = element.getSlot(); + in.ifPresent(integer -> getElement().setItem(integer, element.getElement())); + } + }).scheduleTimer("Unity:" + SpecialID.builder().setLength(12).build(this) + ":" + player.getUniqueId(), 0, 60)); } - Schedule.sync(() -> { + TaskScheduler.of(() -> { SharedPaginated inv = this; for (Player p : inv.getViewers()) { if (p.equals(player)) { - Schedule.sync(() -> player.openInventory(getElement())).run(); + TaskScheduler.of(() -> player.openInventory(getElement())).schedule(); } else { inv.open(p); } } - }).waitReal(2); + }).scheduleLater(2); } else { for (ItemElement element : getGlobalSlot().getAttachment()) { @@ -747,7 +740,7 @@ public Set getViewers() { @Override public synchronized void open(Player player) { viewers.add(player); - + MenuViewer viewer = getViewer(player); if (lazy && getParent().getProperties().contains(Menu.Property.RECURSIVE)) { // This area dictates that our inventory is "lazy" and needs to be instantiated this.inventory = Bukkit.createInventory(null, this.menu.getSize().getSize(), StringUtils.use(MessageFormat.format(this.title, page, 0)).translate()); @@ -758,51 +751,48 @@ public synchronized void open(Player player) { return; } if (this.menu.getProperties().contains(Menu.Property.LIVE_META)) { - if (this.tasks.containsKey(player)) { - this.tasks.get(player).cancelTask(); + if (viewer.getTask() != null) { + viewer.getTask().getTask().cancel(); } getElement().setMaxStackSize(1); - if (this.tasks.size() < 1) { - this.tasks.put(player, Schedule.async(() -> { - Schedule.sync(() -> { - getElement().clear(); - BorderElement border = (BorderElement) getElement(e -> e instanceof BorderElement); - if (border != null) { - for (ItemElement element : border.getAttachment()) { - Optional i = element.getSlot(); - i.ifPresent(integer -> inventory.setItem(integer, element.getElement())); - } + if (getViewers().stream().map(this::getViewer).noneMatch(m -> m.getTask() != null)) { + viewer.setTask(TaskScheduler.of(() -> { + getElement().clear(); + BorderElement border = (BorderElement) getElement(e -> e instanceof BorderElement); + if (border != null) { + for (ItemElement element : border.getAttachment()) { + Optional i = element.getSlot(); + i.ifPresent(integer -> inventory.setItem(integer, element.getElement())); } - for (ItemElement element : getContents()) { - Optional in = element.getSlot(); - if (in.isPresent()) { - getElement().setItem(in.get(), element.getElement()); - } else { - if (!getElement().contains(element.getElement())) { - getElement().addItem(element.getElement()); - } + } + for (ItemElement element : getContents()) { + Optional in = element.getSlot(); + if (in.isPresent()) { + getElement().setItem(in.get(), element.getElement()); + } else { + if (!getElement().contains(element.getElement())) { + getElement().addItem(element.getElement()); } } - for (ItemElement element : items) { - Optional in = element.getSlot(); - in.ifPresent(integer -> getElement().setItem(integer, element.getElement())); - } - FillerElement filler = (FillerElement) getElement(e -> e instanceof FillerElement); - if (filler != null) { - for (ItemElement el : filler.getAttachment()) { - int slot = el.getSlot().orElse(0); - if (getElement().getItem(slot) == null) { - getElement().setItem(slot, el.getElement()); - } + } + for (ItemElement element : items) { + Optional in = element.getSlot(); + in.ifPresent(integer -> getElement().setItem(integer, element.getElement())); + } + FillerElement filler = (FillerElement) getElement(e -> e instanceof FillerElement); + if (filler != null) { + for (ItemElement el : filler.getAttachment()) { + int slot = el.getSlot().orElse(0); + if (getElement().getItem(slot) == null) { + getElement().setItem(slot, el.getElement()); } } - }).run(); - })); - this.tasks.get(player).repeat(0, 1); + } + }).scheduleTimer("Unity:" + SpecialID.builder().setLength(12).build(this) + ":" + player.getUniqueId(), 0, 1)); } - Schedule.sync(() -> { + TaskScheduler.of(() -> { Shared inv = this; for (Player p : inv.getViewers()) { if (p.equals(player)) { @@ -811,7 +801,7 @@ public synchronized void open(Player player) { inv.open(player); } } - }).waitReal(2); + }).scheduleLater(2); return; } else { @@ -846,13 +836,13 @@ public synchronized void open(Player player) { } } - Schedule.sync(() -> player.openInventory(getElement())).run(); + player.openInventory(getElement()); } for (Player p : viewers) { if (getElement() != null) { if (!p.getOpenInventory().getTopInventory().equals(getElement())) { - Schedule.sync(() -> viewers.remove(p)).wait(1); + TaskScheduler.of(() -> viewers.remove(p)).scheduleLater(1); } } } @@ -867,90 +857,85 @@ public Normal(String title, Menu menu) { @Override public synchronized void open(Player player) { - + MenuViewer viewer = getViewer(player); if (lazy && getParent().getProperties().contains(Menu.Property.RECURSIVE)) { // This area dictates that our inventory is "lazy" and needs to be instantiated this.inventory = Bukkit.createInventory(null, this.menu.getSize().getSize(), StringUtils.use(MessageFormat.format(this.title, page, 0)).translate()); - getViewer(player).setElement(null); + viewer.setElement(null); } if (this.menu.getProperties().contains(Menu.Property.LIVE_META)) { - if (this.tasks.containsKey(player)) { - this.tasks.get(player).cancelTask(); + if (viewer.getTask() != null) { + viewer.getTask().getTask().cancel(); } - getViewer(player).getElement().setMaxStackSize(1); - this.tasks.put(player, Schedule.async(() -> { - Schedule.sync(() -> { - getViewer(player).getElement().clear(); - BorderElement border = (BorderElement) getElement(e -> e instanceof BorderElement); - if (border != null) { - for (ItemElement element : border.getAttachment()) { - Optional i = element.getSlot(); - i.ifPresent(integer -> getViewer(player).getElement().setItem(integer, element.getElement())); - } + viewer.getElement().setMaxStackSize(1); + viewer.setTask(TaskScheduler.of(() -> { + viewer.getElement().clear(); + BorderElement border = (BorderElement) getElement(e -> e instanceof BorderElement); + if (border != null) { + for (ItemElement element : border.getAttachment()) { + Optional i = element.getSlot(); + i.ifPresent(integer -> viewer.getElement().setItem(integer, element.getElement())); } - for (ItemElement element : getContents()) { - Optional in = element.getSlot(); - if (in.isPresent()) { - getViewer(player).getElement().setItem(in.get(), element.getElement()); - } else { - if (!getViewer(player).getElement().contains(element.getElement())) { - getViewer(player).getElement().addItem(element.getElement()); - } + } + for (ItemElement element : getContents()) { + Optional in = element.getSlot(); + if (in.isPresent()) { + viewer.getElement().setItem(in.get(), element.getElement()); + } else { + if (!viewer.getElement().contains(element.getElement())) { + viewer.getElement().addItem(element.getElement()); } } - for (ItemElement element : items) { - Optional in = element.getSlot(); - in.ifPresent(integer -> getViewer(player).getElement().setItem(integer, element.getElement())); - } - FillerElement filler = (FillerElement) getElement(e -> e instanceof FillerElement); - if (filler != null) { - for (ItemElement el : filler.getAttachment()) { - int slot = el.getSlot().orElse(0); - if (getViewer(player).getElement().getItem(slot) == null) { - getViewer(player).getElement().setItem(slot, el.getElement()); - } + } + for (ItemElement element : items) { + Optional in = element.getSlot(); + in.ifPresent(integer -> viewer.getElement().setItem(integer, element.getElement())); + } + FillerElement filler = (FillerElement) getElement(e -> e instanceof FillerElement); + if (filler != null) { + for (ItemElement el : filler.getAttachment()) { + int slot = el.getSlot().orElse(0); + if (viewer.getElement().getItem(slot) == null) { + viewer.getElement().setItem(slot, el.getElement()); } } - }).run(); - })); - this.tasks.get(player).repeat(0, 1); - - Schedule.sync(() -> player.openInventory(getViewer(player).getElement())).waitReal(2); + } + }).scheduleTimer("Unity:" + SpecialID.builder().setLength(12).build(this) + ":" + player.getUniqueId(), 0, 1)); } else { BorderElement border = (BorderElement) getElement(e -> e instanceof BorderElement); if (border != null) { for (ItemElement element : border.getAttachment()) { Optional i = element.getSlot(); - i.ifPresent(integer -> getViewer(player).getElement().setItem(integer, element.getElement())); + i.ifPresent(integer -> viewer.getElement().setItem(integer, element.getElement())); } } for (ItemElement element : getContents()) { Optional in = element.getSlot(); if (in.isPresent()) { - getViewer(player).getElement().setItem(in.get(), element.getElement()); + viewer.getElement().setItem(in.get(), element.getElement()); } else { - if (!getViewer(player).getElement().contains(element.getElement())) { - getViewer(player).getElement().addItem(element.getElement()); + if (!viewer.getElement().contains(element.getElement())) { + viewer.getElement().addItem(element.getElement()); } } } for (ItemElement element : items) { Optional in = element.getSlot(); - in.ifPresent(integer -> getViewer(player).getElement().setItem(integer, element.getElement())); + in.ifPresent(integer -> viewer.getElement().setItem(integer, element.getElement())); } FillerElement filler = (FillerElement) getElement(e -> e instanceof FillerElement); if (filler != null) { for (ItemElement el : filler.getAttachment()) { int slot = el.getSlot().orElse(0); - if (getViewer(player).getElement().getItem(slot) == null) { - getViewer(player).getElement().setItem(slot, el.getElement()); + if (viewer.getElement().getItem(slot) == null) { + viewer.getElement().setItem(slot, el.getElement()); } } } - Schedule.sync(() -> player.openInventory(getViewer(player).getElement())).run(); } + player.openInventory(viewer.getElement()); } } @@ -973,6 +958,17 @@ public boolean isVisible() { @Override public void open(Player player) { + if (nms == null) { + Mailer mailer = Mailer.empty(player).prefix().start("&7[").middle("&2&lLabyrinth").end("&7]").finish(); + String reason = LabyrinthProvider.getInstance().isModded() ? "Modded Environment" : "Unknown"; + mailer.chat("&c&lAn internal matter has prevented you from accessing this menu.").deploy(m -> { + if (player.isOp()) { + mailer.chat("&eReason: &f" + reason).queue(); + } + }); + player.closeInventory(); + return; + } nms.handleInventoryCloseEvent(player); nms.setActiveContainerDefault(player); @@ -1005,6 +1001,7 @@ public void open(Player player) { } public void close(Player player, boolean sendPacket) { + if (nms == null) return; if (!visible) throw new IllegalArgumentException("You can't close an inventory that isn't open!"); visible = false; diff --git a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/MenuType.java b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/MenuType.java index 1f7cabc5..be6aab22 100644 --- a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/MenuType.java +++ b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/MenuType.java @@ -1,8 +1,7 @@ package com.github.sanctum.labyrinth.gui.unity.impl; import com.github.sanctum.labyrinth.annotation.Experimental; -import com.github.sanctum.labyrinth.annotation.Note; -import com.github.sanctum.labyrinth.api.MenuRegistration; +import com.github.sanctum.labyrinth.gui.unity.construct.MenuRegistration; import com.github.sanctum.labyrinth.gui.unity.construct.Menu; import com.github.sanctum.labyrinth.gui.unity.construct.PaginatedMenu; import com.github.sanctum.labyrinth.gui.unity.construct.PrintableMenu; diff --git a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/MenuViewer.java b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/MenuViewer.java index 24eefa56..a6909427 100644 --- a/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/MenuViewer.java +++ b/labyrinth-gui/src/main/java/com/github/sanctum/labyrinth/gui/unity/impl/MenuViewer.java @@ -3,6 +3,7 @@ import com.github.sanctum.labyrinth.formatting.UniformedComponents; import com.github.sanctum.labyrinth.gui.unity.construct.Menu; import com.github.sanctum.labyrinth.library.StringUtils; +import com.github.sanctum.labyrinth.task.RenderedTask; import java.text.MessageFormat; import java.util.Arrays; import java.util.Objects; @@ -18,6 +19,8 @@ public class MenuViewer { private Inventory inventory; + private RenderedTask task; + private final UUID id; private final InventoryElement element; @@ -28,6 +31,10 @@ public MenuViewer(UUID id, InventoryElement element) { this.id = id; } + void setTask(RenderedTask task) { + this.task = task; + } + public InventoryElement getInventory() { return element; } @@ -110,6 +117,10 @@ public OfflinePlayer getPlayer() { return Bukkit.getOfflinePlayer(this.id); } + public RenderedTask getTask() { + return task; + } + public InventoryElement.Page getPage() { if (getInventory().isPaginated()) { InventoryElement.Paginated i = (InventoryElement.Paginated) getInventory(); diff --git a/labyrinth-paste/pom.xml b/labyrinth-paste/pom.xml index 18241dce..1de0d55c 100644 --- a/labyrinth-paste/pom.xml +++ b/labyrinth-paste/pom.xml @@ -5,7 +5,7 @@ labyrinth com.github.the-h-team - 1.7.7 + 1.7.8 4.0.0 diff --git a/labyrinth-perms/pom.xml b/labyrinth-perms/pom.xml index ce415b92..73755e3f 100644 --- a/labyrinth-perms/pom.xml +++ b/labyrinth-perms/pom.xml @@ -5,7 +5,7 @@ labyrinth com.github.the-h-team - 1.7.7 + 1.7.8 4.0.0 diff --git a/labyrinth-placeholders/pom.xml b/labyrinth-placeholders/pom.xml index bb3401e1..17f0d39a 100644 --- a/labyrinth-placeholders/pom.xml +++ b/labyrinth-placeholders/pom.xml @@ -5,7 +5,7 @@ labyrinth com.github.the-h-team - 1.7.7 + 1.7.8 4.0.0 diff --git a/labyrinth-plugin/pom.xml b/labyrinth-plugin/pom.xml index 11e417d0..ba27fe33 100644 --- a/labyrinth-plugin/pom.xml +++ b/labyrinth-plugin/pom.xml @@ -5,7 +5,7 @@ labyrinth com.github.the-h-team - 1.7.7 + 1.7.8 4.0.0 diff --git a/labyrinth-plugin/src/main/java/com/github/sanctum/labyrinth/Labyrinth.java b/labyrinth-plugin/src/main/java/com/github/sanctum/labyrinth/Labyrinth.java index b533e836..89d1862e 100644 --- a/labyrinth-plugin/src/main/java/com/github/sanctum/labyrinth/Labyrinth.java +++ b/labyrinth-plugin/src/main/java/com/github/sanctum/labyrinth/Labyrinth.java @@ -45,6 +45,7 @@ import com.github.sanctum.labyrinth.library.ItemCompost; import com.github.sanctum.labyrinth.library.Mailer; import com.github.sanctum.labyrinth.library.NamespacedKey; +import com.github.sanctum.labyrinth.library.StringUtils; import com.github.sanctum.labyrinth.library.TimeWatch; import com.github.sanctum.labyrinth.library.TypeFlag; import com.github.sanctum.labyrinth.permissions.Permissions; @@ -364,7 +365,7 @@ public void onDisable() { } catch (InterruptedException ignored) { } - if (!isLegacy()) { + if (!isLegacy() && !StringUtils.use(getServer().getName()).containsIgnoreCase("forge", "magma")) { for (Item i : Item.getRegistered()) { Item.removeEntry(i); } @@ -374,6 +375,7 @@ public void onDisable() { @Subscribe(priority = Vent.Priority.LOW) public void onJoin(DefaultEvent.Join e) { PlayerSearch.of(e.getPlayer()); + } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/labyrinth-plugin/src/main/java/com/github/sanctum/labyrinth/event/custom/VentMapImpl.java b/labyrinth-plugin/src/main/java/com/github/sanctum/labyrinth/event/custom/VentMapImpl.java index 774210a1..68f9320e 100644 --- a/labyrinth-plugin/src/main/java/com/github/sanctum/labyrinth/event/custom/VentMapImpl.java +++ b/labyrinth-plugin/src/main/java/com/github/sanctum/labyrinth/event/custom/VentMapImpl.java @@ -1,9 +1,10 @@ package com.github.sanctum.labyrinth.event.custom; +import com.github.sanctum.labyrinth.LabyrinthProvider; import com.github.sanctum.labyrinth.api.Service; import com.github.sanctum.labyrinth.data.service.Check; import com.github.sanctum.labyrinth.event.EasyListener; - +import com.github.sanctum.labyrinth.task.TaskScheduler; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -16,16 +17,12 @@ import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import com.github.sanctum.labyrinth.LabyrinthProvider; -import com.github.sanctum.labyrinth.task.Schedule; - public final class VentMapImpl extends VentMap implements Service { final Map>> listeners; @@ -48,7 +45,7 @@ public void unsubscribe(@NotNull Class eventType, @NotNull S .map(s -> s.flatMap(Collection::stream)).orElse(Stream.empty()) ).filter(s -> s.getKey().map(key::equals).orElse(false)).findFirst(); subscription.ifPresent(sub -> - Schedule.sync(() -> subscriptions.get(sub.getUser()).get(eventType).get(sub.getPriority()).remove(sub)) + TaskScheduler.of(() -> subscriptions.get(sub.getUser()).get(eventType).get(sub.getPriority()).remove(sub)).schedule() ); } @@ -59,9 +56,9 @@ public void unsubscribeAll(@NotNull Class eventType, @NotNul .map(Map::values) .map(Collection::stream) .ifPresent(s -> - s.forEachOrdered(set -> Schedule.sync( + s.forEachOrdered(set -> TaskScheduler.of( () -> set.removeIf(sub -> sub.getKey().map(key::equals).orElse(false)) - ).waitReal(1)))); + ).scheduleLater(1)))); } @Override @@ -93,7 +90,7 @@ public void unsubscribeAll(@NotNull String key) { @Override public void unsubscribeAll(Predicate> fun) { subscriptions.values().forEach(v -> v.values().forEach(m -> m.values().forEach( - set -> Schedule.sync(() -> set.removeIf(fun)).run() + set -> TaskScheduler.of(() -> set.removeIf(fun)).schedule() ))); } @@ -109,10 +106,10 @@ public void unsubscribe(@NotNull Object listener) { if (listenerOptional.isPresent()) { VentListener ventListener = listenerOptional.get(); if (Listener.class.isAssignableFrom(ventListener.getListener().getClass())) { - HandlerList.unregisterAll((Listener)ventListener.getListener()); + HandlerList.unregisterAll((Listener) ventListener.getListener()); } - Schedule.sync(() -> listeners.get(ventListener.getHost()).get(ventListener.getKey()).remove(ventListener)) - .run(); + TaskScheduler.of(() -> listeners.get(ventListener.getHost()).get(ventListener.getKey()).remove(ventListener)) + .schedule(); } } @@ -124,12 +121,12 @@ public void unregister(Plugin host, @NotNull String key) { @Override public void unsubscribe(Plugin host, @NotNull String key) { Optional.ofNullable(listeners.get(host)).map(m -> m.get(key)) - .ifPresent(s -> Schedule.sync(() -> s.removeIf(l -> { + .ifPresent(s -> TaskScheduler.of(() -> s.removeIf(l -> { if (Listener.class.isAssignableFrom(l.getListener().getClass())) { - HandlerList.unregisterAll((Listener)l.getListener()); + HandlerList.unregisterAll((Listener) l.getListener()); } return l.getKey().equals(key); - })).run()); + })).schedule()); } public void unregister(Plugin host, @Nullable String key, Object listener) { @@ -139,12 +136,12 @@ public void unregister(Plugin host, @Nullable String key, Object listener) { @Override public void unsubscribe(Plugin host, @Nullable String key, Object listener) { Optional.ofNullable(listeners.get(host)).map(m -> m.get(key)) - .ifPresent(s -> Schedule.sync(() -> s.removeIf(l -> { + .ifPresent(s -> TaskScheduler.of(() -> s.removeIf(l -> { if (Listener.class.isAssignableFrom(l.getListener().getClass())) { - HandlerList.unregisterAll((Listener)l.getListener()); + HandlerList.unregisterAll((Listener) l.getListener()); } return listener.equals(l.getListener()); - })).run()); + })).schedule()); } @Override @@ -157,7 +154,7 @@ public void unsubscribeAll(@NotNull Plugin host) { Optional.ofNullable(listeners.get(host)).ifPresent(m -> { m.values().forEach(set -> set.forEach(l -> { if (Listener.class.isAssignableFrom(l.getListener().getClass())) { - HandlerList.unregisterAll((Listener)l.getListener()); + HandlerList.unregisterAll((Listener) l.getListener()); } })); }); @@ -275,7 +272,7 @@ public List> getSubscriptions() { @Override @SuppressWarnings("unchecked") public Stream> getSubscriptions(final Class tClass, - final Vent.Priority priority) { + final Vent.Priority priority) { return subscriptions.values().stream().map(m -> Optional.ofNullable(m.get(tClass)).map(v -> v.get(priority)) .orElse(Collections.emptySet())) .flatMap(Collection::stream).map(s -> (Vent.Subscription) s); diff --git a/labyrinth-plugin/src/main/resources/lib/1_16_R3.jar b/labyrinth-plugin/src/main/resources/lib/1_16_R3.jar index a154a576..3e7228a1 100644 Binary files a/labyrinth-plugin/src/main/resources/lib/1_16_R3.jar and b/labyrinth-plugin/src/main/resources/lib/1_16_R3.jar differ diff --git a/labyrinth-plugin/src/main/resources/lib/1_18_2_R1.jar b/labyrinth-plugin/src/main/resources/lib/1_18_2_R1.jar new file mode 100644 index 00000000..32dccf59 Binary files /dev/null and b/labyrinth-plugin/src/main/resources/lib/1_18_2_R1.jar differ diff --git a/labyrinth-regions/pom.xml b/labyrinth-regions/pom.xml index ee431bf1..08518a73 100644 --- a/labyrinth-regions/pom.xml +++ b/labyrinth-regions/pom.xml @@ -5,7 +5,7 @@ labyrinth com.github.the-h-team - 1.7.7 + 1.7.8 4.0.0 diff --git a/labyrinth-skulls/pom.xml b/labyrinth-skulls/pom.xml index 5a0b00d4..f698b4cf 100644 --- a/labyrinth-skulls/pom.xml +++ b/labyrinth-skulls/pom.xml @@ -5,7 +5,7 @@ labyrinth com.github.the-h-team - 1.7.7 + 1.7.8 4.0.0 diff --git a/pom.xml b/pom.xml index 9c7951cf..3d6b8e19 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.github.the-h-team labyrinth - 1.7.7 + 1.7.8 labyrinth-common labyrinth-gui @@ -28,7 +28,7 @@ 1.8 UTF-8 1.0.0 - 1.7.2 + 1.7.8