diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java b/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java index 14f07e7eb..955827613 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java @@ -13,6 +13,9 @@ import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData; // New interpreter system imports import noppes.npcs.client.gui.util.script.interpreter.ScriptLine; import noppes.npcs.client.gui.util.script.interpreter.ScriptTextContainer; +import noppes.npcs.client.gui.util.script.interpreter.Token; +import noppes.npcs.client.gui.util.script.interpreter.hover.HoverState; +import noppes.npcs.client.gui.util.script.interpreter.hover.TokenHoverRenderer; import noppes.npcs.client.key.impl.ScriptEditorKeys; import noppes.npcs.util.ValueUtil; import org.lwjgl.input.Keyboard; @@ -82,6 +85,7 @@ public class GuiScriptTextArea extends GuiNpcTextField { // ==================== HELPER CLASS INSTANCES ==================== private final ScrollState scroll = new ScrollState(); private final SelectionState selection = new SelectionState(); + private final HoverState hoverState = new HoverState(); // ==================== UI COMPONENTS ==================== private int cursorCounter; @@ -503,6 +507,9 @@ public class GuiScriptTextArea extends GuiNpcTextField { scroll.initializeIfNeeded(scroll.getScrolledLine()); scroll.update(maxScroll); + // Update hover state for token tooltips + updateHoverState(xMouse, yMouse); + // Handle click-dragging for selection if (clicked) { clicked = Mouse.isButtonDown(0); @@ -872,6 +879,13 @@ public class GuiScriptTextArea extends GuiNpcTextField { // Draw go to line dialog (overlays everything) goToLineDialog.draw(xMouse, yMouse); KEYS_OVERLAY.draw(xMouse, yMouse, wheelDelta); + + // Draw hover tooltip (on top of everything) + if (hoverState.isTooltipVisible()) { + ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft(), + Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight); + TokenHoverRenderer.render(hoverState, sr.getScaledWidth(), sr.getScaledHeight()); + } } private void scissorViewport() { @@ -935,6 +949,107 @@ public class GuiScriptTextArea extends GuiNpcTextField { return selection.getCursorLineIndex(container.lines, text != null ? text.length() : 0); } + /** + * Get the token at a specific screen position (mouse coordinates). + * Also returns the token's screen position and dimensions for tooltip placement. + * + * @param xMouse Screen X coordinate + * @param yMouse Screen Y coordinate + * @return Array of [Token, tokenScreenX, tokenScreenY, tokenWidth] or null if no token + */ + private Object[] getTokenAtScreenPosition(int xMouse, int yMouse) { + if (container == null || !(container instanceof ScriptTextContainer)) { + return null; + } + + ScriptTextContainer scriptContainer = (ScriptTextContainer) container; + + // Check if mouse is within the text viewport + int textAreaX = x + LINE_NUMBER_GUTTER_WIDTH + 1; + if (xMouse < textAreaX || xMouse > x + width || yMouse < y || yMouse > y + height) { + return null; + } + + // Adjust mouse position relative to text area + int relativeX = xMouse - textAreaX; + int relativeY = yMouse - y; + + // Account for fractional scrolling + double fracOffset = scroll.getFractionalOffset(); + double fracPixels = fracOffset * container.lineHeight; + double adjustedY = relativeY + fracPixels; + + // Find which line the mouse is over + int lineIdx = scroll.getScrolledLine() + (int)(adjustedY / container.lineHeight); + if (lineIdx < 0 || lineIdx >= container.lines.size()) { + return null; + } + + LineData lineData = container.lines.get(lineIdx); + String lineText = lineData.text; + + // Find which character position in the line + int charPos = 0; + int accumulatedWidth = 0; + for (int i = 0; i < lineText.length(); i++) { + int charWidth = ClientProxy.Font.width(String.valueOf(lineText.charAt(i))); + if (relativeX < accumulatedWidth + charWidth) { + charPos = i; + break; + } + accumulatedWidth += charWidth; + charPos = i + 1; + } + + // Convert to global position + int globalPos = lineData.start + Math.min(charPos, lineText.length()); + + // Get the token at this position + Token token = scriptContainer.getInterpreterTokenAt(globalPos); + if (token == null) { + return null; + } + + // Calculate token's screen position + int tokenLocalStart = token.getGlobalStart() - lineData.start; + int tokenLocalEnd = token.getGlobalEnd() - lineData.start; + tokenLocalStart = Math.max(0, Math.min(tokenLocalStart, lineText.length())); + tokenLocalEnd = Math.max(0, Math.min(tokenLocalEnd, lineText.length())); + + int tokenScreenX = textAreaX + ClientProxy.Font.width(lineText.substring(0, tokenLocalStart)); + int tokenScreenY = y + (lineIdx - scroll.getScrolledLine()) * container.lineHeight - (int)fracPixels; + int tokenWidth = ClientProxy.Font.width(lineText.substring(tokenLocalStart, tokenLocalEnd)); + + return new Object[] { token, tokenScreenX, tokenScreenY, tokenWidth }; + } + + /** + * Update hover state based on current mouse position. + * Called every frame from drawTextBox. + */ + private void updateHoverState(int xMouse, int yMouse) { + // Don't show tooltips when not active, clicking, or when overlays are visible + if (!active || !isEnabled() || clicked || searchBar.isVisible() || + goToLineDialog.isVisible() || KEYS_OVERLAY.isVisible() || renameHandler.isActive()) { + hoverState.clearHover(); + return; + } + + // Get token at current mouse position + Object[] tokenInfo = getTokenAtScreenPosition(xMouse, yMouse); + + if (tokenInfo != null) { + Token token = (Token) tokenInfo[0]; + int tokenScreenX = (Integer) tokenInfo[1]; + int tokenScreenY = (Integer) tokenInfo[2]; + int tokenWidth = (Integer) tokenInfo[3]; + + hoverState.update(xMouse, yMouse, token, tokenScreenX, tokenScreenY, tokenWidth); + } else { + hoverState.update(xMouse, yMouse, null, 0, 0, 0); + } + } + // Scroll viewport to keep cursor visible (minimal adjustment, like IntelliJ) // Only scrolls if cursor is outside the visible area diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptTextContainer.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptTextContainer.java index 16e604d19..5c98ca2f5 100644 --- a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptTextContainer.java +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/ScriptTextContainer.java @@ -154,6 +154,26 @@ public class ScriptTextContainer extends JavaTextContainer { return document; } + /** + * Get the interpreter Token at a specific global position in the text. + * Returns null if no token is at that position or if the interpreter is disabled. + * + * @param globalPosition Position in the document text + * @return The Token at that position, or null + */ + public noppes.npcs.client.gui.util.script.interpreter.Token getInterpreterTokenAt(int globalPosition) { + if (!USE_NEW_INTERPRETER || document == null) { + return null; + } + + ScriptLine line = document.getLineAt(globalPosition); + if (line == null) { + return null; + } + + return line.getTokenAt(globalPosition); + } + /** * Get method blocks for compatibility with existing code. * Creates MethodBlock-like objects from the new MethodInfo. diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/HoverState.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/HoverState.java new file mode 100644 index 000000000..05f403432 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/HoverState.java @@ -0,0 +1,279 @@ +package noppes.npcs.client.gui.util.script.interpreter.hover; + +import noppes.npcs.client.gui.util.script.interpreter.ScriptDocument; +import noppes.npcs.client.gui.util.script.interpreter.ScriptLine; +import noppes.npcs.client.gui.util.script.interpreter.Token; + +/** + * Manages the hover state for token tooltips in the script editor. + * + * Tracks: + * - Current mouse position + * - Hovered token (if any) + * - Hover duration for delayed tooltip display + * - Whether tooltip should be visible + * + * Implements a 500ms delay before showing tooltips, resetting when + * the mouse moves to a different token. + */ +public class HoverState { + + /** Minimum hover time (ms) before showing tooltip */ + private static final long HOVER_DELAY_MS = 500; + + // ==================== STATE ==================== + + /** Currently hovered token (null if none) */ + private Token hoveredToken; + + /** Time when hover on current token started */ + private long hoverStartTime; + + /** Whether the tooltip should currently be displayed */ + private boolean tooltipVisible; + + /** Cached hover info for the current token */ + private TokenHoverInfo hoverInfo; + + /** Last known mouse position */ + private int lastMouseX; + private int lastMouseY; + + /** Position of the hovered token (for tooltip positioning) */ + private int tokenScreenX; + private int tokenScreenY; + private int tokenWidth; + + // ==================== UPDATE ==================== + + /** + * Update the hover state based on current mouse position. + * Should be called every frame from drawTextBox. + * + * @param mouseX Current mouse X position + * @param mouseY Current mouse Y position + * @param document The script document + * @param viewportX X position of the text viewport (after gutter) + * @param viewportY Y position of the text viewport + * @param viewportWidth Width of the text viewport + * @param viewportHeight Height of the text viewport + * @param scrollOffset Current vertical scroll offset (in lines) + * @param lineHeight Height of each line in pixels + * @param gutterWidth Width of the line number gutter + */ + public void update(int mouseX, int mouseY, ScriptDocument document, + int viewportX, int viewportY, int viewportWidth, int viewportHeight, + float scrollOffset, int lineHeight, int gutterWidth) { + + lastMouseX = mouseX; + lastMouseY = mouseY; + + // Check if mouse is within the text viewport + if (mouseX < viewportX || mouseX > viewportX + viewportWidth || + mouseY < viewportY || mouseY > viewportY + viewportHeight) { + clearHover(); + return; + } + + if (document == null) { + clearHover(); + return; + } + + // Calculate which line the mouse is over + int relativeY = mouseY - viewportY; + int lineIndex = (int) (scrollOffset + (relativeY / (float) lineHeight)); + + // Get the line + ScriptLine line = null; + for (ScriptLine l : document.getLines()) { + if (l.getLineIndex() == lineIndex) { + line = l; + break; + } + } + + if (line == null) { + clearHover(); + return; + } + + // Calculate character position within the line + int relativeX = mouseX - viewportX; + int globalPos = line.getGlobalStart() + getCharacterIndexAtX(line, relativeX); + + // Find the token at this position + Token token = line.getTokenAt(globalPos); + + if (token == null) { + clearHover(); + return; + } + + // Check if this is a new token + if (token != hoveredToken) { + // New token - reset timer + hoveredToken = token; + hoverStartTime = System.currentTimeMillis(); + tooltipVisible = false; + hoverInfo = null; + + // Calculate token screen position for tooltip + calculateTokenPosition(line, token, viewportX, viewportY, scrollOffset, lineHeight); + } else { + // Same token - check if delay has elapsed + long elapsed = System.currentTimeMillis() - hoverStartTime; + if (elapsed >= HOVER_DELAY_MS && !tooltipVisible) { + tooltipVisible = true; + hoverInfo = TokenHoverInfo.fromToken(token); + } + } + } + + /** + * Update the hover state with a specific token. + * Simplified version for when the token has already been found. + * + * @param mouseX Current mouse X position + * @param mouseY Current mouse Y position + * @param token The token at the mouse position (or null if none) + * @param tokenX Screen X position of the token + * @param tokenY Screen Y position of the token + * @param tokenW Width of the token in pixels + */ + public void update(int mouseX, int mouseY, Token token, int tokenX, int tokenY, int tokenW) { + lastMouseX = mouseX; + lastMouseY = mouseY; + + if (token == null) { + clearHover(); + return; + } + + // Check if this is a new token + if (token != hoveredToken) { + // New token - reset timer + hoveredToken = token; + hoverStartTime = System.currentTimeMillis(); + tooltipVisible = false; + hoverInfo = null; + + // Store token position + tokenScreenX = tokenX; + tokenScreenY = tokenY; + tokenWidth = tokenW; + } else { + // Same token - check if delay has elapsed + long elapsed = System.currentTimeMillis() - hoverStartTime; + if (elapsed >= HOVER_DELAY_MS && !tooltipVisible) { + tooltipVisible = true; + hoverInfo = TokenHoverInfo.fromToken(token); + } + } + } + + /** + * Clear the current hover state. + */ + public void clearHover() { + if (hoveredToken != null) { + hoveredToken = null; + hoverStartTime = 0; + tooltipVisible = false; + hoverInfo = null; + } + } + + /** + * Force the tooltip to hide (e.g., when clicking). + */ + public void hideTooltip() { + tooltipVisible = false; + } + + // ==================== POSITION CALCULATION ==================== + + /** + * Get the character index within a line at the given X pixel position. + */ + private int getCharacterIndexAtX(ScriptLine line, int x) { + String text = line.getText(); + if (text == null || text.isEmpty()) return 0; + + int accumWidth = 0; + for (int i = 0; i < text.length(); i++) { + int charWidth = noppes.npcs.client.ClientProxy.Font.width(String.valueOf(text.charAt(i))); + if (accumWidth + charWidth / 2 > x) { + return i; + } + accumWidth += charWidth; + } + return text.length(); + } + + /** + * Calculate the screen position of a token for tooltip positioning. + */ + private void calculateTokenPosition(ScriptLine line, Token token, + int viewportX, int viewportY, + float scrollOffset, int lineHeight) { + // X position: calculate width of text before the token + String lineText = line.getText(); + int tokenLocalStart = token.getGlobalStart() - line.getGlobalStart(); + tokenLocalStart = Math.max(0, Math.min(tokenLocalStart, lineText.length())); + + String textBefore = lineText.substring(0, tokenLocalStart); + tokenScreenX = viewportX + noppes.npcs.client.ClientProxy.Font.width(textBefore); + + // Y position: line position minus scroll + int lineY = line.getLineIndex(); + tokenScreenY = viewportY + (int) ((lineY - scrollOffset) * lineHeight); + + // Token width + tokenWidth = noppes.npcs.client.ClientProxy.Font.width(token.getText()); + } + + // ==================== GETTERS ==================== + + public boolean isTooltipVisible() { + return tooltipVisible && hoverInfo != null && hoverInfo.hasContent(); + } + + public TokenHoverInfo getHoverInfo() { + return hoverInfo; + } + + public Token getHoveredToken() { + return hoveredToken; + } + + public int getTokenScreenX() { + return tokenScreenX; + } + + public int getTokenScreenY() { + return tokenScreenY; + } + + public int getTokenWidth() { + return tokenWidth; + } + + public int getLastMouseX() { + return lastMouseX; + } + + public int getLastMouseY() { + return lastMouseY; + } + + /** + * Get the progress (0.0 to 1.0) of the hover delay. + * Can be used for fade-in animation. + */ + public float getHoverProgress() { + if (hoveredToken == null) return 0f; + long elapsed = System.currentTimeMillis() - hoverStartTime; + return Math.min(1.0f, elapsed / (float) HOVER_DELAY_MS); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverInfo.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverInfo.java new file mode 100644 index 000000000..b624c4cf5 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverInfo.java @@ -0,0 +1,522 @@ +package noppes.npcs.client.gui.util.script.interpreter.hover; + +import noppes.npcs.client.gui.util.script.interpreter.*; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +/** + * Data class containing all displayable information for a token hover tooltip. + * Extracts and formats information from Token metadata for rendering. + * + * Supports display for: + * - Classes/Interfaces/Enums: Package, declaration with modifiers/extends/implements + * - Methods: Return type, signature, parameters, Javadoc + * - Fields: Type, containing class, declaration + * - Variables: Type, scope (local/parameter/global) + * - Errors: Validation errors, type mismatches + */ +public class TokenHoverInfo { + + // ==================== DISPLAY SECTIONS ==================== + + /** Package name (e.g., "net.minecraft.client") - shown in gray */ + private String packageName; + + /** Icon indicator (e.g., "C" for class, "I" for interface, "m" for method) */ + private String iconIndicator; + + /** Primary declaration line with syntax coloring */ + private List declaration = new ArrayList<>(); + + /** Javadoc/documentation comment lines */ + private List documentation = new ArrayList<>(); + + /** Error messages (shown in red) */ + private List errors = new ArrayList<>(); + + /** Additional info lines (e.g., "Variable 'x' is never used") */ + private List additionalInfo = new ArrayList<>(); + + /** The token this info was built from */ + private final Token token; + + // ==================== TEXT SEGMENT ==================== + + /** + * A colored segment of text within the declaration line. + */ + public static class TextSegment { + public final String text; + public final int color; + + public TextSegment(String text, int color) { + this.text = text; + this.color = color; + } + + // Predefined colors matching IntelliJ dark theme + public static final int COLOR_KEYWORD = 0xCC7832; // Orange for keywords/modifiers + public static final int COLOR_TYPE = 0x6897BB; // Blue for types + public static final int COLOR_CLASS = 0xA9B7C6; // Light gray for class names + public static final int COLOR_METHOD = 0xFFC66D; // Yellow for method names + public static final int COLOR_FIELD = 0x9876AA; // Purple for fields + public static final int COLOR_PARAM = 0xA9B7C6; // Light gray for parameters + public static final int COLOR_PACKAGE = 0x808080; // Gray for package + public static final int COLOR_DEFAULT = 0xA9B7C6; // Default text + public static final int COLOR_ERROR = 0xFF6B68; // Red for errors + public static final int COLOR_STRING = 0x6A8759; // Green for strings + public static final int COLOR_ANNOTATION = 0xBBB529; // Yellow-green for annotations + } + + // ==================== CONSTRUCTOR ==================== + + private TokenHoverInfo(Token token) { + this.token = token; + } + + // ==================== FACTORY METHOD ==================== + + /** + * Build hover info from a token based on its type and metadata. + */ + public static TokenHoverInfo fromToken(Token token) { + if (token == null) return null; + + TokenHoverInfo info = new TokenHoverInfo(token); + + // First, check for errors + info.extractErrors(token); + + // Then, extract type-specific information + switch (token.getType()) { + case IMPORTED_CLASS: + case CLASS_DECL: + case INTERFACE_DECL: + case ENUM_DECL: + case TYPE_DECL: + case NEW_TYPE: + info.extractClassInfo(token); + break; + + case METHOD_CALL: + info.extractMethodCallInfo(token); + break; + + case METHOD_DECL: + info.extractMethodDeclInfo(token); + break; + + case GLOBAL_FIELD: + info.extractGlobalFieldInfo(token); + break; + + case LOCAL_FIELD: + info.extractLocalFieldInfo(token); + break; + + case PARAMETER: + info.extractParameterInfo(token); + break; + + case UNDEFINED_VAR: + info.extractUndefinedInfo(token); + break; + + case KEYWORD: + case MODIFIER: + case STRING: + case NUMBER: + case COMMENT: + // These don't need hover info typically + return null; + + default: + // For other types, try to extract any available metadata + if (token.getTypeInfo() != null) { + info.extractClassInfo(token); + } else if (token.getMethodInfo() != null) { + info.extractMethodDeclInfo(token); + } else if (token.getFieldInfo() != null) { + info.extractFieldInfoGeneric(token); + } else { + return null; // Nothing to show + } + break; + } + + return info; + } + + // ==================== EXTRACTION METHODS ==================== + + private void extractErrors(Token token) { + MethodCallInfo callInfo = token.getMethodCallInfo(); + if (callInfo != null) { + if (callInfo.hasArgCountError()) { + errors.add("Expected " + getExpectedArgCount(callInfo) + " argument(s) but found " + callInfo.getArguments().size()); + } + if (callInfo.hasArgTypeError()) { + for (MethodCallInfo.ArgumentTypeError error : callInfo.getArgumentTypeErrors()) { + errors.add(error.getMessage()); + } + } + if (callInfo.hasReturnTypeMismatch()) { + errors.add(callInfo.getErrorMessage()); + } + if (callInfo.hasStaticAccessError()) { + errors.add(callInfo.getErrorMessage()); + } + } + + FieldInfo fieldInfo = token.getFieldInfo(); + if (fieldInfo != null && !fieldInfo.isResolved()) { + errors.add("Cannot resolve symbol '" + token.getText() + "'"); + } + } + + private int getExpectedArgCount(MethodCallInfo callInfo) { + MethodInfo method = callInfo.getResolvedMethod(); + if (method != null) { + return method.getParameterCount(); + } + return 0; + } + + private void extractClassInfo(Token token) { + TypeInfo typeInfo = token.getTypeInfo(); + if (typeInfo == null) return; + + packageName = typeInfo.getPackageName(); + + Class clazz = typeInfo.getJavaClass(); + if (clazz != null) { + // Icon + if (clazz.isInterface()) { + iconIndicator = "I"; + } else if (clazz.isEnum()) { + iconIndicator = "E"; + } else { + iconIndicator = "C"; + } + + // Build declaration + int mods = clazz.getModifiers(); + + // Modifiers + if (Modifier.isPublic(mods)) addSegment("public ", TextSegment.COLOR_KEYWORD); + if (Modifier.isAbstract(mods) && !clazz.isInterface()) addSegment("abstract ", TextSegment.COLOR_KEYWORD); + if (Modifier.isFinal(mods)) addSegment("final ", TextSegment.COLOR_KEYWORD); + + // Class type keyword + if (clazz.isInterface()) { + addSegment("interface ", TextSegment.COLOR_KEYWORD); + } else if (clazz.isEnum()) { + addSegment("enum ", TextSegment.COLOR_KEYWORD); + } else { + addSegment("class ", TextSegment.COLOR_KEYWORD); + } + + // Class name + addSegment(typeInfo.getSimpleName(), TextSegment.COLOR_CLASS); + + // Extends + Class superclass = clazz.getSuperclass(); + if (superclass != null && superclass != Object.class) { + addSegment(" extends ", TextSegment.COLOR_KEYWORD); + int superClassCol = TextSegment.COLOR_TYPE; + if (superclass.isInterface()) { + superClassCol = TokenType.INTERFACE_DECL.getHexColor(); + } else if (superclass.isEnum()) { + superClassCol = TokenType.ENUM_DECL.getHexColor(); + } else { + superClassCol = TokenType.IMPORTED_CLASS.getHexColor(); + + } + addSegment(superclass.getSimpleName(), superClassCol); + } + + List declaration = null; + + // Implements + Class[] interfaces = clazz.getInterfaces(); + if (interfaces.length > 0) { + addSegment(clazz.isInterface() ? " extends " : " implements ", TextSegment.COLOR_KEYWORD); + for (int i = 0; i < Math.min(interfaces.length, 3); i++) { + if (i > 0) addSegment(", ", TextSegment.COLOR_DEFAULT); + addSegment(interfaces[i].getSimpleName(), TokenType.INTERFACE_DECL.getHexColor()); + } + if (interfaces.length > 3) { + addSegment(", ...", TextSegment.COLOR_DEFAULT); + } + } + } else { + // Unresolved type + iconIndicator = "?"; + addSegment(typeInfo.getSimpleName(), TextSegment.COLOR_CLASS); + if (!typeInfo.isResolved()) { + errors.add("Cannot resolve class '" + typeInfo.getSimpleName() + "'"); + } + } + } + + private void extractMethodCallInfo(Token token) { + MethodCallInfo callInfo = token.getMethodCallInfo(); + MethodInfo methodInfo = callInfo != null ? callInfo.getResolvedMethod() : token.getMethodInfo(); + + if (methodInfo == null && callInfo == null) return; + + iconIndicator = "m"; + + TypeInfo containingType = null; + if (callInfo != null) { + containingType = callInfo.getReceiverType(); + } + if (containingType == null && methodInfo != null) { + containingType = methodInfo.getContainingType(); + } + + if (containingType != null) { + // Show full package.ClassName for context (like IntelliJ) + String pkg = containingType.getPackageName(); + String className = containingType.getSimpleName(); + if (pkg != null && !pkg.isEmpty()) { + packageName = pkg + "." + className; + } else { + packageName = className; + } + } + + // Try to get actual Java method for more details + if (containingType != null && containingType.getJavaClass() != null && methodInfo != null) { + Class clazz = containingType.getJavaClass(); + Method javaMethod = findJavaMethod(clazz, methodInfo.getName(), methodInfo.getParameterCount()); + + if (javaMethod != null) { + buildMethodDeclaration(javaMethod, containingType); + extractJavadoc(javaMethod); + return; + } + } + + // Fallback to basic method info + if (methodInfo != null) { + buildBasicMethodDeclaration(methodInfo, containingType); + } + } + + private void extractMethodDeclInfo(Token token) { + MethodInfo methodInfo = token.getMethodInfo(); + if (methodInfo == null) return; + + iconIndicator = "m"; + + // For script-defined methods, show basic declaration + buildBasicMethodDeclaration(methodInfo, null); + } + + private void extractGlobalFieldInfo(Token token) { + FieldInfo fieldInfo = token.getFieldInfo(); + if (fieldInfo == null) return; + + iconIndicator = "f"; + + TypeInfo declaredType = fieldInfo.getDeclaredType(); + if (declaredType != null) { + // Show field's type package.ClassName for context + String pkg = declaredType.getPackageName(); + String className = declaredType.getSimpleName(); + if (pkg != null && !pkg.isEmpty()) { + packageName = pkg; + } + + // Type + addSegment(declaredType.getSimpleName(), TextSegment.COLOR_TYPE); + addSegment(" ", TextSegment.COLOR_DEFAULT); + } + + // Field name + addSegment(fieldInfo.getName(), TextSegment.COLOR_FIELD); + } + + private void extractLocalFieldInfo(Token token) { + FieldInfo fieldInfo = token.getFieldInfo(); + if (fieldInfo == null) return; + + iconIndicator = "v"; + + TypeInfo declaredType = fieldInfo.getDeclaredType(); + if (declaredType != null) { + addSegment(declaredType.getSimpleName(), TextSegment.COLOR_TYPE); + addSegment(" ", TextSegment.COLOR_DEFAULT); + } + + addSegment(fieldInfo.getName(), TextSegment.COLOR_FIELD); + + // Show it's a local variable + additionalInfo.add("Local variable"); + } + + private void extractParameterInfo(Token token) { + FieldInfo fieldInfo = token.getFieldInfo(); + if (fieldInfo == null) return; + + iconIndicator = "p"; + + TypeInfo declaredType = fieldInfo.getDeclaredType(); + if (declaredType != null) { + addSegment(declaredType.getSimpleName(), TextSegment.COLOR_TYPE); + addSegment(" ", TextSegment.COLOR_DEFAULT); + } + + addSegment(fieldInfo.getName(), TextSegment.COLOR_PARAM); + + additionalInfo.add("Parameter"); + } + + private void extractUndefinedInfo(Token token) { + iconIndicator = "?"; + addSegment(token.getText(), TextSegment.COLOR_ERROR); + errors.add("Cannot resolve symbol '" + token.getText() + "'"); + } + + private void extractFieldInfoGeneric(Token token) { + FieldInfo fieldInfo = token.getFieldInfo(); + if (fieldInfo == null) return; + + switch (fieldInfo.getScope()) { + case GLOBAL: + extractGlobalFieldInfo(token); + break; + case LOCAL: + extractLocalFieldInfo(token); + break; + case PARAMETER: + extractParameterInfo(token); + break; + } + } + + // ==================== HELPER METHODS ==================== + + private void addSegment(String text, int color) { + declaration.add(new TextSegment(text, color)); + } + + private Method findJavaMethod(Class clazz, String name, int paramCount) { + try { + for (Method m : clazz.getMethods()) { + if (m.getName().equals(name) && m.getParameterCount() == paramCount) { + return m; + } + } + } catch (Exception e) { + // Ignore + } + return null; + } + + private void buildMethodDeclaration(Method method, TypeInfo containingType) { + int mods = method.getModifiers(); + + // Annotations (show @Contract if present, etc.) + // Skip for now - could add later + + // Modifiers + if (Modifier.isPublic(mods)) addSegment("public ", TextSegment.COLOR_KEYWORD); + else if (Modifier.isProtected(mods)) addSegment("protected ", TextSegment.COLOR_KEYWORD); + else if (Modifier.isPrivate(mods)) addSegment("private ", TextSegment.COLOR_KEYWORD); + + if (Modifier.isStatic(mods)) addSegment("static ", TextSegment.COLOR_KEYWORD); + if (Modifier.isFinal(mods)) addSegment("final ", TextSegment.COLOR_KEYWORD); + if (Modifier.isAbstract(mods)) addSegment("abstract ", TextSegment.COLOR_KEYWORD); + if (Modifier.isSynchronized(mods)) addSegment("synchronized ", TextSegment.COLOR_KEYWORD); + + // Return type + Class returnType = method.getReturnType(); + addSegment(returnType.getSimpleName(), TextSegment.COLOR_TYPE); + addSegment(" ", TextSegment.COLOR_DEFAULT); + + // Method name + addSegment(method.getName(), TextSegment.COLOR_METHOD); + + // Parameters + addSegment("(", TextSegment.COLOR_DEFAULT); + Class[] paramTypes = method.getParameterTypes(); + java.lang.reflect.Parameter[] params = method.getParameters(); + for (int i = 0; i < paramTypes.length; i++) { + if (i > 0) addSegment(", ", TextSegment.COLOR_DEFAULT); + addSegment(paramTypes[i].getSimpleName(), TextSegment.COLOR_TYPE); + addSegment(" ", TextSegment.COLOR_DEFAULT); + // Try to get parameter name if available + String paramName = params.length > i ? params[i].getName() : "arg" + i; + addSegment(paramName, TextSegment.COLOR_PARAM); + } + addSegment(")", TextSegment.COLOR_DEFAULT); + } + + private void buildBasicMethodDeclaration(MethodInfo methodInfo, TypeInfo containingType) { + // Modifiers + if (methodInfo.isStatic()) { + addSegment("static ", TextSegment.COLOR_KEYWORD); + } + + // Return type + TypeInfo returnType = methodInfo.getReturnType(); + if (returnType != null) { + addSegment(returnType.getSimpleName(), TextSegment.COLOR_TYPE); + addSegment(" ", TextSegment.COLOR_DEFAULT); + } else { + addSegment("void ", TextSegment.COLOR_KEYWORD); + } + + // Method name + addSegment(methodInfo.getName(), TextSegment.COLOR_METHOD); + + // Parameters + addSegment("(", TextSegment.COLOR_DEFAULT); + List params = methodInfo.getParameters(); + for (int i = 0; i < params.size(); i++) { + if (i > 0) addSegment(", ", TextSegment.COLOR_DEFAULT); + FieldInfo param = params.get(i); + TypeInfo paramType = param.getDeclaredType(); + if (paramType != null) { + addSegment(paramType.getSimpleName(), TextSegment.COLOR_TYPE); + addSegment(" ", TextSegment.COLOR_DEFAULT); + } + addSegment(param.getName(), TextSegment.COLOR_PARAM); + } + addSegment(")", TextSegment.COLOR_DEFAULT); + } + + private void extractJavadoc(Method method) { + // Java reflection doesn't provide Javadoc at runtime + // We could potentially load it from source files or external documentation + // For now, we'll leave this as a placeholder for future enhancement + + // Check for @Deprecated annotation + if (method.isAnnotationPresent(Deprecated.class)) { + additionalInfo.add("@Deprecated"); + } + } + + // ==================== GETTERS ==================== + + public String getPackageName() { return packageName; } + public String getIconIndicator() { return iconIndicator; } + public List getDeclaration() { return declaration; } + public List getDocumentation() { return documentation; } + public List getErrors() { return errors; } + public List getAdditionalInfo() { return additionalInfo; } + public Token getToken() { return token; } + + public boolean hasContent() { + return !declaration.isEmpty() || !errors.isEmpty() || !documentation.isEmpty(); + } + + public boolean hasErrors() { + return !errors.isEmpty(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverRenderer.java b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverRenderer.java new file mode 100644 index 000000000..08181ff6b --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/script/interpreter/hover/TokenHoverRenderer.java @@ -0,0 +1,332 @@ +package noppes.npcs.client.gui.util.script.interpreter.hover; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.ScaledResolution; +import noppes.npcs.client.ClientProxy; +import org.lwjgl.opengl.GL11; + +import java.util.List; + +/** + * Renders hover tooltips for tokens in the script editor. + * + * Renders IntelliJ-style tooltips with: + * - Package name in gray + * - Icon indicator (C/I/E/m/f/v/p) + * - Colored declaration line + * - Documentation/Javadoc + * - Error messages in red + * + * Handles positioning to keep tooltip on screen. + */ +public class TokenHoverRenderer { + + // ==================== CONSTANTS ==================== + + /** Padding inside the tooltip box */ + private static final int PADDING = 6; + + /** Gap between icon and text */ + private static final int ICON_GAP = 4; + + /** Icon box size */ + private static final int ICON_SIZE = 12; + + /** Line spacing */ + private static final int LINE_SPACING = 2; + + /** Vertical offset from token */ + private static final int VERTICAL_OFFSET = 4; + + /** Maximum tooltip width */ + private static final int MAX_WIDTH = 400; + + /** Minimum tooltip width */ + private static final int MIN_WIDTH = 150; + + // ==================== COLORS ==================== + + /** Background color (dark gray like IntelliJ) */ + private static final int BG_COLOR = 0xF0313335; + + /** Border color */ + private static final int BORDER_COLOR = 0xFF3C3F41; + + /** Package text color */ + private static final int PACKAGE_COLOR = 0xFF808080; + + /** Error text color */ + private static final int ERROR_COLOR = 0xFFFF6B68; + + /** Info text color */ + private static final int INFO_COLOR = 0xFF808080; + + // ==================== ICON COLORS ==================== + + private static final int ICON_CLASS_BG = 0xFF4A6B8A; // Blue for classes + private static final int ICON_INTERFACE_BG = 0xFF8A6B4A; // Orange-brown for interfaces + private static final int ICON_ENUM_BG = 0xFF6B8A4A; // Green for enums + private static final int ICON_METHOD_BG = 0xFF8A4A6B; // Purple for methods + private static final int ICON_FIELD_BG = 0xFF4A8A6B; // Teal for fields + private static final int ICON_VAR_BG = 0xFF6B6B8A; // Blue-gray for variables + private static final int ICON_PARAM_BG = 0xFF8A8A4A; // Yellow for parameters + private static final int ICON_UNKNOWN_BG = 0xFF8A4A4A; // Red for unknown + + // ==================== RENDERING ==================== + + /** + * Render the hover tooltip. + * + * @param hoverState The current hover state + * @param screenWidth Screen width for positioning + * @param screenHeight Screen height for positioning + */ + public static void render(HoverState hoverState, int screenWidth, int screenHeight) { + if (!hoverState.isTooltipVisible()) return; + + TokenHoverInfo info = hoverState.getHoverInfo(); + if (info == null || !info.hasContent()) return; + + // Calculate content dimensions + int contentWidth = calculateContentWidth(info); + int contentHeight = calculateContentHeight(info); + + // Add padding + int boxWidth = Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, contentWidth + PADDING * 2 + ICON_SIZE + ICON_GAP)); + int boxHeight = contentHeight + PADDING * 2; + + // Position the tooltip + int tokenX = hoverState.getTokenScreenX(); + int tokenY = hoverState.getTokenScreenY(); + int lineHeight = ClientProxy.Font.height(); + + // Default: show below the token + int tooltipX = tokenX; + int tooltipY = tokenY + lineHeight + VERTICAL_OFFSET; + + // Adjust if tooltip would go off-screen + if (tooltipX + boxWidth > screenWidth - 10) { + tooltipX = screenWidth - boxWidth - 10; + } + if (tooltipX < 10) { + tooltipX = 10; + } + + if (tooltipY + boxHeight > screenHeight - 10) { + // Show above the token instead + tooltipY = tokenY - boxHeight - VERTICAL_OFFSET; + } + if (tooltipY < 10) { + tooltipY = 10; + } + + // Render the tooltip + renderTooltipBox(tooltipX, tooltipY, boxWidth, boxHeight, info); + } + + /** + * Render the tooltip box with all content. + */ + private static void renderTooltipBox(int x, int y, int width, int height, TokenHoverInfo info) { + // Disable scissor test temporarily for tooltip rendering + GL11.glDisable(GL11.GL_SCISSOR_TEST); + + // Draw background + Gui.drawRect(x, y, x + width, y + height, BG_COLOR); + + // Draw border + Gui.drawRect(x, y, x + width, y + 1, BORDER_COLOR); + Gui.drawRect(x, y + height - 1, x + width, y + height, BORDER_COLOR); + Gui.drawRect(x, y, x + 1, y + height, BORDER_COLOR); + Gui.drawRect(x + width - 1, y, x + width, y + height, BORDER_COLOR); + + int contentX = x + PADDING; + int contentY = y + PADDING; + int textX = contentX + ICON_SIZE + ICON_GAP; + int maxTextWidth = width - PADDING * 2 - ICON_SIZE - ICON_GAP; + + // Draw icon + String icon = info.getIconIndicator(); + if (icon != null && !icon.isEmpty()) { + drawIcon(contentX, contentY, icon); + } + + int currentY = contentY; + + // Draw errors first (if any) + List errors = info.getErrors(); + if (!errors.isEmpty()) { + for (String error : errors) { + drawText(textX, currentY, error, ERROR_COLOR); + currentY += ClientProxy.Font.height() + LINE_SPACING; + } + currentY += LINE_SPACING; // Extra space after errors + } + + // Draw package name + String packageName = info.getPackageName(); + if (packageName != null && !packageName.isEmpty()) { + // Draw package icon + drawText(textX, currentY, "\u25CB " + packageName, PACKAGE_COLOR); + currentY += ClientProxy.Font.height() + LINE_SPACING; + } + + // Draw declaration + List declaration = info.getDeclaration(); + if (!declaration.isEmpty()) { + int segmentX = textX; + for (TokenHoverInfo.TextSegment segment : declaration) { + int segmentWidth = ClientProxy.Font.width(segment.text); + + // Check if we need to wrap (simple wrapping for now) + if (segmentX + segmentWidth > x + width - PADDING && segmentX > textX) { + currentY += ClientProxy.Font.height() + LINE_SPACING; + segmentX = textX; + } + + drawText(segmentX, currentY, segment.text, 0xFF000000 | segment.color); + segmentX += segmentWidth; + } + currentY += ClientProxy.Font.height() + LINE_SPACING; + } + + // Draw documentation + List docs = info.getDocumentation(); + if (!docs.isEmpty()) { + currentY += LINE_SPACING; // Extra space before docs + for (String doc : docs) { + drawText(textX, currentY, doc, 0xFFA9B7C6); + currentY += ClientProxy.Font.height() + LINE_SPACING; + } + } + + // Draw additional info + List additionalInfo = info.getAdditionalInfo(); + if (!additionalInfo.isEmpty()) { + currentY += LINE_SPACING; + for (String line : additionalInfo) { + drawText(textX, currentY, line, INFO_COLOR); + currentY += ClientProxy.Font.height() + LINE_SPACING; + } + } + + // Re-enable scissor test + // GL11.glEnable(GL11.GL_SCISSOR_TEST); + } + + /** + * Draw an icon indicator. + */ + private static void drawIcon(int x, int y, String icon) { + int bgColor; + switch (icon) { + case "C": bgColor = ICON_CLASS_BG; break; + case "I": bgColor = ICON_INTERFACE_BG; break; + case "E": bgColor = ICON_ENUM_BG; break; + case "m": bgColor = ICON_METHOD_BG; break; + case "f": bgColor = ICON_FIELD_BG; break; + case "v": bgColor = ICON_VAR_BG; break; + case "p": bgColor = ICON_PARAM_BG; break; + default: bgColor = ICON_UNKNOWN_BG; break; + } + + // Draw icon background (rounded effect with small rect) + int bgY = y-2; + Gui.drawRect(x, bgY, x + ICON_SIZE, bgY + ICON_SIZE, 0xFF000000 | bgColor); + + // Draw icon letter centered + int textWidth = ClientProxy.Font.width(icon); + int textX = x + (ICON_SIZE - textWidth) / 2; + int textY = y + (ICON_SIZE - ClientProxy.Font.height()) / 2; + drawText(textX, textY, icon, 0xFFFFFFFF); + } + + /** + * Draw text using the Minecraft font renderer. + */ + private static void drawText(int x, int y, String text, int color) { + ClientProxy.Font.drawString(text, x, y, color); + } + + // ==================== DIMENSION CALCULATION ==================== + + /** + * Calculate the width needed for the content. + */ + private static int calculateContentWidth(TokenHoverInfo info) { + int maxWidth = 0; + + // Package name width + String packageName = info.getPackageName(); + if (packageName != null && !packageName.isEmpty()) { + maxWidth = Math.max(maxWidth, ClientProxy.Font.width("\u25CB " + packageName)); + } + + // Declaration width + List declaration = info.getDeclaration(); + int declWidth = 0; + for (TokenHoverInfo.TextSegment segment : declaration) { + declWidth += ClientProxy.Font.width(segment.text); + } + maxWidth = Math.max(maxWidth, declWidth); + + // Error widths + for (String error : info.getErrors()) { + maxWidth = Math.max(maxWidth, ClientProxy.Font.width(error)); + } + + // Documentation widths + for (String doc : info.getDocumentation()) { + maxWidth = Math.max(maxWidth, ClientProxy.Font.width(doc)); + } + + // Additional info widths + for (String line : info.getAdditionalInfo()) { + maxWidth = Math.max(maxWidth, ClientProxy.Font.width(line)); + } + + return maxWidth; + } + + /** + * Calculate the height needed for the content. + */ + private static int calculateContentHeight(TokenHoverInfo info) { + int lineHeight = ClientProxy.Font.height(); + int totalHeight = 0; + int lineCount = 0; + + // Errors + if (!info.getErrors().isEmpty()) { + lineCount += info.getErrors().size(); + totalHeight += LINE_SPACING; // Extra space after errors + } + + // Package name + if (info.getPackageName() != null && !info.getPackageName().isEmpty()) { + lineCount++; + } + + // Declaration + if (!info.getDeclaration().isEmpty()) { + lineCount++; + } + + // Documentation + if (!info.getDocumentation().isEmpty()) { + lineCount += info.getDocumentation().size(); + totalHeight += LINE_SPACING; // Extra space before docs + } + + // Additional info + if (!info.getAdditionalInfo().isEmpty()) { + lineCount += info.getAdditionalInfo().size(); + totalHeight += LINE_SPACING; // Extra space before info + } + + totalHeight += lineCount * (lineHeight + LINE_SPACING); + + return Math.max(ICON_SIZE, totalHeight); + } +}