Made EventDebounce more reusable.

This commit is contained in:
sk89q 2014-08-22 16:52:34 -07:00
parent 9b7970475a
commit d0ff1815aa
2 changed files with 26 additions and 18 deletions

View File

@ -555,20 +555,7 @@ public void onPlayerShearEntity(PlayerShearEntityEvent event) {
@EventHandler
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
Item item = event.getItem();
// These events happen very frequently so let's reduce their frequency
EventDebounce debounce = WGMetadata.getIfPresent(item, ITEM_PICKUP_DEBOUNCE_KEY, EventDebounce.class);
if (debounce != null && debounce.isValid()) {
if (debounce.getLastCancellation()) {
event.setCancelled(true);
}
} else {
boolean cancelled = Events.fireAndTestCancel(new DestroyEntityEvent(event, create(event.getPlayer()), event.getItem()));
if (cancelled) {
event.setCancelled(true);
}
WGMetadata.put(item, ITEM_PICKUP_DEBOUNCE_KEY, new EventDebounce(cancelled));
}
EventDebounce.debounce(item, ITEM_PICKUP_DEBOUNCE_KEY, 10000, event, new DestroyEntityEvent(event, create(event.getPlayer()), event.getItem()));
}
@EventHandler

View File

@ -19,23 +19,44 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.worldguard.bukkit.util.WGMetadata;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.metadata.Metadatable;
class EventDebounce {
private static final int DEBOUNCE_TIME = 10000;
private final long time = System.currentTimeMillis();
private final int debounceTime;
private final boolean cancelled;
EventDebounce(boolean cancelled) {
EventDebounce(int debounceTime, boolean cancelled) {
this.debounceTime = debounceTime;
this.cancelled = cancelled;
}
public boolean isValid() {
return System.currentTimeMillis() - time < DEBOUNCE_TIME;
return System.currentTimeMillis() - time < debounceTime;
}
public boolean getLastCancellation() {
return cancelled;
}
public static <T extends Event & Cancellable> void debounce(Metadatable target, String key, int debounceTime, Cancellable originalEvent, T firedEvent) {
EventDebounce debounce = WGMetadata.getIfPresent(target, key, EventDebounce.class);
if (debounce != null && debounce.isValid()) {
if (debounce.getLastCancellation()) {
originalEvent.setCancelled(true);
}
} else {
boolean cancelled = Events.fireAndTestCancel(firedEvent);
if (cancelled) {
originalEvent.setCancelled(true);
}
WGMetadata.put(target, key, new EventDebounce(debounceTime, cancelled));
}
}
}