Пример #1
0
 @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
 public void onInventoryClick(InventoryClickEvent e) {
   if (useLocaleInv && e.getView() instanceof LocaleInventory) {
     LocaleInventory inv = (LocaleInventory) e.getView();
     InventoryClickEvent clickEvent =
         new InventoryClickEvent(
             inv.getView(), e.getSlotType(), e.getRawSlot(), e.isRightClick(), e.isShiftClick());
     Bukkit.getServer().getPluginManager().callEvent(clickEvent);
     if (clickEvent.isCancelled()) {
       e.setCancelled(true);
     } else {
       switch (clickEvent.getResult()) {
         case DEFAULT: // Can't really do this with current events
         case ALLOW:
           System.out.println("ok...");
           System.out.println(inv.getView().getItem(e.getRawSlot()));
           inv.getView().setItem(e.getRawSlot(), clickEvent.getCursor());
           System.out.println(inv.getView().getItem(e.getRawSlot()));
           break;
         case DENY:
           break;
       }
     }
     for (LocaleInventory localeInv : localeInventories) {
       if (localeInv != inv) localeInv.reload();
     }
   }
 }
Пример #2
0
  @Override
  @SuppressWarnings(
      "deprecation") // Player.updateInventory has been deprecated for a while with no alternative
                     // available yet
  public void onClick(final InventoryClickEvent click) {
    final int last = click.getView().getTopInventory().getSize() - 1;

    // cancel shift clicks on items outside of delivery inventory to prevent indirect moving of
    // items into delivery inventory
    if (click.isShiftClick()
        && (click.getCurrentItem().getTypeId() != Material.AIR.getId())
        && (click.getRawSlot() > last)) click.setCancelled(true);

    // cancel clicks with item on cursor in delivery inventory to prevent direct placement of items
    // into delivery inventory
    if ((click.getCursor().getTypeId() != Material.AIR.getId())
        && (click.getRawSlot() >= 0)
        && (click.getRawSlot() <= last)) click.setCancelled(true);

    if (click.isCancelled()) {
      click.setCursor(click.getCursor());
      ((Player) click.getWhoClicked()).updateInventory();
      this.courier.send((Player) click.getWhoClicked(), "withdraw-only");
    }
  }
Пример #3
0
  @EventHandler(priority = EventPriority.NORMAL)
  public void onInventoryClick(InventoryClickEvent event) {

    if (!isItemInfoBook(event.getCursor())) {
      return;
    }

    if (!isPlace(event.getAction())) {
      return;
    }

    if (isInventory(event.getInventory())) {
      return;
    }

    if ((event.getRawSlot() - event.getView().getTopInventory().getSize()) >= 0) {
      return;
    }

    Module.sendMessage(
        "bInfoBooks",
        (Player) event.getWhoClicked(),
        "You can't store InfoBooks. Please drop the InfoBook to remove it from your inventory.");
    Module.sendMessage(
        "bInfoBooks",
        (Player) event.getWhoClicked(),
        "You can get another copy of the book via the '/book' command.");
    event.setResult(Result.DENY);
  }
Пример #4
0
 @EventHandler(priority = EventPriority.MONITOR)
 void onInventoryClick(InventoryClickEvent event) {
   if ((event.getInventory().getTitle().equals(this.name))
       && (event.getWhoClicked().getName().equals(this.player.getName()))) {
     event.setCancelled(true);
     int slot = event.getRawSlot();
     if ((slot >= 0) && (slot < this.size) && (this.optionNames[slot] != null)) {
       Plugin plugin = this.plugin;
       OptionClickEvent e =
           new OptionClickEvent((Player) event.getWhoClicked(), slot, this.optionNames[slot]);
       this.handler.onOptionClick(e);
       if (e.willClose()) {
         final Player p = (Player) event.getWhoClicked();
         Bukkit.getScheduler()
             .scheduleSyncDelayedTask(
                 plugin,
                 new Runnable() {
                   public void run() {
                     p.closeInventory();
                   }
                 },
                 1L);
       }
       if (e.willDestroy()) {
         destroy();
       }
     }
   }
 }
Пример #5
0
  @EventHandler
  public void onInterfaceInteract(InventoryClickEvent event) {
    if (event.getView() != this) return;

    ItemStack itemClicked = event.getCurrentItem();
    if (itemClicked == null || itemClicked.getType() == Material.AIR) return;

    event.setCancelled(true);

    // If not right or left-click.
    if (!(event.getClick() == ClickType.RIGHT || event.getClick() == ClickType.LEFT)) return;

    if (this.ACCEPT_OBJECT.equals(itemClicked)) {
      onAcceptPressed();
      return;
    }

    if (this.BACK_OBJECT.equals(itemClicked)) {
      if (onBackPressed()) scheduleCloseOfInventory();
      return;
    }

    int rawSlot = event.getRawSlot();
    int slotNumber = event.getSlot();
    boolean usedTopInv = rawSlot < getTopInventory().getSize();

    if (usedTopInv) onSelectionItemPressed(slotNumber, itemClicked);
    else onControlItemPressed(slotNumber, itemClicked);
  }
Пример #6
0
  /**
   * Handles attribute menu interaction
   *
   * @param event event details
   */
  @EventHandler
  public void onClick(InventoryClickEvent event) {
    // Class selection
    if (InventoryManager.isMatching(event.getInventory(), MENU_KEY)) {
      // Do nothing when clicking outside the inventory
      if (event.getSlot() == -999) {
        return;
      }

      boolean top = event.getRawSlot() < event.getView().getTopInventory().getSize();
      AttributeManager manager = SkillAPI.getAttributeManager();

      // Interact with the skill tree when clicking in the top region
      if (top) {
        if (event.getSlot() < manager.getKeys().size() || event.getCursor() != null) {
          event.setCancelled(true);

          PlayerData data = SkillAPI.getPlayerData((Player) event.getWhoClicked());
          if (event.isRightClick() && SkillAPI.getSettings().isAttributesDowngrade()) {
            data.refundAttribute(manager.getKeys().toArray()[event.getSlot()].toString());
          } else if (event.isLeftClick()) {

            Object[] keys = manager.getKeys().toArray();
            data.upAttribute(keys[event.getSlot()].toString());
          }
          data.openAttributeMenu();
        }
      }

      // Do not allow shift clicking items into the inventory
      else if (event.isShiftClick()) {
        event.setCancelled(true);
      }
    }
  }
Пример #7
0
 public static void debug(InventoryClickEvent event) {
   System.out.println("===== DEBUG START =====");
   System.out.println("event.getAction() " + event.getAction());
   System.out.println("event.isLeftClick() " + event.isLeftClick());
   System.out.println("event.isRightClick() " + event.isRightClick());
   System.out.println("event.isShiftClick() " + event.isShiftClick());
   System.out.println("event.getClick() " + event.getClick());
   System.out.println("event.getCurrentItem() " + event.getCurrentItem());
   System.out.println("event.getCursor() " + event.getCursor());
   System.out.println("event.getHotbarButton() " + event.getHotbarButton());
   System.out.println("getInventory().getType() " + event.getInventory().getType());
   System.out.println("event.getRawSlot() " + event.getRawSlot());
   System.out.println("event.getResult() " + event.getResult());
   System.out.println("event.getSlot() " + event.getSlot());
   System.out.println("event.getSlotType() " + event.getSlotType());
   System.out.println(
       "getView().getTopInventory().getType() " + event.getView().getTopInventory().getType());
   System.out.println("getView().getType() " + event.getView().getType());
   System.out.println(
       "getView().getBottomInventory().getType() "
           + event.getView().getBottomInventory().getType());
   System.out.println("event.getWhoClicked() " + event.getWhoClicked());
   System.out.println("-----");
   System.out.println("isOutside(event) " + isOutside(event));
   System.out.println("isTopInventory(event) " + isTopInventory(event));
   System.out.println("isBottomInventory(event) " + isBottomInventory(event));
   System.out.println("getAlter(event) " + getAlter(event));
   System.out.println("isAltering(event) " + isAltering(event));
   System.out.println("isEquipping(event) " + isEquipping(event));
   System.out.println("===== DEBUG END =====");
 }
 @Override
 protected void onInventoryClick(InventoryClickEvent event, Player player) {
   event.setCancelled(true);
   final int slot = event.getRawSlot();
   if (slot >= 0 && slot <= 7) {
     // handle changing sell stack size
     ItemStack item = event.getCurrentItem();
     if (item != null && item.getType() != Material.AIR) {
       int amount = item.getAmount();
       amount = this.getNewAmountAfterEditorClick(event, amount);
       if (amount <= 0) amount = 1;
       if (amount > item.getMaxStackSize()) amount = item.getMaxStackSize();
       item.setAmount(amount);
     }
   } else if ((slot >= 9 && slot <= 16) || (slot >= 18 && slot <= 25)) {
     if (((TradingPlayerShopkeeper) shopkeeper).clickedItem != null) {
       // placing item
       final Inventory inventory = event.getInventory();
       Bukkit.getScheduler()
           .runTaskLater(
               ShopkeepersPlugin.getInstance(),
               new Runnable() {
                 public void run() {
                   inventory.setItem(slot, ((TradingPlayerShopkeeper) shopkeeper).clickedItem);
                   ((TradingPlayerShopkeeper) shopkeeper).clickedItem = null;
                 }
               },
               1);
     } else {
       // changing stack size
       ItemStack item = event.getCurrentItem();
       if (item != null && item.getType() != Material.AIR) {
         int amount = item.getAmount();
         amount = this.getNewAmountAfterEditorClick(event, amount);
         if (amount <= 0) {
           event.getInventory().setItem(slot, null);
         } else {
           if (amount > item.getMaxStackSize()) amount = item.getMaxStackSize();
           item.setAmount(amount);
         }
       }
     }
   } else if (slot >= 27) {
     // clicking in player inventory
     if (event.isShiftClick() || !event.isLeftClick()) {
       return;
     }
     ItemStack cursor = event.getCursor();
     if (cursor != null && cursor.getType() != Material.AIR) {
       return;
     }
     ItemStack current = event.getCurrentItem();
     if (current != null && current.getType() != Material.AIR) {
       ((TradingPlayerShopkeeper) shopkeeper).clickedItem = current.clone();
       ((TradingPlayerShopkeeper) shopkeeper).clickedItem.setAmount(1);
     }
   } else {
     super.onInventoryClick(event, player);
   }
 }
Пример #9
0
  @ClickHandler(
      status = {tNpcStatus.SELL_AMOUNTS},
      inventory = InventoryType.TRADER)
  public void sellAmountsItems(InventoryClickEvent e) {
    e.setCancelled(true);
    // check permission
    if (!perms.has(player, "dtl.trader.sell")) return;

    int slot = e.getSlot();
    if (stock.isUiSlot(slot)) return;

    if (checkItemAmount(slot)) {
      if (handleClick(e.getRawSlot())) {
        if (!inventoryHasPlace(slot)) {
          // send message
          locale.sendMessage(player, "trader-transaction-failed-inventory");
        } else if (!sellTransaction(slot)) {
          // send message
          locale.sendMessage(player, "trader-transaction-failed-player-money");
        } else {
          addToInventory(slot);

          // send message
          locale.sendMessage(
              player,
              "trader-transaction-success",
              "trader",
              getNPC().getName(),
              "player",
              player.getName(),
              "action",
              "#bought",
              "item",
              getSelectedItem().getName(),
              "amount",
              String.valueOf(getSelectedItem().getAmount()),
              "price",
              String.format("%.2f", stock.parsePrice(getSelectedItem(), slot)).replace(',', '.'));

          // update inventory - lore
          updatePlayerInventory();
        }
      } else {
        // informations about the item some1 wants to buy
        locale.sendMessage(
            player,
            "trader-transaction-item",
            "item",
            getSelectedItem().getName(),
            "amount",
            String.valueOf(getSelectedItem().getAmount()),
            "price",
            String.format("%.2f", stock.parsePrice(getSelectedItem(), slot)).replace(',', '.'));
      }
    }
  }
Пример #10
0
 @EventHandler(ignoreCancelled = true)
 public void onPrefsMenuClick(InventoryClickEvent event) {
   Inventory inv = event.getInventory();
   String name = inv.getTitle();
   if (name.equals("§4TARDIS Key Prefs Menu")) {
     Player p = (Player) event.getWhoClicked();
     int slot = event.getRawSlot();
     if (slot >= 0 && slot < 27) {
       switch (slot) {
         case 0:
         case 1:
         case 2:
         case 3:
         case 4:
         case 5:
         case 6:
         case 7:
         case 8:
         case 10:
         case 12:
         case 14:
         case 16:
           event.setCancelled(true);
           // set display name of key in slot 18
           ItemStack key = inv.getItem(18);
           if (key == null || !key.getType().equals(Material.GOLD_NUGGET) || !key.hasItemMeta()) {
             return;
           }
           // get Display name of selected key
           ItemStack choice = inv.getItem(slot);
           ItemMeta choice_im = choice.getItemMeta();
           String choice_name = choice_im.getDisplayName();
           ItemMeta sonic_im = key.getItemMeta();
           sonic_im.setDisplayName(choice_name);
           key.setItemMeta(sonic_im);
           break;
         case 18:
           break;
         case 26:
           // close
           event.setCancelled(true);
           close(p);
           break;
         default:
           event.setCancelled(true);
           break;
       }
     } else {
       ClickType click = event.getClick();
       if (click.equals(ClickType.SHIFT_RIGHT) || click.equals(ClickType.SHIFT_LEFT)) {
         event.setCancelled(true);
       }
     }
   }
 }
Пример #11
0
 @EventHandler
 public void onAnvil(InventoryClickEvent e) {
   if (e.getRawSlot() == 2
       && e.getWhoClicked() instanceof Player
       && e.getInventory().getType() == InventoryType.ANVIL) {
     if (SlimefunItem.getByItem(e.getInventory().getContents()[0]) != null) {
       e.setCancelled(true);
       Messages.local.sendTranslation((Player) e.getWhoClicked(), "anvil.not-working", true);
     }
   }
 }
Пример #12
0
  @EventHandler
  public void onInventoryClick(InventoryClickEvent event) {
    if (event.getInventory().getName() == "Choose a metal") {
      if (event.getRawSlot() <= 8) {
        event.getWhoClicked().getInventory().addItem(new ItemStack(event.getCurrentItem()));

        event.getWhoClicked().closeInventory();
        event.setCancelled(true);
      }
      event.setCancelled(true);
    }
  }
Пример #13
0
 @EventHandler(ignoreCancelled = true)
 public void onFurnaceInsert(final InventoryClickEvent event) {
   if (event.getInventory().getType() != InventoryType.FURNACE) {
     return;
   }
   if (event.getRawSlot() == 0 && event.getCursor().getType() != Material.AIR) {
     if (!validateSmeltingIngredient(event.getCursor())) {
       event.setCancelled(true);
     }
   } else if (event.getRawSlot() >= event.getView().getTopInventory().getSize()) {
     if (event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) {
       if (!validateSmeltingIngredient(event.getCurrentItem())
           && !STBUtil.isFuel(event.getCurrentItem().getType())) {
         event.setCancelled(true);
         int newSlot = findNewSlot(event);
         if (newSlot >= 0) {
           event.getWhoClicked().getInventory().setItem(newSlot, event.getCurrentItem());
           event.setCurrentItem(null);
         }
       }
     }
   } else if (event.getRawSlot() == 2
       && SensibleToolbox.getItemRegistry().isSTBItem(event.getCurrentItem())) {
     // work around CB bug where shift-clicking custom items out of furnace seems
     // to cause a de-sync, leaving phantom items in the furnace
     Bukkit.getScheduler()
         .runTask(
             plugin,
             new Runnable() {
               @Override
               public void run() {
                 STBUtil.forceInventoryRefresh(event.getInventory());
               }
             });
   }
 }
Пример #14
0
 @SuppressWarnings("deprecation")
 @EventHandler(priority = EventPriority.LOWEST)
 public void onFurnaceInsert(InventoryClickEvent e) {
   if (e.getInventory().getType() == InventoryType.FURNACE
       && e.getCursor() != null
       && (e.getRawSlot() == 0 || e.getSlot() == 1)) {
     if (!e.isShiftClick()) {
       ItemStack item = e.getCurrentItem();
       e.setCurrentItem(e.getCursor());
       e.setCursor(item);
       e.setCancelled(true);
       PlayerInventory.update((Player) e.getWhoClicked());
     }
   }
 }
Пример #15
0
  @EventHandler
  public void handleClick(InventoryClickEvent event) {
    if (event.getInventory().getName().equals(name)) {
      event.setCancelled(true);

      int slot = event.getRawSlot();

      if (slot >= 0 && slot < size && items[slot] != null) {
        GUIClickEvent e = new GUIClickEvent(slot, (Player) event.getWhoClicked(), spawner);
        Bukkit.getPluginManager().callEvent(e);

        if (e.willClose()) {
          event.getWhoClicked().getOpenInventory().close();
        }
      }
    }
  }
Пример #16
0
  @Override
  public void clicked(InventoryClickEvent event) {
    int slot = event.getRawSlot();
    event.setCancelled(true);
    if (event.getSlotType() == InventoryType.SlotType.CONTAINER) {
      target = players.get(slot);
      Player player = target != null ? target.get() : null;
      if (player != null) {
        Mage mage = actionContext.getMage();
        mage.deactivateGUI();
        actionContext.setTargetEntity(player);
        actionContext.setTargetLocation(player.getLocation());
        actionContext.playEffects("player_selected");
      }

      players.clear();
      active = false;
    }
  }
Пример #17
0
  @EventHandler(priority = EventPriority.LOWEST)
  public void onMenuItemClicked(InventoryClickEvent event) {
    Inventory inventory = event.getInventory();

    if (inventory.getHolder() instanceof InventoryMenu) {
      InventoryMenu menu = (InventoryMenu) inventory.getHolder();

      if (event.getWhoClicked() instanceof Player) {
        Player player = (Player) event.getWhoClicked();
        int index = event.getRawSlot();

        if (index >= 0 && index < inventory.getSize()) {
          menu.selectItem(player, index, event.isRightClick(), event.isShiftClick());
        }
      }

      event.setCancelled(true);
    }
  }
Пример #18
0
 @EventHandler(ignoreCancelled = true)
 public void onAdminMenuClick(InventoryClickEvent event) {
   Inventory inv = event.getInventory();
   String name = inv.getTitle();
   if (name.equals("§4Admin Menu")) {
     event.setCancelled(true);
     int slot = event.getRawSlot();
     if (slot < 54) {
       String option = getDisplay(inv, slot);
       if (slot == 53 && option.equals("Player Preferences")) {
         final Player p = (Player) event.getWhoClicked();
         // close this gui and load the Player Prefs Menu
         plugin
             .getServer()
             .getScheduler()
             .scheduleSyncDelayedTask(
                 plugin,
                 new Runnable() {
                   @Override
                   public void run() {
                     Inventory ppm =
                         plugin.getServer().createInventory(p, 18, "§4Player Prefs Menu");
                     ppm.setContents(
                         new TARDISPrefsMenuInventory(plugin, p.getUniqueId()).getMenu());
                     p.openInventory(ppm);
                   }
                 },
                 1L);
         return;
       }
       if (!option.isEmpty()) {
         boolean bool = plugin.getConfig().getBoolean(option);
         plugin.getConfig().set(option, !bool);
         String lore = (bool) ? "false" : "true";
         setLore(inv, slot, lore);
         plugin.saveConfig();
       }
     }
   }
 }
Пример #19
0
 @Override
 public void onClick(Player player, InventoryClickEvent event) {
   if (event.getCurrentItem() != null && !event.getCurrentItem().getType().equals(Material.AIR)) {
     if (event.getRawSlot() <= event.getSlot()) {
       int slot = event.getSlot();
       PlayerShopOffer offer = shop.getOffers().get(slot);
       if (offer != null) {
         if (event.isLeftClick()) {
           if (player.getName().equalsIgnoreCase(shop.getOwnerName())) {
             handleOfferEdit(player, event, offer);
           } else {
             handleTrade(player, event, offer);
           }
         } else if (event.isRightClick()) {
           if (getSession().getPermissionsProvider().has(player, ASPermissionKey.MANAGER)) {
             handleOfferEdit(player, event, offer);
           }
         }
       }
     }
   }
 }
Пример #20
0
  @ClickHandler(
      status = {tNpcStatus.SELL},
      inventory = InventoryType.TRADER)
  public void sellItems(InventoryClickEvent e) {
    e.setCancelled(true);
    // check permission
    if (!perms.has(player, "dtl.trader.sell")) return;

    int slot = e.getSlot();
    if (stock.isUiSlot(slot)) return;

    if (e.isLeftClick()) {
      if (selectAndCheckItem(slot)) {
        if (getSelectedItem().hasMultipleAmounts()) {
          // send message
          locale.sendMessage(player, "trader-stock-toggled", "stock", "#stock-amounts");

          // change status
          status = tNpcStatus.SELL_AMOUNTS;
          stock.setAmountsInventory(inventory, status, getSelectedItem());
        } else if (handleClick(e.getRawSlot())) {
          if (!inventoryHasPlace()) {
            // send message
            locale.sendMessage(player, "trader-transaction-failed-inventory");
          } else if (!sellTransaction()) {
            // send message
            locale.sendMessage(player, "trader-transaction-failed-player-money");
          } else {
            addToInventory();

            // send message
            locale.sendMessage(
                player,
                "trader-transaction-success",
                "trader",
                getNPC().getName(),
                "player",
                player.getName(),
                "action",
                "#bought",
                "item",
                getSelectedItem().getName(),
                "amount",
                String.valueOf(getSelectedItem().getAmount()),
                "price",
                String.valueOf(getSelectedItem().getPrice()));

            // update inventory - lore
            updatePlayerInventory();
          }
        } else {
          // informations about the item some1 wants to buy
          locale.sendMessage(
              player,
              "trader-transaction-item",
              "item",
              getSelectedItem().getName(),
              "amount",
              String.valueOf(getSelectedItem().getAmount()),
              "price",
              String.valueOf(getSelectedItem().getPrice()));
        }
      }
    } else {
      if (selectAndCheckItem(slot)) {
        if (handleClick(e.getRawSlot())) {
          if (!inventoryHasPlace()) {
            // send message
            locale.sendMessage(player, "trader-transaction-failed-inventory");
          } else if (!sellTransaction()) {
            // send message
            locale.sendMessage(player, "trader-transaction-failed-player-money");
          } else {
            addToInventory();

            // send message
            locale.sendMessage(
                player,
                "trader-transaction-success",
                "trader",
                getNPC().getName(),
                "player",
                player.getName(),
                "action",
                "#bought",
                "item",
                getSelectedItem().getName(),
                "amount",
                String.valueOf(getSelectedItem().getAmount()),
                "price",
                String.valueOf(getSelectedItem().getPrice()));

            // update inventory - lore
            updatePlayerInventory();
          }
        } else {
          // informations about the item some1 wants to buy
          locale.sendMessage(
              player,
              "trader-transaction-item",
              "item",
              getSelectedItem().getName(),
              "amount",
              String.valueOf(getSelectedItem().getAmount()),
              "price",
              String.valueOf(getSelectedItem().getPrice()));
        }
      }
    }
  }
Пример #21
0
 public static boolean isBottomInventory(InventoryClickEvent event) {
   return isBottomInventory(event.getRawSlot(), event.getInventory());
 }
Пример #22
0
 public static boolean isOutside(InventoryClickEvent event) {
   return isOutside(event.getRawSlot());
 }
  @EventHandler(ignoreCancelled = true)
  void onInventoryClick(InventoryClickEvent event) {
    if (event.getInventory().getHolder() instanceof CChunkLoader
        && event.getWhoClicked() instanceof Player) {
      Player player = (Player) event.getWhoClicked();

      event.setCancelled(true);
      CChunkLoader chunkLoader = (CChunkLoader) event.getInventory().getHolder();
      if (chunkLoader == null) {
        return;
      }

      if (chunkLoader.isAdminChunkLoader()) {
        if (!player.hasPermission("betterchunkloader.adminloader")) {
          player.sendMessage(Messages.get("PermissionDenied"));
          return;
        }
      } else {
        if (!player.getUniqueId().equals(chunkLoader.getOwner())
            && !player.hasPermission("betterchunkloader.edit")) {
          player.sendMessage(Messages.get("CantEditOthersChunkLoaders"));
          return;
        }
      }

      byte pos = (byte) event.getRawSlot();
      if (chunkLoader.getRange() != -1) {
        if (pos == 0) {
          // remove the chunk loader
          DataStoreManager.getDataStore().removeChunkLoader(chunkLoader);
          closeInventory(player);
        } else if (pos > 1 && pos < 7) {
          // change range
          pos -= 2;

          // if higher range, check if the player has enough free chunks
          if (!chunkLoader.isAdminChunkLoader()
              && !player.hasPermission("betterchunkloader.unlimitedchunks")) {
            if (pos > chunkLoader.getRange()) {
              int needed = ((1 + (pos * 2)) * (1 + (pos * 2))) - chunkLoader.size();
              int available;
              if (chunkLoader.isAlwaysOn()) {
                available =
                    DataStoreManager.getDataStore()
                        .getAlwaysOnFreeChunksAmount(chunkLoader.getOwner());
              } else {
                available =
                    DataStoreManager.getDataStore()
                        .getOnlineOnlyFreeChunksAmount(chunkLoader.getOwner());
              }

              if (needed > available) {
                player.sendMessage(
                    Messages.get("NotEnoughChunks")
                        .replace("[needed]", needed + "")
                        .replace("[available]", available + ""));
                closeInventory(player);
                return;
              }
            }
          }

          BetterChunkLoader.instance()
              .getLogger()
              .info(
                  player.getName()
                      + " edited "
                      + chunkLoader.getOwnerName()
                      + "'s chunk loader at "
                      + chunkLoader.getLocationString()
                      + " range from "
                      + chunkLoader.getRange()
                      + " to "
                      + pos);
          DataStoreManager.getDataStore().changeChunkLoaderRange(chunkLoader, pos);
          player.sendMessage(Messages.get("ChunkLoaderUpdated"));
          closeInventory(player);
        }
      } else if (pos > 1 && pos < 7) {
        pos -= 2;

        if (!chunkLoader.isAdminChunkLoader()
            && !player.hasPermission("betterchunkloader.unlimitedchunks")) {
          int needed = (1 + (pos * 2)) * (1 + (pos * 2));
          int available;
          if (chunkLoader.isAlwaysOn()) {
            available =
                DataStoreManager.getDataStore().getAlwaysOnFreeChunksAmount(chunkLoader.getOwner());
          } else {
            available =
                DataStoreManager.getDataStore()
                    .getOnlineOnlyFreeChunksAmount(chunkLoader.getOwner());
          }

          if (needed > available) {
            player.sendMessage(
                Messages.get("NotEnoughChunks")
                    .replace("[needed]", needed + "")
                    .replace("[available]", available + ""));
            closeInventory(player);
            return;
          }
        }

        chunkLoader.setRange(pos);
        chunkLoader.setCreationDate(new Date());
        BetterChunkLoader.instance()
            .getLogger()
            .info(
                player.getName()
                    + " made a new "
                    + (chunkLoader.isAdminChunkLoader() ? "admin " : "")
                    + "chunk loader at "
                    + chunkLoader.getLocationString()
                    + " with range "
                    + pos);
        DataStoreManager.getDataStore().addChunkLoader(chunkLoader);
        closeInventory(player);
        player.sendMessage(Messages.get("ChunkLoaderCreated"));
      }
    }
  }
Пример #24
0
  // Handles player interaction with anvil while in or out of creative.
  @SuppressWarnings("deprecation")
  @EventHandler(priority = EventPriority.NORMAL)
  public void anvilFix(final InventoryClickEvent e) {
    if (!e.isCancelled()) {
      HumanEntity ent = e.getWhoClicked();

      // Anvil used with survival
      if (ent instanceof Player) {
        final Player player = (Player) ent;
        Inventory inv = e.getInventory();

        // Anvil used with creative:
        if (player.getGameMode() == GameMode.CREATIVE) {
          if (inv instanceof AnvilInventory) {
            AnvilInventory anvil = (AnvilInventory) inv;
            InventoryView view = e.getView();
            int rawSlot = e.getRawSlot();
            if (rawSlot == view.convertSlot(rawSlot)) {
              if (rawSlot == 2) {
                ItemStack[] items = anvil.getContents();
                ItemStack item1 = items[0];
                ItemStack item2 = items[1];
                if (item1 != null && item2 != null) {
                  int id1 = item1.getTypeId();
                  int id2 = item2.getTypeId();
                  if (id1 != 0 && id2 != 0) {
                    ItemStack item3 = e.getCurrentItem();
                    if (item3 != null) {
                      ItemMeta meta = item3.getItemMeta();
                      if (meta != null) {
                        // Player has to have 60 or more levels to use the creative combine.
                        if (player.getLevel() >= 60) {
                          player.setLevel(player.getLevel() - 60);
                          player.sendMessage(ChatColor.GREEN + "Repair/Combine Successful!");
                          Bukkit.getServer()
                              .getScheduler()
                              .scheduleSyncDelayedTask(
                                  mobfighter,
                                  new Runnable() {
                                    public void run() {
                                      // Bypass being set to survival after using anvil if the
                                      // player has creative immunity.
                                      if (mobfighter
                                          .getConfig()
                                          .getList("Creative Immunity")
                                          .contains(player.getDisplayName())) return;
                                      // Sets the player back to survival once the anvil is used.
                                      e.getWhoClicked().getOpenInventory().close();
                                      player.setGameMode(GameMode.SURVIVAL);
                                    }
                                  },
                                  20 * 2);
                        } // End of creative combine.
                      } // Didn't have enough levels to combine/finishing.
                    } // Item 3 was/wasn't null.
                  } // Item 1 & 2 id's were/weren't null.
                } // Item 1 & 2 was/wasn't null.
              } // End of (rawSlot == 2)
            } // End of convert view
          } // End of anvil inventory
          else {
            // Bypass having the player's inventory closed if they have creative immunity.
            if (mobfighter
                .getConfig()
                .getList("Creative Immunity")
                .contains(player.getDisplayName())) e.setCancelled(false);
            // Closes the player's inventory after the anvil is used.
            else {
              e.setCancelled(true);
              player.closeInventory();
            }
          }
        } // End of anvil with creative
      } // End of anvil with survival
    } // End of !isCancelled
  } // End of anvilFix
Пример #25
0
  @EventHandler(priority = EventPriority.HIGHEST)
  public void inventoryMenu(final InventoryClickEvent event) {

    // -------Armor wear handling--------
    if (event.getSlotType() == SlotType.ARMOR && event.getClick() != ClickType.DOUBLE_CLICK) {
      CEventHandler.handleArmor(
          (Player) event.getWhoClicked(), event.getCurrentItem(), true, event);
      CEventHandler.handleArmor((Player) event.getWhoClicked(), event.getCursor(), false, event);
      if (event.getCursor() == null)
        CEventHandler.handleArmor(
            (Player) event.getWhoClicked(), event.getCurrentItem(), false, event);

    } else if (event.getClick() == ClickType.SHIFT_LEFT) {
      ItemStack current = event.getCurrentItem();
      String typeS = current.getType().toString();
      PlayerInventory inv = event.getWhoClicked().getInventory();
      if ((typeS.endsWith("HELMET") && inv.getHelmet() == null)
          || (typeS.endsWith("CHESTPLATE") && inv.getChestplate() == null)
          || (typeS.endsWith("LEGGINGS") && inv.getLeggings() == null)
          || (typeS.endsWith("BOOTS") && inv.getBoots() == null))
        CEventHandler.handleArmor(
            (Player) event.getWhoClicked(), event.getCurrentItem(), false, event);
    }
    // ---------------------------------

    if (event.getCurrentItem() == null
        || event.getCurrentItem().getType() == Material.AIR
        || event.getRawSlot() < -1) {
      return;
    }
    if (event.getView().getTopInventory().getTitle().startsWith("CE")) {
      Inventory topInv = event.getView().getTopInventory();
      final Player p = (Player) event.getWhoClicked();
      ItemStack clickedItem = event.getCurrentItem();
      event.setResult(Result.ALLOW);

      event.setCancelled(true);

      // This is the back-button, located in the very last spot of each inventory
      if ((event.getRawSlot() == topInv.getSize() - 1)
          && event.getCurrentItem().getType() != Material.AIR) {
        p.closeInventory();
        p.openInventory(Tools.getPreviousInventory(topInv.getTitle()));
        return;
      }

      if (event.getRawSlot() < topInv.getSize()) {

        // Opens the clicked Enchantments inventory and loads the permissions if needed
        if (topInv.getTitle().equals(Tools.prefix + "Enchantments")) {
          p.closeInventory();
          p.openInventory(Tools.getEnchantmentMenu(p, clickedItem.getItemMeta().getDisplayName()));
          return;
        }

        // Opens the item inventory and loads the permissions if needed
        if (topInv.getTitle().equals(Tools.prefix + "Main Menu") && event.getRawSlot() == 4) {
          p.closeInventory();
          p.openInventory(Tools.getItemMenu(p));
          return;
        }

        // These are the specific menus, clicking one of them will lead to the enchanting menu,
        // which needs to be 'notified' of the enchantment to give and it's cost
        if (topInv.getTitle().equals(Tools.prefix + "Global")
            || topInv.getTitle().equals(Tools.prefix + "Bow")
            || topInv.getTitle().equals(Tools.prefix + "Armor")
            || topInv.getTitle().equals(Tools.prefix + "Helmet")
            || topInv.getTitle().equals(Tools.prefix + "Boots")
            || topInv.getTitle().equals(Tools.prefix + "Tool"))
          if (p.isOp()
              || Tools.checkPermission(
                  Tools.getEnchantmentByDisplayname(clickedItem.getItemMeta().getDisplayName()),
                  p)) {
            Inventory enchantingMenu = Main.CEEnchantingMenu;
            enchantingMenu.setItem(0, clickedItem);
            p.closeInventory();
            p.openInventory(enchantingMenu);
            return;
          } else {
            p.sendMessage(
                ChatColor.RED + "[CE] You do not have permission to buy this Enchantment.");
            return;
          }

        // This opens the Item Creation Menu
        if (topInv.getTitle().equals(Tools.prefix + "Items"))
          if (p.isOp()
              || Tools.checkPermission(
                  Tools.getItemByDisplayname(clickedItem.getItemMeta().getDisplayName()), p)) {

            Inventory approveMenu = Main.CEApproveMenu;
            approveMenu.setItem(0, clickedItem);
            p.closeInventory();
            p.openInventory(approveMenu);
            return;
          } else {
            p.sendMessage(ChatColor.RED + "[CE] You do not have permission to buy this Item.");
            return;
          }
      }

      if (topInv.getTitle().equals(Tools.prefix + "Enchanting")
          || topInv.getTitle().equals(Tools.prefix + "Item Creation")) {
        double cost = 0;
        ItemStack item = clickedItem;
        ItemMeta im = item.getItemMeta();
        String type = "";
        String successString = "";
        Boolean itemSet = false; // TODO: Solve this by adding item-types
        // Swimsuit swimsuit = (Swimsuit) Main.items.get(9);

        if (topInv.getTitle().equals(Tools.prefix + "Enchanting")) {
          if (event.getRawSlot() > topInv.getSize() && event.isLeftClick()) {
            CEnchantment ce =
                Tools.getEnchantmentByDisplayname(
                    topInv.getContents()[0].getItemMeta().getDisplayName());
            cost = ce.getCost();
            type = "enchantment " + ce.getDisplayName();
            if (!ce.getApplication().equals(Application.GLOBAL)
                && !Tools.isApplicationCorrect(ce.getApplication(), clickedItem.getType())) {
              String appS = ce.getApplication().toString().toLowerCase();
              p.sendMessage(
                  ChatColor.RED
                      + "[CE] This enchantment can only be applied to "
                      + ChatColor.GRAY
                      + (appS.endsWith("s") ? appS : appS + "s")
                      + ChatColor.RED
                      + ".");
              return;
            }
            List<String> lore = new ArrayList<String>();
            if (clickedItem.getItemMeta().hasLore()) {
              lore = clickedItem.getItemMeta().getLore();
              int number = 0;
              for (String s : lore) {
                CEnchantment c = Tools.getEnchantmentByDisplayname(s);
                if (c != null && c.originalName == ce.originalName) {
                  p.sendMessage(ChatColor.RED + "[CE] This item already has this enchantment!");
                  return;
                }
                if (c != null) number++;
              }
              if (Main.maxEnchants > 0 && number >= Main.maxEnchants) {
                p.sendMessage(
                    ChatColor.RED
                        + "[CE] This item has already reached the maximum of "
                        + ChatColor.GRAY
                        + Main.maxEnchants
                        + ChatColor.RED
                        + " enchantments.");
                return;
              }
            }

            lore.add(ce.getDisplayName());
            im.setLore(lore);
            item.setItemMeta(im);
          } else return;

        } else if (topInv.getTitle().equals(Tools.prefix + "Item Creation")) {
          item = topInv.getContents()[0];
          cost = Tools.getItemByDisplayname(item.getItemMeta().getDisplayName()).getCost();
          //					if(item.hasItemMeta() && item.getItemMeta().hasDisplayName() &&
          // item.getItemMeta().getDisplayName().equals(swimsuit.getDisplayName())) { //TODO: Always
          // keep the position of the Swimsuit updated
          //
          //
          //						itemSet = true;
          //
          //						int count = 0;
          //
          //						for(ItemStack i : event.getView().getBottomInventory())
          //							if(i == null || i.getType().equals(Material.AIR))
          //								count++;
          //
          //						if(count < 4) {
          //							p.sendMessage(ChatColor.RED + "[CE] Your Inventory is full!");
          //							return;
          //						}
          //
          //
          //					} else {

          if (event.getView().getBottomInventory().firstEmpty() < 0) {
            p.sendMessage(ChatColor.RED + "[CE] Your Inventory is full!");
            return;
          }

          //					}

          ItemMeta itemIm = item.getItemMeta();
          List<String> lore = itemIm.getLore();
          lore.remove(lore.size() - 1);
          itemIm.setLore(lore);
          item.setItemMeta(itemIm);
          type = "item " + itemIm.getDisplayName();
        }

        // TODO: Fix the cost for items
        //      rewrite the whole section to check which enchantment or item is selected

        successString =
            (ChatColor.GREEN + "[CE] You have created the " + type + ChatColor.GREEN + ".");

        if (!p.isOp() && cost != 0) {
          if (Main.econ.getBalance(p.getName()) >= cost) {
            EconomyResponse ecr = Main.econ.withdrawPlayer(p.getName(), cost);
            if (ecr.transactionSuccess())
              successString =
                  (ChatColor.GREEN
                      + "[CE] Purchased "
                      + type
                      + ChatColor.GREEN
                      + " for "
                      + cost
                      + " "
                      + ((cost == 1)
                          ? Main.econ.currencyNameSingular()
                          : Main.econ.currencyNamePlural()));
            else {
              Bukkit.getConsoleSender()
                  .sendMessage(ChatColor.RED + "[CE] An economy error has occured:");
              Bukkit.getConsoleSender().sendMessage(ChatColor.RED + ecr.errorMessage);
              p.closeInventory();
              return;
            }
          } else {
            p.sendMessage(ChatColor.RED + "[CE] You do not have enough money to buy this!");
            p.closeInventory();
            return;
          }
        }
        if (item != null) {
          if (!itemSet)
            if (type.startsWith("item") && event.getRawSlot() < topInv.getSize())
              p.setItemInHand(item);
            else p.getInventory().setItem(event.getSlot(), item);
          //					else {
          //						ItemStack cp = item.clone();
          //						ItemStack le = item.clone();
          //						ItemStack bo = item.clone();
          //
          //						String[] parts = swimsuit.parts;
          //
          //						cp.setType(Material.IRON_CHESTPLATE);
          //						le.setType(Material.IRON_LEGGINGS);
          //						bo.setType(Material.IRON_BOOTS);
          //
          //						im.setDisplayName(parts[1]);
          //						cp.setItemMeta(im);
          //						im.setDisplayName(parts[2]);
          //						le.setItemMeta(im);
          //						im.setDisplayName(parts[3]);
          //						bo.setItemMeta(im);
          //
          //						p.getInventory().addItem(item);
          //						p.getInventory().addItem(cp);
          //						p.getInventory().addItem(le);
          //						p.getInventory().addItem(bo);
          //
          //					}
        }
        p.closeInventory();
        p.sendMessage(successString);
        return;
      }

      if (event.getRawSlot() < topInv.getSize()) {

        p.closeInventory();
        try {
          p.openInventory(Tools.getNextInventory(clickedItem.getItemMeta().getDisplayName()));
        } catch (Exception e) {
          p.sendMessage(ChatColor.RED + "[CE] This feature is disabled.");
        }
      }
    }
  }
  @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
  public void onInventoryClick(InventoryClickEvent event) {

    // Inventory not related to the plugin: do nothing.
    if (!event
            .getInventory()
            .getName()
            .startsWith(
                ChatColor.translateAlternateColorCodes(
                    '&',
                    plugin.getPluginLang().getString("list-gui-title", "&5&lAchievements List")))
        || event.getRawSlot() < 0) {
      return;
    }

    // Prevent players from taking items out of the GUI.
    event.setCancelled(true);

    // Back button; display main GUI again.
    if (event.getCurrentItem().getType() == Material.PAPER) {
      plugin.getAchievementListCommand().executeCommand(event.getWhoClicked(), null, "list");
    }

    // GUI corresponding to the achievement listing of a given category. Do not let the player
    // interact with it.
    if (event.getInventory().getItem(0).getType() == Material.STAINED_CLAY) {
      return;
    }

    // Main GUI displaying all the categories. Do not let players interact with locked categories or
    // slots not
    // corresponding to a category item.
    if (event.getInventory().getItem(0).getType() != Material.STAINED_CLAY
        && (event.getCurrentItem().getType() == Material.BARRIER
            || event.getCurrentItem().getType() == Material.BEDROCK
            || version < 11 && event.getCurrentItem().getType() == Material.CARPET
            || event.getRawSlot()
                > NormalAchievements.values().length
                    + MultipleAchievements.values().length
                    - plugin.getDisabledCategorySet().size())) {
      return;
    }

    // Create GUI according to whether the player clicked on a normal achievements category or a
    // multiple
    // achievement category.
    if (event.getCurrentItem().getType() == Material.STONE
        || event.getCurrentItem().getType() == Material.SMOOTH_BRICK
        || event.getCurrentItem().getType() == Material.BONE
        || event.getCurrentItem().getType() == Material.WORKBENCH
        || event.getCurrentItem().getType() == Material.PAPER) {
      plugin
          .getAchievementListCommand()
          .createCategoryGUIMultiple(
              event.getCurrentItem().getType(), (Player) event.getWhoClicked());
    } else {
      plugin
          .getAchievementListCommand()
          .createCategoryGUINormal(
              event.getCurrentItem().getType(), (Player) event.getWhoClicked());
    }
  }
Пример #27
0
  @ClickHandler(
      status = {tNpcStatus.SELL, tNpcStatus.BUY},
      inventory = InventoryType.PLAYER)
  public void buyItems(InventoryClickEvent e) {
    e.setCancelled(true);
    // check permission
    if (!perms.has(player, "dtl.trader.buy")) return;

    clearSelection();
    int slot = e.getSlot();
    if (e.isLeftClick()) {
      if (selectAndCheckItem(e.getCurrentItem(), "buy")) {
        int scale = e.getCurrentItem().getAmount() / getSelectedItem().getAmount();
        if (scale == 0) return;

        if (handleClick(e.getRawSlot())) {
          if (!buyTransaction(scale)) {
            // send message
            locale.sendMessage(
                player,
                "trader-transaction-failed-trader-money",
                "npc",
                settings.getNPC().getName());
          } else {
            // remove the amount from inventory
            removeFromInventory(slot, scale);

            // send the transaction success message
            locale.sendMessage(
                player,
                "trader-transaction-success",
                "trader",
                getNPC().getName(),
                "player",
                player.getName(),
                "action",
                "#sold",
                "item",
                getSelectedItem().getName(),
                "amount",
                String.valueOf(getSelectedItem().getAmount() * scale),
                "price",
                String.valueOf(stock.parsePrice(getSelectedItem(), 0) * scale));

            // update the inventory lore
            updatePlayerInventory();
          }
        } else {
          // send the information message
          locale.sendMessage(
              player,
              "trader-transaction-item",
              "item",
              getSelectedItem().getName(),
              "amount",
              String.valueOf(getSelectedItem().getAmount()),
              "price",
              String.valueOf(stock.parsePrice(getSelectedItem(), 0)));
        }
      }
    } else {
      if (selectAndCheckItem(e.getCurrentItem(), "buy")) {
        int scale = e.getCurrentItem().getAmount() / getSelectedItem().getAmount();
        if (scale == 0) return;

        if (handleClick(e.getRawSlot())) {
          if (!buyTransaction()) {
            // send message
            locale.sendMessage(
                player,
                "trader-transaction-failed-trader-money",
                "npc",
                settings.getNPC().getName());
          } else {
            // remove the amount from inventory
            removeFromInventory(slot);

            // send the transaction success message
            locale.sendMessage(
                player,
                "trader-transaction-success",
                "trader",
                getNPC().getName(),
                "player",
                player.getName(),
                "action",
                "#sold",
                "item",
                getSelectedItem().getName(),
                "amount",
                String.valueOf(getSelectedItem().getAmount()),
                "price",
                String.valueOf(stock.parsePrice(getSelectedItem(), 0)));

            // update the inventory lore
            updatePlayerInventory();
          }
        } else {
          // send the information message
          locale.sendMessage(
              player,
              "trader-transaction-item",
              "item",
              getSelectedItem().getName(),
              "amount",
              String.valueOf(getSelectedItem().getAmount()),
              "price",
              String.valueOf(stock.parsePrice(getSelectedItem(), 0)));
        }
      }
    }
  }
Пример #28
0
    @EventHandler
    public void NextPageEvent(InventoryClickEvent event) {
      // Get next items when next page item is clicked
      if (event.getInventory().getTitle().equals("Auction House")) {
        if (event.getClick().equals(ClickType.SHIFT_LEFT)) {
          Plugin plugin = RPGMaker.getPlugin(RPGMaker.class);
          boolean flag = true;
          Inventory inv = null;

          if (event.getCurrentItem().equals(nextpage)) {
            // Get next page
            player.sendMessage("Getting next page");
            page++;
            ids.clear();
            inv = getInventory();
          } else if (event.getCurrentItem().equals(sortname)) {
            sortingType = 2;
            ids.clear();
            sortByName();
          } else if (event.getCurrentItem().equals(sortnew)) {
            sortingType = 0;
            ids.clear();
            inv = sortByNew();
          } else if (event.getCurrentItem().equals(sortold)) {
            sortingType = 1;
            ids.clear();
            inv = sortByOld();
          } else {
            flag = false;
            player.sendMessage("You are trying to buy something");
            // Real time updates? -> need to update every viewer of AH
            ItemStack item = event.getCurrentItem();
            if (!(item.getType().equals(Material.AIR))) {
              if (getCost(item) == 0) {
                event.setCancelled(true);
                return;
              }

              item = removeAuctionLore(item);
              int id = ids.get(event.getRawSlot());

              try {
                String Query = "delete from `auctionhouse` where `ID` = " + id + ";";
                database.Query = database.connection.prepareStatement(Query);
                database.Query.execute();
                player.getInventory().addItem(item);
                player.closeInventory(); // for now until I handle realtime updates
                // and economy
              } catch (SQLException e) {
                e.printStackTrace();
              }
            }
          }
          final Inventory savedInv = inv;
          final Inventory oldInv = event.getInventory();
          if (flag) {
            Bukkit.getServer()
                .getScheduler()
                .scheduleSyncDelayedTask(
                    plugin,
                    new Runnable() {
                      @Override
                      public void run() {
                        // player.closeInventory();
                        oldInv.setContents(savedInv.getContents());
                      }
                    },
                    1);
          }
        }
        event.setCancelled(true);
      }
    }
  @SuppressWarnings("deprecation")
  @EventHandler
  public void onInventoryClick(InventoryClickEvent event) {
    // controller.getLogger().info("CLICK: " + event.getAction() + ", " + event.getClick() + " on "
    // + event.getSlotType() + " in "+ event.getInventory().getType() + " slots: " + event.getSlot()
    // + ":" + event.getRawSlot());

    if (event.isCancelled()) return;
    if (!(event.getWhoClicked() instanceof Player)) return;

    Player player = (Player) event.getWhoClicked();
    Mage apiMage = controller.getMage(player);

    if (!(apiMage instanceof com.elmakers.mine.bukkit.magic.Mage)) return;
    final com.elmakers.mine.bukkit.magic.Mage mage = (com.elmakers.mine.bukkit.magic.Mage) apiMage;

    GUIAction gui = mage.getActiveGUI();
    if (gui != null) {
      gui.clicked(event);
      return;
    }

    // Check for temporary items and skill items
    InventoryAction action = event.getAction();
    InventoryType inventoryType = event.getInventory().getType();
    ItemStack clickedItem = event.getCurrentItem();

    boolean isDrop =
        event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP;
    boolean isSkill = clickedItem != null && Wand.isSkill(clickedItem);

    // Preventing putting skills in containers
    if (isSkill && inventoryType != InventoryType.CRAFTING) {
      if (!isDrop) {
        event.setCancelled(true);
      }
      return;
    }

    // Check for right-click-to-use
    if (isSkill && action == InventoryAction.PICKUP_HALF) {
      Spell spell = mage.getSpell(Wand.getSpell(clickedItem));
      if (spell != null) {
        spell.cast();
      }
      player.closeInventory();
      event.setCancelled(true);
      return;
    }

    if (clickedItem != null && NMSUtils.isTemporary(clickedItem)) {
      String message = NMSUtils.getTemporaryMessage(clickedItem);
      if (message != null && message.length() > 1) {
        mage.sendMessage(message);
      }
      ItemStack replacement = NMSUtils.getReplacement(clickedItem);
      event.setCurrentItem(replacement);
      event.setCancelled(true);
      return;
    }

    // Check for wearing spells
    ItemStack heldItem = event.getCursor();
    if (heldItem != null && event.getSlotType() == InventoryType.SlotType.ARMOR) {
      if (Wand.isSpell(heldItem)) {
        event.setCancelled(true);
        return;
      }
      if (Wand.isWand(clickedItem) || Wand.isWand(heldItem)) {
        controller.onArmorUpdated(mage);
      }
    }
    boolean isHotbar =
        event.getAction() == InventoryAction.HOTBAR_SWAP
            || event.getAction() == InventoryAction.HOTBAR_MOVE_AND_READD;
    if (isHotbar && event.getSlotType() == InventoryType.SlotType.ARMOR) {
      int slot = event.getHotbarButton();
      ItemStack item = mage.getPlayer().getInventory().getItem(slot);
      if (item != null && Wand.isSpell(item)) {
        event.setCancelled(true);
        return;
      }
      controller.onArmorUpdated(mage);
    }

    Wand activeWand = mage.getActiveWand();

    boolean isChest =
        inventoryType == InventoryType.CHEST
            || inventoryType == InventoryType.HOPPER
            || inventoryType == InventoryType.DISPENSER
            || inventoryType == InventoryType.DROPPER;
    boolean clickedWand = Wand.isWand(clickedItem);
    boolean isContainerSlot = event.getSlot() == event.getRawSlot();

    if (activeWand != null && activeWand.isInventoryOpen()) {
      // Kind of a hack to avoid hotbar items with 0 amounts disappearing :(
      Inventory inventory = player.getInventory();
      for (int i = 0; i < 8; i++) {
        ItemStack item = inventory.getItem(i);
        if (item != null && item.getAmount() == 0) {
          item.setAmount(1);
        }
      }

      // Don't allow the offhand slot to be messed with while the spell inventory is open
      if (event.getRawSlot() == 45) {
        event.setCancelled(true);
        return;
      }

      if (Wand.isSpell(clickedItem) && clickedItem.getAmount() != 1) {
        clickedItem.setAmount(1);
      }
      if (clickedWand) {
        event.setCancelled(true);
        if (dropChangesPages) {
          activeWand.cycleInventory();
        } else {
          activeWand.cycleHotbar(1);
        }
        return;
      }

      // So many ways to try and move the wand around, that we have to watch for!
      if (isHotbar && Wand.isWand(player.getInventory().getItem(event.getHotbarButton()))) {
        event.setCancelled(true);
        return;
      }

      // Can't wear spells
      if (event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY && clickedItem != null) {
        if (controller.isWearable(clickedItem)) {
          event.setCancelled(true);
          return;
        }
      }

      // Safety check for something that ought not to be possible
      // but perhaps happens with lag?
      if (Wand.isWand(event.getCursor())) {
        activeWand.closeInventory();
        event.setCursor(null);
        event.setCancelled(true);
        return;
      }
    } else if (activeWand != null) {
      // Check for changes that could have been made to the active wand
      Integer activeSlot = player.getInventory().getHeldItemSlot();
      if (activeSlot != null
          && (event.getSlot() == activeSlot
              || (event.getAction() == InventoryAction.HOTBAR_SWAP
                  && event.getHotbarButton() == activeSlot))) {
        mage.checkWand();
        activeWand = mage.getActiveWand();
      }
    } else if (clickedWand
        && Wand.Undroppable
        && !player.hasPermission("Magic.wand.override_drop")
        && isChest
        && !isContainerSlot) {
      Wand wand = new Wand(controller, clickedItem);
      if (wand.isUndroppable()) {
        event.setCancelled(true);
        return;
      }
    }

    // Check for armor changing
    if (event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY && clickedItem != null) {
      if (controller.isWearable(clickedItem)) {
        controller.onArmorUpdated(mage);
      }
    }

    // Check for dropping items out of a wand's inventory
    // or dropping undroppable wands
    if (isDrop) {
      if (clickedWand) {
        Wand wand = new Wand(controller, clickedItem);
        if (wand.isUndroppable()) {
          event.setCancelled(true);
          if (activeWand != null) {
            if (activeWand.getHotbarCount() > 1) {
              activeWand.cycleHotbar(1);
            } else {
              activeWand.closeInventory();
            }
          }
          return;
        }
      }
      if (activeWand != null && activeWand.isInventoryOpen()) {

        ItemStack droppedItem = clickedItem;

        if (!Wand.isSpell(droppedItem)) {
          mage.giveItem(droppedItem);
          event.setCurrentItem(null);
          event.setCancelled(true);
          return;
        }

        // This is a hack to deal with spells on cooldown disappearing,
        // Since the event handler doesn't match the zero-count itemstacks
        Integer slot = event.getSlot();
        int heldSlot = player.getInventory().getHeldItemSlot();
        Inventory hotbar = activeWand.getHotbar();
        if (hotbar != null
            && slot >= 0
            && slot <= hotbar.getSize()
            && slot != heldSlot
            && activeWand.getMode() == WandMode.INVENTORY) {
          if (slot > heldSlot) slot--;
          if (slot < hotbar.getSize()) {
            droppedItem = hotbar.getItem(slot);
          } else {
            slot = null;
          }
        } else {
          slot = null;
        }

        if (!controller.isSpellDroppingEnabled()) {
          player.closeInventory();
          String spellName = Wand.getSpell(droppedItem);
          if (spellName != null && !activeWand.isManualQuickCastDisabled()) {
            Spell spell = mage.getSpell(spellName);
            if (spell != null) {
              activeWand.cast(spell);
              // Just in case a spell has levelled up... jeez!
              if (hotbar != null && slot != null) {
                droppedItem = hotbar.getItem(slot);
              }
            }
          }
          event.setCancelled(true);

          // This is needed to avoid spells on cooldown disappearing from the hotbar
          if (hotbar != null && slot != null && mage.getActiveGUI() == null) {
            player.getInventory().setItem(event.getSlot(), droppedItem);
            player.updateInventory();
          }

          return;
        }
        ItemStack newDrop = controller.removeItemFromWand(activeWand, droppedItem);

        if (newDrop != null) {
          Location location = player.getLocation();
          Item item = location.getWorld().dropItem(location, newDrop);
          item.setVelocity(location.getDirection().normalize());
        } else {
          event.setCancelled(true);
        }
      }
      return;
    }

    // Check for wand cycling with active inventory
    if (activeWand != null) {
      WandMode wandMode = activeWand.getMode();
      if ((wandMode == WandMode.INVENTORY && inventoryType == InventoryType.CRAFTING)
          || (wandMode == WandMode.CHEST && inventoryType == InventoryType.CHEST)) {
        if (activeWand.isInventoryOpen()) {
          if (event.getAction() == InventoryAction.NOTHING) {
            int direction = event.getClick() == ClickType.LEFT ? 1 : -1;
            activeWand.cycleInventory(direction);
            event.setCancelled(true);
            return;
          }

          if (event.getSlotType() == InventoryType.SlotType.ARMOR) {
            event.setCancelled(true);
            return;
          }

          // Chest mode falls back to selection from here.
          if (event.getAction() == InventoryAction.PICKUP_HALF || wandMode == WandMode.CHEST) {
            controller.onPlayerActivateIcon(mage, activeWand, clickedItem);
            player.closeInventory();
            event.setCancelled(true);
          }
        }
      }
    }
  }