Skip to content

Commit

Permalink
Merge pull request #153 from ErrorMikey/1.19-backport-1.18
Browse files Browse the repository at this point in the history
fix: #152 #121 #123 (partial) #119 #150
  • Loading branch information
cpw authored Oct 28, 2022
2 parents 510fe8f + 4ce882c commit a569126
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 85 deletions.
5 changes: 3 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ buildscript {
classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true
}
}

plugins {
id 'com.matthewprenger.cursegradle' version '1.4.0'
id 'se.bjurr.gitchangelog.git-changelog-gradle-plugin' version '1.71.4'
Expand All @@ -33,7 +34,7 @@ java.toolchain.languageVersion = JavaLanguageVersion.of(17)
version = grgit.describe(longDescr: true).split('-').with { "${it[0]}.${it[1]}" }

minecraft {
mappings channel: MCP_CHANNEL, version: MCP_MAPPINGS
mappings channel: "official", version: MC_VERSION
runs {
client {
workingDirectory project.file('run')
Expand All @@ -58,7 +59,7 @@ minecraft {
property 'forge.logging.noansi', 'false'
ideaModule "${project.name}.main"
}

data {
workingDirectory project.file('run')
property 'forge.logging.markers', 'SCAN'
Expand Down
6 changes: 2 additions & 4 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,5 @@
# This is required to provide enough memory for the Minecraft decompilation process.
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false
MC_VERSION=1.18
FORGE_VERSION=38.0.4
MCP_CHANNEL=official
MCP_MAPPINGS=1.18
MC_VERSION=1.18.2
FORGE_VERSION=40.1.84
4 changes: 4 additions & 0 deletions src/main/java/cpw/mods/inventorysorter/ContainerContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.google.common.collect.*;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.Slot;
import net.minecraftforge.items.SlotItemHandler;
import org.apache.logging.log4j.*;

import java.util.*;
Expand All @@ -26,6 +27,9 @@ class ContainerContext
static boolean validSlot(Slot slot) {
// Skip slots without an inventory - they're probably dummy slots
return slot != null && slot.container != null
// Skip slots where the inventory has no slots, these are probably dummies too.
// Since SlotItemHandler also uses empty fake containers, whitelist that explicitly.
&& (slot instanceof SlotItemHandler || slot.container.getContainerSize() > 0)
// Skip blacklisted slots
&& !InventorySorter.INSTANCE.slotblacklist.contains(slot.getClass().getName());
}
Expand Down
77 changes: 47 additions & 30 deletions src/main/java/cpw/mods/inventorysorter/InventorySorter.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.IEventBus;
Expand Down Expand Up @@ -61,9 +59,12 @@ public class InventorySorter
static final Logger LOGGER = LogManager.getLogger();
ResourceLocation lastContainerType;
boolean debugLog;

final Set<String> slotblacklist = new HashSet<>();
final Set<ResourceLocation> containerblacklist = new HashSet<>();
boolean configLoaded = false;

final Set<String> imcSlotBlacklist = new HashSet<>();
final Set<ResourceLocation> imcContainerBlacklist = new HashSet<>();

public InventorySorter() {
INSTANCE = this;
Expand All @@ -84,30 +85,36 @@ private void clientSetup(FMLClientSetupEvent evt) {
private void handleimc(final InterModProcessEvent evt)
{
final Stream<InterModComms.IMCMessage> imc = InterModComms.getMessages("inventorysorter");
imc.forEach(this::handleimcmessage);
}

private void handleimcmessage(final InterModComms.IMCMessage msg) {
if ("slotblacklist".equals(msg.getMethod())) {
final String slotBlacklistTarget = msg.<String>getMessageSupplier().get();
if (slotblacklist.add(slotBlacklistTarget)) {
debugLog("SlotBlacklist added {}", ()->new String[] {slotBlacklistTarget});
imc.forEach(this::handleIMCMessage);
}

/**
* Supply an IMC of `slotblacklist` as {@link String} to add to the slot blacklist. This uses the complete class path.
* For example `net.minecraft.world.inventory.Slot`
* <p>
* Supply an IMC of `containerblacklist as {@link ResourceLocation} to add to the container blacklist. This uses
* the container / menu type, for example: `minecraft:generic_3x3`
*/
private void handleIMCMessage(final InterModComms.IMCMessage msg) {
if ("slotblacklist".equals(msg.method())) {
Object message = msg.messageSupplier().get();
if (message instanceof final String blackListTarget && imcSlotBlacklist.add(blackListTarget)) {
debugLog("SlotBlacklist added {}", () -> new String[]{blackListTarget});
} else {
LOGGER.warn("Rejected slotblacklist due to bad messageSupplier type. Please supply a [String]");
}
}

if ("containerblacklist".equals(msg.getMethod())) {
final ResourceLocation slotContainerTarget = msg.<ResourceLocation>getMessageSupplier().get();
if (containerblacklist.add(slotContainerTarget)) {
debugLog("ContainerBlacklist added {}", () -> new String[] {slotContainerTarget.toString()});
if ("containerblacklist".equals(msg.method())) {
Object message = msg.messageSupplier().get();
if (message instanceof final ResourceLocation blackListTarget && imcContainerBlacklist.add(blackListTarget)) {
debugLog("ContainerBlacklist added {}", () -> new String[] {blackListTarget.toString()});
} else {
LOGGER.warn("Rejected containerblacklist due to bad messageSupplier type. Please supply a [ResourceLocation]");
}
}
updateConfig();
}

private void updateConfig() {
if (!configLoaded) return;
Config.CONFIG.containerBlacklist.set(containerblacklist.stream().map(Objects::toString).collect(Collectors.toList()));
Config.CONFIG.slotBlacklist.set(new ArrayList<>(slotblacklist));
updateBlacklists();
}

private void preinit(FMLCommonSetupEvent evt) {
Expand All @@ -118,11 +125,27 @@ private void onServerStarting(ServerStartingEvent evt) {
InventorySorterCommand.register(evt.getServer().getCommands().getDispatcher());
}

void onConfigLoad(ModConfigEvent configEvent) {
private void updateBlacklists() {
// Clear all entries
this.slotblacklist.clear();
this.slotblacklist.addAll(Config.CONFIG.slotBlacklist.get());
this.containerblacklist.clear();

// Merge in the config values and the imc values
this.slotblacklist.addAll(Config.CONFIG.slotBlacklist.get());
this.containerblacklist.addAll(Config.CONFIG.containerBlacklist.get().stream().map(ResourceLocation::new).collect(Collectors.toSet()));
this.slotblacklist.addAll(imcSlotBlacklist);
this.containerblacklist.addAll(imcContainerBlacklist);
}

private void updateConfig() {
Config.CONFIG.containerBlacklist.set(containerblacklist.stream().filter(e -> !imcContainerBlacklist.contains(e)).map(Objects::toString).collect(Collectors.toList()));
Config.CONFIG.slotBlacklist.set(slotblacklist.stream().filter(e -> !imcSlotBlacklist.contains(e)).collect(Collectors.toList()));

updateBlacklists();
}

void onConfigLoad(ModConfigEvent configEvent) {
updateBlacklists();
}

boolean wheelModConflicts() {
Expand All @@ -139,12 +162,6 @@ final void debugLog(String message, Supplier<String[]> args) {
}
}

private static TextComponent greenText(final String string) {
final TextComponent tcs = new TextComponent(string);
tcs.getStyle().withColor(ChatFormatting.GREEN);
return tcs;
}

static int blackListAdd(final CommandContext<CommandSourceStack> context) {
final ResourceLocation containerType = InventorySorterCommand.Arguments.CONTAINER.get(context);
if (ForgeRegistries.CONTAINERS.containsKey(containerType)) {
Expand Down Expand Up @@ -189,7 +206,7 @@ static int showBlacklist(final CommandContext<CommandSourceStack> context) {
}

static Stream<String> listContainers() {
return ForgeRegistries.CONTAINERS.getEntries().stream().map(e->e.getKey().toString());
return ForgeRegistries.CONTAINERS.getEntries().stream().map(e -> e.getKey().location().toString());
}

static Stream<String> listBlacklist() {
Expand Down
20 changes: 5 additions & 15 deletions src/main/java/cpw/mods/inventorysorter/InventorySorterCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@

public class InventorySorterCommand {
public static void register(final CommandDispatcher<CommandSourceStack> dispatcher) {
final LiteralArgumentBuilder<CommandSourceStack> invsorterBuilder = Commands.literal("invsorter").
requires(cs->cs.hasPermission(1));
final LiteralArgumentBuilder<CommandSourceStack> invsorterBuilder = Commands.literal("invsorter")
.requires(cs->cs.hasPermission(1));

Stream.of(CommandAction.values()).forEach(a->invsorterBuilder.then(a.getCommand()));
invsorterBuilder.executes(InventorySorterCommand::help);
dispatcher.register(invsorterBuilder);
}

private static int help(final CommandContext<CommandSourceStack> context) {
context.getSource().sendFailure(new TranslatableComponent("inventorysorter.commands.inventorysorter.usage"));
context.getSource().sendSuccess(new TranslatableComponent("inventorysorter.commands.inventorysorter.usage"), false);
return 0;
}

Expand All @@ -59,7 +59,8 @@ private void addArguments(LiteralArgumentBuilder<CommandSourceStack> builder) {
final Optional<ArgumentBuilder<CommandSourceStack, ?>> argBuilder = argumentSupplier.stream()
.<ArgumentBuilder<CommandSourceStack, ?>>map(TypedArgumentHandler::build)
.reduce(ArgumentBuilder::then);
ifPresentOrElse(argBuilder, b -> builder.then(b.executes(this.action::applyAsInt)), ()->builder.executes(this.action::applyAsInt));

argBuilder.ifPresentOrElse(b -> builder.then(b.executes(this.action::applyAsInt)), ()->builder.executes(this.action::applyAsInt));
}

public LiteralArgumentBuilder<CommandSourceStack> getCommand() {
Expand All @@ -68,7 +69,6 @@ public LiteralArgumentBuilder<CommandSourceStack> getCommand() {
addArguments(base);
return base;
}

}

public static class Arguments {
Expand Down Expand Up @@ -125,14 +125,4 @@ public Collection<String> getExamples() {
return EXAMPLES;
}
}


public static <T> void ifPresentOrElse(Optional<T> optional, Consumer<? super T> action, Runnable emptyAction) {
if (optional.isPresent()) {
action.accept(optional.get());
} else {
emptyAction.run();
}
}

}
19 changes: 15 additions & 4 deletions src/main/java/cpw/mods/inventorysorter/KeyHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,15 @@

package cpw.mods.inventorysorter;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.client.gui.screens.inventory.CreativeModeInventoryScreen;
import net.minecraft.client.KeyMapping;
import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.level.GameType;
import net.minecraftforge.client.ClientRegistry;
import net.minecraftforge.client.event.ScreenEvent;
import net.minecraftforge.client.settings.KeyConflictContext;
Expand Down Expand Up @@ -95,19 +98,27 @@ private boolean mouseScrollEvaluate(final KeyMapping kb, final ScreenEvent.Mouse
}

private <T extends ScreenEvent> void onInputEvent(T evt, BiPredicate<KeyMapping, T> kbTest) {
// Don't sort on spectator
MultiPlayerGameMode gameMode = Minecraft.getInstance().gameMode;
if (gameMode != null && gameMode.getPlayerMode() == GameType.SPECTATOR) {
return;
}

final Screen gui = evt.getScreen();
if (!(gui instanceof AbstractContainerScreen && !(gui instanceof CreativeModeInventoryScreen))) {
if (!(gui instanceof final AbstractContainerScreen<?> guiContainer && !(gui instanceof CreativeModeInventoryScreen))) {
return;
}
final AbstractContainerScreen guiContainer = (AbstractContainerScreen) gui;

Slot slot = guiContainer.getSlotUnderMouse();
if (!ContainerContext.validSlot(slot)) {
InventorySorter.LOGGER.log(Level.DEBUG, "Skipping action handling for blacklisted slot");
return;
}

final Optional<Action> action = keyBindingMap.entrySet().stream().filter(e -> kbTest.test(e.getKey(), evt)).
map(Map.Entry::getValue).findFirst();
if (!action.isPresent()) return;

if (action.isEmpty()) return;

final Action triggeredAction = action.get();
if (triggeredAction.isActive())
Expand All @@ -121,4 +132,4 @@ private <T extends ScreenEvent> void onInputEvent(T evt, BiPredicate<KeyMapping,
}

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

import net.minecraft.world.inventory.Slot;

import javax.annotation.*;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
Expand All @@ -31,8 +30,7 @@
/**
* @author cpw
*/
public enum ScrollWheelHandler implements Consumer<ContainerContext>
{
public enum ScrollWheelHandler implements Consumer<ContainerContext> {
ONEITEMIN(-1), ONEITEMOUT(1);

private final int moveAmount;
Expand All @@ -41,7 +39,7 @@ public enum ScrollWheelHandler implements Consumer<ContainerContext>
{
this.moveAmount = amount;
}
@Nullable

@Override
public void accept(ContainerContext context)
{
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/cpw/mods/inventorysorter/SortingHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,12 @@ private void distributeInventory(final ContainerContext context, final Multiset<
context.player.containerMenu.getSlot(slot).setChanged();
}
}
private void compactInventory(final ContainerContext context, final Multiset<ItemStackHolder> itemcounts)
{
final ResourceLocation containerTypeName = lookupContainerTypeName(context.player.inventoryMenu);
private void compactInventory(final ContainerContext context, final Multiset<ItemStackHolder> itemcounts) {
final ResourceLocation containerTypeName = lookupContainerTypeName(context.player.containerMenu);

InventorySorter.INSTANCE.lastContainerType = containerTypeName;
if (InventorySorter.INSTANCE.containerblacklist.contains(containerTypeName)) {
InventorySorter.INSTANCE.debugLog("Container {} blacklisted", ()->new String[] {containerTypeName.toString()});
InventorySorter.INSTANCE.debugLog("Container {} blacklisted", ()-> new String[] {containerTypeName.toString()});
return;
}

Expand Down
30 changes: 8 additions & 22 deletions src/main/resources/META-INF/mods.toml
Original file line number Diff line number Diff line change
@@ -1,26 +1,12 @@
# This is an example mods.toml file. It contains the data relating to the loading mods.
# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
# The overall format is standard TOML format, v0.5.0.
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the minecraft version (without the 1.)
loaderVersion="[38,)" #mandatory
# A text field displayed in the mod UI
credits="cpw" #optional
# A text field displayed in the mod UI
authors="cpw" #optional
modLoader="javafml"
loaderVersion="[40,)"
credits="cpw"
authors="cpw"
license="GPLv3"
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="inventorysorter" #mandatory
# The version number of the mod - there's a few well known ${} variables useable here or just hardcode it
version="${file.jarVersion}" #mandatory
# A display name for the mod
displayName="Simple Inventory Sorter" #mandatory
# The description text for the mod (multi line!) (#mandatory)
[[mods]]
modId="inventorysorter"
version="${file.jarVersion}"
displayName="Simple Inventory Sorter"
description='''
Simple inventory sorting.
Expand Down

0 comments on commit a569126

Please sign in to comment.