Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the ability to override listener event priorities #125

Merged
merged 2 commits into from
Aug 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
import dev.frankheijden.insights.api.config.Messages;
import dev.frankheijden.insights.api.config.Notifications;
import dev.frankheijden.insights.api.config.Settings;
import dev.frankheijden.insights.api.listeners.manager.InsightsListenerManager;
import dev.frankheijden.insights.api.metrics.MetricsManager;
import java.util.Map;

public interface InsightsMain {

Expand Down Expand Up @@ -54,5 +54,6 @@ public interface InsightsMain {

ScanHistory getScanHistory();

Map<String, Class<?>> getAllowedDisableEvents();
InsightsListenerManager getListenerManager();

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package dev.frankheijden.insights.api.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AllowPriorityOverride {

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,16 @@
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarFlag;
import org.bukkit.boss.BarStyle;
import org.bukkit.event.Event;
import org.bukkit.event.EventPriority;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class Settings {
Expand All @@ -36,7 +41,8 @@ public class Settings {
public final int SPIGOT_ENTITY_TRACKER_INTERVAL_TICKS;
public final boolean APPLY_PISTON_LIMITS;
public final int PAGINATION_RESULTS_PER_PAGE;
public final List<Class<?>> DISABLED_EVENTS;
public final List<Class<? extends Event>> DISABLED_EVENTS;
public final Map<Class<? extends Event>, EventPriority> LISTENER_PRIORITIES;

/**
* Constructs a new Settings object from the given YamlParser.
Expand Down Expand Up @@ -75,9 +81,26 @@ public Settings(InsightsPlugin plugin, YamlParser parser) {
PAGINATION_RESULTS_PER_PAGE = parser.getInt("settings.pagination-results-per-page", 6, 1, Integer.MAX_VALUE);

DISABLED_EVENTS = new ArrayList<>();
Map<String, Class<?>> events = plugin.getAllowedDisableEvents();
for (String str : parser.getSet("settings.disabled-listeners", events.keySet(), "event")) {
DISABLED_EVENTS.add(events.get(str));
Map<String, Method> disableEvents = plugin.getListenerManager().getAllowedDisableMethods();
for (String str : parser.getSet("settings.disabled-listeners", disableEvents.keySet(), "event")) {
@SuppressWarnings("unchecked")
var eventClass = (Class<? extends Event>) disableEvents.get(str).getParameterTypes()[0];
DISABLED_EVENTS.add(eventClass);
}

LISTENER_PRIORITIES = new HashMap<>();
Map<String, Method> overrideEvents = plugin.getListenerManager().getAllowedPriorityOverrideMethods();
for (String event : parser.getKeys("settings.listener-priorities")) {
String eventUppercase = event.toUpperCase(Locale.ENGLISH);

@SuppressWarnings("unchecked")
var eventClass = (Class<? extends Event>) overrideEvents.get(eventUppercase).getParameterTypes()[0];
if (eventClass == null) continue;

LISTENER_PRIORITIES.put(
eventClass,
parser.getEnum("settings.listener-priorities." + event, EventPriority.LOWEST)
);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package dev.frankheijden.insights.api.listeners.manager;

import java.lang.reflect.Method;
import java.util.Map;

public interface InsightsListenerManager {

void register();

Map<String, Method> getAllowedDisableMethods();

Map<String, Method> getAllowedPriorityOverrideMethods();
}
95 changes: 9 additions & 86 deletions Insights/src/main/java/dev/frankheijden/insights/Insights.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import cloud.commandframework.paper.PaperCommandManager;
import dev.frankheijden.insights.api.InsightsPlugin;
import dev.frankheijden.insights.api.addons.AddonManager;
import dev.frankheijden.insights.api.annotations.AllowDisabling;
import dev.frankheijden.insights.api.concurrent.ChunkContainerExecutor;
import dev.frankheijden.insights.api.concurrent.PlayerList;
import dev.frankheijden.insights.api.concurrent.storage.AddonStorage;
Expand All @@ -23,12 +22,10 @@
import dev.frankheijden.insights.api.config.Settings;
import dev.frankheijden.insights.api.config.limits.Limit;
import dev.frankheijden.insights.api.config.parser.YamlParseException;
import dev.frankheijden.insights.api.listeners.InsightsListener;
import dev.frankheijden.insights.api.metrics.MetricsManager;
import dev.frankheijden.insights.api.objects.wrappers.ScanObject;
import dev.frankheijden.insights.api.tasks.UpdateCheckerTask;
import dev.frankheijden.insights.api.utils.IOUtils;
import dev.frankheijden.insights.api.utils.ReflectionUtils;
import dev.frankheijden.insights.commands.CommandInsights;
import dev.frankheijden.insights.commands.CommandScan;
import dev.frankheijden.insights.commands.CommandScanCache;
Expand All @@ -39,66 +36,28 @@
import dev.frankheijden.insights.commands.parser.ScanHistoryPageArgument;
import dev.frankheijden.insights.commands.parser.ScanObjectArrayArgument;
import dev.frankheijden.insights.concurrent.ContainerExecutorService;
import dev.frankheijden.insights.listeners.BlockListener;
import dev.frankheijden.insights.listeners.ChunkListener;
import dev.frankheijden.insights.listeners.EntityListener;
import dev.frankheijden.insights.listeners.PaperBlockListener;
import dev.frankheijden.insights.listeners.PaperEntityListener;
import dev.frankheijden.insights.listeners.PistonListener;
import dev.frankheijden.insights.listeners.PlayerListener;
import dev.frankheijden.insights.listeners.WorldListener;
import dev.frankheijden.insights.listeners.manager.ListenerManager;
import dev.frankheijden.insights.placeholders.InsightsPlaceholderExpansion;
import dev.frankheijden.insights.tasks.EntityTrackerTask;
import dev.frankheijden.insights.tasks.PlayerTrackerTask;
import dev.frankheijden.minecraftreflection.MinecraftReflection;
import io.leangen.geantyref.TypeToken;
import io.papermc.lib.PaperLib;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;
import org.bukkit.scheduler.BukkitTask;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

public class Insights extends InsightsPlugin {

private static final Map<String, Class<?>> ALLOWED_DISABLED_EVENTS;

static {
Map<String, Class<?>> map = new HashMap<>();

List<Method> listenerMethods = new ArrayList<>();
listenerMethods.addAll(ReflectionUtils.getAnnotatedMethods(BlockListener.class, AllowDisabling.class));
listenerMethods.addAll(ReflectionUtils.getAnnotatedMethods(WorldListener.class, AllowDisabling.class));
if (PaperLib.isPaper()) {
listenerMethods.addAll(ReflectionUtils.getAnnotatedMethods(PaperBlockListener.class, AllowDisabling.class));
}

for (Method method : listenerMethods) {
Class<?>[] params = method.getParameterTypes();
if (params.length != 1) continue;

Class<?> clazz = params[0];
map.put(clazz.getSimpleName().toUpperCase(Locale.ENGLISH), clazz);
}

ALLOWED_DISABLED_EVENTS = Collections.unmodifiableMap(map);
}

private static final String SETTINGS_FILE_NAME = "config.yml";
private static final String MESSAGES_FILE_NAME = "messages.yml";
private static final String LIMITS_FOLDER_NAME = "limits";
Expand All @@ -118,7 +77,7 @@ public class Insights extends InsightsPlugin {
private EntityTrackerTask entityTrackerTask;
private MetricsManager metricsManager;
private ScanHistory scanHistory;
private PlayerListener playerListener;
private ListenerManager listenerManager;
private InsightsPlaceholderExpansion placeholderExpansion;
private BukkitTask playerTracker = null;
private BukkitAudiences audiences = null;
Expand All @@ -133,6 +92,7 @@ public void onLoad() {
public void onEnable() {
super.onEnable();
this.audiences = BukkitAudiences.create(this);
this.listenerManager = new ListenerManager(this);
reloadConfigs();

addonManager = new AddonManager(this, getDataFolder().toPath().resolve("addons"));
Expand Down Expand Up @@ -161,41 +121,14 @@ public void onEnable() {
scanHistory = new ScanHistory();

loadCommands();
listenerManager.register();

List<InsightsListener> listeners = new ArrayList<>();
playerListener = new PlayerListener(this);
listeners.add(playerListener);
listeners.add(new ChunkListener(this));

List<InsightsListener> disableListeners = new ArrayList<>();
disableListeners.add(new BlockListener(this));
disableListeners.add(new WorldListener(this));

if (PaperLib.isPaper()) {
listeners.add(new PaperEntityListener(this));
disableListeners.add(new PaperBlockListener(this));
} else {
listeners.add(new EntityListener(this));
if (!PaperLib.isPaper()) {
entityTrackerTask = new EntityTrackerTask(this);
int interval = settings.SPIGOT_ENTITY_TRACKER_INTERVAL_TICKS;
var interval = settings.SPIGOT_ENTITY_TRACKER_INTERVAL_TICKS;
Bukkit.getScheduler().runTaskTimer(this, entityTrackerTask, 0, interval);
}

if (settings.APPLY_PISTON_LIMITS) {
listeners.add(new PistonListener(this));
}

registerEvents(listeners.toArray(new InsightsListener[0]));
registerEvents(disableListeners.toArray(new InsightsListener[0]));

for (Class<?> clazz : settings.DISABLED_EVENTS) {
HandlerList list = MinecraftReflection.of(clazz).invoke(null, "getHandlerList");
for (InsightsListener listener : disableListeners) {
list.unregister(listener);
}
getLogger().info("Unregistered listener of '" + clazz.getSimpleName() + "'");
}

reload();

if (settings.UPDATE_CHECKER_ENABLED) {
Expand Down Expand Up @@ -223,8 +156,9 @@ public void onDisable() {
audiences.close();
}

public PlayerListener getPlayerListener() {
return playerListener;
@Override
public ListenerManager getListenerManager() {
return listenerManager;
}

public Optional<EntityTrackerTask> getEntityTracker() {
Expand Down Expand Up @@ -417,17 +351,6 @@ public ScanHistory getScanHistory() {
return scanHistory;
}

@Override
public Map<String, Class<?>> getAllowedDisableEvents() {
return ALLOWED_DISABLED_EVENTS;
}

private void registerEvents(InsightsListener... listeners) {
for (InsightsListener listener : listeners) {
Bukkit.getPluginManager().registerEvents(listener, this);
}
}

@Override
public void reload() {
if (playerTracker != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import dev.frankheijden.insights.Insights;
import dev.frankheijden.insights.api.annotations.AllowDisabling;
import dev.frankheijden.insights.api.annotations.AllowPriorityOverride;
import dev.frankheijden.insights.api.listeners.InsightsListener;
import dev.frankheijden.insights.api.objects.wrappers.ScanObject;
import dev.frankheijden.insights.api.util.MaterialTags;
Expand Down Expand Up @@ -45,6 +46,7 @@ public BlockListener(Insights plugin) {
* Handles the BlockPlaceEvent for players.
* Chunk limitations are applied in here on the lowest (first) event priority.
*/
@AllowPriorityOverride
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
var block = event.getBlock();
Expand Down Expand Up @@ -184,7 +186,7 @@ public void onBlockExplode(BlockExplodeEvent event) {
var block = event.getBlock();
var location = block.getLocation();

var playerListener = ((Insights) plugin).getPlayerListener();
var playerListener = ((Insights) plugin).getListenerManager().getPlayerListener();
Optional<PlayerListener.ExplodedBed> bedOptional = playerListener.getIntentionalDesignBugAt(location);
if (bedOptional.isPresent()) {
var explodedBed = bedOptional.get();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dev.frankheijden.insights.listeners;

import dev.frankheijden.insights.api.InsightsPlugin;
import dev.frankheijden.insights.api.annotations.AllowPriorityOverride;
import dev.frankheijden.insights.api.events.EntityRemoveFromWorldEvent;
import dev.frankheijden.insights.api.listeners.InsightsListener;
import dev.frankheijden.insights.api.objects.wrappers.ScanObject;
Expand Down Expand Up @@ -63,6 +64,7 @@ public void onEntityChangeBlock(EntityChangeBlockEvent event) {
/**
* Handles the HangingPlaceEvent for Item Frames and Paintings.
*/
@AllowPriorityOverride
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onHangingPlace(HangingPlaceEvent event) {
if (handleEntityPlace(event.getPlayer(), event.getEntity())) {
Expand All @@ -82,6 +84,7 @@ public void onHangingPlaceMonitor(HangingPlaceEvent event) {
/**
* Handles the EntityPlaceEvent for Armor Stands and End Crystals.
*/
@AllowPriorityOverride
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onEntityPlace(EntityPlaceEvent event) {
if (handleEntityPlace(event.getPlayer(), event.getEntity())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import dev.frankheijden.insights.api.InsightsPlugin;
import dev.frankheijden.insights.api.addons.Region;
import dev.frankheijden.insights.api.annotations.AllowPriorityOverride;
import dev.frankheijden.insights.api.concurrent.ScanOptions;
import dev.frankheijden.insights.api.concurrent.storage.Storage;
import dev.frankheijden.insights.api.config.limits.Limit;
Expand Down Expand Up @@ -29,11 +30,13 @@ public PistonListener(InsightsPlugin plugin) {
super(plugin);
}

@AllowPriorityOverride
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
handlePistonEvent(event, event.getBlocks());
}

@AllowPriorityOverride
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
handlePistonEvent(event, event.getBlocks());
Expand Down
Loading