finished everything

This commit is contained in:
Clisprail
2013-07-01 13:18:51 +02:00
parent a48c7fbb28
commit 36f7e0407e
54 changed files with 1785 additions and 68 deletions
Binary file not shown.
+29 -3
View File
@@ -1,13 +1,15 @@
package org.parabot;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import org.parabot.core.Core;
import org.parabot.core.Directories;
import org.parabot.core.ui.ServerSelector;
import org.parabot.core.ui.utils.UILog;
/**
* Parabot X - A revolution in bot clients
* Parabot v2
*
* @author Clisprail (Parnassian)
* @author Matt, Dane
@@ -16,14 +18,38 @@ import org.parabot.core.ui.ServerSelector;
public final class Landing {
public static void main(String... args) {
parseArgs(args);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Throwable t) {
t.printStackTrace();
}
Directories.validate();
Core.setDebug(true);
ServerSelector.getInstance().setVisible(true);
if(!Core.inDebugMode()) {
UILog.log("Error", "You can only run parabot in debug mode.", JOptionPane.ERROR_MESSAGE);
return;
}
ServerSelector.getInstance();
}
private static void parseArgs(String... args) {
for(int i = 0; i < args.length; i++) {
final String arg = args[i];
switch(arg) {
case "-createdirs":
Directories.validate();
System.out.println("Directories created, you can now run parabot.");
System.exit(0);
break;
case "-debug":
Core.setDebug(true);
break;
case "-server":
ServerSelector.initServer = args[++i];
break;
}
}
}
}
+91 -10
View File
@@ -9,9 +9,13 @@ import org.parabot.core.asm.ASMClassLoader;
import org.parabot.core.bot.loader.BotLoader;
import org.parabot.core.classpath.ClassPath;
import org.parabot.core.paint.PaintDebugger;
import org.parabot.core.parsers.HookParser;
import org.parabot.core.ui.BotUI;
import org.parabot.core.ui.components.GamePanel;
import org.parabot.environment.api.interfaces.Paintable;
import org.parabot.environment.input.Keyboard;
import org.parabot.environment.input.Mouse;
import org.parabot.environment.scripts.Script;
import org.parabot.environment.servers.ServerProvider;
/**
@@ -21,7 +25,7 @@ import org.parabot.environment.servers.ServerProvider;
*
*/
public class Context {
private static HashMap<ThreadGroup, Context> threadGroups = new HashMap<ThreadGroup, Context>();
public static HashMap<ThreadGroup, Context> threadGroups = new HashMap<ThreadGroup, Context>();
private static int id = 1;
private ASMClassLoader classLoader = null;
@@ -29,6 +33,8 @@ public class Context {
private ServerProvider serverProvider = null;
private int tab = 0;
private Applet gameApplet = null;
private HookParser hookParser = null;
private Script runningScript = null;
private Object clientInstance = null;
@@ -37,6 +43,9 @@ public class Context {
private PaintDebugger paintDebugger = new PaintDebugger();
public boolean added = false;
private Mouse mouse = null;
private Keyboard keyboard = null;
public Context(final ServerProvider serverProvider) {
threadGroups.put(Thread.currentThread().getThreadGroup(), this);
@@ -45,6 +54,20 @@ public class Context {
id++;
this.classPath = new ClassPath();
}
/**
* Resolves the context from threadgroup
*
* @return context
*/
public static Context resolve() {
return threadGroups.get(Thread.currentThread().getThreadGroup());
}
public static Context currentTab() {
// TODO
return threadGroups.values().iterator().next();
}
/**
* Sets the ServerProvider class loader
@@ -61,6 +84,47 @@ public class Context {
public void setClientInstance(Object object) {
this.clientInstance = object;
}
/**
* Sets the hook parser
* @param hookParser
*/
public void setHookParser(final HookParser hookParser) {
this.hookParser = hookParser;
}
/**
* Sets the mouse
* @param mouse
*/
public void setMouse(final Mouse mouse) {
this.mouse = mouse;
}
/**
* Gets the mouse
* @return mouse
*/
public Mouse getMouse() {
return mouse;
}
/**
* Sets the keyboard
* @param keyboard
*/
public void setKeyboard(final Keyboard keyboard) {
this.keyboard = keyboard;
}
/**
* Gets the keyboard
* @return keyboard
*/
public Keyboard getKeyboard() {
return keyboard;
}
/**
* ClassPath
@@ -89,15 +153,6 @@ public class Context {
return gameApplet;
}
/**
* Resolves the context from threadgroup
*
* @return context
*/
public static Context resolve() {
return threadGroups.get(Thread.currentThread().getThreadGroup());
}
/**
* Loads the game
*/
@@ -121,6 +176,8 @@ public class Context {
gameApplet.setBounds(0, 0, 765, 503);
}
}, 1000);
serverProvider.initMouse();
serverProvider.initKeyboard();
}
/**
@@ -203,5 +260,29 @@ public class Context {
public Object getClient() {
return this.clientInstance;
}
/**
* Gets the hook parser, may be null if injection is not used or a custom hook parser is used for injecting
* @return hook parser
*/
public HookParser getHookParser() {
return hookParser;
}
/**
* Sets the current running script, if a script stops it will call this method with a null argument
* @param script
*/
public void setRunningScript(final Script script) {
this.runningScript = script;
}
/**
* Gets the current running script
* @return script
*/
public Script getRunningScript() {
return this.runningScript;
}
}
@@ -0,0 +1,63 @@
package org.parabot.core.asm.adapters;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import org.parabot.core.asm.interfaces.Injectable;
/**
* Injects methods which sets a field
*
* @author Clisprail
*
*/
public class AddSetterAdapter implements Opcodes, Injectable {
private ClassNode fieldLocation = null;
private ClassNode into = null;
private FieldNode field = null;
private String name = null;
private String desc = null;
private boolean methodStatic = false;
public AddSetterAdapter(ClassNode fieldLocation, ClassNode into, FieldNode field, String name, String desc, boolean methodStatic) {
this.fieldLocation = fieldLocation;
this.into = into;
this.field = field;
this.name = name;
this.desc = desc;
this.methodStatic = methodStatic;
}
public AddSetterAdapter(ClassNode fieldLocation, ClassNode into, FieldNode field, String name, String desc) {
this(fieldLocation, into, field, name, desc, false);
}
private static void addSetter(ClassNode fieldLocation, ClassNode into, FieldNode field, String name, String desc, boolean methodStatic) {
if (desc.contains("L") && !desc.endsWith("Ljava/lang/String;"))
desc = "Ljava/lang/Object;";
MethodNode method = new MethodNode(ACC_PUBLIC | (methodStatic ? ACC_STATIC : 0), name, "(" + desc + ")V", null, null);
boolean isStatic = (field.access & ACC_STATIC) > 0;
if (!isStatic) {
method.visitVarInsn(ALOAD, 0);
}
if (desc.equals("I"))
method.visitVarInsn(ILOAD, 1);
else
method.visitVarInsn(ALOAD, 1);
method.visitFieldInsn(isStatic ? PUTSTATIC : PUTFIELD, fieldLocation.name, field.name, field.desc);
method.visitInsn(RETURN);
method.visitMaxs(2, 2);
into.methods.add(method);
}
/**
* Injects the setter
*/
@Override
public void inject() {
addSetter(fieldLocation, into, field, name, desc, methodStatic);
}
}
@@ -35,6 +35,7 @@ public class Getter implements Injectable {
this.fieldLocation = ASMUtils.getClass(fieldLocation);
this.fieldNode = ASMUtils.getField(ASMUtils.getClass(fieldLocation), fieldNode);
this.methodName = methodName;
System.out.println(fieldNode);
this.returnDesc = returnDesc == null ? this.fieldNode.desc : returnDesc;
this.staticMethod = staticMethod;
}
@@ -63,6 +64,10 @@ public class Getter implements Injectable {
getAdapter().inject();
}
/**
* Gets the AddGetterAdapter
* @return AddGetterAdapter
*/
public AddGetterAdapter getAdapter() {
return new AddGetterAdapter(into, fieldLocation, fieldNode, methodName, returnDesc, staticMethod);
}
@@ -0,0 +1,53 @@
package org.parabot.core.asm.wrappers;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.parabot.core.asm.ASMUtils;
import org.parabot.core.asm.adapters.AddSetterAdapter;
import org.parabot.core.asm.interfaces.Injectable;
/**
*
* @author Clisprail
*
*/
public class Setter implements Injectable {
private ClassNode fieldLocation = null;
private ClassNode into = null;
private FieldNode field = null;
private String name = null;
private String desc = null;
private boolean methodStatic = false;
public Setter(final String fieldLocation, String into, final String fieldName, final String methodName, final String desc, final boolean methodStatic) {
this.fieldLocation = ASMUtils.getClass(fieldLocation);
into = (into == null) ? fieldLocation : into;
this.into = ASMUtils.getClass(into);
this.field = ASMUtils.getField(this.fieldLocation, fieldName);
this.name = methodName;
this.desc = (desc == null) ? this.field.desc : desc;
this.methodStatic = methodStatic;
}
public Setter(final String fieldLocation, final String fieldName, final String methodName) {
this(fieldLocation, null, fieldName, methodName, null, false);
}
/**
* Short route for getAdaptar().inject();
* @see AddSetterAdapter#inject
*/
@Override
public void inject() {
getAdapter().inject();
}
/**
* Gets the AddGetterAdapter
* @return AddGetterAdapter
*/
public AddSetterAdapter getAdapter() {
return new AddSetterAdapter(fieldLocation, into, field, name, desc, methodStatic);
}
}
@@ -0,0 +1,24 @@
package org.parabot.core.build;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
/**
*
* @author Clisprail
*
*/
public class BuildPath {
public static void add(final URL url) {
try {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke((URLClassLoader) ClassLoader.getSystemClassLoader(), url);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -5,6 +5,7 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
@@ -12,6 +13,7 @@ import java.util.zip.ZipInputStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import org.parabot.core.build.BuildPath;
/**
*
@@ -21,6 +23,20 @@ import org.objectweb.asm.tree.ClassNode;
public class ClassPath {
public final HashMap<String, ClassNode> classes = new HashMap<String, ClassNode>();
public final Map<String, URL> resources = new HashMap<String, URL>();
private boolean isJar = false;
private boolean parseJar = true;
private ArrayList<URL> jarFiles = new ArrayList<URL>();
public URL lastParsed = null;
public ClassPath() {
}
public ClassPath(final boolean isJar) {
this.isJar = isJar;
}
/**
* Adds jar to this classpath
@@ -37,6 +53,10 @@ public class ClassPath {
public void addJar(final URL jarLocation) {
JarParser.parseJar(this, jarLocation.toString());
}
public void parseJarFiles(final boolean enabled) {
this.parseJar = enabled;
}
/**
* Finds and loads all classes/jar files in folder
@@ -63,7 +83,11 @@ public class ClassPath {
if (f1.getName().endsWith(".class"))
loadClass(fin);
else if (f.equals(root) && f1.getName().endsWith(".jar")) {
loadClasses(f1.toURI().toURL());
jarFiles.add(f1.toURI().toURL());
if(this.parseJar) {
// if enabled, there may be problem with duplicate class names.......
loadClasses(f1.toURI().toURL());
}
} else {
String path = f1.toURI().relativize(root.toURI())
.getPath();
@@ -81,7 +105,8 @@ public class ClassPath {
*
* @param url to file
*/
private void loadClasses(URL u) {
public void loadClasses(URL u) {
this.lastParsed = u;
try (ZipInputStream zin = new ZipInputStream(u.openStream())) {
ZipEntry e;
while ((e = zin.getNextEntry()) != null) {
@@ -113,6 +138,7 @@ public class ClassPath {
classes.put(cn.name, cn);
}
/**
* Dumps the classnodes into a jar
*
@@ -121,5 +147,24 @@ public class ClassPath {
public void dump(final String jarName) {
JarDumper.dump(this, jarName);
}
public boolean isJar() {
return isJar;
}
public ClassPath[] getJarFiles() {
final ClassPath[] jars = new ClassPath[jarFiles.size()];
for(int i = 0; i < jarFiles.size(); i++) {
final ClassPath classPath = new ClassPath(true);
classPath.loadClasses(jarFiles.get(i));
jars[i] = classPath;
}
return jars;
}
public void addToBuildPath() {
BuildPath.add(lastParsed);
}
}
@@ -0,0 +1,25 @@
package org.parabot.core.desc;
public class ScriptDescription {
public String scriptName = null;
public String author = null;
public String category = null;
public double version = 0;
public String description = null;
public String[] servers = null;
public int scriptIndex = -1;
public ScriptDescription(final String scriptName, final String author,
final String category, final double version,
final String description, final String[] servers,
final int scriptIndex) {
this.scriptName = scriptName;
this.author = author;
this.category = category;
this.version = version;
this.description = description;
this.servers = servers;
this.scriptIndex = scriptIndex;
}
}
@@ -28,7 +28,7 @@ public class PaintDebugger {
}
}
g.setColor(Color.green);
int y = 20;
int y = 40;
while(stringDebug.size() > 0) {
g.drawString(stringDebug.poll(), 10, y);
y += 15;
@@ -39,7 +39,7 @@ public class PaintDebugger {
return Context.resolve().getPaintDebugger();
}
public final void addString(final String debugLine) {
public final void addLine(final String debugLine) {
stringDebug.add(debugLine);
}
@@ -11,6 +11,7 @@ import org.parabot.core.asm.adapters.AddInterfaceAdapter;
import org.parabot.core.asm.interfaces.Injectable;
import org.parabot.core.asm.wrappers.Getter;
import org.parabot.core.asm.wrappers.Interface;
import org.parabot.core.asm.wrappers.Setter;
import org.parabot.core.asm.wrappers.Super;
import org.parabot.environment.api.utils.WebUtil;
import org.w3c.dom.Document;
@@ -30,6 +31,8 @@ public class HookParser {
private boolean parsedInterfaces = false;
private HashMap<String, String> interfaceMap = new HashMap<String, String>();
private HashMap<String, String> constants = new HashMap<String, String>();
public HookParser(URL url) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
@@ -186,6 +189,12 @@ public class HookParser {
injectables.add(get);
}
}
Setter[] setters = getSetters();
if(setters != null) {
for(Setter set : setters) {
injectables.add(set);
}
}
Super[] supers = getSupers();
if(supers != null) {
for(Super sup : supers) {
@@ -195,6 +204,64 @@ public class HookParser {
return injectables.toArray(new Injectable[injectables.size()]);
}
public final Setter[] getSetters() {
final NodeList setterRootList = doc.getElementsByTagName("setters");
switch(setterRootList.getLength()) {
case 0:
return null;
case 1:
break;
default:
throw new RuntimeException("Hook file may not contains multiple <setters> tags ");
}
final Node node = setterRootList.item(0);
if(node.getNodeType() != Node.ELEMENT_NODE) {
return null;
}
final Element setterRoot = (Element) node;
final NodeList setters = setterRoot.getElementsByTagName("add");
if(setters.getLength() == 0) {
return null;
}
final ArrayList<Setter> setterList = new ArrayList<Setter>();
for(int x = 0; x < setters.getLength(); x++) {
final Node n = setters.item(x);
if(n.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
final Element addSetter = (Element) n;
if(isSet("classname", addSetter) && isSet("accessor", addSetter)) {
throw new RuntimeException("Can't set classname and accessor tag together.");
}
if(isSet("accessor", addSetter) && !parsedInterfaces) {
throw new RuntimeException("You'll need to parse interfaces first.");
}
final String className = isSet("classname", addSetter) ? getValue("classname", addSetter) : interfaceMap.get(getValue("accessor", addSetter));
final String into = isSet("into", addSetter) ? getValue("into", addSetter) : className;
final String fieldName = getValue("field", addSetter);
final String methodName = getValue("methodname", addSetter);
boolean staticMethod = isSet("methstatic", addSetter) ? (getValue("methstatic", addSetter).equals("true")) : false;
String returnDesc = isSet("desc", addSetter) ? getValue("desc", addSetter) : null;
String array = "";
if(returnDesc != null && returnDesc.contains("%s")) {
StringBuilder str = new StringBuilder();
if(returnDesc.startsWith("[")) {
for( int i=0; i<returnDesc.length(); i++ ) {
if( returnDesc.charAt(i) == '[' ) {
array += '[';
}
}
returnDesc = returnDesc.replaceAll("\\[", "");
}
str.append(array).append('L').append(String.format(returnDesc, AddInterfaceAdapter.getAccessorPackage())).append(";");
returnDesc = str.toString();
}
final Setter get = new Setter(into, className, fieldName, methodName, returnDesc, staticMethod);
setterList.add(get);
}
return setterList.toArray(new Setter[setterList.size()]);
}
private static final boolean isSet(String tag, Element element) {
return element.getElementsByTagName(tag).getLength() > 0;
}
@@ -205,6 +272,42 @@ public class HookParser {
return node.getNodeValue();
}
public final HashMap<String, String> getConstants() {
if(!constants.isEmpty()) {
return constants;
}
final NodeList constantsRootList = doc.getElementsByTagName("constants");
switch(constantsRootList.getLength()) {
case 0:
return null;
case 1:
break;
default:
throw new RuntimeException("Hook file may not contains multiple <constants> tags ");
}
final Node node = constantsRootList.item(0);
if(node.getNodeType() != Node.ELEMENT_NODE) {
return null;
}
final Element constantRoot = (Element) node;
final NodeList constantsList = constantRoot.getElementsByTagName("add");
if(constantsList.getLength() == 0) {
// return empty hashmap
return constants;
}
for(int x = 0; x < constantsList.getLength(); x++) {
final Node n = constantsList.item(x);
if(n.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
final Element addConstant = (Element) n;
final String key = getValue("key", addConstant);
final String value = getValue("value", addConstant);
constants.put(key, value);
}
return constants;
}
}
@@ -0,0 +1,90 @@
package org.parabot.core.parsers;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.parabot.core.Core;
import org.parabot.core.Directories;
import org.parabot.core.classpath.ClassPath;
import org.parabot.core.desc.ScriptDescription;
import org.parabot.environment.scripts.Script;
import org.parabot.environment.scripts.ScriptManifest;
import org.parabot.environment.scripts.loader.ScriptLoader;
/**
*
* @author Clisprail
*
*/
public class ScriptManifestParser {
public static Map<ScriptDescription, Script> scriptCache = new HashMap<ScriptDescription, Script>();
/**
* Gets server descriptions
*
* @return list of descriptions
*/
public ScriptDescription[] getDescriptions() {
scriptCache.clear();
if (Core.inDebugMode()) {
return localDesc();
}
return publicDesc();
}
private ScriptDescription[] publicDesc() {
return null;
}
private ScriptDescription[] localDesc() {
// parse classes in server directories
final ClassPath path = new ClassPath();
path.loadClasses(Directories.getScriptCompiledPath(), null);
// init the script loader
final ScriptLoader loader = new ScriptLoader(path);
// list of scripts
final List<Script> scripts = new ArrayList<Script>();
// list of descriptions
final List<ScriptDescription> descs = new ArrayList<ScriptDescription>();
// loop through all classes which extends the 'Script' class
for (final String className : loader.getScriptClassNames()) {
try {
// get class
final Class<?> scriptClass = loader.loadClass(className);
// get annotation
final Object annotation = scriptClass
.getAnnotation(ScriptManifest.class);
if (annotation == null) {
throw new RuntimeException("Missing manifest at "
+ className);
}
// cast object annotation to script manifest annotation
final ScriptManifest manifest = (ScriptManifest) annotation;
// get constructor
final Constructor<?> con = scriptClass.getConstructor();
final Script script = (Script) con.newInstance();
scripts.add(script);
final ScriptDescription desc = new ScriptDescription(manifest.name(), manifest
.author(), manifest.category().toString(), manifest.version(), manifest.description(),
manifest.servers(), scripts.size() - 1);
scriptCache.put(desc, script);
descs.add(desc);
} catch (Throwable t) {
t.printStackTrace();
}
}
if (scripts.isEmpty()) {
return null;
}
return descs.toArray(new ScriptDescription[descs.size()]);
}
}
@@ -1,9 +1,6 @@
package org.parabot.core.parsers;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -42,49 +39,69 @@ public class ServerManifestParser {
}
private ServerDescription[] localDesc() {
final ClassPath path = new ClassPath();
path.loadClasses(Directories.getServerPath(), null);
try {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke((URLClassLoader) ClassLoader.getSystemClassLoader(), Directories.getServerPath().toURI().toURL());
} catch (Exception e) {
e.printStackTrace();
// parse classes in server directories
final ClassPath basePath = new ClassPath();
basePath.parseJarFiles(false);
basePath.loadClasses(Directories.getServerPath(), null);
ArrayList<ClassPath> classPaths = new ArrayList<ClassPath>();
classPaths.add(basePath);
for (final ClassPath classPath : basePath.getJarFiles()) {
classPaths.add(classPath);
}
final ServerLoader loader = new ServerLoader(path);
final List<ServerProvider> providers = new ArrayList<ServerProvider>();
final List<ServerDescription> descs = new ArrayList<ServerDescription>();
for (final String className : loader.getServerClassNames()) {
try {
final Class<?> serverProviderClass = loader.loadClass(className);
final Object annotation = serverProviderClass.getAnnotation(ServerManifest.class);
if (annotation == null) {
throw new RuntimeException("Missing manifest at " + className);
// list of descriptions
final List<ServerDescription> allDescs = new ArrayList<ServerDescription>();
for (final ClassPath path : classPaths) {
final List<ServerDescription> descs = new ArrayList<ServerDescription>();
// init the server loader
final ServerLoader loader = new ServerLoader(path);
// list of providers
final List<ServerProvider> providers = new ArrayList<ServerProvider>();
// loop through all classes which extends the 'ServerProvider' class
for (final String className : loader.getServerClassNames()) {
try {
// get class
final Class<?> serverProviderClass = loader.loadClass(className);
// get annotation
final Object annotation = serverProviderClass
.getAnnotation(ServerManifest.class);
if (annotation == null) {
throw new RuntimeException("Missing manifest at "
+ className);
}
// cast object annotation to server manifest annotation
final ServerManifest manifest = (ServerManifest) annotation;
// get constructor
final Constructor<?> con = serverProviderClass.getConstructor();
final ServerProvider server = (ServerProvider) con.newInstance();
providers.add(server);
descs.add(new ServerDescription(manifest.name(), manifest
.author(), 0, providers.size() - 1));
} catch (Throwable t) {
t.printStackTrace();
}
final ServerManifest manifest = (ServerManifest) annotation;
final Constructor<?> con = serverProviderClass.getConstructor();
final ServerProvider server = (ServerProvider) con.newInstance();
providers.add(server);
descs.add(new ServerDescription(manifest.name(), manifest.author(), 0, providers.size() - 1));
} catch (Throwable t) {
t.printStackTrace();
}
if (providers.isEmpty()) {
continue;
}
final ServerCache cachedServer = new ServerCache(loader, providers.toArray(new ServerProvider[providers.size()]));
for (final ServerDescription desc : descs) {
allDescs.add(desc);
cache.put(desc, cachedServer);
}
}
if (providers.isEmpty()) {
return null;
}
final ServerCache cachedServer = new ServerCache(loader, providers.toArray(new ServerProvider[providers.size()]));
for (final ServerDescription desc : descs) {
cache.put(desc, cachedServer);
}
return descs.toArray(new ServerDescription[descs.size()]);
return allDescs.toArray(new ServerDescription[allDescs.size()]);
}
public class ServerCache {
private ServerLoader serverLoader = null;
private ServerProvider[] serverProviders = null;
private ServerCache(final ServerLoader serverLoader, final ServerProvider[] serverProviders) {
private ServerCache(final ServerLoader serverLoader,
final ServerProvider[] serverProviders) {
this.serverLoader = serverLoader;
this.serverProviders = serverProviders;
}
+6 -2
View File
@@ -10,9 +10,11 @@ import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import org.parabot.core.ui.applet.LoadApplet;
import org.parabot.core.ui.components.BotToolbar;
import org.parabot.core.ui.components.GamePanel;
import org.parabot.core.ui.components.LogArea;
@@ -34,7 +36,8 @@ public class BotUI extends JFrame implements ActionListener {
}
public BotUI() {
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
this.setTitle("Parabot");
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -81,13 +84,14 @@ public class BotUI extends JFrame implements ActionListener {
panel.add(toolbar);
panel.add(gamePanel);
gamePanel.add(LoadApplet.get());
panel.add(scrlConsole);
this.add(panel, BorderLayout.CENTER);
SwingUtil.finalize(this);
LogArea.log("Welcome to Parabot!");
LogArea.log("Welcome to parabot v2!");
}
@Override
@@ -0,0 +1,227 @@
package org.parabot.core.ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import org.parabot.core.Context;
import org.parabot.core.Core;
import org.parabot.core.Directories;
import org.parabot.core.desc.ScriptDescription;
import org.parabot.core.parsers.ScriptManifestParser;
import org.parabot.environment.scripts.Category;
/**
* @author Clisprail
*/
public class ScriptSelector extends JFrame {
private static final long serialVersionUID = 1L;
private HashMap<String, DefaultMutableTreeNode> categories = new HashMap<String, DefaultMutableTreeNode>();
private HashMap<String, ScriptDescription> format = new HashMap<String, ScriptDescription>();
private DefaultMutableTreeNode root = new DefaultMutableTreeNode("Scripts");
private DefaultTreeModel model = null;
private final int WIDTH = 640;
private final int HEIGHT = 256 + 128;
public static ScriptManifestParser parser = null;
public ScriptSelector() {
model = new DefaultTreeModel(root);
putScripts();
createUI();
}
private void runScript(ScriptDescription desc) {
dispose();
final ThreadGroup tg = Context.threadGroups.keySet().iterator()
.next();
new Thread(tg, ScriptManifestParser.scriptCache.get(desc)).start();
}
private void putScripts() {
localScripts();
}
private void localScripts() {
parser = new ScriptManifestParser();
final ScriptDescription[] descs = parser.getDescriptions();
if (descs == null) {
return;
}
for (final ScriptDescription scriptDesc : descs) {
if (categories.get(scriptDesc.category) == null) {
DefaultMutableTreeNode cat = new DefaultMutableTreeNode(Category.valueOf(scriptDesc.category.toUpperCase()));
cat.add(new DefaultMutableTreeNode(scriptDesc.scriptName));
root.add(cat);
categories.put(scriptDesc.category, cat);
} else {
categories.get(scriptDesc.category).add(
new DefaultMutableTreeNode(scriptDesc.scriptName));
}
format.put(scriptDesc.scriptName, scriptDesc);
}
}
private String getScriptName(String path) {
return path.split(", ")[2].replaceAll("\\]", "");
}
private String getServerDesc(final String[] servers) {
if (servers == null) {
return "Unknown";
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < servers.length; i++) {
builder.append(servers[i]);
if ((i + 1) < servers.length) {
builder.append(", ");
}
}
return builder.toString();
}
private void createUI() {
this.setTitle("Script Selector");
this.setLayout(new BorderLayout());
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(null);
panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
tree = new JTree();
tree.setCellRenderer(new ScriptTreeCellRenderer());
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.setModel(model);
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
String path = e.getPath().toString();
if (path.split(",").length == 3) {
// local scripts
ScriptDescription def = format.get(getScriptName(e
.getPath().toString()));
if (def != null) {
StringBuilder html = new StringBuilder("<html>");
html.append("<h1><font color=\"black\">")
.append(def.scriptName)
.append("</font></h1><br/>");
html.append("<font color=\"black\"><b>Author: </b>")
.append(def.author).append("</font><br/>");
html.append("<font color=\"black\"><b>Servers: </b>")
.append(getServerDesc(def.servers))
.append("</font><br/>");
html.append("<font color=\"black\"><b>Version: </b>")
.append(def.version).append("</font><br/>");
html.append(
"<font color=\"black\"><b>Description: </b>")
.append(def.description).append("</font><br/>");
html.append("</html>");
scriptInfo.setText(new String(html));
}
}
}
});
scriptInfo = new JEditorPane();
scriptInfo.setContentType("text/html");
scriptInfo.setEditable(false);
JScrollPane scrlScriptTree = new JScrollPane(tree);
scrlScriptTree.setBounds(4, 4, WIDTH / 2 - 4 - 64, HEIGHT - 4 - 28);
JScrollPane scrlScriptInfo = new JScrollPane(scriptInfo);
scrlScriptInfo.setBounds(WIDTH / 2 + 4 - 64, 4, WIDTH / 2 - 8 + 64,
HEIGHT - 4 - 28);
JButton cmdStart = new JButton("Start");
cmdStart.setBounds(WIDTH - 96 - 4, HEIGHT - 24 - 4, 96, 24);
cmdStart.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String s = getScriptName(tree.getSelectionPath().toString());
if (s != null) {
if (Core.inDebugMode()) {
runScript(format.get(s));
}
}
}
});
JButton cmdHome = new JButton("Open Home");
cmdHome.setBounds(WIDTH - (96 * 2) - 4 - 32, HEIGHT - 24 - 4, 96 + 32,
24);
cmdHome.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Desktop.getDesktop().open(Directories.getWorkspace());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
panel.add(scrlScriptTree);
panel.add(scrlScriptInfo);
panel.add(cmdStart);
panel.add(cmdHome);
this.add(panel);
this.pack();
this.setLocationRelativeTo(getOwner());
}
private class ScriptTreeCellRenderer implements TreeCellRenderer {
private JLabel label;
ScriptTreeCellRenderer() {
label = new JLabel();
}
@Override
public Component getTreeCellRendererComponent(JTree list, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean focused) {
Object o = ((DefaultMutableTreeNode) value).getUserObject();
BufferedImage icon = (o instanceof Category ? ((Category) o)
.getIcon() : Category.getIcon("script"));
label.setIcon(icon != null ? new ImageIcon(icon) : null);
label.setFont(o instanceof Category ? fontCategory : fontScript);
label.setForeground(selected ? Color.DARK_GRAY : Color.BLACK);
label.setText(String.valueOf(value));
return label;
}
}
private Font fontCategory = new Font("Arial", Font.BOLD, 12);
private Font fontScript = new Font("Arial", Font.PLAIN, 12);
private JTree tree;
private JEditorPane scriptInfo;
}
@@ -13,10 +13,11 @@ import org.parabot.core.desc.ServerDescription;
import org.parabot.core.parsers.ServerManifestParser;
import org.parabot.core.ui.utils.SwingUtil;
import org.parabot.core.ui.widgets.ServerWidget;
import org.parabot.environment.Environment;
/**
*
* @author Dane
* @author Dane, Clisprail
*
*/
@@ -25,6 +26,8 @@ public class ServerSelector extends JFrame {
private static final long serialVersionUID = 5238720307271493899L;
private static ServerSelector instance = null;
private JPanel panel;
public static String initServer = null;
public static ServerSelector getInstance() {
if (instance == null) {
@@ -34,6 +37,14 @@ public class ServerSelector extends JFrame {
}
public ServerSelector() {
Queue<ServerWidget> widgets = getServers();
if(initServer != null) {
if(runServer(widgets)) {
initServer = null;
return;
}
}
this.setTitle("Servers");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -42,13 +53,12 @@ public class ServerSelector extends JFrame {
this.panel = new JPanel(new BorderLayout());
this.panel.setPreferredSize(new Dimension(400, 200));
Queue<ServerWidget> widgets = getServers();
JPanel interior = new JPanel(null);
interior.setPreferredSize(new Dimension(400, widgets.size() * 100));
int i = 0;
for (ServerWidget w : widgets) {
while (widgets != null && !widgets.isEmpty()) {
final ServerWidget w = widgets.poll();
w.setSize(400, 100);
w.setLocation(0, i * 100);
interior.add(w);
@@ -65,6 +75,24 @@ public class ServerSelector extends JFrame {
SwingUtil.finalize(this);
}
/**
* This method is called when -server argument is given
* @param widgets
*/
private boolean runServer(Queue<ServerWidget> widgets) {
if(widgets == null || widgets.isEmpty()) {
return false;
}
final String serverName = initServer.toLowerCase();
for(ServerWidget widget : widgets) {
if(widget.desc.serverName.toLowerCase().equals(serverName)) {
Environment.load(widget.desc, widget.desc.serverName.replaceAll(" ", ""));
return true;
}
}
return false;
}
public Queue<ServerWidget> getServers() {
final Queue<ServerWidget> widgets = new LinkedList<ServerWidget>();
@@ -17,8 +17,10 @@ import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import org.parabot.core.Context;
import org.parabot.core.ui.ScriptSelector;
import org.parabot.core.ui.ServerSelector;
import org.parabot.core.ui.images.Images;
import org.parabot.environment.scripts.Script;
/**
* Bot toolbar
@@ -30,12 +32,15 @@ public class BotToolbar extends JToolBar {
private static final long serialVersionUID = 5373484845104212180L;
private static BotToolbar instance = null;
private JButton tab = null;
private final JButton run = new JButton();
private final JButton stop = new JButton();
private static Map<TabButton, Context> environments = new HashMap<TabButton, Context>();
private boolean runScript = false;
private boolean pauseScript = false;
public BotToolbar() {
setFloatable(false);
final JButton run = new JButton();
final JButton pause = new JButton();
tab = new JButton();
tab.addActionListener(new ActionListener() {
@@ -46,19 +51,84 @@ public class BotToolbar extends JToolBar {
});
run.setFocusable(false);
pause.setFocusable(false);
stop.setFocusable(false);
tab.setFocusable(false);
try {
run.setIcon(new ImageIcon(Images.getResource("/org/parabot/core/ui/images/run.png")));
pause.setIcon(new ImageIcon(Images.getResource("/org/parabot/core/ui/images/pause.png")));
stop.setIcon(new ImageIcon(Images.getResource("/org/parabot/core/ui/images/stop.png")));
tab.setIcon(new ImageIcon(Images.getResource("/org/parabot/core/ui/images/add.png")));
} catch (Throwable t) {
t.printStackTrace();
}
run.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
runButtonClicked();
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stopButtonClicked();
}
});
//add(tab);
add(Box.createHorizontalGlue());
add(run);
add(pause);
add(stop);
}
protected void stopButtonClicked() {
if(!runScript){
// obviously do nothing ;d
return;
}
setScriptState(Script.STATE_STOPPED);
}
protected void runButtonClicked() {
if(runScript && pauseScript) {
// unpause
this.pauseScript = false;
scriptRunning();
setScriptState(Script.STATE_RUNNING);
return;
} else if(runScript) {
// pause
this.pauseScript = true;
scriptStopped();
setScriptState(Script.STATE_PAUSE);
} else {
new ScriptSelector().setVisible(true);
}
}
private void setScriptState(int state) {
Context.currentTab().getRunningScript().setState(state);
}
public void toggleRun() {
runScript = !runScript;
if(runScript) {
scriptRunning();
} else {
scriptStopped();
}
}
private void scriptRunning() {
// sets pause icon
run.setIcon(new ImageIcon(Images.getResource("/org/parabot/core/ui/images/pause.png")));
}
private void scriptStopped() {
// sets start icon
run.setIcon(new ImageIcon(Images.getResource("/org/parabot/core/ui/images/run.png")));
}
public static BotToolbar getInstance() {
Binary file not shown.

After

Width:  |  Height:  |  Size: 299 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 331 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 325 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 489 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 357 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 371 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 307 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 311 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 343 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 328 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 431 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 371 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 452 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 668 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 354 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 276 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 310 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 377 B

@@ -0,0 +1,17 @@
package org.parabot.core.ui.utils;
import javax.swing.JOptionPane;
public class UILog {
public static void log(final String title, final String message) {
log(title, message, JOptionPane.INFORMATION_MESSAGE);
}
public static void log(final String title, final String message,
int messageType) {
JOptionPane.showMessageDialog(null, message, title,
messageType);
}
}
@@ -12,6 +12,7 @@ import javax.swing.JLabel;
import javax.swing.JPanel;
import org.parabot.core.desc.ServerDescription;
import org.parabot.core.ui.ServerSelector;
import org.parabot.environment.Environment;
/**
@@ -85,6 +86,7 @@ public class ServerWidget extends JPanel {
}
public void load(final ServerDescription desc, final String serverName) {
ServerSelector.getInstance().dispose();
Environment.load(desc, serverName);
}
}
@@ -1,15 +1,17 @@
package org.parabot.environment;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import org.parabot.core.Context;
import org.parabot.core.Core;
import org.parabot.core.Directories;
import org.parabot.core.build.BuildPath;
import org.parabot.core.classpath.ClassPath;
import org.parabot.core.desc.ServerDescription;
import org.parabot.core.parsers.ServerManifestParser;
import org.parabot.core.parsers.ServerManifestParser.ServerCache;
import org.parabot.core.ui.BotUI;
import org.parabot.core.ui.ServerSelector;
import org.parabot.core.ui.components.BotToolbar;
import org.parabot.environment.servers.ServerProvider;
import org.parabot.environment.servers.loader.ServerLoader;
@@ -27,14 +29,26 @@ public class Environment {
* @param url
*/
public static void load(final ServerDescription desc, final String serverName) {
ServerSelector.getInstance().dispose();
if (!BotUI.getInstance().isVisible()) {
BotUI.getInstance().setVisible(true);
}
final ClassPath classPath = Core.inDebugMode() ? null : new ClassPath();
final ServerCache cache = Core.inDebugMode() ? ServerManifestParser.cache.get(desc) : null;
// buildpath
if(cache != null) {
if(cache.getLoader().getClassPath().isJar()) {
cache.getLoader().getClassPath().addToBuildPath();
} else {
try {
BuildPath.add(Directories.getServerPath().toURI().toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
final ServerLoader serverLoader = Core.inDebugMode() ? cache.getLoader() : new ServerLoader(classPath);
String[] serverProviders = null;
if (!Core.inDebugMode()) {
@@ -0,0 +1,26 @@
package org.parabot.environment.api.utils;
/**
*
* @author Clisprail
*
*/
public class Random {
private final static java.util.Random RANDOM = new java.util.Random();
/**
* Randomizes a number between minimum and maximum
*
* @param min
* @param max
* @return randomized number
*/
public static int between(final int min, final int max) {
try {
return min + (max == min ? 0 : RANDOM.nextInt(max - min));
} catch (Exception e) {
return min + (max - min);
}
}
}
@@ -0,0 +1,35 @@
package org.parabot.environment.api.utils;
/**
*
* @author Clisprail
*
*/
public class Time {
/**
* Sleeps for a given amount of time
* @param ms
*/
public static void sleep(final int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void sleep(final int minumum, final int maximum) {
try {
Thread.sleep(Random.between(minumum, maximum));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static long get() {
return System.currentTimeMillis();
}
}
@@ -0,0 +1,223 @@
package org.parabot.environment.input;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.Random;
import org.parabot.core.Context;
/**
*
* @author Clisprail, Matt, Dane
*
*/
public class Keyboard implements KeyListener {
private Component component = null;
private static HashMap<Character, Character> specialChars;
private long pressTime;
public Keyboard(Component component) {
this.component = component;
}
public static Keyboard getInstance() {
return Context.resolve().getKeyboard();
}
static {
char[] spChars = { '~', '!', '@', '#', '%', '^', '&', '*', '(', ')',
'_', '+', '{', '}', ':', '<', '>', '?', '"', '|' };
char[] replace = { '`', '1', '2', '3', '5', '6', '7', '8', '9', '0',
'-', '=', '[', ']', ';', ',', '.', '/', '\'', '\\' };
specialChars = new HashMap<Character, Character>(spChars.length);
for (int x = 0; x < spChars.length; ++x)
specialChars.put(spChars[x], replace[x]);
}
private static long getRandom() {
Random rand = new Random();
return rand.nextInt(100) + 40;
}
public void sendKeys(String s) {
pressTime = System.currentTimeMillis();
for (char c : s.toCharArray())
for (KeyEvent ke : createKeyClick(component, c)) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendKeyEvent(ke);
}
clickKey(10);
}
public void clickKey(char c) {
pressTime = System.currentTimeMillis();
for (KeyEvent ke : createKeyClick(component, c))
sendKeyEvent(ke);
}
public void clickKey(int keyCode) {
pressTime = System.currentTimeMillis();
for (KeyEvent ke : createKeyClick(component, keyCode))
sendKeyEvent(ke);
}
public void pressKey(int keyCode) {
pressTime = System.currentTimeMillis();
KeyEvent ke = createKeyPress(component, keyCode);
sendKeyEvent(ke);
}
public void releaseKey(int keyCode) {
pressTime = System.currentTimeMillis();
KeyEvent ke = createKeyRelease(component, keyCode);
sendKeyEvent(ke);
}
private KeyEvent[] createKeyClick(Component target, char c) {
pressTime += 2 * getRandom();
Character newChar = specialChars.get(c);
int keyCode = Character.toUpperCase((newChar == null) ? c : newChar);
if (Character.isLowerCase(c)
|| (!Character.isLetter(c) && (newChar == null))) {
KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
pressTime, 0, keyCode, c);
KeyEvent typed = new KeyEvent(target, KeyEvent.KEY_TYPED,
pressTime, 0, 0, c);
pressTime += getRandom();
KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
pressTime, 0, keyCode, c);
return new KeyEvent[] { pressed, typed, released };
} else {
KeyEvent shiftDown = new KeyEvent(target, KeyEvent.KEY_PRESSED,
pressTime, KeyEvent.SHIFT_MASK, KeyEvent.VK_SHIFT,
KeyEvent.CHAR_UNDEFINED);
pressTime += getRandom();
KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
pressTime, KeyEvent.SHIFT_MASK, keyCode, c);
KeyEvent typed = new KeyEvent(target, KeyEvent.KEY_TYPED,
pressTime, KeyEvent.SHIFT_MASK, 0, c);
pressTime += getRandom();
KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
pressTime, KeyEvent.SHIFT_MASK, keyCode, c);
pressTime += getRandom();
KeyEvent shiftUp = new KeyEvent(target, KeyEvent.KEY_RELEASED,
pressTime, 0, KeyEvent.VK_SHIFT, KeyEvent.CHAR_UNDEFINED);
return new KeyEvent[] { shiftDown, pressed, typed, released,
shiftUp };
}
}
private KeyEvent[] createKeyClick(Component target, int keyCode) {
int modifier = 0;
switch (keyCode) {
case KeyEvent.VK_SHIFT:
modifier = KeyEvent.SHIFT_MASK;
break;
case KeyEvent.VK_ALT:
modifier = KeyEvent.ALT_MASK;
break;
case KeyEvent.VK_CONTROL:
modifier = KeyEvent.CTRL_MASK;
break;
}
KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
pressTime, modifier, keyCode, KeyEvent.CHAR_UNDEFINED);
KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
pressTime + getRandom(), 0, keyCode, KeyEvent.CHAR_UNDEFINED);
return new KeyEvent[] { pressed, released };
}
private KeyEvent createKeyPress(Component target, int keyCode) {
int modifier = 0;
switch (keyCode) {
case KeyEvent.VK_SHIFT:
modifier = KeyEvent.SHIFT_MASK;
break;
case KeyEvent.VK_ALT:
modifier = KeyEvent.ALT_MASK;
break;
case KeyEvent.VK_CONTROL:
modifier = KeyEvent.CTRL_MASK;
break;
}
KeyEvent pressed = new KeyEvent(target, KeyEvent.KEY_PRESSED,
pressTime, modifier, keyCode, KeyEvent.CHAR_UNDEFINED);
return pressed;
}
private KeyEvent createKeyRelease(Component target, int keyCode) {
@SuppressWarnings("unused")
int modifier = 0;
switch (keyCode) {
case KeyEvent.VK_SHIFT:
modifier = KeyEvent.SHIFT_MASK;
break;
case KeyEvent.VK_ALT:
modifier = KeyEvent.ALT_MASK;
break;
case KeyEvent.VK_CONTROL:
modifier = KeyEvent.CTRL_MASK;
break;
}
KeyEvent released = new KeyEvent(target, KeyEvent.KEY_RELEASED,
pressTime + getRandom(), 0, keyCode, KeyEvent.CHAR_UNDEFINED);
return released;
}
public void sendKeyEvent(KeyEvent e) {
for (KeyListener kl : component.getKeyListeners()) {
if(kl instanceof Keyboard) {
continue;
}
if (!e.isConsumed()) {
switch (e.getID()) {
case KeyEvent.KEY_PRESSED:
kl.keyPressed(e);
break;
case KeyEvent.KEY_RELEASED:
kl.keyReleased(e);
break;
case KeyEvent.KEY_TYPED:
kl.keyTyped(e);
break;
}
}
}
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
@@ -0,0 +1,158 @@
package org.parabot.environment.input;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import org.parabot.core.Context;
import org.parabot.environment.api.utils.Time;
/**
*
* @author Clisprail
*
*/
public class Mouse implements MouseListener, MouseMotionListener {
private Component component = null;
private int x = 0;
private int y = 0;
public Mouse(Component component) {
this.component = component;
}
public static Mouse getInstance() {
return Context.resolve().getMouse();
}
/**
* Moves the mouse to the given point and clicks
* @param x
* @param y
* @param left
*/
public void click(final int x, final int y, final boolean left) {
moveMouse(x, y);
Time.sleep(50, 200);
MouseEvent me = new MouseEvent(component,
MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), 0, x,
y, 1, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
for(MouseListener l : component.getMouseListeners()) {
if(!(l instanceof Mouse)) {
l.mousePressed(me);
}
}
Time.sleep(10, 100);
releaseMouse(x, y, left);
Time.sleep(10, 100);
clickMouse(x, y, left);
}
public void click(final Point p, final boolean left) {
click(p.x, p.y, left);
}
public void click(final Point p) {
click(p.x, p.y, true);
}
private void clickMouse(int x, int y, boolean left) {
try {
MouseEvent me = new MouseEvent(component,
MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), 0, x,
y, 0, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
for(MouseListener l : component.getMouseListeners()) {
if(!(l instanceof Mouse)) {
l.mouseClicked(me);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void releaseMouse(int x, int y, boolean left) {
try {
MouseEvent me = new MouseEvent(component,
MouseEvent.MOUSE_RELEASED, System.currentTimeMillis(), 0, x,
y, 0, false, left ? MouseEvent.BUTTON1 : MouseEvent.BUTTON3);
for(MouseListener l : component.getMouseListeners()) {
if(!(l instanceof Mouse)) {
l.mouseReleased(me);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Moves the mouse cursor to the given location
* @param x
* @param y
*/
public void moveMouse(int x, int y) {
try {
MouseEvent me = new MouseEvent(component,
MouseEvent.MOUSE_MOVED, System.currentTimeMillis(), 0, x,
y, 0, false);
for(MouseMotionListener l : component.getMouseMotionListeners()) {
if(!(l instanceof Mouse)) {
l.mouseMoved(me);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Mouse cursor current location
* @return point
*/
public Point getPoint() {
return new Point(x, y);
}
@Override
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
}
@@ -0,0 +1,44 @@
package org.parabot.environment.scripts;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import org.parabot.core.ui.images.Images;
/**
*
* @author Dane
*
*/
public enum Category
{
AGILITY, COMBAT, COOKING, CRAFTING, FARMING, FIREMAKING, FISHING, FLETCHING, HERBLORE, MAGIC, MINING, OTHER, PRAYER, RUNECRAFTING, SLAYER, SMITHING, THIEVING, UTILITY, WOODCUTTING;
public BufferedImage getIcon() {
return Category.getIcon(this.name().toLowerCase());
}
public static BufferedImage getIcon(String s) {
if (images.get(s) == null) {
images.put(s, Images.getResource("/org/parabot/core/ui/images/category/" + s + ".png"));
}
return images.get(s);
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append(name().charAt(0));
b.append(name().toLowerCase().substring(1));
return new String(b);
}
private static HashMap<String, BufferedImage> images = new HashMap<String, BufferedImage>();
static {
images.put("script", Images.getResource("/org/parabot/core/ui/images/category/script.png"));
}
}
@@ -0,0 +1,60 @@
package org.parabot.environment.scripts;
import java.util.Collection;
import org.parabot.environment.scripts.framework.AbstractFramework;
import org.parabot.environment.scripts.framework.LoopTask;
import org.parabot.environment.scripts.framework.Strategy;
public class Frameworks {
public static Looper getLooper(LoopTask loopTask) {
return new Looper(loopTask);
}
public static StrategyWorker getStrategyWorker(Collection<Strategy> strategies) {
return new StrategyWorker(strategies);
}
}
class Looper extends AbstractFramework {
private LoopTask loopTask = null;
public Looper(LoopTask loopTask) {
this.loopTask = loopTask;
}
@Override
public boolean execute() {
int sleepTime = loopTask.loop();
if(sleepTime < 0) {
return false;
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
}
class StrategyWorker extends AbstractFramework {
private Collection<Strategy> strategies = null;
public StrategyWorker(Collection<Strategy> strategies) {
this.strategies = strategies;
}
@Override
public boolean execute() {
for(Strategy s : strategies) {
if(s.activate()) {
s.execute();
return true;
}
}
return true;
}
}
@@ -0,0 +1,145 @@
package org.parabot.environment.scripts;
import java.util.Collection;
import org.parabot.core.Context;
import org.parabot.core.ui.components.BotToolbar;
import org.parabot.environment.api.utils.Time;
import org.parabot.environment.scripts.framework.AbstractFramework;
import org.parabot.environment.scripts.framework.LoopTask;
import org.parabot.environment.scripts.framework.SleepCondition;
import org.parabot.environment.scripts.framework.Strategy;
/**
*
* @author Clisprail
*
*/
public class Script implements Runnable {
private Collection<Strategy> strategies = null;
private int frameWorkType = 0;
private AbstractFramework frameWork = null;
public static final int TYPE_STRATEGY = 0;
public static final int TYPE_LOOP = 1;
public static final int TYPE_OTHER = 2;
private int state = 0;
public static final int STATE_RUNNING = 0;
public static final int STATE_PAUSE = 1;
public static final int STATE_STOPPED = 2;
public boolean onExecute() {
return true;
}
public void onFinish() {
}
public final void provide(final Collection<Strategy> strategies) {
this.strategies = strategies;
}
public final int getFrameWorkType() {
return frameWorkType;
}
public final void setFrameWork(int frameWorkType) {
if(frameWorkType < 0 || frameWorkType > 2) {
throw new RuntimeException("Invalid framework type");
}
this.frameWorkType = frameWorkType;
}
public final void setAbstractFrameWork(AbstractFramework f) {
this.frameWork = f;
}
@Override
public final void run() {
Context.resolve().getServerProvider().initScript(this);
if(!onExecute()) {
Context.resolve().getServerProvider().unloadScript(this);
this.state = STATE_STOPPED;
return;
}
Context.resolve().setRunningScript(this);
BotToolbar.getInstance().toggleRun();
if(this instanceof LoopTask) {
frameWorkType = TYPE_LOOP;
frameWork = Frameworks.getLooper((LoopTask) this);
} else if(strategies != null && !strategies.isEmpty()) {
frameWorkType = TYPE_STRATEGY;
frameWork = Frameworks.getStrategyWorker(strategies);
} else {
frameWorkType = TYPE_OTHER;
}
try {
while(this.state != STATE_STOPPED) {
if(this.state == STATE_PAUSE) {
sleep(500);
continue;
}
if(!frameWork.execute()) {
break;
}
}
} catch (Throwable t) {
t.printStackTrace();
}
onFinish();
Context.resolve().getServerProvider().unloadScript(this);
this.state = STATE_STOPPED;
Context.resolve().setRunningScript(null);
BotToolbar.getInstance().toggleRun();
}
/**
* Sleeps until the SleepCondition is valid.
*
* @param conn
* the condition.
* @param timeout
* the time in miliseconds before it stops sleeping.
* @return whether it ran successfully without timing out.
*/
public final boolean sleep(SleepCondition conn, int timeout) {
long start = System.currentTimeMillis();
while (!conn.isValid()) {
if (start + timeout < System.currentTimeMillis()) {
return false;
}
Time.sleep(50);
}
return true;
}
/**
* Sets the script's state
* @param state
*/
public final void setState(final int state) {
if(state < 0 || state > 2) {
throw new IllegalArgumentException("Illegal state");
}
this.state = state;
}
/**
* Sleeps for an amount of milliseconds
* @param ms
*/
public final void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,26 @@
package org.parabot.environment.scripts;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* A script manifest
* @author Clisprail
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ScriptManifest {
String author();
String name();
Category category();
double version();
String description();
String[] servers();
}
@@ -0,0 +1,7 @@
package org.parabot.environment.scripts.framework;
public abstract class AbstractFramework {
public abstract boolean execute();
}
@@ -0,0 +1,7 @@
package org.parabot.environment.scripts.framework;
public interface LoopTask {
public int loop();
}
@@ -0,0 +1,8 @@
package org.parabot.environment.scripts.framework;
public interface SleepCondition {
public boolean isValid();
}
@@ -0,0 +1,9 @@
package org.parabot.environment.scripts.framework;
public interface Strategy {
public boolean activate();
public void execute();
}
@@ -0,0 +1,43 @@
package org.parabot.environment.scripts.loader;
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.tree.ClassNode;
import org.parabot.core.asm.ASMClassLoader;
import org.parabot.core.classpath.ClassPath;
import org.parabot.environment.scripts.Script;
/**
*
* An environment to load a server
*
* @author Clisprail
*
*
*/
public class ScriptLoader extends ASMClassLoader {
private ClassPath classPath = null;
public ScriptLoader(ClassPath classPath) {
super(classPath);
this.classPath = classPath;
}
/**
* Gets all classes that extends ServerProvider
* @return string array of class names that extends ServerProvider
*/
public final String[] getScriptClassNames() {
final List<String> classNames = new ArrayList<String>();
for (ClassNode c : classPath.classes.values())
if (c.superName.replace('/', '.').equals(
Script.class.getName())) {
classNames.add(c.name.replace('/', '.'));
}
return classNames.toArray(new String[classNames.size()]);
}
}
@@ -9,6 +9,9 @@ import org.objectweb.asm.Opcodes;
import org.parabot.core.Context;
import org.parabot.core.asm.interfaces.Injectable;
import org.parabot.core.parsers.HookParser;
import org.parabot.environment.input.Keyboard;
import org.parabot.environment.input.Mouse;
import org.parabot.environment.scripts.Script;
/**
* Provides a server to the bot
@@ -43,7 +46,6 @@ public abstract class ServerProvider implements Opcodes {
public void injectHooks() {
URL hooksFile = getHooks();
if (hooksFile == null) {
System.out.println("null");
return;
}
HookParser parser = new HookParser(hooksFile);
@@ -54,6 +56,7 @@ public abstract class ServerProvider implements Opcodes {
for (Injectable inj : injectables) {
inj.inject();
}
Context.resolve().setHookParser(parser);
}
/**
@@ -76,5 +79,30 @@ public abstract class ServerProvider implements Opcodes {
public void parseJar() {
Context.resolve().getClassPath().addJar(getJar());
}
public void initScript(Script script) {
}
public void initMouse() {
final Context context = Context.resolve();
final Applet applet = context.getApplet();
final Mouse mouse = new Mouse(applet);
applet.addMouseListener(mouse);
applet.addMouseMotionListener(mouse);
context.setMouse(mouse);
}
public void initKeyboard() {
final Context context = Context.resolve();
final Applet applet = context.getApplet();
final Keyboard keyboard = new Keyboard(applet);
applet.addKeyListener(keyboard);
context.setKeyboard(keyboard);
}
public void unloadScript(Script script) {
}
}
@@ -38,5 +38,9 @@ public class ServerLoader extends ASMClassLoader {
}
return classNames.toArray(new String[classNames.size()]);
}
public ClassPath getClassPath() {
return classPath;
}
}