AbstractContainerMenu .java

net.minecraft.world.inventory.AbstractContainerMenu (class): members: getRedstoneSignalFromBlockEntity, getRedstoneSignalFromContainer, addSlot, clicked.

net.minecraft.world.inventoryclass840 linescommon28.9 KB

API Surface (53)

void addInventoryHotbarSlots(final Container inventory, final int left, final int top)
void addInventoryExtendedSlots(final Container inventory, final int left, final int top)
void addStandardInventorySlots(final Container container, final int left, final int top)
boolean stillValid(final ContainerLevelAccess access, final Player player, final Block block)
MenuType<?> getType()
void checkContainerSize(final Container container, final int expected)
void checkContainerDataCount(final ContainerData data, final int expected)
boolean isValidSlotIndex(final int slotIndex)
Slot addSlot(final Slot slot)
DataSlot addDataSlot(final DataSlot dataSlot)
void addDataSlots(final ContainerData container)
void addSlotListener(final ContainerListener listener)
void setSynchronizer(final ContainerSynchronizer synchronizer)
void sendAllDataToRemote()
void removeSlotListener(final ContainerListener listener)
NonNullList<ItemStack> getItems()
void broadcastChanges()
void broadcastFullState()
void setRemoteSlot(final int slot, final ItemStack itemStack)
void setRemoteSlotUnsafe(final int slot, final HashedStack itemStack)
void setRemoteCarried(final HashedStack carriedItem)
boolean clickMenuButton(final Player player, final int buttonId)
Slot getSlot(final int index)
void setSelectedBundleItemIndex(final int slotIndex, final int selectedItemIndex)
void clicked(final int slotIndex, final int buttonNum, final ContainerInput containerInput, final Player player)
ItemStack get()
boolean set(final ItemStack itemStack)
boolean canTakeItemForPickAll(final ItemStack carried, final Slot target)
void removed(final Player player)
void clearContainer(final Player player, final Container container)
void slotsChanged(final Container container)
void setItem(final int slot, final int stateId, final ItemStack itemStack)
void initializeContents(final int stateId, final List<ItemStack> items, final ItemStack carried)
void setData(final int id, final int value)
boolean moveItemStackTo(final ItemStack itemStack, final int startSlot, final int endSlot, final boolean backwards)
int getQuickcraftType(final int mask)
int getQuickcraftHeader(final int mask)
int getQuickcraftMask(final int header, final int type)
boolean isValidQuickcraftType(final int type, final Player player)
void resetQuickCraft()
boolean canItemQuickReplace(final @Nullable Slot slot, final ItemStack itemStack, final boolean ignoreSize)
int getQuickCraftPlaceCount(final int quickCraftSlotsSize, final int quickCraftingType, final ItemStack itemStack)
boolean canDragTo(final Slot slot)
int getRedstoneSignalFromBlockEntity(final @Nullable BlockEntity blockEntity)
int getRedstoneSignalFromContainer(final @Nullable Container container)
void setCarried(final ItemStack carried)
ItemStack getCarried()
void suppressRemoteUpdates()
void resumeRemoteUpdates()
void transferState(final AbstractContainerMenu otherContainer)
OptionalInt findSlot(final Container inventory, final int slotIndex)
int getStateId()
int incrementStateId()

Fields & Constants (30)

LOGGER
SLOT_CLICKED_OUTSIDE
CONTAINER_CLICK_PRIMARY
CONTAINER_CLICK_SECONDARY
QUICKCRAFT_TYPE_CHARITABLE
QUICKCRAFT_TYPE_GREEDY
QUICKCRAFT_TYPE_CLONE
QUICKCRAFT_HEADER_START
QUICKCRAFT_HEADER_CONTINUE
QUICKCRAFT_HEADER_END
CARRIED_SLOT_SIZE
SLOTS_PER_ROW
SLOT_SIZE
lastSlots
slots
dataSlots
carried
remoteSlots
remoteDataSlots
remoteCarried
stateId
menuType
containerId
quickcraftType
quickcraftStatus
quickcraftSlots
containerListeners
synchronizer
suppressRemoteUpdates
clicked

String literals (13)

"Unable to construct this menu by type"
"Container size "
" is smaller than expected "
"Container data count "
"Container click"
"Click info"
"Menu Type"
"<no type>"
"Menu Class"
"Slot Count"
"Slot"
"Button"
"Not a container click button: "

Full Source

AbstractContainerMenu.java840 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.inventory;
2
3
import com.google.common.base.Suppliers;
4
import com.google.common.collect.HashBasedTable;
5
import com.google.common.collect.Lists;
6
import com.google.common.collect.Sets;
7
import com.google.common.collect.Table;
8
import com.mojang.logging.LogUtils;
9
import it.unimi.dsi.fastutil.ints.IntArrayList;
10
import it.unimi.dsi.fastutil.ints.IntList;
11
import java.util.ArrayList;
12
import java.util.List;
13
import java.util.Optional;
14
import java.util.OptionalInt;
15
import java.util.Set;
16
import java.util.function.Supplier;
17
import net.minecraft.CrashReport;
18
import net.minecraft.CrashReportCategory;
19
import net.minecraft.ReportedException;
20
import net.minecraft.core.NonNullList;
21
import net.minecraft.core.registries.BuiltInRegistries;
22
import net.minecraft.network.HashedStack;
23
import net.minecraft.server.level.ServerPlayer;
24
import net.minecraft.util.Mth;
25
import net.minecraft.util.Prediction;
26
import net.minecraft.world.Container;
27
import net.minecraft.world.entity.Entity;
28
import net.minecraft.world.entity.SlotAccess;
29
import net.minecraft.world.entity.player.Inventory;
30
import net.minecraft.world.entity.player.Player;
31
import net.minecraft.world.flag.FeatureFlagSet;
32
import net.minecraft.world.item.BundleItem;
33
import net.minecraft.world.item.ItemStack;
34
import net.minecraft.world.level.block.Block;
35
import net.minecraft.world.level.block.entity.BlockEntity;
36
import org.jspecify.annotations.Nullable;
37
import org.slf4j.Logger;
38
39
public abstract class AbstractContainerMenu {
40
	private static final Logger LOGGER = LogUtils.getLogger();
41
	public static final int SLOT_CLICKED_OUTSIDE = -999;
42
	public static final int CONTAINER_CLICK_PRIMARY = 0;
43
	public static final int CONTAINER_CLICK_SECONDARY = 1;
44
	public static final int QUICKCRAFT_TYPE_CHARITABLE = 0;
45
	public static final int QUICKCRAFT_TYPE_GREEDY = 1;
46
	public static final int QUICKCRAFT_TYPE_CLONE = 2;
47
	public static final int QUICKCRAFT_HEADER_START = 0;
48
	public static final int QUICKCRAFT_HEADER_CONTINUE = 1;
49
	public static final int QUICKCRAFT_HEADER_END = 2;
50
	public static final int CARRIED_SLOT_SIZE = Integer.MAX_VALUE;
51
	public static final int SLOTS_PER_ROW = 9;
52
	public static final int SLOT_SIZE = 18;
53
	private final NonNullList<ItemStack> lastSlots = NonNullList.create();
54
	public final NonNullList<Slot> slots = NonNullList.create();
55
	private final List<DataSlot> dataSlots = Lists.newArrayList();
56
	private ItemStack carried = ItemStack.EMPTY;
57
	private final NonNullList<RemoteSlot> remoteSlots = NonNullList.create();
58
	private final IntList remoteDataSlots = new IntArrayList();
59
	private RemoteSlot remoteCarried = RemoteSlot.PLACEHOLDER;
60
	private int stateId;
61
	private final @Nullable MenuType<?> menuType;
62
	public final int containerId;
63
	private int quickcraftType = -1;
64
	private int quickcraftStatus;
65
	private final Set<Slot> quickcraftSlots = Sets.newHashSet();
66
	private final List<ContainerListener> containerListeners = Lists.newArrayList();
67
	private @Nullable ContainerSynchronizer synchronizer;
68
	private boolean suppressRemoteUpdates;
69
70
	protected AbstractContainerMenu(final @Nullable MenuType<?> menuType, final int containerId) {
71
		this.menuType = menuType;
72
		this.containerId = containerId;
73
	}
74
75
	protected void addInventoryHotbarSlots(final Container inventory, final int left, final int top) {
76
		for (int x = 0; x < 9; x++) {
77
			this.addSlot(new Slot(inventory, x, left + x * 18, top));
78
		}
79
	}
80
81
	protected void addInventoryExtendedSlots(final Container inventory, final int left, final int top) {
82
		for (int y = 0; y < 3; y++) {
83
			for (int x = 0; x < 9; x++) {
84
				this.addSlot(new Slot(inventory, x + (y + 1) * 9, left + x * 18, top + y * 18));
85
			}
86
		}
87
	}
88
89
	protected void addStandardInventorySlots(final Container container, final int left, final int top) {
90
		this.addInventoryExtendedSlots(container, left, top);
91
		int hotbarSeparator = 4;
92
		int topToHotbar = 58;
93
		this.addInventoryHotbarSlots(container, left, top + 58);
94
	}
95
96
	protected static boolean stillValid(final ContainerLevelAccess access, final Player player, final Block block) {
97
		return access.evaluate((level, pos) -> !level.getBlockState(pos).is(block) ? false : player.isWithinBlockInteractionRange(pos, 4.0), true);
98
	}
99
100
	public MenuType<?> getType() {
101
		if (this.menuType == null) {
102
			throw new UnsupportedOperationException("Unable to construct this menu by type");
103
		} else {
104
			return this.menuType;
105
		}
106
	}
107
108
	protected static void checkContainerSize(final Container container, final int expected) {
109
		int actual = container.getContainerSize();
110
		if (actual < expected) {
111
			throw new IllegalArgumentException("Container size " + actual + " is smaller than expected " + expected);
112
		}
113
	}
114
115
	protected static void checkContainerDataCount(final ContainerData data, final int expected) {
116
		int actual = data.getCount();
117
		if (actual < expected) {
118
			throw new IllegalArgumentException("Container data count " + actual + " is smaller than expected " + expected);
119
		}
120
	}
121
122
	public boolean isValidSlotIndex(final int slotIndex) {
123
		return slotIndex == -1 || slotIndex == -999 || slotIndex < this.slots.size();
124
	}
125
126
	protected Slot addSlot(final Slot slot) {
127
		slot.index = this.slots.size();
128
		this.slots.add(slot);
129
		this.lastSlots.add(ItemStack.EMPTY);
130
		this.remoteSlots.add(this.synchronizer != null ? this.synchronizer.createSlot() : RemoteSlot.PLACEHOLDER);
131
		return slot;
132
	}
133
134
	protected DataSlot addDataSlot(final DataSlot dataSlot) {
135
		this.dataSlots.add(dataSlot);
136
		this.remoteDataSlots.add(0);
137
		return dataSlot;
138
	}
139
140
	protected void addDataSlots(final ContainerData container) {
141
		for (int i = 0; i < container.getCount(); i++) {
142
			this.addDataSlot(DataSlot.forContainer(container, i));
143
		}
144
	}
145
146
	public void addSlotListener(final ContainerListener listener) {
147
		if (!this.containerListeners.contains(listener)) {
148
			this.containerListeners.add(listener);
149
			this.broadcastChanges();
150
		}
151
	}
152
153
	public void setSynchronizer(final ContainerSynchronizer synchronizer) {
154
		this.synchronizer = synchronizer;
155
		this.remoteCarried = synchronizer.createSlot();
156
		this.remoteSlots.replaceAll(ignored -> synchronizer.createSlot());
157
		this.sendAllDataToRemote();
158
	}
159
160
	public void sendAllDataToRemote() {
161
		List<ItemStack> itemsToSend = new ArrayList<>(this.slots.size());
162
		int i = 0;
163
164
		for (int slotsSize = this.slots.size(); i < slotsSize; i++) {
165
			ItemStack slotContents = this.slots.get(i).getItem();
166
			itemsToSend.add(slotContents.copy());
167
			this.remoteSlots.get(i).force(slotContents);
168
		}
169
170
		ItemStack carried = this.getCarried();
171
		this.remoteCarried.force(carried);
172
		int ix = 0;
173
174
		for (int slotsSize = this.dataSlots.size(); ix < slotsSize; ix++) {
175
			this.remoteDataSlots.set(ix, this.dataSlots.get(ix).get());
176
		}
177
178
		if (this.synchronizer != null) {
179
			this.synchronizer.sendInitialData(this, itemsToSend, carried.copy(), this.remoteDataSlots.toIntArray());
180
		}
181
	}
182
183
	public void removeSlotListener(final ContainerListener listener) {
184
		this.containerListeners.remove(listener);
185
	}
186
187
	public NonNullList<ItemStack> getItems() {
188
		NonNullList<ItemStack> itemStacks = NonNullList.create();
189
190
		for (Slot slot : this.slots) {
191
			itemStacks.add(slot.getItem());
192
		}
193
194
		return itemStacks;
195
	}
196
197
	public void broadcastChanges() {
198
		for (int i = 0; i < this.slots.size(); i++) {
199
			ItemStack current = this.slots.get(i).getItem();
200
			Supplier<ItemStack> currentCopy = Suppliers.memoize(current::copy);
201
			this.triggerSlotListeners(i, current, currentCopy);
202
			this.synchronizeSlotToRemote(i, current, currentCopy);
203
		}
204
205
		this.synchronizeCarriedToRemote();
206
207
		for (int i = 0; i < this.dataSlots.size(); i++) {
208
			DataSlot current = this.dataSlots.get(i);
209
			int currentValue = current.get();
210
			if (current.checkAndClearUpdateFlag()) {
211
				this.updateDataSlotListeners(i, currentValue);
212
			}
213
214
			this.synchronizeDataSlotToRemote(i, currentValue);
215
		}
216
	}
217
218
	public void broadcastFullState() {
219
		for (int i = 0; i < this.slots.size(); i++) {
220
			ItemStack current = this.slots.get(i).getItem();
221
			this.triggerSlotListeners(i, current, current::copy);
222
		}
223
224
		for (int i = 0; i < this.dataSlots.size(); i++) {
225
			DataSlot current = this.dataSlots.get(i);
226
			if (current.checkAndClearUpdateFlag()) {
227
				this.updateDataSlotListeners(i, current.get());
228
			}
229
		}
230
231
		this.sendAllDataToRemote();
232
	}
233
234
	private void updateDataSlotListeners(final int id, final int currentValue) {
235
		for (ContainerListener containerListener : this.containerListeners) {
236
			containerListener.dataChanged(this, id, currentValue);
237
		}
238
	}
239
240
	private void triggerSlotListeners(final int i, final ItemStack current, final Supplier<ItemStack> currentCopy) {
241
		ItemStack localExpected = this.lastSlots.get(i);
242
		if (!ItemStack.matches(localExpected, current)) {
243
			ItemStack newItem = currentCopy.get();
244
			this.lastSlots.set(i, newItem);
245
246
			for (ContainerListener containerListener : this.containerListeners) {
247
				containerListener.slotChanged(this, i, newItem);
248
			}
249
		}
250
	}
251
252
	private void synchronizeSlotToRemote(final int i, final ItemStack current, final Supplier<ItemStack> currentCopy) {
253
		if (!this.suppressRemoteUpdates) {
254
			RemoteSlot remoteExpected = this.remoteSlots.get(i);
255
			if (!remoteExpected.matches(current)) {
256
				remoteExpected.force(current);
257
				if (this.synchronizer != null) {
258
					this.synchronizer.sendSlotChange(this, i, currentCopy.get());
259
				}
260
			}
261
		}
262
	}
263
264
	private void synchronizeDataSlotToRemote(final int i, final int current) {
265
		if (!this.suppressRemoteUpdates) {
266
			int remoteExpected = this.remoteDataSlots.getInt(i);
267
			if (remoteExpected != current) {
268
				this.remoteDataSlots.set(i, current);
269
				if (this.synchronizer != null) {
270
					this.synchronizer.sendDataChange(this, i, current);
271
				}
272
			}
273
		}
274
	}
275
276
	private void synchronizeCarriedToRemote() {
277
		if (!this.suppressRemoteUpdates) {
278
			ItemStack carriedItem = this.getCarried();
279
			if (!this.remoteCarried.matches(carriedItem)) {
280
				this.remoteCarried.force(carriedItem);
281
				if (this.synchronizer != null) {
282
					this.synchronizer.sendCarriedChange(this, carriedItem.copy());
283
				}
284
			}
285
		}
286
	}
287
288
	public void setRemoteSlot(final int slot, final ItemStack itemStack) {
289
		this.remoteSlots.get(slot).force(itemStack);
290
	}
291
292
	public void setRemoteSlotUnsafe(final int slot, final HashedStack itemStack) {
293
		if (slot >= 0 && slot < this.remoteSlots.size()) {
294
			this.remoteSlots.get(slot).receive(itemStack);
295
		} else {
296
			LOGGER.debug("Incorrect slot index: {} available slots: {}", slot, this.remoteSlots.size());
297
		}
298
	}
299
300
	public void setRemoteCarried(final HashedStack carriedItem) {
301
		this.remoteCarried.receive(carriedItem);
302
	}
303
304
	public boolean clickMenuButton(final Player player, final int buttonId) {
305
		return false;
306
	}
307
308
	public Slot getSlot(final int index) {
309
		return this.slots.get(index);
310
	}
311
312
	public abstract ItemStack quickMoveStack(final Player player, final int slotIndex);
313
314
	public void setSelectedBundleItemIndex(final int slotIndex, final int selectedItemIndex) {
315
		if (slotIndex >= 0 && slotIndex < this.slots.size()) {
316
			ItemStack itemStack = this.slots.get(slotIndex).getItem();
317
			BundleItem.toggleSelectedItem(itemStack, selectedItemIndex);
318
		}
319
	}
320
321
	public void clicked(final int slotIndex, final int buttonNum, final ContainerInput containerInput, final Player player) {
322
		try {
323
			this.doClick(slotIndex, buttonNum, containerInput, player);
324
		} catch (Exception e) {
325
			CrashReport report = CrashReport.forThrowable(e, "Container click");
326
			CrashReportCategory category = report.addCategory("Click info");
327
			category.setDetail("Menu Type", () -> this.menuType != null ? BuiltInRegistries.MENU.getKey(this.menuType).toString() : "<no type>");
328
			category.setDetail("Menu Class", () -> this.getClass().getCanonicalName());
329
			category.setDetail("Slot Count", this.slots.size());
330
			category.setDetail("Slot", slotIndex);
331
			category.setDetail("Button", buttonNum);
332
			category.setDetail("Type", containerInput);
333
			throw new ReportedException(report);
334
		}
335
	}
336
337
	private void doClick(final int slotIndex, final int buttonNum, final ContainerInput containerInput, final Player player) {
338
		Inventory inventory = player.getInventory();
339
		if (containerInput == ContainerInput.QUICK_CRAFT) {
340
			int expectedStatus = this.quickcraftStatus;
341
			this.quickcraftStatus = getQuickcraftHeader(buttonNum);
342
			if ((expectedStatus != 1 || this.quickcraftStatus != 2) && expectedStatus != this.quickcraftStatus) {
343
				this.resetQuickCraft();
344
			} else if (this.getCarried().isEmpty()) {
345
				this.resetQuickCraft();
346
			} else if (this.quickcraftStatus == 0) {
347
				this.quickcraftType = getQuickcraftType(buttonNum);
348
				if (isValidQuickcraftType(this.quickcraftType, player)) {
349
					this.quickcraftStatus = 1;
350
					this.quickcraftSlots.clear();
351
				} else {
352
					this.resetQuickCraft();
353
				}
354
			} else if (this.quickcraftStatus == 1) {
355
				Slot slot = this.slots.get(slotIndex);
356
				ItemStack carriedItemStack = this.getCarried();
357
				if (canItemQuickReplace(slot, carriedItemStack, true)
358
					&& slot.mayPlace(carriedItemStack)
359
					&& (this.quickcraftType == 2 || carriedItemStack.getCount() > this.quickcraftSlots.size())
360
					&& this.canDragTo(slot)) {
361
					this.quickcraftSlots.add(slot);
362
				}
363
			} else if (this.quickcraftStatus == 2) {
364
				if (!this.quickcraftSlots.isEmpty()) {
365
					if (this.quickcraftSlots.size() == 1) {
366
						int slot = this.quickcraftSlots.iterator().next().index;
367
						this.resetQuickCraft();
368
						this.doClick(slot, this.quickcraftType, ContainerInput.PICKUP, player);
369
						return;
370
					}
371
372
					ItemStack source = this.getCarried().copy();
373
					if (source.isEmpty()) {
374
						this.resetQuickCraft();
375
						return;
376
					}
377
378
					int remaining = this.getCarried().getCount();
379
380
					for (Slot slot : this.quickcraftSlots) {
381
						ItemStack carriedItemStack = this.getCarried();
382
						if (slot != null
383
							&& canItemQuickReplace(slot, carriedItemStack, true)
384
							&& slot.mayPlace(carriedItemStack)
385
							&& (this.quickcraftType == 2 || carriedItemStack.getCount() >= this.quickcraftSlots.size())
386
							&& this.canDragTo(slot)) {
387
							int carry = slot.hasItem() ? slot.getItem().getCount() : 0;
388
							int maxSize = Math.min(source.getMaxStackSize(), slot.getMaxStackSize(source));
389
							int newCount = Math.min(getQuickCraftPlaceCount(this.quickcraftSlots.size(), this.quickcraftType, source) + carry, maxSize);
390
							remaining -= newCount - carry;
391
							slot.setByPlayer(source.copyWithCount(newCount));
392
						}
393
					}
394
395
					source.setCount(remaining);
396
					this.setCarried(source);
397
				}
398
399
				this.resetQuickCraft();
400
			} else {
401
				this.resetQuickCraft();
402
			}
403
		} else if (this.quickcraftStatus != 0) {
404
			this.resetQuickCraft();
405
		} else if ((containerInput == ContainerInput.PICKUP || containerInput == ContainerInput.QUICK_MOVE) && isContainerClickButton(buttonNum)) {
406
			ClickAction clickAction = getClickAction(buttonNum);
407
			if (slotIndex == -999) {
408
				if (!this.getCarried().isEmpty()) {
409
					if (clickAction == ClickAction.PRIMARY) {
410
						player.drop(this.getCarried(), true, Prediction.PREDICTED);
411
						this.setCarried(ItemStack.EMPTY);
412
					} else {
413
						player.drop(this.getCarried().split(1), true, Prediction.PREDICTED);
414
					}
415
				}
416
			} else if (containerInput == ContainerInput.QUICK_MOVE) {
417
				if (slotIndex < 0) {
418
					return;
419
				}
420
421
				Slot slot = this.slots.get(slotIndex);
422
				if (!slot.mayPickup(player)) {
423
					return;
424
				}
425
426
				ItemStack clicked = this.quickMoveStack(player, slotIndex);
427
428
				while (!clicked.isEmpty() && ItemStack.isSameItem(slot.getItem(), clicked)) {
429
					clicked = this.quickMoveStack(player, slotIndex);
430
				}
431
			} else {
432
				if (slotIndex < 0) {
433
					return;
434
				}
435
436
				Slot slot = this.slots.get(slotIndex);
437
				ItemStack clicked = slot.getItem();
438
				ItemStack carried = this.getCarried();
439
				player.updateTutorialInventoryAction(carried, slot.getItem(), clickAction);
440
				if (!this.tryItemClickBehaviourOverride(player, clickAction, slot, clicked, carried)) {
441
					if (clicked.isEmpty()) {
442
						if (!carried.isEmpty()) {
443
							int amount = clickAction == ClickAction.PRIMARY ? carried.getCount() : 1;
444
							this.setCarried(slot.safeInsert(carried, amount));
445
						}
446
					} else if (slot.mayPickup(player)) {
447
						if (carried.isEmpty()) {
448
							int amount = clickAction == ClickAction.PRIMARY ? clicked.getCount() : (clicked.getCount() + 1) / 2;
449
							Optional<ItemStack> newCarried = slot.tryRemove(amount, Integer.MAX_VALUE, player);
450
							newCarried.ifPresent(itemsTaken -> {
451
								this.setCarried(itemsTaken);
452
								slot.onTake(player, itemsTaken);
453
							});
454
						} else if (slot.mayPlace(carried)) {
455
							if (ItemStack.isSameItemSameComponents(clicked, carried)) {
456
								int amount = clickAction == ClickAction.PRIMARY ? carried.getCount() : 1;
457
								this.setCarried(slot.safeInsert(carried, amount));
458
							} else if (carried.getCount() <= slot.getMaxStackSize(carried)) {
459
								this.setCarried(clicked);
460
								slot.setByPlayer(carried);
461
							}
462
						} else if (ItemStack.isSameItemSameComponents(clicked, carried)) {
463
							Optional<ItemStack> newCarried = slot.tryRemove(clicked.getCount(), carried.getMaxStackSize() - carried.getCount(), player);
464
							newCarried.ifPresent(itemsTaken -> {
465
								carried.grow(itemsTaken.getCount());
466
								slot.onTake(player, itemsTaken);
467
							});
468
						}
469
					}
470
				}
471
472
				slot.setChanged();
473
			}
474
		} else if (containerInput == ContainerInput.SWAP && (buttonNum >= 0 && buttonNum < 9 || buttonNum == 40)) {
475
			ItemStack source = inventory.getItem(buttonNum);
476
			Slot target = this.slots.get(slotIndex);
477
			ItemStack targetItemStack = target.getItem();
478
			if (!source.isEmpty() || !targetItemStack.isEmpty()) {
479
				if (source.isEmpty()) {
480
					if (target.mayPickup(player)) {
481
						inventory.setItem(buttonNum, targetItemStack);
482
						target.onSwapCraft(targetItemStack.getCount());
483
						target.setByPlayer(ItemStack.EMPTY);
484
						target.onTake(player, targetItemStack);
485
					}
486
				} else if (targetItemStack.isEmpty()) {
487
					if (target.mayPlace(source)) {
488
						int maxStackSize = target.getMaxStackSize(source);
489
						if (source.getCount() > maxStackSize) {
490
							target.setByPlayer(source.split(maxStackSize));
491
						} else {
492
							inventory.setItem(buttonNum, ItemStack.EMPTY);
493
							target.setByPlayer(source);
494
						}
495
					}
496
				} else if (target.mayPickup(player) && target.mayPlace(source)) {
497
					int maxStackSize = target.getMaxStackSize(source);
498
					if (source.getCount() > maxStackSize) {
499
						target.setByPlayer(source.split(maxStackSize));
500
						target.onTake(player, targetItemStack);
501
						if (!inventory.add(targetItemStack)) {
502
							player.drop(targetItemStack, true, Prediction.PREDICTED);
503
						}
504
					} else {
505
						inventory.setItem(buttonNum, targetItemStack);
506
						target.setByPlayer(source);
507
						target.onTake(player, targetItemStack);
508
					}
509
				}
510
			}
511
		} else if (containerInput == ContainerInput.CLONE && player.hasInfiniteMaterials() && this.getCarried().isEmpty() && slotIndex >= 0) {
512
			Slot slot = this.slots.get(slotIndex);
513
			if (slot.hasItem()) {
514
				this.setCarried(slot.safeClone(player));
515
			}
516
		} else if (containerInput == ContainerInput.THROW && this.getCarried().isEmpty() && slotIndex >= 0) {
517
			Slot slot = this.slots.get(slotIndex);
518
			int amount = buttonNum == 0 ? 1 : slot.getItem().getCount();
519
			if (!player.canDropItems()) {
520
				return;
521
			}
522
523
			ItemStack itemStack = slot.safeTake(amount, Integer.MAX_VALUE, player);
524
			player.drop(itemStack, true, Prediction.PREDICTED);
525
			player.handleCreativeModeItemDrop(itemStack);
526
			if (buttonNum == 1) {
527
				while (!itemStack.isEmpty() && ItemStack.isSameItem(slot.getItem(), itemStack)) {
528
					if (!player.canDropItems()) {
529
						return;
530
					}
531
532
					itemStack = slot.safeTake(amount, Integer.MAX_VALUE, player);
533
					player.drop(itemStack, true, Prediction.PREDICTED);
534
					player.handleCreativeModeItemDrop(itemStack);
535
				}
536
			}
537
		} else if (containerInput == ContainerInput.PICKUP_ALL && slotIndex >= 0) {
538
			Slot slot = this.slots.get(slotIndex);
539
			ItemStack carried = this.getCarried();
540
			if (!carried.isEmpty() && (!slot.hasItem() || !slot.mayPickup(player))) {
541
				int start = buttonNum == 0 ? 0 : this.slots.size() - 1;
542
				int step = buttonNum == 0 ? 1 : -1;
543
544
				for (int pass = 0; pass < 2; pass++) {
545
					for (int i = start; i >= 0 && i < this.slots.size() && carried.getCount() < carried.getMaxStackSize(); i += step) {
546
						Slot target = this.slots.get(i);
547
						if (target.hasItem() && canItemQuickReplace(target, carried, true) && target.mayPickup(player) && this.canTakeItemForPickAll(carried, target)) {
548
							ItemStack itemStack = target.getItem();
549
							if (pass != 0 || itemStack.getCount() != itemStack.getMaxStackSize()) {
550
								ItemStack removed = target.safeTake(itemStack.getCount(), carried.getMaxStackSize() - carried.getCount(), player);
551
								carried.grow(removed.getCount());
552
							}
553
						}
554
					}
555
				}
556
			}
557
		}
558
	}
559
560
	private static boolean isContainerClickButton(final int buttonNum) {
561
		return buttonNum == 0 || buttonNum == 1;
562
	}
563
564
	private static ClickAction getClickAction(final int buttonNum) {
565
		return switch (buttonNum) {
566
			case 0 -> ClickAction.PRIMARY;
567
			case 1 -> ClickAction.SECONDARY;
568
			default -> throw new IllegalArgumentException("Not a container click button: " + buttonNum);
569
		};
570
	}
571
572
	private boolean tryItemClickBehaviourOverride(
573
		final Player player, final ClickAction clickAction, final Slot slot, final ItemStack clicked, final ItemStack carried
574
	) {
575
		FeatureFlagSet enabledFeatures = player.level().enabledFeatures();
576
		return carried.isItemEnabled(enabledFeatures) && carried.overrideStackedOnOther(slot, clickAction, player)
577
			? true
578
			: clicked.isItemEnabled(enabledFeatures) && clicked.overrideOtherStackedOnMe(carried, slot, clickAction, player, this.createCarriedSlotAccess());
579
	}
580
581
	private SlotAccess createCarriedSlotAccess() {
582
		return new SlotAccess() {
583
			@Override
584
			public ItemStack get() {
585
				return AbstractContainerMenu.this.getCarried();
586
			}
587
588
			@Override
589
			public boolean set(final ItemStack itemStack) {
590
				AbstractContainerMenu.this.setCarried(itemStack);
591
				return true;
592
			}
593
		};
594
	}
595
596
	public boolean canTakeItemForPickAll(final ItemStack carried, final Slot target) {
597
		return true;
598
	}
599
600
	public void removed(final Player player) {
601
		if (player instanceof ServerPlayer) {
602
			ItemStack carried = this.getCarried();
603
			if (!carried.isEmpty()) {
604
				dropOrPlaceInInventory(player, carried);
605
				this.setCarried(ItemStack.EMPTY);
606
			}
607
		}
608
	}
609
610
	private static void dropOrPlaceInInventory(final Player player, final ItemStack carried) {
611
		if (player instanceof ServerPlayer serverPlayer) {
612
			boolean playerRemovedNotChangingDimension = serverPlayer.isRemoved() && serverPlayer.getRemovalReason() != Entity.RemovalReason.CHANGED_DIMENSION;
613
			if (!playerRemovedNotChangingDimension && !serverPlayer.hasDisconnected()) {
614
				serverPlayer.getInventory().placeItemBackInInventory(carried, Prediction.SERVER_ONLY);
615
			} else {
616
				serverPlayer.drop(carried, false, Prediction.SERVER_ONLY);
617
			}
618
		}
619
	}
620
621
	protected void clearContainer(final Player player, final Container container) {
622
		for (int i = 0; i < container.getContainerSize(); i++) {
623
			dropOrPlaceInInventory(player, container.removeItemNoUpdate(i));
624
		}
625
	}
626
627
	public void slotsChanged(final Container container) {
628
		this.broadcastChanges();
629
	}
630
631
	public void setItem(final int slot, final int stateId, final ItemStack itemStack) {
632
		this.getSlot(slot).set(itemStack);
633
		this.stateId = stateId;
634
	}
635
636
	public void initializeContents(final int stateId, final List<ItemStack> items, final ItemStack carried) {
637
		for (int i = 0; i < items.size(); i++) {
638
			this.getSlot(i).set(items.get(i));
639
		}
640
641
		this.carried = carried;
642
		this.stateId = stateId;
643
	}
644
645
	public void setData(final int id, final int value) {
646
		this.dataSlots.get(id).set(value);
647
	}
648
649
	public abstract boolean stillValid(Player player);
650
651
	protected boolean moveItemStackTo(final ItemStack itemStack, final int startSlot, final int endSlot, final boolean backwards) {
652
		boolean anythingChanged = false;
653
		int destSlot = startSlot;
654
		if (backwards) {
655
			destSlot = endSlot - 1;
656
		}
657
658
		if (itemStack.isStackable()) {
659
			while (!itemStack.isEmpty() && (backwards ? destSlot >= startSlot : destSlot < endSlot)) {
660
				Slot slot = this.slots.get(destSlot);
661
				ItemStack target = slot.getItem();
662
				if (!target.isEmpty() && ItemStack.isSameItemSameComponents(itemStack, target)) {
663
					int totalStack = target.getCount() + itemStack.getCount();
664
					int maxStackSize = slot.getMaxStackSize(target);
665
					if (totalStack <= maxStackSize) {
666
						itemStack.setCount(0);
667
						target.setCount(totalStack);
668
						slot.setChanged();
669
						anythingChanged = true;
670
					} else if (target.getCount() < maxStackSize) {
671
						itemStack.shrink(maxStackSize - target.getCount());
672
						target.setCount(maxStackSize);
673
						slot.setChanged();
674
						anythingChanged = true;
675
					}
676
				}
677
678
				if (backwards) {
679
					destSlot--;
680
				} else {
681
					destSlot++;
682
				}
683
			}
684
		}
685
686
		if (!itemStack.isEmpty()) {
687
			if (backwards) {
688
				destSlot = endSlot - 1;
689
			} else {
690
				destSlot = startSlot;
691
			}
692
693
			while (backwards ? destSlot >= startSlot : destSlot < endSlot) {
694
				Slot slot = this.slots.get(destSlot);
695
				ItemStack target = slot.getItem();
696
				if (target.isEmpty() && slot.mayPlace(itemStack)) {
697
					int maxStackSize = slot.getMaxStackSize(itemStack);
698
					slot.setByPlayer(itemStack.split(Math.min(itemStack.getCount(), maxStackSize)));
699
					slot.setChanged();
700
					anythingChanged = true;
701
					break;
702
				}
703
704
				if (backwards) {
705
					destSlot--;
706
				} else {
707
					destSlot++;
708
				}
709
			}
710
		}
711
712
		return anythingChanged;
713
	}
714
715
	public static int getQuickcraftType(final int mask) {
716
		return mask >> 2 & 3;
717
	}
718
719
	public static int getQuickcraftHeader(final int mask) {
720
		return mask & 3;
721
	}
722
723
	public static int getQuickcraftMask(final int header, final int type) {
724
		return header & 3 | (type & 3) << 2;
725
	}
726
727
	public static boolean isValidQuickcraftType(final int type, final Player player) {
728
		if (type == 0) {
729
			return true;
730
		} else {
731
			return type == 1 ? true : type == 2 && player.hasInfiniteMaterials();
732
		}
733
	}
734
735
	protected void resetQuickCraft() {
736
		this.quickcraftStatus = 0;
737
		this.quickcraftSlots.clear();
738
	}
739
740
	public static boolean canItemQuickReplace(final @Nullable Slot slot, final ItemStack itemStack, final boolean ignoreSize) {
741
		boolean slotIsEmpty = slot == null || !slot.hasItem();
742
		return !slotIsEmpty && ItemStack.isSameItemSameComponents(itemStack, slot.getItem())
743
			? slot.getItem().getCount() + (ignoreSize ? 0 : itemStack.getCount()) <= itemStack.getMaxStackSize()
744
			: slotIsEmpty;
745
	}
746
747
	public static int getQuickCraftPlaceCount(final int quickCraftSlotsSize, final int quickCraftingType, final ItemStack itemStack) {
748
		return switch (quickCraftingType) {
749
			case 0 -> Mth.floor((float)itemStack.getCount() / quickCraftSlotsSize);
750
			case 1 -> 1;
751
			case 2 -> itemStack.getMaxStackSize();
752
			default -> itemStack.getCount();
753
		};
754
	}
755
756
	public boolean canDragTo(final Slot slot) {
757
		return true;
758
	}
759
760
	public static int getRedstoneSignalFromBlockEntity(final @Nullable BlockEntity blockEntity) {
761
		return blockEntity instanceof Container container ? getRedstoneSignalFromContainer(container) : 0;
762
	}
763
764
	public static int getRedstoneSignalFromContainer(final @Nullable Container container) {
765
		if (container == null) {
766
			return 0;
767
		}
768
769
		float totalPercent = 0.0F;
770
771
		for (int i = 0; i < container.getContainerSize(); i++) {
772
			ItemStack itemStack = container.getItem(i);
773
			if (!itemStack.isEmpty()) {
774
				totalPercent += (float)itemStack.getCount() / container.getMaxStackSize(itemStack);
775
			}
776
		}
777
778
		totalPercent /= container.getContainerSize();
779
		return Mth.lerpDiscrete(totalPercent, 0, 15);
780
	}
781
782
	public void setCarried(final ItemStack carried) {
783
		this.carried = carried;
784
	}
785
786
	public ItemStack getCarried() {
787
		return this.carried;
788
	}
789
790
	public void suppressRemoteUpdates() {
791
		this.suppressRemoteUpdates = true;
792
	}
793
794
	public void resumeRemoteUpdates() {
795
		this.suppressRemoteUpdates = false;
796
	}
797
798
	public void transferState(final AbstractContainerMenu otherContainer) {
799
		Table<Container, Integer, Integer> otherSlots = HashBasedTable.create();
800
801
		for (int slotIndex = 0; slotIndex < otherContainer.slots.size(); slotIndex++) {
802
			Slot slot = otherContainer.slots.get(slotIndex);
803
			otherSlots.put(slot.container, slot.getContainerSlot(), slotIndex);
804
		}
805
806
		for (int slotIndex = 0; slotIndex < this.slots.size(); slotIndex++) {
807
			Slot slot = this.slots.get(slotIndex);
808
			Integer otherSlotIndex = otherSlots.get(slot.container, slot.getContainerSlot());
809
			if (otherSlotIndex != null) {
810
				this.lastSlots.set(slotIndex, otherContainer.lastSlots.get(otherSlotIndex));
811
				RemoteSlot sourceRemoteSlot = otherContainer.remoteSlots.get(otherSlotIndex);
812
				RemoteSlot targetRemoteSlot = this.remoteSlots.get(slotIndex);
813
				if (sourceRemoteSlot instanceof RemoteSlot.Synchronized synchronizedSource && targetRemoteSlot instanceof RemoteSlot.Synchronized synchronizedTarget) {
814
					synchronizedTarget.copyFrom(synchronizedSource);
815
				}
816
			}
817
		}
818
	}
819
820
	public OptionalInt findSlot(final Container inventory, final int slotIndex) {
821
		for (int i = 0; i < this.slots.size(); i++) {
822
			Slot slot = this.slots.get(i);
823
			if (slot.container == inventory && slotIndex == slot.getContainerSlot()) {
824
				return OptionalInt.of(i);
825
			}
826
		}
827
828
		return OptionalInt.empty();
829
	}
830
831
	public int getStateId() {
832
		return this.stateId;
833
	}
834
835
	public int incrementStateId() {
836
		this.stateId = this.stateId + 1 & 32767;
837
		return this.stateId;
838
	}
839
}
840

Decompiled Minecraft 26.3 source of AbstractContainerMenu (net/minecraft/world/inventory/AbstractContainerMenu.java) with Mojang official mappings, stored verbatim on the site.