File: MultiClientInputMethodClientCallbackAdaptor.java

package info (click to toggle)
android-platform-frameworks-base 1%3A10.0.0%2Br36-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 321,788 kB
  • sloc: java: 962,234; cpp: 274,314; xml: 242,770; python: 5,060; sh: 1,432; ansic: 494; makefile: 47; sed: 19
file content (475 lines) | stat: -rw-r--r-- 18,042 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.inputmethodservice;

import android.annotation.Nullable;
import android.annotation.WorkerThread;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Looper;
import android.os.ResultReceiver;
import android.util.Log;
import android.view.InputChannel;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.InputEventReceiver;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowManager.LayoutParams.SoftInputModeFlags;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.CursorAnchorInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;

import com.android.internal.annotations.GuardedBy;
import com.android.internal.inputmethod.IMultiClientInputMethodSession;
import com.android.internal.os.SomeArgs;
import com.android.internal.util.function.pooled.PooledLambda;
import com.android.internal.view.IInputContext;
import com.android.internal.view.IInputMethodSession;
import com.android.internal.view.InputConnectionWrapper;

import java.lang.ref.WeakReference;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Re-dispatches all the incoming per-client events to the specified {@link Looper} thread.
 *
 * <p>There are three types of per-client callbacks.</p>
 *
 * <ul>
 *     <li>{@link IInputMethodSession} - from the IME client</li>
 *     <li>{@link IMultiClientInputMethodSession} - from MultiClientInputMethodManagerService</li>
 *     <li>{@link InputChannel} - from the IME client</li>
 * </ul>
 *
 * <p>This class serializes all the incoming events among those channels onto
 * {@link MultiClientInputMethodServiceDelegate.ClientCallback} on the specified {@link Looper}
 * thread.</p>
 */
final class MultiClientInputMethodClientCallbackAdaptor {
    static final boolean DEBUG = false;
    static final String TAG = MultiClientInputMethodClientCallbackAdaptor.class.getSimpleName();

    private final Object mSessionLock = new Object();
    @GuardedBy("mSessionLock")
    CallbackImpl mCallbackImpl;
    @GuardedBy("mSessionLock")
    InputChannel mReadChannel;
    @GuardedBy("mSessionLock")
    KeyEvent.DispatcherState mDispatcherState;
    @GuardedBy("mSessionLock")
    Handler mHandler;
    @GuardedBy("mSessionLock")
    @Nullable
    InputEventReceiver mInputEventReceiver;

    private final AtomicBoolean mFinished = new AtomicBoolean(false);

    IInputMethodSession.Stub createIInputMethodSession() {
        synchronized (mSessionLock) {
            return new InputMethodSessionImpl(
                    mSessionLock, mCallbackImpl, mHandler, mFinished);
        }
    }

    IMultiClientInputMethodSession.Stub createIMultiClientInputMethodSession() {
        synchronized (mSessionLock) {
            return new MultiClientInputMethodSessionImpl(
                    mSessionLock, mCallbackImpl, mHandler, mFinished);
        }
    }

    MultiClientInputMethodClientCallbackAdaptor(
            MultiClientInputMethodServiceDelegate.ClientCallback clientCallback, Looper looper,
            KeyEvent.DispatcherState dispatcherState, InputChannel readChannel) {
        synchronized (mSessionLock) {
            mCallbackImpl = new CallbackImpl(this, clientCallback);
            mDispatcherState = dispatcherState;
            mHandler = new Handler(looper, null, true);
            mReadChannel = readChannel;
            mInputEventReceiver = new ImeInputEventReceiver(mReadChannel, mHandler.getLooper(),
                    mFinished, mDispatcherState, mCallbackImpl.mOriginalCallback);
        }
    }

    private static final class KeyEventCallbackAdaptor implements KeyEvent.Callback {
        private final MultiClientInputMethodServiceDelegate.ClientCallback mLocalCallback;

        KeyEventCallbackAdaptor(
                MultiClientInputMethodServiceDelegate.ClientCallback callback) {
            mLocalCallback = callback;
        }

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            return mLocalCallback.onKeyDown(keyCode, event);
        }

        @Override
        public boolean onKeyLongPress(int keyCode, KeyEvent event) {
            return mLocalCallback.onKeyLongPress(keyCode, event);
        }

        @Override
        public boolean onKeyUp(int keyCode, KeyEvent event) {
            return mLocalCallback.onKeyUp(keyCode, event);
        }

        @Override
        public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) {
            return mLocalCallback.onKeyMultiple(keyCode, event);
        }
    }

    private static final class ImeInputEventReceiver extends InputEventReceiver {
        private final AtomicBoolean mFinished;
        private final KeyEvent.DispatcherState mDispatcherState;
        private final MultiClientInputMethodServiceDelegate.ClientCallback mClientCallback;
        private final KeyEventCallbackAdaptor mKeyEventCallbackAdaptor;

        ImeInputEventReceiver(InputChannel readChannel, Looper looper, AtomicBoolean finished,
                KeyEvent.DispatcherState dispatcherState,
                MultiClientInputMethodServiceDelegate.ClientCallback callback) {
            super(readChannel, looper);
            mFinished = finished;
            mDispatcherState = dispatcherState;
            mClientCallback = callback;
            mKeyEventCallbackAdaptor = new KeyEventCallbackAdaptor(callback);
        }

        @Override
        public void onInputEvent(InputEvent event) {
            if (mFinished.get()) {
                // The session has been finished.
                finishInputEvent(event, false);
                return;
            }
            boolean handled = false;
            try {
                if (event instanceof KeyEvent) {
                    final KeyEvent keyEvent = (KeyEvent) event;
                    handled = keyEvent.dispatch(mKeyEventCallbackAdaptor, mDispatcherState,
                            mKeyEventCallbackAdaptor);
                } else {
                    final MotionEvent motionEvent = (MotionEvent) event;
                    if (motionEvent.isFromSource(InputDevice.SOURCE_CLASS_TRACKBALL)) {
                        handled = mClientCallback.onTrackballEvent(motionEvent);
                    } else {
                        handled = mClientCallback.onGenericMotionEvent(motionEvent);
                    }
                }
            } finally {
                finishInputEvent(event, handled);
            }
        }
    }

    private static final class InputMethodSessionImpl extends IInputMethodSession.Stub {
        private final Object mSessionLock;
        @GuardedBy("mSessionLock")
        private CallbackImpl mCallbackImpl;
        @GuardedBy("mSessionLock")
        private Handler mHandler;
        private final AtomicBoolean mSessionFinished;

        InputMethodSessionImpl(Object lock, CallbackImpl callback, Handler handler,
                AtomicBoolean sessionFinished) {
            mSessionLock = lock;
            mCallbackImpl = callback;
            mHandler = handler;
            mSessionFinished = sessionFinished;
        }

        @Override
        public void updateExtractedText(int token, ExtractedText text) {
            reportNotSupported();
        }

        @Override
        public void updateSelection(int oldSelStart, int oldSelEnd,
                int newSelStart, int newSelEnd,
                int candidatesStart, int candidatesEnd) {
            synchronized (mSessionLock) {
                if (mCallbackImpl == null || mHandler == null) {
                    return;
                }
                final SomeArgs args = SomeArgs.obtain();
                args.argi1 = oldSelStart;
                args.argi2 = oldSelEnd;
                args.argi3 = newSelStart;
                args.argi4 = newSelEnd;
                args.argi5 = candidatesStart;
                args.argi6 = candidatesEnd;
                mHandler.sendMessage(PooledLambda.obtainMessage(
                        CallbackImpl::updateSelection, mCallbackImpl, args));
            }
        }

        @Override
        public void viewClicked(boolean focusChanged) {
            reportNotSupported();
        }

        @Override
        public void updateCursor(Rect newCursor) {
            reportNotSupported();
        }

        @Override
        public void displayCompletions(CompletionInfo[] completions) {
            synchronized (mSessionLock) {
                if (mCallbackImpl == null || mHandler == null) {
                    return;
                }
                mHandler.sendMessage(PooledLambda.obtainMessage(
                        CallbackImpl::displayCompletions, mCallbackImpl, completions));
            }
        }

        @Override
        public void appPrivateCommand(String action, Bundle data) {
            synchronized (mSessionLock) {
                if (mCallbackImpl == null || mHandler == null) {
                    return;
                }
                mHandler.sendMessage(PooledLambda.obtainMessage(
                        CallbackImpl::appPrivateCommand, mCallbackImpl, action, data));
            }
        }

        @Override
        public void toggleSoftInput(int showFlags, int hideFlags) {
            synchronized (mSessionLock) {
                if (mCallbackImpl == null || mHandler == null) {
                    return;
                }
                mHandler.sendMessage(PooledLambda.obtainMessage(
                        CallbackImpl::toggleSoftInput, mCallbackImpl, showFlags,
                        hideFlags));
            }
        }

        @Override
        public void finishSession() {
            synchronized (mSessionLock) {
                if (mCallbackImpl == null || mHandler == null) {
                    return;
                }
                mSessionFinished.set(true);
                mHandler.sendMessage(PooledLambda.obtainMessage(
                        CallbackImpl::finishSession, mCallbackImpl));
                mCallbackImpl = null;
                mHandler = null;
            }
        }

        @Override
        public void updateCursorAnchorInfo(CursorAnchorInfo info) {
            synchronized (mSessionLock) {
                if (mCallbackImpl == null || mHandler == null) {
                    return;
                }
                mHandler.sendMessage(PooledLambda.obtainMessage(
                        CallbackImpl::updateCursorAnchorInfo, mCallbackImpl, info));
            }
        }

        @Override
        public final void notifyImeHidden() {
            // no-op for multi-session since IME is responsible controlling navigation bar buttons.
            reportNotSupported();
        }
    }

    private static final class MultiClientInputMethodSessionImpl
            extends IMultiClientInputMethodSession.Stub {
        private final Object mSessionLock;
        @GuardedBy("mSessionLock")
        private CallbackImpl mCallbackImpl;
        @GuardedBy("mSessionLock")
        private Handler mHandler;
        private final AtomicBoolean mSessionFinished;

        MultiClientInputMethodSessionImpl(Object lock, CallbackImpl callback,
                Handler handler, AtomicBoolean sessionFinished) {
            mSessionLock = lock;
            mCallbackImpl = callback;
            mHandler = handler;
            mSessionFinished = sessionFinished;
        }

        @Override
        public void startInputOrWindowGainedFocus(@Nullable IInputContext inputContext,
                int missingMethods, @Nullable EditorInfo editorInfo, int controlFlags,
                @SoftInputModeFlags int softInputMode, int windowHandle) {
            synchronized (mSessionLock) {
                if (mCallbackImpl == null || mHandler == null) {
                    return;
                }
                final SomeArgs args = SomeArgs.obtain();
                // TODO(Bug 119211536): Remove dependency on AbstractInputMethodService from ICW
                final WeakReference<AbstractInputMethodService> fakeIMS =
                        new WeakReference<>(null);
                args.arg1 = (inputContext == null) ? null
                        : new InputConnectionWrapper(fakeIMS, inputContext, missingMethods,
                                mSessionFinished);
                args.arg2 = editorInfo;
                args.argi1 = controlFlags;
                args.argi2 = softInputMode;
                args.argi3 = windowHandle;
                mHandler.sendMessage(PooledLambda.obtainMessage(
                        CallbackImpl::startInputOrWindowGainedFocus, mCallbackImpl, args));
            }
        }

        @Override
        public void showSoftInput(int flags, ResultReceiver resultReceiver) {
            synchronized (mSessionLock) {
                if (mCallbackImpl == null || mHandler == null) {
                    return;
                }
                mHandler.sendMessage(PooledLambda.obtainMessage(
                        CallbackImpl::showSoftInput, mCallbackImpl, flags,
                        resultReceiver));
            }
        }

        @Override
        public void hideSoftInput(int flags, ResultReceiver resultReceiver) {
            synchronized (mSessionLock) {
                if (mCallbackImpl == null || mHandler == null) {
                    return;
                }
                mHandler.sendMessage(PooledLambda.obtainMessage(
                        CallbackImpl::hideSoftInput, mCallbackImpl, flags,
                        resultReceiver));
            }
        }
    }

    /**
     * The maim part of adaptor to {@link MultiClientInputMethodServiceDelegate.ClientCallback}.
     */
    @WorkerThread
    private static final class CallbackImpl {
        private final MultiClientInputMethodClientCallbackAdaptor mCallbackAdaptor;
        private final MultiClientInputMethodServiceDelegate.ClientCallback mOriginalCallback;
        private boolean mFinished = false;

        CallbackImpl(MultiClientInputMethodClientCallbackAdaptor callbackAdaptor,
                MultiClientInputMethodServiceDelegate.ClientCallback callback) {
            mCallbackAdaptor = callbackAdaptor;
            mOriginalCallback = callback;
        }

        void updateSelection(SomeArgs args) {
            try {
                if (mFinished) {
                    return;
                }
                mOriginalCallback.onUpdateSelection(args.argi1, args.argi2, args.argi3,
                        args.argi4, args.argi5, args.argi6);
            } finally {
                args.recycle();
            }
        }

        void displayCompletions(CompletionInfo[] completions) {
            if (mFinished) {
                return;
            }
            mOriginalCallback.onDisplayCompletions(completions);
        }

        void appPrivateCommand(String action, Bundle data) {
            if (mFinished) {
                return;
            }
            mOriginalCallback.onAppPrivateCommand(action, data);
        }

        void toggleSoftInput(int showFlags, int hideFlags) {
            if (mFinished) {
                return;
            }
            mOriginalCallback.onToggleSoftInput(showFlags, hideFlags);
        }

        void finishSession() {
            if (mFinished) {
                return;
            }
            mFinished = true;
            mOriginalCallback.onFinishSession();
            synchronized (mCallbackAdaptor.mSessionLock) {
                mCallbackAdaptor.mDispatcherState = null;
                if (mCallbackAdaptor.mReadChannel != null) {
                    mCallbackAdaptor.mReadChannel.dispose();
                    mCallbackAdaptor.mReadChannel = null;
                }
                mCallbackAdaptor.mInputEventReceiver = null;
            }
        }

        void updateCursorAnchorInfo(CursorAnchorInfo info) {
            if (mFinished) {
                return;
            }
            mOriginalCallback.onUpdateCursorAnchorInfo(info);
        }

        void startInputOrWindowGainedFocus(SomeArgs args) {
            try {
                if (mFinished) {
                    return;
                }
                final InputConnectionWrapper inputConnection = (InputConnectionWrapper) args.arg1;
                final EditorInfo editorInfo = (EditorInfo) args.arg2;
                final int startInputFlags = args.argi1;
                final int softInputMode = args.argi2;
                final int windowHandle = args.argi3;
                mOriginalCallback.onStartInputOrWindowGainedFocus(inputConnection, editorInfo,
                        startInputFlags, softInputMode, windowHandle);
            } finally {
                args.recycle();
            }
        }

        void showSoftInput(int flags, ResultReceiver resultReceiver) {
            if (mFinished) {
                return;
            }
            mOriginalCallback.onShowSoftInput(flags, resultReceiver);
        }

        void hideSoftInput(int flags, ResultReceiver resultReceiver) {
            if (mFinished) {
                return;
            }
            mOriginalCallback.onHideSoftInput(flags, resultReceiver);
        }
    }

    private static void reportNotSupported() {
        if (DEBUG) {
            Log.d(TAG, Debug.getCaller() + " is not supported");
        }
    }
}