summaryrefslogtreecommitdiffstats
path: root/services/java/com/android/server/gesture/EdgeGestureInputFilter.java
blob: c42b7d098b45d6efa231b601906535d18c99c40c (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
/*
 * Copyright (C) 2013 The CyanogenMod Project (Jens Doll)
 *
 * 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 com.android.server.gesture;

import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.Trace;
import android.util.Slog;
import android.view.Display;
import android.view.DisplayInfo;
import android.view.IInputFilter;
import android.view.IInputFilterHost;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.MotionEvent;
import android.view.WindowManagerPolicy;
import android.view.MotionEvent.PointerCoords;
import android.view.MotionEvent.PointerProperties;

import com.android.internal.R;
import com.android.internal.util.gesture.EdgeGesturePosition;
import com.android.server.gesture.EdgeGestureTracker.OnActivationListener;

import java.io.PrintWriter;

/**
 * A simple input filter, that listens for edge swipe gestures in the motion event input
 * stream.
 * <p>
 * There are 5 distinct states of this filter.
 * 1) LISTEN:
 *    mTracker.active == false
 *    All motion events are passed through. If a ACTION_DOWN within a gesture trigger area happen
 *    switch to DETECTING.
 * 2) DETECTING:
 *    mTracker.active == true
 *    All events are buffered now, and the gesture is checked by mTracker. If mTracker rejects
 *    the gesture (hopefully as fast as possible) all cached events will be flushed out and the
 *    filter falls back to LISTEN.
 *    If mTracker accepts the gesture, clear all cached events and go to LOCKED.
 * 3) LOCKED:
 *    mTracker.active == false
 *    All events will be cached until the state changes to SYNTHESIZE through a filter
 *    unlock event. If there is a ACTION_UP, _CANCEL or any PointerId differently to the last
 *    event seen when mTracker accepted the gesture, we flush all events and go to LISTEN.
 * 4) SYNTHESIZE:
 *    The first motion event found will be turned into a ACTION_DOWN event, all previous events
 *    will be discarded.
 * 5) POSTSYNTHESIZE:
 *    mSyntheticDownTime != -1
 *    All following events will have the down time set to the synthesized ACTION_DOWN event time
 *    until an ACTION_UP or ACTION_CANCEL is encountered and the state is reset to LISTEN.
 * 6) DROP:
 *    All following events will be discarded. If there is an ACTION_UP, _CANCEL
 *    we go to LISTEN state.
 * <p>
 * If you are reading this within Java Doc, you are doing something wrong ;)
 */
public class EdgeGestureInputFilter implements IInputFilter {
    /* WARNING!! The IInputFilter interface is used directly, there is no Binder between this and
     * the InputDispatcher.
     * This is fine, because it prevents unnecessary parceling, but beware:
     * This means we are running on the dispatch or listener thread of the input dispatcher. Every
     * cycle we waste here adds to the overall input latency.
     */
    private static final String TAG = "EdgeGestureInputFilter";
    private static final boolean DEBUG = false;
    private static final boolean DEBUG_INPUT = false;
    // TODO: Should be turned off in final commit
    private static final boolean SYSTRACE = false;

    private final Handler mHandler;

    private IInputFilterHost mHost = null; // dispatcher thread

    private static final class MotionEventInfo {
        private static final int MAX_POOL_SIZE = 16;

        private static final Object sLock = new Object();
        private static MotionEventInfo sPool;
        private static int sPoolSize;

        private boolean mInPool;

        public static MotionEventInfo obtain(MotionEvent event, int policyFlags) {
            synchronized (sLock) {
                MotionEventInfo info;
                if (sPoolSize > 0) {
                    sPoolSize--;
                    info = sPool;
                    sPool = info.next;
                    info.next = null;
                    info.mInPool = false;
                } else {
                    info = new MotionEventInfo();
                }
                info.initialize(event, policyFlags);
                return info;
            }
        }

        private void initialize(MotionEvent event, int policyFlags) {
            this.event = MotionEvent.obtain(event);
            this.policyFlags = policyFlags;
            cachedTimeMillis = SystemClock.uptimeMillis();
        }

        public void recycle() {
            synchronized (sLock) {
                if (mInPool) {
                    throw new IllegalStateException("Already recycled.");
                }
                clear();
                if (sPoolSize < MAX_POOL_SIZE) {
                    sPoolSize++;
                    next = sPool;
                    sPool = this;
                    mInPool = true;
                }
            }
        }

        private void clear() {
            event.recycle();
            event = null;
            policyFlags = 0;
        }

        public MotionEventInfo next;
        public MotionEvent event;
        public int policyFlags;
        public long cachedTimeMillis;
    }
    private final Object mLock = new Object();
    private MotionEventInfo mMotionEventQueue; // guarded by mLock
    private MotionEventInfo mMotionEventQueueTail; // guarded by mLock
    /* DEBUG */
    private int mMotionEventQueueCountDebug; // guarded by mLock

    private int mDeviceId; // dispatcher only
    private enum State {
        LISTEN, DETECTING, LOCKED, SYNTHESIZE, POSTSYNTHESIZE, DROP;
    }
    private State mState = State.LISTEN; // guarded by mLock
    private EdgeGestureTracker mTracker; // guarded by mLock
    private volatile int mPositions; // written by handler / read by dispatcher
    private volatile int mSensitivity; // written by handler / read by dispatcher

    // only used by dispatcher
    private long mSyntheticDownTime = -1;
    private PointerCoords[] mTempPointerCoords = new PointerCoords[1];
    private PointerProperties[] mTempPointerProperties = new PointerProperties[1];

    public EdgeGestureInputFilter(Context context, Handler handler) {
        mHandler = handler;

        final Resources res = context.getResources();
        mTracker = new EdgeGestureTracker(res.getDimensionPixelSize(
                R.dimen.edge_gesture_trigger_thickness),
                res.getDimensionPixelSize(R.dimen.edge_gesture_trigger_distance),
                res.getDimensionPixelSize(R.dimen.edge_gesture_perpendicular_distance));
        mTracker.setOnActivationListener(new OnActivationListener() {
            public void onActivation(MotionEvent event, int touchX, int touchY, EdgeGesturePosition position) {
                // mLock is held by #processMotionEvent
                mHandler.obtainMessage(EdgeGestureService.MSG_EDGE_GESTURE_ACTIVATION,
                        touchX, touchY, position).sendToTarget();
                mState = State.LOCKED;
            }
        });
        mTempPointerCoords[0] = new PointerCoords();
        mTempPointerProperties[0] = new PointerProperties();
    }

    // called from handler thread (lock taken)
    public void updateDisplay(Display display, DisplayInfo displayInfo) {
        synchronized (mLock) {
            mTracker.updateDisplay(display);
        }
    }

    // called from handler thread (lock taken)
    public void updatePositions(int positions) {
        mPositions = positions;
    }

    // called from handler thread (lock taken)
    public void updateSensitivity(int sensitivity) {
        mSensitivity = sensitivity;
    }

    // called from handler thread
    public boolean unlockFilter() {
        synchronized (mLock) {
            if (mState == State.LOCKED) {
                mState = State.SYNTHESIZE;
                return true;
            }
        }
        return false;
    }

    public boolean dropSequence() {
        synchronized (mLock) {
            if (mState == State.LOCKED) {
                mState = State.DROP;
                return true;
            }
        }
        return false;
    }

    /**
     * Called to enqueue the input event for filtering.
     * The event must be recycled after the input filter processed it.
     * This method is guaranteed to be non-reentrant.
     *
     * @see InputFilter#filterInputEvent(InputEvent, int)
     * @param event The input event to enqueue.
     */
    // called by the input dispatcher thread
    public void filterInputEvent(InputEvent event, int policyFlags) throws RemoteException {
        if (SYSTRACE) {
            Trace.traceBegin(Trace.TRACE_TAG_INPUT, "filterInputEvent");
        }
        try {
            if (((event.getSource() & InputDevice.SOURCE_TOUCHSCREEN)
                 != InputDevice.SOURCE_TOUCHSCREEN)
                    || !(event instanceof MotionEvent)) {
                sendInputEvent(event, policyFlags);
                return;
            }
            if (DEBUG_INPUT) {
                Slog.d(TAG, "Received event: " + event + ", policyFlags=0x"
                        + Integer.toHexString(policyFlags));
            }
            MotionEvent motionEvent = (MotionEvent) event;
            final int deviceId = event.getDeviceId();
            if (deviceId != mDeviceId) {
                processDeviceSwitch(deviceId, motionEvent, policyFlags);
            } else {
                if ((policyFlags & WindowManagerPolicy.FLAG_PASS_TO_USER) == 0) {
                    synchronized (mLock) {
                        clearAndResetStateLocked(false, true);
                    }
                }
                processMotionEvent(motionEvent, policyFlags);
            }
        } finally {
            event.recycle();
            if (SYSTRACE) {
                Trace.traceEnd(Trace.TRACE_TAG_INPUT);
            }
        }
    }

    private void processDeviceSwitch(int deviceId, MotionEvent motionEvent, int policyFlags) {
        if (motionEvent.getActionMasked() == MotionEvent.ACTION_DOWN) {
            mDeviceId = deviceId;
            synchronized (mLock) {
                clearAndResetStateLocked(true, false);
                processMotionEvent(motionEvent, policyFlags);
            }
        } else {
            sendInputEvent(motionEvent, policyFlags);
        }
    }

    private void processMotionEvent(MotionEvent motionEvent, int policyFlags) {
        final int action = motionEvent.getActionMasked();

        synchronized (mLock) {
            switch (mState) {
                case LISTEN:
                    if (action ==  MotionEvent.ACTION_DOWN) {
                        boolean hit = mPositions != 0
                                && mTracker.start(motionEvent, mPositions, mSensitivity);
                        if (DEBUG) Slog.d(TAG, "start:" + hit);
                        if (hit) {
                            // cache the down event
                            cacheDelayedMotionEventLocked(motionEvent, policyFlags);
                            mState = State.DETECTING;
                            return;
                        }
                    }
                    sendInputEvent(motionEvent, policyFlags);
                    break;
                case DETECTING:
                    cacheDelayedMotionEventLocked(motionEvent, policyFlags);
                    if (action == MotionEvent.ACTION_MOVE) {
                        if (mTracker.move(motionEvent)) {
                            // return: the tracker is either detecting or triggered onActivation
                            return;
                        }
                    }
                    if (DEBUG) {
                        Slog.d(TAG, "move: reset!");
                    }
                    clearAndResetStateLocked(false, true);
                    break;
                case LOCKED:
                    cacheDelayedMotionEventLocked(motionEvent, policyFlags);
                    if (action != MotionEvent.ACTION_MOVE) {
                        clearAndResetStateLocked(false, true);
                    }
                    break;
                case SYNTHESIZE:
                    if (action == MotionEvent.ACTION_MOVE) {
                        clearDelayedMotionEventsLocked();
                        sendSynthesizedMotionEventLocked(motionEvent, policyFlags);
                        mState = State.POSTSYNTHESIZE;
                    } else {
                        // This is the case where a race condition caught us: We already
                        // returned the handler thread that it is all right to call
                        // #gainTouchFocus(), but apparently this was wrong, as the gesture
                        // was canceled now.
                        clearAndResetStateLocked(false, true);
                    }
                    break;
                case POSTSYNTHESIZE:
                    motionEvent.setDownTime(mSyntheticDownTime);
                    if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
                        mState = State.LISTEN;
                        mSyntheticDownTime = -1;
                    }
                    sendInputEvent(motionEvent, policyFlags);
                    break;
                case DROP:
                    if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
                        clearDelayedMotionEventsLocked();
                        mState = State.LISTEN;
                    }
                    break;
            }
        }
    }

    private void clearAndResetStateLocked(boolean force, boolean shift) {
        // ignore soft reset in POSTSYNTHESIZE, because we need to tamper with
        // the event stream and going to LISTEN after an ACTION_UP anyway
        if (!force && (mState == State.POSTSYNTHESIZE)) {
            return;
        }
        switch (mState) {
            case LISTEN:
                // this is a nop
                break;
            case DETECTING:
                mTracker.reset();
                // intentionally no break here
            case LOCKED:
            case SYNTHESIZE:
                sendDelayedMotionEventsLocked(shift);
                break;
            case POSTSYNTHESIZE:
                // hard reset (this will break the event stream)
                Slog.w(TAG, "Quit POSTSYNTHESIZE without ACTION_UP from ACTION_DOWN at "
                        + mSyntheticDownTime);
                mSyntheticDownTime = -1;
                break;
        }
        // if there are future events that need to be tampered with, goto POSTSYNTHESIZE
        mState = mSyntheticDownTime == -1 ? State.LISTEN : State.POSTSYNTHESIZE;
    }

    private void sendInputEvent(InputEvent event, int policyFlags) {
        try {
            mHost.sendInputEvent(event, policyFlags);
        } catch (RemoteException e) {
            /* ignore */
        }
    }

    private void cacheDelayedMotionEventLocked(MotionEvent event, int policyFlags) {
        MotionEventInfo info = MotionEventInfo.obtain(event, policyFlags);
        if (mMotionEventQueue == null) {
            mMotionEventQueue = info;
        } else {
            mMotionEventQueueTail.next = info;
        }
        mMotionEventQueueTail = info;
        mMotionEventQueueCountDebug++;
        if (SYSTRACE) {
            Trace.traceCounter(Trace.TRACE_TAG_INPUT, "meq", mMotionEventQueueCountDebug);
        }
    }

    private void sendDelayedMotionEventsLocked(boolean shift) {
        while (mMotionEventQueue != null) {
            MotionEventInfo info = mMotionEventQueue;
            mMotionEventQueue = info.next;

            if (DEBUG) {
                Slog.d(TAG, "Replay event: " + info.event);
            }
            mMotionEventQueueCountDebug--;
            if (SYSTRACE) {
                Trace.traceCounter(Trace.TRACE_TAG_INPUT, "meq", mMotionEventQueueCountDebug);
            }
            if (shift) {
                final long offset = SystemClock.uptimeMillis() - info.cachedTimeMillis;
                if (info.event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                    mSyntheticDownTime = info.event.getDownTime() + offset;
                }
                sendMotionEventWithOffsetLocked(info.event, info.policyFlags, mSyntheticDownTime, offset);
                if (info.event.getActionMasked() == MotionEvent.ACTION_UP) {
                    mSyntheticDownTime = -1;
                }
            } else {
                sendInputEvent(info.event, info.policyFlags);
            }
            info.recycle();
        }
        mMotionEventQueueTail = null;
    }

    private void clearDelayedMotionEventsLocked() {
        while (mMotionEventQueue != null) {
            MotionEventInfo next = mMotionEventQueue.next;
            mMotionEventQueue.recycle();
            mMotionEventQueue = next;
        }
        mMotionEventQueueTail = null;
        mMotionEventQueueCountDebug = 0;
        if (SYSTRACE) {
            Trace.traceCounter(Trace.TRACE_TAG_INPUT, "meq", mMotionEventQueueCountDebug);
        }
    }

    private void sendMotionEventWithOffsetLocked(MotionEvent event, int policyFlags,
            long downTime, long offset) {
        final int pointerCount = event.getPointerCount();
        PointerCoords[] coords = getTempPointerCoordsWithMinSizeLocked(pointerCount);
        PointerProperties[] properties = getTempPointerPropertiesWithMinSizeLocked(pointerCount);
        for (int i = 0; i < pointerCount; i++) {
            event.getPointerCoords(i, coords[i]);
            event.getPointerProperties(i, properties[i]);
        }
        final long eventTime = event.getEventTime() + offset;
        sendInputEvent(MotionEvent.obtain(downTime, eventTime, event.getAction(), pointerCount,
                properties, coords, event.getMetaState(), event.getButtonState(), 1.0f, 1.0f,
                event.getDeviceId(), event.getEdgeFlags(), event.getSource(), event.getFlags()),
                policyFlags);
    }

    private PointerCoords[] getTempPointerCoordsWithMinSizeLocked(int size) {
        final int oldSize = mTempPointerCoords.length;
        if (oldSize < size) {
            PointerCoords[] oldTempPointerCoords = mTempPointerCoords;
            mTempPointerCoords = new PointerCoords[size];
            System.arraycopy(oldTempPointerCoords, 0, mTempPointerCoords, 0, oldSize);
        }
        for (int i = oldSize; i < size; i++) {
            mTempPointerCoords[i] = new PointerCoords();
        }
        return mTempPointerCoords;
    }

    private PointerProperties[] getTempPointerPropertiesWithMinSizeLocked(int size) {
        final int oldSize = mTempPointerProperties.length;
        if (oldSize < size) {
            PointerProperties[] oldTempPointerProperties = mTempPointerProperties;
            mTempPointerProperties = new PointerProperties[size];
            System.arraycopy(oldTempPointerProperties, 0, mTempPointerProperties, 0, oldSize);
        }
        for (int i = oldSize; i < size; i++) {
            mTempPointerProperties[i] = new PointerProperties();
        }
        return mTempPointerProperties;
    }

    private void sendSynthesizedMotionEventLocked(MotionEvent event, int policyFlags) {
        if (event.getPointerCount() == 1) {
            event.getPointerCoords(0, mTempPointerCoords[0]);
            event.getPointerProperties(0, mTempPointerProperties[0]);
            MotionEvent down = MotionEvent.obtain(event.getEventTime(), event.getEventTime(),
                    MotionEvent.ACTION_DOWN, 1, mTempPointerProperties, mTempPointerCoords,
                    event.getMetaState(), event.getButtonState(),
                    1.0f, 1.0f, event.getDeviceId(), event.getEdgeFlags(),
                    event.getSource(), event.getFlags());
            Slog.d(TAG, "Synthesized event:" + down);
            sendInputEvent(down, policyFlags);
            mSyntheticDownTime = event.getEventTime();
        } else {
            Slog.w(TAG, "Could not synthesize MotionEvent, this will drop all following events!");
        }
    }

    // should never be called
    public IBinder asBinder() {
        throw new UnsupportedOperationException();
    }

    // called by the input dispatcher thread
    public void install(IInputFilterHost host) throws RemoteException {
        if (DEBUG) {
            Slog.d(TAG, "EdgeGesture input filter installed.");
        }
        mHost = host;
        synchronized (mLock) {
            clearAndResetStateLocked(true, false);
        }
    }

    // called by the input dispatcher thread
    public void uninstall() throws RemoteException {
        if (DEBUG) {
            Slog.d(TAG, "EdgeGesture input filter uninstalled.");
        }
    }

    // called by a Binder thread
    public void dump(PrintWriter pw, String prefix) {
        synchronized (mLock) {
            pw.print(prefix);
            pw.println("mState=" + mState.name());
            pw.print(prefix);
            pw.println("mPositions=0x" + Integer.toHexString(mPositions));
            pw.print(prefix);
            pw.println("mQueue=" + mMotionEventQueueCountDebug + " items");
        }
    }
}