monkeyrunner

16:39:11.345 INFO  jd.cli.Main - Decompiling monkeyrunner.jar
package com.android.monkeyrunner;

import com.google.common.base.Predicate;

final class JythonUtils$1
  implements Predicate<String>
{
  public boolean apply(String value)
  {
    return !value.startsWith("__");
  }
}

/* Location:
 * Qualified Name:     com.android.monkeyrunner.JythonUtils.1
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.monkeyrunner;

import com.android.monkeyrunner.doc.MonkeyRunnerExported;
import com.google.common.base.Predicate;
import java.lang.reflect.AccessibleObject;

final class JythonUtils$2
  implements Predicate<AccessibleObject>
{
  public boolean apply(AccessibleObject ao)
  {
    return ao.isAnnotationPresent(MonkeyRunnerExported.class);
  }
}

/* Location:
 * Qualified Name:     com.android.monkeyrunner.JythonUtils.2
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.monkeyrunner;

import com.google.common.base.Predicate;
import java.lang.reflect.Field;

final class JythonUtils$3
  implements Predicate<Field>
{
  public boolean apply(Field f)
  {
    return (f.getModifiers() & 0x8) != 0;
  }
}

/* Location:
 * Qualified Name:     com.android.monkeyrunner.JythonUtils.3
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.monkeyrunner;

import com.android.monkeyrunner.doc.MonkeyRunnerExported;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.BreakIterator;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.python.core.ArgParser;
import org.python.core.Py;
import org.python.core.PyBoolean;
import org.python.core.PyDictionary;
import org.python.core.PyFloat;
import org.python.core.PyInteger;
import org.python.core.PyList;
import org.python.core.PyNone;
import org.python.core.PyObject;
import org.python.core.PyReflectedField;
import org.python.core.PyReflectedFunction;
import org.python.core.PyString;
import org.python.core.PyStringMap;
import org.python.core.PyTuple;

public final class JythonUtils
{
  private static final Logger LOG = Logger.getLogger(JythonUtils.class.getCanonicalName());
  private static final Map<Class<? extends PyObject>, Class<?>> PYOBJECT_TO_JAVA_OBJECT_MAP;
  
  static
  {
    ImmutableMap.Builder<Class<? extends PyObject>, Class<?>> builder = ImmutableMap.builder();
    
    builder.put(PyString.class, String.class);
    
    builder.put(PyFloat.class, Double.class);
    builder.put(PyInteger.class, Integer.class);
    builder.put(PyBoolean.class, Boolean.class);
    
    PYOBJECT_TO_JAVA_OBJECT_MAP = builder.build();
  }
  
  public static ArgParser createArgParser(PyObject[] args, String[] kws)
  {
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    
    StackTraceElement element = stackTrace[2];
    
    String methodName = element.getMethodName();
    String className = element.getClassName();
    Class<?> clz;
    try
    {
      clz = Class.forName(className);
    }
    catch (ClassNotFoundException e)
    {
      LOG.log(Level.SEVERE, "Got exception: ", e);
      return null;
    }
    Method m;
    try
    {
      m = clz.getMethod(methodName, new Class[] { PyObject[].class, String[].class });
    }
    catch (SecurityException e)
    {
      LOG.log(Level.SEVERE, "Got exception: ", e);
      return null;
    }
    catch (NoSuchMethodException e)
    {
      LOG.log(Level.SEVERE, "Got exception: ", e);
      return null;
    }
    MonkeyRunnerExported annotation = (MonkeyRunnerExported)m.getAnnotation(MonkeyRunnerExported.class);
    return new ArgParser(methodName, args, kws, annotation.args());
  }
  
  public static double getFloat(ArgParser ap, int position)
  {
    PyObject arg = ap.getPyObject(position);
    if (Py.isInstance(arg, PyFloat.TYPE)) {
      return ((PyFloat)arg).asDouble();
    }
    if (Py.isInstance(arg, PyInteger.TYPE)) {
      return ((PyInteger)arg).asDouble();
    }
    throw Py.TypeError("Unable to parse argument: " + position);
  }
  
  public static double getFloat(ArgParser ap, int position, double defaultValue)
  {
    PyObject arg = ap.getPyObject(position, new PyFloat(defaultValue));
    if (Py.isInstance(arg, PyFloat.TYPE)) {
      return ((PyFloat)arg).asDouble();
    }
    if (Py.isInstance(arg, PyInteger.TYPE)) {
      return ((PyInteger)arg).asDouble();
    }
    throw Py.TypeError("Unable to parse argument: " + position);
  }
  
  public static List<Object> getList(ArgParser ap, int position)
  {
    PyObject arg = ap.getPyObject(position, Py.None);
    if (Py.isInstance(arg, PyNone.TYPE)) {
      return Collections.emptyList();
    }
    List<Object> ret = Lists.newArrayList();
    PyList array = (PyList)arg;
    for (int x = 0; x < array.__len__(); x++)
    {
      PyObject item = array.__getitem__(x);
      
      Class<?> javaClass = (Class)PYOBJECT_TO_JAVA_OBJECT_MAP.get(item.getClass());
      if (javaClass != null) {
        ret.add(item.__tojava__(javaClass));
      }
    }
    return ret;
  }
  
  public static Map<String, Object> getMap(ArgParser ap, int position)
  {
    PyObject arg = ap.getPyObject(position, Py.None);
    if (Py.isInstance(arg, PyNone.TYPE)) {
      return Collections.emptyMap();
    }
    Map<String, Object> ret = Maps.newHashMap();
    
    PyDictionary dict = (PyDictionary)arg;
    PyList items = dict.items();
    for (int x = 0; x < items.__len__(); x++)
    {
      PyTuple item = (PyTuple)items.__getitem__(x);
      
      String key = (String)item.__getitem__(0).__str__().__tojava__(String.class);
      PyObject value = item.__getitem__(1);
      
      Class<?> javaClass = (Class)PYOBJECT_TO_JAVA_OBJECT_MAP.get(value.getClass());
      if (javaClass != null) {
        ret.put(key, value.__tojava__(javaClass));
      }
    }
    return ret;
  }
  
  private static PyObject convertObject(Object o)
  {
    if ((o instanceof String)) {
      return new PyString((String)o);
    }
    if ((o instanceof Double)) {
      return new PyFloat(((Double)o).doubleValue());
    }
    if ((o instanceof Integer)) {
      return new PyInteger(((Integer)o).intValue());
    }
    if ((o instanceof Float))
    {
      float f = ((Float)o).floatValue();
      return new PyFloat(f);
    }
    if ((o instanceof Boolean)) {
      return new PyBoolean(((Boolean)o).booleanValue());
    }
    return Py.None;
  }
  
  public static PyDictionary convertMapToDict(Map<String, Object> map)
  {
    Map<PyObject, PyObject> resultMap = Maps.newHashMap();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
      resultMap.put(new PyString((String)entry.getKey()), convertObject(entry.getValue()));
    }
    return new PyDictionary(resultMap);
  }
  
  public static void convertDocAnnotationsForClass(Class<?> clz, PyObject dict)
  {
    Preconditions.checkNotNull(dict);
    Preconditions.checkArgument(dict instanceof PyStringMap);
    if (clz.isAnnotationPresent(MonkeyRunnerExported.class))
    {
      MonkeyRunnerExported doc = (MonkeyRunnerExported)clz.getAnnotation(MonkeyRunnerExported.class);
      String fullDoc = buildClassDoc(doc, clz);
      dict.__setitem__("__doc__", new PyString(fullDoc));
    }
    Collection<String> functions = Sets.newHashSet();
    for (PyObject item : dict.asIterable()) {
      functions.add(item.toString());
    }
    functions = Collections2.filter(functions, new Predicate()
    {
      public boolean apply(String value)
      {
        return !value.startsWith("__");
      }
    });
    for (Method m : clz.getMethods()) {
      if (m.isAnnotationPresent(MonkeyRunnerExported.class))
      {
        String methodName = m.getName();
        PyObject pyFunc = dict.__finditem__(methodName);
        if ((pyFunc != null) && ((pyFunc instanceof PyReflectedFunction)))
        {
          PyReflectedFunction realPyFunc = (PyReflectedFunction)pyFunc;
          MonkeyRunnerExported doc = (MonkeyRunnerExported)m.getAnnotation(MonkeyRunnerExported.class);
          
          __doc__ = new PyString(buildDoc(doc));
          functions.remove(methodName);
        }
      }
    }
    for (Field f : clz.getFields()) {
      if (f.isAnnotationPresent(MonkeyRunnerExported.class))
      {
        String fieldName = f.getName();
        PyObject pyField = dict.__finditem__(fieldName);
        if ((pyField != null) && ((pyField instanceof PyReflectedField)))
        {
          PyReflectedField realPyfield = (PyReflectedField)pyField;
          MonkeyRunnerExported doc = (MonkeyRunnerExported)f.getAnnotation(MonkeyRunnerExported.class);
          
          functions.remove(fieldName);
        }
      }
    }
    for (String name : functions) {
      dict.__delitem__(name);
    }
  }
  
  private static final Predicate<AccessibleObject> SHOULD_BE_DOCUMENTED = new Predicate()
  {
    public boolean apply(AccessibleObject ao)
    {
      return ao.isAnnotationPresent(MonkeyRunnerExported.class);
    }
  };
  private static final Predicate<Field> IS_FIELD_STATIC = new Predicate()
  {
    public boolean apply(Field f)
    {
      return (f.getModifiers() & 0x8) != 0;
    }
  };
  
  private static String buildClassDoc(MonkeyRunnerExported doc, Class<?> clz)
  {
    Collection<Field> annotatedFields = Collections2.filter(Arrays.asList(clz.getFields()), SHOULD_BE_DOCUMENTED);
    Collection<Field> staticFields = Collections2.filter(annotatedFields, IS_FIELD_STATIC);
    Collection<Field> nonStaticFields = Collections2.filter(annotatedFields, Predicates.not(IS_FIELD_STATIC));
    
    StringBuilder sb = new StringBuilder();
    for (String line : splitString(doc.doc(), 80)) {
      sb.append(line).append("\n");
    }
    if (staticFields.size() > 0)
    {
      sb.append("\nClass Fields: \n");
      for (Field f : staticFields) {
        sb.append(buildFieldDoc(f));
      }
    }
    if (nonStaticFields.size() > 0)
    {
      sb.append("\n\nFields: \n");
      for (Field f : nonStaticFields) {
        sb.append(buildFieldDoc(f));
      }
    }
    return sb.toString();
  }
  
  private static String buildFieldDoc(Field f)
  {
    MonkeyRunnerExported annotation = (MonkeyRunnerExported)f.getAnnotation(MonkeyRunnerExported.class);
    StringBuilder sb = new StringBuilder();
    int indentOffset = 5 + f.getName().length();
    String indent = makeIndent(indentOffset);
    
    sb.append("  ").append(f.getName()).append(" - ");
    
    boolean first = true;
    for (String line : splitString(annotation.doc(), 80 - indentOffset)) {
      if (first)
      {
        first = false;
        sb.append(line).append("\n");
      }
      else
      {
        sb.append(indent).append(line).append("\n");
      }
    }
    return sb.toString();
  }
  
  private static String buildDoc(MonkeyRunnerExported doc)
  {
    Collection<String> docs = splitString(doc.doc(), 80);
    StringBuilder sb = new StringBuilder();
    for (String d : docs) {
      sb.append(d).append("\n");
    }
    if ((doc.args() != null) && (doc.args().length > 0))
    {
      String[] args = doc.args();
      String[] argDocs = doc.argDocs();
      
      sb.append("\n  Args:\n");
      boolean first;
      String indent;
      for (int x = 0; x < doc.args().length; x++)
      {
        sb.append("    ").append(args[x]);
        if ((argDocs != null) && (argDocs.length > x))
        {
          sb.append(" - ");
          int indentOffset = args[x].length() + 3 + 4;
          Collection<String> lines = splitString(argDocs[x], 80 - indentOffset);
          first = true;
          indent = makeIndent(indentOffset);
          for (String line : lines) {
            if (first)
            {
              first = false;
              sb.append(line).append("\n");
            }
            else
            {
              sb.append(indent).append(line).append("\n");
            }
          }
        }
      }
    }
    return sb.toString();
  }
  
  private static String makeIndent(int indentOffset)
  {
    if (indentOffset == 0) {
      return "";
    }
    StringBuffer sb = new StringBuffer();
    while (indentOffset > 0)
    {
      sb.append(' ');
      indentOffset--;
    }
    return sb.toString();
  }
  
  private static Collection<String> splitString(String source, int offset)
  {
    BreakIterator boundary = BreakIterator.getLineInstance();
    boundary.setText(source);
    
    List<String> lines = Lists.newArrayList();
    StringBuilder currentLine = new StringBuilder();
    int start = boundary.first();
    for (int end = boundary.next(); end != -1; end = boundary.next())
    {
      String b = source.substring(start, end);
      if (currentLine.length() + b.length() < offset)
      {
        currentLine.append(b);
      }
      else
      {
        lines.add(currentLine.toString());
        currentLine = new StringBuilder(b);
      }
      start = end;
    }
    lines.add(currentLine.toString());
    return lines;
  }
  
  public static Set<String> getMethodNames(Class<?> clazz)
  {
    HashSet<String> methodNames = new HashSet();
    for (Method m : clazz.getMethods()) {
      if (m.isAnnotationPresent(MonkeyRunnerExported.class)) {
        methodNames.add(m.getName());
      }
    }
    return methodNames;
  }
}

/* Location:
 * Qualified Name:     com.android.monkeyrunner.JythonUtils
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.monkeyrunner;

import com.android.chimpchat.core.By;
import com.android.chimpchat.core.IChimpDevice;
import com.android.chimpchat.core.IChimpImage;
import com.android.chimpchat.core.IChimpView;
import com.android.chimpchat.core.TouchPressType;
import com.android.chimpchat.hierarchyviewer.HierarchyViewer;
import com.android.monkeyrunner.doc.MonkeyRunnerExported;
import com.google.common.base.Functions;
import com.google.common.base.Preconditions;
import com.google.common.collect.Collections2;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.logging.Logger;
import org.python.core.ArgParser;
import org.python.core.ClassDictInit;
import org.python.core.Py;
import org.python.core.PyDictionary;
import org.python.core.PyList;
import org.python.core.PyObject;
import org.python.core.PyTuple;

@MonkeyRunnerExported(doc="Represents a device attached to the system.")
public class MonkeyDevice
  extends PyObject
  implements ClassDictInit
{
  private static final Logger LOG = Logger.getLogger(MonkeyDevice.class.getName());
  
  public static void classDictInit(PyObject dict)
  {
    JythonUtils.convertDocAnnotationsForClass(MonkeyDevice.class, dict);
  }
  
  @MonkeyRunnerExported(doc="Sends a DOWN event when used with touch() or press().")
  public static final String DOWN = TouchPressType.DOWN.getIdentifier();
  @MonkeyRunnerExported(doc="Sends an UP event when used with touch() or press().")
  public static final String UP = TouchPressType.UP.getIdentifier();
  @MonkeyRunnerExported(doc="Sends a DOWN event, immediately followed by an UP event when used with touch() or press()")
  public static final String DOWN_AND_UP = TouchPressType.DOWN_AND_UP.getIdentifier();
  @MonkeyRunnerExported(doc="Sends a MOVE event when used with touch().")
  public static final String MOVE = TouchPressType.MOVE.getIdentifier();
  private IChimpDevice impl;
  
  public MonkeyDevice(IChimpDevice impl)
  {
    this.impl = impl;
  }
  
  public IChimpDevice getImpl()
  {
    return impl;
  }
  
  @MonkeyRunnerExported(doc="Get the HierarchyViewer object for the device.", returns="A HierarchyViewer object")
  public HierarchyViewer getHierarchyViewer(PyObject[] args, String[] kws)
  {
    return impl.getHierarchyViewer();
  }
  
  @MonkeyRunnerExported(doc="Gets the device's screen buffer, yielding a screen capture of the entire display.", returns="A MonkeyImage object (a bitmap wrapper)")
  public MonkeyImage takeSnapshot()
  {
    IChimpImage image = impl.takeSnapshot();
    return new MonkeyImage(image);
  }
  
  @MonkeyRunnerExported(doc="Given the name of a variable on the device, returns the variable's value", args={"key"}, argDocs={"The name of the variable. The available names are listed in http://developer.android.com/guide/topics/testing/monkeyrunner.html."}, returns="The variable's value")
  public String getProperty(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    return impl.getProperty(ap.getString(0));
  }
  
  @MonkeyRunnerExported(doc="Synonym for getProperty()", args={"key"}, argDocs={"The name of the system variable."}, returns="The variable's value.")
  public String getSystemProperty(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    return impl.getSystemProperty(ap.getString(0));
  }
  
  @MonkeyRunnerExported(doc="Sends a touch event at the specified location", args={"x", "y", "type"}, argDocs={"x coordinate in pixels", "y coordinate in pixels", "touch event type as returned by TouchPressType()"})
  public void touch(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    int x = ap.getInt(0);
    int y = ap.getInt(1);
    
    TouchPressType type = TouchPressType.fromIdentifier(ap.getString(2));
    if (type == null)
    {
      LOG.warning(String.format("Invalid TouchPressType specified (%s) default used instead", new Object[] { ap.getString(2) }));
      
      type = TouchPressType.DOWN_AND_UP;
    }
    impl.touch(x, y, type);
  }
  
  @MonkeyRunnerExported(doc="Simulates dragging (touch, hold, and move) on the device screen.", args={"start", "end", "duration", "steps"}, argDocs={"The starting point for the drag (a tuple (x,y) in pixels)", "The end point for the drag (a tuple (x,y) in pixels", "Duration of the drag in seconds (default is 1.0 seconds)", "The number of steps to take when interpolating points. (default is 10)"})
  public void drag(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    PyObject startObject = ap.getPyObject(0);
    if (!(startObject instanceof PyTuple)) {
      throw Py.TypeError("Agrument 0 is not a tuple");
    }
    PyObject endObject = ap.getPyObject(1);
    if (!(endObject instanceof PyTuple)) {
      throw Py.TypeError("Agrument 1 is not a tuple");
    }
    PyTuple start = (PyTuple)startObject;
    PyTuple end = (PyTuple)endObject;
    
    int startx = ((Integer)start.__getitem__(0).__tojava__(Integer.class)).intValue();
    int starty = ((Integer)start.__getitem__(1).__tojava__(Integer.class)).intValue();
    int endx = ((Integer)end.__getitem__(0).__tojava__(Integer.class)).intValue();
    int endy = ((Integer)end.__getitem__(1).__tojava__(Integer.class)).intValue();
    
    double seconds = JythonUtils.getFloat(ap, 2, 1.0D);
    long ms = (seconds * 1000.0D);
    
    int steps = ap.getInt(3, 10);
    
    impl.drag(startx, starty, endx, endy, steps, ms);
  }
  
  @MonkeyRunnerExported(doc="Send a key event to the specified key", args={"name", "type"}, argDocs={"the keycode of the key to press (see android.view.KeyEvent)", "touch event type as returned by TouchPressType(). To simulate typing a key, send DOWN_AND_UP"})
  public void press(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    String name = ap.getString(0);
    String touchType = ap.getString(1, DOWN_AND_UP);
    if (touchType.equals("DOWN_AND_UP")) {
      touchType = "downAndUp";
    }
    TouchPressType type = TouchPressType.fromIdentifier(touchType);
    
    impl.press(name, type);
  }
  
  @MonkeyRunnerExported(doc="Types the specified string on the keyboard. This is equivalent to calling press(keycode,DOWN_AND_UP) for each character in the string.", args={"message"}, argDocs={"The string to send to the keyboard."})
  public void type(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    String message = ap.getString(0);
    impl.type(message);
  }
  
  @MonkeyRunnerExported(doc="Executes an adb shell command and returns the result, if any.", args={"cmd", "timeout"}, argDocs={"The adb shell command to execute.", "This arg is optional. It specifies the maximum amount of time during which thecommand can go without any output. A value of 0 means the methodwill wait forever. The unit of the timeout is millisecond"}, returns="The output from the command.")
  public String shell(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    String cmd = ap.getString(0);
    if (args.length == 2) {
      return impl.shell(cmd, ap.getInt(1));
    }
    return impl.shell(cmd);
  }
  
  @MonkeyRunnerExported(doc="Reboots the specified device into a specified bootloader.", args={"into"}, argDocs={"the bootloader to reboot into: bootloader, recovery, or None"})
  public void reboot(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    String into = ap.getString(0, null);
    
    impl.reboot(into);
  }
  
  @MonkeyRunnerExported(doc="Installs the specified Android package (.apk file) onto the device. If the package already exists on the device, it is replaced.", args={"path"}, argDocs={"The package's path and filename on the host filesystem."}, returns="True if the install succeeded")
  public boolean installPackage(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    String path = ap.getString(0);
    return impl.installPackage(path);
  }
  
  @MonkeyRunnerExported(doc="Deletes the specified package from the device, including its associated data and cache.", args={"package"}, argDocs={"The name of the package to delete."}, returns="True if remove succeeded")
  public boolean removePackage(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    String packageName = ap.getString(0);
    return impl.removePackage(packageName);
  }
  
  @MonkeyRunnerExported(doc="Starts an Activity on the device by sending an Intent constructed from the specified parameters.", args={"uri", "action", "data", "mimetype", "categories", "extras", "component", "flags"}, argDocs={"The URI for the Intent.", "The action for the Intent.", "The data URI for the Intent", "The mime type for the Intent.", "A Python iterable containing the category names for the Intent.", "A dictionary of extras to add to the Intent. Types of these extras are inferred from the python types of the values.", "The component of the Intent.", "An iterable of flags for the Intent.All arguments are optional. The default value for each argument is null.(see android.content.Intent)"})
  public void startActivity(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    String uri = ap.getString(0, null);
    String action = ap.getString(1, null);
    String data = ap.getString(2, null);
    String mimetype = ap.getString(3, null);
    Collection<String> categories = Collections2.transform(JythonUtils.getList(ap, 4), Functions.toStringFunction());
    
    Map<String, Object> extras = JythonUtils.getMap(ap, 5);
    String component = ap.getString(6, null);
    int flags = ap.getInt(7, 0);
    
    impl.startActivity(uri, action, data, mimetype, categories, extras, component, flags);
  }
  
  @MonkeyRunnerExported(doc="Sends a broadcast intent to the device.", args={"uri", "action", "data", "mimetype", "categories", "extras", "component", "flags"}, argDocs={"The URI for the Intent.", "The action for the Intent.", "The data URI for the Intent", "The mime type for the Intent.", "An iterable of category names for the Intent.", "A dictionary of extras to add to the Intent. Types of these extras are inferred from the python types of the values.", "The component of the Intent.", "An iterable of flags for the Intent.All arguments are optional. The default value for each argument is null.(see android.content.Context.sendBroadcast(Intent))"})
  public void broadcastIntent(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    String uri = ap.getString(0, null);
    String action = ap.getString(1, null);
    String data = ap.getString(2, null);
    String mimetype = ap.getString(3, null);
    Collection<String> categories = Collections2.transform(JythonUtils.getList(ap, 4), Functions.toStringFunction());
    
    Map<String, Object> extras = JythonUtils.getMap(ap, 5);
    String component = ap.getString(6, null);
    int flags = ap.getInt(7, 0);
    
    impl.broadcastIntent(uri, action, data, mimetype, categories, extras, component, flags);
  }
  
  @MonkeyRunnerExported(doc="Run the specified package with instrumentation and return the output it generates. Use this to run a test package using InstrumentationTestRunner.", args={"className", "args"}, argDocs={"The class to run with instrumentation. The format is packagename/classname. Use packagename to specify the Android package to run, and classname to specify the class to run within that package. For test packages, this is usually testpackagename/InstrumentationTestRunner", "A map of strings to objects containing the arguments to pass to this instrumentation (default value is None)."}, returns="A map of strings to objects for the output from the package. For a test package, contains a single key-value pair: the key is 'stream' and the value is a string containing the test output.")
  public PyDictionary instrument(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    String packageName = ap.getString(0);
    Map<String, Object> instrumentArgs = JythonUtils.getMap(ap, 1);
    if (instrumentArgs == null) {
      instrumentArgs = Collections.emptyMap();
    }
    Map<String, Object> result = impl.instrument(packageName, instrumentArgs);
    return JythonUtils.convertMapToDict(result);
  }
  
  @MonkeyRunnerExported(doc="Wake up the screen on the device")
  public void wake(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    impl.wake();
  }
  
  @MonkeyRunnerExported(doc="Retrieve the properties that can be queried")
  public PyList getPropertyList(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    Collection<String> properties = impl.getPropertyList();
    return new PyList(properties);
  }
  
  @MonkeyRunnerExported(doc="Retrieve the view ids for the current application")
  public PyList getViewIdList(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    Collection<String> viewIds = impl.getViewIdList();
    return new PyList(viewIds);
  }
  
  @MonkeyRunnerExported(doc="Obtains the view with the specified id.", args={"id"}, argDocs={"The id of the view to retrieve."}, returns="The view object with the specified id.")
  public MonkeyView getViewById(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    String id = ap.getString(0);
    IChimpView view = impl.getView(By.id(id));
    return new MonkeyView(view);
  }
  
  @MonkeyRunnerExported(doc="Obtains the view with the specified accessibility ids.", args={"windowId", "accessibility id"}, argDocs={"The window id of the view to retrieve.", "The accessibility id of the view to retrieve."}, returns="The view object with the specified id.")
  public MonkeyView getViewByAccessibilityIds(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    int windowId = Integer.parseInt(ap.getString(0));
    long accessibilityId = Long.parseLong(ap.getString(1));
    IChimpView view = impl.getView(By.accessibilityIds(windowId, accessibilityId));
    return new MonkeyView(view);
  }
  
  @MonkeyRunnerExported(doc="Obtains current root view", returns="The root view object")
  public MonkeyView getRootView(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    return new MonkeyView(impl.getRootView());
  }
  
  @MonkeyRunnerExported(doc="Obtains a list of views that contain the specified text.", args={"text"}, argDocs={"The text to search for"}, returns="A list of view objects that contain the specified text.")
  public PyList getViewsByText(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    String text = ap.getString(0);
    Collection<IChimpView> views = impl.getViews(By.text(text));
    PyList pyViews = new PyList();
    for (IChimpView view : views) {
      pyViews.append(new MonkeyView(view));
    }
    return pyViews;
  }
}

/* Location:
 * Qualified Name:     com.android.monkeyrunner.MonkeyDevice
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.monkeyrunner;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

class MonkeyFormatter$PrintWriterWithHeader
  extends PrintWriter
{
  private final ByteArrayOutputStream out;
  private final String header;
  
  public MonkeyFormatter$PrintWriterWithHeader(MonkeyFormatter paramMonkeyFormatter, String header)
  {
    this(paramMonkeyFormatter, header, new ByteArrayOutputStream());
  }
  
  public MonkeyFormatter$PrintWriterWithHeader(MonkeyFormatter paramMonkeyFormatter, String header, ByteArrayOutputStream out)
  {
    super(out, true);
    this.header = header;
    this.out = out;
  }
  
  public void println(Object x)
  {
    print(header);
    super.println(x);
  }
  
  public void println(String x)
  {
    print(header);
    super.println(x);
  }
  
  public String toString()
  {
    return out.toString();
  }
}

/* Location:
 * Qualified Name:     com.android.monkeyrunner.MonkeyFormatter.PrintWriterWithHeader
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.monkeyrunner;

import com.google.common.collect.Maps;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;

public class MonkeyFormatter
  extends Formatter
{
  public static final Formatter DEFAULT_INSTANCE = new MonkeyFormatter();
  private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyMMdd HH:mm:ss.SSS");
  private static Map<Level, String> LEVEL_TO_STRING_CACHE = Maps.newHashMap();
  
  private static final String levelToString(Level level)
  {
    String levelName = (String)LEVEL_TO_STRING_CACHE.get(level);
    if (levelName == null)
    {
      levelName = level.getName().substring(0, 1);
      LEVEL_TO_STRING_CACHE.put(level, levelName);
    }
    return levelName;
  }
  
  private static String getHeader(LogRecord record)
  {
    StringBuilder sb = new StringBuilder();
    
    sb.append(FORMAT.format(new Date(record.getMillis()))).append(":");
    sb.append(levelToString(record.getLevel())).append(" ");
    
    sb.append("[").append(Thread.currentThread().getName()).append("] ");
    
    String loggerName = record.getLoggerName();
    if (loggerName != null) {
      sb.append("[").append(loggerName).append("]");
    }
    return sb.toString();
  }
  
  private class PrintWriterWithHeader
    extends PrintWriter
  {
    private final ByteArrayOutputStream out;
    private final String header;
    
    public PrintWriterWithHeader(String header)
    {
      this(header, new ByteArrayOutputStream());
    }
    
    public PrintWriterWithHeader(String header, ByteArrayOutputStream out)
    {
      super(true);
      this.header = header;
      this.out = out;
    }
    
    public void println(Object x)
    {
      print(header);
      super.println(x);
    }
    
    public void println(String x)
    {
      print(header);
      super.println(x);
    }
    
    public String toString()
    {
      return out.toString();
    }
  }
  
  public String format(LogRecord record)
  {
    Throwable thrown = record.getThrown();
    String header = getHeader(record);
    
    StringBuilder sb = new StringBuilder();
    sb.append(header);
    sb.append(" ").append(formatMessage(record));
    sb.append("\n");
    if (thrown != null)
    {
      PrintWriter pw = new PrintWriterWithHeader(header);
      thrown.printStackTrace(pw);
      sb.append(pw.toString());
    }
    return sb.toString();
  }
}

/* Location:
 * Qualified Name:     com.android.monkeyrunner.MonkeyFormatter
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.monkeyrunner;

import com.android.chimpchat.core.IChimpImage;
import com.android.monkeyrunner.doc.MonkeyRunnerExported;
import com.google.common.base.Preconditions;
import java.util.logging.Logger;
import org.python.core.ArgParser;
import org.python.core.ClassDictInit;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyTuple;

@MonkeyRunnerExported(doc="An image")
public class MonkeyImage
  extends PyObject
  implements ClassDictInit
{
  private static Logger LOG = Logger.getLogger(MonkeyImage.class.getCanonicalName());
  private final IChimpImage impl;
  
  public static void classDictInit(PyObject dict)
  {
    JythonUtils.convertDocAnnotationsForClass(MonkeyImage.class, dict);
  }
  
  public MonkeyImage(IChimpImage impl)
  {
    this.impl = impl;
  }
  
  public IChimpImage getImpl()
  {
    return impl;
  }
  
  @MonkeyRunnerExported(doc="Converts the MonkeyImage into a particular format and returns the result as a String. Use this to get access to the rawpixels in a particular format. String output is for better performance.", args={"format"}, argDocs={"The destination format (for example, 'png' for Portable Network Graphics format). The default is png."}, returns="The resulting image as a String.")
  public byte[] convertToBytes(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    String format = ap.getString(0, "png");
    return impl.convertToBytes(format);
  }
  
  @MonkeyRunnerExported(doc="Write the MonkeyImage to a file.  If no format is specified, this method guesses the output format based on the extension of the provided file extension. If it is unable to guess the format, it uses PNG.", args={"path", "format"}, argDocs={"The output filename, optionally including its path", "The destination format (for example, 'png' for  Portable Network Graphics format."}, returns="boolean true if writing succeeded.")
  public boolean writeToFile(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    String path = ap.getString(0);
    String format = ap.getString(1, null);
    return impl.writeToFile(path, format);
  }
  
  @MonkeyRunnerExported(doc="Get a single ARGB (alpha, red, green, blue) pixel at location x,y. The arguments x and y are 0-based, expressed in pixel dimensions. X increases to the right, and Y increases towards the bottom. This method returns a tuple.", args={"x", "y"}, argDocs={"the x offset of the pixel", "the y offset of the pixel"}, returns="A tuple of (A, R, G, B) for the pixel. Each item in the tuple has the range 0-255.")
  public PyObject getRawPixel(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    int x = ap.getInt(0);
    int y = ap.getInt(1);
    int pixel = impl.getPixel(x, y);
    PyInteger a = new PyInteger((pixel & 0xFF000000) >> 24);
    PyInteger r = new PyInteger((pixel & 0xFF0000) >> 16);
    PyInteger g = new PyInteger((pixel & 0xFF00) >> 8);
    PyInteger b = new PyInteger((pixel & 0xFF) >> 0);
    return new PyTuple(new PyObject[] { a, r, g, b });
  }
  
  @MonkeyRunnerExported(doc="Get a single ARGB (alpha, red, green, blue) pixel at location x,y. The arguments x and y are 0-based, expressed in pixel dimensions. X increases to the right, and Y increases towards the bottom. This method returns an Integer.", args={"x", "y"}, argDocs={"the x offset of the pixel", "the y offset of the pixel"}, returns="An unsigned integer pixel for x,y. The 8 high-order bits are A, followedby 8 bits for R, 8 for G, and 8 for B.")
  public int getRawPixelInt(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    int x = ap.getInt(0);
    int y = ap.getInt(1);
    return impl.getPixel(x, y);
  }
  
  @MonkeyRunnerExported(doc="Compare this MonkeyImage object to aother MonkeyImage object.", args={"other", "percent"}, argDocs={"The other MonkeyImage object.", "A float in the range 0.0 to 1.0, indicating the percentage of pixels that need to be the same for the method to return 'true'. Defaults to 1.0."}, returns="boolean 'true' if the two objects contain the same image.")
  public boolean sameAs(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    PyObject otherObject = ap.getPyObject(0);
    IChimpImage other = ((MonkeyImage)otherObject.__tojava__(MonkeyImage.class)).getImpl();
    
    double percent = JythonUtils.getFloat(ap, 1, 1.0D);
    
    return impl.sameAs(other, percent);
  }
  
  @MonkeyRunnerExported(doc="Copy a rectangular region of the image.", args={"rect"}, argDocs={"A tuple (x, y, w, h) describing the region to copy. x and y specify upper lefthand corner of the region. w is the width of the region in pixels, and h is its height."}, returns="a MonkeyImage object representing the copied region.")
  public MonkeyImage getSubImage(PyObject[] args, String[] kws)
  {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);
    
    PyTuple rect = (PyTuple)ap.getPyObjectByType(0, PyTuple.TYPE);
    int x = rect.__getitem__(0).asInt();
    int y = rect.__getitem__(1).asInt();
    int w = rect.__getitem__(2).asInt();
    int h = rect.__getitem__(3).asInt();
    
    IChimpImage image = impl.getSubImage(x, y, w, h);
    return new MonkeyImage(image);
  }
}

/* Location:
 * Qualified Name:     com.android.monkeyrunner.MonkeyImage
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.monkeyrunner;

import com.android.chimpchat.core.ChimpRect;
import com.android.monkeyrunner.doc.MonkeyRunnerExported;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import org.python.core.ClassDictInit;
import org.python.core.PyInteger;
import org.python.core.PyList;
import org.python.core.PyO
1 2 3 4

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd