DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (31ec81b5d7bb)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
#filter substitution
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package @ANDROID_PACKAGE_NAME@;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.InvocationHandler;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.database.Cursor;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

import com.jayway.android.robotium.solo.Solo;

import static @ANDROID_PACKAGE_NAME@.FennecNativeDriver.LogLevel;

public class FennecNativeActions implements Actions {
    private Solo mSolo;
    private Instrumentation mInstr;
    private Activity mGeckoApp;
    private Assert mAsserter;

    // Objects for reflexive access of fennec classes.
    private ClassLoader mClassLoader;
    private Class mApiClass;
    private Class mEventListenerClass;
    private Class mDrawListenerClass;
    private Method mRegisterEventListener;
    private Method mUnregisterEventListener;
    private Method mBroadcastEvent;
    private Method mPreferencesGetEvent;
    private Method mPreferencesObserveEvent;
    private Method mPreferencesRemoveObserversEvent;
    private Method mSetDrawListener;
    private Method mQuerySql;
    private Object mRobocopApi;

    private static final String LOGTAG = "FennecNativeActions";

    public FennecNativeActions(Activity activity, Solo robocop, Instrumentation instrumentation, Assert asserter) {
        mSolo = robocop;
        mInstr = instrumentation;
        mGeckoApp = activity;
        mAsserter = asserter;
        // Set up reflexive access of java classes and methods.
        try {
            mClassLoader = activity.getClassLoader();

            mApiClass = mClassLoader.loadClass("org.mozilla.gecko.RobocopAPI");
            mEventListenerClass = mClassLoader.loadClass("org.mozilla.gecko.util.GeckoEventListener");
            mDrawListenerClass = mClassLoader.loadClass("org.mozilla.gecko.gfx.GeckoLayerClient$DrawListener");

            mRegisterEventListener = mApiClass.getMethod("registerEventListener", String.class, mEventListenerClass);
            mUnregisterEventListener = mApiClass.getMethod("unregisterEventListener", String.class, mEventListenerClass);
            mBroadcastEvent = mApiClass.getMethod("broadcastEvent", String.class, String.class);
            mPreferencesGetEvent = mApiClass.getMethod("preferencesGetEvent", Integer.TYPE, String[].class);
            mPreferencesObserveEvent = mApiClass.getMethod("preferencesObserveEvent", Integer.TYPE, String[].class);
            mPreferencesRemoveObserversEvent = mApiClass.getMethod("preferencesRemoveObserversEvent", Integer.TYPE);
            mSetDrawListener = mApiClass.getMethod("setDrawListener", mDrawListenerClass);
            mQuerySql = mApiClass.getMethod("querySql", String.class, String.class);

            mRobocopApi = mApiClass.getConstructor(Activity.class).newInstance(activity);
        } catch (Exception e) {
            FennecNativeDriver.log(LogLevel.ERROR, e);
        }
    }

    class wakeInvocationHandler implements InvocationHandler {
        private final GeckoEventExpecter mEventExpecter;

        public wakeInvocationHandler(GeckoEventExpecter expecter) {
            mEventExpecter = expecter;
        }

        public Object invoke(Object proxy, Method method, Object[] args) {
            String methodName = method.getName();
            //Depending on the method, return a completely different type.
            if(methodName.equals("toString")) {
                return this.toString();
            }
            if(methodName.equals("equals")) {
                return
                    args[0] == null ? false :
                    this.toString().equals(args[0].toString());
            }
            if(methodName.equals("clone")) {
                return this;
            }
            if(methodName.equals("hashCode")) {
                return 314;
            }
            FennecNativeDriver.log(FennecNativeDriver.LogLevel.DEBUG, 
                "Waking up on "+methodName);
            mEventExpecter.notifyOfEvent(args);
            return null;
        }
    }

    class GeckoEventExpecter implements RepeatedEventExpecter {
        private final String mGeckoEvent;
        private Object[] mRegistrationParams;
        private boolean mEventEverReceived;
        private String mEventData;
        private BlockingQueue<String> mEventDataQueue;
        private static final int MAX_WAIT_MS = 90000;

        GeckoEventExpecter(String geckoEvent, Object[] registrationParams) {
            if (TextUtils.isEmpty(geckoEvent)) {
                throw new IllegalArgumentException("geckoEvent must not be empty");
            }
            if (registrationParams == null || registrationParams.length == 0) {
                throw new IllegalArgumentException("registrationParams must not be empty");
            }

            mGeckoEvent = geckoEvent;
            mRegistrationParams = registrationParams;
            mEventDataQueue = new LinkedBlockingQueue<String>();
        }

        public void blockForEvent() {
            blockForEvent(MAX_WAIT_MS, true);
        }

        private void blockForEvent(long millis, boolean failOnTimeout) {
            if (mRegistrationParams == null) {
                throw new IllegalStateException("listener not registered");
            }
            try {
                mEventData = mEventDataQueue.poll(millis, TimeUnit.MILLISECONDS);
            } catch (InterruptedException ie) {
                FennecNativeDriver.log(LogLevel.ERROR, ie);
            }
            if (mEventData == null) {
                if (failOnTimeout) {
                    FennecNativeDriver.logAllStackTraces(FennecNativeDriver.LogLevel.ERROR);
                    mAsserter.ok(false, "GeckoEventExpecter",
                        "blockForEvent timeout: "+mGeckoEvent);
                } else {
                    FennecNativeDriver.log(FennecNativeDriver.LogLevel.DEBUG,
                        "blockForEvent timeout: "+mGeckoEvent);
                }
            } else {
                FennecNativeDriver.log(FennecNativeDriver.LogLevel.DEBUG,
                    "unblocked on expecter for " + mGeckoEvent);
            }
        }

        public void blockUntilClear(long millis) {
            if (mRegistrationParams == null) {
                throw new IllegalStateException("listener not registered");
            }
            if (millis <= 0) {
                throw new IllegalArgumentException("millis must be > 0");
            }
            // wait for at least one event
            try {
                mEventData = mEventDataQueue.poll(MAX_WAIT_MS, TimeUnit.MILLISECONDS);
            } catch (InterruptedException ie) {
                FennecNativeDriver.log(LogLevel.ERROR, ie);
            }
            if (mEventData == null) {
                FennecNativeDriver.logAllStackTraces(FennecNativeDriver.LogLevel.ERROR);
                mAsserter.ok(false, "GeckoEventExpecter", "blockUntilClear timeout");
                return;
            }
            // now wait for a period of millis where we don't get an event
            while (true) {
                try {
                    mEventData = mEventDataQueue.poll(millis, TimeUnit.MILLISECONDS);
                } catch (InterruptedException ie) {
                    FennecNativeDriver.log(LogLevel.INFO, ie);
                }
                if (mEventData == null) {
                    // success
                    break;
                }
            }
            FennecNativeDriver.log(FennecNativeDriver.LogLevel.DEBUG,
                "unblocked on expecter for " + mGeckoEvent);
        }

        public String blockForEventData() {
            blockForEvent();
            return mEventData;
        }

        public String blockForEventDataWithTimeout(long millis) {
            blockForEvent(millis, false);
            return mEventData;
        }

        public void unregisterListener() {
            if (mRegistrationParams == null) {
                throw new IllegalStateException("listener not registered");
            }
            try {
                FennecNativeDriver.log(LogLevel.INFO, "EventExpecter: no longer listening for "+mGeckoEvent);
                mUnregisterEventListener.invoke(mRobocopApi, mRegistrationParams);
                mRegistrationParams = null;
            } catch (IllegalAccessException e) {
                FennecNativeDriver.log(LogLevel.ERROR, e);
            } catch (InvocationTargetException e) {
                FennecNativeDriver.log(LogLevel.ERROR, e);
            }
        }

        public synchronized boolean eventReceived() {
            return mEventEverReceived;
        }

        void notifyOfEvent(Object[] args) {
            FennecNativeDriver.log(FennecNativeDriver.LogLevel.DEBUG,
                "received event " + mGeckoEvent);
            synchronized (this) {
                mEventEverReceived = true;
            }
            try {
                mEventDataQueue.put(args[1].toString());
            } catch (InterruptedException e) {
                FennecNativeDriver.log(LogLevel.ERROR,
                    "EventExpecter dropped event: "+args[1].toString());
                FennecNativeDriver.log(LogLevel.ERROR, e);
            }
        }
    }

    public RepeatedEventExpecter expectGeckoEvent(String geckoEvent) {
        FennecNativeDriver.log(FennecNativeDriver.LogLevel.DEBUG,
            "waiting for "+geckoEvent);
        try {
            Object[] finalParams = new Object[2];
            finalParams[0] = geckoEvent;
            GeckoEventExpecter expecter = new GeckoEventExpecter(geckoEvent, finalParams);
            wakeInvocationHandler wIH = new wakeInvocationHandler(expecter);
            Object proxy = Proxy.newProxyInstance(mClassLoader, new Class[] { mEventListenerClass }, wIH);
            finalParams[1] = proxy;

            mRegisterEventListener.invoke(mRobocopApi, finalParams);
            return expecter;
        } catch (IllegalAccessException e) {
            FennecNativeDriver.log(LogLevel.ERROR, e);
        } catch (InvocationTargetException e) {
            FennecNativeDriver.log(LogLevel.ERROR, e);
        }
        return null;
    }

    public void sendGeckoEvent(String geckoEvent, String data) {
        try {
            mBroadcastEvent.invoke(mRobocopApi, geckoEvent, data);
        } catch (IllegalAccessException e) {
            FennecNativeDriver.log(LogLevel.ERROR, e);
        } catch (InvocationTargetException e) {
            FennecNativeDriver.log(LogLevel.ERROR, e);
        }
    }

    private void sendPreferencesEvent(Method method, int requestId, String[] prefNames) {
        try {
            method.invoke(mRobocopApi, requestId, prefNames);
        } catch (IllegalAccessException e) {
            FennecNativeDriver.log(LogLevel.ERROR, e);
        } catch (InvocationTargetException e) {
            FennecNativeDriver.log(LogLevel.ERROR, e);
        }
    }

    public void sendPreferencesGetEvent(int requestId, String[] prefNames) {
        sendPreferencesEvent(mPreferencesGetEvent, requestId, prefNames);
    }

    public void sendPreferencesObserveEvent(int requestId, String[] prefNames) {
        sendPreferencesEvent(mPreferencesObserveEvent, requestId, prefNames);
    }

    public void sendPreferencesRemoveObserversEvent(int requestId) {
        try {
            mPreferencesRemoveObserversEvent.invoke(mRobocopApi, requestId);
        } catch (IllegalAccessException e) {
            FennecNativeDriver.log(LogLevel.ERROR, e);
        } catch (InvocationTargetException e) {
            FennecNativeDriver.log(LogLevel.ERROR, e);
        } 
    }

    class DrawListenerProxy implements InvocationHandler {
        private final PaintExpecter mPaintExpecter;

        DrawListenerProxy(PaintExpecter paintExpecter) {
            mPaintExpecter = paintExpecter;
        }

        public Object invoke(Object proxy, Method method, Object[] args) {
            String methodName = method.getName();
            if ("drawFinished".equals(methodName)) {
                FennecNativeDriver.log(FennecNativeDriver.LogLevel.DEBUG,
                    "Received drawFinished notification");
                mPaintExpecter.notifyOfEvent(args);
            } else if ("toString".equals(methodName)) {
                return "DrawListenerProxy";
            } else if ("equals".equals(methodName)) {
                return false;
            } else if ("hashCode".equals(methodName)) {
                return 0;
            }
            return null;
        }
    }

    class PaintExpecter implements RepeatedEventExpecter {
        private boolean mPaintDone;
        private boolean mListening;
        private static final int MAX_WAIT_MS = 90000;

        PaintExpecter() throws IllegalAccessException, InvocationTargetException {
            Object proxy = Proxy.newProxyInstance(mClassLoader, new Class[] { mDrawListenerClass }, new DrawListenerProxy(this));
            mSetDrawListener.invoke(mRobocopApi, proxy);
            mListening = true;
        }

        void notifyOfEvent(Object[] args) {
            synchronized (this) {
                mPaintDone = true;
                this.notifyAll();
            }
        }

        private synchronized void blockForEvent(long millis, boolean failOnTimeout) {
            if (!mListening) {
                throw new IllegalStateException("draw listener not registered");
            }
            long startTime = SystemClock.uptimeMillis();
            long endTime = 0;
            while (!mPaintDone) {
                try {
                    this.wait(millis);
                } catch (InterruptedException ie) {
                    FennecNativeDriver.log(LogLevel.ERROR, ie);
                    break;
                }
                endTime = SystemClock.uptimeMillis();
                if (!mPaintDone && (endTime - startTime >= millis)) {
                    if (failOnTimeout) {
                        FennecNativeDriver.logAllStackTraces(FennecNativeDriver.LogLevel.ERROR);
                        mAsserter.ok(false, "PaintExpecter", "blockForEvent timeout");
                    }
                    return;
                }
            }
        }

        public synchronized void blockForEvent() {
            blockForEvent(MAX_WAIT_MS, true);
        }

        public synchronized String blockForEventData() {
            blockForEvent();
            return null;
        }

        public synchronized String blockForEventDataWithTimeout(long millis) {
            blockForEvent(millis, false);
            return null;
        }

        public synchronized boolean eventReceived() {
            return mPaintDone;
        }

        public synchronized void blockUntilClear(long millis) {
            if (!mListening) {
                throw new IllegalStateException("draw listener not registered");
            }
            if (millis <= 0) {
                throw new IllegalArgumentException("millis must be > 0");
            }
            // wait for at least one event
            long startTime = SystemClock.uptimeMillis();
            long endTime = 0;
            while (!mPaintDone) {
                try {
                    this.wait(MAX_WAIT_MS);
                } catch (InterruptedException ie) {
                    FennecNativeDriver.log(LogLevel.ERROR, ie);
                    break;
                }
                endTime = SystemClock.uptimeMillis();
                if (!mPaintDone && (endTime - startTime >= MAX_WAIT_MS)) {
                    FennecNativeDriver.logAllStackTraces(FennecNativeDriver.LogLevel.ERROR);
                    mAsserter.ok(false, "PaintExpecter", "blockUtilClear timeout");
                    return;
                }
            }
            // now wait for a period of millis where we don't get an event
            startTime = SystemClock.uptimeMillis();
            while (true) {
                try {
                    this.wait(millis);
                } catch (InterruptedException ie) {
                    FennecNativeDriver.log(LogLevel.ERROR, ie);
                    break;
                }
                endTime = SystemClock.uptimeMillis();
                if (endTime - startTime >= millis) {
                    // success
                    break;
                }
                // we got a notify() before we could wait long enough, so we need to start over
                startTime = endTime;
            }
        }

        public synchronized void unregisterListener() {
            if (!mListening) {
                throw new IllegalStateException("listener not registered");
            }
            try {
                FennecNativeDriver.log(LogLevel.INFO, "PaintExpecter: no longer listening for events");
                mListening = false;
                mSetDrawListener.invoke(mRobocopApi, (Object)null);
            } catch (Exception e) {
                FennecNativeDriver.log(LogLevel.ERROR, e);
            }
        }
    }

    public RepeatedEventExpecter expectPaint() {
        try {
            return new PaintExpecter();
        } catch (Exception e) {
            FennecNativeDriver.log(LogLevel.ERROR, e);
            return null;
        }
    }

    public void sendSpecialKey(SpecialKey button) {
        switch(button) {
            case DOWN:
                sendKeyCode(KeyEvent.KEYCODE_DPAD_DOWN);
                break;
            case UP:
                sendKeyCode(KeyEvent.KEYCODE_DPAD_UP);
                break;
            case LEFT:
                sendKeyCode(KeyEvent.KEYCODE_DPAD_LEFT);
                break;
            case RIGHT:
                sendKeyCode(KeyEvent.KEYCODE_DPAD_RIGHT);
                break;
            case ENTER:
                sendKeyCode(KeyEvent.KEYCODE_ENTER);
                break;
            case MENU:
                sendKeyCode(KeyEvent.KEYCODE_MENU);
                break;
            case BACK:
                sendKeyCode(KeyEvent.KEYCODE_BACK);
                break;
            default:
                mAsserter.ok(false, "sendSpecialKey", "Unknown SpecialKey " + button);
                break;
        }
    }

    public void sendKeyCode(int keyCode) {
        if (keyCode <= 0 || keyCode > KeyEvent.getMaxKeyCode()) {
            mAsserter.ok(false, "sendKeyCode", "Unknown keyCode " + keyCode);
        }
        mInstr.sendCharacterSync(keyCode);
    }

    @Override
    public void sendKeys(String input) {
        mInstr.sendStringSync(input);
    }

    public void drag(int startingX, int endingX, int startingY, int endingY) {
        mSolo.drag(startingX, endingX, startingY, endingY, 10);
    }

    public Cursor querySql(String dbPath, String sql) {
        try {
            return (Cursor)mQuerySql.invoke(mRobocopApi, dbPath, sql);
        } catch(InvocationTargetException ex) {
            Log.e(LOGTAG, "Error invoking method", ex);
        } catch(IllegalAccessException ex) {
            Log.e(LOGTAG, "Error using field", ex);
        }
        return null;
    }
}