diff --git a/2006Scape Client/src/main/java/Game.java b/2006Scape Client/src/main/java/Game.java index 0f90d6e3..fd9ce078 100644 --- a/2006Scape Client/src/main/java/Game.java +++ b/2006Scape Client/src/main/java/Game.java @@ -175,7 +175,7 @@ public class Game extends RSApplet { } static final boolean constructMusic() { - anInt720 = 20; + anInt720 = 0; try { if (ClientSettings.ANDROID) { aClass56_749 = (Class56) AndroidHooks.getMusicPlayer(); @@ -224,14 +224,7 @@ public class Game extends RSApplet { if (fetchMusic) { byte[] is = musicData; if (is != null) { - if (ClientSettings.ANDROID) - method853(musicVolume2, is, aBoolean995); - else if (anInt116 >= 0) - method684(aBoolean995, anInt116, musicVolume2, is); - else if (anInt139 >= 0) - method899(anInt139, -1, aBoolean995, is, musicVolume2); - else - method853(musicVolume2, is, aBoolean995); + method853(musicVolume2, is, aBoolean995); fetchMusic = false; } } @@ -249,7 +242,7 @@ public class Game extends RSApplet { aClass56_749.method833(); anInt478 = -1; aByteArray347 = null; - anInt720 = 20; + anInt720 = 0; anInt155 = 0; } if (is != null) { @@ -337,7 +330,7 @@ public class Game extends RSApplet { anInt720--; if (anInt720 == 0) { aClass56_749.method833(); - anInt720 = 20; + anInt720 = 0; anInt478 = -1; } } @@ -9936,11 +9929,7 @@ public class Game extends RSApplet { boolean isPortrait = isModern && (ClientSettings.VIEWPORT_WIDTH < ClientSettings.VIEWPORT_HEIGHT); int tooltipX = isModern ? (ClientSettings.ANDROID ? (isPortrait ? 16 : 72) : 8) : 4; int tooltipY = isModern ? (ClientSettings.ANDROID ? 28 : 20) : 15; - if (HD317Pipeline.isGpuActive()) { - chatTextDrawingArea.textLeftShadow(true, tooltipX, 0xffffff, s, tooltipY); - } else { - chatTextDrawingArea.method390(tooltipX, 0xffffff, s, loopCycle / 1000, tooltipY); - } + chatTextDrawingArea.textLeftShadow(true, tooltipX, 0xffffff, s, tooltipY); } public void drawMinimap() { diff --git a/2006Scape Client/src/main/java/GroundItemsOverlayPlugin.java b/2006Scape Client/src/main/java/GroundItemsOverlayPlugin.java deleted file mode 100644 index 5c0e0706..00000000 --- a/2006Scape Client/src/main/java/GroundItemsOverlayPlugin.java +++ /dev/null @@ -1,449 +0,0 @@ -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * RuneLite-style Ground Items Plugin for Revision 377 client. - * Features: - * - Highlighted items with custom magenta/cyan colors and wildcard matching. - * - Hidden items filter (omitted from overlay). - * - Tile collapsing (merges identical items on the same ground tile). - * - Vertical stacked offsets per tile (prevents overlapping labels). - * - Price & value tiers: Common, Low, Medium, High, and Insane value coloring. - * - Radiant 3D lootbeams for high-value and highlighted drops. - * - Deprioritizes left-click 'Take' for hidden ground items below 'Walk here'. - * - Chat commands (::highlight, ::hide, ::unhighlight, ::unhide, ::grounditems). - */ -public class GroundItemsOverlayPlugin extends ClientPlugin { - - // Configurable Settings - private boolean showNames = true; - private boolean showQuantities = true; - private boolean showValues = true; - private boolean collapseEntries = true; - private boolean showLootbeam = true; - private boolean deprioritizeHidden = true; - - private String highlightedItems = "clue scroll*, *whip, rune *, dragon *, dark bow"; - private String hiddenItems = "vial, empty vial, ashes, pot, jug, bucket, bones"; - - private int lowValueThreshold = 1000; - private int mediumValueThreshold = 10000; - private int highValueThreshold = 100000; - private int insaneValueThreshold = 1000000; - - // Opacity & Transparency settings (0 = transparent, 255 = solid) - private int boxOpacity = 100; - private int textOpacity = 200; - - // Color Palette (RuneLite Authentic) - public static final int COLOR_HIGHLIGHT = 0xdc00ff; // Magenta - public static final int COLOR_INSANE = 0xff9810; // Orange/Amber - public static final int COLOR_HIGH = 0xffd700; // Gold/Yellow - public static final int COLOR_MEDIUM = 0x00ffff; // Cyan - public static final int COLOR_LOW = 0x66ff66; // Light Green - public static final int COLOR_COMMON = 0xffffff; // White - - @Override - public String getName() { - return "Ground Items"; - } - - @Override - public String getDescription() { - return "RuneLite-style ground item labels, price tiers, lootbeams, and tile collapsing."; - } - - @Override - public String getAuthor() { - return "2006Scape"; - } - - @Override - public boolean isEnabledByDefault() { - return true; - } - - @Override - public List getConfigItems() { - List list = new ArrayList<>(); - list.add(new PluginConfigItem("showNames", "Show Ground Items", "Render names and values over ground items", showNames)); - list.add(new PluginConfigItem("highlightedItems", "Highlighted Items", "Comma-separated items or wildcards to highlight (e.g. rune *, whip)", highlightedItems)); - list.add(new PluginConfigItem("hiddenItems", "Hidden Items", "Comma-separated items or wildcards to hide (e.g. ashes, vial)", hiddenItems)); - list.add(new PluginConfigItem("collapseEntries", "Collapse Duplicates", "Collapse identical ground items on the same tile", collapseEntries)); - list.add(new PluginConfigItem("showQuantities", "Show Quantities", "Display quantity stack size next to item names", showQuantities)); - list.add(new PluginConfigItem("showValues", "Show Values", "Display store/alch value in gold next to items", showValues)); - list.add(new PluginConfigItem("showLootbeam", "Show Lootbeams", "Display radiant vertical light beams on valuable drops", showLootbeam)); - list.add(new PluginConfigItem("deprioritizeHidden", "Deprioritize Hidden", "Move left-click 'Take' below 'Walk here' for hidden items", deprioritizeHidden)); - list.add(new PluginConfigItem("lowValueThreshold", "Low Value (Green)", "Threshold for low value items (gp)", lowValueThreshold, 0, 1000000)); - list.add(new PluginConfigItem("mediumValueThreshold", "Medium Value (Cyan)", "Threshold for medium value items (gp)", mediumValueThreshold, 0, 10000000)); - list.add(new PluginConfigItem("highValueThreshold", "High Value (Gold)", "Threshold for high value items (gp)", highValueThreshold, 0, 100000000)); - list.add(new PluginConfigItem("insaneValueThreshold", "Insane Value (Orange)", "Threshold for insane value items (gp)", insaneValueThreshold, 0, 2000000000)); - list.add(new PluginConfigItem("boxOpacity", "Box Opacity", "Background pill box opacity (0 = transparent, 255 = solid)", boxOpacity, 0, 255)); - list.add(new PluginConfigItem("textOpacity", "Text Opacity", "Font transparency for item labels (50 = faint, 255 = solid)", textOpacity, 50, 255)); - list.add(new PluginConfigItem("chatCommands", "Chat Commands", "Allow ::highlight / ::unhighlight / ::hide in chat", true)); - return list; - } - - @Override - public void onConfigChanged(String key, Object value) { - if ("showNames".equals(key)) showNames = (Boolean) value; - else if ("highlightedItems".equals(key)) highlightedItems = (String) value; - else if ("hiddenItems".equals(key)) hiddenItems = (String) value; - else if ("collapseEntries".equals(key)) collapseEntries = (Boolean) value; - else if ("showQuantities".equals(key)) showQuantities = (Boolean) value; - else if ("showValues".equals(key)) showValues = (Boolean) value; - else if ("showLootbeam".equals(key)) showLootbeam = (Boolean) value; - else if ("deprioritizeHidden".equals(key)) deprioritizeHidden = (Boolean) value; - else if ("lowValueThreshold".equals(key)) lowValueThreshold = ((Number) value).intValue(); - else if ("mediumValueThreshold".equals(key)) mediumValueThreshold = ((Number) value).intValue(); - else if ("highValueThreshold".equals(key)) highValueThreshold = ((Number) value).intValue(); - else if ("insaneValueThreshold".equals(key)) insaneValueThreshold = ((Number) value).intValue(); - else if ("boxOpacity".equals(key)) boxOpacity = ((Number) value).intValue(); - else if ("textOpacity".equals(key)) textOpacity = ((Number) value).intValue(); - } - - /** - * Grouped item entry for rendering vertically stacked on a tile. - */ - private static class DisplayItem { - final int id; - final String name; - int amount; - final int singleValue; - long totalValue; - final boolean isHighlighted; - final int color; - - DisplayItem(PluginContext.GroundItemWrapper item, boolean isHighlighted, int color) { - this.id = item.id; - this.name = item.name; - this.amount = item.amount; - this.singleValue = item.value; - this.totalValue = item.totalValue; - this.isHighlighted = isHighlighted; - this.color = color; - } - - void addAmount(int add) { - this.amount += add; - this.totalValue = (long) this.singleValue * this.amount; - } - } - - @Override - public void onRenderOverlay(PluginGraphics g) { - if (!showNames || ctx == null || !ctx.isLoggedIn()) return; - - List rawItems = ctx.getGroundItems(); - if (rawItems == null || rawItems.isEmpty()) return; - - // Group items by tile: key = (worldX << 16) | (worldY & 0xffff) - Map> tileMap = new LinkedHashMap<>(); - Map tileCoords = new HashMap<>(); - - for (PluginContext.GroundItemWrapper raw : rawItems) { - if (raw.getDistance() > 20) continue; - - // Check hidden filter - if (isItemHidden(raw.name)) { - continue; - } - - boolean isHl = isItemHighlighted(raw.name); - int color = getItemColor(raw.name, raw.totalValue, isHl); - - long tileKey = (((long) raw.worldX) << 32) | (raw.worldY & 0xffffffffL); - List list = tileMap.computeIfAbsent(tileKey, k -> new ArrayList<>()); - tileCoords.putIfAbsent(tileKey, new int[]{raw.worldX, raw.worldY}); - - if (collapseEntries) { - // Check if identical item already on tile - DisplayItem existing = null; - for (DisplayItem d : list) { - if (d.id == raw.id) { - existing = d; - break; - } - } - if (existing != null) { - existing.addAmount(raw.amount); - continue; - } - } - - list.add(new DisplayItem(raw, isHl, color)); - } - - // Render each tile's stacked items - for (Map.Entry> entry : tileMap.entrySet()) { - long tileKey = entry.getKey(); - List itemsOnTile = entry.getValue(); - if (itemsOnTile.isEmpty()) continue; - - int[] coords = tileCoords.get(tileKey); - int tileX = coords[0]; - int tileY = coords[1]; - - // Sort so most valuable / highlighted items are on top - Collections.sort(itemsOnTile, (a, b) -> { - if (a.isHighlighted != b.isHighlighted) { - return a.isHighlighted ? 1 : -1; - } - return Long.compare(a.totalValue, b.totalValue); - }); - - // Check if tile qualifies for a lootbeam - if (showLootbeam) { - DisplayItem bestItem = itemsOnTile.get(itemsOnTile.size() - 1); - if (bestItem.isHighlighted || bestItem.totalValue >= highValueThreshold) { - g.drawLootbeam(tileX, tileY, bestItem.color); - } - } - - // Project ground coordinates - int[] screen = g.worldToScreen(tileX, tileY, 20); - if (screen == null) continue; - - int baseX = screen[0]; - int baseY = screen[1]; - - // Render items vertically stacked with offset - for (int i = 0; i < itemsOnTile.size(); i++) { - DisplayItem item = itemsOnTile.get(i); - int rowY = baseY - (i * 14); - - String label = buildItemLabel(item); - int textW = g.getTextWidth(label); - int boxX = baseX - (textW / 2) - 3; - int boxY = rowY - 11; - int boxW = textW + 6; - int boxH = 13; - - // Soft translucent background pill box - if (boxOpacity > 0) { - g.fillRect(boxX, boxY, boxW, boxH, 0x000000, boxOpacity); - } - - // Highlighted / Insane items get colored borders - if (item.isHighlighted || item.totalValue >= insaneValueThreshold) { - g.drawRect(boxX, boxY, boxW, boxH, item.color); - } else if (item.totalValue >= highValueThreshold) { - g.drawRect(boxX, boxY, boxW, boxH, 0x4a4338); - } - - // Render text with configured alpha transparency - g.drawCenteredString(label, baseX, rowY - 1, item.color, textOpacity); - } - } - } - - /** - * Deprioritizes left-click Take for hidden items below 'Walk here'. - */ - @Override - public void onPreMenuRender(List entries) { - if (!deprioritizeHidden || entries == null || entries.size() <= 1) return; - - // Default left-click action is at the end of the entries list - int topIdx = entries.size() - 1; - MenuEntry top = entries.get(topIdx); - - if ("Take".equalsIgnoreCase(top.getAction())) { - String targetName = MenuEntry.stripColorTags(top.getTarget()); - if (isItemHidden(targetName)) { - // Find Walk here entry - int walkIdx = -1; - for (int i = 0; i < entries.size(); i++) { - String clean = MenuEntry.stripColorTags(entries.get(i).getRawText()).toLowerCase(); - if (clean.startsWith("walk here") || clean.startsWith("walk")) { - walkIdx = i; - break; - } - } - if (walkIdx != -1 && walkIdx != topIdx) { - // Promote Walk here to the top (default left click) - MenuEntry walk = entries.remove(walkIdx); - entries.add(walk); - } - } - } - } - - private String buildItemLabel(DisplayItem item) { - StringBuilder sb = new StringBuilder(item.name); - if (showQuantities && item.amount > 1) { - sb.append(" (").append(formatQuantity(item.amount)).append(")"); - } - if (showValues && item.totalValue > 0) { - sb.append(" [").append(formatValue(item.totalValue)).append("]"); - } - return sb.toString(); - } - - private int getItemColor(String name, long totalValue, boolean isHighlighted) { - if (isHighlighted) return COLOR_HIGHLIGHT; - if (totalValue >= insaneValueThreshold) return COLOR_INSANE; - if (totalValue >= highValueThreshold) return COLOR_HIGH; - if (totalValue >= mediumValueThreshold) return COLOR_MEDIUM; - if (totalValue >= lowValueThreshold) return COLOR_LOW; - return COLOR_COMMON; - } - - public boolean isItemHighlighted(String name) { - return matchesAnyPattern(name, highlightedItems); - } - - public boolean isItemHidden(String name) { - return matchesAnyPattern(name, hiddenItems); - } - - private static boolean matchesAnyPattern(String text, String commaSeparatedPatterns) { - if (text == null || commaSeparatedPatterns == null || commaSeparatedPatterns.trim().isEmpty()) { - return false; - } - String cleanText = text.trim().toLowerCase(); - String[] patterns = commaSeparatedPatterns.split(","); - for (String p : patterns) { - String pat = p.trim().toLowerCase(); - if (pat.isEmpty()) continue; - if (matchesWildcard(cleanText, pat)) { - return true; - } - } - return false; - } - - private static boolean matchesWildcard(String text, String pattern) { - if ("*".equals(pattern)) return true; - if (pattern.startsWith("*") && pattern.endsWith("*")) { - String mid = pattern.substring(1, pattern.length() - 1); - return text.contains(mid); - } - if (pattern.startsWith("*")) { - return text.endsWith(pattern.substring(1)); - } - if (pattern.endsWith("*")) { - return text.startsWith(pattern.substring(0, pattern.length() - 1)); - } - return text.equals(pattern); - } - - private static String formatQuantity(int amount) { - if (amount >= 10000000) return (amount / 1000000) + "m"; - if (amount >= 100000) return (amount / 1000) + "k"; - if (amount >= 1000) { - DecimalFormat df = new DecimalFormat("#,###"); - return df.format(amount); - } - return String.valueOf(amount); - } - - private static String formatValue(long value) { - if (value >= 10000000) return (value / 1000000) + "M gp"; - if (value >= 1000000) return String.format("%.1fM gp", value / 1000000.0); - if (value >= 1000) return (value / 1000) + "k gp"; - return value + " gp"; - } - - @Override - public boolean onCommand(String command, String[] args) { - String cmd = command.toLowerCase(); - - if ("highlight".equals(cmd) || "hl".equals(cmd)) { - if (args.length > 0) { - String item = joinArgs(args); - highlightedItems = (highlightedItems != null && !highlightedItems.isEmpty()) ? highlightedItems + ", " + item : item; - if (ctx != null) ctx.sendClientMessage("Added to ground item highlights: " + item); - } else if (ctx != null) { - ctx.sendClientMessage("Usage: ::highlight "); - } - return true; - } - - if ("unhighlight".equals(cmd) || "unhl".equals(cmd)) { - if (args.length > 0) { - String item = joinArgs(args); - highlightedItems = removePattern(highlightedItems, item); - if (ctx != null) ctx.sendClientMessage("Removed from ground item highlights: " + item); - } - return true; - } - - if ("hide".equals(cmd)) { - if (args.length > 0) { - String item = joinArgs(args); - hiddenItems = (hiddenItems != null && !hiddenItems.isEmpty()) ? hiddenItems + ", " + item : item; - if (ctx != null) ctx.sendClientMessage("Added to hidden ground items: " + item); - } else if (ctx != null) { - ctx.sendClientMessage("Usage: ::hide "); - } - return true; - } - - if ("unhide".equals(cmd)) { - if (args.length > 0) { - String item = joinArgs(args); - hiddenItems = removePattern(hiddenItems, item); - if (ctx != null) ctx.sendClientMessage("Removed from hidden ground items: " + item); - } - return true; - } - - if ("grounditems".equals(cmd) || "gi".equals(cmd)) { - if (ctx != null) { - ctx.sendClientMessage("Ground Items Config: [Highlighted: " + highlightedItems + "]"); - ctx.sendClientMessage("Hidden: [" + hiddenItems + "]"); - ctx.sendClientMessage("Tiers: Low=" + lowValueThreshold + "gp, Med=" + mediumValueThreshold + "gp, High=" + highValueThreshold + "gp, Insane=" + insaneValueThreshold + "gp"); - } - return true; - } - - return false; - } - - private static String joinArgs(String[] args) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < args.length; i++) { - if (i > 0) sb.append(" "); - sb.append(args[i]); - } - return sb.toString().trim(); - } - - private static String removePattern(String csv, String target) { - if (csv == null || target == null) return csv; - String[] parts = csv.split(","); - StringBuilder sb = new StringBuilder(); - for (String p : parts) { - String trimmed = p.trim(); - if (!trimmed.equalsIgnoreCase(target.trim()) && !trimmed.isEmpty()) { - if (sb.length() > 0) sb.append(", "); - sb.append(trimmed); - } - } - return sb.toString(); - } - - public int getBoxOpacity() { - return boxOpacity; - } - - public void setBoxOpacity(int boxOpacity) { - this.boxOpacity = Math.max(0, Math.min(255, boxOpacity)); - } - - public int getTextOpacity() { - return textOpacity; - } - - public void setTextOpacity(int textOpacity) { - this.textOpacity = Math.max(50, Math.min(255, textOpacity)); - } -} diff --git a/2006Scape Client/src/main/java/MenuEntrySwapperPlugin.java b/2006Scape Client/src/main/java/MenuEntrySwapperPlugin.java deleted file mode 100644 index a2666843..00000000 --- a/2006Scape Client/src/main/java/MenuEntrySwapperPlugin.java +++ /dev/null @@ -1,156 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * RuneLite-style Menu Entry Swapper Plugin. - * Allows left-click swapping for NPCs, objects, ground items, and custom rules. - */ -public class MenuEntrySwapperPlugin extends ClientPlugin { - - private boolean swapBank = true; - private boolean swapTrade = true; - private boolean swapPickpocket = true; - private boolean swapTravel = true; - private boolean chatCommands = true; - private String customRules = ""; - - @Override - public String getName() { - return "Menu Entry Swapper"; - } - - @Override - public String getDescription() { - return "Swaps default left-click actions for Bank, Pickpocket, Trade, and custom rules."; - } - - @Override - public String getAuthor() { - return "2006Scape"; - } - - @Override - public boolean isEnabledByDefault() { - return true; - } - - @Override - public List getConfigItems() { - List list = new ArrayList<>(); - list.add(new PluginConfigItem("swapBank", "Swap Bank", "Promote 'Bank' over 'Talk-to' on bankers", swapBank)); - list.add(new PluginConfigItem("swapTrade", "Swap Trade", "Promote 'Trade' over 'Talk-to' on shopkeepers", swapTrade)); - list.add(new PluginConfigItem("swapPickpocket", "Swap Pickpocket", "Promote 'Pickpocket' on NPCs", swapPickpocket)); - list.add(new PluginConfigItem("swapTravel", "Swap Travel", "Promote 'Travel'/'Pay-fare' on captains", swapTravel)); - list.add(new PluginConfigItem("customRules", "Custom Rules", "Comma-separated Option:Target pairs (e.g. Bury:Bones)", customRules)); - list.add(new PluginConfigItem("chatCommands", "Chat Commands", "Allow ::swap / ::swapper in chat", chatCommands)); - return list; - } - - @Override - public void onConfigChanged(String key, Object value) { - if ("swapBank".equals(key)) swapBank = (Boolean) value; - else if ("swapTrade".equals(key)) swapTrade = (Boolean) value; - else if ("swapPickpocket".equals(key)) swapPickpocket = (Boolean) value; - else if ("swapTravel".equals(key)) swapTravel = (Boolean) value; - else if ("chatCommands".equals(key)) chatCommands = (Boolean) value; - else if ("customRules".equals(key)) customRules = (String) value; - } - - @Override - public void onPreMenuRender(List entries) { - if (entries == null || entries.size() <= 1) { - return; - } - - // Apply custom swap rules first - if (customRules != null && !customRules.trim().isEmpty()) { - String[] rules = customRules.split(","); - for (String rule : rules) { - String[] parts = rule.trim().split(":"); - if (parts.length >= 2) { - String action = parts[0].trim(); - String target = parts[1].trim(); - if (promoteEntry(entries, action, target)) { - return; - } - } - } - } - - // Built-in Bank swap (Banker, Bank booth, Bank chest) - if (swapBank) { - if (promoteEntry(entries, "Bank", "*") || promoteEntry(entries, "Open", "Bank")) { - return; - } - } - - // Built-in Pickpocket swap - if (swapPickpocket) { - if (promoteEntry(entries, "Pickpocket", "*")) { - return; - } - } - - // Built-in Trade swap - if (swapTrade) { - if (promoteEntry(entries, "Trade", "*")) { - return; - } - } - - // Built-in Travel / Pay-fare swap - if (swapTravel) { - if (promoteEntry(entries, "Pay-fare", "*") || - promoteEntry(entries, "Travel", "*") || - promoteEntry(entries, "Charter", "*") || - promoteEntry(entries, "Teleport", "*")) { - return; - } - } - } - - private boolean promoteEntry(List entries, String action, String target) { - int foundIdx = -1; - for (int i = 0; i < entries.size(); i++) { - MenuEntry e = entries.get(i); - if (e.matches(action, target)) { - foundIdx = i; - break; - } - } - if (foundIdx != -1 && foundIdx != entries.size() - 1) { - MenuEntry targetEntry = entries.remove(foundIdx); - entries.add(targetEntry); // Top of menu (left-click) - return true; - } - return false; - } - - @Override - public boolean onCommand(String command, String[] args) { - if ("swap".equalsIgnoreCase(command) || "swapper".equalsIgnoreCase(command)) { - if (args.length >= 2 && "add".equalsIgnoreCase(args[0])) { - String newRule = args[1].trim(); - customRules = (customRules != null && !customRules.isEmpty()) ? customRules + "," + newRule : newRule; - if (ctx != null) { - ctx.sendClientMessage("Added swap rule: " + newRule); - } - return true; - } else if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { - customRules = ""; - if (ctx != null) { - ctx.sendClientMessage("Custom swap rules cleared."); - } - return true; - } else { - if (ctx != null) { - ctx.sendClientMessage("Menu Swapper Rules: " + customRules); - ctx.sendClientMessage("Usage: ::swap add : or ::swap clear"); - } - return true; - } - } - return false; - } -} diff --git a/2006Scape Client/src/main/java/PluginContext.java b/2006Scape Client/src/main/java/PluginContext.java index 596395a2..5a50d002 100644 --- a/2006Scape Client/src/main/java/PluginContext.java +++ b/2006Scape Client/src/main/java/PluginContext.java @@ -580,18 +580,51 @@ public class PluginContext { } public List getGroundItems() { + return getGroundItemsInternal(104); + } + + /** + * Scans only tiles within {@code radius} of the player instead of the full 104x104 region. + */ + public List getGroundItems(int radius) { if (!isLoggedIn()) return Collections.emptyList(); + if (game == null) { + // Allow test mocks that override getGroundItems() to continue working without a Game instance. + List all = getGroundItems(); + if (all == null || all.isEmpty()) return Collections.emptyList(); + List filtered = new ArrayList<>(); + for (GroundItemWrapper item : all) { + if (item.getDistance() <= radius) { + filtered.add(item); + } + } + return filtered; + } + return getGroundItemsInternal(radius); + } + + private List getGroundItemsInternal(int radius) { + if (!isLoggedIn() || game == null) return Collections.emptyList(); List list = new ArrayList<>(); int p = game.plane; + int plx = getPlayerLocalX(); + int ply = getPlayerLocalY(); int px = getPlayerX(); int py = getPlayerY(); + int minX = Math.max(0, plx - radius); + int maxX = Math.min(103, plx + radius); + int minY = Math.max(0, ply - radius); + int maxY = Math.min(103, ply + radius); - for (int x = 0; x < 104; x++) { - for (int y = 0; y < 104; y++) { + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y <= maxY; y++) { NodeList nodeList = game.groundArray[p][x][y]; if (nodeList != null) { for (Item item = (Item) nodeList.getFirst(); item != null; item = (Item) nodeList.getNext()) { - list.add(new GroundItemWrapper(item, x, y, p, game.baseX, game.baseY, px, py)); + GroundItemWrapper w = new GroundItemWrapper(item, x, y, p, game.baseX, game.baseY, px, py); + if (w.getDistance() <= radius) { + list.add(w); + } } } } @@ -600,6 +633,45 @@ public class PluginContext { return list; } + /** + * Lightweight fingerprint of ground items within {@code radius} tiles without allocating wrappers or looking up ItemDefs. + */ + public long getGroundItemsSignature(int radius) { + if (!isLoggedIn()) return 0L; + if (game == null) { + List items = getGroundItems(radius); + long h = 1469598103934665603L; + for (int i = 0; i < items.size(); i++) { + GroundItemWrapper w = items.get(i); + h = (h * 1099511628211L) ^ w.worldX ^ ((long) w.worldY << 16) ^ ((long) w.id << 32) ^ ((long) w.amount << 48); + } + return h ^ items.size(); + } + int p = game.plane; + int plx = getPlayerLocalX(); + int ply = getPlayerLocalY(); + int minX = Math.max(0, plx - radius); + int maxX = Math.min(103, plx + radius); + int minY = Math.max(0, ply - radius); + int maxY = Math.min(103, ply + radius); + long h = 1469598103934665603L; + int count = 0; + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y <= maxY; y++) { + NodeList nodeList = game.groundArray[p][x][y]; + if (nodeList != null) { + for (Item item = (Item) nodeList.getFirst(); item != null; item = (Item) nodeList.getNext()) { + int wx = x + game.baseX; + int wy = y + game.baseY; + h = (h * 1099511628211L) ^ wx ^ ((long) wy << 16) ^ ((long) item.ID << 32) ^ ((long) item.amount << 48); + count++; + } + } + } + } + return (h ^ ((long) p << 24) ^ count); + } + public GroundItemWrapper findNearestGroundItem(String... names) { List items = getGroundItems(); for (GroundItemWrapper item : items) { @@ -1669,6 +1741,14 @@ public class PluginContext { // Utilities & Configuration // ========================================================================= + public List createList() { + return new ArrayList<>(); + } + + public java.util.Map createMap() { + return new java.util.HashMap<>(); + } + public void sendClientMessage(String msg) { if (game != null && msg != null) { game.pushMessage(msg, 0, ""); diff --git a/2006Scape Client/src/main/java/PluginGraphics.java b/2006Scape Client/src/main/java/PluginGraphics.java index d6417509..d17343e4 100644 --- a/2006Scape Client/src/main/java/PluginGraphics.java +++ b/2006Scape Client/src/main/java/PluginGraphics.java @@ -178,6 +178,18 @@ public class PluginGraphics { return new int[]{game.spriteDrawX, game.spriteDrawY}; } + /** + * Projects world coordinate to screen (viewport) coordinate as a 2-element List [x, y], or null if off-screen. + */ + public java.util.List worldToScreenList(int worldX, int worldY, int heightOffset) { + int[] pos = worldToScreen(worldX, worldY, heightOffset); + if (pos == null) return null; + java.util.List list = new java.util.ArrayList<>(2); + list.add(pos[0]); + list.add(pos[1]); + return list; + } + /** * Draws a tile highlight marker and label in the 3D world. */ @@ -224,6 +236,85 @@ public class PluginGraphics { drawHorizontalLine(gx - 3, gy + 1, 7, rgb); } + /** + * Renders pre-computed ground item tile batches in compiled Java, avoiding per-frame + * script loop and reflection overhead (critical for TeaVM/Web performance). + */ + @SuppressWarnings("unchecked") + public void drawTileLabelBatches(java.util.List tiles, int boxOpacity, int textOpacity) { + if (tiles == null || tiles.isEmpty()) return; + for (int t = 0; t < tiles.size(); t++) { + Object tileObj = tiles.get(t); + if (!(tileObj instanceof java.util.Map)) continue; + java.util.Map tile = (java.util.Map) tileObj; + + int tileX = toIntValue(tile.get("x"), 0); + int tileY = toIntValue(tile.get("y"), 0); + + Object beamFlag = tile.get("hasBeam"); + if (beamFlag instanceof Boolean && ((Boolean) beamFlag).booleanValue()) { + drawLootbeam(tileX, tileY, toIntValue(tile.get("beamColor"), 0xffffff)); + } + + int baseX; + int baseY; + if (game != null) { + int[] pos = worldToScreen(tileX, tileY, 20); + if (pos == null) continue; + baseX = pos[0]; + baseY = pos[1]; + } else { + java.util.List screen = worldToScreenList(tileX, tileY, 20); + if (screen == null || screen.size() < 2) continue; + baseX = screen.get(0); + baseY = screen.get(1); + } + + Object itemsObj = tile.get("items"); + if (!(itemsObj instanceof java.util.List)) continue; + java.util.List itemsOnTile = (java.util.List) itemsObj; + + for (int rowIdx = 0; rowIdx < itemsOnTile.size(); rowIdx++) { + Object itemObj = itemsOnTile.get(rowIdx); + if (!(itemObj instanceof java.util.Map)) continue; + java.util.Map item = (java.util.Map) itemObj; + + int rowY = baseY - (rowIdx * 14); + int color = toIntValue(item.get("color"), 0xffffff); + int borderColor = toIntValue(item.get("borderColor"), -1); + Object labelObj = item.get("label"); + String label = labelObj != null ? labelObj.toString() : ""; + + int textW = toIntValue(item.get("textW"), -1); + if (textW < 0) { + textW = getTextWidth(label); + item.put("textW", textW); + } + + int halfW = textW / 2; + int boxX = baseX - halfW - 3; + int boxY = rowY - 11; + int boxW = textW + 6; + int boxH = 13; + + if (boxOpacity > 0) { + fillRect(boxX, boxY, boxW, boxH, 0x000000, boxOpacity); + } + if (borderColor != -1) { + drawRect(boxX, boxY, boxW, boxH, borderColor); + } + drawCenteredString(label, baseX, rowY - 1, color, textOpacity); + } + } + } + + private static int toIntValue(Object val, int fallback) { + if (val instanceof Number) { + return ((Number) val).intValue(); + } + return fallback; + } + /** * Renders a list of world {x, y} path tiles as step markers on screen. */ diff --git a/2006Scape Client/src/main/java/PluginManager.java b/2006Scape Client/src/main/java/PluginManager.java index 0eeb83b3..f9f69a4d 100644 --- a/2006Scape Client/src/main/java/PluginManager.java +++ b/2006Scape Client/src/main/java/PluginManager.java @@ -22,6 +22,7 @@ public class PluginManager { private final List plugins = new ArrayList<>(); private final List scripts = new ArrayList<>(); private final List lastLoadErrors = new ArrayList<>(); + private final Set reportedPluginErrors = new HashSet<>(); private ClientScript activeScript = null; private final int[] lastSkillXp = new int[25]; private int lastPlayerAnim = Integer.MIN_VALUE; @@ -90,8 +91,6 @@ public class PluginManager { // ========================================================================= private void registerBuiltIns() { - registerPlugin(new MenuEntrySwapperPlugin()); - registerPlugin(new GroundItemsOverlayPlugin()); registerPlugin(new Hd317Plugin()); } @@ -137,29 +136,47 @@ public class PluginManager { plugins.add(plugin); } - // Load saved enabled state or default + applyConfigToPlugin(plugin, true); + } + + private void applyConfigToPlugin(ClientPlugin plugin, boolean startIfEnabled) { String key = "plugin." + plugin.getName().replace(' ', '_') + ".enabled"; + boolean wasEnabled = plugin.isEnabled(); boolean enabled = Boolean.parseBoolean(configProps.getProperty(key, String.valueOf(plugin.isEnabledByDefault()))); plugin.setEnabled(enabled); - // Load saved config items for (PluginConfigItem item : plugin.getConfigItems()) { String propKey = "config." + plugin.getName().replace(' ', '_') + "." + item.getKey(); if (configProps.containsKey(propKey)) { - String valStr = configProps.getProperty(propKey); - applyConfigValue(plugin, item, valStr); + applyConfigValue(plugin, item, configProps.getProperty(propKey)); } } - if (enabled) { + if (enabled && (!wasEnabled || startIfEnabled)) { try { plugin.onStart(context); } catch (Throwable t) { System.err.println("Error starting plugin " + plugin.getName() + ": " + t.getMessage()); } + } else if (!enabled && wasEnabled) { + try { + plugin.onStop(); + } catch (Throwable ignored) {} } } + public synchronized void reloadStorage() { + configProps.clear(); + loadConfig(); + for (int i = 0; i < plugins.size(); i++) { + ClientPlugin p = plugins.get(i); + if (!(p instanceof ScriptInterpreter.InterpretedPlugin)) { + applyConfigToPlugin(p, false); + } + } + reloadExternal(); + } + public synchronized void registerScript(ClientScript script) { if (script == null) return; if (!isApiCompatible(script.getMinApiVersion())) { @@ -222,6 +239,7 @@ public class PluginManager { } public synchronized void reloadExternal() { + reportedPluginErrors.clear(); // Stop active external scripts/plugins first if (activeScript != null) { stopScript(activeScript); @@ -353,6 +371,8 @@ public class PluginManager { parseConfigLines(webCfg); return; } + // Seed web localStorage config on first boot so the Storage editor sees plugin_config.ini + saveConfig(); if (!configFile.exists()) return; try (FileInputStream fis = new FileInputStream(configFile); java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(fis, java.nio.charset.StandardCharsets.UTF_8))) { @@ -596,7 +616,7 @@ public class PluginManager { try { p.onGameTick(); } catch (Throwable t) { - System.err.println("Plugin " + p.getName() + " tick error: " + t.getMessage()); + reportPluginError(p, "onGameTick", t); } } } @@ -621,7 +641,7 @@ public class PluginManager { try { p.onPreMenuRender(entries); } catch (Throwable t) { - System.err.println("Plugin " + p.getName() + " menu error: " + t.getMessage()); + reportPluginError(p, "onPreMenuRender", t); } } } @@ -748,7 +768,7 @@ public class PluginManager { try { p.onRenderOverlay(graphics); } catch (Throwable t) { - System.err.println("Plugin " + p.getName() + " overlay error: " + t.getMessage()); + reportPluginError(p, "onRenderOverlay", t); } } } @@ -762,6 +782,15 @@ public class PluginManager { } } + private void reportPluginError(ClientPlugin p, String phase, Throwable t) { + String msg = t.getMessage() != null ? t.getMessage() : t.getClass().getSimpleName(); + System.err.println("Plugin " + p.getName() + " " + phase + " error: " + msg); + String key = p.getName() + ":" + phase; + if (reportedPluginErrors.add(key) && context != null && context.isLoggedIn()) { + context.sendClientMessage("@red@[Plugin Error] " + p.getName() + " (" + phase + "): " + msg); + } + } + public boolean onCommand(String input) { if (input == null || !input.startsWith("::")) return false; String clean = input.substring(2).trim(); diff --git a/2006Scape Client/src/main/java/PluginPanelUI.java b/2006Scape Client/src/main/java/PluginPanelUI.java index 8f98b1d4..1070ffd7 100644 --- a/2006Scape Client/src/main/java/PluginPanelUI.java +++ b/2006Scape Client/src/main/java/PluginPanelUI.java @@ -17,6 +17,13 @@ public class PluginPanelUI { private static int scrollOffset = 0; private static String searchQuery = ""; private static boolean searchFocused = false; + private static String editingStringKey = null; + private static String editingStringValue = ""; + private static int editingStringCursor = 0; + private static List editorLines = null; + private static List editorLineStarts = null; + private static int editorStartLine = 0; + private static PluginGraphics lastEditorGraphics = null; private static String openDropdownKey = null; private static int dropdownScrollOffset = 0; private static boolean isDraggingDropdown = false; @@ -39,13 +46,70 @@ public class PluginPanelUI { } public static boolean isSearchFocused() { - return modalOpen && searchFocused && (currentModalTab == 0 || currentModalTab == 1 || currentModalTab == 2); + return modalOpen && ((searchFocused && (currentModalTab == 0 || currentModalTab == 1 || currentModalTab == 2)) + || (currentModalTab == 3 && editingStringKey != null)); + } + + private static void commitStringEdit(PluginManager pm) { + if (editingStringKey == null) return; + if (pm != null && configTarget != null) { + List items = getVisibleConfigItems(pm, configTarget); + if (items != null) { + for (PluginConfigItem item : items) { + if (editingStringKey.equals(item.getKey())) { + pm.setConfigValue(configTarget, item, editingStringValue != null ? editingStringValue : ""); + break; + } + } + } + } + editingStringKey = null; + editingStringValue = ""; + editingStringCursor = 0; + editorLines = null; + editorLineStarts = null; } public static void handleKeyChar(int ch) { if (!isSearchFocused()) { return; } + if (currentModalTab == 3 && editingStringKey != null) { + if (editingStringValue == null) editingStringValue = ""; + int len = editingStringValue.length(); + if (editingStringCursor < 0) editingStringCursor = 0; + if (editingStringCursor > len) editingStringCursor = len; + + if (ch == 1) { + if (editingStringCursor > 0) editingStringCursor--; + } else if (ch == 2) { + if (editingStringCursor < len) editingStringCursor++; + } else if (ch == 1000) { + editingStringCursor = 0; + } else if (ch == 1001) { + editingStringCursor = len; + } else if (ch == 8) { + if (editingStringCursor > 0) { + editingStringValue = editingStringValue.substring(0, editingStringCursor - 1) + + editingStringValue.substring(editingStringCursor); + editingStringCursor--; + } + } else if (ch == 10 || ch == 13) { + commitStringEdit(PluginManager.get()); + } else if (ch == 27) { + editingStringKey = null; + editingStringValue = ""; + editingStringCursor = 0; + editorLines = null; + editorLineStarts = null; + } else if (ch >= 32 && ch <= 126 && len < 1024) { + editingStringValue = editingStringValue.substring(0, editingStringCursor) + + (char) ch + + editingStringValue.substring(editingStringCursor); + editingStringCursor++; + } + return; + } if (ch == 8) { if (!searchQuery.isEmpty()) { searchQuery = searchQuery.substring(0, searchQuery.length() - 1); @@ -82,6 +146,7 @@ public class PluginPanelUI { } public static void closeModal() { + commitStringEdit(PluginManager.get()); modalOpen = false; searchFocused = false; configTarget = null; @@ -676,7 +741,7 @@ public class PluginPanelUI { drawStoneBox(g, mx, my, MODAL_WIDTH, MODAL_HEIGHT); // 2. Centered Header in Authentic RuneScape Gold with drop shadow - String title = scriptsAvailable ? "RUNELITE PLUGIN & SCRIPT HUB" : "RUNELITE PLUGIN HUB"; + String title = scriptsAvailable ? ClientSettings.SERVER_NAME + " PLUGIN & SCRIPT HUB" : ClientSettings.SERVER_NAME + " PLUGIN HUB"; if (game != null && game.aTextDrawingArea_1271 != null) { game.aTextDrawingArea_1271.textCenterShadow(0xff981f, mx + (MODAL_WIDTH / 2), title, my + 19, true); } else { @@ -791,6 +856,7 @@ public class PluginPanelUI { DrawingArea.defaultDrawingAreaSize(); } drawConfigDropdownOverlay(g, pm, wellInnerX, wellInnerW, contentY, contentH, headerH); + drawConfigStringEditorOverlay(g, pm, wellInnerX, wellInnerW, contentY, contentH, headerH); } else { currentModalTab = 0; } @@ -1298,7 +1364,7 @@ public class PluginPanelUI { int maxLabelW = (item.getType() == PluginConfigItem.Type.BOOLEAN) ? (w - 60 - 20) : (item.getType() == PluginConfigItem.Type.INTEGER) ? (w - 126 - 20) - : (item.getType() == PluginConfigItem.Type.CHOICE) ? (w - DROPDOWN_WIDTH - 20) : (w - 180); + : (item.getType() == PluginConfigItem.Type.CHOICE) ? (w - DROPDOWN_WIDTH - 20) : (w - 230); g.drawStringTruncated(item.getLabel(), x + 10, rowY + 20, maxLabelW, 0xffffff, false); if (item.getType() == PluginConfigItem.Type.BOOLEAN) { @@ -1364,7 +1430,19 @@ public class PluginPanelUI { g.drawHorizontalLine(arrowX + 1, btnY + 1, 22, 0x655542); g.drawStringBold(isOpen ? "^" : "v", arrowX + 8, btnY + 19, 0xffffff, true); } else { - g.drawString("(Edit in .properties or chat)", x + w - 170, rowY + 20, 0xa09484, false); + int boxW = 220; + int boxX = x + w - boxW; + int boxY = rowY + 3; + int boxH = 24; + boolean isEditing = item.getKey().equals(editingStringKey); + Object rawVal = pm.getConfigValue(configTarget, item); + String strVal = isEditing ? editingStringValue : (rawVal != null ? String.valueOf(rawVal) : ""); + String displayVal = strVal.isEmpty() ? "(click to edit)" : strVal; + + g.fillRect(boxX, boxY, boxW, boxH, isEditing ? 0x1a1712 : 0x221d17, 255); + g.drawRect(boxX, boxY, boxW, boxH, isEditing ? 0xd9a84e : 0x4e4230); + g.drawStringTruncated(displayVal, boxX + 6, boxY + 17, boxW - 12, + isEditing ? 0xffffff : (strVal.isEmpty() ? 0x807566 : 0xe6d5a8), false); } } rowY += 32; @@ -1432,6 +1510,142 @@ public class PluginPanelUI { } } + private static int[] getStringEditorBounds(int wellInnerX, int wellInnerW, int contentY, int contentH, int headerH) { + int edX = wellInnerX + 12; + int edW = Math.max(200, wellInnerW - 24); + int availH = Math.max(100, contentH - headerH); + int edH = Math.min(166, availH - 12); + int edY = contentY + headerH + Math.max(4, (availH - edH) / 2); + return new int[]{edX, edY, edW, edH}; + } + + private static void wrapTextForWidth(PluginGraphics g, String text, int maxW, List outLines, List outStarts) { + outLines.clear(); + outStarts.clear(); + if (text == null || text.isEmpty()) { + outLines.add(""); + outStarts.add(0); + return; + } + int start = 0; + int len = text.length(); + while (start < len) { + int end = start; + int lastBreak = -1; + while (end < len) { + char c = text.charAt(end); + if (c == ',' || c == ' ') { + lastBreak = end + 1; + } + if (g.getTextWidth(text.substring(start, end + 1)) > maxW) { + break; + } + end++; + } + if (end == start) { + end = start + 1; + } else if (end < len && lastBreak > start) { + end = lastBreak; + } + outLines.add(text.substring(start, end)); + outStarts.add(start); + start = end; + } + } + + private static void drawConfigStringEditorOverlay(PluginGraphics g, PluginManager pm, int wellInnerX, int wellInnerW, + int contentY, int contentH, int headerH) { + if (editingStringKey == null || configTarget == null) { + return; + } + List items = getVisibleConfigItems(pm, configTarget); + PluginConfigItem targetItem = null; + if (items != null) { + for (PluginConfigItem item : items) { + if (editingStringKey.equals(item.getKey())) { + targetItem = item; + break; + } + } + } + if (targetItem == null) { + return; + } + + // Dim background over config list + g.fillRect(wellInnerX, contentY + headerH, wellInnerW, contentH - headerH, 0x0a0907, 175); + + int[] b = getStringEditorBounds(wellInnerX, wellInnerW, contentY, contentH, headerH); + int edX = b[0], edY = b[1], edW = b[2], edH = b[3]; + + g.fillRect(edX, edY, edW, edH, 0x2a241d, 255); + g.drawRect(edX, edY, edW, edH, 0x0e0c09); + g.drawRect(edX + 1, edY + 1, edW - 2, edH - 2, 0x52473a); + + g.drawStringBoldTruncated("Edit: " + targetItem.getLabel(), edX + 10, edY + 18, edW - 20, 0xff981f, true); + + int inputX = edX + 10; + int inputY = edY + 25; + int inputW = edW - 20; + int inputH = edH - 61; + g.fillRect(inputX, inputY, inputW, inputH, 0x16130f, 255); + g.drawRect(inputX, inputY, inputW, inputH, 0xd9a84e); + + String val = editingStringValue != null ? editingStringValue : ""; + int cursor = Math.max(0, Math.min(val.length(), editingStringCursor)); + if (editorLines == null) editorLines = new java.util.ArrayList(); + if (editorLineStarts == null) editorLineStarts = new java.util.ArrayList(); + wrapTextForWidth(g, val, inputW - 14, editorLines, editorLineStarts); + lastEditorGraphics = g; + + int cursorLine = Math.max(0, editorLines.size() - 1); + for (int li = 0; li < editorLines.size(); li++) { + int lStart = editorLineStarts.get(li); + int lEnd = lStart + editorLines.get(li).length(); + boolean isLast = (li == editorLines.size() - 1); + if (cursor >= lStart && (cursor < lEnd || isLast)) { + cursorLine = li; + break; + } + } + + int lineH = 14; + int maxLines = Math.max(1, (inputH - 8) / lineH); + if (editorLines.size() <= maxLines) { + editorStartLine = 0; + } else { + if (cursorLine < editorStartLine) { + editorStartLine = cursorLine; + } else if (cursorLine >= editorStartLine + maxLines) { + editorStartLine = cursorLine - maxLines + 1; + } + if (editorStartLine > editorLines.size() - maxLines) { + editorStartLine = editorLines.size() - maxLines; + } + if (editorStartLine < 0) editorStartLine = 0; + } + + int textY = inputY + 16; + int endLine = Math.min(editorLines.size(), editorStartLine + maxLines); + for (int li = editorStartLine; li < endLine; li++) { + String line = editorLines.get(li); + g.drawString(line, inputX + 7, textY, 0xffffff, false); + if (li == cursorLine) { + int inLine = Math.max(0, Math.min(line.length(), cursor - editorLineStarts.get(li))); + int caretX = inputX + 7 + g.getTextWidth(line.substring(0, inLine)); + g.drawVerticalLine(caretX, textY - 11, 13, 0xffd700); + } + textY += lineH; + } + + int btnY = edY + edH - 28; + int btnH = 22; + int btnW = 64; + drawColoredButton(g, edX + 10, btnY, btnW, btnH, "Clear", 0x4a2020, 0x6e3232, 0x281111, 0xffb0b0); + drawColoredButton(g, edX + edW - 10 - btnW * 2 - 8, btnY, btnW, btnH, "Cancel", 0x332c23, 0x52473a, 0x181410, 0xffffff); + drawColoredButton(g, edX + edW - 10 - btnW, btnY, btnW, btnH, "Save", 0x1b461f, 0x347c3c, 0x0f2611, 0x76ff76); + } + // ========================================================================= // Modal Click Handling // ========================================================================= @@ -1712,6 +1926,7 @@ public class PluginPanelUI { } if (cx >= wellInnerX + wellInnerW - 58 && cx <= wellInnerX + wellInnerW - 2 && cy >= contentY + 2 && cy <= contentY + 22) { + commitStringEdit(pm); currentModalTab = configReturnTab; configTarget = null; scrollOffset = 0; @@ -1724,6 +1939,68 @@ public class PluginPanelUI { if (items == null) return true; int headerH = getConfigHeaderHeight(); + if (editingStringKey != null) { + int[] b = getStringEditorBounds(wellInnerX, wellInnerW, contentY, contentH, headerH); + int edX = b[0], edY = b[1], edW = b[2], edH = b[3]; + int btnY = edY + edH - 28; + int btnH = 22; + int btnW = 64; + // Clear + if (cx >= edX + 10 && cx <= edX + 10 + btnW && cy >= btnY && cy <= btnY + btnH) { + editingStringValue = ""; + editingStringCursor = 0; + return true; + } + // Cancel + int cancelX = edX + edW - 10 - btnW * 2 - 8; + if (cx >= cancelX && cx <= cancelX + btnW && cy >= btnY && cy <= btnY + btnH) { + editingStringKey = null; + editingStringValue = ""; + editingStringCursor = 0; + editorLines = null; + editorLineStarts = null; + return true; + } + // Save + int saveX = edX + edW - 10 - btnW; + if (cx >= saveX && cx <= saveX + btnW && cy >= btnY && cy <= btnY + btnH) { + commitStringEdit(pm); + return true; + } + // Click inside text box to position cursor + int inputX = edX + 10; + int inputY = edY + 25; + int inputW = edW - 20; + int inputH = edH - 61; + if (cx >= inputX && cx <= inputX + inputW && cy >= inputY && cy <= inputY + inputH + && editorLines != null && !editorLines.isEmpty() && editorLineStarts != null) { + int row = Math.max(0, (cy - (inputY + 5)) / 14); + int lineIdx = Math.min(editorLines.size() - 1, editorStartLine + row); + String lineText = editorLines.get(lineIdx); + int lineStart = editorLineStarts.get(lineIdx); + int relX = Math.max(0, cx - (inputX + 7)); + int bestIdx = lineText.length(); + if (lastEditorGraphics != null) { + int bestDist = Integer.MAX_VALUE; + for (int ci = 0; ci <= lineText.length(); ci++) { + int wAt = lastEditorGraphics.getTextWidth(lineText.substring(0, ci)); + int dist = Math.abs(relX - wAt); + if (dist <= bestDist) { + bestDist = dist; + bestIdx = ci; + } + } + } + int valLen = editingStringValue != null ? editingStringValue.length() : 0; + editingStringCursor = Math.min(valLen, lineStart + bestIdx); + return true; + } + // Click outside overlay commits & closes; inside consumes + if (cx < edX || cx > edX + edW || cy < edY || cy > edY + edH) { + commitStringEdit(pm); + } + return true; + } if (cy < contentY + headerH || cy > contentY + contentH) { openDropdownKey = null; dropdownScrollOffset = 0; @@ -1814,10 +2091,24 @@ public class PluginPanelUI { dropdownScrollOffset = Math.min(maxDropScroll, Math.max(0, (curIdx - 2) * DROPDOWN_ROW_H)); return true; } + } else { + int boxW = 220; + int boxX = wellInnerX + wellInnerW - boxW; + if (cx >= boxX && cx <= boxX + boxW && cy >= btnY && cy <= btnY + btnH) { + if (!item.getKey().equals(editingStringKey)) { + commitStringEdit(pm); + Object rawVal = pm.getConfigValue(configTarget, item); + editingStringKey = item.getKey(); + editingStringValue = rawVal != null ? String.valueOf(rawVal) : ""; + editingStringCursor = editingStringValue.length(); + } + return true; + } } } rowY += 32; } + commitStringEdit(pm); } return true; // Consume any other click inside modal diff --git a/2006Scape Client/src/main/java/PluginRepoClient.java b/2006Scape Client/src/main/java/PluginRepoClient.java index 84d448c5..a324842f 100644 --- a/2006Scape Client/src/main/java/PluginRepoClient.java +++ b/2006Scape Client/src/main/java/PluginRepoClient.java @@ -18,6 +18,8 @@ public class PluginRepoClient { PLUGIN_REPO_RAW_BASE + PLUGIN_REPO_BRANCH + "/index.json"; private static final String REPO_INFO_REFS_URL = PLUGIN_REPO_URL + ".git/info/refs?service=git-upload-pack"; + private static final String REPO_COMMIT_API_URL = + "https://api.github.com/repos/" + PLUGIN_REPO_SLUG + "/commits/" + PLUGIN_REPO_BRANCH; private static volatile String resolvedMainSha = null; public enum InstallStatus { @@ -300,6 +302,23 @@ public class PluginRepoClient { String candidate = body.substring(idx - 40, idx); if (candidate.matches("[0-9a-fA-F]{40}")) { resolvedMainSha = candidate; + return; + } + } + } catch (Throwable ignored) { + } + // Browser fallback: GitHub REST API commits endpoint supports CORS without preflight + try { + String json = httpGetRaw(REPO_COMMIT_API_URL + "?t=" + System.currentTimeMillis()); + int shaKey = json.indexOf("\"sha\""); + if (shaKey != -1) { + int q1 = json.indexOf('"', shaKey + 5); + int q2 = q1 != -1 ? json.indexOf('"', q1 + 1) : -1; + if (q1 != -1 && q2 - q1 - 1 == 40) { + String candidate = json.substring(q1 + 1, q2); + if (candidate.matches("[0-9a-fA-F]{40}")) { + resolvedMainSha = candidate; + } } } } catch (Throwable ignored) { diff --git a/2006Scape Client/src/main/java/RSApplet.java b/2006Scape Client/src/main/java/RSApplet.java index da2c55c4..86f64cf1 100644 --- a/2006Scape Client/src/main/java/RSApplet.java +++ b/2006Scape Client/src/main/java/RSApplet.java @@ -600,7 +600,7 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh if (j > 0 && j < 128) { keyArray[j] = 1; } - if (j > 4) { + if (j > 4 || ((j == 1 || j == 2) && PluginPanelUI.isSearchFocused())) { charQueue[writeIndex] = j; writeIndex = writeIndex + 1 & 0x7f; } diff --git a/2006Scape Client/src/main/java/ScriptInterpreter.java b/2006Scape Client/src/main/java/ScriptInterpreter.java index 972930a1..b00366c4 100644 --- a/2006Scape Client/src/main/java/ScriptInterpreter.java +++ b/2006Scape Client/src/main/java/ScriptInterpreter.java @@ -12,6 +12,31 @@ import java.util.*; */ public class ScriptInterpreter { + private static final Map, Map>> METHOD_CACHE = new HashMap<>(); + + private static List getCachedMethods(Class clazz, String methodName) { + Map> byName = METHOD_CACHE.get(clazz); + if (byName == null) { + byName = new HashMap<>(); + try { + for (Method m : clazz.getMethods()) { + String key = m.getName().toLowerCase(Locale.ROOT); + List bucket = byName.get(key); + if (bucket == null) { + bucket = new ArrayList<>(2); + byName.put(key, bucket); + } + bucket.add(m); + } + } catch (Throwable ignored) { + // TeaVM may strip metadata for unscriptable classes; fast-paths handle common APIs. + } + METHOD_CACHE.put(clazz, byName); + } + List result = byName.get(methodName.toLowerCase(Locale.ROOT)); + return result != null ? result : Collections.emptyList(); + } + public static class ScriptMetadata { public String name = "Unnamed Script"; public String author = "Anonymous"; @@ -19,6 +44,7 @@ public class ScriptInterpreter { public String version = "1.0.0"; public String minApiVersion = "1.0.0"; public String type = "script"; // "plugin" or "script" + public boolean defaultEnabled = false; public List commands = new ArrayList<>(); public List configItems = new ArrayList<>(); } @@ -42,6 +68,8 @@ public class ScriptInterpreter { meta.version = comment.substring(8).trim(); } else if (comment.startsWith("@minApi")) { meta.minApiVersion = comment.substring(7).trim(); + } else if (comment.startsWith("@defaultEnabled")) { + meta.defaultEnabled = Boolean.parseBoolean(comment.substring(15).trim()); } else if (comment.startsWith("@command")) { String rawCmds = comment.substring(8).trim(); for (String c : rawCmds.split(",")) { @@ -117,10 +145,12 @@ public class ScriptInterpreter { * Runtime execution environment holding functions, global variables, and evaluator. */ private static String lastEvalExpr = ""; + private static String lastPhase = ""; public static class Environment { private final Map globals = new HashMap<>(); private final Map functions = new HashMap<>(); + private final Set reportedErrors = new HashSet<>(); public Environment() { } @@ -146,17 +176,30 @@ public class ScriptInterpreter { if (fn == null) return null; return fn.execute(this, args); } + + void reportRuntimeError(String fnName, Throwable t) { + if (!reportedErrors.add(fnName)) return; + String msg = t.getMessage() != null ? t.getMessage() : t.getClass().getSimpleName(); + msg = msg.replace("(JavaScript) TypeError: Cannot read properties of ", "NPE "); + StackTraceElement[] st = t.getStackTrace(); + String loc = (st != null && st.length > 0) ? " @" + st[0].getMethodName() + ":" + st[0].getLineNumber() : ""; + PluginManager pm = PluginManager.get(); + if (pm != null && pm.getContext() != null && pm.getContext().isLoggedIn()) { + String exprHint = (lastEvalExpr != null && !lastEvalExpr.isEmpty()) ? " [" + lastEvalExpr + "|" + lastPhase + "]" : ""; + pm.getContext().sendClientMessage("@red@[Script Error] " + fnName + exprHint + loc + ": " + msg); + } + } } public static class FunctionDef { final String name; final List params; - final String body; + final List stmts; FunctionDef(String name, List params, String body) { this.name = name; this.params = params; - this.body = body; + this.stmts = parseBlock(body); } public Object execute(Environment parentEnv, Object[] argValues) { @@ -165,12 +208,13 @@ public class ScriptInterpreter { scope.setLocal(params.get(i), argValues[i]); } try { - return executeBlock(body, scope, parentEnv); + return executeStmts(stmts, scope, parentEnv); } catch (ReturnSignal r) { return r.value; } catch (Throwable t) { System.err.println("Script runtime error in function " + name + " [expr=" + lastEvalExpr + "]: " + t.getMessage()); t.printStackTrace(); + parentEnv.reportRuntimeError(name, t); return null; } } @@ -221,6 +265,10 @@ public class ScriptInterpreter { } } + private static class BreakSignal extends RuntimeException {} + + private static class ContinueSignal extends RuntimeException {} + /** * Parses source code into functions and initial statements, returning an Environment. */ @@ -234,6 +282,7 @@ public class ScriptInterpreter { env.setVariable("NpcID", NpcID.class); env.setVariable("ObjectID", ObjectID.class); env.setVariable("PluginContext", PluginContext.class); + env.setVariable("MenuEntry", MenuEntry.class); String cleaned = cleanComments(source); Scope globalScope = new Scope(env.globals, true); @@ -342,118 +391,396 @@ public class ScriptInterpreter { return sb.toString(); } - private static Object executeBlock(String block, Scope scope, Environment env) { - int pos = 0; - int len = block.length(); - - while (pos < len) { - // Skip whitespace - while (pos < len && Character.isWhitespace(block.charAt(pos))) pos++; - if (pos >= len) break; - - // Check control statements - if (block.startsWith("if", pos) && !Character.isJavaIdentifierPart(block.charAt(pos + 2))) { - pos = executeIfStatement(block, pos, scope, env); - continue; - } - - if (block.startsWith("while", pos) && (pos + 5 == len || !Character.isJavaIdentifierPart(block.charAt(pos + 5)))) { - int openParen = block.indexOf('(', pos); - int closeParen = findMatchingParen(block, openParen); - String condStr = block.substring(openParen + 1, closeParen); - int openBrace = block.indexOf('{', closeParen); - int closeBrace = findMatchingBrace(block, openBrace); - String loopBlock = block.substring(openBrace + 1, closeBrace); - int guard = 0; - while (guard++ < 1000 && isTruthy(evalExpression(condStr, scope, env))) { - executeBlock(loopBlock, scope, env); - } - pos = closeBrace + 1; - continue; - } - - if (block.startsWith("return", pos) && (pos + 6 == len || !Character.isJavaIdentifierPart(block.charAt(pos + 6)))) { - int semi = block.indexOf(';', pos); - String retExpr = semi != -1 ? block.substring(pos + 6, semi).trim() : block.substring(pos + 6).trim(); - Object val = retExpr.isEmpty() ? null : evalExpression(retExpr, scope, env); - throw new ReturnSignal(val); - } - - // Normal statement ending with semicolon - int semi = block.indexOf(';', pos); - if (semi == -1) { - semi = len; - } - String stmt = block.substring(pos, semi).trim(); - executeStatement(stmt, scope, env); - pos = semi + 1; - } - - return null; + private interface Stmt { + void execute(Scope scope, Environment env); } - private static int executeIfStatement(String block, int pos, Scope scope, Environment env) { + private static boolean isKeywordAt(String s, int pos, String kw) { + int len = s.length(); + int kwLen = kw.length(); + return pos + kwLen <= len && s.startsWith(kw, pos) + && (pos + kwLen == len || !Character.isJavaIdentifierPart(s.charAt(pos + kwLen))); + } + + private static List parseBlock(String block) { + List list = new ArrayList<>(); + int pos = 0; + int len = block.length(); + int[] nextPos = new int[1]; + + while (pos < len) { + while (pos < len && Character.isWhitespace(block.charAt(pos))) pos++; + if (pos >= len) break; + Stmt s = parseOneStatement(block, pos, nextPos); + if (s != null) { + list.add(s); + } + pos = nextPos[0]; + } + return list; + } + + private static List parseBodyOrSingleStatement(String block, int pos, int[] outNextPos) { + int len = block.length(); + while (pos < len && Character.isWhitespace(block.charAt(pos))) pos++; + if (pos < len && block.charAt(pos) == '{') { + int closeBrace = findMatchingBrace(block, pos); + outNextPos[0] = closeBrace + 1; + return parseBlock(block.substring(pos + 1, closeBrace)); + } + Stmt single = parseOneStatement(block, pos, outNextPos); + return single != null ? Collections.singletonList(single) : Collections.emptyList(); + } + + private static Stmt parseOneStatement(String block, int pos, int[] outNextPos) { + int len = block.length(); + + if (isKeywordAt(block, pos, "if")) { + return parseIfStatement(block, pos, outNextPos); + } + + if (isKeywordAt(block, pos, "while")) { + int openParen = block.indexOf('(', pos); + int closeParen = findMatchingParen(block, openParen); + String condStr = block.substring(openParen + 1, closeParen); + List loopStmts = parseBodyOrSingleStatement(block, closeParen + 1, outNextPos); + return (scope, env) -> { + int guard = 0; + try { + while (guard++ < 1000 && isTruthy(evalExpression(condStr, scope, env))) { + try { + executeStmts(loopStmts, scope, env); + } catch (ContinueSignal ignored) {} + } + } catch (BreakSignal ignored) {} + }; + } + + if (isKeywordAt(block, pos, "for")) { + return parseForStatement(block, pos, outNextPos); + } + + if (isKeywordAt(block, pos, "switch")) { + return parseSwitchStatement(block, pos, outNextPos); + } + + if (isKeywordAt(block, pos, "return")) { + int semi = block.indexOf(';', pos); + String retExpr = semi != -1 ? block.substring(pos + 6, semi).trim() : block.substring(pos + 6).trim(); + outNextPos[0] = semi != -1 ? semi + 1 : len; + return (scope, env) -> { + Object val = retExpr.isEmpty() ? null : evalExpression(retExpr, scope, env); + throw new ReturnSignal(val); + }; + } + + if (isKeywordAt(block, pos, "break")) { + int semi = block.indexOf(';', pos); + outNextPos[0] = semi != -1 ? semi + 1 : len; + return (scope, env) -> { throw new BreakSignal(); }; + } + + if (isKeywordAt(block, pos, "continue")) { + int semi = block.indexOf(';', pos); + outNextPos[0] = semi != -1 ? semi + 1 : len; + return (scope, env) -> { throw new ContinueSignal(); }; + } + + int semi = block.indexOf(';', pos); + if (semi == -1) { + semi = len; + } + String stmt = block.substring(pos, semi).trim(); + outNextPos[0] = semi + 1; + return stmt.isEmpty() ? null : parseSimpleStatement(stmt); + } + + private static Stmt parseForStatement(String block, int pos, int[] outNextPos) { + int openParen = block.indexOf('(', pos); + int closeParen = findMatchingParen(block, openParen); + String header = block.substring(openParen + 1, closeParen).trim(); + List bodyStmts = parseBodyOrSingleStatement(block, closeParen + 1, outNextPos); + + int colonIdx = findTopLevelOp(header, ":"); + int semiIdx = findTopLevelOp(header, ";"); + if (colonIdx != -1 && semiIdx == -1) { + String left = header.substring(0, colonIdx).trim(); + String[] parts = left.split("\\s+"); + String varName = parts.length > 1 ? parts[parts.length - 1] : left; + String iterableExpr = header.substring(colonIdx + 1).trim(); + return (scope, env) -> { + Object iterObj = evalExpression(iterableExpr, scope, env); + if (iterObj instanceof Iterable) { + try { + int guard = 0; + for (Object item : (Iterable) iterObj) { + if (guard++ >= 1000) break; + scope.set(varName, item); + try { + executeStmts(bodyStmts, scope, env); + } catch (ContinueSignal ignored) {} + } + } catch (BreakSignal ignored) {} + } else if (iterObj != null && iterObj.getClass().isArray()) { + try { + int lenArr = Math.min(1000, java.lang.reflect.Array.getLength(iterObj)); + for (int idx = 0; idx < lenArr; idx++) { + scope.set(varName, java.lang.reflect.Array.get(iterObj, idx)); + try { + executeStmts(bodyStmts, scope, env); + } catch (ContinueSignal ignored) {} + } + } catch (BreakSignal ignored) {} + } + }; + } + + String initStr = ""; + String condStr = ""; + String updateStr = ""; + if (semiIdx != -1) { + initStr = header.substring(0, semiIdx).trim(); + String rest = header.substring(semiIdx + 1); + int semi2 = findTopLevelOp(rest, ";"); + if (semi2 != -1) { + condStr = rest.substring(0, semi2).trim(); + updateStr = rest.substring(semi2 + 1).trim(); + } else { + condStr = rest.trim(); + } + } + final Stmt initStmt = initStr.isEmpty() ? null : parseSimpleStatement(initStr); + final String finalCond = condStr; + final Stmt updateStmt = updateStr.isEmpty() ? null : parseSimpleStatement(updateStr); + + return (scope, env) -> { + if (initStmt != null) { + initStmt.execute(scope, env); + } + int guard = 0; + try { + while (guard++ < 1000 && (finalCond.isEmpty() || isTruthy(evalExpression(finalCond, scope, env)))) { + try { + executeStmts(bodyStmts, scope, env); + } catch (ContinueSignal ignored) {} + if (updateStmt != null) { + updateStmt.execute(scope, env); + } + } + } catch (BreakSignal ignored) {} + }; + } + + private static Stmt parseSwitchStatement(String block, int pos, int[] outNextPos) { + int openParen = block.indexOf('(', pos); + int closeParen = findMatchingParen(block, openParen); + String switchExpr = block.substring(openParen + 1, closeParen).trim(); + int openBrace = block.indexOf('{', closeParen); + int closeBrace = findMatchingBrace(block, openBrace); + outNextPos[0] = closeBrace + 1; + + String body = block.substring(openBrace + 1, closeBrace); + List caseExprs = new ArrayList<>(); + List> caseBodies = new ArrayList<>(); + int[] defaultIdx = new int[]{-1}; + + int p = 0; + int bLen = body.length(); + int currentStart = -1; + String currentLabel = null; + boolean currentIsDefault = false; + + int depthParen = 0; + int depthBrace = 0; + boolean inStr = false; + while (p < bLen) { + char c = body.charAt(p); + if (c == '"' && (p == 0 || body.charAt(p - 1) != '\\')) { + inStr = !inStr; + p++; + continue; + } + if (!inStr) { + if (c == '(') { depthParen++; p++; continue; } + if (c == ')') { depthParen--; p++; continue; } + if (c == '{') { depthBrace++; p++; continue; } + if (c == '}') { depthBrace--; p++; continue; } + if (depthParen == 0 && depthBrace == 0) { + boolean isCase = isKeywordAt(body, p, "case"); + boolean isDef = !isCase && isKeywordAt(body, p, "default"); + if (isCase || isDef) { + int colon = body.indexOf(':', p); + if (colon != -1) { + if (currentStart != -1) { + int idx = caseBodies.size(); + caseExprs.add(currentLabel); + caseBodies.add(parseBlock(body.substring(currentStart, p))); + if (currentIsDefault) defaultIdx[0] = idx; + } + currentIsDefault = isDef; + currentLabel = isCase ? body.substring(p + 4, colon).trim() : null; + currentStart = colon + 1; + p = colon + 1; + continue; + } + } + } + } + p++; + } + if (currentStart != -1) { + int idx = caseBodies.size(); + caseExprs.add(currentLabel); + caseBodies.add(parseBlock(body.substring(currentStart))); + if (currentIsDefault) defaultIdx[0] = idx; + } + + final int defIndex = defaultIdx[0]; + return (scope, env) -> { + Object val = evalExpression(switchExpr, scope, env); + int matchIdx = -1; + for (int i = 0; i < caseExprs.size(); i++) { + String lbl = caseExprs.get(i); + if (lbl != null && safeEquals(val, evalExpression(lbl, scope, env))) { + matchIdx = i; + break; + } + } + if (matchIdx == -1) matchIdx = defIndex; + if (matchIdx != -1) { + try { + for (int i = matchIdx; i < caseBodies.size(); i++) { + executeStmts(caseBodies.get(i), scope, env); + } + } catch (BreakSignal ignored) {} + } + }; + } + + private static Stmt parseIfStatement(String block, int pos, int[] outNextPos) { int len = block.length(); int openParen = block.indexOf('(', pos); int closeParen = findMatchingParen(block, openParen); String condStr = block.substring(openParen + 1, closeParen); - boolean cond = isTruthy(evalExpression(condStr, scope, env)); - int openBrace = block.indexOf('{', closeParen); - int closeBrace = findMatchingBrace(block, openBrace); - String thenBlock = block.substring(openBrace + 1, closeBrace); + int[] bodyNext = new int[1]; + List thenStmts = parseBodyOrSingleStatement(block, closeParen + 1, bodyNext); - if (cond) { - executeBlock(thenBlock, scope, env); - return skipElseChain(block, closeBrace + 1); - } - - int nextPos = closeBrace + 1; + int nextPos = bodyNext[0]; while (nextPos < len && Character.isWhitespace(block.charAt(nextPos))) nextPos++; - if (nextPos + 4 <= len && block.startsWith("else", nextPos) - && (nextPos + 4 == len || !Character.isJavaIdentifierPart(block.charAt(nextPos + 4)))) { + List elseStmts = null; + if (isKeywordAt(block, nextPos, "else")) { int afterElse = nextPos + 4; - while (afterElse < len && Character.isWhitespace(block.charAt(afterElse))) afterElse++; - if (afterElse + 2 <= len && block.startsWith("if", afterElse) - && (afterElse + 2 == len || !Character.isJavaIdentifierPart(block.charAt(afterElse + 2)))) { - return executeIfStatement(block, afterElse, scope, env); - } - int elseBrace = block.indexOf('{', afterElse); - int elseClose = findMatchingBrace(block, elseBrace); - String elseBlock = block.substring(elseBrace + 1, elseClose); - executeBlock(elseBlock, scope, env); - return elseClose + 1; + int[] elseNext = new int[1]; + elseStmts = parseBodyOrSingleStatement(block, afterElse, elseNext); + nextPos = elseNext[0]; } - return nextPos; + outNextPos[0] = nextPos; + final List finalElse = elseStmts; + return (scope, env) -> { + if (isTruthy(evalExpression(condStr, scope, env))) { + executeStmts(thenStmts, scope, env); + } else if (finalElse != null) { + executeStmts(finalElse, scope, env); + } + }; } - private static int skipElseChain(String block, int pos) { - int len = block.length(); - while (pos < len) { - int nextPos = pos; - while (nextPos < len && Character.isWhitespace(block.charAt(nextPos))) nextPos++; - if (nextPos + 4 <= len && block.startsWith("else", nextPos) - && (nextPos + 4 == len || !Character.isJavaIdentifierPart(block.charAt(nextPos + 4)))) { - int afterElse = nextPos + 4; - while (afterElse < len && Character.isWhitespace(block.charAt(afterElse))) afterElse++; - if (afterElse + 2 <= len && block.startsWith("if", afterElse) - && (afterElse + 2 == len || !Character.isJavaIdentifierPart(block.charAt(afterElse + 2)))) { - int openParen = block.indexOf('(', afterElse); - int closeParen = findMatchingParen(block, openParen); - int openBrace = block.indexOf('{', closeParen); - int closeBrace = findMatchingBrace(block, openBrace); - pos = closeBrace + 1; - continue; - } - int elseBrace = block.indexOf('{', afterElse); - int elseClose = findMatchingBrace(block, elseBrace); - return elseClose + 1; + private static Stmt parseSimpleStatement(String stmt) { + int compIdx = -1; + char compOp = 0; + String[] compOps = {"+=", "-=", "*=", "/=", "%="}; + for (int k = 0; k < compOps.length; k++) { + int idx = findTopLevelOp(stmt, compOps[k]); + if (idx != -1 && (compIdx == -1 || idx < compIdx)) { + compIdx = idx; + compOp = compOps[k].charAt(0); } - return pos; } - return pos; + if (compIdx != -1) { + final char op = compOp; + String varName = stmt.substring(0, compIdx).trim(); + String right = stmt.substring(compIdx + 2).trim(); + return (scope, env) -> { + Object cur = scope.get(varName); + Object rhs = evalExpression(right, scope, env); + if (op == '+' && (cur instanceof String || rhs instanceof String)) { + scope.set(varName, safeToString(cur) + safeToString(rhs)); + } else if (isIntegral(cur) && isIntegral(rhs)) { + long a = ((Number) cur).longValue(); + long b = ((Number) rhs).longValue(); + long res; + if (op == '+') res = a + b; + else if (op == '-') res = a - b; + else if (op == '*') res = a * b; + else if (op == '/') res = b != 0 ? a / b : 0; + else res = b != 0 ? a % b : 0; + scope.set(varName, toIntegralResult(cur, rhs, res)); + } else { + double a = toDouble(cur); + double b = toDouble(rhs); + double res; + if (op == '+') res = a + b; + else if (op == '-') res = a - b; + else if (op == '*') res = a * b; + else if (op == '/') res = b != 0 ? a / b : 0; + else res = b != 0 ? a % b : 0; + scope.set(varName, res); + } + }; + } + + int eqIndex = findTopLevelOp(stmt, "="); + if (eqIndex != -1 + && (eqIndex + 1 >= stmt.length() || stmt.charAt(eqIndex + 1) != '=') + && (eqIndex == 0 || (stmt.charAt(eqIndex - 1) != '!' && stmt.charAt(eqIndex - 1) != '<' && stmt.charAt(eqIndex - 1) != '>'))) { + String left = stmt.substring(0, eqIndex).trim(); + String right = stmt.substring(eqIndex + 1).trim(); + if (left.endsWith("]")) { + int openBracket = findMatchingOpenBracket(left); + if (openBracket > 0) { + String targetExpr = left.substring(0, openBracket).trim(); + String idxExpr = left.substring(openBracket + 1, left.length() - 1).trim(); + return (scope, env) -> { + Object target = evalExpression(targetExpr, scope, env); + Object idx = evalExpression(idxExpr, scope, env); + Object val = evalExpression(right, scope, env); + setIndexValue(target, idx, val); + }; + } + } + String[] parts = left.split("\\s+"); + String varName = parts.length > 1 ? parts[parts.length - 1] : left; + return (scope, env) -> { + Object val = evalExpression(right, scope, env); + scope.set(varName, val); + }; + } + + if (stmt.endsWith("++") || stmt.endsWith("--")) { + boolean isInc = stmt.endsWith("++"); + String varName = stmt.substring(0, stmt.length() - 2).trim(); + return (scope, env) -> { + Object cur = scope.get(varName); + int num = (cur instanceof Number) ? ((Number) cur).intValue() : 0; + scope.set(varName, isInc ? num + 1 : num - 1); + }; + } + + return (scope, env) -> evalExpression(stmt, scope, env); + } + + private static Object executeStmts(List stmts, Scope scope, Environment env) { + for (int i = 0; i < stmts.size(); i++) { + stmts.get(i).execute(scope, env); + } + return null; + } + + private static Object executeBlock(String block, Scope scope, Environment env) { + return executeStmts(parseBlock(block), scope, env); } private static int findMatchingParen(String s, int openIndex) { @@ -469,68 +796,11 @@ public class ScriptInterpreter { return -1; } - private static void executeStatement(String stmt, Scope scope, Environment env) { - if (stmt == null || stmt.isEmpty()) return; - - // Compound assignment: += or -= - int plusEq = stmt.indexOf("+="); - int minusEq = stmt.indexOf("-="); - if (plusEq != -1 || minusEq != -1) { - boolean isAdd = plusEq != -1 && (minusEq == -1 || plusEq < minusEq); - int opIdx = isAdd ? plusEq : minusEq; - String varName = stmt.substring(0, opIdx).trim(); - String right = stmt.substring(opIdx + 2).trim(); - Object cur = scope.get(varName); - Object rhs = evalExpression(right, scope, env); - if (isAdd && (cur instanceof String || rhs instanceof String)) { - scope.set(varName, safeToString(cur) + safeToString(rhs)); - } else if (isIntegral(cur) && isIntegral(rhs)) { - long res = isAdd ? (((Number) cur).longValue() + ((Number) rhs).longValue()) - : (((Number) cur).longValue() - ((Number) rhs).longValue()); - scope.set(varName, toIntegralResult(cur, rhs, res)); - } else { - double a = toDouble(cur); - double b = toDouble(rhs); - scope.set(varName, isAdd ? (a + b) : (a - b)); - } - return; - } - - // Check for variable declaration: var x = ..., int x = ..., String s = ... - int eqIndex = stmt.indexOf('='); - if (eqIndex != -1 && !stmt.startsWith("==") && (eqIndex == 0 || stmt.charAt(eqIndex - 1) != '!' && stmt.charAt(eqIndex - 1) != '<' && stmt.charAt(eqIndex - 1) != '>')) { - String left = stmt.substring(0, eqIndex).trim(); - String right = stmt.substring(eqIndex + 1).trim(); - - String varName = left; - String[] parts = left.split("\\s+"); - if (parts.length > 1) { - varName = parts[parts.length - 1]; - } - - Object val = evalExpression(right, scope, env); - scope.set(varName, val); - return; - } - - // Increment / decrement: i++ or i-- - if (stmt.endsWith("++") || stmt.endsWith("--")) { - boolean isInc = stmt.endsWith("++"); - String varName = stmt.substring(0, stmt.length() - 2).trim(); - Object cur = scope.get(varName); - int num = (cur instanceof Number) ? ((Number) cur).intValue() : 0; - scope.set(varName, isInc ? num + 1 : num - 1); - return; - } - - // Expression statement (e.g. method call) - evalExpression(stmt, scope, env); - } - public static Object evalExpression(String expr, Scope scope, Environment env) { if (expr == null) return null; expr = expr.trim(); lastEvalExpr = expr; + lastPhase = "eval"; if (expr.isEmpty()) return null; // Parentheses @@ -541,6 +811,18 @@ public class ScriptInterpreter { } } + // Ternary conditional: cond ? a : b + int qIdx = findTopLevelOp(expr, "?"); + if (qIdx != -1) { + int colonIdx = findMatchingTernaryColon(expr, qIdx); + if (colonIdx != -1) { + boolean cond = isTruthy(evalExpression(expr.substring(0, qIdx), scope, env)); + return cond + ? evalExpression(expr.substring(qIdx + 1, colonIdx), scope, env) + : evalExpression(expr.substring(colonIdx + 1), scope, env); + } + } + // Logical OR: || int orIdx = findTopLevelOp(expr, "||"); if (orIdx != -1) { @@ -636,6 +918,17 @@ public class ScriptInterpreter { double b = toDouble(evalExpression(expr.substring(divIdx + 1), scope, env)); return b != 0 ? a / b : 0; } + int modIdx = findTopLevelOp(expr, "%"); + if (modIdx != -1) { + Object a = evalExpression(expr.substring(0, modIdx), scope, env); + Object b = evalExpression(expr.substring(modIdx + 1), scope, env); + if (isIntegral(a) && isIntegral(b)) { + long lb = ((Number) b).longValue(); + return lb != 0 ? toIntegralResult(a, b, ((Number) a).longValue() % lb) : 0; + } + double db = toDouble(b); + return db != 0 ? toDouble(a) % db : 0; + } // Unary NOT: ! if (expr.startsWith("!")) { @@ -658,6 +951,9 @@ public class ScriptInterpreter { if (expr.matches("^0[xX][0-9a-fA-F]+$")) { return (int) Long.parseLong(expr.substring(2), 16); } + if (expr.matches("^-?\\d+[lL]$")) { + return Long.parseLong(expr.substring(0, expr.length() - 1)); + } if (expr.matches("^-?\\d+$")) { try { return Integer.parseInt(expr); @@ -669,6 +965,42 @@ public class ScriptInterpreter { return Double.parseDouble(expr); } + // List literals: [a, b, c] + if (expr.startsWith("[") && expr.endsWith("]")) { + int closeBracket = findMatchingCloseBracket(expr, 0); + if (closeBracket == expr.length() - 1) { + String inner = expr.substring(1, expr.length() - 1).trim(); + return new ArrayList<>(parseArguments(inner, scope, env)); + } + } + + // Constructor invocation: new ClassName(args) + if (expr.startsWith("new ") && expr.endsWith(")")) { + int openParen = findMethodOpenParen(expr); + if (openParen > 4) { + String className = expr.substring(4, openParen).trim(); + int genericIdx = className.indexOf('<'); + if (genericIdx != -1) { + className = className.substring(0, genericIdx).trim(); + } + String argsStr = expr.substring(openParen + 1, expr.length() - 1).trim(); + List argsList = parseArguments(argsStr, scope, env); + return constructObject(className, argsList, env); + } + } + + // Index access: target[idx] + if (expr.endsWith("]")) { + int openBracket = findMatchingOpenBracket(expr); + if (openBracket > 0) { + String targetExpr = expr.substring(0, openBracket).trim(); + String idxExpr = expr.substring(openBracket + 1, expr.length() - 1).trim(); + Object target = evalExpression(targetExpr, scope, env); + Object idx = evalExpression(idxExpr, scope, env); + return getIndexValue(target, idx); + } + } + // Method invocation or member access: obj.method(args) or func(args) if (expr.endsWith(")")) { int openParen = findMethodOpenParen(expr); @@ -710,6 +1042,7 @@ public class ScriptInterpreter { private static int findTopLevelOp(String s, String op) { int depthParen = 0; int depthBrace = 0; + int depthBracket = 0; boolean inStr = false; int len = s.length(); int opLen = op.length(); @@ -723,7 +1056,9 @@ public class ScriptInterpreter { else if (c == ')') depthParen--; else if (c == '{') depthBrace++; else if (c == '}') depthBrace--; - else if (depthParen == 0 && depthBrace == 0) { + else if (c == '[') depthBracket++; + else if (c == ']') depthBracket--; + else if (depthParen == 0 && depthBrace == 0 && depthBracket == 0) { if (s.startsWith(op, i)) { return i; } @@ -733,18 +1068,185 @@ public class ScriptInterpreter { return -1; } + private static int findMatchingTernaryColon(String s, int qIdx) { + int depthParen = 0; + int depthBrace = 0; + int depthBracket = 0; + int ternaryDepth = 1; + boolean inStr = false; + for (int i = qIdx + 1; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '"' && (i == 0 || s.charAt(i - 1) != '\\')) { + inStr = !inStr; + } else if (!inStr) { + if (c == '(') depthParen++; + else if (c == ')') depthParen--; + else if (c == '{') depthBrace++; + else if (c == '}') depthBrace--; + else if (c == '[') depthBracket++; + else if (c == ']') depthBracket--; + else if (depthParen == 0 && depthBrace == 0 && depthBracket == 0) { + if (c == '?') ternaryDepth++; + else if (c == ':') { + ternaryDepth--; + if (ternaryDepth == 0) return i; + } + } + } + } + return -1; + } + + private static int findMatchingCloseBracket(String s, int openIndex) { + int depth = 1; + boolean inStr = false; + for (int i = openIndex + 1; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '"' && (i == 0 || s.charAt(i - 1) != '\\')) { + inStr = !inStr; + } else if (!inStr) { + if (c == '[') depth++; + else if (c == ']') { + depth--; + if (depth == 0) return i; + } + } + } + return -1; + } + + private static int findMatchingOpenBracket(String s) { + int depth = 0; + boolean inStr = false; + for (int i = s.length() - 1; i >= 0; i--) { + char c = s.charAt(i); + if (c == '"' && (i == 0 || s.charAt(i - 1) != '\\')) { + inStr = !inStr; + } else if (!inStr) { + if (c == ']') depth++; + else if (c == '[') { + depth--; + if (depth == 0) return i; + } + } + } + return -1; + } + + private static Object getIndexValue(Object target, Object idx) { + lastPhase = "getIdx"; + if (target == null || idx == null) return null; + if (target instanceof List) { + return ((List) target).get(((Number) idx).intValue()); + } + if (target instanceof Map) { + return ((Map) target).get(idx); + } + if (target instanceof String) { + return String.valueOf(((String) target).charAt(((Number) idx).intValue())); + } + if (target.getClass().isArray()) { + return java.lang.reflect.Array.get(target, ((Number) idx).intValue()); + } + return null; + } + + @SuppressWarnings("unchecked") + private static void setIndexValue(Object target, Object idx, Object val) { + lastPhase = "setIdx:" + idx; + if (target == null || idx == null) return; + if (target instanceof List) { + ((List) target).set(((Number) idx).intValue(), val); + } else if (target instanceof Map) { + ((Map) target).put(idx, val); + } else if (target.getClass().isArray()) { + java.lang.reflect.Array.set(target, ((Number) idx).intValue(), convertArg(val, target.getClass().getComponentType())); + } + } + + private static Object constructObject(String className, List args, Environment env) { + if ("ArrayList".equals(className) || "java.util.ArrayList".equals(className) || "List".equals(className)) { + if (args.size() == 1 && args.get(0) instanceof Collection) { + return new ArrayList<>((Collection) args.get(0)); + } + if (args.size() == 1 && args.get(0) instanceof Number) { + return new ArrayList<>(((Number) args.get(0)).intValue()); + } + return new ArrayList<>(); + } + if ("HashMap".equals(className) || "java.util.HashMap".equals(className) || "Map".equals(className)) { + if (args.size() == 1 && args.get(0) instanceof Map) { + return new HashMap<>((Map) args.get(0)); + } + return new HashMap<>(); + } + if ("LinkedHashMap".equals(className) || "java.util.LinkedHashMap".equals(className)) { + if (args.size() == 1 && args.get(0) instanceof Map) { + return new LinkedHashMap<>((Map) args.get(0)); + } + return new LinkedHashMap<>(); + } + if ("HashSet".equals(className) || "java.util.HashSet".equals(className) || "Set".equals(className)) { + if (args.size() == 1 && args.get(0) instanceof Collection) { + return new HashSet<>((Collection) args.get(0)); + } + return new HashSet<>(); + } + if ("StringBuilder".equals(className) || "java.lang.StringBuilder".equals(className)) { + if (args.size() == 1 && args.get(0) != null) { + return new StringBuilder(safeToString(args.get(0))); + } + return new StringBuilder(); + } + if (("WorldArea".equals(className) || "PluginContext.WorldArea".equals(className)) && args.size() == 4) { + return new PluginContext.WorldArea( + (int) toDouble(args.get(0)), + (int) toDouble(args.get(1)), + (int) toDouble(args.get(2)), + (int) toDouble(args.get(3))); + } + if ("MenuEntry".equals(className) && args.size() == 5) { + return new MenuEntry( + safeToString(args.get(0)), + (int) toDouble(args.get(1)), + (int) toDouble(args.get(2)), + (int) toDouble(args.get(3)), + (int) toDouble(args.get(4))); + } + try { + Object var = env != null ? env.getVariable(className) : null; + Class clazz = (var instanceof Class) ? (Class) var : Class.forName(className); + for (java.lang.reflect.Constructor ctor : clazz.getConstructors()) { + Class[] pTypes = ctor.getParameterTypes(); + if (pTypes.length == args.size()) { + Object[] converted = new Object[args.size()]; + for (int i = 0; i < args.size(); i++) { + converted[i] = convertArg(args.get(i), pTypes[i]); + } + return ctor.newInstance(converted); + } + } + } catch (Throwable ignored) {} + return null; + } + private static boolean isOperator(char c) { - return c == '+' || c == '-' || c == '*' || c == '/' || c == '=' || c == '<' || c == '>' || c == '!' || c == '&' || c == '|'; + return c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '=' || c == '<' || c == '>' || c == '!' || c == '&' || c == '|'; } private static int findMethodOpenParen(String s) { int depth = 0; + boolean inStr = false; for (int i = s.length() - 1; i >= 0; i--) { char c = s.charAt(i); - if (c == ')') depth++; - else if (c == '(') { - depth--; - if (depth == 0) return i; + if (c == '"' && (i == 0 || s.charAt(i - 1) != '\\')) { + inStr = !inStr; + } else if (!inStr) { + if (c == ')') depth++; + else if (c == '(') { + depth--; + if (depth == 0) return i; + } } } return -1; @@ -755,6 +1257,7 @@ public class ScriptInterpreter { List list = new ArrayList<>(); int depthParen = 0; int depthBrace = 0; + int depthBracket = 0; boolean inStr = false; int start = 0; int len = argsStr.length(); @@ -768,7 +1271,9 @@ public class ScriptInterpreter { else if (c == ')') depthParen--; else if (c == '{') depthBrace++; else if (c == '}') depthBrace--; - else if (c == ',' && depthParen == 0 && depthBrace == 0) { + else if (c == '[') depthBracket++; + else if (c == ']') depthBracket--; + else if (c == ',' && depthParen == 0 && depthBrace == 0 && depthBracket == 0) { list.add(evalExpression(argsStr.substring(start, i), scope, env)); start = i + 1; } @@ -781,6 +1286,7 @@ public class ScriptInterpreter { } private static Object invokeMethod(Object target, String methodName, List args) { + lastPhase = "invoke:" + methodName; if (target == null) return null; if (target == Math.class) { if ("max".equalsIgnoreCase(methodName) && args.size() == 2) { @@ -838,6 +1344,11 @@ public class ScriptInterpreter { return System.nanoTime(); } } + if (target == MenuEntry.class) { + if ("stripColorTags".equals(methodName) && args.size() == 1) { + return MenuEntry.stripColorTags(args.get(0) != null ? safeToString(args.get(0)) : null); + } + } if (target instanceof String) { String s = (String) target; if ("length".equals(methodName) && args.isEmpty()) return s.length(); @@ -908,16 +1419,115 @@ public class ScriptInterpreter { Boolean b = (Boolean) target; if ("booleanValue".equals(methodName) && args.isEmpty()) return b.booleanValue(); if ("toString".equals(methodName) && args.isEmpty()) return b.toString(); + } else if (target instanceof StringBuilder) { + StringBuilder sb = (StringBuilder) target; + if ("append".equals(methodName) && args.size() == 1) { + return sb.append(safeToString(args.get(0))); + } + if ("toString".equals(methodName) && args.isEmpty()) return sb.toString(); + if ("length".equals(methodName) && args.isEmpty()) return sb.length(); + if ("setLength".equals(methodName) && args.size() == 1) { + sb.setLength((int) toDouble(args.get(0))); + return null; + } + } else if (target instanceof PluginContext.GroundItemWrapper) { + if ("getDistance".equals(methodName) && args.isEmpty()) { + return ((PluginContext.GroundItemWrapper) target).getDistance(); + } + } else if (target instanceof PluginContext) { + PluginContext pc = (PluginContext) target; + if ("isLoggedIn".equals(methodName) && args.isEmpty()) return pc.isLoggedIn(); + if ("getGroundItems".equals(methodName)) { + if (args.isEmpty()) return pc.getGroundItems(); + if (args.size() == 1) return pc.getGroundItems((int) toDouble(args.get(0))); + } + if ("getGroundItemsSignature".equals(methodName) && args.size() == 1) { + return pc.getGroundItemsSignature((int) toDouble(args.get(0))); + } + if ("createList".equals(methodName) && args.isEmpty()) return pc.createList(); + if ("createMap".equals(methodName) && args.isEmpty()) return pc.createMap(); + if ("sendClientMessage".equals(methodName) && args.size() == 1) { + pc.sendClientMessage(safeToString(args.get(0))); + return null; + } + if ("getPlayerX".equals(methodName) && args.isEmpty()) return pc.getPlayerX(); + if ("getPlayerY".equals(methodName) && args.isEmpty()) return pc.getPlayerY(); + if ("getPlayerAnim".equals(methodName) && args.isEmpty()) return pc.getPlayerAnim(); + if ("isBankOpen".equals(methodName) && args.isEmpty()) return pc.isBankOpen(); + if ("getInventoryCount".equals(methodName) && args.isEmpty()) return pc.getInventoryCount(); + if ("walkTo".equals(methodName) && args.size() == 2) { + pc.walkTo((int) toDouble(args.get(0)), (int) toDouble(args.get(1))); + return null; + } + } else if (target instanceof MenuEntry) { + MenuEntry me = (MenuEntry) target; + if ("matches".equals(methodName) && args.size() == 2) { + return me.matches(safeToString(args.get(0)), safeToString(args.get(1))); + } + if ("getAction".equals(methodName) && args.isEmpty()) return me.getAction(); + if ("getTarget".equals(methodName) && args.isEmpty()) return me.getTarget(); + if ("getRawText".equals(methodName) && args.isEmpty()) return me.getRawText(); + if ("setRawText".equals(methodName) && args.size() == 1) { + me.setRawText(safeToString(args.get(0))); + return null; + } + } else if (target instanceof PluginGraphics) { + PluginGraphics pg = (PluginGraphics) target; + if ("drawTileLabelBatches".equals(methodName) && args.size() == 3 && args.get(0) instanceof List) { + pg.drawTileLabelBatches((List) args.get(0), (int) toDouble(args.get(1)), (int) toDouble(args.get(2))); + return null; + } + if ("fillRect".equals(methodName) && args.size() == 6) { + pg.fillRect((int) toDouble(args.get(0)), (int) toDouble(args.get(1)), (int) toDouble(args.get(2)), + (int) toDouble(args.get(3)), (int) toDouble(args.get(4)), (int) toDouble(args.get(5))); + return null; + } + if ("drawRect".equals(methodName) && args.size() == 5) { + pg.drawRect((int) toDouble(args.get(0)), (int) toDouble(args.get(1)), (int) toDouble(args.get(2)), + (int) toDouble(args.get(3)), (int) toDouble(args.get(4))); + return null; + } + if ("drawCenteredString".equals(methodName)) { + if (args.size() == 4) { + pg.drawCenteredString(safeToString(args.get(0)), (int) toDouble(args.get(1)), (int) toDouble(args.get(2)), (int) toDouble(args.get(3))); + return null; + } + if (args.size() == 5) { + pg.drawCenteredString(safeToString(args.get(0)), (int) toDouble(args.get(1)), (int) toDouble(args.get(2)), (int) toDouble(args.get(3)), (int) toDouble(args.get(4))); + return null; + } + } + if ("drawString".equals(methodName) && args.size() == 5) { + pg.drawString(safeToString(args.get(0)), (int) toDouble(args.get(1)), (int) toDouble(args.get(2)), (int) toDouble(args.get(3)), isTruthy(args.get(4))); + return null; + } + if ("drawStringBold".equals(methodName) && args.size() == 5) { + pg.drawStringBold(safeToString(args.get(0)), (int) toDouble(args.get(1)), (int) toDouble(args.get(2)), (int) toDouble(args.get(3)), isTruthy(args.get(4))); + return null; + } + if ("getTextWidth".equals(methodName) && args.size() == 1) return pg.getTextWidth(safeToString(args.get(0))); + if ("getTextWidthBold".equals(methodName) && args.size() == 1) return pg.getTextWidthBold(safeToString(args.get(0))); + if ("worldToScreenList".equals(methodName) && args.size() == 3) { + return pg.worldToScreenList((int) toDouble(args.get(0)), (int) toDouble(args.get(1)), (int) toDouble(args.get(2))); + } + if ("drawLootbeam".equals(methodName) && args.size() == 3) { + pg.drawLootbeam((int) toDouble(args.get(0)), (int) toDouble(args.get(1)), (int) toDouble(args.get(2))); + return null; + } + if ("getViewportWidth".equals(methodName) && args.isEmpty()) return pg.getViewportWidth(); + if ("getViewportHeight".equals(methodName) && args.isEmpty()) return pg.getViewportHeight(); } boolean isStaticClass = target instanceof Class; Class clazz = isStaticClass ? (Class) target : target.getClass(); Object invokeTarget = isStaticClass ? null : target; + List candidates = getCachedMethods(clazz, methodName); Throwable lastErr = null; // 1. Exact fixed-arity match - for (Method m : clazz.getMethods()) { + for (int c = 0; c < candidates.size(); c++) { + Method m = candidates.get(c); if (isStaticClass && !Modifier.isStatic(m.getModifiers())) continue; - if (!m.isVarArgs() && m.getName().equalsIgnoreCase(methodName) && m.getParameterTypes().length == args.size()) { + if (!m.isVarArgs() && m.getParameterTypes().length == args.size()) { try { Class[] pTypes = m.getParameterTypes(); Object[] convertedArgs = new Object[args.size()]; @@ -934,9 +1544,10 @@ public class ScriptInterpreter { } // 2. Varargs match (e.g., depositAllExcept("Coins", "Bread"), named("Cow", "Calf")) - for (Method m : clazz.getMethods()) { + for (int c = 0; c < candidates.size(); c++) { + Method m = candidates.get(c); if (isStaticClass && !Modifier.isStatic(m.getModifiers())) continue; - if (m.isVarArgs() && m.getName().equalsIgnoreCase(methodName)) { + if (m.isVarArgs()) { Class[] pTypes = m.getParameterTypes(); int fixedCount = pTypes.length - 1; if (args.size() < fixedCount) continue; @@ -1018,6 +1629,7 @@ public class ScriptInterpreter { } private static Object getProperty(Object target, String propertyName) { + lastPhase = "prop:" + propertyName; if (target == null) return null; boolean isStaticClass = target instanceof Class; Class clazz = isStaticClass ? (Class) target : target.getClass(); @@ -1135,6 +1747,11 @@ public class ScriptInterpreter { return metadata.minApiVersion; } + @Override + public boolean isEnabledByDefault() { + return metadata.defaultEnabled; + } + @Override public List getConfigItems() { return metadata.configItems; @@ -1241,6 +1858,16 @@ public class ScriptInterpreter { env.invoke("onRenderOverlay", ctx, g); } } + + @Override + public boolean onCommand(String command, String[] args) { + if (env.hasFunction("onCommand")) { + String joined = (args != null && args.length > 0) ? String.join(" ", args) : ""; + Object res = env.invoke("onCommand", command, joined); + return Boolean.TRUE.equals(res); + } + return false; + } } public static class InterpretedScript extends ClientScript { diff --git a/2006Scape Client/src/test/java/ScriptInterpreterTest.java b/2006Scape Client/src/test/java/ScriptInterpreterTest.java index 67561125..9374be65 100644 --- a/2006Scape Client/src/test/java/ScriptInterpreterTest.java +++ b/2006Scape Client/src/test/java/ScriptInterpreterTest.java @@ -105,4 +105,82 @@ public class ScriptInterpreterTest { assertTrue(map.containsKey("cow")); assertEquals("hide", env.invoke("mapLookup", map, "cow")); } + + @Test + public void evaluatesTernaryModuloConstructorsAndIndexing() { + String src = + "int runCalc(int x) {\n" + + " int val = x > 5 ? x * 2 : x + 10;\n" + + " val *= 2;\n" + + " val /= 4;\n" + + " val %= 7;\n" + + " return val;\n" + + "}\n" + + "String testContainersAndIndexing() {\n" + + " List items = [10, 20, 30];\n" + + " items[1] = 25;\n" + + " Map m = new HashMap();\n" + + " m[\"key\"] = \"hello\";\n" + + " StringBuilder sb = new StringBuilder();\n" + + " sb.append(m[\"key\"]).append(\" (\").append(items[1]).append(\")-\").append(17 % 5);\n" + + " return sb.toString();\n" + + "}\n"; + + ScriptInterpreter.Environment env = ScriptInterpreter.compile(src); + // x = 6 -> 12 * 2 = 24 / 4 = 6 % 7 = 6 + assertEquals(6, ((Number) env.invoke("runCalc", 6)).intValue()); + // x = 3 -> 13 * 2 = 26 / 4 = 6 % 7 = 6 + assertEquals(6, ((Number) env.invoke("runCalc", 3)).intValue()); + assertEquals("hello (25)-2", env.invoke("testContainersAndIndexing")); + } + + @Test + public void evaluatesForLoopsBreakContinueBracelessAndSwitch() { + String src = + "int sumForAndBreakContinue() {\n" + + " int sum = 0;\n" + + " for (int i = 0; i < 10; i++) {\n" + + " if (i % 2 == 0) continue;\n" + + " if (i > 7) break;\n" + + " sum += i;\n" + + " }\n" + + " return sum;\n" + + "}\n" + + "int sumForEach(List items) {\n" + + " int total = 0;\n" + + " for (Object item : items) total += item;\n" + + " return total;\n" + + "}\n" + + "String testSwitchAndBracelessIf(int v) {\n" + + " if (v < 0) return \"neg\";\n" + + " String res = \"\";\n" + + " switch (v) {\n" + + " case 1:\n" + + " case 2:\n" + + " res = \"low\";\n" + + " break;\n" + + " case 3:\n" + + " res = \"three\";\n" + + " break;\n" + + " default:\n" + + " res = \"other\";\n" + + " }\n" + + " return res;\n" + + "}\n" + + "String testMenuEntryFastPath() {\n" + + " MenuEntry me = new MenuEntry(\"Take @lre@Coins\", 234, 995, 10, 10);\n" + + " return me.matches(\"Take\", \"Coins\") ? MenuEntry.stripColorTags(me.getTarget()) : \"no\";\n" + + "}\n"; + + ScriptInterpreter.Environment env = ScriptInterpreter.compile(src); + // 1 + 3 + 5 + 7 = 16 + assertEquals(16, ((Number) env.invoke("sumForAndBreakContinue")).intValue()); + assertEquals(60, ((Number) env.invoke("sumForEach", java.util.Arrays.asList(10, 20, 30))).intValue()); + assertEquals("neg", env.invoke("testSwitchAndBracelessIf", -1)); + assertEquals("low", env.invoke("testSwitchAndBracelessIf", 1)); + assertEquals("low", env.invoke("testSwitchAndBracelessIf", 2)); + assertEquals("three", env.invoke("testSwitchAndBracelessIf", 3)); + assertEquals("other", env.invoke("testSwitchAndBracelessIf", 99)); + assertEquals("Coins", env.invoke("testMenuEntryFastPath")); + } } diff --git a/2006Scape Server/src/main/java/com/rs2/net/PacketSender.java b/2006Scape Server/src/main/java/com/rs2/net/PacketSender.java index bf8aeba5..17cae18e 100644 --- a/2006Scape Server/src/main/java/com/rs2/net/PacketSender.java +++ b/2006Scape Server/src/main/java/com/rs2/net/PacketSender.java @@ -98,6 +98,12 @@ public class PacketSender { } } } + player.getPacketSender().sendConfig(168, player.musicOn ? player.musicVolumeLevel : 4); + player.getPacketSender().sendConfig(169, player.soundOn ? player.soundVolumeLevel : 4); + player.getPlayList().sendMusicConfigs(); + if (Constants.SOUND) { + Music.playMusic(player); + } player.lastLoginDate = player.getLastLogin(); QuestAssistant.sendStages(player); if (player.hasNpc) { @@ -156,12 +162,6 @@ public class PacketSender { player.getPacketSender().sendConfig(504, 0); player.getPacketSender().sendConfig(173, 0); } - player.getPacketSender().sendConfig(168, player.musicOn ? player.musicVolumeLevel : 4); - player.getPacketSender().sendConfig(169, player.soundOn ? player.soundVolumeLevel : 4); - player.getPlayList().sendMusicConfigs(); - if (Constants.SOUND) { - Music.playMusic(player); - } player.getPlayerAction().setAction(false); player.getPlayerAction().canWalk(true); player.getPlayerAssistant().handleWeaponStyle();