Compare commits

...
12 changed files with 495 additions and 109 deletions

No files matched your search

@@ -9,7 +9,6 @@ import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
@@ -1025,11 +1024,11 @@ public class NEIClientConfig {
@Override
public void run() {
final Stream<Class<?>> stream = NEIClientConfig.getBooleanSetting("loadPluginsInParallel")
? NEIClientConfig.pluginsList.parallelStream()
: NEIClientConfig.pluginsList.stream();
PluginLoader.load(stream, NEIModContainer.plugins, logger);
PluginLoader.load(
NEIClientConfig.pluginsList,
NEIClientConfig.getBooleanSetting("loadPluginsInParallel"),
NEIModContainer.plugins,
logger);
KeyManager.requestOptionsReload();
RecipeCatalysts.loadCatalystInfo();
+48 -20
View File
@@ -1,7 +1,8 @@
package codechicken.nei;
import java.util.Collection;
import java.util.stream.Stream;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import org.apache.logging.log4j.Logger;
@@ -11,28 +12,55 @@ final class PluginLoader {
private PluginLoader() {}
static void load(Stream<Class<?>> plugins, Collection<IConfigureNEI> loadedPlugins, Logger logger) {
final ClassLoader classLoader = IConfigureNEI.class.getClassLoader();
static void load(Collection<Class<?>> plugins, boolean parallel, Collection<IConfigureNEI> loadedPlugins,
Logger logger) {
if (parallel && canSetContextClassLoader()) {
// Common pool workers use the system loader, which cannot see FML-only classes (old Log4j then throws
// while logging a plugin's stack frames), and under a SecurityManager they forbid changing it.
final ClassLoader classLoader = IConfigureNEI.class.getClassLoader();
final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors(), owner -> {
final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(owner);
worker.setContextClassLoader(classLoader);
return worker;
}, null, false);
plugins.forEach(clazz -> {
final Thread thread = Thread.currentThread();
final ClassLoader previousClassLoader = thread.getContextClassLoader();
// Common-pool workers may use the system loader, which cannot see FML-only classes. Keep FML's loader
// through error logging too: old Log4j can otherwise throw while resolving a plugin's stack frames.
try {
thread.setContextClassLoader(classLoader);
try {
IConfigureNEI config = (IConfigureNEI) clazz.getConstructor().newInstance();
config.loadConfig();
loadedPlugins.add(config);
logger.debug("Loaded {}", clazz.getName());
} catch (Throwable e) {
logger.error("Failed to Load {}", clazz.getName(), e);
}
pool.submit(() -> plugins.parallelStream().forEach(clazz -> load(clazz, loadedPlugins, logger))).join();
} finally {
thread.setContextClassLoader(previousClassLoader);
pool.shutdown();
}
});
} else {
if (parallel) {
logger.warn("Context class loader cannot be changed, loading plugins sequentially");
}
plugins.forEach(clazz -> load(clazz, loadedPlugins, logger));
}
}
private static void load(Class<?> clazz, Collection<IConfigureNEI> loadedPlugins, Logger logger) {
try {
IConfigureNEI config = (IConfigureNEI) clazz.getConstructor().newInstance();
config.loadConfig();
loadedPlugins.add(config);
logger.debug("Loaded {}", clazz.getName());
} catch (Throwable e) {
logger.error("Failed to Load {}", clazz.getName(), e);
}
}
private static boolean canSetContextClassLoader() {
final SecurityManager securityManager = System.getSecurityManager();
if (securityManager == null) {
return true;
}
try {
securityManager.checkPermission(new RuntimePermission("setContextClassLoader"));
return true;
} catch (SecurityException e) {
return false;
}
}
}
@@ -59,6 +59,7 @@ import codechicken.nei.SearchTokenParser.SearchMode;
import codechicken.nei.config.ArrayDumper;
import codechicken.nei.config.HandlerDumper;
import codechicken.nei.config.ItemPanelDumper;
import codechicken.nei.config.RecipeDumper;
import codechicken.nei.config.RegistryDumper;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.item.FluidDisplayRenderer;
@@ -284,6 +285,7 @@ public class ItemInfo {
});
API.addOption(new ItemPanelDumper("tools.dump.itempanel"));
API.addOption(new HandlerDumper("tools.dump.handlers"));
API.addOption(new RecipeDumper("tools.dump.recipes"));
}
@SuppressWarnings("unchecked")
@@ -333,12 +335,6 @@ public class ItemInfo {
}
private static void addVanillaBlockProperties() {
API.setOverrideName(new ItemStack(Blocks.flowing_water), "Water Source");
API.setOverrideName(new ItemStack(Blocks.water), "Water Still");
API.setOverrideName(new ItemStack(Blocks.flowing_lava), "Lava Source");
API.setOverrideName(new ItemStack(Blocks.lava), "Lava Still");
API.setOverrideName(new ItemStack(Blocks.end_portal), "End Portal");
API.setOverrideName(new ItemStack(Blocks.end_portal_frame), "End Portal Frame");
API.hideItem(new ItemStack(Blocks.double_stone_slab, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Blocks.double_wooden_slab, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Blocks.carrots));
@@ -343,7 +343,6 @@ public abstract class ShortcutInputHandler {
if (handlerRef != null) {
final GuiFavoriteButton button = new GuiFavoriteButton(handlerRef, 0, 0);
button.saveRecipeInBookmark();
return true;
}
return true;
@@ -0,0 +1,54 @@
package codechicken.nei.config;
import java.util.Collections;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.recipe.RecipeJsonWriter;
public class RecipeDumper extends DataDumper {
public RecipeDumper(String name) {
super(name);
}
@Override
public String[] header() {
return new String[0];
}
@Override
public Iterable<String[]> dump(int mode) {
return Collections.emptyList();
}
@Override
public String renderName() {
return translateN(name);
}
public Rectangle4i separateButtonSize() {
return dumpButtonSize();
}
public Rectangle4i combinedButtonSize() {
return modeButtonSize();
}
@Override
public void draw(int mousex, int mousey, float frame) {
drawPrefix();
drawButton(mousex, mousey, combinedButtonSize(), translateN(name + ".combined"));
drawButton(mousex, mousey, separateButtonSize(), translateN(name + ".separate"));
}
@Override
public void mouseClicked(int mousex, int mousey, int button) {
final boolean combined = combinedButtonSize().contains(mousex, mousey);
if (combined || separateButtonSize().contains(mousex, mousey)) {
NEIClientUtils.playClickSound();
RecipeJsonWriter.dumpAll(!combined);
}
}
}
@@ -501,13 +501,20 @@ public class GuiContainerManager {
public boolean lastKeyTyped(int keyID, char keyChar) {
if (keyID == 1) return false;
// hotkeys go before lastKeyTyped, otherwise a third-party handler that consumes every key blocks them
if (handleHotkeys()) return true;
for (IContainerInputHandler inputhander : inputHandlers)
if (inputhander.lastKeyTyped(window, keyChar, keyID)) return true;
return onHotkeyPressed();
return handleScreenHotkeys();
}
public boolean onHotkeyPressed() {
return handleHotkeys() || handleScreenHotkeys();
}
private boolean handleHotkeys() {
if (window instanceof IGuiHotkeyListener && ((IGuiHotkeyListener) window).onHotkeyPressed()) {
return true;
@@ -519,6 +526,10 @@ public class GuiContainerManager {
}
}
return false;
}
private boolean handleScreenHotkeys() {
return window instanceof IGuiHotkeyListener && ((IGuiHotkeyListener) window).onScreenHotkeyPressed();
}
@@ -682,6 +682,10 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
return this.handlerPages.getRecipeIndices();
}
public List<Integer> getFilteredRecipes() {
return this.handler.getFilteredRecipes();
}
@Override
public void keyTyped(char c, int i) {
@@ -0,0 +1,303 @@
package codechicken.nei.recipe;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import net.minecraft.event.ClickEvent;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.EnumChatFormatting;
import com.google.common.base.Stopwatch;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import codechicken.core.CommonUtils;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.config.GuiItemIconDumper;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.Recipe.RecipeIngredient;
import codechicken.nei.util.NBTJson;
import cpw.mods.fml.relauncher.ReflectionHelper;
/**
* Writes recipes as JSON, one object per line, with stacks in the format of {@link StackInfo#itemStackToNBT}.
*/
public class RecipeJsonWriter {
protected static Field mEUt = null;
protected static Field mDuration = null;
protected static Field mRecipe = null;
static {
try {
final ClassLoader loader = RecipeJsonWriter.class.getClassLoader();
final Class<?> gtRecipe = ReflectionHelper
.getClass(loader, "gregtech.api.util.GTRecipe", "gregtech.api.util.GT_Recipe");
final Class<?> cachedDefaultRecipe = ReflectionHelper.getClass(
loader,
"gregtech.nei.GTNEIDefaultHandler$CachedDefaultRecipe",
"gregtech.nei.GT_NEI_DefaultHandler$CachedDefaultRecipe");
mEUt = gtRecipe.getField("mEUt");
mDuration = gtRecipe.getField("mDuration");
mRecipe = cachedDefaultRecipe.getField("mRecipe");
} catch (Exception ignored) {}
}
private static final File DUMP_DIR = new File(CommonUtils.getMinecraftDir(), "dumps/recipes");
// display names by stack NBT without Count, built once per dump
private final Map<String, String> names = new HashMap<>();
private int dumped = 0;
private int skipped = 0;
public static void dump(IRecipeHandler handler, List<Integer> recipeIndices) {
final RecipeJsonWriter dumper = new RecipeJsonWriter();
final File file = new File(DUMP_DIR, fileName(handler) + ".jsonl");
try {
final Stopwatch stopwatch = Stopwatch.createStarted();
dumper.writeFile(file, Collections.singletonList(handler), h -> recipeIndices);
NEIClientConfig.logger.info("Writing " + dumper.dumped + " recipes took " + stopwatch.stop());
dumper.printDumped(file);
} catch (Exception e) {
printFailed(e);
}
}
/**
* Loads all recipes of every crafting handler and writes them either all to {@code dumps/recipes.jsonl} or each
* handler to its own file in {@code dumps/recipes}.
*/
public static void dumpAll(boolean separate) {
final RecipeJsonWriter dumper = new RecipeJsonWriter();
try {
final Stopwatch stopwatch = Stopwatch.createStarted();
final List<ICraftingHandler> handlers = GuiCraftingRecipe.getCraftingHandlers("all");
NEIClientConfig.logger.info("Loading " + handlers.size() + " recipe handlers took " + stopwatch.stop());
stopwatch.reset().start();
if (separate) {
if (DUMP_DIR.exists()) {
for (File f : DUMP_DIR.listFiles()) if (f.isFile()) f.delete();
} else DUMP_DIR.mkdirs();
for (ICraftingHandler handler : handlers) {
final String name = fileName(handler);
File file = new File(DUMP_DIR, name + ".jsonl");
for (int i = 2; file.exists(); i++) file = new File(DUMP_DIR, name + '_' + i + ".jsonl");
dumper.writeFile(file, Collections.singletonList(handler), RecipeJsonWriter::filteredRecipes);
}
NEIClientConfig.logger.info("Writing " + dumper.dumped + " recipes took " + stopwatch.stop());
dumper.printDumped(DUMP_DIR);
} else {
final File file = new File(CommonUtils.getMinecraftDir(), "dumps/recipes.jsonl");
dumper.writeFile(file, handlers, RecipeJsonWriter::filteredRecipes);
NEIClientConfig.logger.info("Writing " + dumper.dumped + " recipes took " + stopwatch.stop());
dumper.printDumped(file);
}
} catch (Exception e) {
printFailed(e);
}
}
private static String fileName(IRecipeHandler handler) {
return GuiItemIconDumper
.cleanFileName(EnumChatFormatting.getTextWithoutFormattingCodes(handler.getRecipeName()).trim());
}
private static List<Integer> filteredRecipes(IRecipeHandler handler) {
return new SearchRecipeHandler<>(handler).getFilteredRecipes();
}
private void writeFile(File file, List<? extends IRecipeHandler> handlers,
Function<IRecipeHandler, List<Integer>> recipeIndices) throws IOException {
file.getParentFile().mkdirs();
try (PrintWriter writer = new PrintWriter(file, StandardCharsets.UTF_8.name())) {
for (IRecipeHandler handler : handlers) {
write(writer, handler, recipeIndices.apply(handler));
}
}
}
private void printDumped(File file) {
final Path minecraftDir = CommonUtils.getMinecraftDir().getAbsoluteFile().toPath().normalize();
final String path = minecraftDir.relativize(file.getAbsoluteFile().toPath().normalize()).toString()
.replace('\\', '/');
final ChatComponentText chatLink = new ChatComponentText(path);
chatLink.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, file.getAbsolutePath()));
chatLink.getChatStyle().setUnderlined(true);
NEIClientUtils.printChatMessage(
new ChatComponentTranslation("nei.options.tools.dump.recipes.dumped", this.dumped, chatLink));
if (this.skipped > 0) {
NEIClientUtils.printChatMessage(
new ChatComponentTranslation("nei.options.tools.dump.recipes.skipped", this.skipped));
}
}
private static void printFailed(Exception e) {
NEIClientConfig.logger.error("Error dumping recipes", e);
NEIClientUtils.printChatMessage(
new ChatComponentTranslation("nei.options.tools.dump.recipes.failed", e.getMessage()));
}
private void write(PrintWriter writer, IRecipeHandler handler, List<Integer> recipeIndices) {
for (int recipeIndex : recipeIndices) {
final String line;
try {
line = recipeJson(handler, recipeIndex);
} catch (Exception e) {
NEIClientConfig.logger.warn("Skipping recipe {} of {}", recipeIndex, handler.getRecipeName(), e);
this.skipped++;
continue;
}
writer.println(line);
this.dumped++;
}
}
private String recipeJson(IRecipeHandler handler, int recipeIndex) throws IllegalAccessException {
final Recipe recipe = Recipe.of(handler, recipeIndex);
final JsonObject json = new JsonObject();
json.addProperty("handler", recipe.getHandlerName());
json.add("ingredients", slotsJson(recipe.getIngredients(), handler instanceof ShapedRecipeHandler));
json.add("results", slotsJson(recipe.getResults(), false));
final JsonObject gt = gtJson(handler, recipeIndex);
if (gt != null) {
json.add("gt", gt);
}
return NBTJson.toJson(json);
}
/**
* Each slot's shown stack, with {@code anyOf} listing every accepted stack. In a crafting grid, an ingredient's
* container item (an empty bucket, a damaged tool) goes under {@code returns}.
*/
private JsonArray slotsJson(List<RecipeIngredient> slots, boolean craftingGrid) {
final JsonArray array = new JsonArray();
for (RecipeIngredient slot : slots) {
final ItemStack stack = slot.getItemStack();
final JsonObject json = stackJson(stack);
if (json == null) {
continue;
}
if (slot.getChance() != PositionedStack.CHANCE_FULL) {
json.addProperty("chance", slot.getChance());
}
if (slot.getPermutations().size() > 1) {
final JsonArray anyOf = new JsonArray();
for (ItemStack permutation : slot.getPermutations()) {
final JsonObject option = stackJson(permutation);
if (option != null) {
option.remove("Count");
anyOf.add(option);
}
}
json.add("anyOf", anyOf);
}
if (craftingGrid) {
final JsonObject container = stackJson(containerItem(stack));
if (container != null) {
json.add("returns", container);
}
}
array.add(json);
}
return array;
}
private JsonObject stackJson(ItemStack stack) {
final NBTTagCompound nbTag = stack != null ? StackInfo.itemStackToNBT(stack) : null;
if (nbTag == null) {
return null;
}
final NBTBase count = nbTag.getTag("Count");
nbTag.removeTag("Count");
final String name = this.names.computeIfAbsent(
nbTag.toString(),
key -> EnumChatFormatting
.getTextWithoutFormattingCodes(GuiContainerManager.itemDisplayNameShort(stack)));
if (count != null) {
nbTag.setTag("Count", count);
}
final JsonObject json = NBTJson.toJsonObject(nbTag).getAsJsonObject();
json.addProperty("name", name);
return json;
}
private static ItemStack containerItem(ItemStack stack) {
if (!stack.getItem().hasContainerItem(stack)) {
return null;
}
final boolean isPausedItemDamageSound = StackInfo.isPausedItemDamageSound();
try {
StackInfo.pauseItemDamageSound(true);
return stack.getItem().getContainerItem(stack);
} finally {
StackInfo.pauseItemDamageSound(isPausedItemDamageSound);
}
}
private static JsonObject gtJson(IRecipeHandler handler, int recipeIndex) throws IllegalAccessException {
if (mRecipe == null || !(handler instanceof TemplateRecipeHandler templateHandler)
|| recipeIndex >= templateHandler.arecipes.size()) {
return null;
}
final Object cachedRecipe = templateHandler.arecipes.get(recipeIndex);
if (!mRecipe.getDeclaringClass().isInstance(cachedRecipe)) {
return null;
}
final Object gtRecipe = mRecipe.get(cachedRecipe);
final long eut = ((Number) mEUt.get(gtRecipe)).longValue();
final long duration = ((Number) mDuration.get(gtRecipe)).longValue();
final JsonObject gt = new JsonObject();
gt.addProperty("eut", eut);
gt.addProperty("durationTicks", duration);
gt.addProperty("totalEU", eut * duration);
return gt;
}
}
@@ -3,11 +3,9 @@ package codechicken.nei.recipe.chain;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
@@ -23,7 +21,6 @@ import codechicken.nei.ItemSorter;
import codechicken.nei.ItemStackAmount;
import codechicken.nei.ItemsTooltipLineHandler;
import codechicken.nei.ItemsTooltipLineHandler.AmountRenderer;
import codechicken.nei.ItemsTooltipLineHandler.StacksAmountRenderer;
import codechicken.nei.ItemsTooltipLineHandler.TotalAmountRenderer;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
@@ -39,25 +36,6 @@ import codechicken.nei.recipe.StackInfo;
public class RecipeChainTooltipLineHandler extends CompositeTooltipLineHandler {
protected static class MissingStacksAmountRenderer extends StacksAmountRenderer {
protected static final int MISSING_COLOR = 0xFF5555;
protected final Set<NBTTagCompound> missing;
private final Map<ItemStack, Boolean> cache = new IdentityHashMap<>();
public MissingStacksAmountRenderer(Set<NBTTagCompound> missing) {
this.missing = missing;
}
@Override
protected int getColor(ItemStack stack) {
return this.cache.computeIfAbsent(stack, key -> this.missing.contains(StackInfo.itemStackToNBT(key, false)))
? MISSING_COLOR
: super.getColor(stack);
}
}
protected static class HandlerIconRenderer extends TotalAmountRenderer {
protected static final int ICON_SIZE = 16;
@@ -285,35 +263,15 @@ public class RecipeChainTooltipLineHandler extends CompositeTooltipLineHandler {
}
}
final Set<NBTTagCompound> missing = new HashSet<>();
if (this.lastShiftKey) {
for (ItemStack stack : inputs) {
missing.add(StackInfo.itemStackToNBT(stack, false));
}
}
// items with a shortage are already in the inputs list, holding the missing amount instead of the required one
final List<ItemStack> covered = new ArrayList<>();
for (ItemStack stack : available) {
if (!missing.contains(StackInfo.itemStackToNBT(stack, false))) {
covered.add(stack);
}
}
final Comparator<ItemStack> comparator = Comparator
.comparing((ItemStack stack) -> StackInfo.getFluid(stack) != null)
.thenComparingInt(stack -> -1 * stack.stackSize).thenComparing(ItemSorter.instance);
inputs.sort(comparator);
covered.sort(comparator);
available.sort(comparator);
outputs.sort(comparator);
remainder.sort(comparator);
// missing items stay on top of the list
inputs.addAll(covered);
if (this.lastShiftKey) {
outputs.addAll(remainder);
}
@@ -332,12 +290,21 @@ public class RecipeChainTooltipLineHandler extends CompositeTooltipLineHandler {
EnumChatFormatting.BLUE,
new HandlerIconRenderer(craftingHandlers));
if (this.lastShiftKey) {
addLine(
NEIClientUtils.translate("bookmark.crafting_chain.missing"),
inputs,
true,
EnumChatFormatting.RED,
new TotalAmountRenderer());
}
addLine(
NEIClientUtils.translate("bookmark.crafting_chain.input"),
inputs,
this.lastShiftKey ? available : inputs,
this.lastShiftKey,
EnumChatFormatting.YELLOW,
this.lastShiftKey ? new MissingStacksAmountRenderer(missing) : new TotalAmountRenderer());
new TotalAmountRenderer());
}
protected static void putHandlerInfo(Map<NBTTagCompound, HandlerInfo> handlers, ItemStack stack,
@@ -41,6 +41,7 @@ import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.HandlerInfo;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.RecipeHandlerRef;
import codechicken.nei.recipe.RecipeJsonWriter;
import codechicken.nei.recipe.ShapedRecipeHandler;
import codechicken.nei.recipe.TemplateRecipeHandler;
import codechicken.nei.recipe.TemplateRecipeHandler.RecipeTransferRect;
@@ -272,6 +273,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
API.addRecipeFilter(() -> this.duplicatesOnly ? this::isDuplicate : null);
}
y = addExportWidget("ExportRecipes", y);
this.h = 10 + LINE_HEIGHT + y;
this.container.h = this.h - INLINE_PADDING * 2 - LINE_HEIGHT;
}
@@ -332,6 +335,45 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
return y + value.h + 1;
}
private int addExportWidget(String key, int y) {
final LabelWidget label = new LabelWidget(0x888888, false) {
@Override
public List<String> handleTooltip(int mx, int my, List<String> tooltip) {
if (contains(mx, my)) {
super.handleTooltip(mx, my, tooltip);
tooltip.add(
EnumChatFormatting.GRAY + NEIClientUtils.translate("debug.RecipeHandler.export.tooltip"));
}
return tooltip;
}
};
final Button value = new Button(NEIClientUtils.translate("debug.RecipeHandler.export")) {
@Override
public boolean onButtonPress(boolean rightclick) {
if (rightclick || !(NEIClientUtils.getGuiContainer() instanceof GuiRecipe<?>recipe)) return false;
RecipeJsonWriter.dump(recipe.getHandler(), recipe.getFilteredRecipes());
return true;
}
};
value.w = 58;
value.h = 16;
value.y = label.y = y;
value.x = this.w - INLINE_PADDING * 2 - value.w - 1;
label.w = value.x;
label.updateValue(NEIClientUtils.translate(TOOLTIP_PREFIX + key));
this.container.addWidget(label);
this.container.addWidget(value);
return y + value.h + 1;
}
private int addOverrideInfoWidget(String key, int y) {
final LabelWidget label = new LabelWidget(0x888888, false);
final LabelWidget value = new LabelWidget(0xffffff, true);
@@ -48,6 +48,7 @@ nei.bookmark.recipe.toggle_collapse=Toggle Collapse/Expand
nei.bookmark.recipe.chat_link=Send Recipe to Chat
nei.bookmark.crafting_chain=Crafting Chain
nei.bookmark.crafting_chain.input=Ingredients
nei.bookmark.crafting_chain.missing=Missing Items
nei.bookmark.crafting_chain.needed=Required Crafts
nei.bookmark.tree.title=Crafting Tree
nei.bookmark.tree.empty=No crafting chain to display
@@ -611,6 +612,12 @@ nei.options.tools.dump.handlers=NEI Handlers
nei.options.tools.dump.handlers.dumped=handlers were dumped to %s
nei.options.tools.dump.handlers.mode.0=CSV
nei.options.tools.dump.handlers.mode.1=Json
nei.options.tools.dump.recipes=All Handler Recipes
nei.options.tools.dump.recipes.combined=Combined
nei.options.tools.dump.recipes.separate=Separate
nei.options.tools.dump.recipes.dumped=%s recipes were dumped to %s
nei.options.tools.dump.recipes.skipped=%s recipes threw an error and were skipped, see the log
nei.options.tools.dump.recipes.failed=Failed to dump recipes: %s
nei.debug.RecipeHandler.title=Debug Recipe Handler
nei.debug.RecipeHandler.copy=Copy
@@ -632,6 +639,9 @@ nei.debug.RecipeHandler.DuplicatesOnly=Duplicates Only
nei.debug.RecipeHandler.AllowOverflowY=Allow Overflow Y
nei.debug.RecipeHandler.AllowOverflowX=Allow Overflow X
nei.debug.RecipeHandler.Override=Override
nei.debug.RecipeHandler.ExportRecipes=Export Recipes
nei.debug.RecipeHandler.export=Export
nei.debug.RecipeHandler.export.tooltip=Exports the currently visible recipes to JSON.
nei.debug.RecipeHandler.checkbox.on=On
nei.debug.RecipeHandler.checkbox.off=Off
nei.debug.RecipeHandler.yes=Yes
@@ -2,12 +2,10 @@ package codechicken.nei;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -20,20 +18,16 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import codechicken.nei.api.IConfigureNEI;
class PluginLoaderTest {
@ParameterizedTest
@ValueSource(booleans = { false, true })
void loadsPluginsAndLogsFailuresWithTheGameClassLoader(boolean parallel) throws Exception {
@Test
void loadsPluginsInParallelAndLogsFailuresWithTheGameClassLoader() throws Exception {
ClassLoader workerClassLoader = new ClassLoader(null) {};
Set<Thread> workers = ConcurrentHashMap.newKeySet();
ForkJoinPool pool = new ForkJoinPool(2, owner -> {
@@ -57,8 +51,7 @@ class PluginLoaderTest {
List<IConfigureNEI> loaded = new CopyOnWriteArrayList<>();
try {
pool.submit(() -> PluginLoader.load(parallel ? plugins.parallelStream() : plugins.stream(), loaded, logger))
.get(10, TimeUnit.SECONDS);
pool.submit(() -> PluginLoader.load(plugins, true, loaded, logger)).get(10, TimeUnit.SECONDS);
assertEquals(16, loaded.size());
verify(logger, times(32)).error(eq("Failed to Load {}"), anyString(), any(Throwable.class));
@@ -68,26 +61,6 @@ class PluginLoaderTest {
}
}
@Test
void restoresTheClassLoaderEvenIfErrorLoggingThrows() {
Thread thread = Thread.currentThread();
ClassLoader previousClassLoader = thread.getContextClassLoader();
ClassLoader workerClassLoader = new ClassLoader(null) {};
Logger logger = mock(Logger.class);
doThrow(new LinkageError("Logging failed")).when(logger)
.error(eq("Failed to Load {}"), anyString(), any(Throwable.class));
try {
thread.setContextClassLoader(workerClassLoader);
assertThrows(
LinkageError.class,
() -> PluginLoader.load(Stream.of(ConfigurationFailurePlugin.class), new ArrayList<>(), logger));
assertSame(workerClassLoader, thread.getContextClassLoader());
} finally {
thread.setContextClassLoader(previousClassLoader);
}
}
public static class HealthyPlugin implements IConfigureNEI {
public HealthyPlugin() {