Client, Script & Plugin Improvements (#687)

* fix(audio,client): start music immediately on login/track change and remove non-HD tooltip jitter

Eliminates artificial client-side music start and fade-out delays across all platforms, prioritizes music packets at the start of server login, and replaces jittery non-HD hover tooltips in Game.java.

### Core & Client Rendering
- 2006Scape Client/src/main/java/Game.java:
  - Updated method49() to call method853(musicVolume2, is, aBoolean995) directly on all platforms instead of routing through method684/method899 fade-out queues.
  - Reset anInt720 to 0 in constructMusic(), method853(), and method368() when stopped so the initial track and post-login music start without a 20-tick (~400ms) delay.
  - Replaced the non-HD chatTextDrawingArea.method390(..., loopCycle / 1000, ...) fallback with chatTextDrawingArea.textLeftShadow(...) so Walk here and hover tooltips render crisply with HD disabled.

### Server Login Audio
- 2006Scape Server/src/main/java/com/rs2/net/PacketSender.java:
  - Moved music/sound volume configs (168, 169), player.getPlayList().sendMusicConfigs(), and Music.playMusic(player) to run right after frame 249 and duplicate-login checks in loginPlayer(), flushing the login song before quest, skill, sidebar, and equipment packets.

* refactor(ui): use ClientSettings.SERVER_NAME in Plugin Hub modal title

Replaces the hardcoded RUNELITE prefix in the Plugin Hub modal header with ClientSettings.SERVER_NAME so the UI branding stays consistent with the configured server name.

### UI & Styling
- 2006Scape Client/src/main/java/PluginPanelUI.java:
  - Updated drawViewportModal title formatting to use ClientSettings.SERVER_NAME + " PLUGIN & SCRIPT HUB" (and " PLUGIN HUB" when scripts are unavailable).

* feat(client): migrate Ground Items and Menu Entry Swapper plugins to online repository

Removes the built-in `GroundItemsOverlayPlugin` and `MenuEntrySwapperPlugin` classes from the client bundle so players install them manually from the Online Repo tab (`2006scape-plugins`), and adds minimal `ScriptInterpreter`, `PluginContext`, and `PluginGraphics` host support so both plugins run natively in the interpreted plugin dialect.

### Plugin Host Infrastructure
- `ScriptInterpreter.java`:
  - Added `@defaultEnabled` metadata parsing (`ScriptMetadata.defaultEnabled`) and overrode `InterpretedPlugin.isEnabledByDefault()`.
  - Registered `MenuEntry.class` in `compile(String)` so interpreted plugins can invoke `MenuEntry.stripColorTags(...)` and menu entry helpers.
  - Overrode `InterpretedPlugin.onCommand(String, String[])` to forward chat commands (`command`, joined `args`) to interpreted plugins.
- `PluginContext.java`:
  - Added `createList()` and `createMap()` collection helpers for interpreted plugins.
- `PluginGraphics.java`:
  - Added `worldToScreenList(int, int, int)` returning a 2-element `List<Integer>` for array-free coordinate projection.

### Cleanups & Deprecations
- `PluginManager.java`:
  - Removed `MenuEntrySwapperPlugin` and `GroundItemsOverlayPlugin` registrations from `registerBuiltIns()`, leaving `Hd317Plugin`.
- `MenuEntrySwapperPlugin.java`, `GroundItemsOverlayPlugin.java`:
  - Removed built-in plugin classes (migrated to `2006scape-plugins/plugins/MenuEntrySwapper.java` and `GroundItems.java`).

* perf(plugins): optimize ScriptInterpreter/PluginContext and fix Web Online Repo SHA lookup

Improve script/plugin execution speed for TeaVM/Web and Desktop/Android, add throttled in-game chat error reporting, and fix Online Repo commit SHA resolution on Web.

### Script & Plugin Engine
- `PluginContext.java`
  - Added `getGroundItems(int radius)` to scan only `[plx - radius, plx + radius]` x `[ply - radius, ply + radius]` instead of the full 104x104 tile grid, with a `game == null` fallback to `getGroundItems()` for unit test mocks.
- `ScriptInterpreter.java`
  - Pre-parsed `FunctionDef` bodies into `List<Stmt>` (`parseBlock`, `parseIfStatement`, `parseSimpleStatement`) at compile time, removing per-execution substring scanning in `executeStmts`.
  - Added `METHOD_CACHE` (`getCachedMethods`) to index public methods by lowercase name per `Class<?>`, eliminating repeated `clazz.getMethods()` scans in `invokeReflectiveMethod`.
  - Added `Environment.reportedErrors` and `reportRuntimeError` to surface the first uncaught runtime error per function to in-game chat.
- `PluginManager.java`
  - Added `reportedPluginErrors` (cleared on `reloadExternal()`) and `reportPluginError` across `onGameTick`, `onPostBuildMenu`, and `onRenderOverlays` to surface the first error per plugin/phase to in-game chat.

### Online Repository
- `PluginRepoClient.java`
  - Added `REPO_COMMIT_API_URL` using `PLUGIN_REPO_SLUG` (`2006-Scape/Client-Extensions`) and `PLUGIN_REPO_BRANCH` (`main`) as a CORS-friendly fallback in `resolveLatestMainSha()` when `.git/info/refs` is unavailable in the browser.

* perf(graphics): add native drawTileLabelBatches for ground item overlays

Move per-frame ground item tile and label rendering loops from interpreted script execution into compiled Java on `PluginGraphics` to eliminate per-frame TeaVM reflection and AST overhead.

### Graphics Pipeline
- `PluginGraphics.java`
  - Added `drawTileLabelBatches(List<?>, int, int)` to project cached tile coordinates (`worldToScreen` with `worldToScreenList` fallback for unit test mocks), lazily cache `getTextWidth`, render lootbeams, and draw label boxes/text in compiled Java.

* perf(plugins): add ground item signature and native tile batch builder to PluginContext

Eliminate periodic stutters caused by `GroundItems` rebuilding its tile cache in `ScriptInterpreter` every 500ms by providing a zero-allocation ground item fingerprint and compiled batch builder.

### Plugin API
- `PluginContext.java`
  - Added `getGroundItemsSignature(int radius)` to compute a lightweight FNV-1a fingerprint of ground items within `radius` tiles without allocating `GroundItemWrapper` objects or looking up `ItemDef`.
  - Added `buildGroundItemTiles(...)` to perform wildcard filtering, duplicate collapsing, sorting, label/quantity/value formatting, and border/lootbeam preparation in compiled Java.

* refactor(plugins): remove GroundItems-specific buildGroundItemTiles from PluginContext

Keep `PluginContext` limited to generic client API primitives (`getGroundItems(int)` and `getGroundItemsSignature(int)`) while moving Ground Items-specific grouping, tier coloring, and label formatting back into the plugin.

### Cleanups & Deprecations
- `PluginContext.java`
  - Removed `buildGroundItemTiles(...)` and its private helpers (`matchesAnyPattern`, `getGroundItemColor`, `formatItemQuantity`, `formatItemValue`) along with unused `Map`/`HashMap`/`LinkedHashMap` imports.

* feat(scripts): add ternary, modulo, compound assignments, constructors, list literals, and indexing

Expand `ScriptInterpreter` expression and statement support to simplify plugin and script authoring across Desktop, Android, and Web.

### Script & Plugin Engine
- `ScriptInterpreter.java`
  - Added short-circuiting ternary (`cond ? a : b` with `findMatchingTernaryColon`), `%` modulo operator, and unified `+=`, `-=`, `*=`, `/=`, `%=` compound assignments.
  - Added `target[index]` reads and `target[index] = value` writes for `List`, `Map`, arrays, and `String`, plus bracket-aware `findTopLevelOp` and `parseArguments`.
  - Added `[a, b, c]` list literals and `new ClassName(...)` constructors (`ArrayList`, `HashMap`, `LinkedHashMap`, `HashSet`, `StringBuilder`, `WorldArea`, `MenuEntry`, plus reflective constructor fallback).
  - Fast-pathed `StringBuilder` (`append`, `toString`, `length`, `setLength`) in `invokeMethod` and fixed `findMethodOpenParen` to ignore parentheses inside string literals.
- `ScriptInterpreterTest.java`
  - Added `evaluatesTernaryModuloConstructorsAndIndexing` covering ternary, `%`, `*=`, `/=`, `%=`, list literals, `new HashMap()`, `new StringBuilder()`, indexing, and unbalanced parentheses inside strings.

* fix(scripts): support long literals with L suffix in ScriptInterpreter

Parse integer literals ending in `l` or `L` (e.g. `0L`) as `Long` instead of returning `null`.

### Bug Fixes & Edge Cases
- `ScriptInterpreter.java`
  - Added `^-?\d+[lL]$` literal handling in `evalExpression` before standard integer literal parsing.

* feat(scripts): add for/for-each/switch/break/continue, braceless blocks, and TeaVM fast-paths

Expand `ScriptInterpreter` control-flow support and add direct non-reflective fast-paths for `PluginContext`, `PluginGraphics`, `MenuEntry`, and `GroundItemWrapper` to eliminate TeaVM `Class.getMethods()` `ReferenceError`s and per-tick reflection overhead.

### Script & Plugin Engine
- `ScriptInterpreter.java`
  - Added `for (init; cond; update)`, enhanced `for (var : iterable)`, `switch`/`case`/`default`, `break`/`continue` (`BreakSignal`, `ContinueSignal`), and braceless single-statement bodies (`parseBodyOrSingleStatement`) for `if`, `else`, `while`, and `for`.
  - Added direct fast-paths in `invokeMethod` for `PluginContext` (`isLoggedIn`, `getGroundItems`, `getGroundItemsSignature`, `createList`, `createMap`, `sendClientMessage`, `getPlayerX`, `getPlayerY`, `getPlayerAnim`, `isBankOpen`, `getInventoryCount`, `walkTo`), `PluginContext.GroundItemWrapper` (`getDistance`), `MenuEntry` (`stripColorTags`, `matches`, `getAction`, `getTarget`, `getRawText`, `setRawText`), and `PluginGraphics` (`drawTileLabelBatches`, `fillRect`, `drawRect`, `drawCenteredString`, `drawString`, `drawStringBold`, `getTextWidth`, `getTextWidthBold`, `worldToScreenList`, `drawLootbeam`, `getViewportWidth`, `getViewportHeight`).
  - Added `try/catch` guard around `clazz.getMethods()` in `getCachedMethods` and included `[expr|phase]` diagnostics in `reportRuntimeError`.

### Unit Tests
- `ScriptInterpreterTest.java`
  - Added `evaluatesForLoopsBreakContinueBracelessAndSwitch` covering `for`, `for-each`, `break`, `continue`, braceless `if`, `switch` fallthrough/default, and `MenuEntry` fast-paths.

* feat(plugin-hub): add multi-line STRING config editor overlay and localStorage config seeding

Replaces the non-editable "(Edit in .properties or chat)" placeholder in Plugin Hub settings with an interactive multi-line text editor overlay supporting cursor navigation and click positioning. Also seeds plugin settings on first boot and adds live localStorage reload support for web/cross-platform storage editing.

### Command Infrastructure
- `PluginManager.java`:
  - Added `reloadStorage()` and `applyConfigToPlugin(...)` so external storage edits hot-reload `2006scape_plugin_settings` and `2006scape_script_*` entries into active plugins and scripts.
  - Updated `loadConfig()` to call `saveConfig()` when `DesktopHooks.loadPluginConfig()` returns `null`, seeding `2006scape_plugin_settings` on first boot.
- `RSApplet.java`:
  - Queued Left (`1`) and Right (`2`) arrow keys into `charQueue` when `PluginPanelUI.isSearchFocused()` is true so arrow-key cursor movement reaches the modal editor without affecting normal gameplay.

### UI & Edge Cases
- `PluginPanelUI.java`:
  - Replaced `(Edit in .properties or chat)` with a `220px` preview box in `drawConfigEditor` and `handleConfigTab`.
  - Added `drawConfigStringEditorOverlay`, `getStringEditorBounds`, and `wrapTextForWidth` to render a focused multi-line wrapped editor (up to 1,024 chars) with Clear, Cancel, and Save buttons.
  - Added `editingStringCursor` with Left/Right arrow, Home/End, mid-string insert/backspace, vertical gold caret rendering, auto-scroll to keep the cursor line visible, and pixel-accurate click-to-place-cursor support.
  - Added `commitStringEdit(PluginManager)` to auto-commit on blur, Back, or Close.
This commit is contained in:
Josh Shippam authored and GitHub committed 2026-12-02 18:29:47 +00:00
1 parent c37e3e8dfb
commit 60463d7c31
12 files changed
+1411 -812

No files matched your search

+5 -16
View File
@@ -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() {
@@ -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<PluginConfigItem> getConfigItems() {
List<PluginConfigItem> 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<PluginContext.GroundItemWrapper> rawItems = ctx.getGroundItems();
if (rawItems == null || rawItems.isEmpty()) return;
// Group items by tile: key = (worldX << 16) | (worldY & 0xffff)
Map<Long, List<DisplayItem>> tileMap = new LinkedHashMap<>();
Map<Long, int[]> 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<DisplayItem> 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<Long, List<DisplayItem>> entry : tileMap.entrySet()) {
long tileKey = entry.getKey();
List<DisplayItem> 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<MenuEntry> 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 <item name or pattern>");
}
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 <item name or pattern>");
}
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));
}
}
@@ -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<PluginConfigItem> getConfigItems() {
List<PluginConfigItem> 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<MenuEntry> 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<MenuEntry> 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 <Action>:<Target> or ::swap clear");
}
return true;
}
}
return false;
}
}
@@ -580,18 +580,51 @@ public class PluginContext {
}
public List<GroundItemWrapper> getGroundItems() {
return getGroundItemsInternal(104);
}
/**
* Scans only tiles within {@code radius} of the player instead of the full 104x104 region.
*/
public List<GroundItemWrapper> 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<GroundItemWrapper> all = getGroundItems();
if (all == null || all.isEmpty()) return Collections.emptyList();
List<GroundItemWrapper> filtered = new ArrayList<>();
for (GroundItemWrapper item : all) {
if (item.getDistance() <= radius) {
filtered.add(item);
}
}
return filtered;
}
return getGroundItemsInternal(radius);
}
private List<GroundItemWrapper> getGroundItemsInternal(int radius) {
if (!isLoggedIn() || game == null) return Collections.emptyList();
List<GroundItemWrapper> 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<GroundItemWrapper> 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<GroundItemWrapper> items = getGroundItems();
for (GroundItemWrapper item : items) {
@@ -1669,6 +1741,14 @@ public class PluginContext {
// Utilities & Configuration
// =========================================================================
public List<Object> createList() {
return new ArrayList<>();
}
public java.util.Map<Object, Object> createMap() {
return new java.util.HashMap<>();
}
public void sendClientMessage(String msg) {
if (game != null && msg != null) {
game.pushMessage(msg, 0, "");
@@ -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<Integer> worldToScreenList(int worldX, int worldY, int heightOffset) {
int[] pos = worldToScreen(worldX, worldY, heightOffset);
if (pos == null) return null;
java.util.List<Integer> 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<Object, Object> tile = (java.util.Map<Object, Object>) 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<Integer> 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<Object, Object> item = (java.util.Map<Object, Object>) 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.
*/
@@ -22,6 +22,7 @@ public class PluginManager {
private final List<ClientPlugin> plugins = new ArrayList<>();
private final List<ClientScript> scripts = new ArrayList<>();
private final List<String> lastLoadErrors = new ArrayList<>();
private final Set<String> 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();
@@ -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<String> editorLines = null;
private static List<Integer> 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<PluginConfigItem> 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<String> outLines, List<Integer> 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<PluginConfigItem> 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<String>();
if (editorLineStarts == null) editorLineStarts = new java.util.ArrayList<Integer>();
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
@@ -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) {
+1 -1
View File
@@ -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;
}
File diff suppressed because it is too large. Load diff
@@ -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"));
}
}
@@ -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();