Compare commits

...
10 Commits
42 changed files with 884 additions and 222 deletions

No files matched your search

+2 -2
View File
@@ -3,9 +3,9 @@ name: Build and test
on:
pull_request:
branches: [ master, main ]
branches: [ master, main, release/** ]
push:
branches: [ master, main ]
branches: [ master, main, release/** ]
jobs:
build-and-test:
+2 -1
View File
@@ -24,6 +24,7 @@ DASH : '-' ;
RECIPE_INGREDIENTS : '<&' | '<' ;
RECIPE_RESULT : '>&' | '>' ;
RECIPE_OTHERS : '^&' | '^' ;
RECIPE_TEXT : '~' ;
OR : '|' ;
LEFT_BRACKET : '{' ;
@@ -33,7 +34,7 @@ SPACE : ' ' ;
ESCAPED_SYMBOL : '\\' . ;
PREFIX : CLEAN_SYMBOL {searchParser.hasRedefinedPrefix(getText().charAt(0))}? ;
CLEAN_SYMBOL : ~[-<>^{}|/\\ "] ;
CLEAN_SYMBOL : ~[-<>^~{}|/\\ "] ;
mode REGEX;
+1
View File
@@ -19,6 +19,7 @@ recipeClauseExpression
: ingredientsPrefix=RECIPE_INGREDIENTS searchExpression[0, $ingredientsPrefix.getText().length() > 1]
| resultPrefix=RECIPE_RESULT searchExpression[1, $resultPrefix.getText().length() > 1]
| othersPrefix=RECIPE_OTHERS searchExpression[2, $othersPrefix.getText().length() > 1]
| RECIPE_TEXT searchExpression[4, false]
| searchExpression[3, false]
;
@@ -8,6 +8,7 @@ import org.lwjgl.opengl.GL11;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
@@ -55,12 +56,14 @@ public abstract class AbstractSubpanel<T extends ItemsGrid<? extends ItemsGridSl
}
protected void updateLinePadding() {
GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
final INEIGuiHandler[] handlers = GuiInfo.getGuiHandlersSnapshot();
final Rectangle4i rect = new Rectangle4i(this.x, this.y - 1, 10, 2);
this.linePaddingStart = 0;
while (GuiInfo
.hideItemPanelSlot(guiContainer, new Rectangle4i(this.x + this.linePaddingStart, this.y - 1, 10, 2))) {
while (this.linePaddingStart < this.w && GuiInfo.hideItemPanelSlot(guiContainer, rect, handlers)) {
this.linePaddingStart += 10;
rect.x += 10;
}
}
@@ -54,7 +54,10 @@ import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiUsageRecipe;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.RecipeHandlerRef;
import codechicken.nei.recipe.RecipeItemInputHandler;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.recipe.debug.DebugHandlerWidget;
import cpw.mods.fml.client.CustomModLoadingErrorDisplayException;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
@@ -444,6 +447,11 @@ public class ClientHandler {
if (event.world == mc.theWorld) {
NEIClientConfig.unloadWorld();
ItemMobSpawner.clearEntityReferences();
RecipeItemInputHandler.instance.clearTooltipCache();
RecipeHandlerRef.clearCache();
ItemPanels.itemPanel.craftablesPanel.clearGuiReferences();
DebugHandlerWidget.instance.clearGuiReferences();
NEIController.manager = null;
}
}
@@ -7,8 +7,11 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTBase.NBTPrimitive;
@@ -35,6 +38,7 @@ public class CollapsibleItems {
public ItemFilter filter;
public boolean expanded = false;
public String displayName = "";
public String unlocalizedName;
public void setFilter(String filter) {
this.filter = ItemStackFilterParser.parse(filter.trim());
@@ -46,15 +50,38 @@ public class CollapsibleItems {
this.guid = guid;
}
public String getDisplayName() {
if (this.unlocalizedName != null && !this.unlocalizedName.isEmpty()) {
final String translated = StatCollector.translateToLocal(this.unlocalizedName);
if (!translated.equals(this.unlocalizedName)) {
return translated;
}
}
return this.displayName;
}
public boolean matches(ItemStack stack) {
return this.filter.matches(stack);
}
}
public static class ApiGroup {
private String unlocalizedName;
public ApiGroup setName(String unlocalizedName) {
this.unlocalizedName = unlocalizedName;
return this;
}
}
private static final String STATE_KEY = "collapsibleitems";
protected static File statesFile;
protected static final List<GroupItem> groups = new ArrayList<>();
protected static final List<Supplier<GroupItem>> apiGroups = new CopyOnWriteArrayList<>();
protected static final Map<ItemStack, Integer> cache = new ConcurrentHashMap<>();
private CollapsibleItems() {}
@@ -77,11 +104,57 @@ public class CollapsibleItems {
ClientHandler.loadSettingsFile(
"collapsibleitems.cfg",
lines -> parseFile(lines.collect(Collectors.toCollection(ArrayList::new))));
for (Supplier<GroupItem> apiGroup : CollapsibleItems.apiGroups) {
try {
addGroup(apiGroup.get());
} catch (Exception e) {
NEIClientConfig.logger.error("Failed to add API group", e);
}
}
}
loadStates();
}
public static ApiGroup registerGroup(String filter) {
final ApiGroup apiGroup = new ApiGroup();
CollapsibleItems.apiGroups.add(() -> {
GroupItem group = new GroupItem();
group.setFilter(filter);
group.unlocalizedName = apiGroup.unlocalizedName;
return group;
});
return apiGroup;
}
public static ApiGroup registerGroup(Iterable<ItemStack> items) {
final ApiGroup apiGroup = new ApiGroup();
final ItemStackSet filter = new ItemStackSet();
for (ItemStack stack : items) {
if (stack != null) filter.add(stack.copy());
}
if (filter.isEmpty()) return apiGroup;
final String key = filter.keys().stream()
.map(stack -> Item.itemRegistry.getNameForObject(stack.getItem()) + ":" + stack.getItemDamage())
.sorted().collect(Collectors.joining(","));
final String guid = UUID.nameUUIDFromBytes(key.getBytes()).toString();
CollapsibleItems.apiGroups.add(() -> {
GroupItem group = new GroupItem();
group.setFilter(filter, guid);
group.unlocalizedName = apiGroup.unlocalizedName;
return group;
});
return apiGroup;
}
private static void parseFile(List<String> itemStrings) {
final JsonParser parser = new JsonParser();
GroupItem group = new GroupItem();
@@ -92,17 +165,8 @@ public class CollapsibleItems {
if (itemStr.startsWith("; ")) {
JsonObject settings = parser.parse(itemStr.substring(2)).getAsJsonObject();
if (settings.get("displayName") != null) {
group.displayName = settings.get("displayName").getAsString();
}
if (settings.get("unlocalizedName") != null) {
String unlocalizedName = settings.get("unlocalizedName").getAsString();
String displayName = StatCollector.translateToLocal(unlocalizedName);
if (!displayName.equals(unlocalizedName)) {
group.displayName = displayName;
}
group.unlocalizedName = settings.get("unlocalizedName").getAsString();
}
if (settings.get("expanded") != null) {
@@ -176,7 +240,7 @@ public class CollapsibleItems {
public static String getDisplayName(int groupIndex) {
if (groupIndex < CollapsibleItems.groups.size()) {
return CollapsibleItems.groups.get(groupIndex).displayName;
return CollapsibleItems.groups.get(groupIndex).getDisplayName();
}
return null;
@@ -0,0 +1,188 @@
package codechicken.nei;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.function.Predicate;
import net.minecraft.client.gui.inventory.GuiContainer;
import codechicken.lib.vec.Rectangle4i;
final class GridOverlapScanner {
private static boolean scanRequested = true;
private static boolean scanFrame = true;
private static boolean wasShowTooltip = true;
private static WeakReference<GuiContainer> lastGui = new WeakReference<>(null);
private boolean invalidated = true;
private final Rectangle4i rect = new Rectangle4i();
private boolean[] checked = new boolean[0];
private int[] queue = new int[0];
private int tail;
private Predicate<Rectangle4i> isHidden;
private boolean[] hidden;
private int hiddenCount;
private int left;
private int top;
private int slotSize;
private int columns;
public static void requestScan() {
scanRequested = true;
}
public static void beginFrame(GuiContainer gui, boolean shouldShowTooltip) {
if (wasShowTooltip != shouldShowTooltip) {
scanRequested = true;
}
wasShowTooltip = shouldShowTooltip;
if (lastGui.get() != gui) {
lastGui = new WeakReference<>(gui);
scanRequested = true;
}
scanFrame = scanRequested;
scanRequested = false;
}
public static boolean isScanFrame() {
return scanFrame;
}
public void invalidate() {
this.invalidated = true;
}
public boolean shouldRefresh() {
final boolean refresh = this.invalidated || scanFrame;
this.invalidated = false;
return refresh;
}
public int scan(Predicate<Rectangle4i> isHidden, int left, int top, int slotSize, int rows, int columns,
boolean seedLeft, boolean seedRight, boolean[] hidden) {
final int size = rows * columns;
if (this.checked.length < size) {
this.checked = new boolean[size];
this.queue = new int[size];
} else {
Arrays.fill(this.checked, 0, size, false);
}
this.isHidden = isHidden;
this.hidden = hidden;
this.hiddenCount = 0;
this.tail = 0;
this.left = left;
this.top = top;
this.slotSize = slotSize;
this.columns = columns;
for (int r = 0; r < rows; r++) {
if (seedLeft) {
probe(r, 0);
}
if (seedRight) {
probe(r, columns - 1);
}
}
for (int head = 0; head < this.tail; head++) {
final int row = this.queue[head] / columns;
final int column = this.queue[head] % columns;
for (int r = Math.max(0, row - 1); r <= Math.min(rows - 1, row + 1); r++) {
for (int c = Math.max(0, column - 1); c <= Math.min(columns - 1, column + 1); c++) {
probe(r, c);
}
}
}
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
if (this.checked[r * columns + c]) {
continue;
}
int c1 = c;
while (c1 + 1 < columns && !this.checked[r * columns + c1 + 1]) {
c1++;
}
int r1 = r;
while (r1 + 1 < rows && isUnchecked(r1 + 1, c, c1)) {
r1++;
}
scanArea(r, r1, c, c1);
c = c1;
}
}
this.isHidden = null;
this.hidden = null;
return this.hiddenCount;
}
private void probe(int row, int column) {
final int idx = row * this.columns + column;
if (!this.checked[idx]) {
this.checked[idx] = true;
if (test(row, row, column, column)) {
this.hidden[idx] = true;
this.queue[this.tail++] = idx;
this.hiddenCount++;
}
}
}
private void scanArea(int r0, int r1, int c0, int c1) {
if (!test(r0, r1, c0, c1)) {
for (int r = r0; r <= r1; r++) {
Arrays.fill(this.checked, r * this.columns + c0, r * this.columns + c1 + 1, true);
}
} else if (r0 == r1 && c0 == c1) {
this.checked[r0 * this.columns + c0] = true;
this.hidden[r0 * this.columns + c0] = true;
this.hiddenCount++;
} else if (r1 - r0 >= c1 - c0) {
final int mid = (r0 + r1) / 2;
scanArea(r0, mid, c0, c1);
scanArea(mid + 1, r1, c0, c1);
} else {
final int mid = (c0 + c1) / 2;
scanArea(r0, r1, c0, mid);
scanArea(r0, r1, mid + 1, c1);
}
}
private boolean isUnchecked(int row, int c0, int c1) {
for (int c = c0; c <= c1; c++) {
if (this.checked[row * this.columns + c]) {
return false;
}
}
return true;
}
private boolean test(int r0, int r1, int c0, int c1) {
this.rect.set(
this.left + c0 * this.slotSize,
this.top + r0 * this.slotSize,
(c1 - c0 + 1) * this.slotSize,
(r1 - r0 + 1) * this.slotSize);
return this.isHidden.test(this.rect);
}
}
@@ -137,7 +137,11 @@ public class ItemCraftablesPanel
@Override
public void execute() {
pendingResult.set(generateCraftables(ItemCraftablesPanel.this.pendingSnapshot));
final CraftablesSnapshot snapshot = ItemCraftablesPanel.this.pendingSnapshot;
if (snapshot != null) {
pendingResult.set(generateCraftables(snapshot));
}
}
};
@@ -298,6 +302,11 @@ public class ItemCraftablesPanel
}
}
public void clearGuiReferences() {
this.lastGuiContainer = null;
this.pendingSnapshot = null;
}
private GuiContainer getGuiContainer() {
final GuiContainer firstGui = NEIClientUtils.getGuiContainer();
return (firstGui instanceof GuiRecipe<?>gui) ? gui.firstGui : firstGui;
+6 -1
View File
@@ -127,7 +127,12 @@ public class ItemZoom extends Widget implements IContainerInputHandler {
this.displayName = "Unnamed";
}
this.stack = StackInfo.loadFromNBT(StackInfo.itemStackToNBT(stack), 0);
// Copying the stack copies its whole NBT, so it is only done when the hovered stack changes
final boolean sameStack = this.stack != null && this.stack.isItemEqual(stack)
&& ItemStack.areItemStackTagsEqual(this.stack, stack);
if (!sameStack) {
this.stack = StackInfo.withAmount(stack, 0);
}
} else {
this.stack = null;
this.displayName = "";
+26 -36
View File
@@ -282,6 +282,8 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
protected boolean[] invalidSlotMap;
private final GridOverlapScanner overlapScanner = new GridOverlapScanner();
protected ScreenCapture screenCapture = null;
public ArrayList<ItemStack> getItems() {
@@ -359,12 +361,13 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
width = newWidth;
height = newHeight;
columns = width / SLOT_SIZE;
rows = height / SLOT_SIZE;
this.columns = newWidth / SLOT_SIZE;
this.rows = newHeight / SLOT_SIZE;
paddingLeft = (width % SLOT_SIZE) / 2;
if (changed) {
this.overlapScanner.invalidate();
onGridChanged();
}
}
@@ -405,55 +408,42 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
}
public void refresh(GuiContainer gui) {
final int gridRenderingCacheMode = getGridRenderingCacheMode();
if (gridRenderingCacheMode <= 0 || screenCapture == null || screenCapture.needRefresh(gridRenderingCacheMode)) {
if (this.overlapScanner.shouldRefresh()) {
updateGuiOverlapSlots(gui);
}
shiftPage(0);
}
protected void updateGuiOverlapSlots(GuiContainer gui) {
final boolean[] oldSlotMap = invalidSlotMap;
final int oldRows = rows;
final int oldColumns = columns;
final boolean[] oldSlotMap = this.invalidSlotMap;
final int size = this.rows * this.columns;
final boolean[] slotMap = new boolean[size];
invalidSlotMap = new boolean[rows * columns];
perPage = columns * rows;
this.perPage = size;
if (gui != null) {
if (gui != null && size > 0) {
final INEIGuiHandler[] handlers = GuiInfo.getGuiHandlersSnapshot();
if (NEIClientConfig.optimizeGuiOverlapComputation()) {
checkGuiOverlap(gui, handlers, 0, columns - 2, 1);
checkGuiOverlap(gui, handlers, columns - 1, 1, -1);
} else {
checkGuiOverlap(gui, handlers, 0, columns, 1);
}
final Rectangle4i origin = getSlotRect(0, 0);
this.perPage -= this.overlapScanner.scan(
rect -> GuiInfo.hideItemPanelSlot(gui, rect, handlers),
origin.x,
origin.y,
SLOT_SIZE,
this.rows,
this.columns,
origin.x + this.columns * SLOT_SIZE > gui.guiLeft,
origin.x < gui.guiLeft + gui.xSize,
slotMap);
}
if (oldRows != rows || oldColumns != columns || !Arrays.equals(oldSlotMap, invalidSlotMap)) {
this.invalidSlotMap = slotMap;
if (!Arrays.equals(oldSlotMap, slotMap)) {
onGridChanged();
}
}
private void checkGuiOverlap(GuiContainer gui, INEIGuiHandler[] handlers, int start, int end, int dir) {
boolean validColumn = false;
for (int c = start; c != end && (!NEIClientConfig.optimizeGuiOverlapComputation() || !validColumn); c += dir) {
validColumn = true;
for (int r = 0; r < rows; r++) {
final int idx = columns * r + c;
if (idx >= 0 && idx < invalidSlotMap.length
&& !invalidSlotMap[idx]
&& GuiInfo.hideItemPanelSlot(gui, getSlotRect(r, c), handlers)) {
invalidSlotMap[idx] = true;
validColumn = false;
perPage--;
}
}
}
}
public T getSlotMouseOver(int mousex, int mousey) {
if (!contains(mousex, mousey)) {
return null;
@@ -388,6 +388,8 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
public static void layout(GuiContainer gui) {
GridOverlapScanner.beginFrame(gui, GuiContainerManager.shouldShowTooltip(gui));
VisiblityData visiblity = new VisiblityData();
visiblity.showNEI = !isHidden();
visiblity.showBookmarkPanel = !isBookmarkPanelHidden();
@@ -821,6 +823,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
if (!isEnabled()) return;
GridOverlapScanner.requestScan();
AutoFocusWidget.instance.guiTick();
for (Widget widget : drawWidgets) widget.update();
@@ -498,10 +498,6 @@ public class NEIClientConfig {
tag.getTag("inventory.showItemQuantityWidget").setComment("Show Item Quantity Widget").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.showItemQuantityWidget", true));
tag.getTag("inventory.optimize_gui_overlap_computation").setComment("Optimize computation for GUI overlap")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.optimize_gui_overlap_computation", true));
tag.getTag("inventory.autocrafting").setComment("Autocrafting").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.autocrafting", true));
@@ -1160,10 +1156,6 @@ public class NEIClientConfig {
return getBooleanSetting("inventory.bookmarks.craftingTreeZoomWithoutModifier");
}
public static boolean optimizeGuiOverlapComputation() {
return getBooleanSetting("inventory.optimize_gui_overlap_computation");
}
public static boolean showCycledIngredientsTooltip() {
return getBooleanSetting("inventory.guirecipe.cycledIngredientsTooltip");
}
+31 -20
View File
@@ -29,6 +29,9 @@ public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ?
protected T grid;
private int headerPaddingLeft;
private int headerPaddingRight;
public ArrayList<ItemStack> getItems() {
return this.grid.getItems();
}
@@ -105,26 +108,15 @@ public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ?
protected int resizeHeader(GuiContainer gui) {
final int BUTTON_SIZE = 16;
int paddingLeft = 0;
int paddingRight = 0;
while (paddingLeft < w && GuiInfo.hideItemPanelSlot(
gui,
new Rectangle4i(x + paddingLeft, y, ItemsGrid.SLOT_SIZE, ItemsGrid.SLOT_SIZE))) {
paddingLeft += ItemsGrid.SLOT_SIZE;
if (GridOverlapScanner.isScanFrame()) {
updateHeaderPadding(gui);
}
while (paddingRight < w && GuiInfo.hideItemPanelSlot(
gui,
new Rectangle4i(
x + w - paddingRight - ItemsGrid.SLOT_SIZE,
y,
ItemsGrid.SLOT_SIZE,
ItemsGrid.SLOT_SIZE))) {
paddingRight += ItemsGrid.SLOT_SIZE;
}
final int paddingLeft = this.headerPaddingLeft;
final int paddingRight = this.headerPaddingRight;
if (paddingLeft + paddingRight >= w) {
if (paddingLeft + paddingRight >= this.w) {
return 0;
}
@@ -132,16 +124,35 @@ public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ?
pagePrev.h = pageNext.h = BUTTON_SIZE;
pagePrev.y = pageNext.y = y;
pagePrev.x = x + paddingLeft;
pageNext.x = x + w - pageNext.w - paddingRight;
pagePrev.x = this.x + paddingLeft;
pageNext.x = this.x + this.w - pageNext.w - paddingRight;
pageLabel.x = x + paddingLeft + (w - paddingLeft - paddingRight) / 2;
pageLabel.y = y + 5;
pageLabel.x = this.x + paddingLeft + (this.w - paddingLeft - paddingRight) / 2;
pageLabel.y = this.y + 5;
pageLabel.text = getLabelText();
return BUTTON_SIZE + 2;
}
private void updateHeaderPadding(GuiContainer gui) {
final INEIGuiHandler[] handlers = GuiInfo.getGuiHandlersSnapshot();
final Rectangle4i slot = new Rectangle4i(this.x, this.y, ItemsGrid.SLOT_SIZE, ItemsGrid.SLOT_SIZE);
this.headerPaddingLeft = 0;
this.headerPaddingRight = 0;
while (this.headerPaddingLeft < this.w && GuiInfo.hideItemPanelSlot(gui, slot, handlers)) {
this.headerPaddingLeft += ItemsGrid.SLOT_SIZE;
slot.x += ItemsGrid.SLOT_SIZE;
}
slot.x = this.x + this.w - ItemsGrid.SLOT_SIZE;
while (this.headerPaddingRight < this.w && GuiInfo.hideItemPanelSlot(gui, slot, handlers)) {
this.headerPaddingRight += ItemsGrid.SLOT_SIZE;
slot.x -= ItemsGrid.SLOT_SIZE;
}
}
protected abstract int resizeFooter(GuiContainer gui);
public void setVisible() {
@@ -88,23 +88,20 @@ public class PositionedStack implements Cloneable {
return this.acceptsLabel;
}
public PositionedStack setBadges(List<Badge> badges) {
public void setBadges(List<Badge> badges) {
this.badges = badges;
return this;
}
public List<Badge> getBadges() {
return this.badges;
}
public PositionedStack setTooltip(List<String> tooltip) {
public void setTooltip(List<String> tooltip) {
this.tooltip = tooltip == null ? null : item -> tooltip;
return this;
}
public PositionedStack setTooltipProvider(Function<ItemStack, List<String>> provider) {
public void setTooltipProvider(Function<ItemStack, List<String>> provider) {
this.tooltip = provider;
return this;
}
public List<String> getTooltip() {
@@ -115,9 +112,8 @@ public class PositionedStack implements Cloneable {
return this.chance;
}
public PositionedStack setChance(int chance) {
public void setChance(int chance) {
this.chance = chance;
return this;
}
public PositionedStack copy() {
@@ -58,7 +58,9 @@ public class SearchTextFormatter implements TextFormatter {
int startIndex = 0;
for (SearchToken token : searchParser.splitSearchText(contextPart[1])) {
final String prefixes = contextPart[0].startsWith("~") ? "" : searchParser.getPrefixes();
for (SearchToken token : searchParser.splitSearchText(contextPart[1], prefixes)) {
formattedText.append(contextPart[1].substring(startIndex, token.start));
EnumChatFormatting tokenColor = EnumChatFormatting.RESET;
@@ -5,6 +5,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import net.minecraft.client.Minecraft;
@@ -21,6 +22,7 @@ import codechicken.nei.filter.AllMultiRecipeFilter;
import codechicken.nei.filter.AnyMultiRecipeFilter;
import codechicken.nei.filter.RecipeFilter;
import codechicken.nei.filter.RecipeFilter.FilterContext;
import codechicken.nei.filter.RecipeTextFilter;
import codechicken.nei.search.ItemFilterVisitor;
import codechicken.nei.search.RecipeFilterVisitor;
import codechicken.nei.search.SearchExpressionUtils;
@@ -207,7 +209,8 @@ public class SearchTokenParser {
for (String[] contextQuery : splitByDelimiters(subQuery[1], contextTokens, false)) {
if (contextQuery[1].isEmpty() || contextQuery[0].startsWith(">")
|| contextQuery[0].startsWith("^")) {
|| contextQuery[0].startsWith("^")
|| contextQuery[0].startsWith("~")) {
continue;
}
@@ -286,6 +289,7 @@ public class SearchTokenParser {
}
final List<IRecipeFilter> tokens = new ArrayList<>();
final boolean recipeText = contextQuery[0].startsWith("~");
FilterContext context = FilterContext.ANY;
if (!contextQuery[0].isEmpty()) {
@@ -293,12 +297,26 @@ public class SearchTokenParser {
contextQuery[0] = contextQuery[0].substring(1);
}
for (SearchToken token : splitSearchText(contextQuery[0] + contextQuery[1])) {
final ItemFilter result = token.getFilter(this);
if (result != null) {
tokens.add(
new RecipeFilter(context, token.ignore == null || token.ignore != '!', result));
for (SearchToken token : splitSearchText(
contextQuery[0] + contextQuery[1],
recipeText ? "" : getPrefixes())) {
if (recipeText) {
final IRecipeFilter text = recipeTextFilter(token);
if (text != null) {
tokens.add(text);
}
} else {
final ItemFilter result = token.getFilter(this);
if (result != null) {
tokens.add(
new RecipeFilter(
context,
token.ignore == null || token.ignore != '!',
result));
}
}
}
if (tokens.size() == 1) {
@@ -338,14 +356,31 @@ public class SearchTokenParser {
}
private static IRecipeFilter recipeTextFilter(SearchToken token) {
if (token.rawText.isEmpty()) return null;
final List<Predicate<List<String>>> words = new ArrayList<>();
for (String word : token.words) {
final Pattern pattern = SearchField.getPattern(word);
if (pattern != null) words.add(RecipeTextFilter.matching(pattern));
}
if (words.isEmpty()) return null;
final Predicate<List<String>> text = lines -> words.stream().allMatch(word -> word.test(lines));
return new RecipeTextFilter(token.ignore == null ? text : text.negate());
}
public List<SearchToken> splitSearchText(String filterText) {
return splitSearchText(filterText, getPrefixes());
}
public List<SearchToken> splitSearchText(String filterText, String prefixes) {
if (filterText.isEmpty()) {
return Collections.emptyList();
}
final List<SearchToken> tokens = new ArrayList<>();
final int spaceMode = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
final String prefixes = getPrefixes();
SearchToken lastToken = null;
int lastEnd = 0;
@@ -514,7 +549,7 @@ public class SearchTokenParser {
public String getRecipeContextTokens() {
// '^' is the start anchor and the negated class in regex mode
return NEIClientConfig.getIntSetting("inventory.search.patternMode") == 2 ? "<>" : "<>^";
return NEIClientConfig.getIntSetting("inventory.search.patternMode") == 2 ? "<>~" : "<>~^";
}
public char getRedefinedPrefix(char prefix) {
@@ -19,6 +19,7 @@ import org.lwjgl.input.Keyboard;
import com.google.common.collect.Sets;
import codechicken.nei.BookmarkContainerInfo;
import codechicken.nei.CollapsibleItems;
import codechicken.nei.ItemList;
import codechicken.nei.ItemSorter;
import codechicken.nei.ItemStackSet;
@@ -341,6 +342,30 @@ public class API {
SubsetWidget.addTag(tag);
}
/**
* Registers a group of items that is collapsed into a single entry in the item panel. Groups registered here have
* the lowest priority: an item that matches a preset or a collapsibleitems.cfg group stays there. They are active
* only while the Collapsible Items option is enabled. Must be called while plugins are loading.
*
* @param filter A search string for matching items that belong to this group. Also identifies the group when its
* expanded state is saved, so changing it resets the saved state.
* @return A handle to optionally set the name shown for the group
*/
public static CollapsibleItems.ApiGroup addCollapsibleGroup(String filter) {
return CollapsibleItems.registerGroup(filter);
}
/**
* Same as {@link #addCollapsibleGroup(String)}, but the group is given as a list of item stacks. The stacks
* identify the group when its expanded state is saved, so changing them resets the saved state.
*
* @param items Item stacks that belong to this group
* @return A handle to optionally set the name shown for the group
*/
public static CollapsibleItems.ApiGroup addCollapsibleGroup(Iterable<ItemStack> items) {
return CollapsibleItems.registerGroup(items);
}
@Deprecated
public static void addSearchProvider(ISearchProvider provider) {}
@@ -7,7 +7,6 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.ItemSorter;
@@ -132,7 +131,7 @@ public class BookmarkGridGenerator {
itemIndex++;
}
} else if (group.crafting != null && group.crafting.itemToRecipe.values().contains(bookmarkItem.recipeId)) {
} else if (group.crafting != null && group.crafting.recipeToItems.containsKey(bookmarkItem.recipeId)) {
absoluteSlotIndex = generateCollapsedRecipe(prevBookmarkItem, itemIndex, absoluteSlotIndex, borderGrid);
prevBookmarkItem = bookmarkItem;
@@ -218,8 +217,7 @@ public class BookmarkGridGenerator {
}
private List<Integer> getShadows(BookmarkGroup group, RecipeId recipeId) {
return group.crafting.itemToRecipe.entrySet().stream().filter(entry -> recipeId.equals(entry.getValue()))
.map(entry -> entry.getKey()).collect(Collectors.toList());
return new ArrayList<>(group.crafting.recipeToItems.getOrDefault(recipeId, Collections.emptyList()));
}
private int nextSlotIndex(int index, BookmarkItem previousMeta, BookmarkItem meta, BookmarkViewMode viewMode) {
@@ -111,6 +111,7 @@ public class RecipeChainDetails {
public final Map<Integer, BookmarkChainItem> calculatedItems = new HashMap<>();
public final Map<Integer, RecipeId> itemToRecipe = new HashMap<>();
public final Map<RecipeId, List<Integer>> recipeToItems = new HashMap<>();
public final Set<RecipeId> outputRecipes = new HashSet<>();
public final Set<RecipeId> recipeInMiddle = new HashSet<>();
@@ -124,6 +125,7 @@ public class RecipeChainDetails {
}
this.itemToRecipe.clear();
this.recipeToItems.clear();
this.outputRecipes.clear();
this.recipeInMiddle.clear();
this.calculatedItems.clear();
@@ -180,6 +182,10 @@ public class RecipeChainDetails {
}
for (Map.Entry<Integer, RecipeId> entry : this.itemToRecipe.entrySet()) {
this.recipeToItems.computeIfAbsent(entry.getValue(), recipeId -> new ArrayList<>()).add(entry.getKey());
}
for (Map.Entry<Integer, BookmarkItem> entry : chainItems.entrySet()) {
final int itemIndex = entry.getKey();
if (itemIndex >= 0 && this.calculatedItems.containsKey(itemIndex)) {
@@ -37,8 +37,8 @@ public class SortableItem {
&& (group.viewMode == BookmarkViewMode.TODO_LIST || group.crafting != null);
this.crossGroup = !group.collapsed && group.viewMode == BookmarkViewMode.TODO_LIST
&& bookmarkItem.type != BookmarkItemType.INGREDIENT;
this.isCollapsedRecipe = group.crafting != null && group.crafting.itemToRecipe.values().stream()
.anyMatch(recipeId -> this.bookmarkItem.equalsRecipe(recipeId, this.bookmarkItem.groupId));
this.isCollapsedRecipe = group.crafting != null && this.bookmarkItem.recipeId != null
&& group.crafting.recipeToItems.containsKey(this.bookmarkItem.recipeId);
this.update();
}
@@ -9,6 +9,7 @@ import codechicken.nei.api.IRecipeFilter;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.RecipeRole;
public class RecipeFilter implements IRecipeFilter {
@@ -47,17 +48,17 @@ public class RecipeFilter implements IRecipeFilter {
public boolean matches(IRecipeHandler handler, int recipeIndex) {
if ((this.context == FilterContext.ANY || this.context == FilterContext.INPUT)
&& matchPositionedStack(handler.getIngredientStacks(recipeIndex), this.anyMatch)) {
&& matchPositionedStack(handler.getSearchStacks(recipeIndex, RecipeRole.INPUT), this.anyMatch)) {
return this.anyMatch;
}
if ((this.context == FilterContext.ANY || this.context == FilterContext.OUTPUT)
&& matchPositionedStack(handler.getResultStacks(recipeIndex), this.anyMatch)) {
&& matchPositionedStack(handler.getSearchStacks(recipeIndex, RecipeRole.OUTPUT), this.anyMatch)) {
return this.anyMatch;
}
if ((this.context == FilterContext.ANY || this.context == FilterContext.AUXILIARY)
&& matchPositionedStack(handler.getAuxiliaryStacks(recipeIndex), this.anyMatch)) {
&& matchPositionedStack(handler.getSearchStacks(recipeIndex, RecipeRole.AUXILIARY), this.anyMatch)) {
return this.anyMatch;
}
@@ -0,0 +1,32 @@
package codechicken.nei.filter;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import codechicken.nei.api.IRecipeFilter;
import codechicken.nei.recipe.IRecipeHandler;
public class RecipeTextFilter implements IRecipeFilter {
private final Predicate<List<String>> lines;
public RecipeTextFilter(Predicate<List<String>> lines) {
this.lines = lines;
}
public static Predicate<List<String>> matching(Pattern pattern) {
return lines -> {
for (String line : lines) {
if (pattern.matcher(line).find()) return true;
}
return false;
};
}
@Override
public boolean matches(IRecipeHandler handler, int recipeIndex) {
final List<String> text = handler.getSearchText(recipeIndex);
return !text.isEmpty() && this.lines.test(text);
}
}
@@ -199,6 +199,10 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
NEIClientUtils.translate(
"recipe.search.tooltip.output",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + ">"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.text",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + "~"));
final int patternMode = NEIClientConfig.getIntSetting("inventory.search.patternMode");
@@ -121,6 +121,26 @@ public interface IRecipeHandler {
return getResultStack(recipe) != null ? getOtherStacks(recipe) : Collections.emptyList();
}
/**
* Override it to let the recipe search see stacks that the recipe doesn't draw and doesn't give to the overlay.
*
* @return The stacks of the role the recipe search looks at; called from the search threads.
*/
default List<PositionedStack> getSearchStacks(int recipe, RecipeRole role) {
return switch (role) {
case INPUT -> getIngredientStacks(recipe);
case OUTPUT -> getResultStacks(recipe);
case AUXILIARY -> getAuxiliaryStacks(recipe);
};
}
/**
* @return The text the recipe text search looks at, none by default; called from the search threads.
*/
default List<String> getSearchText(int recipe) {
return Collections.emptyList();
}
/**
* @param recipe The recipe index to get the group id for.
* @return An id shared by every recipe in this recipe's group, or {@code null} if this recipe isn't grouped.
@@ -19,12 +19,21 @@ import codechicken.nei.recipe.Recipe.RecipeId;
public class RecipeItemInputHandler implements IContainerInputHandler, IContainerTooltipHandler {
public static final RecipeItemInputHandler instance = new RecipeItemInputHandler();
protected RecipeTooltipLineHandler recipeTooltipLineHandler = null;
protected RecipeItemInputHandler() {
}
public static void load() {
RecipeItemInputHandler recipeHandler = new RecipeItemInputHandler();
GuiContainerManager.addInputHandler(recipeHandler);
GuiContainerManager.addTooltipHandler(recipeHandler);
GuiContainerManager.addInputHandler(instance);
GuiContainerManager.addTooltipHandler(instance);
}
public void clearTooltipCache() {
this.recipeTooltipLineHandler = null;
}
@Override
@@ -64,16 +73,17 @@ public class RecipeItemInputHandler implements IContainerInputHandler, IContaine
: null;
if (recipeId == null) {
recipeTooltipLineHandler = null;
} else if (recipeTooltipLineHandler == null || !recipeTooltipLineHandler.getRecipeId().equals(recipeId)) {
recipeTooltipLineHandler = new RecipeTooltipLineHandler(recipeId);
}
clearTooltipCache();
} else if (this.recipeTooltipLineHandler == null
|| !this.recipeTooltipLineHandler.getRecipeId().equals(recipeId)) {
this.recipeTooltipLineHandler = new RecipeTooltipLineHandler(recipeId);
}
if (recipeTooltipLineHandler != null) {
currenttip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(recipeTooltipLineHandler));
if (this.recipeTooltipLineHandler != null) {
currenttip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.recipeTooltipLineHandler));
}
} else {
recipeTooltipLineHandler = null;
clearTooltipCache();
}
return currenttip;
@@ -0,0 +1,7 @@
package codechicken.nei.recipe;
public enum RecipeRole {
INPUT,
OUTPUT,
AUXILIARY
}
@@ -35,7 +35,6 @@ public class RecipeTooltipLineHandler implements ITooltipLineHandler {
protected long lastUpdate = System.currentTimeMillis();
protected String recipeName = "";
protected GuiRecipe<?> gui = null;
protected RecipeHandlerRef handlerRef = null;
protected RecipeWidget widget = null;
protected RecipeId recipeId = null;
@@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
@@ -16,7 +17,7 @@ import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidContainerItem;
import codechicken.nei.ClientHandler;
import codechicken.nei.ItemStackMap;
import codechicken.nei.ItemStackMap.StackMetaKey;
import codechicken.nei.LRUCache;
import codechicken.nei.api.IStackStringifyHandler;
import codechicken.nei.api.ItemInfo;
@@ -31,7 +32,7 @@ public class StackInfo {
private static final FluidStack NULL_FLUID = new FluidStack(FluidRegistry.WATER, 0);
public static final List<IStackStringifyHandler> stackStringifyHandlers = new ArrayList<>();
private static final Map<String, HashMap<String, String[]>> guidfilters = new HashMap<>();
private static final ItemStackMap<String> guidcache = new ItemStackMap<>();
private static final Map<Item, Map<StackMetaKey, String>> guidcache = new ConcurrentHashMap<>();
private static final LRUCache<ItemStackKey, FluidStack> fluidcache = new LRUCache<>(200);
private static boolean isPausedItemDamageSound = false;
@@ -182,7 +183,9 @@ public class StackInfo {
}
public static String getItemStackGUID(ItemStack stack) {
String guid = guidcache.get(stack);
final Item stackItem = stack.getItem();
final Map<StackMetaKey, String> itemGuids = stackItem != null ? guidcache.get(stackItem) : null;
String guid = itemGuids != null ? itemGuids.get(new StackMetaKey(stack)) : null;
if (guid != null) {
return guid;
@@ -190,7 +193,7 @@ public class StackInfo {
final NBTTagCompound nbTag = itemStackToNBT(stack, false);
if (nbTag == null) {
if (nbTag == null || stack.getItem() == null) {
return "unknown";
}
@@ -239,16 +242,15 @@ public class StackInfo {
}
});
synchronized (guidcache) {
guidcache.put(stack, keys.toString());
}
guid = keys.toString();
} else {
synchronized (guidcache) {
guidcache.put(stack, NBTHelper.toString(nbTag));
}
guid = NBTHelper.toString(nbTag);
}
return guidcache.get(stack);
guidcache.computeIfAbsent(stack.getItem(), item -> new ConcurrentHashMap<>())
.put(new StackMetaKey(stack.copy()), guid);
return guid;
}
public static void loadGuidFilters() {
@@ -536,11 +536,7 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
@Override
public boolean handleKeyPress(int keyID, char keyChar) {
if (NEIClientConfig.getBooleanSetting("inventory.guirecipe.handlerInfo") && keyID == Keyboard.KEY_D
&& NEIClientUtils.shiftKey()) {
this.showWidget = !this.showWidget;
return true;
} else if (this.record != null) {
if (this.record != null) {
if (this.container.handleKeyPress(keyID, keyChar)) {
return true;
@@ -556,6 +552,13 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
@Override
public boolean onHotkeyPressed() {
if (NEIClientConfig.getBooleanSetting("inventory.guirecipe.handlerInfo") && Keyboard.isKeyDown(Keyboard.KEY_D)
&& NEIClientUtils.shiftKey()) {
this.showWidget = !this.showWidget;
return true;
}
return this.record != null && this.container.onHotkeyPressed();
}
@@ -733,6 +736,10 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
});
}
public void clearGuiReferences() {
this.hoveredRecipe = null;
}
public void loadHandlerInfoPatch() {
ClientHandler.loadSettingsFile("handlers.patch", lines -> {
@@ -10,6 +10,9 @@ import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import codechicken.nei.api.IStackStringifyHandler;
import codechicken.nei.item.ItemFluidDisplay;
import cpw.mods.fml.common.registry.GameRegistry;
@@ -22,6 +25,11 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
protected static Class<?> gtMetaGeneratedTool = null;
protected static Field playSound = null;
private static final Supplier<Item> AE2FC_FLUID_PACKET = Suppliers
.memoize(() -> GameRegistry.findItem("ae2fc", "fluid_packet"));
private static final Supplier<Item> AE2FC_FLUID_DROP = Suppliers
.memoize(() -> GameRegistry.findItem("ae2fc", "fluid_drop"));
static {
try {
final ClassLoader loader = GTFluidStackStringifyHandler.class.getClassLoader();
@@ -94,11 +102,11 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
return new FluidStack(fluid, 0);
}
} else if (item == GameRegistry.findItem("ae2fc", "fluid_packet")) {
} else if (item == AE2FC_FLUID_PACKET.get()) {
NBTTagCompound nbtTag = stack.getTagCompound();
return FluidStack.loadFluidStackFromNBT((NBTTagCompound) nbtTag.getTag("FluidStack"));
} else if (item == GameRegistry.findItem("ae2fc", "fluid_drop")) {
} else if (item == AE2FC_FLUID_DROP.get()) {
NBTTagCompound nbtTag = stack.getTagCompound();
Fluid fluid = FluidRegistry.getFluid(nbtTag.getString("Fluid").toLowerCase());
@@ -113,9 +121,9 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
@Override
public ItemStack normalizeRecipeQueryStack(ItemStack stack) {
final Item item = stack.getItem();
if (stack.getItem() == GameRegistry.findItem("ae2fc", "fluid_drop")
|| stack.getItem() == GameRegistry.findItem("ae2fc", "fluid_packet")) {
if (item == AE2FC_FLUID_DROP.get() || item == AE2FC_FLUID_PACKET.get()) {
final FluidStack fluidStack = getFluid(stack);
if (fluidStack != null) {
@@ -139,8 +147,7 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
@Override
public boolean isFluidDisplayItem(ItemStack stack) {
final Item item = stack.getItem();
return (itemFluidDisplay != null && itemFluidDisplay.isInstance(item))
|| item == GameRegistry.findItem("ae2fc", "fluid_packet");
return (itemFluidDisplay != null && itemFluidDisplay.isInstance(item)) || item == AE2FC_FLUID_PACKET.get();
}
}
@@ -3,7 +3,6 @@ package codechicken.nei.search;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Pattern;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
@@ -13,17 +12,11 @@ import codechicken.nei.ItemList.AllMultiItemFilter;
import codechicken.nei.ItemList.AnyMultiItemFilter;
import codechicken.nei.ItemList.NegatedItemFilter;
import codechicken.nei.ItemList.NothingItemFilter;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.SearchTokenParser;
import codechicken.nei.api.ItemFilter;
public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilter> {
private static final Pattern REGEX_ESCAPED_SPACE_PATTERN = Pattern.compile("([^\\\\](?:\\\\\\\\)+)?\\\\ ");
private static final Pattern ESCAPED_SYMBOL_PATTERN = Pattern.compile("\\\\(.)");
private static final Pattern ESCAPED_QUOTE_PATTERN = Pattern.compile("\\\\\"");
private static final Pattern ESCAPED_SPACE_PATTERN = Pattern.compile("\\\\ ");
public ItemFilterVisitor(SearchTokenParser searchParser) {
super(searchParser);
}
@@ -69,7 +62,7 @@ public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilte
@Override
public ItemFilter visitPrefixedExpression(SearchExpressionParser.PrefixedExpressionContext ctx) {
if (ctx.token() != null) {
final String cleanPattern = getCleanPattern(ctx.token());
final String cleanPattern = SearchExpressionUtils.getCleanPattern(ctx.token());
final SearchTokenParser.ISearchParserProvider provider = searchParser.getProvider(ctx.token().prefix);
if (cleanPattern == null || provider == null) {
return defaultResult();
@@ -81,7 +74,7 @@ public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilte
@Override
public ItemFilter visitToken(SearchExpressionParser.TokenContext ctx) {
final String cleanPattern = getCleanPattern(ctx);
final String cleanPattern = SearchExpressionUtils.getCleanPattern(ctx);
if (cleanPattern != null) {
return getAlwaysProvidersFilter(cleanPattern);
}
@@ -118,38 +111,6 @@ public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilte
return constructFilter(filters, AllMultiItemFilter::new);
}
private String getCleanPattern(SearchExpressionParser.TokenContext ctx) {
String cleanPattern = null;
if (ctx.plainText() != null) {
cleanPattern = Pattern.quote(
ESCAPED_SYMBOL_PATTERN.matcher(ctx.plainText().getText())
// Unescape everything in search expression
.replaceAll("$1"));
} else if (ctx.regex() != null) {
if (ctx.regex().REGEX_CONTENT() != null) {
cleanPattern = ctx.regex().REGEX_CONTENT().getSymbol().getText();
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanPattern = REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll("$1 ");
}
}
} else if (ctx.quoted() != null) {
if (ctx.quoted().QUOTED_CONTENT() != null) {
cleanPattern = ctx.quoted().QUOTED_CONTENT().getSymbol().getText();
// Unescape quotes
cleanPattern = ESCAPED_QUOTE_PATTERN.matcher(cleanPattern).replaceAll("\"");
cleanPattern = Pattern.quote(cleanPattern);
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanPattern = ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll(" ");
}
}
}
return cleanPattern;
}
private ItemFilter visitChildren(ParserRuleContext node, Function<List<ItemFilter>, ItemFilter> filterConstructor) {
if (node.children != null && !node.children.isEmpty()) {
// By default return any found rule child filter (there should be only one)
@@ -2,6 +2,7 @@ package codechicken.nei.search;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import codechicken.nei.ItemList.EverythingItemFilter;
import codechicken.nei.SearchTokenParser;
@@ -10,6 +11,7 @@ import codechicken.nei.api.ItemFilter;
import codechicken.nei.filter.AllMultiRecipeFilter;
import codechicken.nei.filter.RecipeFilter;
import codechicken.nei.filter.RecipeFilter.FilterContext;
import codechicken.nei.filter.RecipeTextFilter;
public class RecipeFilterVisitor extends AbstractSearchExpressionVisitor<IRecipeFilter> {
@@ -41,6 +43,10 @@ public class RecipeFilterVisitor extends AbstractSearchExpressionVisitor<IRecipe
if (ctx == null) {
return defaultResult();
}
if (ctx.type == 4) {
final Predicate<List<String>> text = new RecipeTextVisitor(this.searchParser).visitSearchExpression(ctx);
return text == null ? defaultResult() : new RecipeTextFilter(text);
}
final ItemFilter itemFilter = itemFilterVisitor.visitSearchExpression(ctx);
switch (ctx.type) {
case 0:
@@ -0,0 +1,86 @@
package codechicken.nei.search;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.RuleNode;
import codechicken.nei.SearchField;
import codechicken.nei.SearchTokenParser;
import codechicken.nei.filter.RecipeTextFilter;
public class RecipeTextVisitor extends AbstractSearchExpressionVisitor<Predicate<List<String>>> {
public RecipeTextVisitor(SearchTokenParser searchParser) {
super(searchParser);
}
@Override
public Predicate<List<String>> visitChildren(RuleNode node) {
if (!(node instanceof ParserRuleContext context) || context.children == null) return null;
for (ParseTree child : context.children) {
if (child instanceof RuleNode) return visit(child);
}
return null;
}
@Override
public Predicate<List<String>> visitOrExpression(SearchExpressionParser.OrExpressionContext ctx) {
final List<Predicate<List<String>>> parts = children(ctx);
return parts == null ? null : lines -> parts.stream().anyMatch(part -> part.test(lines));
}
@Override
public Predicate<List<String>> visitSequenceExpression(SearchExpressionParser.SequenceExpressionContext ctx) {
final List<Predicate<List<String>>> parts = children(ctx);
return parts == null ? null : lines -> parts.stream().allMatch(part -> part.test(lines));
}
@Override
public Predicate<List<String>> visitNegateExpression(SearchExpressionParser.NegateExpressionContext ctx) {
final Predicate<List<String>> inner = visitChildren(ctx);
return inner == null ? null : inner.negate();
}
@Override
public Predicate<List<String>> visitPrefixedExpression(SearchExpressionParser.PrefixedExpressionContext ctx) {
final String prefix = Pattern.quote(String.valueOf(ctx.prefix));
final String cleanPattern = ctx.token() != null ? SearchExpressionUtils.getCleanPattern(ctx.token()) : null;
return matcher(cleanPattern == null ? prefix : prefix + cleanPattern);
}
@Override
public Predicate<List<String>> visitToken(SearchExpressionParser.TokenContext ctx) {
return matcher(SearchExpressionUtils.getCleanPattern(ctx));
}
@Override
protected Predicate<List<String>> defaultResult() {
return null;
}
private static Predicate<List<String>> matcher(String cleanPattern) {
final Pattern pattern = cleanPattern != null ? SearchField.getPattern(cleanPattern) : null;
return pattern == null ? null : RecipeTextFilter.matching(pattern);
}
private List<Predicate<List<String>>> children(ParserRuleContext ctx) {
if (ctx.children == null) return null;
final List<Predicate<List<String>>> parts = new ArrayList<>();
for (ParseTree child : ctx.children) {
if (!(child instanceof RuleNode)) continue;
final Predicate<List<String>> part = visit(child);
if (part == null) return null;
parts.add(part);
}
return parts.isEmpty() ? null : parts;
}
}
@@ -1,7 +1,6 @@
package codechicken.nei.search;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import net.minecraft.util.EnumChatFormatting;
@@ -17,9 +16,6 @@ import codechicken.nei.SearchTokenParser.ISearchParserProvider;
public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisitor<String> {
private static final Pattern REGEX_ESCAPED_SPACE_PATTERN = Pattern.compile("([^\\\\](?:\\\\\\\\)+)?\\\\ ");
private static final Pattern ESCAPED_SPACE_PATTERN = Pattern.compile("\\\\ ");
public SearchExpressionFormatVisitor(SearchTokenParser searchParser) {
super(searchParser);
}
@@ -35,7 +31,7 @@ public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisit
@Override
public String visitPrefixedExpression(SearchExpressionParser.PrefixedExpressionContext ctx) {
final EnumChatFormatting format = getFormatting(ctx.prefix, null);
final EnumChatFormatting format = getFormatting(ctx, ctx.prefix, null);
return format + String.valueOf(ctx.prefix) + visitToken(ctx.token());
}
@@ -66,19 +62,19 @@ public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisit
cleanText = ctx.plainText().getText();
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanText = ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
cleanText = SearchExpressionUtils.ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
}
final EnumChatFormatting format = getFormatting(prefix, EnumChatFormatting.RESET);
final EnumChatFormatting format = getFormatting(ctx, prefix, EnumChatFormatting.RESET);
return format + cleanText;
} else if (ctx.regex() != null) {
cleanText = visitRegex(ctx.regex());
if (spaceModeEnabled == 1) {
cleanText = REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll("$1 ");
cleanText = SearchExpressionUtils.REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll("$1 ");
}
} else if (ctx.quoted() != null) {
cleanText = visitQuoted(ctx.quoted());
if (spaceModeEnabled == 1) {
cleanText = ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
cleanText = SearchExpressionUtils.ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
}
}
return cleanText;
@@ -91,7 +87,7 @@ public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisit
// check if highlight is defined for the token
Optional.ofNullable(SearchExpressionUtils.getHighlight(type))
// check if highlight is defined for the prefix
.orElse(getFormatting(prefix, null))
.orElse(getFormatting(child, prefix, null))
// use default highlight otherwise
).map(EnumChatFormatting::toString).orElse("");
@@ -108,9 +104,16 @@ public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisit
return defaultResult();
}
private EnumChatFormatting getFormatting(Character prefix, EnumChatFormatting defaultFormatting) {
private static boolean isRecipeText(ParseTree node) {
while (node != null && !(node instanceof SearchExpressionParser.SearchExpressionContext)) {
node = node.getParent();
}
return node != null && ((SearchExpressionParser.SearchExpressionContext) node).type == 4;
}
private EnumChatFormatting getFormatting(ParseTree node, Character prefix, EnumChatFormatting defaultFormatting) {
if (prefix != null) {
if (prefix == '\0') {
if (prefix == '\0' || isRecipeText(node)) {
return EnumChatFormatting.RESET;
}
final ISearchParserProvider provider = searchParser.getProvider(prefix);
@@ -2,6 +2,7 @@ package codechicken.nei.search;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import net.minecraft.util.EnumChatFormatting;
@@ -14,6 +15,11 @@ import codechicken.nei.SearchTokenParser;
public class SearchExpressionUtils {
static final Pattern REGEX_ESCAPED_SPACE_PATTERN = Pattern.compile("([^\\\\](?:\\\\\\\\)+)?\\\\ ");
private static final Pattern ESCAPED_SYMBOL_PATTERN = Pattern.compile("\\\\(.)");
private static final Pattern ESCAPED_QUOTE_PATTERN = Pattern.compile("\\\\\"");
static final Pattern ESCAPED_SPACE_PATTERN = Pattern.compile("\\\\ ");
private static final Map<Integer, EnumChatFormatting> HIGHLIGHT_MAP = new HashMap<>();
static {
for (HIGHLIGHTS elem : HIGHLIGHTS.values()) {
@@ -26,7 +32,8 @@ public class SearchExpressionUtils {
public static enum HIGHLIGHTS {
RECIPE(EnumChatFormatting.GREEN, SearchExpressionParser.RECIPE_INGREDIENTS,
SearchExpressionParser.RECIPE_RESULT, SearchExpressionParser.RECIPE_OTHERS),
SearchExpressionParser.RECIPE_RESULT, SearchExpressionParser.RECIPE_OTHERS,
SearchExpressionParser.RECIPE_TEXT),
OR(EnumChatFormatting.GRAY, SearchExpressionParser.OR),
BRACKETS(EnumChatFormatting.GRAY, SearchExpressionParser.LEFT_BRACKET, SearchExpressionParser.RIGHT_BRACKET),
NEGATE(EnumChatFormatting.BLUE, SearchExpressionParser.DASH),
@@ -67,6 +74,38 @@ public class SearchExpressionUtils {
return visitor.visitRecipeSearchExpression(parser.recipeSearchExpression());
}
public static String getCleanPattern(SearchExpressionParser.TokenContext ctx) {
String cleanPattern = null;
if (ctx.plainText() != null) {
cleanPattern = Pattern.quote(
ESCAPED_SYMBOL_PATTERN.matcher(ctx.plainText().getText())
// Unescape everything in search expression
.replaceAll("$1"));
} else if (ctx.regex() != null) {
if (ctx.regex().REGEX_CONTENT() != null) {
cleanPattern = ctx.regex().REGEX_CONTENT().getSymbol().getText();
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanPattern = REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll("$1 ");
}
}
} else if (ctx.quoted() != null) {
if (ctx.quoted().QUOTED_CONTENT() != null) {
cleanPattern = ctx.quoted().QUOTED_CONTENT().getSymbol().getText();
// Unescape quotes
cleanPattern = ESCAPED_QUOTE_PATTERN.matcher(cleanPattern).replaceAll("\"");
cleanPattern = Pattern.quote(cleanPattern);
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanPattern = ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll(" ");
}
}
}
return cleanPattern;
}
private static <T> SearchExpressionParser createSearchExpressionParser(String text, SearchTokenParser searchParser,
SearchExpressionParserBaseVisitor<T> visitor) {
final boolean doLogExceptions = NEIClientConfig.getBooleanSetting("inventory.search.logSearchExceptions");
@@ -26,6 +26,9 @@ public class FavoriteStorage {
protected final Map<RecipeId, Long> recipeIdToItemHash = new HashMap<>();
protected final Map<Long, ItemStack> itemHashToItemStack = new HashMap<>();
/** The key of the last looked up stack. Its NBT copies the whole stack, which is looked up every frame. */
private static volatile LookupKey lastLookupKey = null;
public void clear() {
this.itemStackToRecipeId.clear();
this.fluidToRecipeId.clear();
@@ -95,7 +98,7 @@ public class FavoriteStorage {
RecipeId recipeId = this.itemHashToRecipeId.get(getItemKey(stack));
if (recipeId == null) {
recipeId = this.itemStackToRecipeId.get(StackInfo.itemStackToNBT(stack, false));
recipeId = this.itemStackToRecipeId.get(getLookupKey(stack));
}
if (recipeId == null) {
@@ -105,6 +108,28 @@ public class FavoriteStorage {
return recipeId;
}
private static NBTTagCompound getLookupKey(ItemStack stack) {
LookupKey key = lastLookupKey;
if (key == null || !key.stack.isItemEqual(stack) || !ItemStack.areItemStackTagsEqual(key.stack, stack)) {
key = new LookupKey(stack.copy(), StackInfo.itemStackToNBT(stack, false));
lastLookupKey = key;
}
return key.nbt;
}
private static class LookupKey {
private final ItemStack stack;
private final NBTTagCompound nbt;
private LookupKey(ItemStack stack, NBTTagCompound nbt) {
this.stack = stack;
this.nbt = nbt;
}
}
public ItemStack getItemStack(RecipeId recipeId) {
NBTTagCompound itemStackNBT = this.recipeIdToItemStack.get(recipeId);
@@ -10,6 +10,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
import net.minecraft.creativetab.CreativeTabs;
@@ -128,8 +129,8 @@ public class ItemUntranslator {
private static final String CONFIG_FILE = "untranslator.cfg";
private static final ItemUntranslator instance = new ItemUntranslator();
private final Map<String, String> secondNames = new HashMap<>();
private final Map<String, String> processedNames = new HashMap<>();
private final Map<String, String> secondNames = new ConcurrentHashMap<>();
private final Map<String, String> processedNames = new ConcurrentHashMap<>();
private ItemUntranslator() {}
@@ -241,14 +242,19 @@ public class ItemUntranslator {
return EnumChatFormatting.getTextWithoutFormattingCodes(name).trim();
}
public synchronized String getItemStackDisplayName(ItemStack stack) {
public String getItemStackDisplayName(ItemStack stack) {
if (stack == null || this.secondNames.isEmpty()) {
return "";
}
final String guidKey = StackInfo.getItemStackGUID(stack);
final String displayName = this.processedNames.get(guidKey);
return displayName != null ? displayName : processDisplayName(stack, guidKey);
}
private synchronized String processDisplayName(ItemStack stack, String guidKey) {
return this.processedNames.computeIfAbsent(guidKey, stackKey -> {
String displayName = this.secondNames.get(stackKey);
@@ -412,9 +412,6 @@ nei.options.inventory.search.subsetsSearchMode=Item Subsets Search
nei.options.inventory.search.subsetsSearchMode.0=Always
nei.options.inventory.search.subsetsSearchMode.1=Prefix: %s
nei.options.inventory.search.subsetsSearchMode.2=Never
nei.options.inventory.optimize_gui_overlap_computation=Optimize computation for GUI overlap
nei.options.inventory.optimize_gui_overlap_computation.true=Yes
nei.options.inventory.optimize_gui_overlap_computation.false=No
nei.options.inventory.autocrafting=Autocrafting
nei.options.inventory.autocrafting.true=Enabled
nei.options.inventory.autocrafting.false=Disabled
@@ -649,7 +646,8 @@ nei.recipe.search.tooltip.name=Filter Syntax
nei.recipe.search.tooltip.shift=§7Hold §6Shift§7 for more info
nei.recipe.search.tooltip.input=%s§ftext§8 - §7search in inputs
nei.recipe.search.tooltip.output=%s§ftext§8 - §7search in outputs
nei.recipe.search.tooltip.auxiliary=%s§ftext§8 - §7search in other stacks (fuel, catalysts)
nei.recipe.search.tooltip.text=%s§ftext§8 - §7search in recipe text
nei.recipe.search.tooltip.auxiliary=%s§ftext§8 - §7search in other stacks
nei.recipe.search.tooltip.all=%s§ftext§8 - §7all inputs must match (same with > and ^)
nei.recipe.search.tooltip.prefix=%stext§8 - §7%s
@@ -251,9 +251,6 @@ nei.options.inventory.search.subsetsSearchMode=Поиск по подмноже
nei.options.inventory.search.subsetsSearchMode.0=Всегда
nei.options.inventory.search.subsetsSearchMode.1=Префикс: %s
nei.options.inventory.search.subsetsSearchMode.2=Никогда
nei.options.inventory.optimize_gui_overlap_computation=Оптимизация вычислений при перекрытии GUI
nei.options.inventory.optimize_gui_overlap_computation.true=Да
nei.options.inventory.optimize_gui_overlap_computation.false=Нет
nei.options.inventory.guirecipe.shiftOverlayRecipe=Требовать удержание Shift для перемещения предметов при отображении рецепта
nei.options.inventory.guirecipe.shiftOverlayRecipe.true=Да
nei.options.inventory.guirecipe.shiftOverlayRecipe.false=Нет
@@ -359,9 +359,6 @@ nei.options.inventory.search.subsetsSearchMode=Пошук у підгрупах
nei.options.inventory.search.subsetsSearchMode.0=Завжди
nei.options.inventory.search.subsetsSearchMode.1=Префікс: %s
nei.options.inventory.search.subsetsSearchMode.2=Ніколи
nei.options.inventory.optimize_gui_overlap_computation=Оптимізувати обчислення перекриття інтерфейсів
nei.options.inventory.optimize_gui_overlap_computation.true=Так
nei.options.inventory.optimize_gui_overlap_computation.false=Ні
nei.options.inventory.autocrafting=Автокрафт
nei.options.inventory.autocrafting.true=Увімкнено
nei.options.inventory.autocrafting.false=Вимкнено
@@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.List;
@@ -16,7 +15,7 @@ import org.junit.jupiter.api.Test;
public class ItemsGridTest {
@Test
void synchronizesOverlapAndCaptureRefresh() {
void refreshesCaptureOnlyWhenGridChanged() {
TestGrid grid = new TestGrid();
ItemsGrid.ScreenCapture capture = mock(ItemsGrid.ScreenCapture.class);
grid.screenCapture = capture;
@@ -24,22 +23,48 @@ public class ItemsGridTest {
grid.setGridSize(1, 2, 18, 18);
grid.setGridSize(1, 2, 18, 18);
verify(capture, times(1)).refreshBuffer();
}
when(capture.needRefresh(1)).thenReturn(false, true);
grid.refresh(null);
@Test
void refreshesOverlapOnlyOnGridChangeOrScanFrame() {
TestGrid grid = new TestGrid();
GridOverlapScanner.requestScan();
GridOverlapScanner.beginFrame(null, true);
grid.setGridSize(1, 2, 18, 18);
grid.refresh(null);
assertEquals(1, grid.overlapRefreshes);
GridOverlapScanner.beginFrame(null, true);
grid.refresh(null);
assertEquals(1, grid.overlapRefreshes);
grid.setGridSize(1, 2, 36, 18);
grid.refresh(null);
assertEquals(2, grid.overlapRefreshes);
GridOverlapScanner.requestScan();
GridOverlapScanner.beginFrame(null, true);
grid.refresh(null);
assertEquals(3, grid.overlapRefreshes);
GridOverlapScanner.beginFrame(null, false);
grid.refresh(null);
assertEquals(4, grid.overlapRefreshes);
GridOverlapScanner.beginFrame(null, false);
grid.refresh(null);
assertEquals(4, grid.overlapRefreshes);
GridOverlapScanner.beginFrame(null, true);
grid.refresh(null);
assertEquals(5, grid.overlapRefreshes);
}
private static final class TestGrid extends ItemsGrid<ItemsGrid.ItemsGridSlot, ItemsGrid.MouseContext> {
private int overlapRefreshes;
@Override
protected int getGridRenderingCacheMode() {
return 1;
}
@Override
protected void updateGuiOverlapSlots(GuiContainer gui) {
overlapRefreshes++;
@@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Named.named;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@@ -35,6 +36,7 @@ import codechicken.nei.SearchField.SearchParserProvider;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.RecipeRole;
import codechicken.nei.search.IdentifierFilter;
@DisplayName("Search expression")
@@ -152,6 +154,10 @@ public class SearchTokenParserTest {
spaceModes,
nonRegexPatternModes);
private static final List<Arguments> regexAllSpaceModesTestProvider = combinationsProvider(
spaceModes,
new ModeValue[] { patternModes[2] });
private static final List<Arguments> spaceIsAndExtendedPlusModeTestProvider = combinationsProvider(
spaceIsAndMode,
extendedPlusPatternMode);
@@ -379,9 +385,9 @@ public class SearchTokenParserTest {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = mock(IRecipeHandler.class);
when(handler.getIngredientStacks(0)).thenReturn(positionedStacks(itemA));
when(handler.getResultStacks(0)).thenReturn(positionedStacks(itemB));
when(handler.getAuxiliaryStacks(0)).thenReturn(positionedStacks(itemC));
when(handler.getSearchStacks(0, RecipeRole.INPUT)).thenReturn(positionedStacks(itemA));
when(handler.getSearchStacks(0, RecipeRole.OUTPUT)).thenReturn(positionedStacks(itemB));
when(handler.getSearchStacks(0, RecipeRole.AUXILIARY)).thenReturn(positionedStacks(itemC));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "<" + itemA.getDisplayName(), handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, ">" + itemB.getDisplayName(), handler));
@@ -390,6 +396,84 @@ public class SearchTokenParserTest {
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, ">" + itemC.getDisplayName(), handler));
}
@DisplayName("Recipe text")
@ParameterizedTest(name = "{argumentsWithNames}")
@FieldSource("nonRegexAllSpaceModesTestProvider")
public void testRecipeText(int spaceMode, int patternMode) {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = recipeTextHandler(Arrays.asList("Foo", "xyz"));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~foo", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~xyz", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~zzz", handler));
// the text search does not look at the stacks
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~a", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "a", handler));
// the plain search does not look at the text
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "foo", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~-foo", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~-zzz", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "<a~foo", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "<a~zzz", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "<b~foo", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, ">b~xyz", handler));
}
@DisplayName("Recipe text of a recipe without text")
@ParameterizedTest(name = "{argumentsWithNames}")
@FieldSource("nonRegexAllSpaceModesTestProvider")
public void testRecipeTextWithoutText(int spaceMode, int patternMode) {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = recipeTextHandler(Collections.emptyList());
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~a", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~-a", handler));
}
@DisplayName("Recipe text with wildcards and regex in Extended mode")
@ParameterizedTest(name = "{argumentsWithNames}")
@FieldSource("extendedOnlyAllSpaceModesTestProvider")
public void testRecipeTextExtended(int spaceMode, int patternMode) {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = recipeTextHandler(Arrays.asList("Foo", "xyz"));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~f?o", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~x*z", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~x?z?", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~r/^fo+$/", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~r/^o+$/", handler));
}
@DisplayName("Recipe text in Regex mode")
@ParameterizedTest(name = "{argumentsWithNames}")
@FieldSource("regexAllSpaceModesTestProvider")
public void testRecipeTextRegex(int spaceMode, int patternMode) {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = recipeTextHandler(Arrays.asList("Foo", "xyz"));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~f.o", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~x[y]z", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~x[^y]z", handler));
}
@DisplayName("Recipe text with brackets in Extended+ mode")
@ParameterizedTest(name = "{argumentsWithNames}")
@FieldSource("extendedPlusAllSpaceModesTestProvider")
public void testRecipeTextBrackets(int spaceMode, int patternMode) {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = recipeTextHandler(Arrays.asList("Foo", "xyz"));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~{foo|zzz}", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~{zzz|qqq}", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~-{zzz|qqq}", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~-{foo|qqq}", handler));
}
// Extended+ specific tests
@DisplayName("Sequence")
@@ -488,6 +572,15 @@ public class SearchTokenParserTest {
return matchedItems;
}
private static IRecipeHandler recipeTextHandler(List<String> text) {
IRecipeHandler handler = mock(IRecipeHandler.class);
when(handler.getSearchStacks(0, RecipeRole.INPUT)).thenReturn(positionedStacks(itemA));
when(handler.getSearchStacks(0, RecipeRole.OUTPUT)).thenReturn(positionedStacks(itemB));
when(handler.getSearchStacks(0, RecipeRole.AUXILIARY)).thenReturn(Collections.emptyList());
when(handler.getSearchText(0)).thenReturn(text);
return handler;
}
private static boolean testRecipeFilter(int spaceMode, int patternMode, SearchTokenParser searchParser,
String search, IRecipeHandler handler) {
setModes(spaceMode, patternMode);