Skip to content
Open
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 @@ -60,6 +60,9 @@ public void onCommandExecute(PlayerCommandPreprocessEvent event) {
public void onLeave(PlayerQuitEvent event) {
Player player = event.getPlayer();

// A menu that is still being built must not open after the player has left.
Menu.cancelPendingOpen(player);

if (Menu.isInMenu(player)) {
Menu.closeMenu(plugin, player, false);
}
Expand Down
82 changes: 62 additions & 20 deletions src/main/java/com/extendedclip/deluxemenus/menu/Menu.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;

import net.kyori.adventure.text.Component;
Expand All @@ -25,7 +26,11 @@
public class Menu {

private static final Map<String, Menu> menus = new HashMap<>();
private static final Set<MenuHolder> menuHolders = new HashSet<>();
// Concurrent because it is also read off the main thread (placeholders, refresh tasks).
private static final Set<MenuHolder> menuHolders = ConcurrentHashMap.newKeySet();
// Player UUID -> the newest menu that is still being built for them. Removed when the player quits or a newer
// openMenu() replaces it, so the sync open step knows it must not open (and leak) this holder.
private static final Map<UUID, MenuHolder> pendingOpens = new ConcurrentHashMap<>();
private static final Map<UUID, Menu> lastOpenedMenus = new HashMap<>();

private final DeluxeMenus plugin;
Expand Down Expand Up @@ -102,6 +107,7 @@ public static void unloadForShutdown(final @NotNull DeluxeMenus plugin) {
}
}
menus.clear();
pendingOpens.clear();
}

public static int getLoadedMenuSize() {
Expand Down Expand Up @@ -190,8 +196,7 @@ public static void closeMenu(final @NotNull DeluxeMenus plugin, final @NotNull P

MenuHolder holder = optionalHolder.get();

holder.stopPlaceholderUpdate();
holder.stopRefreshTask();
holder.markClosed();

if (executeCloseActions) {
holder.getMenu().map(Menu::options).map(MenuOptions::closeHandler).flatMap(h -> h).ifPresent(h -> h.onClick(holder));
Expand All @@ -208,12 +213,28 @@ public static void closeMenu(final @NotNull DeluxeMenus plugin, final @NotNull P
}

public static void closeMenuForShutdown(final @NotNull DeluxeMenus plugin, final @NotNull Player player) {
getMenuHolder(player).ifPresent(MenuHolder::stopPlaceholderUpdate);
getMenuHolder(player).ifPresent(MenuHolder::markClosed);

player.closeInventory();
cleanInventory(plugin, player);
}

/**
* Cancels a menu open that is still being built for this player. Called when the player quits, so the open
* cannot finish afterwards and register a holder for a player who is gone.
*/
public static void cancelPendingOpen(final @NotNull Player player) {
pendingOpens.remove(player.getUniqueId());
}

/**
* Drops a holder whose player disconnected without the menu being closed. Main thread only.
*/
static void discardHolder(final @NotNull MenuHolder holder) {
holder.markClosed();
menuHolders.remove(holder);
}

public static void closeMenu(final @NotNull DeluxeMenus plugin, final @NotNull Player player, final boolean close) {
closeMenu(plugin, player, close, false);
}
Expand Down Expand Up @@ -293,7 +314,15 @@ public void openMenu(final @NotNull Player viewer, final @Nullable Map<String, S
return;
}

final UUID viewerId = viewer.getUniqueId();
// Newest open wins: this replaces any older open for this player that is still being built.
pendingOpens.put(viewerId, holder);

Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
// The player quit, or a newer openMenu() replaced this one. Don't bother building it.
if (pendingOpens.get(viewerId) != holder) {
return;
}

Set<MenuItem> activeItems = new HashSet<>();

Expand Down Expand Up @@ -329,6 +358,7 @@ public void openMenu(final @NotNull Player viewer, final @Nullable Map<String, S
}

if (activeItems.isEmpty()) {
pendingOpens.remove(viewerId, holder);
return;
}

Expand Down Expand Up @@ -383,28 +413,40 @@ public void openMenu(final @NotNull Player viewer, final @Nullable Map<String, S
final boolean updatePlaceholders = update;

Bukkit.getScheduler().runTask(plugin, () -> {
if(options.refresh()) {
holder.startRefreshTask();
// Drop this open if the player quit (or a newer open replaced it) while the menu was being built.
// Without this, the holder would be registered and its tasks started for a player who is gone,
// and nothing would ever close it. isConnected() checks this exact Player object, unlike
// isOnline(), which is also true when the same player has already rejoined.
if (!pendingOpens.remove(viewerId, holder) || !viewer.isConnected()) {
holder.markClosed();
return;
}

if (isInMenu(holder.getViewer())) {
closeMenu(plugin, holder.getViewer(), false);
if (isInMenu(viewer)) {
closeMenu(plugin, viewer, false);
}

// null means the open did not happen (for example InventoryOpenEvent was cancelled).
if (viewer.openInventory(inventory) == null) {
holder.markClosed();
return;
}

viewer.openInventory(inventory);
menuHolders.add(holder);

if (updatePlaceholders) {
holder.startUpdatePlaceholdersTask();
}
});

Bukkit.getScheduler().runTask(plugin, () -> {
DeluxeMenusOpenMenuEvent openEvent = new DeluxeMenusOpenMenuEvent(viewer, holder);
Bukkit.getPluginManager().callEvent(openEvent);
});
});
}
if (options.refresh()) {
holder.startRefreshTask();
}

if (updatePlaceholders) {
holder.startUpdatePlaceholdersTask();
}

DeluxeMenusOpenMenuEvent openEvent = new DeluxeMenusOpenMenuEvent(viewer, holder);
Bukkit.getPluginManager().callEvent(openEvent);
});
});
}

public void refreshForAll() {
menuHolders.stream().filter(menuHolder -> menuHolder.getMenuName().equalsIgnoreCase(options.name())).forEach(MenuHolder::refreshMenu);
Expand Down
64 changes: 63 additions & 1 deletion src/main/java/com/extendedclip/deluxemenus/menu/MenuHolder.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ public class MenuHolder implements InventoryHolder {
private BukkitTask refreshTask = null;
private Inventory inventory;
private boolean updating;
// Set once the menu is closed (or never opened). A closed holder never starts tasks again. Volatile because the
// repeating tasks read it on async threads.
private volatile boolean closed = false;
private boolean parsePlaceholdersInArguments;
private boolean parsePlaceholdersAfterArguments;
private Map<String, String> typedArgs;
Expand Down Expand Up @@ -124,6 +127,9 @@ public Optional<Menu> getMenu() {
}

public void refreshMenu() {
if (closed) {
return;
}

Optional<Menu> optionalMenu = getMenu();
if (optionalMenu.isEmpty()) {
Expand Down Expand Up @@ -173,10 +179,20 @@ public void refreshMenu() {
}

if (active.isEmpty()) {
Menu.closeMenu(plugin, getViewer(), true);
// Close on the main thread, and only if this is still the player's open menu (not a newer one).
Bukkit.getScheduler().runTask(plugin, () -> {
if (Menu.getMenuHolder(getViewer()).orElse(null) == this) {
Menu.closeMenu(plugin, getViewer(), true);
}
});
return;
}

Bukkit.getScheduler().runTask(plugin, () -> {
// Closed while refreshing: don't touch it, and above all don't restart its update task.
if (closed) {
return;
}

boolean update = false;

Expand Down Expand Up @@ -236,14 +252,53 @@ public void stopRefreshTask() {
}
}

/**
* Marks this holder as closed and stops its tasks. After this, the start methods do nothing.
*/
void markClosed() {
closed = true;
stopPlaceholderUpdate();
stopRefreshTask();
}

public boolean isClosed() {
return closed;
}

/**
* Safety net for the repeating tasks: cancels the task if this holder is closed or its player disconnected.
* A holder whose player is gone but was never closed is also removed from the open menus on the main thread.
*
* @return true if the task was cancelled and should not run
*/
private boolean stopIfAbandoned(final @NotNull BukkitRunnable task) {
if (!closed && viewer.isConnected()) {
return false;
}

task.cancel();
if (!closed && plugin.isEnabled()) {
Bukkit.getScheduler().runTask(plugin, () -> Menu.discardHolder(this));
}
return true;
}

public void startRefreshTask() {
if (closed) {
return;
}

if(refreshTask != null) {
stopRefreshTask();
}

refreshTask = new BukkitRunnable() {
@Override
public void run() {
if (stopIfAbandoned(this)) {
return;
}

refreshMenu();
}
}.runTaskTimerAsynchronously(plugin, 20L,
Expand All @@ -254,6 +309,9 @@ public void run() {
}

public void startUpdatePlaceholdersTask() {
if (closed) {
return;
}

if (updateTask != null) {
stopPlaceholderUpdate();
Expand All @@ -264,6 +322,10 @@ public void startUpdatePlaceholdersTask() {
@Override
public void run() {

if (stopIfAbandoned(this)) {
return;
}

if (updating) {
return;
}
Expand Down