summaryrefslogtreecommitdiffstats
path: root/mobile/android/geckoview/src/main/java/org/mozilla/gecko/NativeQueue.java
blob: 7932e6c8390e8c4027099291617b6484387d73a3 (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
/* -*- 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 java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

public class NativeQueue {
  private static final String LOGTAG = "GeckoNativeQueue";

  public interface State {
    boolean is(final State other);

    boolean isAtLeast(final State other);
  }

  private volatile State mState;
  private final State mReadyState;

  public NativeQueue(final State initial, final State ready) {
    mState = initial;
    mReadyState = ready;
  }

  public boolean isReady() {
    return getState().isAtLeast(mReadyState);
  }

  public State getState() {
    return mState;
  }

  public boolean setState(final State newState) {
    return checkAndSetState(null, newState);
  }

  public synchronized boolean checkAndSetState(final State expectedState, final State newState) {
    if (expectedState != null && !mState.is(expectedState)) {
      return false;
    }
    flushQueuedLocked(newState);
    mState = newState;
    return true;
  }

  private static class QueuedCall {
    public Method method;
    public Object target;
    public Object[] args;
    public State state;

    public QueuedCall(
        final Method method, final Object target, final Object[] args, final State state) {
      this.method = method;
      this.target = target;
      this.args = args;
      this.state = state;
    }
  }

  private static final int QUEUED_CALLS_COUNT = 16;
  /* package */ final ArrayList<QueuedCall> mQueue = new ArrayList<>(QUEUED_CALLS_COUNT);

  // Invoke the given Method and handle checked Exceptions.
  private static void invokeMethod(final Method method, final Object obj, final Object[] args) {
    try {
      method.setAccessible(true);
      method.invoke(obj, args);
    } catch (final IllegalAccessException e) {
      throw new IllegalStateException("Unexpected exception", e);
    } catch (final InvocationTargetException e) {
      throw new UnsupportedOperationException("Cannot make call", e.getCause());
    }
  }

  // Queue a call to the given method.
  private void queueNativeCallLocked(
      final Class<?> cls,
      final String methodName,
      final Object obj,
      final Object[] args,
      final State state) {
    final ArrayList<Class<?>> argTypes = new ArrayList<>(args.length);
    final ArrayList<Object> argValues = new ArrayList<>(args.length);

    for (int i = 0; i < args.length; i++) {
      if (args[i] instanceof Class) {
        argTypes.add((Class<?>) args[i]);
        argValues.add(args[++i]);
        continue;
      }
      Class<?> argType = args[i].getClass();
      if (argType == Boolean.class) argType = Boolean.TYPE;
      else if (argType == Byte.class) argType = Byte.TYPE;
      else if (argType == Character.class) argType = Character.TYPE;
      else if (argType == Double.class) argType = Double.TYPE;
      else if (argType == Float.class) argType = Float.TYPE;
      else if (argType == Integer.class) argType = Integer.TYPE;
      else if (argType == Long.class) argType = Long.TYPE;
      else if (argType == Short.class) argType = Short.TYPE;
      argTypes.add(argType);
      argValues.add(args[i]);
    }
    final Method method;
    try {
      method = cls.getDeclaredMethod(methodName, argTypes.toArray(new Class<?>[argTypes.size()]));
    } catch (final NoSuchMethodException e) {
      throw new IllegalArgumentException("Cannot find method", e);
    }

    if (!Modifier.isNative(method.getModifiers())) {
      // As a precaution, we disallow queuing non-native methods. Queuing non-native
      // methods is dangerous because the method could end up being called on either
      // the original thread or the Gecko thread depending on timing. Native methods
      // usually handle this by posting an event to the Gecko thread automatically,
      // but there is no automatic mechanism for non-native methods.
      throw new UnsupportedOperationException("Not allowed to queue non-native methods");
    }

    if (getState().isAtLeast(state)) {
      invokeMethod(method, obj, argValues.toArray());
      return;
    }

    mQueue.add(new QueuedCall(method, obj, argValues.toArray(), state));
  }

  /**
   * Queue a call to the given instance method if the given current state does not satisfy the
   * isReady condition.
   *
   * @param obj Object that declares the instance method.
   * @param methodName Name of the instance method.
   * @param args Args to call the instance method with; to specify a parameter type, pass in a Class
   *     instance first, followed by the value.
   */
  public synchronized void queueUntilReady(
      final Object obj, final String methodName, final Object... args) {
    queueNativeCallLocked(obj.getClass(), methodName, obj, args, mReadyState);
  }

  /**
   * Queue a call to the given static method if the given current state does not satisfy the isReady
   * condition.
   *
   * @param cls Class that declares the static method.
   * @param methodName Name of the instance method.
   * @param args Args to call the instance method with; to specify a parameter type, pass in a Class
   *     instance first, followed by the value.
   */
  public synchronized void queueUntilReady(
      final Class<?> cls, final String methodName, final Object... args) {
    queueNativeCallLocked(cls, methodName, null, args, mReadyState);
  }

  /**
   * Queue a call to the given instance method if the given current state does not satisfy the given
   * state.
   *
   * @param state The state in which the native call could be executed.
   * @param obj Object that declares the instance method.
   * @param methodName Name of the instance method.
   * @param args Args to call the instance method with; to specify a parameter type, pass in a Class
   *     instance first, followed by the value.
   */
  public synchronized void queueUntil(
      final State state, final Object obj, final String methodName, final Object... args) {
    queueNativeCallLocked(obj.getClass(), methodName, obj, args, state);
  }

  /**
   * Queue a call to the given static method if the given current state does not satisfy the given
   * state.
   *
   * @param state The state in which the native call could be executed.
   * @param cls Class that declares the static method.
   * @param methodName Name of the instance method.
   * @param args Args to call the instance method with; to specify a parameter type, pass in a Class
   *     instance first, followed by the value.
   */
  public synchronized void queueUntil(
      final State state, final Class<?> cls, final String methodName, final Object... args) {
    queueNativeCallLocked(cls, methodName, null, args, state);
  }

  // Run all queued methods
  private void flushQueuedLocked(final State state) {
    int lastSkipped = -1;
    for (int i = 0; i < mQueue.size(); i++) {
      final QueuedCall call = mQueue.get(i);
      if (call == null) {
        // We already handled the call.
        continue;
      }
      if (!state.isAtLeast(call.state)) {
        // The call is not ready yet; skip it.
        lastSkipped = i;
        continue;
      }
      // Mark as handled.
      mQueue.set(i, null);

      invokeMethod(call.method, call.target, call.args);
    }
    if (lastSkipped < 0) {
      // We're done here; release the memory
      mQueue.clear();
    } else if (lastSkipped < mQueue.size() - 1) {
      // We skipped some; free up null entries at the end,
      // but keep all the previous entries for later.
      mQueue.subList(lastSkipped + 1, mQueue.size()).clear();
    }
  }

  public synchronized void reset(final State initial) {
    mQueue.clear();
    mState = initial;
  }
}