summaryrefslogtreecommitdiffstats
path: root/mobile/android/geckoview/src/main/java/org/mozilla/geckoview/SessionTextInput.java
blob: f5e6c6976c66e6675de568faa6e2c08be208d34a (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
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
 * 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.geckoview;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.RectF;
import android.os.Handler;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.CursorAnchorInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import androidx.annotation.AnyThread;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.mozilla.gecko.IGeckoEditableParent;
import org.mozilla.gecko.InputMethods;
import org.mozilla.gecko.NativeQueue;
import org.mozilla.gecko.annotation.WrapForJNI;
import org.mozilla.gecko.util.ThreadUtils;

/**
 * {@code SessionTextInput} handles text input for {@code GeckoSession} through key events or input
 * methods. It is typically used to implement certain methods in {@link android.view.View} such as
 * {@link android.view.View#onCreateInputConnection}, by forwarding such calls to corresponding
 * methods in {@code SessionTextInput}.
 *
 * <p>For full functionality, {@code SessionTextInput} requires a {@link android.view.View} to be
 * set first through {@link #setView}. When a {@link android.view.View} is not set or set to null,
 * {@code SessionTextInput} will operate in a reduced functionality mode. See {@link
 * #onCreateInputConnection} and methods in {@link GeckoSession.TextInputDelegate} for changes in
 * behavior in this viewless mode.
 */
public final class SessionTextInput {
  /* package */ static final String LOGTAG = "GeckoSessionTextInput";
  private static final boolean DEBUG = false;

  // Interface to access GeckoInputConnection from SessionTextInput.
  /* package */ interface InputConnectionClient {
    View getView();

    Handler getHandler(Handler defHandler);

    InputConnection onCreateInputConnection(EditorInfo attrs);
  }

  // Interface to access GeckoEditable from GeckoInputConnection.
  /* package */ interface EditableClient {
    // The following value is used by requestCursorUpdates
    // ONE_SHOT calls updateCompositionRects() after getting current composing
    // character rects.
    @Retention(RetentionPolicy.SOURCE)
    @IntDef({ONE_SHOT, START_MONITOR, END_MONITOR})
    /* package */ @interface CursorMonitorMode {}

    @WrapForJNI static final int ONE_SHOT = 1;
    // START_MONITOR start the monitor for composing character rects.  If is is
    // updaed,  call updateCompositionRects()
    @WrapForJNI static final int START_MONITOR = 2;
    // ENDT_MONITOR stops the monitor for composing character rects.
    @WrapForJNI static final int END_MONITOR = 3;

    void sendKeyEvent(@Nullable View view, int action, @NonNull KeyEvent event);

    Editable getEditable();

    void setBatchMode(boolean isBatchMode);

    Handler setInputConnectionHandler(@NonNull Handler handler);

    void postToInputConnection(@NonNull Runnable runnable);

    void requestCursorUpdates(@CursorMonitorMode int requestMode);

    void insertImage(@NonNull byte[] data, @NonNull String mimeType);
  }

  // Interface to access GeckoInputConnection from GeckoEditable.
  /* package */ interface EditableListener {
    // IME notification type for notifyIME(), corresponding to NotificationToIME enum.
    @Retention(RetentionPolicy.SOURCE)
    @IntDef({
      NOTIFY_IME_OF_TOKEN,
      NOTIFY_IME_OPEN_VKB,
      NOTIFY_IME_REPLY_EVENT,
      NOTIFY_IME_OF_FOCUS,
      NOTIFY_IME_OF_BLUR,
      NOTIFY_IME_TO_COMMIT_COMPOSITION,
      NOTIFY_IME_TO_CANCEL_COMPOSITION
    })
    /* package */ @interface IMENotificationType {}

    @WrapForJNI static final int NOTIFY_IME_OF_TOKEN = -3;
    @WrapForJNI static final int NOTIFY_IME_OPEN_VKB = -2;
    @WrapForJNI static final int NOTIFY_IME_REPLY_EVENT = -1;
    @WrapForJNI static final int NOTIFY_IME_OF_FOCUS = 1;
    @WrapForJNI static final int NOTIFY_IME_OF_BLUR = 2;
    @WrapForJNI static final int NOTIFY_IME_TO_COMMIT_COMPOSITION = 8;
    @WrapForJNI static final int NOTIFY_IME_TO_CANCEL_COMPOSITION = 9;

    // IME enabled state for notifyIMEContext().
    @Retention(RetentionPolicy.SOURCE)
    @IntDef({IME_STATE_UNKNOWN, IME_STATE_DISABLED, IME_STATE_ENABLED, IME_STATE_PASSWORD})
    /* package */ @interface IMEState {}

    static final int IME_STATE_UNKNOWN = -1;
    static final int IME_STATE_DISABLED = 0;
    static final int IME_STATE_ENABLED = 1;
    static final int IME_STATE_PASSWORD = 2;

    // Flags for notifyIMEContext().
    @Retention(RetentionPolicy.SOURCE)
    @IntDef(
        flag = true,
        value = {IME_FLAG_PRIVATE_BROWSING, IME_FLAG_USER_ACTION, IME_FOCUS_NOT_CHANGED})
    /* package */ @interface IMEContextFlags {}

    @WrapForJNI static final int IME_FLAG_PRIVATE_BROWSING = 1 << 0;
    @WrapForJNI static final int IME_FLAG_USER_ACTION = 1 << 1;
    @WrapForJNI static final int IME_FOCUS_NOT_CHANGED = 1 << 2;

    void notifyIME(@IMENotificationType int type);

    void notifyIMEContext(
        @IMEState int state,
        String typeHint,
        String modeHint,
        String actionHint,
        @IMEContextFlags int flag);

    void onSelectionChange();

    void onTextChange();

    void onDiscardComposition();

    void onDefaultKeyEvent(KeyEvent event);

    void updateCompositionRects(final RectF[] aRects, final RectF aCaretRect);
  }

  private static final class DefaultDelegate implements GeckoSession.TextInputDelegate {
    public static final DefaultDelegate INSTANCE = new DefaultDelegate();

    private InputMethodManager getInputMethodManager(@Nullable final View view) {
      if (view == null) {
        return null;
      }
      return (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    @Override
    public void restartInput(@NonNull final GeckoSession session, final int reason) {
      ThreadUtils.assertOnUiThread();
      final View view = session.getTextInput().getView();

      final InputMethodManager imm = getInputMethodManager(view);
      if (imm == null) {
        return;
      }

      // InputMethodManager has internal logic to detect if we are restarting input
      // in an already focused View, which is the case here because all content text
      // fields are inside one LayerView. When this happens, InputMethodManager will
      // tell the input method to soft reset instead of hard reset. Stock latin IME
      // on Android 4.2+ has a quirk that when it soft resets, it does not clear the
      // composition. The following workaround tricks the IME into clearing the
      // composition when soft resetting.
      if (InputMethods.needsSoftResetWorkaround(
          InputMethods.getCurrentInputMethod(view.getContext()))) {
        // Fake a selection change, because the IME clears the composition when
        // the selection changes, even if soft-resetting. Offsets here must be
        // different from the previous selection offsets, and -1 seems to be a
        // reasonable, deterministic value
        imm.updateSelection(view, -1, -1, -1, -1);
      }

      try {
        imm.restartInput(view);
      } catch (final RuntimeException e) {
        Log.e(LOGTAG, "Error restarting input", e);
      }
    }

    @Override
    public void showSoftInput(@NonNull final GeckoSession session) {
      ThreadUtils.assertOnUiThread();
      final View view = session.getTextInput().getView();
      final InputMethodManager imm = getInputMethodManager(view);
      if (imm != null) {
        if (view.hasFocus() && !imm.isActive(view)) {
          // Marshmallow workaround: The view has focus but it is not the active
          // view for the input method. (Bug 1211848)
          view.clearFocus();
          view.requestFocus();
        }
        imm.showSoftInput(view, 0);
      }
    }

    @Override
    public void hideSoftInput(@NonNull final GeckoSession session) {
      ThreadUtils.assertOnUiThread();
      final View view = session.getTextInput().getView();
      final InputMethodManager imm = getInputMethodManager(view);
      if (imm != null) {
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
      }
    }

    @Override
    public void updateSelection(
        @NonNull final GeckoSession session,
        final int selStart,
        final int selEnd,
        final int compositionStart,
        final int compositionEnd) {
      ThreadUtils.assertOnUiThread();
      final View view = session.getTextInput().getView();
      final InputMethodManager imm = getInputMethodManager(view);
      if (imm != null) {
        // When composition start and end is -1,
        // InputMethodManager.updateSelection will remove composition
        // on most IMEs. If not working, we have to add a workaround
        // to EditableListener.onDiscardComposition.
        imm.updateSelection(view, selStart, selEnd, compositionStart, compositionEnd);
      }
    }

    @Override
    public void updateExtractedText(
        @NonNull final GeckoSession session,
        @NonNull final ExtractedTextRequest request,
        @NonNull final ExtractedText text) {
      ThreadUtils.assertOnUiThread();
      final View view = session.getTextInput().getView();
      final InputMethodManager imm = getInputMethodManager(view);
      if (imm != null) {
        imm.updateExtractedText(view, request.token, text);
      }
    }

    @TargetApi(21)
    @Override
    public void updateCursorAnchorInfo(
        @NonNull final GeckoSession session, @NonNull final CursorAnchorInfo info) {
      ThreadUtils.assertOnUiThread();
      final View view = session.getTextInput().getView();
      final InputMethodManager imm = getInputMethodManager(view);
      if (imm != null) {
        imm.updateCursorAnchorInfo(view, info);
      }
    }
  }

  private final GeckoSession mSession;
  private final NativeQueue mQueue;
  private final GeckoEditable mEditable;
  private InputConnectionClient mInputConnection;
  private GeckoSession.TextInputDelegate mDelegate;

  /* package */ SessionTextInput(
      final @NonNull GeckoSession session, final @NonNull NativeQueue queue) {
    mSession = session;
    mQueue = queue;
    mEditable = new GeckoEditable(session);
  }

  /* package */ void onWindowChanged(final GeckoSession.Window window) {
    if (mQueue.isReady()) {
      window.attachEditable(mEditable);
    } else {
      mQueue.queueUntilReady(window, "attachEditable", IGeckoEditableParent.class, mEditable);
    }
  }

  /**
   * Get a Handler for the background input method thread. In order to use a background thread for
   * input method operations on systems prior to Nougat, first override {@code View.getHandler()}
   * for the View returning the InputConnection instance, and then call this method from the
   * overridden method.
   *
   * <p>For example:
   *
   * <pre>
   * &#64;Override
   * public Handler getHandler() {
   *     if (Build.VERSION.SDK_INT &gt;= 24) {
   *         return super.getHandler();
   *     }
   *     return getSession().getTextInput().getHandler(super.getHandler());
   * }</pre>
   *
   * @param defHandler Handler returned by the system {@code getHandler} implementation.
   * @return Handler to return to the system through {@code getHandler}.
   */
  @AnyThread
  public synchronized @NonNull Handler getHandler(final @NonNull Handler defHandler) {
    // May be called on any thread.
    if (mInputConnection != null) {
      return mInputConnection.getHandler(defHandler);
    }
    return defHandler;
  }

  /**
   * Get the current {@link android.view.View} for text input.
   *
   * @return Current text input View or null if not set.
   * @see #setView(View)
   */
  @UiThread
  public @Nullable View getView() {
    ThreadUtils.assertOnUiThread();
    return mInputConnection != null ? mInputConnection.getView() : null;
  }

  /**
   * Set the current {@link android.view.View} for text input. The {@link android.view.View} is used
   * to interact with the system input method manager and to display certain text input UI elements.
   * See the {@code SessionTextInput} class documentation for information on viewless mode, when the
   * current {@link android.view.View} is not set or set to null.
   *
   * @param view Text input View or null to clear current View.
   * @see #getView()
   */
  @UiThread
  public synchronized void setView(final @Nullable View view) {
    ThreadUtils.assertOnUiThread();

    if (view == null) {
      mInputConnection = null;
    } else if (mInputConnection == null || mInputConnection.getView() != view) {
      mInputConnection = GeckoInputConnection.create(mSession, view, mEditable);
    }
    mEditable.setListener((EditableListener) mInputConnection);
  }

  /**
   * Get an {@link android.view.inputmethod.InputConnection} instance. In viewless mode, this method
   * still fills out the {@link android.view.inputmethod.EditorInfo} object, but the return value
   * will always be null.
   *
   * @param attrs EditorInfo instance to be filled on return.
   * @return InputConnection instance, or null if there is no active input (or if in viewless mode).
   */
  @AnyThread
  public synchronized @Nullable InputConnection onCreateInputConnection(
      final @NonNull EditorInfo attrs) {
    // May be called on any thread.
    mEditable.onCreateInputConnection(attrs);

    if (!mQueue.isReady() || mInputConnection == null) {
      return null;
    }
    return mInputConnection.onCreateInputConnection(attrs);
  }

  /**
   * Process a KeyEvent as a pre-IME event.
   *
   * @param keyCode Key code.
   * @param event KeyEvent instance.
   * @return True if the event was handled.
   */
  @UiThread
  public boolean onKeyPreIme(final int keyCode, final @NonNull KeyEvent event) {
    ThreadUtils.assertOnUiThread();
    return mEditable.onKeyPreIme(getView(), keyCode, event);
  }

  /**
   * Process a KeyEvent as a key-down event.
   *
   * @param keyCode Key code.
   * @param event KeyEvent instance.
   * @return True if the event was handled.
   */
  @UiThread
  public boolean onKeyDown(final int keyCode, final @NonNull KeyEvent event) {
    ThreadUtils.assertOnUiThread();
    return mEditable.onKeyDown(getView(), keyCode, event);
  }

  /**
   * Process a KeyEvent as a key-up event.
   *
   * @param keyCode Key code.
   * @param event KeyEvent instance.
   * @return True if the event was handled.
   */
  @UiThread
  public boolean onKeyUp(final int keyCode, final @NonNull KeyEvent event) {
    ThreadUtils.assertOnUiThread();
    return mEditable.onKeyUp(getView(), keyCode, event);
  }

  /**
   * Process a KeyEvent as a long-press event.
   *
   * @param keyCode Key code.
   * @param event KeyEvent instance.
   * @return True if the event was handled.
   */
  @UiThread
  public boolean onKeyLongPress(final int keyCode, final @NonNull KeyEvent event) {
    ThreadUtils.assertOnUiThread();
    return mEditable.onKeyLongPress(getView(), keyCode, event);
  }

  /**
   * Process a KeyEvent as a multiple-press event.
   *
   * @param keyCode Key code.
   * @param repeatCount Key repeat count.
   * @param event KeyEvent instance.
   * @return True if the event was handled.
   */
  @UiThread
  public boolean onKeyMultiple(
      final int keyCode, final int repeatCount, final @NonNull KeyEvent event) {
    ThreadUtils.assertOnUiThread();
    return mEditable.onKeyMultiple(getView(), keyCode, repeatCount, event);
  }

  /**
   * Set the current text input delegate.
   *
   * @param delegate TextInputDelegate instance or null to restore to default.
   */
  @UiThread
  public void setDelegate(@Nullable final GeckoSession.TextInputDelegate delegate) {
    ThreadUtils.assertOnUiThread();
    mDelegate = delegate;
  }

  /**
   * Get the current text input delegate.
   *
   * @return TextInputDelegate instance or a default instance if no delegate has been set.
   */
  @UiThread
  public @NonNull GeckoSession.TextInputDelegate getDelegate() {
    ThreadUtils.assertOnUiThread();
    if (mDelegate == null) {
      mDelegate = DefaultDelegate.INSTANCE;
    }
    return mDelegate;
  }
}