private void sendItemWidgetClicked(final int mouseX, final int mouseY, final int mouseButton) {
    for (int index = 0; index < this.widgetCount; ++index) {
      WidgetAEItem currentWidget = this.itemWidgets.get(index);

      if (currentWidget.isMouseOverWidget(mouseX, mouseY)) {
        IAEItemStack widgetStack = currentWidget.getItemStack();

        if (widgetStack != null) {
          if (widgetStack.getStackSize() == 0) {
            if (widgetStack.isCraftable()) {
              // new PacketChiselingTerminalServer().createRequestAutoCraft( this.player,
              // widgetStack ).sendPacketToServer();
            }
          } else {
            boolean isShiftHeld =
                Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT);

            new PacketChiselingTerminalServer()
                .createRequestExtract(this.entityPlayer, widgetStack, mouseButton, isShiftHeld)
                .sendPacketToServer();
          }
        }

        return;
      }
    }
  }
 private void loadPattern(final ArcaneCraftingPattern pattern) {
   if ((pattern == null) || (!pattern.isPatternValid())) {
     return;
   }
   // Set the slots
   for (int index = 0; index < this.craftingSlots.length; index++) {
     IAEItemStack ingStack = pattern.getInputs()[index];
     if (ingStack != null) {
       this.craftingSlots[index].putStack(ingStack.getItemStack());
     } else {
       this.craftingSlots[index].putStack(null);
     }
   }
 }
 private void writeItem(IAEItemStack slotItem, ByteBuf data) throws IOException {
   if (slotItem == null) {
     data.writeBoolean(false);
   } else {
     data.writeBoolean(true);
     slotItem.writeToPacket(data);
   }
 }
  private void updateMEWidgets() {
    int repoIndex = 0;

    for (int index = 0; index < this.widgetCount; ++index) {
      IAEItemStack stack = this.itemRepo.getReferenceItem(repoIndex++);

      if (stack != null) {
        if (stack.getStackSize() == 0) {
          index--;
          continue;
        }

        this.itemWidgets.get(index).setItemStack(stack);
      } else {
        this.itemWidgets.get(index).setItemStack(null);
      }
    }
  }
  public void onReceivePlayerHeld(IAEItemStack heldItemChange) {
    ItemStack itemStack = null;

    if (heldItemChange != null) {
      itemStack = heldItemChange.getItemStack();
    }

    this.entityPlayer.inventory.setItemStack(itemStack);
  }
        @Override
        public int compare(IAEItemStack o1, IAEItemStack o2) {
          // Logger.info("Comparing by EMC");
          int itememc1 = EMCHelper.getEmcValue(o1.getItemStack());
          BigInteger stack1 =
              BigInteger.valueOf(itememc1).multiply(BigInteger.valueOf(o1.getStackSize()));
          // Logger.info(o1.getItemStack().getDisplayName() +
          // stack1.toString());
          int stackemc1;
          if (stack1.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) >= 0) {
            // Logger.info("Value is bigger than Integer.MAX_VALUE");
            stackemc1 = Integer.MAX_VALUE;
            // Logger.info(String.valueOf(stackemc1));
          } else {
            stackemc1 = stack1.intValue();
          }
          int itememc2 = EMCHelper.getEmcValue(o2.getItemStack());
          BigInteger stack2 =
              BigInteger.valueOf(itememc2).multiply(BigInteger.valueOf(o2.getStackSize()));
          int stackemc2;
          if (stack2.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) >= 0) {
            stackemc2 = Integer.MAX_VALUE;
          } else {
            stackemc2 = stack2.intValue();
          }

          // Logger.info("FirstStack:" + String.valueOf(stackemc1));
          // Logger.info("SecondStack:" + String.valueOf(stackemc2));

          if (Direction == SortDir.ASCENDING) {
            // Logger.info(String.valueOf(compareInt(stackemc2,
            // stackemc1)));
            // return compareInt(stackemc2, stackemc1);
            return this.secondarySort(compareInt(stackemc2, stackemc1), o1, o2);
          }
          // Logger.info(String.valueOf(compareInt(stackemc1, stackemc2)));
          // return compareInt(stackemc1, stackemc2);
          return this.secondarySort(compareInt(stackemc1, stackemc2), o2, o1);
        }
  public void craftOrGetItem(final PacketPatternSlot packetPatternSlot) {
    if (packetPatternSlot.slotItem != null && this.getCellInventory() != null) {
      final IAEItemStack out = packetPatternSlot.slotItem.copy();
      InventoryAdaptor inv = new AdaptorPlayerHand(this.getPlayerInv().player);
      final InventoryAdaptor playerInv =
          InventoryAdaptor.getAdaptor(this.getPlayerInv().player, ForgeDirection.UNKNOWN);

      if (packetPatternSlot.shift) {
        inv = playerInv;
      }

      if (inv.simulateAdd(out.getItemStack()) != null) {
        return;
      }

      final IAEItemStack extracted =
          Platform.poweredExtraction(
              this.getPowerSource(), this.getCellInventory(), out, this.getActionSource());
      final EntityPlayer p = this.getPlayerInv().player;

      if (extracted != null) {
        inv.addItems(extracted.getItemStack());
        if (p instanceof EntityPlayerMP) {
          this.updateHeld((EntityPlayerMP) p);
        }
        this.detectAndSendChanges();
        return;
      }

      final InventoryCrafting ic = new InventoryCrafting(new ContainerNull(), 3, 3);
      final InventoryCrafting real = new InventoryCrafting(new ContainerNull(), 3, 3);

      for (int x = 0; x < 9; x++) {
        ic.setInventorySlotContents(
            x,
            packetPatternSlot.pattern[x] == null
                ? null
                : packetPatternSlot.pattern[x].getItemStack());
      }

      final IRecipe r = Platform.findMatchingRecipe(ic, p.worldObj);

      if (r == null) {
        return;
      }

      final IMEMonitor<IAEItemStack> storage = this.getPatternTerminal().getItemInventory();
      final IItemList<IAEItemStack> all = storage.getStorageList();

      final ItemStack is = r.getCraftingResult(ic);

      for (int x = 0; x < ic.getSizeInventory(); x++) {
        if (ic.getStackInSlot(x) != null) {
          final ItemStack pulled =
              Platform.extractItemsByRecipe(
                  this.getPowerSource(),
                  this.getActionSource(),
                  storage,
                  p.worldObj,
                  r,
                  is,
                  ic,
                  ic.getStackInSlot(x),
                  x,
                  all,
                  Actionable.MODULATE,
                  ItemViewCell.createFilter(this.getViewCells()));
          real.setInventorySlotContents(x, pulled);
        }
      }

      final IRecipe rr = Platform.findMatchingRecipe(real, p.worldObj);

      if (rr == r && Platform.isSameItemPrecise(rr.getCraftingResult(real), is)) {
        final SlotCrafting sc = new SlotCrafting(p, real, this.cOut, 0, 0, 0);
        sc.onPickupFromSlot(p, is);

        for (int x = 0; x < real.getSizeInventory(); x++) {
          final ItemStack failed = playerInv.addItems(real.getStackInSlot(x));

          if (failed != null) {
            p.dropPlayerItemWithRandomChoice(failed, false);
          }
        }

        inv.addItems(is);
        if (p instanceof EntityPlayerMP) {
          this.updateHeld((EntityPlayerMP) p);
        }
        this.detectAndSendChanges();
      } else {
        for (int x = 0; x < real.getSizeInventory(); x++) {
          final ItemStack failed = real.getStackInSlot(x);
          if (failed != null) {
            this.getCellInventory()
                .injectItems(
                    AEItemStack.create(failed),
                    Actionable.MODULATE,
                    new MachineSource(this.getPatternTerminal()));
          }
        }
      }
    }
  }
  @Override
  protected void handleMouseClick(
      final Slot slot, final int slotIdx, final int ctrlDown, final int key) {
    final EntityPlayer player = Minecraft.getMinecraft().thePlayer;

    if (slot instanceof SlotFake) {
      final InventoryAction action =
          ctrlDown == 1
              ? InventoryAction.SPLIT_OR_PLACE_SINGLE
              : InventoryAction.PICKUP_OR_SET_DOWN;

      if (this.drag_click.size() > 1) {
        return;
      }

      final PacketInventoryAction p = new PacketInventoryAction(action, slotIdx, 0);
      NetworkHandler.instance.sendToServer(p);

      return;
    }

    if (slot instanceof SlotPatternTerm) {
      if (key == 6) {
        return; // prevent weird double clicks..
      }

      try {
        NetworkHandler.instance.sendToServer(((SlotPatternTerm) slot).getRequest(key == 1));
      } catch (final IOException e) {
        AELog.debug(e);
      }
    } else if (slot instanceof SlotCraftingTerm) {
      if (key == 6) {
        return; // prevent weird double clicks..
      }

      InventoryAction action = null;
      if (key == 1) {
        action = InventoryAction.CRAFT_SHIFT;
      } else {
        action = ctrlDown == 1 ? InventoryAction.CRAFT_STACK : InventoryAction.CRAFT_ITEM;
      }

      final PacketInventoryAction p = new PacketInventoryAction(action, slotIdx, 0);
      NetworkHandler.instance.sendToServer(p);

      return;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
      if (this.enableSpaceClicking()) {
        IAEItemStack stack = null;
        if (slot instanceof SlotME) {
          stack = ((SlotME) slot).getAEStack();
        }

        int slotNum = this.getInventorySlots().size();

        if (!(slot instanceof SlotME) && slot != null) {
          slotNum = slot.slotNumber;
        }

        ((AEBaseContainer) this.inventorySlots).setTargetStack(stack);
        final PacketInventoryAction p =
            new PacketInventoryAction(InventoryAction.MOVE_REGION, slotNum, 0);
        NetworkHandler.instance.sendToServer(p);
        return;
      }
    }

    if (slot instanceof SlotDisconnected) {
      InventoryAction action = null;

      switch (key) {
        case 0: // pickup / set-down.
          action =
              ctrlDown == 1
                  ? InventoryAction.SPLIT_OR_PLACE_SINGLE
                  : InventoryAction.PICKUP_OR_SET_DOWN;
          break;
        case 1:
          action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK;
          break;

        case 3: // creative dupe:
          if (player.capabilities.isCreativeMode) {
            action = InventoryAction.CREATIVE_DUPLICATE;
          }

          break;

        default:
        case 4: // drop item:
        case 6:
      }

      if (action != null) {
        final PacketInventoryAction p =
            new PacketInventoryAction(
                action, slot.getSlotIndex(), ((SlotDisconnected) slot).getSlot().getId());
        NetworkHandler.instance.sendToServer(p);
      }

      return;
    }

    if (slot instanceof SlotME) {
      InventoryAction action = null;
      IAEItemStack stack = null;

      switch (key) {
        case 0: // pickup / set-down.
          action =
              ctrlDown == 1
                  ? InventoryAction.SPLIT_OR_PLACE_SINGLE
                  : InventoryAction.PICKUP_OR_SET_DOWN;
          stack = ((SlotME) slot).getAEStack();

          if (stack != null
              && action == InventoryAction.PICKUP_OR_SET_DOWN
              && stack.getStackSize() == 0
              && player.inventory.getItemStack() == null) {
            action = InventoryAction.AUTO_CRAFT;
          }

          break;
        case 1:
          action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK;
          stack = ((SlotME) slot).getAEStack();
          break;

        case 3: // creative dupe:
          stack = ((SlotME) slot).getAEStack();
          if (stack != null && stack.isCraftable()) {
            action = InventoryAction.AUTO_CRAFT;
          } else if (player.capabilities.isCreativeMode) {
            final IAEItemStack slotItem = ((SlotME) slot).getAEStack();
            if (slotItem != null) {
              action = InventoryAction.CREATIVE_DUPLICATE;
            }
          }
          break;

        default:
        case 4: // drop item:
        case 6:
      }

      if (action != null) {
        ((AEBaseContainer) this.inventorySlots).setTargetStack(stack);
        final PacketInventoryAction p =
            new PacketInventoryAction(action, this.getInventorySlots().size(), 0);
        NetworkHandler.instance.sendToServer(p);
      }

      return;
    }

    if (!this.disableShiftClick && isShiftKeyDown()) {
      this.disableShiftClick = true;

      if (this.dbl_whichItem == null
          || this.bl_clicked != slot
          || this.dbl_clickTimer.elapsed(TimeUnit.MILLISECONDS) > 150) {
        // some simple double click logic.
        this.bl_clicked = slot;
        this.dbl_clickTimer = Stopwatch.createStarted();
        if (slot != null) {
          this.dbl_whichItem = slot.getHasStack() ? slot.getStack().copy() : null;
        } else {
          this.dbl_whichItem = null;
        }
      } else if (this.dbl_whichItem != null) {
        // a replica of the weird broken vanilla feature.

        final List<Slot> slots = this.getInventorySlots();
        for (final Slot inventorySlot : slots) {
          if (inventorySlot != null
              && inventorySlot.canTakeStack(this.mc.thePlayer)
              && inventorySlot.getHasStack()
              && inventorySlot.inventory == slot.inventory
              && Container.func_94527_a(inventorySlot, this.dbl_whichItem, true)) {
            this.handleMouseClick(inventorySlot, inventorySlot.slotNumber, ctrlDown, 1);
          }
        }
      }

      this.disableShiftClick = false;
    }

    super.handleMouseClick(slot, slotIdx, ctrlDown, key);
  }
  @Override
  public void detectAndSendChanges() {
    if (Platform.isServer()) {
      if (this.monitor != this.host.getItemInventory()) {
        this.isContainerValid = false;
      }

      for (final Settings set : this.serverCM.getSettings()) {
        final Enum<?> sideLocal = this.serverCM.getSetting(set);
        final Enum<?> sideRemote = this.clientCM.getSetting(set);

        if (sideLocal != sideRemote) {
          this.clientCM.putSetting(set, sideLocal);
          for (final Object crafter : this.crafters) {
            try {
              NetworkHandler.instance.sendTo(
                  new PacketValueConfig(set.name(), sideLocal.name()), (EntityPlayerMP) crafter);
            } catch (final IOException e) {
              AELog.error(e);
            }
          }
        }
      }

      if (!this.items.isEmpty()) {
        try {
          final IItemList<IAEItemStack> monitorCache = this.monitor.getStorageList();

          final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate();

          for (final IAEItemStack is : this.items) {
            final IAEItemStack send = monitorCache.findPrecise(is);
            if (send == null) {
              is.setStackSize(0);
              piu.appendItem(is);
            } else {
              piu.appendItem(send);
            }
          }

          if (!piu.isEmpty()) {
            this.items.resetStatus();

            for (final Object c : this.crafters) {
              if (c instanceof EntityPlayer) {
                NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c);
              }
            }
          }
        } catch (final IOException e) {
          AELog.error(e);
        }
      }

      this.updatePowerStatus();

      final boolean oldAccessible = this.canAccessViewCells;
      this.canAccessViewCells = this.hasAccess(SecurityPermissions.BUILD, false);
      if (this.canAccessViewCells != oldAccessible) {
        for (int y = 0; y < 5; y++) {
          if (this.cellView[y] != null) {
            this.cellView[y].allowEdit = this.canAccessViewCells;
          }
        }
      }

      super.detectAndSendChanges();
    }
  }
  @Override
  public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) {
    EntityPlayerMP pmp = (EntityPlayerMP) player;
    Container con = pmp.openContainer;

    if (con instanceof IContainerCraftingPacket) {
      IContainerCraftingPacket cct = (IContainerCraftingPacket) con;
      IGridNode node = cct.getNetworkNode();
      if (node != null) {
        IGrid grid = node.getGrid();
        if (grid == null) {
          return;
        }

        IStorageGrid inv = grid.getCache(IStorageGrid.class);
        IEnergyGrid energy = grid.getCache(IEnergyGrid.class);
        ISecurityGrid security = grid.getCache(ISecurityGrid.class);
        IInventory craftMatrix = cct.getInventoryByName("crafting");
        IInventory playerInventory = cct.getInventoryByName("player");

        Actionable realForFake = cct.useRealItems() ? Actionable.MODULATE : Actionable.SIMULATE;

        if (inv != null && this.recipe != null && security != null) {
          InventoryCrafting testInv = new InventoryCrafting(new ContainerNull(), 3, 3);
          for (int x = 0; x < 9; x++) {
            if (this.recipe[x] != null && this.recipe[x].length > 0) {
              testInv.setInventorySlotContents(x, this.recipe[x][0]);
            }
          }

          IRecipe r = Platform.findMatchingRecipe(testInv, pmp.worldObj);

          if (r != null && security.hasPermission(player, SecurityPermissions.EXTRACT)) {
            ItemStack is = r.getCraftingResult(testInv);

            if (is != null) {
              IMEMonitor<IAEItemStack> storage = inv.getItemInventory();
              IItemList all = storage.getStorageList();
              IPartitionList<IAEItemStack> filter = ItemViewCell.createFilter(cct.getViewCells());

              for (int x = 0; x < craftMatrix.getSizeInventory(); x++) {
                ItemStack patternItem = testInv.getStackInSlot(x);

                ItemStack currentItem = craftMatrix.getStackInSlot(x);
                if (currentItem != null) {
                  testInv.setInventorySlotContents(x, currentItem);
                  ItemStack newItemStack =
                      r.matches(testInv, pmp.worldObj) ? r.getCraftingResult(testInv) : null;
                  testInv.setInventorySlotContents(x, patternItem);

                  if (newItemStack == null || !Platform.isSameItemPrecise(newItemStack, is)) {
                    IAEItemStack in = AEItemStack.create(currentItem);
                    if (in != null) {
                      IAEItemStack out =
                          realForFake == Actionable.SIMULATE
                              ? null
                              : Platform.poweredInsert(energy, storage, in, cct.getSource());
                      if (out != null) {
                        craftMatrix.setInventorySlotContents(x, out.getItemStack());
                      } else {
                        craftMatrix.setInventorySlotContents(x, null);
                      }

                      currentItem = craftMatrix.getStackInSlot(x);
                    }
                  }
                }

                // True if we need to fetch an item for the recipe
                if (patternItem != null && currentItem == null) {
                  // Grab from network by recipe
                  ItemStack whichItem =
                      Platform.extractItemsByRecipe(
                          energy,
                          cct.getSource(),
                          storage,
                          player.worldObj,
                          r,
                          is,
                          testInv,
                          patternItem,
                          x,
                          all,
                          realForFake,
                          filter);

                  // If that doesn't get it, grab exact items from network (?)
                  // TODO see if this code is necessary
                  if (whichItem == null) {
                    for (int y = 0; y < this.recipe[x].length; y++) {
                      IAEItemStack request = AEItemStack.create(this.recipe[x][y]);
                      if (request != null) {
                        if (filter == null || filter.isListed(request)) {
                          request.setStackSize(1);
                          IAEItemStack out =
                              Platform.poweredExtraction(energy, storage, request, cct.getSource());
                          if (out != null) {
                            whichItem = out.getItemStack();
                            break;
                          }
                        }
                      }
                    }
                  }

                  // If that doesn't work, grab from the player's inventory
                  if (whichItem == null && playerInventory != null) {
                    whichItem = extractItemFromPlayerInventory(player, realForFake, patternItem);
                  }

                  craftMatrix.setInventorySlotContents(x, whichItem);
                }
              }
              con.onCraftMatrixChanged(craftMatrix);
            }
          }
        }
      }
    }
  }