From 816f52b313b499bdc15bcb1e0af8674f32e8e51a Mon Sep 17 00:00:00 2001 From: Xel Date: Sat, 28 May 2011 12:10:41 +0300 Subject: [PATCH] back to orig source for now --- readme | 2 +- resources/Manifest.txt | 1 - resources/images/database_error.png | Bin 0 -> 682 bytes resources/version.txt | 2 +- src/org/rsbot/Application.java | 2 - src/org/rsbot/Boot.java | 1 - src/org/rsbot/bot/Crawler.java | 20 +- src/org/rsbot/event/impl/DrawInventory.java | 4 +- src/org/rsbot/event/impl/DrawWeb.java | 10 +- src/org/rsbot/event/impl/TTab.java | 5 +- .../rsbot/event/impl/TUserInputAllowed.java | 6 +- src/org/rsbot/gui/AccountManager.java | 4 +- src/org/rsbot/gui/BotGUI.java | 114 ++--- src/org/rsbot/gui/BotHome.java | 5 +- src/org/rsbot/gui/BotMenuBar.java | 24 +- src/org/rsbot/gui/BotToolBar.java | 5 + src/org/rsbot/gui/ScriptSelector.java | 199 +++++---- src/org/rsbot/gui/SettingsManager.java | 50 ++- src/org/rsbot/gui/SplashAd.java | 10 +- src/org/rsbot/loader/ClientLoader.java | 8 +- src/org/rsbot/loader/script/ModScript.java | 2 +- src/org/rsbot/log/TextAreaLogHandler.java | 2 +- src/org/rsbot/script/AccountStore.java | 26 +- src/org/rsbot/script/background/WebData.java | 9 +- .../rsbot/script/background/WebLoader.java | 5 +- src/org/rsbot/script/methods/Account.java | 6 - src/org/rsbot/script/methods/Bank.java | 84 ++-- .../rsbot/script/methods/Calculations.java | 421 +++++++++--------- src/org/rsbot/script/methods/Camera.java | 2 - src/org/rsbot/script/methods/ClanChat.java | 64 +-- src/org/rsbot/script/methods/Combat.java | 202 +++++---- src/org/rsbot/script/methods/Equipment.java | 5 +- src/org/rsbot/script/methods/FriendChat.java | 16 +- src/org/rsbot/script/methods/Game.java | 335 +++++++++----- src/org/rsbot/script/methods/GameGUI.java | 53 +-- src/org/rsbot/script/methods/Hiscores.java | 1 - src/org/rsbot/script/methods/Interfaces.java | 29 +- src/org/rsbot/script/methods/Inventory.java | 14 +- src/org/rsbot/script/methods/Lobby.java | 2 +- src/org/rsbot/script/methods/Magic.java | 23 +- src/org/rsbot/script/methods/Menu.java | 6 +- .../rsbot/script/methods/MethodContext.java | 2 - .../rsbot/script/methods/MethodProvider.java | 2 - src/org/rsbot/script/methods/Mouse.java | 55 +-- src/org/rsbot/script/methods/NPCs.java | 2 - src/org/rsbot/script/methods/Nodes.java | 5 +- src/org/rsbot/script/methods/Objects.java | 31 +- src/org/rsbot/script/methods/Players.java | 2 - src/org/rsbot/script/methods/Prayer.java | 6 +- src/org/rsbot/script/methods/Quests.java | 4 +- src/org/rsbot/script/methods/Settings.java | 1 - src/org/rsbot/script/methods/Skills.java | 6 +- src/org/rsbot/script/methods/Store.java | 12 +- src/org/rsbot/script/methods/Tiles.java | 2 - src/org/rsbot/script/methods/Trade.java | 42 +- src/org/rsbot/script/methods/Walking.java | 8 +- src/org/rsbot/script/methods/Web.java | 112 +++-- .../script/provider/FileScriptSource.java | 50 ++- .../script/provider/ScriptDefinition.java | 40 +- .../provider/ScriptDeliveryNetwork.java | 272 ++++------- .../script/provider/ScriptDownloader.java | 3 +- .../rsbot/script/randoms/FirstTimeDeath.java | 4 +- .../rsbot/script/randoms/FreakyForester.java | 7 +- src/org/rsbot/script/randoms/FrogCave.java | 21 +- src/org/rsbot/script/randoms/LoginBot.java | 46 +- .../rsbot/script/randoms/TeleotherCloser.java | 5 +- src/org/rsbot/script/util/BankCache.java | 5 +- src/org/rsbot/script/util/SkillData.java | 5 + .../script/web/methods/TeleportItem.java | 22 +- .../script/web/methods/TeleportJewelry.java | 30 +- .../script/web/methods/TeleportRunes.java | 6 +- .../rsbot/script/wrappers/RSCharacter.java | 2 +- src/org/rsbot/script/wrappers/RSObject.java | 14 + .../security/RestrictedSecurityManager.java | 9 +- src/org/rsbot/service/Monitoring.java | 8 +- src/org/rsbot/service/WebQueue.java | 38 +- src/org/rsbot/util/StringUtil.java | 4 + src/org/rsbot/util/UpdateChecker.java | 7 +- src/org/rsbot/util/io/HttpClient.java | 61 ++- src/org/rsbot/util/io/IniParser.java | 11 +- 80 files changed, 1372 insertions(+), 1369 deletions(-) create mode 100644 resources/images/database_error.png diff --git a/readme b/readme index 4541a0f..0720e26 100644 --- a/readme +++ b/readme @@ -1 +1 @@ -Everything is fucked up ;P have to update most stuff.. \ No newline at end of file +Back to orig source for now. \ No newline at end of file diff --git a/resources/Manifest.txt b/resources/Manifest.txt index 6147632..145003b 100644 --- a/resources/Manifest.txt +++ b/resources/Manifest.txt @@ -1,5 +1,4 @@ Main-Class: org.rsbot.Boot -Class-Path: lib/xel.jar Name: org/rsbot Sealed: true diff --git a/resources/images/database_error.png b/resources/images/database_error.png new file mode 100644 index 0000000000000000000000000000000000000000..578221aaab1c7f6f1f5f9eb4adf02aaad93bf407 GIT binary patch literal 682 zcmV;b0#*HqP)87 z5D7ClS`>i>siY*D_Hz7r-uLe7+&8^)8l^=KKF+=8o%5aVo_ns%Fbw?9=NR3j(`lIq z&l4_j&X15iM4%;qPxcepJA`yB7SpX9o27t~=V*Q3@ApT8!5};y58Q4y#D7Im(CKtg zsZ`KtG+vYMVmuzNnu#JnAeBlzFPF=roH6NRj2XFH&PXPcD^{M}l0uuKfk5D&XAXrz zpdx3t^?;lvW4&I7%jJSB%WyiKrmxrQq19@kTCE}+4x6zP2^(duC2SE#)bB9=iVf68`kSQeakO%!CNk8ZR-m z?*w*FFTmM-3w@)sMZq=#Gl@t{bZZ!XeF5)YAM_uOFn#O_`sF9!I-5*jRo65I^~*E( zBNu?dI#%!A!!BPRgIX3|y(Et%5U{H2%16kyA-q#PaP>1aiIe;_%$~lEAY1pW-a6^s zLLj7ztD;GSyh8%7JcV!OIC$?J<@T`{kAM$r)ZhXRM9)c@I=uF`f~8C*(=8T@aDLBH z?I;- zi%TAvMLVRO5!65AQFy%kz&7qVzqz^CG<5E!W7`eUT(0v?OSAIJVzcSlpH|(e&rbmL QkpKVy07*qoM6N<$f|gM=-T(jq literal 0 HcmV?d00001 diff --git a/resources/version.txt b/resources/version.txt index 8d0003f..2c2b1af 100644 --- a/resources/version.txt +++ b/resources/version.txt @@ -1 +1 @@ -245 \ No newline at end of file +245 diff --git a/src/org/rsbot/Application.java b/src/org/rsbot/Application.java index ba50149..4799dc9 100644 --- a/src/org/rsbot/Application.java +++ b/src/org/rsbot/Application.java @@ -8,7 +8,6 @@ import org.rsbot.util.ApplicationException; import org.rsbot.util.io.IOHelper; - import javax.swing.*; import java.awt.*; @@ -33,7 +32,6 @@ public static void main(final String[] args) { System.setProperty("java.io.tmpdir", Configuration.Paths.getGarbageDirectory()); gui = new BotGUI(); gui.setVisible(true); - } catch (final Exception e) { e.printStackTrace(); System.out.print(e.getMessage()); diff --git a/src/org/rsbot/Boot.java b/src/org/rsbot/Boot.java index db9c9da..993e9cb 100644 --- a/src/org/rsbot/Boot.java +++ b/src/org/rsbot/Boot.java @@ -4,7 +4,6 @@ import java.net.URLDecoder; - /** * @author Paris */ diff --git a/src/org/rsbot/bot/Crawler.java b/src/org/rsbot/bot/Crawler.java index 682908d..15ec255 100644 --- a/src/org/rsbot/bot/Crawler.java +++ b/src/org/rsbot/bot/Crawler.java @@ -1,9 +1,8 @@ package org.rsbot.bot; -import org.rsbot.Configuration; +import org.rsbot.util.io.HttpClient; -import java.io.BufferedReader; -import java.io.InputStreamReader; +import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; @@ -50,22 +49,15 @@ public Crawler(final String root) { private String downloadPage(final String url, final String referer) { try { - final HttpURLConnection con = Configuration.getHttpConnection(new URL(url)); + final HttpURLConnection con = HttpClient.getHttpConnection(new URL(url)); if (referer != null && !referer.isEmpty()) { con.addRequestProperty("Referer", referer); } - final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); - final StringBuilder buf = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - buf.append(line); - } - reader.close(); - return buf.toString(); - } catch (final Exception e) { + return HttpClient.downloadAsString(con); + } catch (final IOException e) { e.printStackTrace(); + return ""; } - return null; } private String firstMatch(final String regex, final String str) { diff --git a/src/org/rsbot/event/impl/DrawInventory.java b/src/org/rsbot/event/impl/DrawInventory.java index eb44e77..4a459e8 100644 --- a/src/org/rsbot/event/impl/DrawInventory.java +++ b/src/org/rsbot/event/impl/DrawInventory.java @@ -9,20 +9,18 @@ import java.awt.*; public class DrawInventory implements PaintListener { - private final MethodContext ctx; public DrawInventory(final Bot bot) { ctx = bot.getMethodContext(); } - @Override public void onRepaint(final Graphics render) { if (!ctx.game.isLoggedIn()) { return; } - if (ctx.game.getCurrentTab() != Game.TAB_INVENTORY) { + if (ctx.game.getTab() != Game.Tab.INVENTORY) { return; } diff --git a/src/org/rsbot/event/impl/DrawWeb.java b/src/org/rsbot/event/impl/DrawWeb.java index 95396f2..c602ef6 100644 --- a/src/org/rsbot/event/impl/DrawWeb.java +++ b/src/org/rsbot/event/impl/DrawWeb.java @@ -2,9 +2,9 @@ import org.rsbot.bot.Bot; import org.rsbot.event.listeners.PaintListener; +import org.rsbot.script.internal.wrappers.TileData; import org.rsbot.script.methods.MethodContext; import org.rsbot.script.methods.Web; -import org.rsbot.script.internal.wrappers.TileData; import org.rsbot.script.wrappers.RSPlayer; import org.rsbot.script.wrappers.RSTile; @@ -18,7 +18,6 @@ * @author Timer */ public class DrawWeb implements PaintListener { - private final MethodContext ctx; /** @@ -49,10 +48,11 @@ public void onRepaint(final Graphics render) { } final RSTile oT = player.getLocation(); final int plane = ctx.game.getPlane(); - final Iterator> rs = Web.rs_map.entrySet().iterator(); + final Iterator> rs = Web.rs_map.entrySet().iterator(); while (rs.hasNext()) { - Map.Entry e = rs.next(); - final RSTile t = e.getKey(); + final Map.Entry e = rs.next(); + final Short[] tile = e.getKey(); + final RSTile t = new RSTile(tile[0], tile[1], tile[2]); final int key = e.getValue(); if (t.getZ() == plane && ctx.calc.distanceBetween(t, oT) < 105) { render.setColor(TileData.Questionable(key) ? Color.yellow : TileData.Special(key) ? Color.cyan : Color.red); diff --git a/src/org/rsbot/event/impl/TTab.java b/src/org/rsbot/event/impl/TTab.java index 05078e5..0c5b9bd 100644 --- a/src/org/rsbot/event/impl/TTab.java +++ b/src/org/rsbot/event/impl/TTab.java @@ -3,6 +3,7 @@ import org.rsbot.bot.Bot; import org.rsbot.event.listeners.TextPaintListener; import org.rsbot.script.methods.Game; +import org.rsbot.script.methods.Game.Tab; import org.rsbot.util.StringUtil; import java.awt.*; @@ -17,9 +18,9 @@ public TTab(final Bot bot) { @Override public int drawLine(final Graphics render, int idx) { - final int cTab = game.getCurrentTab(); + final Tab cTab = game.getTab(); StringUtil.drawLine(render, idx++, - "Current Tab: " + cTab + (cTab != -1 ? " (" + Game.TAB_NAMES[cTab] + ")" : "")); + "Current Tab: " + cTab.description() + " (" + cTab.index() + ")"); return idx; } diff --git a/src/org/rsbot/event/impl/TUserInputAllowed.java b/src/org/rsbot/event/impl/TUserInputAllowed.java index 6ce5fd7..f1526ed 100644 --- a/src/org/rsbot/event/impl/TUserInputAllowed.java +++ b/src/org/rsbot/event/impl/TUserInputAllowed.java @@ -16,9 +16,9 @@ public TUserInputAllowed(final Bot bot) { @Override public int drawLine(final Graphics render, int idx) { - StringUtil.drawLine(render, idx++, "User Input: " + - (bot.inputFlags == 0 && !bot.overrideInput ? - "[red]Disabled (" + bot.inputFlags + ")" : "[green]Enabled")); + final String i = bot.overrideInput || bot.inputFlags == 3 ? "[green]Enabled" : + "[red]Disabled (" + bot.inputFlags + ")"; + StringUtil.drawLine(render, idx++, "User Input: " + i); return idx; } } diff --git a/src/org/rsbot/gui/AccountManager.java b/src/org/rsbot/gui/AccountManager.java index a35b4cf..7c3416b 100644 --- a/src/org/rsbot/gui/AccountManager.java +++ b/src/org/rsbot/gui/AccountManager.java @@ -2,7 +2,7 @@ import org.rsbot.Configuration; import org.rsbot.script.AccountStore; -import org.rsbot.script.provider.ScriptDeliveryNetwork; +import org.rsbot.service.DRM; import javax.swing.*; import javax.swing.event.ListSelectionEvent; @@ -48,7 +48,7 @@ public class AccountManager extends JDialog implements ActionListener { private static final AccountStore accountStore = new AccountStore(new File(FILE_ACCOUNT_STORAGE)); static { - accountStore.setPassword(ScriptDeliveryNetwork.getInstance().getKey()); + accountStore.setPassword(DRM.getServiceKey()); try { accountStore.load(); } catch (final IOException ignored) { diff --git a/src/org/rsbot/gui/BotGUI.java b/src/org/rsbot/gui/BotGUI.java index 11e78c5..a909fe8 100644 --- a/src/org/rsbot/gui/BotGUI.java +++ b/src/org/rsbot/gui/BotGUI.java @@ -3,31 +3,24 @@ import org.rsbot.Configuration; import org.rsbot.Configuration.OperatingSystem; import org.rsbot.bot.Bot; +import org.rsbot.gui.component.Messages; import org.rsbot.log.TextAreaLogHandler; import org.rsbot.script.Script; import org.rsbot.script.ScriptManifest; import org.rsbot.script.internal.ScriptHandler; import org.rsbot.script.internal.event.ScriptListener; import org.rsbot.script.methods.Environment; -import org.rsbot.script.provider.ScriptDeliveryNetwork; import org.rsbot.script.provider.ScriptDownloader; import org.rsbot.script.util.WindowUtil; import org.rsbot.service.Monitoring; import org.rsbot.service.Monitoring.Type; import org.rsbot.service.TwitterUpdates; -import org.rsbot.service.TwitterUpdates2; -import org.rsbot.service.TwitterUpdates3; import org.rsbot.service.WebQueue; import org.rsbot.util.ApplicationException; import org.rsbot.util.UpdateChecker; +import org.rsbot.util.io.IOHelper; import org.rsbot.util.io.ScreenshotUtil; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPopupMenu; -import javax.swing.ToolTipManager; -import javax.swing.UIManager; -import java.awt.Dimension; import javax.swing.*; import java.awt.*; import java.awt.TrayIcon.MessageType; @@ -39,17 +32,11 @@ import java.util.List; import java.util.logging.Logger; - /** * @author Paris * @author Jacmob - * @author Xel */ public class BotGUI extends JFrame implements ActionListener, ScriptListener { - - - - public static final int PANEL_WIDTH = 765, PANEL_HEIGHT = 503, LOG_HEIGHT = 120; public static final int MAX_BOTS = 6; private static final long serialVersionUID = -5411033752001988794L; @@ -66,45 +53,16 @@ public class BotGUI extends JFrame implements ActionListener, ScriptListener { private TrayIcon tray = null; private java.util.Timer shutdown = null; private java.util.Timer clean = null; - public BotGUI() throws ApplicationException { - - - - - Toolkit.getDefaultToolkit().setDynamicLayout(true); - System.setProperty("sun.awt.noerasebackground", "true"); - JFrame.setDefaultLookAndFeelDecorated(true); - JDialog.setDefaultLookAndFeelDecorated(true); - - try { - UIManager.setLookAndFeel("de.muntjak.tinylookandfeel.TinyLookAndFeel"); - //UIManager.setLookAndFeel("org.jvnet.substance.SubstanceLookAndFeel"); - //UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.SubstanceOfficeBlue2007LookAndFeel"); - //UIManager.setLookAndFeel(new SubstanceLookAndFeel()); - //SubstanceLookAndFeel.setCurrentTheme(new SubstanceEbonyTheme()); - - - } catch(Exception ex) { - ex.printStackTrace(); - } - - - - - - /*try { - UIManager.setLookAndFeel("de.muntjak.tinylookandfeel.TinyLookAndFeel"); - //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (final Exception ignored) { } - */ if (UpdateChecker.isError()) { throw new ApplicationException("Unable to obtain latest version information.\nPlease check your internet connection and try again."); } else if (Configuration.RUNNING_FROM_JAR && UpdateChecker.isDeprecatedVersion()) { - throw new ApplicationException("Your RSCBot version has been killed. " + "Go to http://rscoders.org and get the latest version"); + throw new ApplicationException("This version has been deprecated, please update at " + Configuration.Paths.URLs.DOWNLOAD); } init(); pack(); @@ -126,20 +84,6 @@ public void run() { if (Configuration.Twitter.ENABLED) { TwitterUpdates.loadTweets(Configuration.Twitter.MESSAGES); } - UpdateChecker.notify(BotGUI.this); - if (Configuration.Twitter2.ENABLED) { - TwitterUpdates2.loadTweets(Configuration.Twitter2.MESSAGES); - } - UpdateChecker.notify(BotGUI.this); - if (Configuration.Twitter3.ENABLED) { - TwitterUpdates3.loadTweets(Configuration.Twitter3.MESSAGES); - } - new Thread() { - @Override - public void run() { - ScriptDeliveryNetwork.getInstance().start(); - } - }.start(); Monitoring.start(); addBot(); updateScriptControls(); @@ -156,20 +100,18 @@ public void run() { }, 1000 * 60 * 10, 1000 * 60 * 10); } - @Override public void setTitle(final String title) { - String t = Configuration.NAME + " v" + "0.23"; + String t = Configuration.NAME + " v" + Configuration.getVersionFormatted(); final int v = Configuration.getVersion(), l = UpdateChecker.getLatestVersion(); if (v > l) { - t += " "; + t += " beta"; } if (title != null) { t = title + " - " + t; } super.setTitle(t); } - public void actionPerformed(final ActionEvent evt) { final String action = evt.getActionCommand(); @@ -206,8 +148,6 @@ public void actionPerformed(final ActionEvent evt) { if (current != null) { showScriptSelector(current); } - } else if (option.equals(Messages.SERVICEKEY)) { - serviceKeyQuery(option); } else if (option.equals(Messages.STOPSCRIPT)) { final Bot current = getCurrentBot(); if (current != null) { @@ -240,6 +180,8 @@ public void actionPerformed(final ActionEvent evt) { updateScriptControls(); } else if (option.equals(Messages.LESSCPU)) { lessCpu(((JCheckBoxMenuItem) evt.getSource()).isSelected()); + } else if (option.equals(Messages.EXTDVIEWS)) { + menuBar.setExtendedView(((JCheckBoxMenuItem) evt.getSource()).isSelected()); } else if (option.equals(Messages.DISABLEANTIRANDOMS)) { current.disableRandoms = ((JCheckBoxMenuItem) evt.getSource()).isSelected(); } else if (option.equals(Messages.DISABLEAUTOLOGIN)) { @@ -284,7 +226,16 @@ public void actionPerformed(final ActionEvent evt) { } } } else if (menu.equals(Messages.TOOLS)) { - if (option.equals(Messages.OPTIONS)) { + if (option.equals(Messages.CLEARCACHE)) { + final int result = JOptionPane.showConfirmDialog(this, + "Delete all preferences and settings?\nNote: only use if the application is having errors.", option, + JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); + if (result == JOptionPane.YES_OPTION) { + IOHelper.recursiveDelete(new File(Configuration.Paths.getCacheDirectory()), false); + IOHelper.recursiveDelete(new File(Configuration.Paths.getSettingsDirectory()), false); + log.info("Cache cleared and preferences reset to defaults"); + } + } else if (option.equals(Messages.OPTIONS)) { settings.display(); } } else if (menu.equals(Messages.HELP)) { @@ -293,7 +244,7 @@ public void actionPerformed(final ActionEvent evt) { } else if (option.equals(Messages.PROJECT)) { openURL(Configuration.Paths.URLs.PROJECT); } else if (option.equals(Messages.ABOUT)) { - JOptionPane.showMessageDialog(this, new String[]{"RSBot client modified by Xel", "Visit " + "http://rscoders.org" + "/ for more information."}, option, JOptionPane.INFORMATION_MESSAGE); + JOptionPane.showMessageDialog(this, new String[]{"An open source bot developed by the community.", "Visit " + Configuration.Paths.URLs.SITE + "/ for more information."}, option, JOptionPane.INFORMATION_MESSAGE); } } else if (menu.equals("Tab")) { final Bot curr = getCurrentBot(); @@ -306,7 +257,11 @@ public void actionPerformed(final ActionEvent evt) { } } - private void updateScriptControls() { + public void updateScriptControls() { + updateScriptControls(false); + } + + public void updateScriptControls(final boolean block) { boolean idle = true, paused = false; final Bot bot = getCurrentBot(); @@ -320,40 +275,32 @@ private void updateScriptControls() { } } + if (block) { + idle = false; + } + menuBar.getMenuItem(Messages.RUNSCRIPT).setVisible(idle); menuBar.getMenuItem(Messages.STOPSCRIPT).setVisible(!idle); menuBar.getMenuItem(Messages.PAUSESCRIPT).setEnabled(!idle); menuBar.setPauseScript(paused); + toolBar.setInputButtonVisible(!idle); + menuBar.setEnabled(Messages.FORCEINPUT, !idle); if (idle) { toolBar.setOverrideInput(false); menuBar.setOverrideInput(false); toolBar.setInputState(Environment.INPUT_KEYBOARD | Environment.INPUT_MOUSE); toolBar.setScriptButton(BotToolBar.RUN_SCRIPT); - menuBar.setEnabled(Messages.FORCEINPUT, false); } else { toolBar.setOverrideInput(bot.overrideInput); toolBar.setOverrideInput(bot.overrideInput); toolBar.setInputState(bot.inputFlags); toolBar.setScriptButton(paused ? BotToolBar.RESUME_SCRIPT : BotToolBar.PAUSE_SCRIPT); - menuBar.setEnabled(Messages.FORCEINPUT, true); } toolBar.updateInputButton(); } - private void serviceKeyQuery(final String option) { - final String currentKey = ScriptDeliveryNetwork.getInstance().getKey(); - final String key = (String) JOptionPane.showInputDialog(this, null, option, JOptionPane.QUESTION_MESSAGE, null, null, currentKey); - if (key == null || key.length() == 0) { - log.info("Services have been disabled"); - } else if (key.length() != 40) { - log.warning("Invalid service key"); - } else { - log.info("Services have been linked to {0}"); - } - } - private void lessCpu(boolean on) { disableRendering(on || menuBar.isTicked(Messages.LESSCPU)); } @@ -714,4 +661,3 @@ public void mousePressed(MouseEvent arg0) { lessCpu(true); } } - diff --git a/src/org/rsbot/gui/BotHome.java b/src/org/rsbot/gui/BotHome.java index 0c846bc..90ec411 100644 --- a/src/org/rsbot/gui/BotHome.java +++ b/src/org/rsbot/gui/BotHome.java @@ -7,7 +7,6 @@ import java.awt.image.BufferedImage; import java.util.Collection; - /** * @author Jacmob * @author Paris @@ -77,7 +76,7 @@ public void paint(final Graphics g) { final FontMetrics metrics = g.getFontMetrics(FONT); g.setColor(new Color(0, 0, 0, 170)); g.fillRect(0, height - 30, width, 30); - g.setColor(Color.MAGENTA); + g.setColor(Color.white); g.drawString("Spectating " + (bots.length == 1 ? "1 bot." : bots.length + " bots."), 5, height + metrics.getDescent() - 14); } @@ -96,7 +95,7 @@ public void draw(final Graphics g, final int idx, final int x, final int y, fina h = (int) ((float) h_img / (float) w_img * w); } g.drawImage(img.getScaledInstance(w, h, Image.SCALE_SMOOTH), x + width / 2 - w / 2, y + height / 2 - h / 2, null); - g.setColor(Color.MAGENTA); + g.setColor(Color.gray); g.drawRect(x, y, width - 1, height - 1); } } diff --git a/src/org/rsbot/gui/BotMenuBar.java b/src/org/rsbot/gui/BotMenuBar.java index 3922a7d..ad73027 100644 --- a/src/org/rsbot/gui/BotMenuBar.java +++ b/src/org/rsbot/gui/BotMenuBar.java @@ -5,6 +5,7 @@ import org.rsbot.event.impl.*; import org.rsbot.event.listeners.PaintListener; import org.rsbot.event.listeners.TextPaintListener; +import org.rsbot.gui.component.Messages; import javax.swing.*; import java.awt.*; @@ -23,7 +24,8 @@ public class BotMenuBar extends JMenuBar { public static final String[] TITLES; public static final String[][] ELEMENTS; - private static final String[] DEVELOPER_CHECK_FEATURES = {"Game State", "Current Tab", "Camera", "Floor Height", + private static final boolean EXTD_VIEW_INITIAL = !Configuration.RUNNING_FROM_JAR; + private static final String[] EXTD_VIEW_ITEMS = {"Game State", "Current Tab", "Camera", "Floor Height", "Mouse Position", "User Input Allowed", "Menu", "Menu Actions", "Cache", "Models", "Calc Test", "Settings"}; static { @@ -59,7 +61,7 @@ public class BotMenuBar extends JMenuBar { TITLES = new String[]{Messages.FILE, Messages.EDIT, Messages.VIEW, Messages.TOOLS, Messages.HELP}; ELEMENTS = new String[][]{ {Messages.NEWBOT, Messages.CLOSEBOT, Messages.MENUSEPERATOR, - Messages.SERVICEKEY, Messages.ADDSCRIPT, + Messages.ADDSCRIPT, Messages.RUNSCRIPT, Messages.STOPSCRIPT, Messages.PAUSESCRIPT, Messages.MENUSEPERATOR, Messages.SAVESCREENSHOT, Messages.MENUSEPERATOR, @@ -67,10 +69,11 @@ public class BotMenuBar extends JMenuBar { {Messages.ACCOUNTS, Messages.MENUSEPERATOR, Messages.TOGGLEFALSE + Messages.FORCEINPUT, Messages.TOGGLEFALSE + Messages.LESSCPU, + (EXTD_VIEW_INITIAL ? Messages.TOGGLETRUE : Messages.TOGGLEFALSE) + Messages.EXTDVIEWS, Messages.MENUSEPERATOR, Messages.TOGGLEFALSE + Messages.DISABLEANTIRANDOMS, Messages.TOGGLEFALSE + Messages.DISABLEAUTOLOGIN}, - constructDebugs(), {Messages.OPTIONS}, {Messages.SITE, Messages.PROJECT, Messages.ABOUT}}; + constructDebugs(), {Messages.CLEARCACHE, Messages.OPTIONS}, {Messages.SITE, Messages.PROJECT, Messages.ABOUT}}; } private static String[] constructDebugs() { @@ -112,7 +115,6 @@ private void constructItemIcons() { final HashMap map = new HashMap(16); map.put(Messages.NEWBOT, Configuration.Paths.Resources.ICON_APPADD); map.put(Messages.CLOSEBOT, Configuration.Paths.Resources.ICON_APPDELETE); - map.put(Messages.SERVICEKEY, Configuration.Paths.Resources.ICON_KEY); map.put(Messages.ADDSCRIPT, Configuration.Paths.Resources.ICON_SCRIPT_ADD); map.put(Messages.RUNSCRIPT, Configuration.Paths.Resources.ICON_PLAY); map.put(Messages.STOPSCRIPT, Configuration.Paths.Resources.ICON_DELETE); @@ -121,6 +123,7 @@ private void constructItemIcons() { map.put(Messages.HIDEBOT, Configuration.Paths.Resources.ICON_ARROWIN); map.put(Messages.EXIT, Configuration.Paths.Resources.ICON_CLOSE); map.put(Messages.ACCOUNTS, Configuration.Paths.Resources.ICON_REPORTKEY); + map.put(Messages.CLEARCACHE, Configuration.Paths.Resources.DATABASE_ERROR); map.put(Messages.OPTIONS, Configuration.Paths.Resources.ICON_WRENCH); map.put(Messages.SITE, Configuration.Paths.Resources.ICON_WEBLINK); map.put(Messages.PROJECT, Configuration.Paths.Resources.ICON_GITHUB); @@ -144,13 +147,14 @@ public BotMenuBar(final ActionListener listener) { add(constructMenu(title, elems)); } constructItemIcons(); - commandMenuItem.get(Messages.SERVICEKEY).setVisible(false); commandMenuItem.get(Messages.HIDEBOT).setVisible(SystemTray.isSupported()); - if (Configuration.RUNNING_FROM_JAR) { - for (String disableFeature : DEVELOPER_CHECK_FEATURES) { - if (commandCheckMap.containsKey(disableFeature)) { - commandCheckMap.get(disableFeature).setVisible(false); - } + setExtendedView(EXTD_VIEW_INITIAL); + } + + public void setExtendedView(final boolean show) { + for (String disableFeature : EXTD_VIEW_ITEMS) { + if (commandCheckMap.containsKey(disableFeature)) { + commandCheckMap.get(disableFeature).setVisible(show); } } } diff --git a/src/org/rsbot/gui/BotToolBar.java b/src/org/rsbot/gui/BotToolBar.java index c2cac64..8ff6bd3 100644 --- a/src/org/rsbot/gui/BotToolBar.java +++ b/src/org/rsbot/gui/BotToolBar.java @@ -1,6 +1,7 @@ package org.rsbot.gui; import org.rsbot.Configuration; +import org.rsbot.gui.component.Messages; import org.rsbot.script.methods.Environment; import javax.imageio.ImageIO; @@ -128,6 +129,10 @@ public void setAddTabVisible(final boolean visible) { addTabButton.setVisible(visible); } + public void setInputButtonVisible(final boolean visible) { + userInputButton.setVisible(visible); + } + public void addTab() { final int idx = getComponentCount() - BUTTONCOUNT - TABINDEX + 1; add(new BotButton(Messages.TABDEFAULTTEXT, ICON_BOT), idx); diff --git a/src/org/rsbot/gui/ScriptSelector.java b/src/org/rsbot/gui/ScriptSelector.java index 22e59ae..2e15ecd 100644 --- a/src/org/rsbot/gui/ScriptSelector.java +++ b/src/org/rsbot/gui/ScriptSelector.java @@ -2,6 +2,7 @@ import org.rsbot.Configuration; import org.rsbot.bot.Bot; +import org.rsbot.gui.component.JComboCheckBox; import org.rsbot.script.Script; import org.rsbot.script.internal.ScriptHandler; import org.rsbot.script.internal.event.ScriptListener; @@ -15,10 +16,13 @@ import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableColumn; + import java.awt.*; import java.awt.event.*; import java.io.File; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.logging.Logger; @@ -29,15 +33,17 @@ public class ScriptSelector extends JDialog implements ScriptListener { private static final long serialVersionUID = 5475451138208522511L; private static final Logger log = Logger.getLogger(ScriptSelector.class.getName()); - private static final String[] COLUMN_NAMES = new String[]{"", "Name", "Version", "Author", "Description"}; + private static final String[] COLUMN_NAMES = new String[]{"", "Name", "Description"}; private static final ScriptSource SRC_SOURCES; private static final ScriptSource SRC_PRECOMPILED; - private static final ScriptSource SRC_DRM; + private static final ScriptSource SRC_NETWORK; + private final BotGUI frame; private final Bot bot; private JTable table; private JTextField search; private JComboBox accounts; + private final JComboCheckBox categories = new JComboCheckBox(); private final ScriptTableModel model; private final List scripts; private JButton submit; @@ -46,11 +52,12 @@ public class ScriptSelector extends JDialog implements ScriptListener { static { SRC_SOURCES = new FileScriptSource(new File(Configuration.Paths.getScriptsSourcesDirectory())); SRC_PRECOMPILED = new FileScriptSource(new File(Configuration.Paths.getScriptsPrecompiledDirectory())); - SRC_DRM = ScriptDeliveryNetwork.getInstance(); + SRC_NETWORK = ScriptDeliveryNetwork.getInstance(); } - public ScriptSelector(final Frame frame, final Bot bot) { + public ScriptSelector(final BotGUI frame, final Bot bot) { super(frame, "Script Selector", true); + this.frame = frame; this.bot = bot; scripts = new ArrayList(); model = new ScriptTableModel(scripts); @@ -75,11 +82,31 @@ public void update() { private void load() { scripts.clear(); if (connected) { - scripts.addAll(SRC_DRM.list()); + final List net = SRC_NETWORK.list(); + if (net != null) { + scripts.addAll(net); + } } scripts.addAll(SRC_PRECOMPILED.list()); scripts.addAll(SRC_SOURCES.list()); - model.search((search == null || search.getText().contains("\0")) ? "" : search.getText()); + Collections.sort(scripts); + + final ArrayList keywords = new ArrayList(scripts.size()); + for (final ScriptDefinition def : scripts) { + if (def.keywords == null || def.keywords.length == 0) { + continue; + } + for (String keyword : def.keywords) { + keyword = keyword.toLowerCase().trim(); + if (keyword.length() > 0 && !keywords.contains(keyword)) { + keywords.add(keyword); + } + } + } + Collections.sort(keywords); + categories.populate(keywords, false); + + filter(); table.revalidate(); } @@ -99,16 +126,14 @@ public void windowClosing(final WindowEvent e) { final JButton refresh = new JButton(new ImageIcon(Configuration.getImage(Configuration.Paths.Resources.ICON_REFRESH))); refresh.setToolTipText("Refresh"); refresh.addActionListener(new ActionListener() { - @Override public void actionPerformed(ActionEvent arg0) { refresh.setEnabled(false); SwingUtilities.invokeLater(new Runnable() { - @Override public void run() { new Thread() { @Override public void run() { - ScriptDeliveryNetwork.getInstance().forceUpdate(); + ScriptDeliveryNetwork.getInstance().refresh(true); load(); refresh.setEnabled(true); } @@ -124,21 +149,7 @@ public void run() { public String getToolTipText(MouseEvent e) { int row = rowAtPoint(e.getPoint()); ScriptDefinition def = model.getDefinition(row); - if (def != null) { - StringBuilder b = new StringBuilder(); - b.append(def.name); - b.append(" v"); - b.append(def.version); - b.append(" by "); - for (int i = 0; i < def.authors.length; i++) { - if (i > 0) { - b.append(i == def.authors.length - 1 ? " and " : ", "); - } - b.append(def.authors[i]); - } - return b.toString(); - } - return super.getToolTipText(e); + return def.toString(); } }; table.addMouseListener(new MouseAdapter() { @@ -207,7 +218,7 @@ public void actionPerformed(ActionEvent e) { table.setShowGrid(false); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getSelectionModel().addListSelectionListener(new TableSelectionListener()); - setColumnWidths(table, 30, 175, 55, 95); + setColumnWidths(table, 30, 200); final JToolBar toolBar = new JToolBar(); toolBar.setMargin(new Insets(1, 1, 1, 1)); toolBar.setFloatable(false); @@ -237,9 +248,10 @@ public void focusLost(final FocusEvent e) { search.addKeyListener(new KeyAdapter() { @Override public void keyTyped(final KeyEvent e) { - model.search(search.getText()); + filter(); table.revalidate(); } + @Override public void keyReleased(final KeyEvent e) { keyTyped(e); @@ -254,17 +266,29 @@ public void keyReleased(final KeyEvent e) { submit.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent evt) { final ScriptDefinition def = model.getDefinition(table.getSelectedRow()); - try { - bot.setAccount((String) accounts.getSelectedItem()); - bot.getScriptHandler().runScript(def.source.load(def)); - bot.getScriptHandler().removeScriptListener(ScriptSelector.this); - dispose(); - } catch (final ServiceException e) { - e.printStackTrace(); - } + setVisible(false); + final String account = (String) accounts.getSelectedItem(); + bot.getScriptHandler().removeScriptListener(ScriptSelector.this); + dispose(); + new Thread() { + @Override + public void run() { + Script script = null; + frame.updateScriptControls(true); + try { + script = def.source.load(def); + } catch (final ServiceException e) { + log.severe(e.getMessage()); + } + if (script != null) { + bot.setAccount(account); + bot.getScriptHandler().runScript(script); + frame.updateScriptControls(); + } + } + }.start(); } }); - connect.setEnabled(Configuration.SCRIPT_DRM ? true : false); if (connect.isEnabled()) { final ActionListener listenConnect = new ActionListener() { public void actionPerformed(final ActionEvent e) { @@ -279,9 +303,39 @@ public void actionPerformed(final ActionEvent e) { connect.addActionListener(listenConnect); } accounts = new JComboBox(AccountManager.getAccountNames()); - accounts.setPreferredSize(new Dimension(200, 20)); + accounts.setPreferredSize(new Dimension(125, 20)); + categories.setPreferredSize(new Dimension(150, 20)); + categories.addActionListener(new ActionListener() { + @Override + public void actionPerformed(final ActionEvent arg0) { + final String[] selected = categories.getSelectedItems(); + final StringBuilder s = new StringBuilder(16); + switch (selected.length) { + case 0: + s.append("Showing all"); + break; + case 1: + s.append(selected[0]); + break; + case 2: + s.append(selected[0]); + s.append(" & "); + s.append(selected[1]); + break; + default: + s.append("Showing "); + s.append(selected.length); + s.append(" types"); + break; + } + categories.setText(s.toString()); + filter(); + } + }); toolBar.add(search); toolBar.add(Box.createHorizontalStrut(5)); + toolBar.add(categories); + toolBar.add(Box.createHorizontalStrut(5)); toolBar.add(accounts); toolBar.add(Box.createHorizontalStrut(5)); toolBar.add(refresh); @@ -302,11 +356,16 @@ public void actionPerformed(final ActionEvent e) { search.requestFocus(); } + private void filter() { + model.search((search == null || search.getText().contains("\0")) ? "" : search.getText(), categories.getSelectedItems()); + } + private void setColumnWidths(final JTable table, final int... widths) { for (int i = 0; i < widths.length; ++i) { - table.getColumnModel().getColumn(i).setPreferredWidth(widths[i]); - table.getColumnModel().getColumn(i).setMinWidth(widths[i]); - table.getColumnModel().getColumn(i).setMaxWidth(widths[i]); + final TableColumn col = table.getColumnModel().getColumn(i); + col.setPreferredWidth(widths[i]); + col.setMinWidth(widths[i]); + col.setMaxWidth(widths[i]); } } @@ -341,7 +400,7 @@ private static class ScriptTableModel extends AbstractTableModel { Configuration.getImage(Configuration.Paths.Resources.ICON_SCRIPT_EDIT)); public static final ImageIcon ICON_SCRIPT_PRE = new ImageIcon( Configuration.getImage(Configuration.Paths.Resources.ICON_SCRIPT_GEAR)); - public static final ImageIcon ICON_SCRIPT_DRM = new ImageIcon( + public static final ImageIcon ICON_SCRIPT_NET = new ImageIcon( Configuration.getImage(Configuration.Paths.Resources.ICON_SCRIPT_LIVE)); private final List scripts; private final List matches; @@ -351,25 +410,26 @@ public ScriptTableModel(final List scripts) { matches = new ArrayList(); } - public void search(String substr) { + public void search(final String find, final String[] keys) { matches.clear(); - substr = substr.trim(); - if (substr.isEmpty()) { - matches.addAll(scripts); - } else { - substr = substr.toLowerCase(); - for (final ScriptDefinition def : scripts) { - if (def.name.toLowerCase().contains(substr)) { - matches.add(def); - } else { - for (final String keyword : def.keywords) { - if (keyword.toLowerCase().contains(substr)) { - matches.add(def); - break; - } - } + for (final ScriptDefinition def : scripts) { + if (find.length() != 0 && !def.name.toLowerCase().contains(find)) { + continue; + } + final ArrayList list = new ArrayList(def.keywords.length); + for (final String key : def.keywords) { + list.add(key.toLowerCase()); + } + boolean hit = true; + for (final String key : keys) { + if (!list.contains(key)) { + hit = false; + break; } } + if (hit) { + matches.add(def); + } } fireTableDataChanged(); } @@ -389,30 +449,19 @@ public int getColumnCount() { public Object getValueAt(final int rowIndex, final int columnIndex) { if (rowIndex >= 0 && rowIndex < matches.size()) { final ScriptDefinition def = matches.get(rowIndex); - if (columnIndex == 0) { + switch (columnIndex) { + case 0: if (def.source == SRC_SOURCES) { return ICON_SCRIPT_SRC; } if (def.source == SRC_PRECOMPILED) { return ICON_SCRIPT_PRE; } - return ICON_SCRIPT_DRM; - } - if (columnIndex == 1) { - return def.name; - } - if (columnIndex == 2) { - return def.version; - } - if (columnIndex == 3) { - final StringBuilder b = new StringBuilder(); - for (final String author : def.authors) { - b.append(author).append(", "); - } - return b.replace(b.length() - 2, b.length(), ""); - } - if (columnIndex == 4) { - return def.description; + return ICON_SCRIPT_NET; + case 1: + return def.getName(); + case 2: + return def.getDescription(); } } return null; @@ -431,4 +480,4 @@ public String getColumnName(final int col) { return COLUMN_NAMES[col]; } } -} \ No newline at end of file +} diff --git a/src/org/rsbot/gui/SettingsManager.java b/src/org/rsbot/gui/SettingsManager.java index 5f62324..0fb11a0 100644 --- a/src/org/rsbot/gui/SettingsManager.java +++ b/src/org/rsbot/gui/SettingsManager.java @@ -2,11 +2,14 @@ import org.rsbot.Configuration; import org.rsbot.Configuration.OperatingSystem; +import org.rsbot.gui.component.Messages; import org.rsbot.service.Monitoring; +import org.rsbot.service.DRM; import org.rsbot.util.StringUtil; import org.rsbot.util.io.IniParser; import javax.swing.*; + import java.awt.*; import java.awt.event.*; import java.io.*; @@ -19,6 +22,7 @@ public class SettingsManager extends JDialog { private static Logger log = Logger.getLogger(SettingsManager.class.getName()); private static final long serialVersionUID = 1657935322078534422L; + private static final String DEFAULTPASSWORD = "\0\0\0\0\0\0\0\0"; private Preferences prefs; public class Preferences { @@ -28,7 +32,7 @@ public class Preferences { * Whether or not to disable ads. */ public boolean ads = true; - + public String user = ""; public boolean confirmations = true; public boolean monitoring = true; public boolean shutdown = false; @@ -48,15 +52,16 @@ public void load() { if (!store.exists()) { store.createNewFile(); } - final BufferedReader reader = new BufferedReader(new FileReader(store)); - keys = IniParser.deserialise(reader).get(IniParser.emptySection); - reader.close(); + keys = IniParser.deserialise(store).get(IniParser.emptySection); } catch (final IOException ignored) { log.severe("Failed to load preferences"); } if (keys == null || keys.isEmpty()) { return; } + if (keys.containsKey("user")) { + user = keys.get("user"); + } if (keys.containsKey("ads")) { ads = IniParser.parseBool(keys.get("ads")); } @@ -89,6 +94,7 @@ public void load() { public void save() { final HashMap keys = new HashMap(5); + keys.put("user", user); keys.put("ads", Boolean.toString(ads)); keys.put("confirmations", Boolean.toString(confirmations)); keys.put("monitoring", Boolean.toString(monitoring)); @@ -125,6 +131,8 @@ public SettingsManager(final Frame owner, final File store) { setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setIconImage(Configuration.getImage(Configuration.Paths.Resources.ICON_WRENCH)); + final JPanel panelLogin = new JPanel(new GridLayout(2, 1)); + panelLogin.setBorder(BorderFactory.createTitledBorder("Service Login")); final JPanel panelOptions = new JPanel(new GridLayout(0, 1)); panelOptions.setBorder(BorderFactory.createTitledBorder("Display")); final JPanel panelInternal = new JPanel(new GridLayout(0, 1)); @@ -132,8 +140,22 @@ public SettingsManager(final Frame owner, final File store) { final JPanel panelWeb = new JPanel(new GridLayout(2, 1)); panelWeb.setBorder(BorderFactory.createTitledBorder("Web UI")); + final JPanel[] panelLoginOptions = new JPanel[2]; + for (int i = 0; i < panelLoginOptions.length; i++) { + panelLoginOptions[i] = new JPanel(new GridLayout(1, 2)); + } + panelLoginOptions[0].add(new JLabel(" Username:")); + final JTextField textLoginUser = new JTextField(prefs.user); + textLoginUser.setToolTipText(Configuration.Paths.URLs.HOST + " forum account username, leave blank to log out"); + panelLoginOptions[0].add(textLoginUser); + panelLoginOptions[1].add(new JLabel(" Password:")); + final JPasswordField textLoginPass = new JPasswordField(prefs.user.length() == 0 ? "" : DEFAULTPASSWORD); + panelLoginOptions[1].add(textLoginPass); + panelLogin.add(panelLoginOptions[0]); + panelLogin.add(panelLoginOptions[1]); + final JCheckBox checkAds = new JCheckBox(Messages.DISABLEADS); - checkAds.setToolTipText("Show splash image on startup"); + checkAds.setToolTipText("Show advertisment on startup"); checkAds.setSelected(prefs.ads); final JCheckBox checkConf = new JCheckBox(Messages.DISABLECONFIRMATIONS); @@ -174,7 +196,7 @@ public void actionPerformed(final ActionEvent arg0) { final JCheckBox checkWebPass = new JCheckBox(Messages.USEPASSWORD); checkWebPass.setSelected(prefs.webPassRequire); panelWebOptions[1].add(checkWebPass); - final JPasswordField textWebPass = new JPasswordField("\0\0\0\0\0\0\0\0"); + final JPasswordField textWebPass = new JPasswordField(DEFAULTPASSWORD); textWebPass.addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { @@ -227,13 +249,22 @@ public void actionPerformed(ActionEvent arg0) { prefs.shutdownTime = modelShutdown.getNumber().intValue(); prefs.web = checkWeb.isSelected(); prefs.webBind = textWebBind.getText(); - final char[] pass = textWebPass.getPassword(); - if (pass.length > 0 && pass[0] != '\0') { - prefs.webPass = StringUtil.sha1sum(new String(pass)); + final String webUser = textLoginUser.getText(), webPass = new String(textWebPass.getPassword()); + if (!webUser.equals(prefs.user) || !webPass.equals(DEFAULTPASSWORD)) { + prefs.webPass = StringUtil.sha1sum(webPass); } + prefs.user = webUser; prefs.webPassRequire = checkWebPass.isSelected() && checkWebPass.isEnabled(); prefs.commit(); + final String loginPass = new String(textLoginPass.getPassword()); + if (!loginPass.equals(DEFAULTPASSWORD)) { + if (!DRM.login(prefs.user, loginPass)) { + prefs.user = ""; + } + } prefs.save(); + textLoginPass.setText(DEFAULTPASSWORD); + textWebPass.setText(DEFAULTPASSWORD); dispose(); } }); @@ -255,6 +286,7 @@ public void actionPerformed(ActionEvent arg0) { final JPanel panel = new JPanel(new GridLayout(0, 1)); panel.setBorder(panelAction.getBorder()); + panel.add(panelLogin); panel.add(panelOptions); panel.add(panelInternal); diff --git a/src/org/rsbot/gui/SplashAd.java b/src/org/rsbot/gui/SplashAd.java index f1491f4..9aecab0 100644 --- a/src/org/rsbot/gui/SplashAd.java +++ b/src/org/rsbot/gui/SplashAd.java @@ -12,9 +12,7 @@ import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; -import java.io.BufferedReader; import java.io.File; -import java.io.FileReader; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; @@ -42,7 +40,7 @@ public SplashAd(final JFrame owner) { setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setUndecorated(true); - setTitle("Splash by Risk @ RSCoders.org"); + setTitle("Advertisement"); setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); if (!sync()) { @@ -83,10 +81,8 @@ private boolean sync() { final URL source = new URL(Configuration.Paths.URLs.AD_INFO); final File cache = new File(Configuration.Paths.getCacheDirectory(), "ads.txt"); HttpClient.download(source, cache); - final BufferedReader reader = new BufferedReader(new FileReader(cache)); - keys = IniParser.deserialise(reader).get(IniParser.emptySection); - reader.close(); - } catch (final Exception e) { + keys = IniParser.deserialise(cache).get(IniParser.emptySection); + } catch (final IOException e) { return false; } diff --git a/src/org/rsbot/loader/ClientLoader.java b/src/org/rsbot/loader/ClientLoader.java index 54d7d90..f9d18de 100644 --- a/src/org/rsbot/loader/ClientLoader.java +++ b/src/org/rsbot/loader/ClientLoader.java @@ -148,13 +148,13 @@ private int checkVersion(final InputStream in) throws IOException { final ClassReader reader = new ClassReader(in); final VersionVisitor vv = new VersionVisitor(); reader.accept(vv, ClassReader.SKIP_FRAMES); - if (vv.getVersion() != vv.getVersion()) { + if (vv.getVersion() != script.getVersion()) { JOptionPane.showMessageDialog( null, - "O fuck what just happened?.. please hold......... rscoders.org", - "What is this.. i don't even..", + "The bot is currently oudated, please wait patiently for a new version.", + "Outdated", JOptionPane.INFORMATION_MESSAGE); - throw new IOException("WaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaithttp://www.youtube.com/watch?v=UsDWj2NhIncWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWaitWait" + script.getVersion() + " != #" + vv.getVersion()); + throw new IOException("ModScript #" + script.getVersion() + " != #" + vv.getVersion()); } return vv.getVersion(); } diff --git a/src/org/rsbot/loader/script/ModScript.java b/src/org/rsbot/loader/script/ModScript.java index 6c37b51..7d2084e 100644 --- a/src/org/rsbot/loader/script/ModScript.java +++ b/src/org/rsbot/loader/script/ModScript.java @@ -204,4 +204,4 @@ private ClassVisitor delegate(final String clazz) { } } -} +} \ No newline at end of file diff --git a/src/org/rsbot/log/TextAreaLogHandler.java b/src/org/rsbot/log/TextAreaLogHandler.java index 80027cc..19ccf66 100644 --- a/src/org/rsbot/log/TextAreaLogHandler.java +++ b/src/org/rsbot/log/TextAreaLogHandler.java @@ -1,6 +1,6 @@ package org.rsbot.log; -import org.rsbot.gui.LogTextArea; +import org.rsbot.gui.component.LogTextArea; import java.util.logging.Handler; import java.util.logging.LogRecord; diff --git a/src/org/rsbot/script/AccountStore.java b/src/org/rsbot/script/AccountStore.java index a0fcd17..d692352 100644 --- a/src/org/rsbot/script/AccountStore.java +++ b/src/org/rsbot/script/AccountStore.java @@ -37,33 +37,11 @@ public String getUsername() { } public String getPassword() { - boolean safe = true; - final StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); - for (final StackTraceElement stackTraceElement : stackTraceElements) { - safe = safe && (stackTraceElement.getClassName().contains("org.rsbot.") || stackTraceElement - .getClassName().contains("java.lang.T") || stackTraceElement - .getClassName().contains("java.awt.") || stackTraceElement - .getClassName().contains("javax.swing.") || stackTraceElement - .getClassName().contains("java.security.") || stackTraceElement - .getClassName().contains("sun.awt.")); - } - return safe ? password : null; + return password; } public String getAttribute(final String key) { - boolean safe = true; - final StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); - if (key.equalsIgnoreCase("pin")) { - for (final StackTraceElement stackTraceElement : stackTraceElements) { - safe = safe && (stackTraceElement.getClassName().contains("org.rsbot.") || stackTraceElement - .getClassName().contains("java.lang.T") || stackTraceElement - .getClassName().contains("java.awt.") || stackTraceElement - .getClassName().contains("javax.swing.") || stackTraceElement - .getClassName().contains("java.security.") || stackTraceElement - .getClassName().contains("sun.awt.")); - } - } - return safe ? attributes.get(key) : null; + return attributes.get(key); } public void setAttribute(final String key, final String value) { diff --git a/src/org/rsbot/script/background/WebData.java b/src/org/rsbot/script/background/WebData.java index ee98c0c..bdc1cdc 100644 --- a/src/org/rsbot/script/background/WebData.java +++ b/src/org/rsbot/script/background/WebData.java @@ -13,7 +13,7 @@ public class WebData extends BackgroundScript { private RSTile lb = null; private int lp = -1; - public final HashMap rs_map = new HashMap(); + public final HashMap rs_map = new HashMap(); private static final Object lock = new Object(); @Override @@ -49,11 +49,12 @@ public int loop() { final int x = t.x, y = t.y; final int f_x = x - off_x, f_y = y - off_y; final int here = flags[f_x][f_y]; + final Short[] theArray = {(short) start.getX(), (short) start.getY(), (short) start.getZ()}; synchronized (lock) { - if (!Web.rs_map.containsKey(start) && (!TileData.Walkable(here) || TileData.Questionable(here))) { - rs_map.put(start, here); + if (!Web.rs_map.containsKey(theArray) && (!TileData.Walkable(here) || TileData.Questionable(here))) { + rs_map.put(theArray, here); } else { - if (Web.rs_map.containsKey(start) && (Web.rs_map.get(start) != here || here == 0)) { + if (Web.rs_map.containsKey(theArray) && (Web.rs_map.get(theArray) != here || here == 0)) { WebQueue.Remove(start); lb = null; lp = -1; diff --git a/src/org/rsbot/script/background/WebLoader.java b/src/org/rsbot/script/background/WebLoader.java index 82b1e53..d69ee93 100644 --- a/src/org/rsbot/script/background/WebLoader.java +++ b/src/org/rsbot/script/background/WebLoader.java @@ -4,7 +4,6 @@ import org.rsbot.script.BackgroundScript; import org.rsbot.script.ScriptManifest; import org.rsbot.script.methods.Web; -import org.rsbot.script.wrappers.RSTile; import org.rsbot.service.WebQueue; import java.io.BufferedReader; @@ -36,14 +35,14 @@ public int loop() { } final BufferedReader bufferedReader = new BufferedReader(new FileReader(Configuration.Paths.getWebDatabase())); String dataLine; - final HashMap mapData = new HashMap(); + final HashMap mapData = new HashMap(); while ((dataLine = bufferedReader.readLine()) != null) { final String[] storeData = dataLine.split("k"); if (storeData.length == 2) { final String[] tileData = storeData[0].split(","); if (tileData.length == 3) { try { - final RSTile tile = new RSTile(Integer.parseInt(tileData[0]), Integer.parseInt(tileData[1]), Integer.parseInt(tileData[2])); + final Short[] tile = {Short.parseShort(tileData[0]), Short.parseShort(tileData[1]), Short.parseShort(tileData[2])}; final int tileFlag = Integer.parseInt(storeData[1]); if (mapData.containsKey(tile)) { WebQueue.Remove(dataLine);//Line is double, remove from file--bad collection! diff --git a/src/org/rsbot/script/methods/Account.java b/src/org/rsbot/script/methods/Account.java index 1c5f6bf..3380823 100644 --- a/src/org/rsbot/script/methods/Account.java +++ b/src/org/rsbot/script/methods/Account.java @@ -2,15 +2,10 @@ import org.rsbot.gui.AccountManager; -import java.util.logging.Logger; - /** * Selected account information. */ public class Account extends MethodProvider { - - Logger log = Logger.getLogger(getClass().getName()); - public Account(final MethodContext ctx) { super(ctx); } @@ -50,5 +45,4 @@ public String getPin() { public String getReward() { return AccountManager.getReward(getName()); } - } diff --git a/src/org/rsbot/script/methods/Bank.java b/src/org/rsbot/script/methods/Bank.java index 639039b..d70005b 100644 --- a/src/org/rsbot/script/methods/Bank.java +++ b/src/org/rsbot/script/methods/Bank.java @@ -9,16 +9,46 @@ * Bank related operations. */ public class Bank extends MethodProvider { + public static final Filter OBJECT_BANKS = new Filter() { + private final String[] bankNames = {"Bank Booth", "Bank Chest", "Counter"}; - public static final int[] BANKERS = {44, 45, 494, 495, 499, 553, 958, 1036, 2271, 2354, 2355, 2759, 3824, 5488, - 5901, 5912, 5913, 6362, 6532, 6533, 6534, 6535, 7605, 8948, 9710, 14367}; - public static final int[] BANK_BOOTHS = {782, 2213, 6084, 11402, 11758, 12759, 14367, 19230, 24914, 25808, 26972, - 29085, 34752, 35647, 36786}; - public static final int[] BANK_CHESTS = {4483, 12308, 20607, 21301, 27663, 42192}; - public static final int[] BANK_DEPOSIT_BOX = {9398, 20228, 26969, 36788}; - public static final int[] DO_NOT_DEPOSIT = new int[]{1265, 1267, 1269, 1273, 1271, 1275, 1351, 590, 303}; - public static final RSTile[] UNREACHABLE_BANKERS = { - new RSTile(3191, 3445), new RSTile(3180, 3433) // VARROCK EAST + public boolean accept(final RSObject rsObject) { + final String name = rsObject != null ? rsObject.getName() : null; + for (String bankName : bankNames) { + if (name.equalsIgnoreCase(bankName)) { + return true; + } + } + return false; + } + }; + + public static final Filter OBJECT_DEPOSIT_BOX = new Filter() { + private final String[] depositBoxNames = {"Deposit Box"}; + + public boolean accept(final RSObject rsObject) { + final String name = rsObject != null ? rsObject.getName() : null; + for (String bankName : depositBoxNames) { + if (name.equalsIgnoreCase(bankName)) { + return true; + } + } + return false; + } + }; + + public static final Filter NPC_BANKERS = new Filter() { + private final String[] bankerNames = {"Banker"}; + + public boolean accept(final RSNPC rsNPC) { + final String name = rsNPC != null ? rsNPC.getName() : null; + for (String bankName : bankerNames) { + if (name.equalsIgnoreCase(bankName)) { + return true; + } + } + return false; + } }; public static final int INTERFACE_BANK = 762; @@ -361,24 +391,6 @@ public boolean isDepositOpen() { return methods.interfaces.get(INTERFACE_DEPOSIT_BOX).isValid(); } - private static class ReachableBankerFilter implements Filter { - public boolean accept(final RSNPC npc) { - final int id = npc.getID(); - final RSTile location = npc.getLocation(); - for (final int banker : BANKERS) { - if (banker == id) { - for (final RSTile unreachableBanker : UNREACHABLE_BANKERS) { - if (unreachableBanker.equals(location)) { - return false; - } - } - return true; - } - } - return false; - } - } - /** * Opens one of the supported banker NPCs, booths, or chests nearby. If they * are not nearby, and they are not null, it will automatically walk to the @@ -395,9 +407,8 @@ public boolean open() { methods.mouse.moveSlightly(); sleep(random(20, 30)); } - RSObject bankBooth = methods.objects.getNearest(BANK_BOOTHS); - RSNPC banker = methods.npcs.getNearest(new ReachableBankerFilter()); - final RSObject bankChest = methods.objects.getNearest(BANK_CHESTS); + RSObject bankBooth = methods.objects.getNearest(OBJECT_BANKS); + RSNPC banker = methods.npcs.getNearest(NPC_BANKERS); /* Find closest one, others are set to null. Remember distance and tile. */ int lowestDist = Integer.MAX_VALUE; RSTile tile = null; @@ -410,21 +421,13 @@ public boolean open() { lowestDist = methods.calc.distanceTo(tile); bankBooth = null; } - if (bankChest != null && methods.calc.distanceTo(bankChest) < lowestDist) { - tile = bankChest.getLocation(); - lowestDist = methods.calc.distanceTo(tile); - bankBooth = null; - banker = null; - } /* Open closest one, if any found */ if (lowestDist < 5 && methods.calc.tileOnMap(tile) && methods.calc.canReach(tile, true)) { boolean didAction = false; if (bankBooth != null) { - didAction = bankBooth.doAction("Use-Quickly"); + didAction = bankBooth.doAction("Use-quickly"); } else if (banker != null) { didAction = banker.doAction("Bank", "Banker"); - } else if (bankChest != null) { - didAction = bankChest.doAction("Bank") || methods.menu.doAction("Use"); } if (didAction) { int count = 0; @@ -461,7 +464,7 @@ public boolean openDepositBox() { methods.mouse.moveSlightly(); sleep(random(20, 30)); } - final RSObject depositBox = methods.objects.getNearest(BANK_DEPOSIT_BOX); + final RSObject depositBox = methods.objects.getNearest(OBJECT_DEPOSIT_BOX); if (depositBox != null && methods.calc.distanceTo(depositBox) < 8 && methods.calc.tileOnMap(depositBox.getLocation()) && methods.calc.canReach(depositBox.getLocation(), true)) { if (depositBox.doAction("Deposit")) { int count = 0; @@ -789,5 +792,4 @@ public int getItemID(final String name) { } return -1; } - } \ No newline at end of file diff --git a/src/org/rsbot/script/methods/Calculations.java b/src/org/rsbot/script/methods/Calculations.java index 6af5c71..146c3ed 100644 --- a/src/org/rsbot/script/methods/Calculations.java +++ b/src/org/rsbot/script/methods/Calculations.java @@ -44,79 +44,83 @@ static class RenderData { } /** - * Checks whether or not a given tile is on the minimap. + * Returns the angle to a given tile in degrees anti-clockwise from the + * positive x axis (where the x-axis is from west to east). * - * @param t The RSTile to check. - * @return true if the RSTile is on the minimap; otherwise false. - * @see #tileToMinimap(RSTile) + * @param t The target tile + * @return The angle in degrees */ - public boolean tileOnMap(final RSTile t) { - return distanceTo(t) < 15; + public int angleToTile(final RSTile t) { + final RSTile me = methods.players.getMyPlayer().getLocation(); + final int angle = (int) Math.toDegrees(Math.atan2(t.getY() - me.getY(), t.getX() - me.getX())); + return angle >= 0 ? angle : 360 + angle; } /** - * Checks whether or not the centroid of a given tile is on the screen. + * Determines whether or not a given RSTile is reachable by the player. * - * @param t The RSTile to check. - * @return true if the RSTile is on the screen; otherwise false. + * @param dest The RSTile to check. + * @param isObject True if an instance of RSObject. + * @return true if a path can be made to the specified tile; otherwise false. */ - public boolean tileOnScreen(final RSTile t) { - return pointOnScreen(tileToScreen(t, 0.5, 0.5, 0)); + public boolean canReach(final RSTile dest, final boolean isObject) { + return pathLengthTo(dest, isObject) != -1; } /** - * Returns the Point on screen where a given tile is shown on the minimap. + * Calculates the distance between two points. * - * @param t The RSTile to check. - * @return Point within minimap; otherwise new Point(-1, -1). + * @param curr The first point. + * @param dest The second point. + * @return The distance between the two points, using the distance formula. + * @see #distanceBetween(RSTile, RSTile) */ - public Point tileToMinimap(final RSTile t) { - return worldToMinimap(t.getX(), t.getY()); + public double distanceBetween(final Point curr, final Point dest) { + return Math.sqrt((curr.x - dest.x) * (curr.x - dest.x) + (curr.y - dest.y) * (curr.y - dest.y)); } /** - * Checks whether a point is within the rectangle that determines the bounds - * of game screen. This will work fine when in fixed mode. In resizable mode - * it will exclude any points that are less than 253 pixels from the right - * of the screen or less than 169 pixels from the bottom of the screen, - * giving a rough area. + * Returns the diagonal distance (hypot) between two RSTiles. * - * @param check The point to check. - * @return true if the point is within the rectangle; otherwise - * false. + * @param curr The starting tile. + * @param dest The destination tile. + * @return The diagonal distance between the two RSTiles. + * @see #distanceBetween(Point, Point) */ - public boolean pointOnScreen(final Point check) { - final int x = check.x, y = check.y; - if (methods.game.isFixed()) { - return x > 4 && x < methods.game.getWidth() - 253 && y > 4 && y < methods.game.getHeight() - 169; - } else { - return x > 0 && x < methods.game.getWidth() - 260 && y > 0 && y < methods.game.getHeight() - 149; - } + public double distanceBetween(final RSTile curr, final RSTile dest) { + return Math.sqrt((curr.getX() - dest.getX()) * (curr.getX() - dest.getX()) + (curr.getY() - dest.getY()) * (curr.getY() - dest.getY())); } /** - * Calculates the distance between two points. + * Returns the diagonal distance to a given RSCharacter. * - * @param curr The first point. - * @param dest The second point. - * @return The distance between the two points, using the distance formula. - * @see #distanceBetween(RSTile, RSTile) + * @param c The destination character. + * @return Distance to RSCharacter. + * @see #distanceTo(RSTile) */ - public double distanceBetween(final Point curr, final Point dest) { - return Math.sqrt((curr.x - dest.x) * (curr.x - dest.x) + (curr.y - dest.y) * (curr.y - dest.y)); + public int distanceTo(final RSCharacter c) { + return c == null ? -1 : distanceTo(c.getLocation()); } /** - * Returns a random double in a specified range + * Returns the diagonal distance to a given RSObject. * - * @param min Minimum value (inclusive). - * @param max Maximum value (exclusive). - * @return The random double generated. + * @param o The destination object. + * @return Distance to RSObject. + * @see #distanceTo(RSTile) */ - @Override - public double random(final double min, final double max) { - return Math.min(min, max) + methods.random.nextDouble() - * Math.abs(max - min); + public int distanceTo(final RSObject o) { + return o == null ? -1 : distanceTo(o.getLocation()); + } + + /** + * Returns the diagonal distance to a given RSTile. + * + * @param t The destination tile. + * @return Distance to RSTile. + */ + public int distanceTo(final RSTile t) { + return t == null ? -1 : (int) distanceBetween(methods.players.getMyPlayer().getLocation(), t); } /** @@ -144,138 +148,212 @@ public RSTile getTileOnScreen(final RSTile tile) { } /** - * Returns the angle to a given tile in degrees anti-clockwise from the - * positive x axis (where the x-axis is from west to east). + * Returns the screen location of a given point on the ground. This accounts + * for the height of the ground at the given location. * - * @param t The target tile - * @return The angle in degrees + * @param x x value based on the game plane. + * @param y y value based on the game plane. + * @param height height offset (normal to the ground). + * @return Point based on screen; otherwise new Point(-1, -1). */ - public int angleToTile(final RSTile t) { - final RSTile me = methods.players.getMyPlayer().getLocation(); - final int angle = (int) Math.toDegrees(Math.atan2(t.getY() - me.getY(), t.getX() - me.getX())); - return angle >= 0 ? angle : 360 + angle; + public Point groundToScreen(final int x, final int y, final int height) { + if (methods.client.getGroundByteArray() == null || methods.client.getTileData() == null || x < 512 || y < 512 || x > 52224 || y > 52224) { + return new Point(-1, -1); + } + final int z = tileHeight(x, y) + height; + return worldToScreen(x, y, z); } /** - * Returns the screen location of a Tile with given 3D x, y and height - * offset values. + * Returns the length of the path generated to a given RSTile. * - * @param tile RSTile for which the screen location should be calculated. - * @param dX Distance from bottom left of the tile to bottom right. Ranges from 0-1; - * @param dY Distance from bottom left of the tile to top left. Ranges from 0-1; - * @param height Height offset (normal to the ground) to return the Point at. - * @return Point based on position on the game plane; otherwise new Point(-1, -1). + * @param dest The destination tile. + * @param isObject true if reaching any tile adjacent to the destination should be accepted. + * @return true if reaching any tile adjacent to the destination should be accepted. */ - public Point tileToScreen(final RSTile tile, final double dX, final double dY, final int height) { - return groundToScreen((int) ((tile.getX() - methods.client.getBaseX() + dX) * 512), - (int) ((tile.getY() - methods.client.getBaseY() + dY) * 512), height); + public int pathLengthTo(final RSTile dest, final boolean isObject) { + final RSTile curPos = methods.players.getMyPlayer().getLocation(); + return pathLengthBetween(curPos, dest, isObject); } /** - * Returns the screen location of a Tile with a given 3D height offset. + * Returns the length of the path generates between two RSTiles. * - * @param tile RSTile for which the screen location should be calculated. - * @param height Height offset (normal to the ground) to return the Point at. - * @return Point based on position on the game plane; if null new Point(-1, -1). - * @see #tileToScreen(RSTile, double, double, int) + * @param start The starting tile. + * @param dest The destination tile. + * @param isObject true if reaching any tile adjacent to the destination should be accepted. + * @return true if reaching any tile adjacent to the destination should be accepted. */ - public Point tileToScreen(final RSTile tile, final int height) { - return tileToScreen(tile, 0.5, 0.5, height); + public int pathLengthBetween(final RSTile start, final RSTile dest, final boolean isObject) { + return dijkstraDist(start.getX() - methods.client.getBaseX(), // startX + start.getY() - methods.client.getBaseY(), // startY + dest.getX() - methods.client.getBaseX(), // destX + dest.getY() - methods.client.getBaseY(), // destY + isObject); // if it's an object, accept any adjacent tile } /** - * Returns the screen location of the south-west corner of the given tile. + * Checks whether a point is within the rectangle that determines the bounds + * of game screen. This will work fine when in fixed mode. In resizable mode + * it will exclude any points that are less than 253 pixels from the right + * of the screen or less than 169 pixels from the bottom of the screen, + * giving a rough area. * - * @param tile RSTile for which the screen location should be calculated. - * @return Center Point of the RSTile at a height of 0; if null new Point(-1, -1). - * @see #tileToScreen(RSTile, int) + * @param check The point to check. + * @return true if the point is within the rectangle; otherwise + * false. */ - public Point tileToScreen(final RSTile tile) { - return tileToScreen(tile, 0); + public boolean pointOnScreen(final Point check) { + final int x = check.x, y = check.y; + if (methods.game.isFixed()) { + return x > 4 && x < methods.game.getWidth() - 253 && y > 4 && y < methods.game.getHeight() - 169; + } else { + return x > 0 && x < methods.game.getWidth() - 260 && y > 0 && y < methods.game.getHeight() - 149; + } } /** - * Returns the diagonal distance to a given RSCharacter. + * Returns a random double in a specified range * - * @param c The destination character. - * @return Distance to RSCharacter. - * @see #distanceTo(RSTile) + * @param min Minimum value (inclusive). + * @param max Maximum value (exclusive). + * @return The random double generated. */ - public int distanceTo(final RSCharacter c) { - return c == null ? -1 : distanceTo(c.getLocation()); + @Override + public double random(final double min, final double max) { + return Math.min(min, max) + methods.random.nextDouble() * Math.abs(max - min); } /** - * Returns the diagonal distance to a given RSObject. + * Returns the height of the ground at the given location in the game world. * - * @param o The destination object. - * @return Distance to RSObject. - * @see #distanceTo(RSTile) + * @param x x value based on the game plane. + * @param y y value based on the game plane. + * @return The ground height at the given location; otherwise 0. */ - public int distanceTo(final RSObject o) { - return o == null ? -1 : distanceTo(o.getLocation()); + public int tileHeight(final int x, final int y) { + int p = methods.client.getPlane(); + final int x1 = x >> 9; + final int y1 = y >> 9; + final byte[][][] settings = methods.client.getGroundByteArray(); + if (settings != null && x1 >= 0 && x1 < 104 && y1 >= 0 && y1 < 104) { + if (p <= 3 && (settings[1][x1][y1] & 2) != 0) { + ++p; + } + final TileData[] planes = methods.client.getTileData(); + if (planes != null && p < planes.length && planes[p] != null) { + final int[][] heights = planes[p].getHeights(); + if (heights != null) { + final int x2 = x & 512 - 1; + final int y2 = y & 512 - 1; + final int start_h = heights[x1][y1] * (512 - x2) + heights[x1 + 1][y1] * x2 >> 9; + final int end_h = heights[x1][1 + y1] * (512 - x2) + heights[x1 + 1][y1 + 1] * x2 >> 9; + return start_h * (512 - y2) + end_h * y2 >> 9; + } + } + } + return 0; } /** - * Returns the diagonal distance to a given RSTile. + * Checks whether or not a given tile is on the minimap. * - * @param t The destination tile. - * @return Distance to RSTile. + * @param t The RSTile to check. + * @return true if the RSTile is on the minimap; otherwise false. + * @see #tileToMinimap(RSTile) */ - public int distanceTo(final RSTile t) { - return t == null ? -1 : (int) distanceBetween(methods.players.getMyPlayer().getLocation(), t); + public boolean tileOnMap(final RSTile t) { + return distanceTo(t) < 15; } /** - * Returns the diagonal distance (hypot) between two RSTiles. + * Checks whether or not the centroid of a given tile is on the screen. * - * @param curr The starting tile. - * @param dest The destination tile. - * @return The diagonal distance between the two RSTiles. - * @see #distanceBetween(Point, Point) + * @param t The RSTile to check. + * @return true if the RSTile is on the screen; otherwise false. */ - public double distanceBetween(final RSTile curr, final RSTile dest) { - return Math.sqrt((curr.getX() - dest.getX()) * (curr.getX() - dest.getX()) + (curr.getY() - dest.getY()) * - (curr.getY() - dest.getY())); + public boolean tileOnScreen(final RSTile t) { + return pointOnScreen(tileToScreen(t, 0.5, 0.5, 0)); } /** - * Returns the length of the path generated to a given RSTile. + * Returns the Point on screen where a given tile is shown on the minimap. * - * @param dest The destination tile. - * @param isObject true if reaching any tile adjacent to the destination should be accepted. - * @return true if reaching any tile adjacent to the destination should be accepted. + * @param t The RSTile to check. + * @return Point within minimap; otherwise new Point(-1, -1). */ - public int pathLengthTo(final RSTile dest, final boolean isObject) { - final RSTile curPos = methods.players.getMyPlayer().getLocation(); - return pathLengthBetween(curPos, dest, isObject); + public Point tileToMinimap(final RSTile t) { + return worldToMinimap(t.getX(), t.getY()); } /** - * Returns the length of the path generates between two RSTiles. + * Returns the screen location of a Tile with given 3D x, y and height + * offset values. * - * @param start The starting tile. - * @param dest The destination tile. - * @param isObject true if reaching any tile adjacent to the destination should be accepted. - * @return true if reaching any tile adjacent to the destination should be accepted. + * @param tile RSTile for which the screen location should be calculated. + * @param dX Distance from bottom left of the tile to bottom right. Ranges from 0-1; + * @param dY Distance from bottom left of the tile to top left. Ranges from 0-1; + * @param height Height offset (normal to the ground) to return the Point at. + * @return Point based on position on the game plane; otherwise new Point(-1, -1). */ - public int pathLengthBetween(final RSTile start, final RSTile dest, final boolean isObject) { - return dijkstraDist(start.getX() - methods.client.getBaseX(), // startX - start.getY() - methods.client.getBaseY(), // startY - dest.getX() - methods.client.getBaseX(), // destX - dest.getY() - methods.client.getBaseY(), // destY - isObject); // if it's an object, accept any adjacent tile + public Point tileToScreen(final RSTile tile, final double dX, final double dY, final int height) { + return groundToScreen((int) ((tile.getX() - methods.client.getBaseX() + dX) * 512), + (int) ((tile.getY() - methods.client.getBaseY() + dY) * 512), height); } /** - * checks whether or not a given RSTile is reachable. + * Returns the screen location of a Tile with a given 3D height offset. * - * @param dest The RSTile to check. - * @param isObject True if an instance of RSObject. - * @return true if player can reach specified Object; otherwise false. + * @param tile RSTile for which the screen location should be calculated. + * @param height Height offset (normal to the ground) to return the Point at. + * @return Point based on position on the game plane; if null new Point(-1, -1). + * @see #tileToScreen(RSTile, double, double, int) */ - public boolean canReach(final RSTile dest, final boolean isObject) { - return pathLengthTo(dest, isObject) != -1; + public Point tileToScreen(final RSTile tile, final int height) { + return tileToScreen(tile, 0.5, 0.5, height); + } + + /** + * Returns the screen location of the south-west corner of the given tile. + * + * @param tile RSTile for which the screen location should be calculated. + * @return Center Point of the RSTile at a height of 0; if null new Point(-1, -1). + * @see #tileToScreen(RSTile, int) + */ + public Point tileToScreen(final RSTile tile) { + return tileToScreen(tile, 0); + } + + /** + * Updates the rendering data. For internal use only. + * + * @param r The client graphics toolkit. + * @param rd The client viewport. + */ + public void updateRenderInfo(final org.rsbot.client.Render r, final org.rsbot.client.RenderData rd) { + if (r == null || rd == null) { + return; + } + render.absoluteX1 = r.getAbsoluteX1(); + render.absoluteX2 = r.getAbsoluteX2(); + render.absoluteY1 = r.getAbsoluteY1(); + render.absoluteY2 = r.getAbsoluteY2(); + render.xMultiplier = r.getXMultiplier(); + render.yMultiplier = r.getYMultiplier(); + render.zNear = r.getZNear(); + render.zFar = r.getZFar(); + renderData.xOff = rd.getXOff(); + renderData.xX = rd.getXX(); + renderData.xY = rd.getXY(); + renderData.xZ = rd.getXZ(); + renderData.yOff = rd.getYOff(); + renderData.yX = rd.getYX(); + renderData.yY = rd.getYY(); + renderData.yZ = rd.getYZ(); + renderData.zOff = rd.getZOff(); + renderData.zX = rd.getZX(); + renderData.zY = rd.getZY(); + renderData.zZ = rd.getZZ(); } /** @@ -318,15 +396,7 @@ public Point worldToMinimap(double x, double y) { final int calcCenterY = cc * calculatedY - cs * calculatedX >> 15; final int screenx = calcCenterX + mm2.getAbsoluteX() + mm2.getWidth() / 2; final int screeny = -calcCenterY + mm2.getAbsoluteY() + mm2.getHeight() / 2; - - // Check whether point is within the circle of the minimap - // rather than the rectangle. - // if ((Math.max(calcCenterY, -calcCenterY) <= mm2.getWidth() / - // 2.0 * .8) && (Math.max(calcCenterX, -calcCenterX) <= - // mm2.getHeight() / 2 * .8)) return new Point(screenx, screeny); - // else - // return new Point(-1, -1); } } catch (final NullPointerException ignored) { } @@ -334,55 +404,6 @@ public Point worldToMinimap(double x, double y) { return new Point(-1, -1); } - /** - * Returns the screen location of a given point on the ground. This accounts - * for the height of the ground at the given location. - * - * @param x x value based on the game plane. - * @param y y value based on the game plane. - * @param height height offset (normal to the ground). - * @return Point based on screen; otherwise new Point(-1, -1). - */ - public Point groundToScreen(final int x, final int y, final int height) { - if (methods.client.getGroundByteArray() == null || methods.client.getTileData() == null || x < 512 || - y < 512 || x > 52224 || y > 52224) { - return new Point(-1, -1); - } - final int z = tileHeight(x, y) + height; - return worldToScreen(x, y, z); - } - - /** - * Returns the height of the ground at the given location in the game world. - * - * @param x x value based on the game plane. - * @param y y value based on the game plane. - * @return The ground height at the given location; otherwise 0. - */ - public int tileHeight(final int x, final int y) { - int p = methods.client.getPlane(); - final int x1 = x >> 9; - final int y1 = y >> 9; - final byte[][][] settings = methods.client.getGroundByteArray(); - if (settings != null && x1 >= 0 && x1 < 104 && y1 >= 0 && y1 < 104) { - if (p <= 3 && (settings[1][x1][y1] & 2) != 0) { - ++p; - } - final TileData[] planes = methods.client.getTileData(); - if (planes != null && p < planes.length && planes[p] != null) { - final int[][] heights = planes[p].getHeights(); - if (heights != null) { - final int x2 = x & 512 - 1; - final int y2 = y & 512 - 1; - final int start_h = heights[x1][y1] * (512 - x2) + heights[x1 + 1][y1] * x2 >> 9; - final int end_h = heights[x1][1 + y1] * (512 - x2) + heights[x1 + 1][y1 + 1] * x2 >> 9; - return start_h * (512 - y2) + end_h * y2 >> 9; - } - } - } - return 0; - } - /** * Returns the screen location of a given 3D point in the game world. * @@ -415,40 +436,6 @@ public Point worldToScreen(final int x, final int y, final int z) { return new Point(-1, -1); } - // ---- Internal ---- - - /** - * Updates the rendering data. For internal use only. - * - * @param r The client graphics toolkit. - * @param rd The client viewport. - */ - public void updateRenderInfo(final org.rsbot.client.Render r, final org.rsbot.client.RenderData rd) { - if (r == null || rd == null) { - return; - } - render.absoluteX1 = r.getAbsoluteX1(); - render.absoluteX2 = r.getAbsoluteX2(); - render.absoluteY1 = r.getAbsoluteY1(); - render.absoluteY2 = r.getAbsoluteY2(); - render.xMultiplier = r.getXMultiplier(); - render.yMultiplier = r.getYMultiplier(); - render.zNear = r.getZNear(); - render.zFar = r.getZFar(); - renderData.xOff = rd.getXOff(); - renderData.xX = rd.getXX(); - renderData.xY = rd.getXY(); - renderData.xZ = rd.getXZ(); - renderData.yOff = rd.getYOff(); - renderData.yX = rd.getYX(); - renderData.yY = rd.getYY(); - renderData.yZ = rd.getYZ(); - renderData.zOff = rd.getZOff(); - renderData.zX = rd.getZX(); - renderData.zY = rd.getZY(); - renderData.zZ = rd.getZZ(); - } - /** * @param startX the startX (0 < startX < 104) * @param startY the startY (0 < startY < 104) diff --git a/src/org/rsbot/script/methods/Camera.java b/src/org/rsbot/script/methods/Camera.java index 6aec295..12e51d2 100644 --- a/src/org/rsbot/script/methods/Camera.java +++ b/src/org/rsbot/script/methods/Camera.java @@ -11,7 +11,6 @@ * Camera related operations. */ public class Camera extends MethodProvider { - Camera(final MethodContext ctx) { super(ctx); } @@ -329,5 +328,4 @@ public int getY() { public int getZ() { return methods.client.getCamPosZ(); } - } diff --git a/src/org/rsbot/script/methods/ClanChat.java b/src/org/rsbot/script/methods/ClanChat.java index cf1d832..01355c9 100644 --- a/src/org/rsbot/script/methods/ClanChat.java +++ b/src/org/rsbot/script/methods/ClanChat.java @@ -41,21 +41,8 @@ public ClanUser(String name, RSComponent rank, RSComponent world) { */ public String getOwner() { String temp = null; - if (informationOpen()) { + if (informationOpen() || (methods.game.openTab(Game.Tab.CLAN_CHAT) && openInformation())) { temp = methods.interfaces.getComponent(INTERFACE_CLAN_CHAT_INFO, INTERFACE_CLAN_CHAT_INFO_CHANNEL_OWNER).getText(); - } else { - if (methods.game.getCurrentTab() != Game.TAB_CLAN_CHAT) { - methods.game.openTab(Game.TAB_CLAN_CHAT); - } - if (methods.game.getCurrentTab() == Game.TAB_CLAN_CHAT) { - if (openInformation()) { - if (informationOpen()) { - temp = methods.interfaces.getComponent(INTERFACE_CLAN_CHAT_INFO, INTERFACE_CLAN_CHAT_INFO_CHANNEL_OWNER).getText(); - } - } - } - } - if (informationOpen()) { closeInformation(); } return temp != null ? temp.trim() : null; @@ -68,21 +55,8 @@ public String getOwner() { */ public String getChannelName() { String temp = null; - if (informationOpen()) { + if (informationOpen() || (methods.game.openTab(Game.Tab.CLAN_CHAT) && openInformation())) { temp = methods.interfaces.getComponent(INTERFACE_CLAN_CHAT_INFO, INTERFACE_CLAN_CHAT_INFO_CHANNEL_NAME).getText(); - } else { - if (methods.game.getCurrentTab() != Game.TAB_CLAN_CHAT) { - methods.game.openTab(Game.TAB_CLAN_CHAT); - } - if (methods.game.getCurrentTab() == Game.TAB_CLAN_CHAT) { - if (openInformation()) { - if (informationOpen()) { - temp = methods.interfaces.getComponent(INTERFACE_CLAN_CHAT_INFO, INTERFACE_CLAN_CHAT_INFO_CHANNEL_NAME).getText(); - } - } - } - } - if (informationOpen()) { closeInformation(); } return temp != null ? temp.trim() : null; @@ -143,10 +117,8 @@ public ClanUser getUser(String... names) { * @return true if in a channel; otherwise false */ public boolean inChannel() { - if (methods.game.getCurrentTab() != Game.TAB_CLAN_CHAT) { - methods.game.openTab(Game.TAB_CLAN_CHAT); - } - return methods.game.getCurrentTab() == Game.TAB_CLAN_CHAT && methods.interfaces.getComponent(INTERFACE_CLAN_CHAT, INTERFACE_CLAN_CHAT_CHECK).containsText("If you"); + methods.game.openTab(Game.Tab.CLAN_CHAT); + return methods.game.getTab() == Game.Tab.CLAN_CHAT && methods.interfaces.getComponent(INTERFACE_CLAN_CHAT, INTERFACE_CLAN_CHAT_CHECK).containsText("If you"); } /** @@ -155,17 +127,11 @@ public boolean inChannel() { * @return true if open/has been opened; otherwise false */ public boolean openInformation() { - if (!informationOpen()) { - if (methods.game.getCurrentTab() != Game.TAB_CLAN_CHAT) { - methods.game.openTab(Game.TAB_CLAN_CHAT); - } - if (methods.game.getCurrentTab() == Game.TAB_CLAN_CHAT) { - if (inChannel()) { - methods.interfaces.getComponent(INTERFACE_CLAN_CHAT_INFO, INTERFACE_CLAN_CHAT_INFO_BUTTON).doClick(); - } else { - return false; - } + if (!informationOpen() && methods.game.openTab(Game.Tab.CLAN_CHAT)) { + if (!inChannel()) { + return false; } + methods.interfaces.getComponent(INTERFACE_CLAN_CHAT_INFO, INTERFACE_CLAN_CHAT_INFO_BUTTON).doClick(); } return informationOpen(); } @@ -198,17 +164,11 @@ public boolean informationOpen() { * @return true if open/has been opened; otherwise false */ public boolean openSettings() { - if (!settingsOpen()) { - if (methods.game.getCurrentTab() != Game.TAB_CLAN_CHAT) { - methods.game.openTab(Game.TAB_CLAN_CHAT); - } - if (methods.game.getCurrentTab() == Game.TAB_CLAN_CHAT) { - if (inChannel()) { - methods.interfaces.getComponent(INTERFACE_CLAN_CHAT_SETTINGS, INTERFACE_CLAN_CHAT_SETTINGS_BUTTON).doClick(); - } else { - return false; - } + if (!settingsOpen() && methods.game.openTab(Game.Tab.CLAN_CHAT)) { + if (!inChannel()) { + return false; } + methods.interfaces.getComponent(INTERFACE_CLAN_CHAT_SETTINGS, INTERFACE_CLAN_CHAT_SETTINGS_BUTTON).doClick(); } return settingsOpen(); } diff --git a/src/org/rsbot/script/methods/Combat.java b/src/org/rsbot/script/methods/Combat.java index e2e67e8..d5ccd50 100644 --- a/src/org/rsbot/script/methods/Combat.java +++ b/src/org/rsbot/script/methods/Combat.java @@ -41,32 +41,6 @@ public boolean eat(final int percent, final int... foods) { return false; } - /** - * Turns auto-retaliate on or off in the combat tab. - * - * @param enable true to enable; false to disable. - */ - public void setAutoRetaliate(final boolean enable) { - final RSComponent autoRetal = methods.interfaces.getComponent(884, 15); - if (isAutoRetaliateEnabled() != enable) { - if (methods.game.getCurrentTab() != Game.TAB_ATTACK) { - methods.game.openTab(Game.TAB_ATTACK); - } - if (methods.game.getCurrentTab() == Game.TAB_ATTACK && autoRetal != null) { - autoRetal.doClick(); - } - } - } - - /** - * Returns whether or not the auto-retaliate option is enabled. - * - * @return true if retaliate is enabled; otherwise false. - */ - public boolean isAutoRetaliateEnabled() { - return methods.settings.getSetting(Settings.SETTING_AUTO_RETALIATE) == 0; - } - /** * Gets the attack mode. * @@ -77,30 +51,48 @@ public int getFightMode() { } /** - * Sets the attack mode. - * - * @param fightMode The fight mode to set it to. From 0-3 corresponding to the 4 - * attacking modes; Else if there is only 3 attacking modes then, - * from 0-2 corresponding to the 3 attacking modes - * @return true if the interface was clicked; otherwise - * false. - * @see #getFightMode() - */ - public boolean setFightMode(final int fightMode) { - if (fightMode != getFightMode()) { - methods.game.openTab(Game.TAB_ATTACK); - if (fightMode == 0) { - return methods.interfaces.getComponent(884, 11).doClick(); - } else if (fightMode == 1) { - return methods.interfaces.getComponent(884, 12).doClick(); - } else if (fightMode == 2 || fightMode == 3 && methods.interfaces.getComponent(884, 14).getActions() == null) { - return methods.interfaces.getComponent(884, 13).doClick(); - } else if (fightMode == 3) { - return methods.interfaces.getComponent(884, 14).doClick(); - } - } - return false; - } + * Gets the current player's health as a percentage of full health. + * + * @return The current percentage health remaining. + */ + public int getHealth() { + return getLifePoints() * 10 / methods.skills.getRealLevel(Skills.CONSTITUTION); + } + + /** + * Gets the current player's life points. + * + * @return The current life points if the interface is valid; otherwise 0. + */ + public int getLifePoints() { + try { + return Integer.parseInt(methods.interfaces.get(748).getComponent(8).getText()); + } catch (final NumberFormatException ex) { + return 0; + } + } + + /** + * Gets the current player's prayer points. + * + * @return The current prayer points if the interface is valid; otherwise 0. + */ + public int getPrayerPoints() { + try { + return Integer.parseInt(methods.interfaces.get(Game.INTERFACE_PRAYER_ORB).getComponent(4).getText().trim()); + } catch (final NumberFormatException ex) { + return 0; + } + } + + /** + * Gets the special bar energy amount. + * + * @return The current spec energy. + */ + public int getSpecialBarEnergy() { + return methods.settings.getSetting(300) / 10; + } /** * Gets the current Wilderness Level. Written by Speed. @@ -112,17 +104,24 @@ public int getWildernessLevel() { } /** - * Gets the current player's life points. - * - * @return The current life points if the interface is valid; otherwise 0. - */ - public int getLifePoints() { - try { - return Integer.parseInt(methods.interfaces.get(748).getComponent(8).getText()); - } catch (final NumberFormatException ex) { - return 0; - } - } + * Checks if your character is interacting with an Npc. + * + * @param npc The Npc we want to fight. + * @return true if interacting; otherwise false. + */ + public boolean isAttacking(final RSNPC npc) { + final RSCharacter interact = methods.players.getMyPlayer().getInteracting(); + return interact != null && interact.equals(npc); + } + + /** + * Returns whether or not the auto-retaliate option is enabled. + * + * @return true if retaliate is enabled; otherwise false. + */ + public boolean isAutoRetaliateEnabled() { + return methods.settings.getSetting(Settings.SETTING_AUTO_RETALIATE) == 0; + } /** * Returns whether or not we're poisoned. @@ -143,44 +142,59 @@ public boolean isSpecialEnabled() { } /** - * Gets the special bar energy amount. - * - * @return The current spec energy. - */ - public int getSpecialBarEnergy() { - return methods.settings.getSetting(300) / 10; - } + * Turns auto-retaliate on or off in the combat tab. + * + * @param enable true to enable; false to disable. + */ + public void setAutoRetaliate(final boolean enable) { + if (isAutoRetaliateEnabled() != enable && methods.game.openTab(Game.Tab.ATTACK)) { + final RSComponent autoRetal = methods.interfaces.getComponent(884, 15); + if (autoRetal != null) { + autoRetal.doClick(); + } + } + } /** - * Gets the current player's prayer points. - * - * @return The current prayer points if the interface is valid; otherwise 0. - */ - public int getPrayerPoints() { - try { - return Integer.parseInt(methods.interfaces.get(Game.INTERFACE_PRAYER_ORB).getComponent(4).getText().trim()); - } catch (final NumberFormatException ex) { - return 0; - } - } + * Sets the attack mode. + * + * @param fightMode The fight mode to set it to. From 0-3 corresponding to the 4 + * attacking modes; Else if there is only 3 attacking modes then, + * from 0-2 corresponding to the 3 attacking modes + * @return true if the interface was clicked; otherwise + * false. + * @see #getFightMode() + */ + public boolean setFightMode(final int fightMode) { + if (fightMode != getFightMode()) { + methods.game.openTab(Game.Tab.ATTACK); + if (fightMode == 0) { + return methods.interfaces.getComponent(884, 11).doClick(); + } else if (fightMode == 1) { + return methods.interfaces.getComponent(884, 12).doClick(); + } else if (fightMode == 2 || fightMode == 3 && methods.interfaces.getComponent(884, 14).getActions() == null) { + return methods.interfaces.getComponent(884, 13).doClick(); + } else if (fightMode == 3) { + return methods.interfaces.getComponent(884, 14).doClick(); + } + } + return false; + } /** - * Gets the current player's health as a percentage of full health. + * Sets the special attack option on or off. * - * @return The current percentage health remaining. + * @param enabled true enable; false to disable. + * @return true if the special bar was clicked; otherwise false. */ - public int getHealth() { - return getLifePoints() * 10 / methods.skills.getRealLevel(Skills.CONSTITUTION); - } - - /** - * Checks if your character is interacting with an Npc. - * - * @param npc The Npc we want to fight. - * @return true if interacting; otherwise false. - */ - public boolean isAttacking(final RSNPC npc) { - final RSCharacter interact = methods.players.getMyPlayer().getInteracting(); - return interact != null && interact.equals(npc); + public boolean setSpecialAttack(final boolean enabled) { + if (isSpecialEnabled() != enabled) { + methods.game.openTab(Game.Tab.ATTACK); + final RSComponent specBar = methods.interfaces.getComponent(884, 4); + if (specBar != null && isSpecialEnabled() != enabled) { + return specBar.doClick(); + } + } + return false; } } diff --git a/src/org/rsbot/script/methods/Equipment.java b/src/org/rsbot/script/methods/Equipment.java index 4e92406..0d725b8 100644 --- a/src/org/rsbot/script/methods/Equipment.java +++ b/src/org/rsbot/script/methods/Equipment.java @@ -33,12 +33,11 @@ public class Equipment extends MethodProvider { * @return the equipment interface */ public RSInterface getInterface() { - // Tab needs to be open for it to update its content -.- - if (methods.game.getCurrentTab() != Game.TAB_EQUIPMENT) { + if (methods.game.getTab() != Game.Tab.EQUIPMENT) { if (methods.bank.isOpen()) { methods.bank.close(); } - methods.game.openTab(Game.TAB_EQUIPMENT); + methods.game.openTab(Game.Tab.EQUIPMENT); sleep(random(900, 1500)); } return methods.interfaces.get(INTERFACE_EQUIPMENT); diff --git a/src/org/rsbot/script/methods/FriendChat.java b/src/org/rsbot/script/methods/FriendChat.java index 3c0cc96..ea02af6 100644 --- a/src/org/rsbot/script/methods/FriendChat.java +++ b/src/org/rsbot/script/methods/FriendChat.java @@ -135,7 +135,7 @@ public interface Friend { * @return true if successful; otherwise false */ public boolean join(final String channel) { - methods.game.openTab(Game.TAB_FRIENDS_CHAT); + methods.game.openTab(Game.Tab.FRIENDS_CHAT); if (isInChannel()) { if (getName() == channel) { return true; @@ -167,7 +167,7 @@ public boolean join(final String channel) { * @return true if successful; otherwise false */ public boolean joinLastChannel() { - methods.game.openTab(Game.TAB_FRIENDS_CHAT); + methods.game.openTab(Game.Tab.FRIENDS_CHAT); if (isInChannel()) { return true; } @@ -193,7 +193,7 @@ public boolean joinLastChannel() { * @return true if successful; otherwise false */ public boolean leave() { - methods.game.openTab(Game.TAB_FRIENDS_CHAT); + methods.game.openTab(Game.Tab.FRIENDS_CHAT); if (isInChannel()) { lastCachedChannel = getOwner(); methods.interfaces.getComponent(INTERFACE_FRIEND_CHAT, INTERFACE_FRIEND_CHAT_JOIN_BUTTON).doClick(); @@ -209,7 +209,7 @@ public boolean leave() { * @return true if in a channel; otherwise false */ public boolean isInChannel() { - methods.game.openTab(Game.TAB_FRIENDS_CHAT); + methods.game.openTab(Game.Tab.FRIENDS_CHAT); if (getName() != null) { lastCachedChannel = getName(); } @@ -285,7 +285,7 @@ public User[] getUsers() { */ public String getName() { try { - methods.game.openTab(Game.TAB_FRIENDS_CHAT); + methods.game.openTab(Game.Tab.FRIENDS_CHAT); final String name = stripFormatting(methods.interfaces.getComponent( INTERFACE_FRIEND_CHAT, INTERFACE_FRIEND_CHAT_CHANNEL_INFO).getText()); return name.substring(name.indexOf("Talking in: " + 12)); @@ -301,7 +301,7 @@ public String getName() { */ public String getOwner() { try { - methods.game.openTab(Game.TAB_FRIENDS_CHAT); + methods.game.openTab(Game.Tab.FRIENDS_CHAT); if (getName() != null) { lastCachedChannel = getName(); } @@ -524,9 +524,7 @@ public Friend[] getFriends(final String... names) { * Opens the friends list tab if not already opened. */ public void openTab() { - if (methods.game.getCurrentTab() != Game.TAB_FRIENDS) { - methods.game.openTab(Game.TAB_FRIENDS); - } + methods.game.openTab(Game.Tab.FRIENDS); } /** diff --git a/src/org/rsbot/script/methods/Game.java b/src/org/rsbot/script/methods/Game.java index 5acde69..709259f 100644 --- a/src/org/rsbot/script/methods/Game.java +++ b/src/org/rsbot/script/methods/Game.java @@ -73,11 +73,69 @@ public int textIdx() { } } + /** + * The game tabs + * + * @author kiko + */ + public enum Tab { + NONE(-1, "None", 0, -1), + ATTACK(0, "Combat Styles", KeyEvent.VK_F5, 884), + TASK(1, "Task System", 0, 1056), + STATS(2, "Stats", 0, Skills.INTERFACE_TAB_STATS), + QUESTS(3, "Quest Journals", 0, Quests.QUESTS), + INVENTORY(4, "Inventory", KeyEvent.VK_F1, Inventory.INTERFACE_INVENTORY), + EQUIPMENT(5, "Worn Equipment", KeyEvent.VK_F2, Equipment.INTERFACE_EQUIPMENT), + PRAYER(6, "Prayer List", KeyEvent.VK_F3, Prayer.INTERFACE_PRAYER), + MAGIC(7, "Magic Spellbook", KeyEvent.VK_F4, 192), + FRIENDS(9, "Friends List", 0, 550), + FRIENDS_CHAT(10, "Friends Chat", 0, FriendChat.INTERFACE_FRIEND_CHAT), + CLAN_CHAT(11, "Clan Chat", 0, ClanChat.INTERFACE_CLAN_CHAT), + OPTIONS(12, "Options", 0, 261), + EMOTES(13, "Emotes", 0, 464), + MUSIC(14, "Music Player", 0, 187), + NOTES(15, "Notes", 0, 34), + LOGOUT(16, "Exit", 0, Game.INTERFACE_LOGOUT); + + final String description; + final int functionKey; + final int index; + final int inter; + + Tab(final int index, final String description, final int functionKey, final int inter) { + this.description = description; + this.functionKey = functionKey; + this.index = index; + this.inter = inter; + } + + public String description() { + return description; + } + + public int functionKey() { + return functionKey; + } + + public boolean hasFunctionKey() { + return functionKey != 0; + } + + public int index() { + return index; + } + + public int interfaceID() { + return inter; + } + } + public static final int[] INDEX_LOGGED_IN = {10, 11}; public static final int INDEX_LOGIN_SCREEN = 3; public static final int INDEX_LOBBY_SCREEN = 7; public static final int INDEX_FIXED = 746; + @Deprecated public static final int[] TAB_FUNCTION_KEYS = { KeyEvent.VK_F5, // Attack 0, // Achievements @@ -146,12 +204,11 @@ public int textIdx() { 102, 161, 249, 243, 64, 65, 244, 255, 249, 230, 372, 421}; public static final int[] INTERFACE_OPTIONS = {230, 228}; - public static final String[] TAB_NAMES = new String[]{"Combat Styles", - "Task System", "Stats", "Quest Journals", "Inventory", - "Worn Equipment", "Prayer List", "Magic Spellbook", "", - "Friends List", "Friends Chat", "Clan Chat", "Options", - "Emotes", - "Music Player", "Notes", "Exit"}; + @Deprecated + public static final String[] TAB_NAMES = new String[]{"Combat Styles", "Task System", "Stats", + "Quest Journals", "Inventory", "Worn Equipment", "Prayer List", "Magic Spellbook", "", + "Friends List", "Friends Chat", "Clan Chat", "Options", "Emotes", "Music Player", + "Notes", "Exit"}; Game(final MethodContext ctx) { super(ctx); @@ -161,8 +218,8 @@ public int textIdx() { * Closes the currently open tab if in resizable mode. */ public void closeTab() { - final int tab = getCurrentTab(); - if (isFixed() || tab == TAB_LOGOUT) { + final Tab tab = getTab(); + if (isFixed() || tab == Tab.LOGOUT) { return; } final org.rsbot.client.RSInterface iTab = methods.gui.getTab(tab); @@ -171,6 +228,19 @@ public void closeTab() { } } + /** + * Turns accept aid off if it isn't already. + * + * @return true if the setting was clicked; otherwise false. + */ + public boolean disableAid() { + if (methods.settings.getSetting(427) == 1 && openTab(Tab.OPTIONS)) { + final RSComponent toggle = methods.interfaces.getComponent(Tab.OPTIONS.interfaceID(), 7); + return toggle != null && toggle.doClick(); + } + return false; + } + /** * Gets the x coordinate of the loaded map area (far west). * @@ -189,19 +259,6 @@ public int getBaseY() { return methods.client.getBaseY(); } - /** - * Fetch the chat button of the provided index for depreciated methods. - * For internal use only. - */ - private ChatButton getButton(final int idx) { - for (ChatButton b : ChatButton.values()) { - if (b.idx() == idx) { - return b; - } - } - return null; - } - /** * Gets the game state. * @@ -212,10 +269,10 @@ public int getClientState() { } /** - * Gets a color corresponding to x and y co ordinates from the current game screen. + * Gets a color corresponding to x and y coordinates from the current game screen. * - * @param x: The x co ordinate at which to get the color. - * @param y: The y co ordinate at which to get the color. + * @param x The x coordinate at which to get the color. + * @param y The y coordinate at which to get the color. * @return Color * @see java.awt.color */ @@ -229,31 +286,19 @@ public Color getColorAtPoint(final int x, final int y) { * * @return The currently open tab or the logout tab by default. */ + @Deprecated public int getCurrentTab() { - for (int i = 0; i < TAB_NAMES.length; i++) { - - final org.rsbot.client.RSInterface tab = methods.gui.getTab(i); - if (tab == null) { - continue; - } - - if (tab.getTextureID() != -1) { - return i; - } - } - - return -1; + return getTab().index(); } /** * Access the last message spoken by a player. * - * @return The last message spoken by a player or "" if none + * @return The last message spoken by a player or "" if none. */ public String getLastMessage() { final RSInterface chatBox = methods.interfaces.get(INTERFACE_CHAT_BOX); - for (int i = 279; i >= 180; i--) {// Valid text is from 180 to 279, was - // 58-157 + for (int i = 279; i >= 180; i--) {// Valid text is from 180 to 279, was 58-157 final String text = chatBox.getComponent(i).getText(); if (!text.isEmpty() && text.contains("<")) { return text; @@ -283,11 +328,36 @@ public int getPlane() { return methods.client.getPlane(); } + /** + * Gets a random selectable game tab (excludes Logout). + * + * @return Returns a random selectable game tab. + */ + public Tab getRandomTab() { + final Tab[] tabs = Tab.values(); + return tabs[random(0, tabs.length - 1)]; + } + + /** + * Gets the currently open tab. + * + * @return The currently open tab. + */ + public Tab getTab() { + for (Tab t : Tab.values()) { + final org.rsbot.client.RSInterface tab = methods.gui.getTab(t); + if (tab != null && tab.getTextureID() != -1) { + return t; + } + } + final RSInterface logout = methods.interfaces.get(INTERFACE_LOGOUT); + return logout != null && logout.isValid() ? Tab.LOGOUT : Tab.NONE; + } + /** * Returns the valid chat component. * - * @return RSInterfaceChild of the current valid talk interface; - * otherwise null. + * @return RSComponent of the current valid talk interface; otherwise null. * @see #INTERFACE_TALKS */ public RSComponent getTalkInterface() { @@ -319,8 +389,7 @@ public int getHeight() { } /** - * Excludes Loginbot, BankPin, TeleotherCloser, CloseAllInterface, - * ImprovedRewardsBox + * Excludes Loginbot, BankPin, TeleotherCloser, CloseAllInterface, ImprovedRewardsBox * * @return True if player is in a random */ @@ -342,12 +411,12 @@ public Boolean inRandom() { } public boolean isButtonSelected(final ChatButton button) { - return methods.interfaces.getComponent(CHAT_OPTION, button.selectIdx()).getBackgroundColor() == 1022; + return methods.interfaces.getComponent(CHAT_OPTION, button.selectIdx()) + .getBackgroundColor() == 1022; } /** - * Determines whether or not the client is currently in the fixed display - * mode. + * Determines whether or not the client is currently in the fixed display mode. * * @return true if in fixed mode; otherwise false. */ @@ -356,20 +425,17 @@ public boolean isFixed() { } /** - * Determines whether or not the client is currently logged in to an - * account. + * Determines whether or not the client is currently logged in to an account. * * @return true if logged in; otherwise false. */ public boolean isLoggedIn() { final org.rsbot.client.Client client = methods.client; - final int index = client == null ? -1 : client.getLoginIndex(); - for (final int idx : INDEX_LOGGED_IN) { - if (index == idx) { - return true; - } + if (client == null) { + return true; } - return false; + final int index = client.getLoginIndex(); + return index == 10 || index == 11; } /** @@ -387,18 +453,9 @@ public boolean isLoginScreen() { * * @return true if on the logout tab. */ + @Deprecated public boolean isOnLogoutTab() { - for (int i = 0; i < TAB_NAMES.length; i++) { - final org.rsbot.client.RSInterface tab = methods.gui.getTab(i); - if (tab == null) { - continue; - } - final int id = tab.getTextureID(); - if (id > -1 && id < 2201) { - return false; - } - } - return true; + return getTab() == Tab.LOGOUT; } /** @@ -408,8 +465,8 @@ public boolean isOnLogoutTab() { * otherwise false. */ public boolean isWelcomeScreen() { - return methods.interfaces.get(INTERFACE_WELCOME_SCREEN) - .getComponent(INTERFACE_WELCOME_SCREEN_CHILD).getAbsoluteY() > 2; + return methods.interfaces.getComponent(INTERFACE_WELCOME_SCREEN, + INTERFACE_WELCOME_SCREEN_CHILD).getAbsoluteY() > 2; } /** @@ -437,9 +494,9 @@ public boolean logout(final boolean lobby) { return false; } if (methods.client.isSpellSelected() || methods.inventory.isItemSelected()) { - final int currentTab = methods.game.getCurrentTab(); + final Tab currentTab = methods.game.getTab(); int randomTab = random(1, 6); - while (randomTab == currentTab) { + while (randomTab == currentTab.index()) { randomTab = random(1, 6); } if (methods.game.openTab(randomTab)) { @@ -449,22 +506,22 @@ public boolean logout(final boolean lobby) { if (methods.client.isSpellSelected() || methods.inventory.isItemSelected()) { return false; } - if (!isOnLogoutTab()) { + if (getTab() != Tab.LOGOUT) { final int idx = methods.client.getGUIRSInterfaceIndex(); RSComponent exitComponent = methods.interfaces.getComponent(idx, isFixed() ? 181 : 173); if (exitComponent == null || !exitComponent.doClick()) { return false; } long time = System.currentTimeMillis(); - while (!isOnLogoutTab()) { + while (getTab() != Tab.LOGOUT) { if (System.currentTimeMillis() - time > 2000) { break; } sleep(random(50, 100)); } } - RSComponent exitToComponent = methods.interfaces.getComponent(182, lobby ? 5 : 10); - if (exitToComponent.doClick()) { + RSComponent exitToComponent = methods.interfaces.getComponent(INTERFACE_LOGOUT, lobby ? 2 : 13); + if (exitToComponent != null && exitToComponent.doClick()) { sleep(random(1500, 2000)); } return !isLoggedIn(); @@ -500,80 +557,91 @@ public boolean mouseChatButton(final ChatButton button, final boolean left) { /** * Opens the specified tab at the specified index. * - * @param tab The tab to open, functionKey if wanting to use function keys - * to switch. - * @param functionKey Use a function key for fast switching? - * @return true if tab successfully selected; otherwise - * false. + * @param tab The tab to open, functionKey if wanting to use function keys to switch. + * @param functionKey Use a function key (if available) for fast switching. + * @return true if tab successfully selected; otherwise false. + * @see #openTab(Tab tab, boolean functionKey) */ + @Deprecated public boolean open(final int tab, final boolean functionKey) { - if (tab == getCurrentTab()) { - return true; - } - if (functionKey && tab < TAB_FUNCTION_KEYS.length && TAB_FUNCTION_KEYS[tab] != 0) { - methods.keyboard.pressKey((char) TAB_FUNCTION_KEYS[tab]); - sleep(random(80, 200)); - methods.keyboard.releaseKey((char) TAB_FUNCTION_KEYS[tab]); - } else { - final org.rsbot.client.RSInterface iTab = methods.gui.getTab(tab); - if (iTab == null) { - return false; - } - methods.interfaces.getComponent(iTab.getID()).doClick(); - } - for (int i = 0; i < 4; i++) { - if (tab == getCurrentTab()) { - break; - } - sleep(random(100, 150)); - } - return tab == getCurrentTab(); + return openTab(getTab(tab), functionKey); } /** * Opens the specified tab at the specified index. * * @param tab The tab to open. - * @return true if tab successfully selected; otherwise - * false. - * @see #openTab(int tab, boolean functionKey) + * @return true if tab successfully selected; otherwise false. + * @see #openTab(Tab tab, boolean functionKey) */ + @Deprecated public boolean openTab(final int tab) { + return openTab(getTab(tab)); + } + + /** + * Opens the specified game tab. + * + * @param tab The tab to open. + * @return true if tab successfully selected; otherwise false. + * @see #openTab(Tab tab, boolean functionKey) + */ + public boolean openTab(final Tab tab) { return openTab(tab, false); } /** * Opens the specified tab at the specified index. * - * @param tab The tab to open, functionKey if wanting to use function keys - * to switch. - * @return true if tab successfully selected; otherwise - * false. + * @param tab The tab to open, functionKey if wanting to use function keys to switch. + * @return true if tab successfully selected; otherwise false. + * @see #openTab(Tab tab, boolean functionKey) */ + @Deprecated public boolean openTab(final int tab, final boolean functionKey) { - // Check current tab - if (tab == getCurrentTab()) { - return true; + return openTab(getTab(tab), functionKey); + } + + /** + * Opens the specified game tab. + * + * @param tab The tab to open, functionKey if wanting to use function keys to switch. + * @return true if tab successfully selected; otherwise false. + */ + public boolean openTab(final Tab tab, final boolean functionKey) { + if (tab == Tab.NONE) { + return false; } - if (functionKey) { - if (tab >= TAB_FUNCTION_KEYS.length || TAB_FUNCTION_KEYS[tab] == 0) { - return false;// no function key for specified tab - } + if (getTab() == tab) { + return true; + } - methods.keyboard.pressKey((char) TAB_FUNCTION_KEYS[tab]); - sleep(random(80, 200)); - methods.keyboard.releaseKey((char) TAB_FUNCTION_KEYS[tab]); + if (functionKey && tab.hasFunctionKey()) { + methods.keyboard.pressKey((char) tab.functionKey()); + sleep(random(60, 200)); + methods.keyboard.releaseKey((char) tab.functionKey()); } else { final org.rsbot.client.RSInterface iTab = methods.gui.getTab(tab); - if (iTab == null) { + if (iTab == null || !methods.interfaces.getComponent(iTab.getID()).doClick()) { return false; } - methods.interfaces.getComponent(iTab.getID()).doClick(); } - sleep(random(400, 600)); - return tab == getCurrentTab(); + boolean opened = false; + for (int i = 0; i < 4; i++) { + if (!opened) { + if (getTab() == tab) { + opened = true; + i--; + continue; + } + } else if (methods.interfaces.get(tab.interfaceID()).isValid()) { + return true; + } + sleep(random(100, 200)); + } + return getTab() == tab; } /** @@ -648,4 +716,29 @@ public boolean switchWorld(final int world) { } return false; } + + /** + * Fetch the chat button at the provided index for deprecated methods. + * For internal use only. + */ + private ChatButton getButton(final int idx) { + for (ChatButton b : ChatButton.values()) { + if (b.idx() == idx) { + return b; + } + } + return null; + } + + /** + * Fetch the game tab at the provided index. For internal use only. + */ + private Tab getTab(final int idx) { + for (Tab t : Tab.values()) { + if (t.index() == idx) { + return t; + } + } + return Tab.NONE; + } } \ No newline at end of file diff --git a/src/org/rsbot/script/methods/GameGUI.java b/src/org/rsbot/script/methods/GameGUI.java index 1bc2311..3e17d28 100644 --- a/src/org/rsbot/script/methods/GameGUI.java +++ b/src/org/rsbot/script/methods/GameGUI.java @@ -1,6 +1,7 @@ package org.rsbot.script.methods; import org.rsbot.client.RSInterface; +import org.rsbot.script.methods.Game.Tab; /** * For internal use to find GUI components. @@ -8,7 +9,6 @@ * @author Qauters */ class GameGUI extends MethodProvider { - private int ind_GUI; private int ind_Minimap; private int ind_Compass; @@ -46,9 +46,7 @@ public synchronized RSInterface getCompass() { // Check if we need to find a new compass index if (ind_Compass == -1) { for (int i = 0; i < gui.length; i++) { - if (gui[i] != null && gui[i].getActions() != null - && gui[i].getActions().length == 1 - && gui[i].getActions()[0].equals("Face North")) { + if (gui[i] != null && gui[i].getActions() != null && gui[i].getActions().length == 1 && gui[i].getActions()[0].equals("Face North")) { ind_Compass = i; break; } @@ -71,8 +69,7 @@ public synchronized RSInterface getMinimapInterface() { checkGUI(); // Get the GUI interface - final RSInterface[] gui = ind_GUI != -1 ? methods.client - .getRSInterfaceCache()[ind_GUI] : null; + final RSInterface[] gui = ind_GUI != -1 ? methods.client.getRSInterfaceCache()[ind_GUI] : null; if (gui == null) { return null; } @@ -96,12 +93,11 @@ public synchronized RSInterface getMinimapInterface() { } /** - * @param id The ID of the tab. + * @param tab The tab. * @return The specified tab RSInterface; otherwise null. */ - public synchronized RSInterface getTab(final int id) { - // Check argument - if (id < 0 || id >= ind_Tabs.length) { + public synchronized RSInterface getTab(final Game.Tab tab) { + if (tab == Tab.NONE) { return null; } @@ -109,29 +105,26 @@ public synchronized RSInterface getTab(final int id) { checkGUI(); // Get GUI interface - final RSInterface[] gui = ind_GUI != -1 ? methods.client - .getRSInterfaceCache()[ind_GUI] : null; - if (gui == null) { - return null; - } - - // Check if we need to find a new tab index - if (ind_Tabs[id] == -1) { - for (int i = 0; i < gui.length; i++) { - if (gui[i] != null && gui[i].getActions() != null - && gui[i].getActions().length > 0 - && gui[i].getActions()[0].equals(Game.TAB_NAMES[id])) { - ind_Tabs[id] = i; - break; + final RSInterface[] gui = ind_GUI != -1 ? methods.client.getRSInterfaceCache()[ind_GUI] : null; + if (gui != null) { + // Check if we need to find a new tab index + if (ind_Tabs[tab.index()] == -1) { + for (int i = 0; i < gui.length; i++) { + if (gui[i] != null) { + final String[] actions = gui[i].getActions(); + if (actions != null && actions.length > 0 && actions[0].equals(tab.description())) { + ind_Tabs[tab.index()] = i; + break; + } + } } } - } - // Return the tab interface - if (ind_Tabs[id] != -1) { - return gui[ind_Tabs[id]]; + // Return the tab interface + if (ind_Tabs[tab.index()] != -1) { + return gui[ind_Tabs[tab.index()]]; + } } - return null; } @@ -148,4 +141,4 @@ private synchronized void resetIDs() { ind_Tabs[i] = -1; } } -} +} \ No newline at end of file diff --git a/src/org/rsbot/script/methods/Hiscores.java b/src/org/rsbot/script/methods/Hiscores.java index f804932..53a20f3 100644 --- a/src/org/rsbot/script/methods/Hiscores.java +++ b/src/org/rsbot/script/methods/Hiscores.java @@ -15,7 +15,6 @@ * @version 0.2 */ public class Hiscores extends MethodProvider { - private static final String HOST = "http://hiscore.runescape.com"; private static final String GET = "/index_lite.ws?player="; diff --git a/src/org/rsbot/script/methods/Interfaces.java b/src/org/rsbot/script/methods/Interfaces.java index 8e8d817..715c1e7 100644 --- a/src/org/rsbot/script/methods/Interfaces.java +++ b/src/org/rsbot/script/methods/Interfaces.java @@ -11,7 +11,6 @@ * Provides access to interfaces. */ public class Interfaces extends MethodProvider { - Interfaces(final MethodContext ctx) { super(ctx); } @@ -134,9 +133,7 @@ public RSComponent getContinueComponent() { final int len = iface.getChildCount(); for (int i = 0; i < len; i++) { final RSComponent child = iface.getComponent(i); - if (child.containsText("Click here to continue") - && child.isValid() && child.getAbsoluteX() > 10 - && child.getAbsoluteY() > 300) { + if (child.containsText("Click here to continue") && child.isValid() && child.getAbsoluteX() > 10 && child.getAbsoluteY() > 300) { return child; } } @@ -166,9 +163,7 @@ public boolean clickComponent(final RSComponent c, final String action) { final Rectangle actual = new Rectangle(minX, minY, width, height); // Check if the menu already contains the action otherwise reposition // before clicking - if (actual.contains(methods.mouse.getLocation()) - && methods.menu.contains(action) - && methods.menu.doAction(action)) { + if (actual.contains(methods.mouse.getLocation()) && methods.menu.contains(action) && methods.menu.doAction(action)) { return true; } methods.mouse.move(random(minX, minX + width), @@ -271,9 +266,7 @@ public boolean scrollTo(final RSComponent component, final RSComponent scrollBar final RSComponent scrollBarArea = scrollBar.getComponent(0); final int contentHeight = scrollableArea.getScrollableContentHeight(); - int pos = (int) ((float) scrollBarArea.getRealHeight() / contentHeight * (component - .getRelativeY() + random(-areaHeight / 2, areaHeight / 2 - - component.getRealHeight()))); + int pos = (int) ((float) scrollBarArea.getRealHeight() / contentHeight * (component.getRelativeY() + random(-areaHeight / 2, areaHeight / 2 - component.getRealHeight()))); if (pos < 0) // inner { pos = 0; @@ -282,18 +275,13 @@ public boolean scrollTo(final RSComponent component, final RSComponent scrollBar } // Click on the scrollbar - methods.mouse.click( - scrollBarArea.getAbsoluteX() - + random(0, scrollBarArea.getRealWidth()), - scrollBarArea.getAbsoluteY() + pos, true); + methods.mouse.click(scrollBarArea.getAbsoluteX() + random(0, scrollBarArea.getRealWidth()), scrollBarArea.getAbsoluteY() + pos, true); // Wait a bit sleep(random(200, 400)); // Scroll to it if we missed it - while (component.getAbsoluteY() < areaY - || component.getAbsoluteY() > areaY + areaHeight - component - .getRealHeight()) { + while (component.getAbsoluteY() < areaY || component.getAbsoluteY() > areaY + areaHeight - component.getRealHeight()) { final boolean scrollUp = component.getAbsoluteY() < areaY; scrollBar.getComponent(scrollUp ? 4 : 5).doAction(""); @@ -301,17 +289,14 @@ public boolean scrollTo(final RSComponent component, final RSComponent scrollBar } // Return whether or not the component is visible now. - return component.getAbsoluteY() >= areaY - && component.getAbsoluteY() <= areaY + areaHeight - - component.getRealHeight(); + return component.getAbsoluteY() >= areaY && component.getAbsoluteY() <= areaY + areaHeight - component.getRealHeight(); } /** * Enlarges the cache if there are more interfaces than the cache size. */ private synchronized void enlargeCache() { - final org.rsbot.client.RSInterface[][] inters = methods.client - .getRSInterfaceCache(); + final org.rsbot.client.RSInterface[][] inters = methods.client.getRSInterfaceCache(); if (inters != null && mainCache.length < inters.length) { // enlarge // cache mainCache = Arrays.copyOf(mainCache, inters.length); diff --git a/src/org/rsbot/script/methods/Inventory.java b/src/org/rsbot/script/methods/Inventory.java index 607645a..c4bf961 100644 --- a/src/org/rsbot/script/methods/Inventory.java +++ b/src/org/rsbot/script/methods/Inventory.java @@ -208,10 +208,10 @@ public boolean dropItem(final int col, final int row) { methods.interfaces.clickContinue(); sleep(random(800, 1300)); } - if (methods.game.getCurrentTab() != Game.TAB_INVENTORY + if (methods.game.getTab() != Game.Tab.INVENTORY && !methods.interfaces.get(Bank.INTERFACE_BANK).isValid() && !methods.interfaces.get(Store.INTERFACE_STORE).isValid()) { - methods.game.openTab(Game.TAB_INVENTORY); + methods.game.openTab(Game.Tab.INVENTORY); } if (col < 0 || col > 3 || row < 0 || row > 6) { return false; @@ -505,9 +505,9 @@ public RSComponent getInterface(final boolean cached) { } } - if (!cached && methods.game.getCurrentTab() != Game.TAB_INVENTORY) { - methods.game.openTab(Game.TAB_INVENTORY); - sleep(random(400, 800)); + if (!cached && methods.game.getTab() != Game.Tab.INVENTORY) { + methods.game.openTab(Game.Tab.INVENTORY); + sleep(random(200, 400)); } return methods.interfaces.getComponent(INTERFACE_INVENTORY, 0); @@ -648,7 +648,7 @@ public boolean useItem(final int itemID, final RSObject object) { * otherwise false. */ public boolean useItem(final RSItem item, final RSItem targetItem) { - methods.game.openTab(Game.TAB_INVENTORY); + methods.game.openTab(Game.Tab.INVENTORY); return selectItem(item) && targetItem.doAction("Use"); } @@ -661,7 +661,7 @@ public boolean useItem(final RSItem item, final RSItem targetItem) { * RSItem and RSObject; otherwise false. */ public boolean useItem(final RSItem item, final RSObject targetObject) { - methods.game.openTab(Game.TAB_INVENTORY); + methods.game.openTab(Game.Tab.INVENTORY); return selectItem(item) && targetObject.doAction("Use", targetObject.getName()); } } diff --git a/src/org/rsbot/script/methods/Lobby.java b/src/org/rsbot/script/methods/Lobby.java index 0c86e4b..fb77fbc 100644 --- a/src/org/rsbot/script/methods/Lobby.java +++ b/src/org/rsbot/script/methods/Lobby.java @@ -70,7 +70,7 @@ public int getCurrentTab() { return -1; } for (int i = 0; i < TABS.length; i++) { - if (methods.interfaces.getComponent(TAB_PLAYER_INFO, TABS_TEXTURE[i]).getBackgroundColor() == SELECTED_TEXTURE) { + if (methods.interfaces.getComponent(PLAYER_INFO_INTERFACE, TABS_TEXTURE[i]).getBackgroundColor() == SELECTED_TEXTURE) { return i; } } diff --git a/src/org/rsbot/script/methods/Magic.java b/src/org/rsbot/script/methods/Magic.java index b2a2db7..262880e 100644 --- a/src/org/rsbot/script/methods/Magic.java +++ b/src/org/rsbot/script/methods/Magic.java @@ -262,11 +262,7 @@ public boolean isAutoCasting() { * @return true if the spell was clicked; otherwise false. */ public boolean castSpell(final int spell) { - if (methods.game.getCurrentTab() != Game.TAB_MAGIC) { - methods.game.openTab(Game.TAB_MAGIC); - sleep(random(150, 250)); - } - if (methods.game.getCurrentTab() == Game.TAB_MAGIC) { + if (methods.game.openTab(Game.Tab.MAGIC)) { final RSInterface inter = getInterface(); if (inter != null) { final RSComponent comp = inter.getComponent(spell); @@ -285,11 +281,7 @@ public boolean castSpell(final int spell) { * @return true if the spell was clicked; otherwise false. */ public boolean hoverSpell(final int spell) { - if (methods.game.getCurrentTab() != Game.TAB_MAGIC) { - methods.game.openTab(Game.TAB_MAGIC); - sleep(random(150, 250)); - } - if (methods.game.getCurrentTab() == Game.TAB_MAGIC) { + if (methods.game.openTab(Game.Tab.MAGIC)) { final RSInterface inter = getInterface(); if (inter != null) { final RSComponent comp = inter.getComponent(spell); @@ -307,11 +299,7 @@ public boolean hoverSpell(final int spell) { * otherwise false. */ public boolean autoCastSpell(final int spell) { - if (methods.settings.getSetting(43) != 4) { - if (methods.game.getCurrentTab() != Game.TAB_MAGIC) { - methods.game.openTab(Game.TAB_MAGIC); - sleep(random(150, 250)); - } + if (methods.settings.getSetting(43) != 4 && methods.game.openTab(Game.Tab.MAGIC)) { final RSInterface inter = getInterface(); if (inter != null) { final RSComponent comp = inter.getComponent(spell); @@ -327,10 +315,7 @@ public boolean autoCastSpell(final int spell) { * @return The current magic RSInterface. */ public RSInterface getInterface() { - if (methods.game.getCurrentTab() != Game.TAB_MAGIC) { - methods.game.openTab(Game.TAB_MAGIC); - sleep(random(150, 250)); - } + methods.game.openTab(Game.Tab.MAGIC); for (Book book : Book.values()) { RSInterface inter = methods.interfaces.get(book.getInterfaceID()); if (inter.isValid()) { diff --git a/src/org/rsbot/script/methods/Menu.java b/src/org/rsbot/script/methods/Menu.java index d9ba1b5..8fcb482 100644 --- a/src/org/rsbot/script/methods/Menu.java +++ b/src/org/rsbot/script/methods/Menu.java @@ -119,11 +119,7 @@ public boolean clickIndex(final int i) { int subIdx = 0; for (MenuItemNode item = subItems.getHead(); item != null; item = subItems.getNext(), ++subIdx) { if (idx++ == i) { - if (subItems.size() == 1) { - return clickMain(items, mainIdx); - } else { - return clickSub(items, mainIdx, subIdx); - } + return subIdx == 0 ? clickMain(items, mainIdx) : clickSub(items, mainIdx, subIdx); } } } diff --git a/src/org/rsbot/script/methods/MethodContext.java b/src/org/rsbot/script/methods/MethodContext.java index bd0035c..cbfc6d4 100644 --- a/src/org/rsbot/script/methods/MethodContext.java +++ b/src/org/rsbot/script/methods/MethodContext.java @@ -11,7 +11,6 @@ * @author Jacmob */ public class MethodContext { - /** * The instance of {@link java.util.Random} for random number generation. */ @@ -215,5 +214,4 @@ public MethodContext(final Bot bot) { client = bot.getClient(); inputManager = bot.getInputManager(); } - } diff --git a/src/org/rsbot/script/methods/MethodProvider.java b/src/org/rsbot/script/methods/MethodProvider.java index 95bdcd4..a0dd050 100644 --- a/src/org/rsbot/script/methods/MethodProvider.java +++ b/src/org/rsbot/script/methods/MethodProvider.java @@ -7,7 +7,6 @@ * @author Jacmob */ public abstract class MethodProvider { - protected final MethodContext methods; public MethodProvider(final MethodContext ctx) { @@ -90,5 +89,4 @@ public void sleep(final int toSleep) { } catch (final InterruptedException ignored) { } } - } diff --git a/src/org/rsbot/script/methods/Mouse.java b/src/org/rsbot/script/methods/Mouse.java index fd8f332..f063146 100644 --- a/src/org/rsbot/script/methods/Mouse.java +++ b/src/org/rsbot/script/methods/Mouse.java @@ -8,7 +8,6 @@ * Mouse related operations. */ public class Mouse extends MethodProvider { - private int mouseSpeed = MouseHandler.DEFAULT_MOUSE_SPEED; Mouse(final MethodContext ctx) { @@ -59,14 +58,10 @@ public void moveRandomly(final int minDistance, final int maxDistance) { * maximum distance so the maximum distance will give a valid X * coordinate */ - distance -= Math.abs((maxX - Math.max(0, - Math.min(methods.game.getWidth(), maxX))) - / xvec); + distance -= Math.abs((maxX - Math.max(0, Math.min(methods.game.getWidth(), maxX))) / xvec); /* Do the same thing with the Y coordinate */ final int maxY = (int) Math.round(yvec * distance + p.y); - distance -= Math.abs((maxY - Math.max(0, - Math.min(methods.game.getHeight(), maxY))) - / yvec); + distance -= Math.abs((maxY - Math.max(0, Math.min(methods.game.getHeight(), maxY))) / yvec); /* * If the maximum distance in the generated direction is too small, * don't move the mouse at all @@ -144,8 +139,7 @@ public synchronized void click(final boolean leftClick, if (moveAfterDist > 0) { sleep(random(50, 350)); final Point pos = getLocation(); - move(pos.x - moveAfterDist, pos.y - moveAfterDist, - moveAfterDist * 2, moveAfterDist * 2); + move(pos.x - moveAfterDist, pos.y - moveAfterDist, moveAfterDist * 2, moveAfterDist * 2); } } @@ -170,8 +164,7 @@ public void click(final int x, final int y, final boolean leftClick) { * @param leftClick true to left-click, falseto right-click. * @see #move(int, int, int, int) */ - public synchronized void click(final int x, final int y, final int randX, - final int randY, final boolean leftClick) { + public synchronized void click(final int x, final int y, final int randX, final int randY, final boolean leftClick) { move(x, y, randX, randY); sleep(random(50, 350)); click(leftClick, MouseHandler.DEFAULT_MAX_MOVE_AFTER); @@ -189,8 +182,7 @@ public synchronized void click(final int x, final int y, final int randX, * @param moveAfterDist The maximum distance in pixels to move on both axes shortly * after moving to the destination. */ - public synchronized void click(final int x, final int y, final int randX, - final int randY, final boolean leftClick, final int moveAfterDist) { + public synchronized void click(final int x, final int y, final int randX, final int randY, final boolean leftClick, final int moveAfterDist) { move(x, y, randX, randY); sleep(random(50, 350)); click(leftClick, moveAfterDist); @@ -206,8 +198,7 @@ public void click(final Point p, final boolean leftClick) { click(p.x, p.y, leftClick); } - public void click(final Point p, final int x, final int y, - final boolean leftClick) { + public void click(final Point p, final int x, final int y, final boolean leftClick) { click(p.x, p.y, x, y, leftClick); } @@ -222,8 +213,7 @@ public void click(final Point p, final int x, final int y, * @param moveAfterDist The maximum distance in pixels to move on both axes shortly * after moving to the destination. */ - public void click(final Point p, final int x, final int y, - final boolean leftClick, final int moveAfterDist) { + public void click(final Point p, final int x, final int y, final boolean leftClick, final int moveAfterDist) { click(p.x, p.y, x, y, leftClick, moveAfterDist); } @@ -231,11 +221,8 @@ public void click(final Point p, final int x, final int y, * Moves the mouse slightly depending on where it currently is and clicks. */ public void clickSlightly() { - final Point p = new Point( - (int) (getLocation().getX() + (Math.random() * 50 > 25 ? 1 : -1) - * (30 + Math.random() * 90)), (int) (getLocation() - .getY() + (Math.random() * 50 > 25 ? 1 : -1) - * (30 + Math.random() * 90))); + final Point p = new Point((int) (getLocation().getX() + (Math.random() * 50 > 25 ? 1 : -1) * (30 + Math.random() * 90)), + (int) (getLocation().getY() + (Math.random() * 50 > 25 ? 1 : -1) * (30 + Math.random() * 90))); if (p.getX() < 1 || p.getY() < 1 || p.getX() > 761 || p.getY() > 499) { clickSlightly(); return; @@ -324,15 +311,13 @@ public void move(final int speed, final int x, final int y, * @param afterOffset The maximum distance in pixels to move on both axes shortly * after moving to the destination. */ - public synchronized void move(final int speed, final int x, final int y, - final int randX, final int randY, final int afterOffset) { + public synchronized void move(final int speed, final int x, final int y, final int randX, final int randY, final int afterOffset) { if (x != -1 || y != -1) { methods.inputManager.moveMouse(speed, x, y, randX, randY); if (afterOffset > 0) { sleep(random(60, 300)); final Point pos = getLocation(); - move(pos.x - afterOffset, pos.y - afterOffset, afterOffset * 2, - afterOffset * 2); + move(pos.x - afterOffset, pos.y - afterOffset, afterOffset * 2, afterOffset * 2); } } } @@ -368,8 +353,7 @@ public void move(final Point p, final int randX, final int randY) { /** * @see #move(int, int, int, int, int, int) */ - public void move(final Point p, final int randX, final int randY, - final int afterOffset) { + public void move(final Point p, final int randX, final int randY, final int afterOffset) { move(getSpeed(), p.x, p.y, randX, randY, afterOffset); } @@ -423,10 +407,8 @@ public void hop(final Point p, final int randX, final int randY) { */ public void moveSlightly() { final Point p = new Point( - (int) (getLocation().getX() + (Math.random() * 50 > 25 ? 1 : -1) - * (30 + Math.random() * 90)), (int) (getLocation() - .getY() + (Math.random() * 50 > 25 ? 1 : -1) - * (30 + Math.random() * 90))); + (int) (getLocation().getX() + (Math.random() * 50 > 25 ? 1 : -1) * (30 + Math.random() * 90)), + (int) (getLocation().getY() + (Math.random() * 50 > 25 ? 1 : -1) * (30 + Math.random() * 90))); if (p.getX() < 1 || p.getY() < 1 || p.getX() > 761 || p.getY() > 499) { moveSlightly(); return; @@ -448,9 +430,7 @@ public int getRandomX(final int maxDistance) { return p.x - random(0, p.x < maxDistance ? p.x : maxDistance); } else { final int dist = methods.game.getWidth() - p.x; - return p.x - + random(1, dist < maxDistance && dist > 0 ? dist - : maxDistance); + return p.x + random(1, dist < maxDistance && dist > 0 ? dist : maxDistance); } } @@ -468,9 +448,7 @@ public int getRandomY(final int maxDistance) { return p.y - random(0, p.y < maxDistance ? p.y : maxDistance); } else { final int dist = methods.game.getHeight() - p.y; - return p.y - + random(1, dist < maxDistance && dist > 0 ? dist - : maxDistance); + return p.y + random(1, dist < maxDistance && dist > 0 ? dist : maxDistance); } } @@ -515,5 +493,4 @@ public boolean isPressed() { final org.rsbot.client.input.Mouse mouse = methods.client.getMouse(); return mouse != null && mouse.isPressed(); } - } diff --git a/src/org/rsbot/script/methods/NPCs.java b/src/org/rsbot/script/methods/NPCs.java index edf7099..1d3702e 100644 --- a/src/org/rsbot/script/methods/NPCs.java +++ b/src/org/rsbot/script/methods/NPCs.java @@ -12,7 +12,6 @@ * Provides access to non-player characters. */ public class NPCs extends MethodProvider { - /** * A filter that accepts all matches. */ @@ -178,5 +177,4 @@ public boolean accept(final RSNPC npc) { } }); } - } \ No newline at end of file diff --git a/src/org/rsbot/script/methods/Nodes.java b/src/org/rsbot/script/methods/Nodes.java index 0b92185..9854497 100644 --- a/src/org/rsbot/script/methods/Nodes.java +++ b/src/org/rsbot/script/methods/Nodes.java @@ -9,7 +9,6 @@ * structures. */ public class Nodes extends MethodProvider { - Nodes(final MethodContext ctx) { super(ctx); } @@ -26,8 +25,7 @@ public Node lookup(final HashTable nc, final long id) { } final Node n = nc.getBuckets()[(int) (id & nc.getBuckets().length - 1)]; - for (Node node = n.getPrevious(); node != n; node = node - .getPrevious()) { + for (Node node = n.getPrevious(); node != n; node = node.getPrevious()) { if (node.getID() == id) { return node; } @@ -48,5 +46,4 @@ public Node lookup(final DefLoader loader, final long id) { } return lookup(loader.getCache().getTable(), id); } - } diff --git a/src/org/rsbot/script/methods/Objects.java b/src/org/rsbot/script/methods/Objects.java index 7b1616a..1ce453c 100644 --- a/src/org/rsbot/script/methods/Objects.java +++ b/src/org/rsbot/script/methods/Objects.java @@ -12,7 +12,6 @@ * Provides access to in-game physical objects. */ public class Objects extends MethodProvider { - public static final int TYPE_INTERACTABLE = 1; public static final int TYPE_FLOOR_DECORATION = 2; public static final int TYPE_BOUNDARY = 4; @@ -124,9 +123,7 @@ public RSObject[] getAllAt(final RSTile t) { * @return An RSObject[] of the objects on the specified tile. */ public RSObject[] getAt(final RSTile t, final int mask) { - final Set objects = getAtLocal( - t.getX() - methods.client.getBaseX(), - t.getY() - methods.client.getBaseY(), mask); + final Set objects = getAtLocal(t.getX() - methods.client.getBaseX(), t.getY() - methods.client.getBaseY(), mask); return objects.toArray(new RSObject[objects.size()]); } @@ -147,15 +144,13 @@ private Set getAtLocal(int x, int y, final int mask) { // Interactable (e.g. Trees) if ((mask & TYPE_INTERACTABLE) != 0) { - for (RSAnimableNode node = rsGround.getRSAnimableList(); node != null; node = node - .getNext()) { + for (RSAnimableNode node = rsGround.getRSAnimableList(); node != null; node = node.getNext()) { obj = node.getRSAnimable(); if (obj != null && obj instanceof org.rsbot.client.RSObject) { rsObj = (org.rsbot.client.RSObject) obj; if (rsObj.getID() != -1) { - objects.add(new RSObject(methods, rsObj, - RSObject.Type.INTERACTABLE, plane)); + objects.add(new RSObject(methods, rsObj, RSObject.Type.INTERACTABLE, plane)); } } } @@ -167,8 +162,7 @@ private Set getAtLocal(int x, int y, final int mask) { if (obj != null) { rsObj = (org.rsbot.client.RSObject) obj; if (rsObj.getID() != -1) { - objects.add(new RSObject(methods, rsObj, - RSObject.Type.FLOOR_DECORATION, plane)); + objects.add(new RSObject(methods, rsObj, RSObject.Type.FLOOR_DECORATION, plane)); } } } @@ -179,8 +173,7 @@ private Set getAtLocal(int x, int y, final int mask) { if (obj != null) { rsObj = (org.rsbot.client.RSObject) obj; if (rsObj.getID() != -1) { - objects.add(new RSObject(methods, rsObj, - RSObject.Type.BOUNDARY, plane)); + objects.add(new RSObject(methods, rsObj, RSObject.Type.BOUNDARY, plane)); } } @@ -188,8 +181,7 @@ private Set getAtLocal(int x, int y, final int mask) { if (obj != null) { rsObj = (org.rsbot.client.RSObject) obj; if (rsObj.getID() != -1) { - objects.add(new RSObject(methods, rsObj, - RSObject.Type.BOUNDARY, plane)); + objects.add(new RSObject(methods, rsObj, RSObject.Type.BOUNDARY, plane)); } } } @@ -200,8 +192,7 @@ private Set getAtLocal(int x, int y, final int mask) { if (obj != null) { rsObj = (org.rsbot.client.RSObject) obj; if (rsObj.getID() != -1) { - objects.add(new RSObject(methods, rsObj, - RSObject.Type.WALL_DECORATION, plane)); + objects.add(new RSObject(methods, rsObj, RSObject.Type.WALL_DECORATION, plane)); } } @@ -209,8 +200,7 @@ private Set getAtLocal(int x, int y, final int mask) { if (obj != null) { rsObj = (org.rsbot.client.RSObject) obj; if (rsObj.getID() != -1) { - objects.add(new RSObject(methods, rsObj, - RSObject.Type.WALL_DECORATION, plane)); + objects.add(new RSObject(methods, rsObj, RSObject.Type.WALL_DECORATION, plane)); } } } @@ -237,9 +227,7 @@ public RSObject getNearest(final Filter filter) { final Set objs = getAtLocal(x, y, -1); for (final RSObject o : objs) { if (o != null && filter.accept(o)) { - final double distTmp = methods.calc.distanceBetween( - methods.players.getMyPlayer().getLocation(), - o.getLocation()); + final double distTmp = methods.calc.distanceBetween(methods.players.getMyPlayer().getLocation(), o.getLocation()); if (cur == null) { dist = distTmp; cur = o; @@ -325,5 +313,4 @@ public RSObject getTopAt(final RSTile t, final int mask) { final RSObject[] objects = getAt(t, mask); return objects.length > 0 ? objects[0] : null; } - } diff --git a/src/org/rsbot/script/methods/Players.java b/src/org/rsbot/script/methods/Players.java index 738086e..7615769 100644 --- a/src/org/rsbot/script/methods/Players.java +++ b/src/org/rsbot/script/methods/Players.java @@ -10,7 +10,6 @@ * Player related operations. */ public class Players extends MethodProvider { - /** * A filter that accepts all matches. */ @@ -127,5 +126,4 @@ public boolean accept(final RSPlayer player) { } }); } - } diff --git a/src/org/rsbot/script/methods/Prayer.java b/src/org/rsbot/script/methods/Prayer.java index 1cb4e6b..a1b70cb 100644 --- a/src/org/rsbot/script/methods/Prayer.java +++ b/src/org/rsbot/script/methods/Prayer.java @@ -261,10 +261,8 @@ public boolean setPrayer(Book pray, boolean active) { if (methods.skills.getRealLevel(Skills.PRAYER) < pray.getRequiredLevel()) { return false; } - if (methods.game.getCurrentTab() != Game.TAB_PRAYER) { - methods.game.openTab(Game.TAB_PRAYER); - } - if (methods.game.getCurrentTab() == Game.TAB_PRAYER) { + methods.game.openTab(Game.Tab.PRAYER); + if (methods.game.getTab() == Game.Tab.PRAYER) { RSComponent component = methods.interfaces.getComponent(PRAYER_INTERFACE, 7) .getComponent(pray.getComponentIndex()); if (component.isValid()) { diff --git a/src/org/rsbot/script/methods/Quests.java b/src/org/rsbot/script/methods/Quests.java index b416143..0a2835d 100644 --- a/src/org/rsbot/script/methods/Quests.java +++ b/src/org/rsbot/script/methods/Quests.java @@ -140,9 +140,7 @@ public RSComponent[] getComponents() { * Selects the quests tab if not already selected. */ public void openTab() { - if (methods.game.getCurrentTab() != Game.TAB_QUESTS) { - methods.game.openTab(Game.TAB_QUESTS); - } + methods.game.openTab(Game.Tab.QUESTS); } } diff --git a/src/org/rsbot/script/methods/Settings.java b/src/org/rsbot/script/methods/Settings.java index 4aceca6..ea7674b 100644 --- a/src/org/rsbot/script/methods/Settings.java +++ b/src/org/rsbot/script/methods/Settings.java @@ -56,5 +56,4 @@ public int getSetting(final int setting) { } return -1; } - } diff --git a/src/org/rsbot/script/methods/Skills.java b/src/org/rsbot/script/methods/Skills.java index 40ed4d6..239465f 100644 --- a/src/org/rsbot/script/methods/Skills.java +++ b/src/org/rsbot/script/methods/Skills.java @@ -479,10 +479,9 @@ public int ammountTillMaxLevel(final int index, final double exp) { * index. */ public boolean doHover(final int component) { - methods.game.openTab(Game.TAB_STATS); + methods.game.openTab(Game.Tab.STATS); sleep(random(10, 100)); - return methods.interfaces.getComponent(INTERFACE_TAB_STATS, component) - .doHover(); + return methods.interfaces.getComponent(INTERFACE_TAB_STATS, component) .doHover(); } /** @@ -490,7 +489,6 @@ public boolean doHover(final int component) { * * @param index The index of the skill. * @return true if one the given skills is boosted. - * @author Dunnkers */ public boolean isSkillBoosted(final int... index) { if (!isSkill(index)) { diff --git a/src/org/rsbot/script/methods/Store.java b/src/org/rsbot/script/methods/Store.java index 455beb4..9f299d5 100644 --- a/src/org/rsbot/script/methods/Store.java +++ b/src/org/rsbot/script/methods/Store.java @@ -10,7 +10,6 @@ * Store related operations. */ public class Store extends MethodProvider { - public static final int INTERFACE_STORE = 620; public static final int INTERFACE_STORE_BUTTON_CLOSE = 18; public static final int INTERFACE_STORE_ITEMS = 25; @@ -88,9 +87,7 @@ public boolean close() { if (!isOpen()) { return true; } - - if (methods.interfaces.getComponent(INTERFACE_STORE, - INTERFACE_STORE_BUTTON_CLOSE).doClick()) { + if (methods.interfaces.getComponent(INTERFACE_STORE,INTERFACE_STORE_BUTTON_CLOSE).doClick()) { sleep(random(500, 600)); return !isOpen(); } else { @@ -154,17 +151,14 @@ public RSItem getItem(final int id) { * in the stores RSInterface. */ public RSItem[] getItems() { - if (getInterface() == null - || getInterface().getComponent(INTERFACE_STORE_ITEMS) == null) { + if (getInterface() == null || getInterface().getComponent(INTERFACE_STORE_ITEMS) == null) { return null; } final ArrayList items = new ArrayList(); - final RSComponent[] components = getInterface().getComponent( - INTERFACE_STORE_ITEMS).getComponents(); + final RSComponent[] components = getInterface().getComponent(INTERFACE_STORE_ITEMS).getComponents(); for (final RSComponent component : components) { - if (component != null && component.getComponentID() != -1) { items.add(new RSItem(methods, component)); } diff --git a/src/org/rsbot/script/methods/Tiles.java b/src/org/rsbot/script/methods/Tiles.java index ccc0800..70a2d3c 100644 --- a/src/org/rsbot/script/methods/Tiles.java +++ b/src/org/rsbot/script/methods/Tiles.java @@ -8,7 +8,6 @@ * Tile related operations. */ public class Tiles extends MethodProvider { - Tiles(final MethodContext ctx) { super(ctx); } @@ -137,5 +136,4 @@ public RSTile getTileUnderPoint(final Point p) { public boolean isCloser(final RSTile t, final RSTile tt) { return methods.calc.distanceTo(t) < methods.calc.distanceTo(tt); } - } diff --git a/src/org/rsbot/script/methods/Trade.java b/src/org/rsbot/script/methods/Trade.java index 7ad3e25..4028404 100644 --- a/src/org/rsbot/script/methods/Trade.java +++ b/src/org/rsbot/script/methods/Trade.java @@ -1,8 +1,12 @@ package org.rsbot.script.methods; +import org.rsbot.script.wrappers.RSComponent; import org.rsbot.script.wrappers.RSInterface; +import org.rsbot.script.wrappers.RSItem; import org.rsbot.script.wrappers.RSPlayer; +import java.util.ArrayList; +import java.util.List; import java.util.logging.Logger; /** @@ -11,7 +15,6 @@ * @author Timer * @author kyleshay */ -@SuppressWarnings("unused") public class Trade extends MethodProvider { private static final Logger log = Logger.getLogger(Trade.class.getName()); @@ -131,8 +134,7 @@ public boolean tradePlayer(final RSPlayer targetPlayer) { */ public boolean acceptTrade() { if (inTradeMain()) { - return methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_ACCEPT).doAction( - "Accept"); + return methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_ACCEPT).doAction("Accept"); } else { return inTradeSecond() && methods.interfaces.get(INTERFACE_TRADE_SECOND).getComponent(INTERFACE_TRADE_SECOND_ACCEPT).doAction("Accept"); } @@ -145,8 +147,7 @@ public boolean acceptTrade() { */ public boolean declineTrade() { if (inTradeMain()) { - return methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_DECLINE).doAction( - "Decline"); + return methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_DECLINE).doAction("Decline"); } else { return inTradeSecond() && methods.interfaces.get(INTERFACE_TRADE_SECOND).getComponent(INTERFACE_TRADE_SECOND_DECLINE).doAction("Decline"); } @@ -189,7 +190,7 @@ public boolean waitForTrade(final int tradeType, final long timeOut) { * * @return The person's name you're trading with. */ - private String getTradingWith() { + public String getTradingWith() { if (inTradeMain()) { final String name = methods.interfaces.getComponent(INTERFACE_TRADE_MAIN, INTERFACE_TRADE_MAIN_NAME).getText(); return name.substring(name.indexOf(": ") + 2); @@ -205,7 +206,7 @@ private String getTradingWith() { * @param name The person's name. * @return true if true; otherwise false. */ - private boolean isTradingWith(final String name) { + public boolean isTradingWith(final String name) { return getTradingWith().equals(name); } @@ -214,26 +215,40 @@ private boolean isTradingWith(final String name) { * * @return The number of items offered. */ - private int getNumberOfItemsOffered() { + public int getNumberOfItemsOffered() { int number = 0; for (int i = 0; i < 28; i++) { - if (methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent( - INTERFACE_TRADE_MAIN_OUR).getComponent(i).getComponentStackSize() != 0) { + if (methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_THEIR).getComponent(i).getComponentStackSize() != 0) { ++number; } } return number; } + /** + * Returns the items offered by another player + * + * @return The items offered. + */ + public RSItem[] getItemsOffered() { + List items = new ArrayList(); + for (int i = 0; i < 28; i++) { + RSComponent component = methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_THEIR).getComponent(i); + if (component != null && component.getComponentStackSize() != 0) { + items.add(new RSItem(methods, component)); + } + } + return items.toArray(new RSItem[items.size()]); + } + /** * Returns the total number of free slots the other player has * * @return The number of free slots. */ - private int getFreeSlots() { + public int getFreeSlots() { if (inTradeMain()) { - String text = methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent( - INTERFACE_TRADE_MAIN_INV_SLOTS).getText().substring(4, 6); + String text = methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_INV_SLOTS).getText().substring(4, 6); text = text.trim(); try { return Integer.parseInt(text); @@ -242,5 +257,4 @@ private int getFreeSlots() { } return 0; } - } diff --git a/src/org/rsbot/script/methods/Walking.java b/src/org/rsbot/script/methods/Walking.java index b19d105..56ed0b3 100644 --- a/src/org/rsbot/script/methods/Walking.java +++ b/src/org/rsbot/script/methods/Walking.java @@ -11,7 +11,6 @@ * Walking related operations. */ public class Walking extends MethodProvider { - public final int INTERFACE_RUN_ORB = 750; Walking(final MethodContext ctx) { @@ -274,9 +273,7 @@ public RSTile getDestination() { if (methods.client.getDestX() <= 0) { return null; } - return new RSTile( - methods.client.getDestX() + methods.client.getBaseX(), - methods.client.getDestY() + methods.client.getBaseY()); + return new RSTile(methods.client.getDestX() + methods.client.getBaseX(), methods.client.getDestY() + methods.client.getBaseY()); } /** @@ -297,8 +294,7 @@ public int[][] getCollisionFlags(final int plane) { * @return The offset as an RSTile. */ public RSTile getCollisionOffset(final int plane) { - final org.rsbot.client.RSGroundData data = methods.client - .getRSGroundDataArray()[plane]; + final org.rsbot.client.RSGroundData data = methods.client .getRSGroundDataArray()[plane]; return new RSTile(data.getX(), data.getY()); } } diff --git a/src/org/rsbot/script/methods/Web.java b/src/org/rsbot/script/methods/Web.java index 5f3d93b..1479051 100644 --- a/src/org/rsbot/script/methods/Web.java +++ b/src/org/rsbot/script/methods/Web.java @@ -16,7 +16,7 @@ * @author Timer */ public class Web extends MethodProvider { - public static final HashMap rs_map = new HashMap(); + public static final HashMap rs_map = new HashMap(); public static boolean loaded = false; Web(final MethodContext ctx) { @@ -133,11 +133,7 @@ private Route[] generateRoutes(final RSTile start, final RSTile end, final Route if (traverse.destPlane() == end.getZ()) {//TODO more complex method--prevent infinite loops once made. final Route route = planeRoute(start, end, traverse); route.parent = lastRoute; - if (route != null) { - return generateRoutes(traverse.dest(), end, route); - } else { - return null;//Routing failed from here. How did this happen, oh wait, we need the more complex plane check method + distancing. - } + return generateRoutes(traverse.dest(), end, route); } } return null;//No applicable plane transfers. @@ -302,44 +298,44 @@ private static List Successors(final Node t) { final int x = t.x, y = t.y; final RSTile here = t.toRSTile(); if (!Flag(here, TileData.Key.W_S) && - !Flag(new RSTile(here.getX(), here.getY() - 1), TileData.Key.BLOCKED | TileData.Key.WATER)) { - tiles.add(new Node(x, y - 1, t.toRSTile().getZ())); + !Flag(here.getX(), here.getY() - 1, here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER)) { + tiles.add(new Node(x, y - 1, here.getZ())); } if (!Flag(here, TileData.Key.W_W) && - !Flag(new RSTile(here.getX() - 1, here.getY()), TileData.Key.BLOCKED | TileData.Key.WATER)) { - tiles.add(new Node(x - 1, y, t.toRSTile().getZ())); + !Flag(here.getX() - 1, here.getY(), here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER)) { + tiles.add(new Node(x - 1, y, here.getZ())); } if (!Flag(here, TileData.Key.W_N) && - !Flag(new RSTile(here.getX(), here.getY() + 1), TileData.Key.BLOCKED | TileData.Key.WATER)) { - tiles.add(new Node(x, y + 1, t.toRSTile().getZ())); + !Flag(here.getX(), here.getY() + 1, here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER)) { + tiles.add(new Node(x, y + 1, here.getZ())); } if (!Flag(here, TileData.Key.W_E) && - !Flag(new RSTile(here.getX() + 1, here.getY()), TileData.Key.BLOCKED | TileData.Key.WATER)) { - tiles.add(new Node(x + 1, y, t.toRSTile().getZ())); + !Flag(here.getX() + 1, here.getY(), here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER)) { + tiles.add(new Node(x + 1, y, here.getZ())); } if (!Flag(here, TileData.Key.W_SW | TileData.Key.W_S | TileData.Key.W_W) && - !Flag(new RSTile(here.getX() - 1, here.getY() - 1), TileData.Key.BLOCKED | TileData.Key.WATER) && - !Flag(new RSTile(here.getX(), here.getY() - 1), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_W) && - !Flag(new RSTile(here.getX() - 1, here.getY()), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_S)) { - tiles.add(new Node(x - 1, y - 1, t.toRSTile().getZ())); + !Flag(here.getX() - 1, here.getY() - 1, here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER) && + !Flag(here.getX(), here.getY() - 1, here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_W) && + !Flag(here.getX() - 1, here.getY(), here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_S)) { + tiles.add(new Node(x - 1, y - 1, here.getZ())); } if (!Flag(here, TileData.Key.W_NW | TileData.Key.W_N | TileData.Key.W_W) && - !Flag(new RSTile(here.getX() - 1, here.getY() + 1), TileData.Key.BLOCKED | TileData.Key.WATER) && - !Flag(new RSTile(here.getX(), here.getY() + 1), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_W) && - !Flag(new RSTile(here.getX() - 1, here.getY()), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_N)) { - tiles.add(new Node(x - 1, y + 1, t.toRSTile().getZ())); + !Flag(here.getX() - 1, here.getY() + 1, here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER) && + !Flag(here.getX(), here.getY() + 1, here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_W) && + !Flag(here.getX() - 1, here.getY(), here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_N)) { + tiles.add(new Node(x - 1, y + 1, here.getZ())); } if (!Flag(here, TileData.Key.W_SE | TileData.Key.W_S | TileData.Key.W_E) && - !Flag(new RSTile(here.getX() + 1, here.getY() - 1), TileData.Key.BLOCKED | TileData.Key.WATER) && - !Flag(new RSTile(here.getX(), here.getY() - 1), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_E) && - !Flag(new RSTile(here.getX() + 1, here.getY()), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_S)) { - tiles.add(new Node(x + 1, y - 1, t.toRSTile().getZ())); + !Flag(here.getX() + 1, here.getY() - 1, here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER) && + !Flag(here.getX(), here.getY() - 1, here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_E) && + !Flag(here.getX() + 1, here.getY(), here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_S)) { + tiles.add(new Node(x + 1, y - 1, here.getZ())); } if (!Flag(here, TileData.Key.W_NE | TileData.Key.W_N | TileData.Key.W_E) && - !Flag(new RSTile(here.getX() + 1, here.getY() + 1), TileData.Key.BLOCKED | TileData.Key.WATER) && - !Flag(new RSTile(here.getX(), here.getY() + 1), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_E) && - !Flag(new RSTile(here.getX() + 1, here.getY()), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_N)) { - tiles.add(new Node(x + 1, y + 1, t.toRSTile().getZ())); + !Flag(here.getX() + 1, here.getY() + 1, here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER) && + !Flag(here.getX(), here.getY() + 1, here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_E) && + !Flag(here.getX() + 1, here.getY(), here.getZ(), TileData.Key.BLOCKED | TileData.Key.WATER | TileData.Key.W_N)) { + tiles.add(new Node(x + 1, y + 1, here.getZ())); } return tiles; } @@ -362,8 +358,60 @@ public static int GetTileFlag(final RSTile tile) { * @return true if the tile contains flags. */ public static boolean Flag(final RSTile tile, final int key) { - if (Web.rs_map.containsKey(tile)) { - final int theTile = Web.rs_map.get(tile); + final Short[] tileData = {(short) tile.getX(), (short) tile.getY(), (short) tile.getZ()}; + if (Web.rs_map.containsKey(tileData)) { + final int theTile = Web.rs_map.get(tileData); + return (theTile & key) != 0; + } + return false; + } + + /** + * Checks the flags of a tile. + * + * @param tileData The tile to check. + * @param key Keys to look for. + * @return true if the tile contains flags. + */ + public static boolean Flag(final Short[] tileData, final int key) { + if (Web.rs_map.containsKey(tileData)) { + final int theTile = Web.rs_map.get(tileData); + return (theTile & key) != 0; + } + return false; + } + + /** + * Checks the flags of a tile. + * + * @param x The tile to check (x). + * @param y The tile to check (y). + * @param z The tile to check (z). + * @param key Keys to look for. + * @return true if the tile contains flags. + */ + public static boolean Flag(final short x, final short y, final short z, final int key) { + final Short[] tileData = {x, y, z}; + if (Web.rs_map.containsKey(tileData)) { + final int theTile = Web.rs_map.get(tileData); + return (theTile & key) != 0; + } + return false; + } + + /** + * Checks the flags of a tile. + * + * @param x The tile to check (x). + * @param y The tile to check (y). + * @param z The tile to check (z). + * @param key Keys to look for. + * @return true if the tile contains flags. + */ + public static boolean Flag(final int x, final int y, final int z, final int key) { + final Short[] tileData = {(short) x, (short) y, (short) z}; + if (Web.rs_map.containsKey(tileData)) { + final int theTile = Web.rs_map.get(tileData); return (theTile & key) != 0; } return false; diff --git a/src/org/rsbot/script/provider/FileScriptSource.java b/src/org/rsbot/script/provider/FileScriptSource.java index fb1579e..da09ac6 100644 --- a/src/org/rsbot/script/provider/FileScriptSource.java +++ b/src/org/rsbot/script/provider/FileScriptSource.java @@ -19,9 +19,7 @@ * @author Paris */ public class FileScriptSource implements ScriptSource { - - private final Logger log = Logger.getLogger(getClass().getSimpleName()); - + private static final Logger log = Logger.getLogger(FileScriptSource.class.getName()); private final File[] files; public FileScriptSource(final File... file) { @@ -48,13 +46,9 @@ private void list(final File file, final LinkedList defs) { if (file != null) { if (file.isDirectory()) { try { - final ClassLoader ldr = new ScriptClassLoader(file.toURI().toURL()); - for (final File f : file.listFiles()) { - if (isJar(f)) { - load(new ScriptClassLoader(getJarUrl(f)), defs, new JarFile(f)); - } else { - load(ldr, defs, f, ""); - } + final ClassLoader loader = new ScriptClassLoader(file.toURI().toURL()); + for (final File item : file.listFiles()) { + load(item, defs, loader); } } catch (final IOException ignored) { } @@ -66,33 +60,50 @@ private void list(final File file, final LinkedList defs) { } } } + for (final ScriptDefinition def : defs) { + def.source = this; + } } public Script load(final ScriptDefinition def) throws ServiceException { if (!(def instanceof FileScriptDefinition)) { throw new IllegalArgumentException("Invalid definition!"); } - final FileScriptDefinition fsd = (FileScriptDefinition) def; try { - return fsd.clazz.asSubclass(Script.class).newInstance(); + return load((FileScriptDefinition) def); } catch (final Exception ex) { throw new ServiceException(ex.toString()); } } - private void load(final ClassLoader loader, final LinkedList scripts, final JarFile jar) { + public static Script load(final FileScriptDefinition def) throws InstantiationException, IllegalAccessException { + return def.clazz.asSubclass(Script.class).newInstance(); + } + + public static void load(final File file, final LinkedList defs, ClassLoader loader) throws IOException { + if (isJar(file)) { + load(new ScriptClassLoader(getJarUrl(file)), defs, new JarFile(file)); + } else { + if (loader == null) { + loader = new ScriptClassLoader(file.getParentFile().toURI().toURL()); + } + load(loader, defs, file, ""); + } + } + + private static void load(final ClassLoader loader, final LinkedList scripts, final JarFile jar) { final Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { final JarEntry e = entries.nextElement(); final String name = e.getName().replace('/', '.'); final String ext = ".class"; if (name.endsWith(ext) && !name.contains("$")) { - load(loader, scripts, name.substring(0, name.length() - ext.length()), null); + load(loader, scripts, name.substring(0, name.length() - ext.length()), jar.getName()); } } } - private void load(final ClassLoader loader, final LinkedList scripts, final File file, final String prefix) { + private static void load(final ClassLoader loader, final LinkedList scripts, final File file, final String prefix) { if (file.isDirectory()) { if (!file.getName().startsWith(".")) { for (final File f : file.listFiles()) { @@ -109,7 +120,7 @@ private void load(final ClassLoader loader, final LinkedList s } } - private void load(final ClassLoader loader, final LinkedList scripts, final String name, final String path) { + private static void load(final ClassLoader loader, final LinkedList scripts, final String name, final String path) { Class clazz; try { clazz = loader.loadClass(name); @@ -132,7 +143,6 @@ private void load(final ClassLoader loader, final LinkedList s def.description = manifest.description(); def.website = manifest.website(); def.clazz = clazz; - def.source = this; def.path = path; if (manifest.requiresVersion() <= Configuration.getVersion()) { scripts.add(def); @@ -140,17 +150,17 @@ private void load(final ClassLoader loader, final LinkedList s } } - private boolean isJar(final File file) { + public static boolean isJar(final File file) { return file.getName().endsWith(".jar") || file.getName().endsWith(".dat"); } - private URL getJarUrl(final File file) throws IOException { + public static URL getJarUrl(final File file) throws IOException { URL url = file.toURI().toURL(); url = new URL("jar:" + url.toExternalForm() + "!/"); return url; } - private static class FileScriptDefinition extends ScriptDefinition { + public static class FileScriptDefinition extends ScriptDefinition { Class clazz; } diff --git a/src/org/rsbot/script/provider/ScriptDefinition.java b/src/org/rsbot/script/provider/ScriptDefinition.java index e785e1b..5e82416 100644 --- a/src/org/rsbot/script/provider/ScriptDefinition.java +++ b/src/org/rsbot/script/provider/ScriptDefinition.java @@ -1,10 +1,31 @@ package org.rsbot.script.provider; +import org.rsbot.util.StringUtil; + /** - * @author Jacmob + * @author Paris */ -public class ScriptDefinition { +public class ScriptDefinition implements Comparable { + + public String getName() { + return StringUtil.stripHtml(name); + } + + public String getDescription() { + return StringUtil.stripHtml(description); + } + + public String getAuthors() { + final StringBuilder s = new StringBuilder(16); + for (int i = 0; i < authors.length; i++) { + if (i > 0) { + s.append(i == authors.length - 1 ? " and " : ", "); + } + s.append(authors[i]); + } + return StringUtil.stripHtml(s.toString()); + } public int id; @@ -24,4 +45,19 @@ public class ScriptDefinition { public String path; + public int compareTo(final ScriptDefinition def) { + final int c = getName().compareToIgnoreCase(def.getName()); + return c == 0 ? Double.compare(version, def.version) : c; + } + + @Override + public String toString() { + final StringBuilder s = new StringBuilder(46); + s.append(getName()); + s.append(" v"); + s.append(version); + s.append(" by "); + s.append(getAuthors()); + return s.toString(); + } } diff --git a/src/org/rsbot/script/provider/ScriptDeliveryNetwork.java b/src/org/rsbot/script/provider/ScriptDeliveryNetwork.java index e238003..18d2bd6 100644 --- a/src/org/rsbot/script/provider/ScriptDeliveryNetwork.java +++ b/src/org/rsbot/script/provider/ScriptDeliveryNetwork.java @@ -1,51 +1,33 @@ package org.rsbot.script.provider; -import org.rsbot.Configuration; -import org.rsbot.util.io.HttpClient; -import org.rsbot.util.io.IniParser; - -import java.io.BufferedReader; import java.io.File; -import java.io.FileReader; import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; import java.util.Map.Entry; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.logging.Logger; +import org.rsbot.Configuration; +import org.rsbot.script.Script; +import org.rsbot.script.provider.FileScriptSource.FileScriptDefinition; +import org.rsbot.service.ServiceException; +import org.rsbot.util.io.HttpClient; +import org.rsbot.util.io.IniParser; + /** * @author Paris */ -public class ScriptDeliveryNetwork extends FileScriptSource { +public class ScriptDeliveryNetwork implements ScriptSource { private static final Logger log = Logger.getLogger("ScriptDelivery"); private static ScriptDeliveryNetwork instance; - private String key; - private final String defaultKey = "0000000000000000000000000000000000000000"; - private final int version = 1; - private URL base = null; - private boolean forceUpdate = false; + private URL base; + final File manifest; private ScriptDeliveryNetwork() { - super(new File(Configuration.Paths.getScriptsNetworkDirectory())); - key = defaultKey; - } - - public void start() { - if (load()) { - try { - init(); - } catch (final Exception e) { - e.printStackTrace(); - log.severe("Could not download scripts from the network!"); - } - } + manifest = getFile("manifests"); } public static ScriptDeliveryNetwork getInstance() { @@ -55,192 +37,98 @@ public static ScriptDeliveryNetwork getInstance() { return instance; } - public void forceUpdate() { - forceUpdate = true; - try { - init(); - } catch (final IOException ignored) { - } + private static File getFile(final String name) { + return new File(Configuration.Paths.getCacheDirectory(), "sdn-" + name + ".txt"); } - private boolean load() { - HashMap keys = null; - boolean enabled = true; - String error = "could not load control file"; - - try { - final URL source = new URL(Configuration.Paths.URLs.SDN_CONTROL); - final File cache = getChachedFile("control.txt"); - HttpClient.download(source, cache); - final BufferedReader reader = new BufferedReader(new FileReader(cache)); - keys = IniParser.deserialise(reader).get(IniParser.emptySection); - reader.close(); - } catch (final Exception e) { - enabled = false; + private static void parseManifests(final HashMap> entries, final List defs) { + for (final Entry> entry : entries.entrySet()) { + final ScriptDefinition def = new ScriptDefinition(); + def.path = entry.getKey(); + final HashMap values = entry.getValue(); + def.id = Integer.parseInt(values.get("id")); + def.name = values.get("name"); + def.version = Double.parseDouble(values.get("version")); + def.description = values.get("description"); + def.authors = values.get("authors").split(ScriptList.DELIMITER); + def.keywords = values.get("keywords").split(ScriptList.DELIMITER); + def.website = values.get("website"); + defs.add(def); } + } - if (keys == null || keys.isEmpty() || keys.containsKey("enabled") && !IniParser.parseBool(keys.get("enabled"))) { - enabled = false; - } else { - if (keys.containsKey("error")) { - error = keys.get("error"); - } - if (keys.containsKey("version")) { - final int remoteVersion = Integer.parseInt(keys.get("version")); - if (version != remoteVersion) { - enabled = false; - error = "please update your version of the bot"; - } - } - if (keys.containsKey("url")) { - try { - base = new URL(keys.get("url").replace("%key", getKey())); - } catch (final MalformedURLException e) { + public void refresh(final boolean force) { + final File controlFile = getFile("control"); + if (force || !manifest.exists()) { + try { + HttpClient.download(new URL(Configuration.Paths.URLs.SDN_CONTROL), controlFile); + final HashMap control = IniParser.deserialise(controlFile).get(IniParser.emptySection); + if (control == null || !IniParser.parseBool(control.get("enabled")) || !control.containsKey("manifest")) { + throw new ServiceException("Service currently disabled"); } + base = HttpClient.download(new URL(control.get("manifest")), manifest).getURL(); + } catch (final ServiceException e) { + log.severe(e.getMessage()); + } catch (final IOException ignored) { + log.warning("Unable to load scripts from the network"); } } + } - if (base == null) { - enabled = false; + @Override + public List list() { + final ArrayList defs = new ArrayList(); + refresh(false); + try { + parseManifests(IniParser.deserialise(manifest), defs); + } catch (final IOException ignored) { + log.warning("Error reading network script manifests"); } - - if (!enabled) { - log.warning("Service disabled: " + error); + for (final ScriptDefinition def : defs) { + def.source = this; } - - return enabled; + return defs; } - private void init() throws IOException { - final File cache = new File(Configuration.Paths.getScriptsNetworkDirectory()); - - if (!cache.exists()) { - cache.mkdirs(); + private static File getCacheDirectory() { + final File store = new File(Configuration.Paths.getScriptsNetworkDirectory()); + if (!store.exists()) { + store.mkdirs(); } - if (Configuration.getCurrentOperatingSystem() == Configuration.OperatingSystem.WINDOWS) { - final String path = "\"" + cache.getAbsolutePath() + "\""; + final String path = "\"" + store.getAbsolutePath() + "\""; try { Runtime.getRuntime().exec("attrib +H " + path); - } catch (final IOException e) { - } - } - - BufferedReader br, br1; - String line, line1; - final HashMap scripts = new HashMap(64); - - final File manifest = getChachedFile("manifest.txt"); - final HttpURLConnection con = HttpClient.download(base, manifest); - base = con.getURL(); - br = new BufferedReader(new FileReader(manifest)); - - while ((line = br.readLine()) != null) { - final URL packUrl = new URL(base, line); - long mod = 0; - final File pack = getChachedFile("pack-" + getFileName(packUrl)); - if (pack.exists()) { - mod = pack.lastModified(); - } - final HttpURLConnection packCon = HttpClient.download(packUrl, pack); - if (pack.lastModified() == mod && !forceUpdate) { - continue; + } catch (final IOException ignored) { } - br1 = new BufferedReader(new FileReader(pack)); - while ((line1 = br1.readLine()) != null) { - final URL scriptUrl = new URL(packCon.getURL(), line1); - scripts.put(getFileName(scriptUrl), scriptUrl); - } - br1.close(); } - - br.close(); - - if (!scripts.isEmpty()) { - sync(scripts); - } - - forceUpdate = false; + return store; } - private void sync(final HashMap scripts) { - int n = 0; - for (final String name : scripts.keySet()) { - if (!name.contains("$")) { - n++; - } - } - if (n > 0) { - log.info("Loading " + Integer.toString(n) + " scripts from the network"); - } - - int created = 0, deleted = 0, updated = 0; - final File dir = new File(Configuration.Paths.getScriptsNetworkDirectory()); - final ArrayList delete = new ArrayList(64); - - for (final File f : dir.listFiles()) { - if (f.getName().endsWith(".class")) { - delete.add(f); - } - } - - final ArrayList>> tasks = new ArrayList>>(); - - for (final Entry key : scripts.entrySet()) { - final File path = new File(dir, key.getKey()); - if (!path.getName().contains("$")) { - if (delete.contains(path)) { - updated++; - } else { - created++; + @Override + public Script load(ScriptDefinition def) throws ServiceException { + final File store = getCacheDirectory(); + final File file = new File(store, def.path); + final LinkedList defs = new LinkedList(); + if (file.exists()) { + try { + FileScriptSource.load(file, defs, null); + if (defs.size() != 1 || defs.getFirst().version < def.version) { + file.delete(); } + } catch (final IOException ignored) { } - delete.remove(path); - tasks.add(new Callable>() { - public Collection call() throws Exception { - log.fine("Downloading: " + path.getName()); - HttpClient.download(key.getValue(), path); - return null; - } - - ; - }); } - - int threads = Runtime.getRuntime().availableProcessors(); - final ExecutorService executorService = Executors.newFixedThreadPool(threads); try { - executorService.invokeAll(tasks); - } catch (final InterruptedException e) { - e.printStackTrace(); - } - - for (final File f : delete) { - if (!f.delete()) { - f.deleteOnExit(); - } - if (!f.getName().contains("$")) { - deleted++; + if (!file.exists()) { + log.info("Downloading script " + def.name + "..."); + HttpClient.download(new URL(base, def.path), file); } + FileScriptSource.load(file, defs, null); + return FileScriptSource.load((FileScriptDefinition) defs.getFirst()); + } catch (final Exception ignored) { + log.severe("Unable to load script"); } - - log.fine(String.format("Downloaded %1$d new scripts, updated %2$d and deleted %3$d", created, deleted, updated)); - } - - private String getFileName(final URL url) { - final String path = url.getPath(); - return path.substring(path.lastIndexOf('/') + 1); - } - - private File getChachedFile(final String name) { - return new File(Configuration.Paths.getCacheDirectory(), "sdn-" + name); - } - - public String getKey() { - return key; - } - - public void setKey(final String key) { - this.key = key; + return null; } } diff --git a/src/org/rsbot/script/provider/ScriptDownloader.java b/src/org/rsbot/script/provider/ScriptDownloader.java index f6b05d9..eb3ca5a 100644 --- a/src/org/rsbot/script/provider/ScriptDownloader.java +++ b/src/org/rsbot/script/provider/ScriptDownloader.java @@ -1,6 +1,7 @@ package org.rsbot.script.provider; import org.rsbot.Configuration; +import org.rsbot.util.StringUtil; import org.rsbot.util.io.HttpClient; import org.rsbot.util.io.IOHelper; import org.rsbot.util.io.JavaCompiler; @@ -73,7 +74,7 @@ public static void save(String sourceURL) { source = source.substring(z); } source = source.replaceAll("\\", "\r\n"); - source = source.replaceAll("\\<.*?\\>", ""); + source = StringUtil.stripHtml(source); source = source.replaceAll(" ", " "); source = source.replaceAll(""", "\""); source = source.replaceAll("<", "<"); diff --git a/src/org/rsbot/script/randoms/FirstTimeDeath.java b/src/org/rsbot/script/randoms/FirstTimeDeath.java index b76eed2..5ef08f1 100644 --- a/src/org/rsbot/script/randoms/FirstTimeDeath.java +++ b/src/org/rsbot/script/randoms/FirstTimeDeath.java @@ -14,8 +14,7 @@ public class FirstTimeDeath extends Random { @Override public boolean activateCondition() { - return (reaper = npcs.getNearest(8869)) != null - || (reaper = npcs.getNearest(8870)) != null; + return (reaper = npcs.getNearest(8869)) != null || (reaper = npcs.getNearest(8870)) != null; } @Override @@ -73,5 +72,4 @@ public void onFinish() { exit = false; reaper = null; } - } diff --git a/src/org/rsbot/script/randoms/FreakyForester.java b/src/org/rsbot/script/randoms/FreakyForester.java index 28adfdd..1617087 100644 --- a/src/org/rsbot/script/randoms/FreakyForester.java +++ b/src/org/rsbot/script/randoms/FreakyForester.java @@ -14,7 +14,6 @@ */ @ScriptManifest(authors = {"Pwnaz0r", "Taha", "zqqou", "Zach"}, name = "FreakyForester", version = 2.6) public class FreakyForester extends Random implements MessageListener { - private RSNPC forester; private static final int FORESTER_ID = 2458; private static final int SEARCH_INTERFACE_ID = 242; @@ -203,8 +202,8 @@ public int loop() { } */ if (unequip && inventory.getCount(false) != 28) { - if (game.getCurrentTab() != Game.TAB_EQUIPMENT) { - game.openTab(Game.TAB_EQUIPMENT); + if (game.getTab() != Game.Tab.EQUIPMENT) { + game.openTab(Game.Tab.EQUIPMENT); sleep(random(1000, 1500)); interfaces.get(Equipment.INTERFACE_EQUIPMENT).getComponent(17).doClick(); return random(1000, 1500); @@ -325,7 +324,5 @@ public void messageReceived(final MessageEvent e) { if (serverString.contains("no ammo left")) { unequip = true; } - } - } \ No newline at end of file diff --git a/src/org/rsbot/script/randoms/FrogCave.java b/src/org/rsbot/script/randoms/FrogCave.java index 3f163ee..8630cbf 100644 --- a/src/org/rsbot/script/randoms/FrogCave.java +++ b/src/org/rsbot/script/randoms/FrogCave.java @@ -11,7 +11,6 @@ */ @ScriptManifest(authors = {"Nightmares18", "joku.rules", "Taha", "Fred"}, name = "FrogCave", version = 2.3) public class FrogCave extends Random { - private RSNPC frog; private boolean talkedToHerald, talkedToFrog; private int tries; @@ -20,18 +19,15 @@ public class FrogCave extends Random { public boolean activateCondition() { if (!game.isLoggedIn()) { return false; - } else if (npcs.getNearest("Frog Herald") != null - && objects.getNearest(5917) != null) { + } else if (npcs.getNearest("Frog Herald") != null && objects.getNearest(5917) != null) { sleep(random(2000, 3000)); - return npcs.getNearest("Frog Herald") != null - && objects.getNearest(5917) != null; + return npcs.getNearest("Frog Herald") != null && objects.getNearest(5917) != null; } return false; } private RSNPC findFrog() { return npcs.getNearest(new Filter() { - @Override public boolean accept(final RSNPC npc) { return !npc.isMoving() && npc.getHeight() == -278; } @@ -39,8 +35,7 @@ public boolean accept(final RSNPC npc) { } private boolean canContinue() { - return interfaces.canContinue() - || interfaces.getComponent(65, 6).isValid(); + return interfaces.canContinue() || interfaces.getComponent(65, 6).isValid(); } @Override @@ -59,11 +54,8 @@ public int loop() { if (canContinue()) { // log("can continue..."); if (!talkedToHerald) { - final RSComponent heraldTalkComp = interfaces.getComponent( - 242, 4); - talkedToHerald = heraldTalkComp.isValid() - && (heraldTalkComp.containsText("crown") || heraldTalkComp - .containsText("is still waiting")); + final RSComponent heraldTalkComp = interfaces.getComponent(242, 4); + talkedToHerald = heraldTalkComp.isValid() && (heraldTalkComp.containsText("crown") || heraldTalkComp.containsText("is still waiting")); } if (!interfaces.clickContinue()) { interfaces.getComponent(65, 6).doClick(); @@ -92,8 +84,7 @@ public int loop() { log("Princess found! ID: " + frog.getID()); } } - if (frog != null && frog.getLocation() != null - && (!talkedToFrog || !canContinue())) { + if (frog != null && frog.getLocation() != null && (!talkedToFrog || !canContinue())) { if (calc.distanceTo(frog) < 5) { if (!calc.tileOnScreen(frog.getLocation())) { camera.turnTo(frog); diff --git a/src/org/rsbot/script/randoms/LoginBot.java b/src/org/rsbot/script/randoms/LoginBot.java index 921031c..a2cb1e4 100644 --- a/src/org/rsbot/script/randoms/LoginBot.java +++ b/src/org/rsbot/script/randoms/LoginBot.java @@ -10,25 +10,27 @@ import java.awt.event.KeyEvent; /** - * @author Iscream, Aut0r, Doout, Pervy + * @author Iscream + * @author Pervy + * @author Timer */ -@ScriptManifest(authors = {"Iscream", "Pervy Shuya", "Aut0r"}, name = "Login", version = 2.1) +@ScriptManifest(authors = {"Iscream", "Pervy Shuya", "Timer"}, name = "Login", version = 2.1) public class LoginBot extends Random { - private static final int INTERFACE_MAIN = 905; private static final int INTERFACE_MAIN_CHILD = 59; private static final int INTERFACE_MAIN_CHILD_COMPONENT_ID = 4; private static final int INTERFACE_LOGIN_SCREEN = 596; - private static final int INTERFACE_USERNAME = 65; - private static final int INTERFACE_USERNAME_WINDOW = 37; - private static final int INTERFACE_PASSWORD = 71; - private static final int INTERFACE_PASSWORD_WINDOW = 39; - private static final int INTERFACE_BUTTON_LOGIN = 42; - private static final int INTERFACE_TEXT_RETURN = 11; - private static final int INTERFACE_BUTTON_BACK = 60; + private static final int INTERFACE_USERNAME = 73; + private static final int INTERFACE_USERNAME_WINDOW = 40; + private static final int INTERFACE_PASSWORD = 79; + private static final int INTERFACE_PASSWORD_WINDOW = 42; + private static final int INTERFACE_BUTTON_LOGIN = 45; + private static final int INTERFACE_TEXT_RETURN = 14; + private static final int INTERFACE_BUTTON_BACK = 68; private static final int INTERFACE_WELCOME_SCREEN = 906; private static final int INTERFACE_WELCOME_SCREEN_BUTTON_PLAY_1 = 160; private static final int INTERFACE_WELCOME_SCREEN_BUTTON_PLAY_2 = 171; + private static final int INTERFACE_WELCOME_SCREEN_BUTTON_TEXT = 173; //private static final int INTERFACE_WELCOME_SCREEN_BUTTON_LOGOUT = 193; private static final int INTERFACE_WELCOME_SCREEN_TEXT_RETURN = 221; private static final int INTERFACE_WELCOME_SCREEN_BUTTON_BACK = 218; @@ -41,7 +43,6 @@ public class LoginBot extends Random { private static final int INDEX_LOGGED_OUT = 3; private static final int INDEX_LOBBY = 7; private int invalidCount, worldFullCount; - public Random Rand; @Override public boolean activateCondition() { @@ -66,19 +67,22 @@ public int loop() { } final RSInterface welcome_screen = interfaces.get(INTERFACE_WELCOME_SCREEN); - final RSComponent welcome_screen_button_play_1 = welcome_screen.getComponent(INTERFACE_WELCOME_SCREEN_BUTTON_PLAY_1); - final RSComponent welcome_screen_button_play_2 = welcome_screen.getComponent(INTERFACE_WELCOME_SCREEN_BUTTON_PLAY_2); + if (welcome_screen.getComponent(INTERFACE_WELCOME_SCREEN_BUTTON_TEXT).getText().equals("Play")) { + final RSComponent welcome_screen_button_play_1 = welcome_screen.getComponent(INTERFACE_WELCOME_SCREEN_BUTTON_PLAY_1); + final RSComponent welcome_screen_button_play_2 = welcome_screen.getComponent(INTERFACE_WELCOME_SCREEN_BUTTON_PLAY_2); - mouse.click(welcome_screen_button_play_1.getAbsoluteX(), - welcome_screen_button_play_1.getAbsoluteY(), - welcome_screen_button_play_2.getAbsoluteX() - + welcome_screen_button_play_2.getWidth() - - welcome_screen_button_play_1.getAbsoluteX(), - welcome_screen_button_play_1.getHeight(), true); + mouse.click(welcome_screen_button_play_1.getAbsoluteX(), + welcome_screen_button_play_1.getAbsoluteY(), + welcome_screen_button_play_2.getAbsoluteX() + + welcome_screen_button_play_2.getWidth() + - welcome_screen_button_play_1.getAbsoluteX(), + welcome_screen_button_play_1.getHeight(), true); - for (int i = 0; i < 4 && game.getClientState() == 6; i++) { - sleep(500); + for (int i = 0; i < 4 && game.getClientState() == 6; i++) { + sleep(500); + } } + returnText = interfaces.get(INTERFACE_WELCOME_SCREEN).getComponent(INTERFACE_WELCOME_SCREEN_TEXT_RETURN).getText().toLowerCase(); if (returnText.contains("total skill level of") diff --git a/src/org/rsbot/script/randoms/TeleotherCloser.java b/src/org/rsbot/script/randoms/TeleotherCloser.java index 10130d5..5ea9502 100644 --- a/src/org/rsbot/script/randoms/TeleotherCloser.java +++ b/src/org/rsbot/script/randoms/TeleotherCloser.java @@ -2,7 +2,6 @@ import org.rsbot.script.Random; import org.rsbot.script.ScriptManifest; -import org.rsbot.script.methods.Game; import org.rsbot.script.wrappers.RSInterface; @ScriptManifest(authors = {"ToshiXZ"}, name = "TeleotherCloser", version = 1.0) @@ -18,10 +17,8 @@ public boolean activateCondition() { public int loop() { interfaces.get(326).getComponent(8).doClick(); sleep(random(500, 750)); - game.openTab(Game.TAB_OPTIONS); - sleep(random(500, 750)); log.info("Disabling accept aid"); - mouse.click(random(569, 603), random(415, 440), false); + game.disableAid(); return -1; } } diff --git a/src/org/rsbot/script/util/BankCache.java b/src/org/rsbot/script/util/BankCache.java index 9ec9589..4be7f27 100644 --- a/src/org/rsbot/script/util/BankCache.java +++ b/src/org/rsbot/script/util/BankCache.java @@ -74,11 +74,8 @@ public static void Load() throws Exception { return; } } - final FileReader fr = new FileReader(cacheFile); - final BufferedReader br = new BufferedReader(fr); data.clear(); - data.putAll(IniParser.deserialise(br)); - br.close(); + data.putAll(IniParser.deserialise(cacheFile)); } } diff --git a/src/org/rsbot/script/util/SkillData.java b/src/org/rsbot/script/util/SkillData.java index bc43a5b..c57ed69 100644 --- a/src/org/rsbot/script/util/SkillData.java +++ b/src/org/rsbot/script/util/SkillData.java @@ -4,6 +4,11 @@ import org.rsbot.script.methods.MethodProvider; import org.rsbot.script.methods.Skills; +/** + * Skill data tracker + * + * @author Timer + */ public class SkillData extends MethodProvider { private int[] startExp = new int[25], startLvl = new int[25]; private Timer runTimer = null; diff --git a/src/org/rsbot/script/web/methods/TeleportItem.java b/src/org/rsbot/script/web/methods/TeleportItem.java index f22e94e..1197c2d 100644 --- a/src/org/rsbot/script/web/methods/TeleportItem.java +++ b/src/org/rsbot/script/web/methods/TeleportItem.java @@ -60,20 +60,14 @@ public boolean perform() { } } } - if (item != null) { - if (methods.game.getCurrentTab() != (equip ? Game.TAB_EQUIPMENT : Game.TAB_INVENTORY)) { - methods.game.openTab(equip ? Game.TAB_EQUIPMENT : Game.TAB_INVENTORY); - sleep(500); - } - if (item != null) { - for (String act : action) { - if (item.doAction(act)) { - final long tO = System.currentTimeMillis(); - while (System.currentTimeMillis() - tO < 10000) { - sleep(100); - if (methods.calc.distanceBetween(methods.players.getMyPlayer().getLocation(), teleportationLocation()) < 15) { - break; - } + if (item != null && methods.game.openTab(equip ? Game.Tab.EQUIPMENT : Game.Tab.INVENTORY)) { + for (String act : action) { + if (item.doAction(act)) { + final long tO = System.currentTimeMillis(); + while (System.currentTimeMillis() - tO < 10000) { + sleep(100); + if (methods.calc.distanceBetween(methods.players.getMyPlayer().getLocation(), teleportationLocation()) < 15) { + break; } } } diff --git a/src/org/rsbot/script/web/methods/TeleportJewelry.java b/src/org/rsbot/script/web/methods/TeleportJewelry.java index 0d5a3f2..407e468 100644 --- a/src/org/rsbot/script/web/methods/TeleportJewelry.java +++ b/src/org/rsbot/script/web/methods/TeleportJewelry.java @@ -7,6 +7,12 @@ import org.rsbot.script.wrappers.RSItem; import org.rsbot.script.wrappers.RSTile; +/** + * The class that handles all teleportation actions via jewelry transportation. + * + * @author Timer + * @author kyleshay + */ public class TeleportJewelry extends TeleportItem { public TeleportJewelry(MethodContext ctx, RSTile teleportationLocation, String[] action, int[] itemIDs) { super(ctx, teleportationLocation, action, itemIDs); @@ -16,6 +22,10 @@ public TeleportJewelry(MethodContext ctx, RSTile teleportationLocation, String a super(ctx, teleportationLocation, action, itemIDs); } + public boolean meetsPrerequisites() { + return !deepWilderness() /* && !teleportBlocked()*/; + } + /** * Performs the usage on the jewelery. * @@ -35,11 +45,7 @@ public boolean perform() { } } } - if (item != null) { - if (methods.game.getCurrentTab() != (equip ? Game.TAB_EQUIPMENT : Game.TAB_INVENTORY)) { - methods.game.openTab(equip ? Game.TAB_EQUIPMENT : Game.TAB_INVENTORY); - sleep(500); - } + if (item != null && methods.game.openTab(equip ? Game.Tab.EQUIPMENT : Game.Tab.INVENTORY)) { for (String s : action) { if (item.doAction(s)) { final long tO = System.currentTimeMillis(); @@ -98,4 +104,18 @@ private RSComponent getDialogOption(String... opts) { } return null; } + + /** + * Jewelry restriction for wilderness is > 30 instead of 20. + * confirmed for: + * Amulet of glory + * Combat bracelet + * Skills necklace + * Pharaoh's sceptre + * Grand seed pod + * Ring of Life + */ + private boolean deepWilderness() { + return methods.combat.getWildernessLevel() > 30; + } } diff --git a/src/org/rsbot/script/web/methods/TeleportRunes.java b/src/org/rsbot/script/web/methods/TeleportRunes.java index 01729a1..4726ff8 100644 --- a/src/org/rsbot/script/web/methods/TeleportRunes.java +++ b/src/org/rsbot/script/web/methods/TeleportRunes.java @@ -70,11 +70,7 @@ public boolean isApplicable(RSTile base, RSTile destination) { } public boolean perform() { - if (hasRunes()) { - if (methods.game.getCurrentTab() != Game.TAB_MAGIC) { - methods.game.openTab(Game.TAB_MAGIC); - sleep(500); - } + if (hasRunes() && methods.game.openTab(Game.Tab.MAGIC)) { if (methods.magic.castSpell(spell)) { final long t = System.currentTimeMillis(); while (System.currentTimeMillis() - t < 10000) { diff --git a/src/org/rsbot/script/wrappers/RSCharacter.java b/src/org/rsbot/script/wrappers/RSCharacter.java index 8f9bd41..1f0ae67 100644 --- a/src/org/rsbot/script/wrappers/RSCharacter.java +++ b/src/org/rsbot/script/wrappers/RSCharacter.java @@ -78,7 +78,7 @@ public int getHeight() { } /** - * @return The % of HP + * @return The % of HP remaining */ public int getHPPercent() { return isInCombat() ? getAccessor().getHPRatio() * 100 / 255 : 100; diff --git a/src/org/rsbot/script/wrappers/RSObject.java b/src/org/rsbot/script/wrappers/RSObject.java index 51ec7be..7e711fb 100644 --- a/src/org/rsbot/script/wrappers/RSObject.java +++ b/src/org/rsbot/script/wrappers/RSObject.java @@ -214,6 +214,20 @@ public boolean isOnScreen() { } } + /** + * Determines whether the object is reachable by the player. + * + * @return true if a path can be made to the specified object; + * otherwise false. + */ + public boolean isReachable() { + for (RSTile t : getArea().getTileArray()) { + if (methods.calc.canReach(t, true)) + return true; + } + return false; + } + @Override public boolean equals(final Object o) { return o instanceof RSObject && ((RSObject) o).obj == obj; diff --git a/src/org/rsbot/security/RestrictedSecurityManager.java b/src/org/rsbot/security/RestrictedSecurityManager.java index 4f91a6e..0104067 100644 --- a/src/org/rsbot/security/RestrictedSecurityManager.java +++ b/src/org/rsbot/security/RestrictedSecurityManager.java @@ -22,11 +22,14 @@ import java.net.InetAddress; import java.security.Permission; import java.util.ArrayList; +import java.util.logging.Logger; /** * @author Paris */ public class RestrictedSecurityManager extends SecurityManager { + private static Logger log = Logger.getLogger("Security"); + private String getCallingClass() { final String prefix = Application.class.getPackage().getName() + "."; for (final Class c : getClassContext()) { @@ -56,7 +59,6 @@ public ArrayList getAllowedHosts() { whitelist.add(".ipcounter.de"); whitelist.add("shadowscripting.org"); // iDungeon - whitelist.add("xelr.byethost5.com"); // Xel's stuffs whitelist.add("shadowscripting.wordpress.com"); // iDungeon whitelist.add(".glorb.nl"); // SXForce - Swamp Lizzy Paid, Snake Killah whitelist.add("scripts.johnkeech.com"); // MrSneaky - SneakyFarmerPro @@ -101,6 +103,7 @@ public void checkConnect(final String host, final int port) { // ports other than HTTP (80), HTTPS (443) and unknown (-1) are automatically denied if (!(port == -1 || port == 80 || port == 443)) { + log.warning("Connection denied on port: " + port); throw new SecurityException(); } @@ -125,6 +128,7 @@ public void checkConnect(final String host, final int port) { } if (!allowed) { + log.warning("Connection denied: " + host); throw new SecurityException(); } } @@ -298,8 +302,6 @@ public void checkWrite(final FileDescriptor fd) { @Override public void checkWrite(final String file) { - if (file.contains("hosts")) - System.out.println(getCallingClass()); checkFilePath(file, false); super.checkWrite(file); } @@ -351,6 +353,7 @@ private void checkFilePath(String path, final boolean readOnly) { } } if (fail) { + log.warning((readOnly ? "Read" : "Write") + " access denied: " + path); throw new SecurityException(); } } diff --git a/src/org/rsbot/service/Monitoring.java b/src/org/rsbot/service/Monitoring.java index 1c1eb06..ad4675c 100644 --- a/src/org/rsbot/service/Monitoring.java +++ b/src/org/rsbot/service/Monitoring.java @@ -40,10 +40,8 @@ private static void init() { final URL source = new URL(Configuration.Paths.URLs.MONITORING_CONTROL); final File cache = new File(Configuration.Paths.getCacheDirectory(), "monitoring-control.txt"); HttpClient.download(source, cache); - final BufferedReader reader = new BufferedReader(new FileReader(cache)); - keys = IniParser.deserialise(reader).get(IniParser.emptySection); - reader.close(); - } catch (final Exception e) { + keys = IniParser.deserialise(cache).get(IniParser.emptySection); + } catch (final IOException ignored) { return; } @@ -142,7 +140,7 @@ private static void uploadUdp(final URI uri, final byte[] data) throws IOExcepti } private static void uploadHttp(final URL url, final String data) throws IOException { - final HttpURLConnection con = Configuration.getHttpConnection(url); + final HttpURLConnection con = HttpClient.getHttpConnection(url); con.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(data); diff --git a/src/org/rsbot/service/WebQueue.java b/src/org/rsbot/service/WebQueue.java index baa0e46..12703bd 100644 --- a/src/org/rsbot/service/WebQueue.java +++ b/src/org/rsbot/service/WebQueue.java @@ -33,34 +33,36 @@ public class WebQueue { * * @param gameTiles The data. */ - public static void Add(final HashMap gameTiles) { + public static void Add(final HashMap gameTiles) { Web.rs_map.putAll(gameTiles); final int count = gameTiles.size(); new Thread() { @Override public void run() { try { - final HashMap mapData = new HashMap(); + final HashMap mapData = new HashMap(); mapData.putAll(gameTiles); - final Map safeMapData = Collections.unmodifiableMap(mapData); + final Map safeMapData = Collections.unmodifiableMap(mapData); bufferingCount = bufferingCount + count; - final Iterator> safeIterator = safeMapData.entrySet().iterator(); + final Iterator> safeIterator = safeMapData.entrySet().iterator(); while (safeIterator.hasNext()) { - final Map.Entry tileData = safeIterator.next(); - final RSTile tile = tileData.getKey(); - final int key = tileData.getValue(); - if (tileData != null) { - synchronized (queueLock) { - queue.add(tile.getX() + "," + tile.getY() + "," + tile.getZ() + "k" + key); - } - synchronized (bufferLock) { - bufferingCount--; - try { - weAreBuffering = true; - if (!speedBuffer) { - Thread.sleep(1); + final Map.Entry tileData = safeIterator.next(); + if (tileData.getKey().length == 3) { + final Short[] tile = tileData.getKey(); + final int key = tileData.getValue(); + if (tileData != null) { + synchronized (queueLock) { + queue.add(tile[0] + "," + tile[1] + "," + tile[2] + "k" + key); + } + synchronized (bufferLock) { + bufferingCount--; + try { + weAreBuffering = true; + if (!speedBuffer) { + Thread.sleep(1); + } + } catch (final InterruptedException ignored) { } - } catch (final InterruptedException ignored) { } } } diff --git a/src/org/rsbot/util/StringUtil.java b/src/org/rsbot/util/StringUtil.java index 5b465df..1ac3759 100644 --- a/src/org/rsbot/util/StringUtil.java +++ b/src/org/rsbot/util/StringUtil.java @@ -17,6 +17,10 @@ public class StringUtil { private static final String[] COLOURS_STR = new String[]{"red", "green", "cyan", "purple", "white"}; private static final Map COLOR_MAP = new HashMap(); + public static String stripHtml(final String s) { + return s.replaceAll("\\<.*?\\>", ""); + } + public static String join(final String[] s) { final int l = s.length; switch (l) { diff --git a/src/org/rsbot/util/UpdateChecker.java b/src/org/rsbot/util/UpdateChecker.java index 6d5917b..bbc52cf 100644 --- a/src/org/rsbot/util/UpdateChecker.java +++ b/src/org/rsbot/util/UpdateChecker.java @@ -13,7 +13,6 @@ import java.util.logging.Logger; /** - * @author Xel * @author Paris */ public final class UpdateChecker { @@ -33,7 +32,7 @@ public static void notify(final BotGUI instance) { return; } log.info("New version available"); - final int update = JOptionPane.showConfirmDialog(instance, "RSCBot is outdated, would you like to update?", "Update Found", JOptionPane.YES_NO_OPTION); + final int update = JOptionPane.showConfirmDialog(instance, "A newer version is available. Do you wish to update?", "Update Found", JOptionPane.YES_NO_OPTION); if (update != 0) { return; } @@ -58,7 +57,7 @@ public static int getLatestVersion() { if (latest != -1 || error) { return latest; } - final File cache = new File(Configuration.Paths.getCacheDirectory(), "0.23.txt"); + final File cache = new File(Configuration.Paths.getCacheDirectory(), "version-latest.txt"); BufferedReader reader = null; try { HttpClient.download(new URL(Configuration.Paths.URLs.VERSION), cache); @@ -83,7 +82,7 @@ public static int getLatestVersion() { private static void update(final BotGUI instance) throws IOException { log.info("Downloading update..."); - final File jarNew = new File(Configuration.NAME + "-" + "0.23" + ".jar"); + final File jarNew = new File(Configuration.NAME + "-" + getLatestVersion() + ".jar"); HttpClient.download(new URL(Configuration.Paths.URLs.DOWNLOAD), jarNew); final String jarOld = Configuration.Paths.getRunningJarPath(); Runtime.getRuntime().exec("java -jar \"" + jarNew + "\" --delete \"" + jarOld + "\""); diff --git a/src/org/rsbot/util/io/HttpClient.java b/src/org/rsbot/util/io/HttpClient.java index a9b9195..d03d2f2 100644 --- a/src/org/rsbot/util/io/HttpClient.java +++ b/src/org/rsbot/util/io/HttpClient.java @@ -14,10 +14,58 @@ */ public class HttpClient { private static final Logger log = Logger.getLogger(HttpClient.class.getName()); + static String httpUserAgent = null; + + public static String getHttpUserAgent() { + if (httpUserAgent == null) { + httpUserAgent = getDefaultHttpUserAgent(); + } + return httpUserAgent; + } + + private static String getDefaultHttpUserAgent() { + final boolean x64 = System.getProperty("sun.arch.data.model").equals("64"); + final String os; + switch (Configuration.getCurrentOperatingSystem()) { + case MAC: + os = "Macintosh; Intel Mac OS X 10_6_6"; + break; + case LINUX: + os = "X11; Linux " + (x64 ? "x86_64" : "i686"); + break; + default: + os = "Windows NT 6.1" + (x64 ? "; WOW64" : ""); + break; + } + final StringBuilder buf = new StringBuilder(125); + buf.append("Mozilla/5.0 (").append(os).append(")"); + buf.append(" AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.68 Safari/534.24"); + return buf.toString(); + } + + public static HttpURLConnection getHttpConnection(final URL url) throws IOException { + final HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); + con.addRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); + con.addRequestProperty("Accept-Encoding", "gzip,deflate"); + con.addRequestProperty("Accept-Language", "en-us,en;q=0.5"); + con.addRequestProperty("Host", url.getHost()); + con.addRequestProperty("User-Agent", getHttpUserAgent()); + con.setConnectTimeout(10000); + return con; + } + + private static HttpURLConnection getConnection(final URL url) throws IOException { + final HttpURLConnection con = getHttpConnection(url); + con.setUseCaches(true); + return con; + } public static HttpURLConnection download(final URL url, final File file) throws IOException { - final HttpURLConnection con = getConnection(url); + return download(getConnection(url), file); + } + public static HttpURLConnection download(final HttpURLConnection con, final File file) throws IOException { if (file.exists()) { con.setIfModifiedSince(file.lastModified()); con.connect(); @@ -53,15 +101,12 @@ public static HttpURLConnection download(final URL url, final File file) throws } public static String downloadAsString(final URL url) throws IOException { - final HttpURLConnection con = getConnection(url); - final byte[] buffer = downloadBinary(con); - return new String(buffer); + return downloadAsString(getConnection(url)); } - private static HttpURLConnection getConnection(final URL url) throws IOException { - final HttpURLConnection con = Configuration.getHttpConnection(url); - con.setUseCaches(true); - return con; + public static String downloadAsString(final HttpURLConnection con) throws IOException { + final byte[] buffer = downloadBinary(con); + return new String(buffer); } private static byte[] downloadBinary(final URLConnection con) throws IOException { diff --git a/src/org/rsbot/util/io/IniParser.java b/src/org/rsbot/util/io/IniParser.java index 1d10c58..d62a639 100644 --- a/src/org/rsbot/util/io/IniParser.java +++ b/src/org/rsbot/util/io/IniParser.java @@ -2,6 +2,8 @@ import java.io.BufferedReader; import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map.Entry; @@ -50,6 +52,13 @@ private static void writeSection(final String section, final HashMap> deserialise(final File input) throws IOException { + final BufferedReader reader = new BufferedReader(new FileReader(input)); + final HashMap> data = deserialise(reader); + reader.close(); + return data; + } + public static HashMap> deserialise(final BufferedReader input) throws IOException { final HashMap> data = new HashMap>(); String line, section = emptySection; @@ -65,7 +74,7 @@ public static HashMap> deserialise(final Buffere if (t == sectionOpen) { z = line.indexOf(sectionClose, 1); z = z == -1 ? l : z; - section = z == 1 ? "" : line.substring(1, z - 1).trim(); + section = z == 1 ? "" : line.substring(1, z).trim(); } else { boolean skip = false; for (final char c : comments) {