summaryrefslogtreecommitdiffstats
path: root/mobile/android/geckoview/src/main/java/org/mozilla/gecko/EventDispatcher.java
blob: 647ac5bc0908989aa597521793b0692ee7ce0879 (plain)
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
 * vim: ts=4 sw=4 expandtab:
/* 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 org.mozilla.gecko;

import android.os.Handler;
import android.util.Log;
import androidx.annotation.AnyThread;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.mozilla.gecko.annotation.ReflectionTarget;
import org.mozilla.gecko.annotation.RobocopTarget;
import org.mozilla.gecko.annotation.WrapForJNI;
import org.mozilla.gecko.mozglue.JNIObject;
import org.mozilla.gecko.util.BundleEventListener;
import org.mozilla.gecko.util.EventCallback;
import org.mozilla.gecko.util.GeckoBundle;
import org.mozilla.gecko.util.ThreadUtils;
import org.mozilla.geckoview.BuildConfig;
import org.mozilla.geckoview.GeckoResult;

@RobocopTarget
public final class EventDispatcher extends JNIObject {
  private static final String LOGTAG = "GeckoEventDispatcher";

  private static final EventDispatcher INSTANCE = new EventDispatcher();

  /**
   * The capacity of a HashMap is rounded up to the next power-of-2. Every time the size of the map
   * goes beyond 75% of the capacity, the map is rehashed. Therefore, to empirically determine the
   * initial capacity that avoids rehashing, we need to determine the initial size, divide it by
   * 75%, and round up to the next power-of-2.
   */
  private static final int DEFAULT_UI_EVENTS_COUNT = 128; // Empirically measured

  private static class Message {
    final String type;
    final GeckoBundle bundle;
    final EventCallback callback;

    Message(final String type, final GeckoBundle bundle, final EventCallback callback) {
      this.type = type;
      this.bundle = bundle;
      this.callback = callback;
    }
  }

  // GeckoBundle-based events.
  private final MultiMap<String, BundleEventListener> mListeners =
      new MultiMap<>(DEFAULT_UI_EVENTS_COUNT);
  private Deque<Message> mPendingMessages = new ArrayDeque<>();

  private boolean mAttachedToGecko;
  private final NativeQueue mNativeQueue;
  private final String mName;

  private static Map<String, EventDispatcher> sDispatchers = new HashMap<>();

  @ReflectionTarget
  @WrapForJNI(calledFrom = "gecko")
  public static EventDispatcher getInstance() {
    return INSTANCE;
  }

  /**
   * Gets a named EventDispatcher.
   *
   * <p>Named EventDispatchers can be used to communicate to Gecko's corresponding named
   * EventDispatcher.
   *
   * <p>Messages for named EventDispatcher are queued by default when no listener is present. Queued
   * messages will be released automatically when a listener is attached.
   *
   * <p>A named EventDispatcher needs to be disposed manually by calling {@link #shutdown} when it
   * is not needed anymore.
   *
   * @param name Name for this EventDispatcher.
   * @return the existing named EventDispatcher for a given name or a newly created one if it
   *     doesn't exist.
   */
  @ReflectionTarget
  @WrapForJNI(calledFrom = "gecko")
  public static EventDispatcher byName(final String name) {
    synchronized (sDispatchers) {
      EventDispatcher dispatcher = sDispatchers.get(name);

      if (dispatcher == null) {
        dispatcher = new EventDispatcher(name);
        sDispatchers.put(name, dispatcher);
      }

      return dispatcher;
    }
  }

  /* package */ EventDispatcher() {
    mNativeQueue = GeckoThread.getNativeQueue();
    mName = null;
  }

  /* package */ EventDispatcher(final String name) {
    mNativeQueue = GeckoThread.getNativeQueue();
    mName = name;
  }

  public EventDispatcher(final NativeQueue queue) {
    mNativeQueue = queue;
    mName = null;
  }

  private boolean isReadyForDispatchingToGecko() {
    return mNativeQueue.isReady();
  }

  @WrapForJNI
  @Override // JNIObject
  protected native void disposeNative();

  @WrapForJNI(stubName = "Shutdown")
  protected native void shutdownNative();

  @WrapForJNI private static final int DETACHED = 0;
  @WrapForJNI private static final int ATTACHED = 1;
  @WrapForJNI private static final int REATTACHING = 2;

  @WrapForJNI(calledFrom = "gecko")
  private synchronized void setAttachedToGecko(final int state) {
    if (mAttachedToGecko && state == DETACHED) {
      dispose(false);
    }
    mAttachedToGecko = (state == ATTACHED);
  }

  /**
   * Shuts down this EventDispatcher and release resources.
   *
   * <p>Only named EventDispatcher can be shut down manually. A shut down EventDispatcher will not
   * receive any further messages.
   */
  public void shutdown() {
    if (mName == null) {
      throw new RuntimeException("Only named EventDispatcher's can be shut down.");
    }

    mAttachedToGecko = false;
    shutdownNative();
    dispose(false);

    synchronized (sDispatchers) {
      sDispatchers.put(mName, null);
    }
  }

  private void dispose(final boolean force) {
    final Handler geckoHandler = ThreadUtils.sGeckoHandler;
    if (geckoHandler == null) {
      return;
    }

    geckoHandler.post(
        new Runnable() {
          @Override
          public void run() {
            if (force || !mAttachedToGecko) {
              disposeNative();
            }
          }
        });
  }

  public void registerUiThreadListener(final BundleEventListener listener, final String... events) {
    try {
      synchronized (mListeners) {
        for (final String event : events) {
          if (!BuildConfig.RELEASE_OR_BETA && mListeners.containsEntry(event, listener)) {
            throw new IllegalStateException("Already registered " + event);
          }
          mListeners.add(event, listener);
        }
        flush(events);
      }
    } catch (final Exception e) {
      throw new IllegalArgumentException("Invalid new list type", e);
    }
  }

  public void unregisterUiThreadListener(
      final BundleEventListener listener, final String... events) {
    synchronized (mListeners) {
      for (final String event : events) {
        if (!mListeners.remove(event, listener) && !BuildConfig.RELEASE_OR_BETA) {
          throw new IllegalArgumentException(event + " was not registered");
        }
      }
    }
  }

  @WrapForJNI
  private native boolean hasGeckoListener(final String event);

  @WrapForJNI(dispatchTo = "gecko")
  private native void dispatchToGecko(
      final String event, final GeckoBundle data, final EventCallback callback);

  /**
   * Dispatch event to any registered Bundle listeners (non-Gecko thread listeners).
   *
   * @param type Event type
   * @param message Bundle message
   */
  public void dispatch(final String type, final GeckoBundle message) {
    dispatch(type, message, /* callback */ null);
  }

  private abstract class CallbackResult<T> extends GeckoResult<T> implements EventCallback {
    @Override
    public void sendError(final Object response) {
      completeExceptionally(new QueryException(response));
    }
  }

  public class QueryException extends Exception {
    public final Object data;

    public QueryException(final Object data) {
      this.data = data;
    }
  }

  /**
   * Query event to any registered Bundle listeners (non-Gecko thread listeners).
   *
   * <p>The returned GeckoResult completes when the event handler returns.
   *
   * @param type Event type
   */
  public GeckoResult<Void> queryVoid(final String type) {
    return queryVoid(type, null);
  }

  /**
   * Query event to any registered Bundle listeners (non-Gecko thread listeners).
   *
   * <p>The returned GeckoResult completes when the event handler returns.
   *
   * @param type Event type
   * @param message GeckoBundle message
   */
  public GeckoResult<Void> queryVoid(final String type, final GeckoBundle message) {
    return query(type, message);
  }

  /**
   * Query event to any registered Bundle listeners (non-Gecko thread listeners).
   *
   * <p>The returned GeckoResult completes with the given boolean value returned by the handler.
   *
   * @param type Event type
   */
  public GeckoResult<Boolean> queryBoolean(final String type) {
    return queryBoolean(type, null);
  }

  /**
   * Query event to any registered Bundle listeners (non-Gecko thread listeners).
   *
   * <p>The returned GeckoResult completes with the given boolean value returned by the handler.
   *
   * @param type Event type
   * @param message GeckoBundle message
   */
  public GeckoResult<Boolean> queryBoolean(final String type, final GeckoBundle message) {
    return query(type, message);
  }

  /**
   * Query event to any registered Bundle listeners (non-Gecko thread listeners).
   *
   * <p>The returned GeckoResult completes with the given String value returned by the handler.
   *
   * @param type Event type
   */
  public GeckoResult<String> queryString(final String type) {
    return queryString(type, null);
  }

  /**
   * Query event to any registered Bundle listeners (non-Gecko thread listeners).
   *
   * <p>The returned GeckoResult completes with the given String value returned by the handler.
   *
   * @param type Event type
   * @param message GeckoBundle message
   */
  public GeckoResult<String> queryString(final String type, final GeckoBundle message) {
    return query(type, message);
  }

  /**
   * Query event to any registered Bundle listeners (non-Gecko thread listeners).
   *
   * <p>The returned GeckoResult completes with the given {@link GeckoBundle} value returned by the
   * handler.
   *
   * @param type Event type
   */
  public GeckoResult<GeckoBundle> queryBundle(final String type) {
    return queryBundle(type, null);
  }

  /**
   * Query event to any registered Bundle listeners (non-Gecko thread listeners).
   *
   * <p>The returned GeckoResult completes with the given {@link GeckoBundle} value returned by the
   * handler.
   *
   * @param type Event type
   * @param message GeckoBundle message
   */
  public GeckoResult<GeckoBundle> queryBundle(final String type, final GeckoBundle message) {
    return query(type, message);
  }

  private <T> GeckoResult<T> query(final String type, final GeckoBundle message) {
    final CallbackResult<T> result =
        new CallbackResult<T>() {
          @Override
          @SuppressWarnings("unchecked") // Not a lot we can do about this :(
          public void sendSuccess(final Object response) {
            complete((T) response);
          }
        };

    dispatch(type, message, result);
    return result;
  }

  /**
   * Flushes pending messages of given types.
   *
   * <p>All unhandled messages are put into a pending state by default for named EventDispatcher
   * obtained from {@link #byName}.
   *
   * @param types Types of message to flush.
   */
  private void flush(final String[] types) {
    final Set<String> typeSet = new HashSet<>(Arrays.asList(types));

    final Deque<Message> pendingMessages;
    synchronized (mPendingMessages) {
      pendingMessages = mPendingMessages;
      mPendingMessages = new ArrayDeque<>(pendingMessages.size());
    }

    Message message;
    while (!pendingMessages.isEmpty()) {
      message = pendingMessages.removeFirst();
      if (typeSet.contains(message.type)) {
        dispatchToThreads(message.type, message.bundle, message.callback);
      } else {
        synchronized (mPendingMessages) {
          mPendingMessages.addLast(message);
        }
      }
    }
  }

  /**
   * Dispatch event to any registered Bundle listeners (non-Gecko thread listeners).
   *
   * @param type Event type
   * @param message Bundle message
   * @param callback Optional object for callbacks from events.
   */
  @AnyThread
  private void dispatch(
      final String type, final GeckoBundle message, final EventCallback callback) {
    final boolean isGeckoReady;
    synchronized (this) {
      isGeckoReady = isReadyForDispatchingToGecko();
      if (isGeckoReady && mAttachedToGecko && hasGeckoListener(type)) {
        dispatchToGecko(type, message, JavaCallbackDelegate.wrap(callback));
        return;
      }
    }

    dispatchToThreads(type, message, callback, isGeckoReady);
  }

  @WrapForJNI(calledFrom = "gecko")
  private boolean dispatchToThreads(
      final String type, final GeckoBundle message, final EventCallback callback) {
    return dispatchToThreads(type, message, callback, /* isGeckoReady */ true);
  }

  private boolean dispatchToThreads(
      final String type,
      final GeckoBundle message,
      final EventCallback callback,
      final boolean isGeckoReady) {
    // We need to hold the lock throughout dispatching, to ensure the listeners list
    // is consistent, while we iterate over it. We don't have to worry about listeners
    // running for a long time while we have the lock, because the listeners will run
    // on a separate thread.
    synchronized (mListeners) {
      if (mListeners.containsKey(type)) {
        // Use a delegate to make sure callbacks happen on a specific thread.
        final EventCallback wrappedCallback = JavaCallbackDelegate.wrap(callback);

        // Event listeners will call | callback.sendError | if applicable.
        for (final BundleEventListener listener : mListeners.get(type)) {
          ThreadUtils.getUiHandler()
              .post(
                  new Runnable() {
                    @Override
                    public void run() {
                      final Double startTime = GeckoJavaSampler.tryToGetProfilerTime();
                      listener.handleMessage(type, message, wrappedCallback);
                      GeckoJavaSampler.addMarker(
                          "EventDispatcher handleMessage", startTime, null, type);
                    }
                  });
        }
        return true;
      }
    }

    if (!isGeckoReady) {
      // Usually, we discard an event if there is no listeners for it by
      // the time of the dispatch. However, if Gecko(View) is not ready and
      // there is no listener for this event that's possibly headed to
      // Gecko, we make a special exception to queue this event until
      // Gecko(View) is ready. This way, Gecko can first register its
      // listeners, and accept the event when it is ready.
      mNativeQueue.queueUntilReady(
          this,
          "dispatchToGecko",
          String.class,
          type,
          GeckoBundle.class,
          message,
          EventCallback.class,
          JavaCallbackDelegate.wrap(callback));
      return true;
    }

    // Named EventDispatchers use pending messages
    if (mName != null) {
      synchronized (mPendingMessages) {
        mPendingMessages.addLast(new Message(type, message, callback));
      }
      return true;
    }

    final String error = "No listener for " + type;
    if (callback != null) {
      callback.sendError(error);
    }

    Log.w(LOGTAG, error);
    return false;
  }

  @WrapForJNI
  public boolean hasListener(final String event) {
    synchronized (mListeners) {
      return mListeners.containsKey(event);
    }
  }

  @Override
  protected void finalize() throws Throwable {
    dispose(true);
  }

  private static class NativeCallbackDelegate extends JNIObject implements EventCallback {
    @WrapForJNI(calledFrom = "gecko")
    private NativeCallbackDelegate() {}

    @Override // JNIObject
    protected void disposeNative() {
      // We dispose in finalize().
      throw new UnsupportedOperationException();
    }

    @WrapForJNI(dispatchTo = "proxy")
    @Override // EventCallback
    public native void sendSuccess(Object response);

    @WrapForJNI(dispatchTo = "proxy")
    @Override // EventCallback
    public native void sendError(Object response);

    @WrapForJNI(dispatchTo = "gecko")
    @Override // Object
    protected native void finalize();
  }

  private static class JavaCallbackDelegate implements EventCallback {
    private final Thread mOriginalThread = Thread.currentThread();
    private final EventCallback mCallback;

    public static EventCallback wrap(final EventCallback callback) {
      if (callback == null) {
        return null;
      }
      if (callback instanceof NativeCallbackDelegate) {
        // NativeCallbackDelegate always posts to Gecko thread if needed.
        return callback;
      }
      return new JavaCallbackDelegate(callback);
    }

    JavaCallbackDelegate(final EventCallback callback) {
      mCallback = callback;
    }

    private void makeCallback(final boolean callSuccess, final Object rawResponse) {
      final Object response;
      if (rawResponse instanceof Number) {
        // There is ambiguity because a number can be converted to either int or
        // double, so e.g. the user can be expecting a double when we give it an
        // int. To avoid these pitfalls, we disallow all numbers. The workaround
        // is to wrap the number in a JS object / GeckoBundle, which supports
        // type coersion for numbers.
        throw new UnsupportedOperationException("Cannot use number as Java callback result");
      } else if (rawResponse != null && rawResponse.getClass().isArray()) {
        // Same with arrays.
        throw new UnsupportedOperationException("Cannot use arrays as Java callback result");
      } else if (rawResponse instanceof Character) {
        response = rawResponse.toString();
      } else {
        response = rawResponse;
      }

      // Call back synchronously if we happen to be on the same thread as the thread
      // making the original request.
      if (ThreadUtils.isOnThread(mOriginalThread)) {
        if (callSuccess) {
          mCallback.sendSuccess(response);
        } else {
          mCallback.sendError(response);
        }
        return;
      }

      // Make callback on the thread of the original request, if the original thread
      // is the UI or Gecko thread. Otherwise default to the background thread.
      final Handler handler =
          mOriginalThread == ThreadUtils.getUiThread()
              ? ThreadUtils.getUiHandler()
              : mOriginalThread == ThreadUtils.sGeckoThread
                  ? ThreadUtils.sGeckoHandler
                  : ThreadUtils.getBackgroundHandler();
      final EventCallback callback = mCallback;

      handler.post(
          new Runnable() {
            @Override
            public void run() {
              if (callSuccess) {
                callback.sendSuccess(response);
              } else {
                callback.sendError(response);
              }
            }
          });
    }

    @Override // EventCallback
    public void sendSuccess(final Object response) {
      makeCallback(/* success */ true, response);
    }

    @Override // EventCallback
    public void sendError(final Object response) {
      makeCallback(/* success */ false, response);
    }
  }
}