PointerTracker.java revision 6c3304ea961fd4da0a1da01dc1fac4797c713bcc
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17package com.android.inputmethod.keyboard;
18
19import android.content.res.TypedArray;
20import android.os.SystemClock;
21import android.util.Log;
22import android.view.MotionEvent;
23
24import com.android.inputmethod.accessibility.AccessibilityUtils;
25import com.android.inputmethod.keyboard.internal.GestureStroke;
26import com.android.inputmethod.keyboard.internal.GestureStrokeWithPreviewTrail;
27import com.android.inputmethod.keyboard.internal.PointerTrackerQueue;
28import com.android.inputmethod.latin.CollectionUtils;
29import com.android.inputmethod.latin.InputPointers;
30import com.android.inputmethod.latin.LatinImeLogger;
31import com.android.inputmethod.latin.R;
32import com.android.inputmethod.latin.define.ProductionFlag;
33import com.android.inputmethod.research.ResearchLogger;
34
35import java.util.ArrayList;
36
37public class PointerTracker implements PointerTrackerQueue.Element {
38    private static final String TAG = PointerTracker.class.getSimpleName();
39    private static final boolean DEBUG_EVENT = false;
40    private static final boolean DEBUG_MOVE_EVENT = false;
41    private static final boolean DEBUG_LISTENER = false;
42    private static boolean DEBUG_MODE = LatinImeLogger.sDBG;
43
44    /** True if {@link PointerTracker}s should handle gesture events. */
45    private static boolean sShouldHandleGesture = false;
46    private static boolean sMainDictionaryAvailable = false;
47    private static boolean sGestureHandlingEnabledByInputField = false;
48    private static boolean sGestureHandlingEnabledByUser = false;
49
50    private static final int MIN_GESTURE_RECOGNITION_TIME = 100; // msec
51
52    public interface KeyEventHandler {
53        /**
54         * Get KeyDetector object that is used for this PointerTracker.
55         * @return the KeyDetector object that is used for this PointerTracker
56         */
57        public KeyDetector getKeyDetector();
58
59        /**
60         * Get KeyboardActionListener object that is used to register key code and so on.
61         * @return the KeyboardActionListner for this PointerTracker
62         */
63        public KeyboardActionListener getKeyboardActionListener();
64
65        /**
66         * Get DrawingProxy object that is used for this PointerTracker.
67         * @return the DrawingProxy object that is used for this PointerTracker
68         */
69        public DrawingProxy getDrawingProxy();
70
71        /**
72         * Get TimerProxy object that handles key repeat and long press timer event for this
73         * PointerTracker.
74         * @return the TimerProxy object that handles key repeat and long press timer event.
75         */
76        public TimerProxy getTimerProxy();
77    }
78
79    public interface DrawingProxy extends MoreKeysPanel.Controller {
80        public void invalidateKey(Key key);
81        public void showKeyPreview(PointerTracker tracker);
82        public void dismissKeyPreview(PointerTracker tracker);
83        public void showGesturePreviewTrail(PointerTracker tracker);
84    }
85
86    public interface TimerProxy {
87        public void startTypingStateTimer(Key typedKey);
88        public boolean isTypingState();
89        public void startKeyRepeatTimer(PointerTracker tracker);
90        public void startLongPressTimer(PointerTracker tracker);
91        public void startLongPressTimer(int code);
92        public void cancelLongPressTimer();
93        public void startDoubleTapTimer();
94        public void cancelDoubleTapTimer();
95        public boolean isInDoubleTapTimeout();
96        public void cancelKeyTimers();
97
98        public static class Adapter implements TimerProxy {
99            @Override
100            public void startTypingStateTimer(Key typedKey) {}
101            @Override
102            public boolean isTypingState() { return false; }
103            @Override
104            public void startKeyRepeatTimer(PointerTracker tracker) {}
105            @Override
106            public void startLongPressTimer(PointerTracker tracker) {}
107            @Override
108            public void startLongPressTimer(int code) {}
109            @Override
110            public void cancelLongPressTimer() {}
111            @Override
112            public void startDoubleTapTimer() {}
113            @Override
114            public void cancelDoubleTapTimer() {}
115            @Override
116            public boolean isInDoubleTapTimeout() { return false; }
117            @Override
118            public void cancelKeyTimers() {}
119        }
120    }
121
122    static class PointerTrackerParams {
123        public final boolean mSlidingKeyInputEnabled;
124        public final int mTouchNoiseThresholdTime;
125        public final float mTouchNoiseThresholdDistance;
126        public final int mTouchNoiseThresholdDistanceSquared;
127
128        public static final PointerTrackerParams DEFAULT = new PointerTrackerParams();
129
130        private PointerTrackerParams() {
131            mSlidingKeyInputEnabled = false;
132            mTouchNoiseThresholdTime = 0;
133            mTouchNoiseThresholdDistance = 0.0f;
134            mTouchNoiseThresholdDistanceSquared = 0;
135        }
136
137        public PointerTrackerParams(TypedArray mainKeyboardViewAttr) {
138            mSlidingKeyInputEnabled = mainKeyboardViewAttr.getBoolean(
139                    R.styleable.MainKeyboardView_slidingKeyInputEnable, false);
140            mTouchNoiseThresholdTime = mainKeyboardViewAttr.getInt(
141                    R.styleable.MainKeyboardView_touchNoiseThresholdTime, 0);
142            final float touchNouseThresholdDistance = mainKeyboardViewAttr.getDimension(
143                    R.styleable.MainKeyboardView_touchNoiseThresholdDistance, 0);
144            mTouchNoiseThresholdDistance = touchNouseThresholdDistance;
145            mTouchNoiseThresholdDistanceSquared =
146                    (int)(touchNouseThresholdDistance * touchNouseThresholdDistance);
147        }
148    }
149
150    // Parameters for pointer handling.
151    private static PointerTrackerParams sParams;
152    private static boolean sNeedsPhantomSuddenMoveEventHack;
153
154    private static final ArrayList<PointerTracker> sTrackers = CollectionUtils.newArrayList();
155    private static PointerTrackerQueue sPointerTrackerQueue;
156
157    public final int mPointerId;
158
159    private DrawingProxy mDrawingProxy;
160    private TimerProxy mTimerProxy;
161    private KeyDetector mKeyDetector;
162    private KeyboardActionListener mListener = EMPTY_LISTENER;
163
164    private Keyboard mKeyboard;
165    private int mKeyQuarterWidthSquared;
166
167    private boolean mIsDetectingGesture = false; // per PointerTracker.
168    private static boolean sInGesture = false;
169    private static long sGestureFirstDownTime;
170    private static final InputPointers sAggregratedPointers = new InputPointers(
171            GestureStroke.DEFAULT_CAPACITY);
172    private static int sLastRecognitionPointSize = 0;
173    private static long sLastRecognitionTime = 0;
174
175    // The position and time at which first down event occurred.
176    private long mDownTime;
177    private long mUpTime;
178
179    // The current key where this pointer is.
180    private Key mCurrentKey = null;
181    // The position where the current key was recognized for the first time.
182    private int mKeyX;
183    private int mKeyY;
184
185    // Last pointer position.
186    private int mLastX;
187    private int mLastY;
188
189    // true if keyboard layout has been changed.
190    private boolean mKeyboardLayoutHasBeenChanged;
191
192    // true if event is already translated to a key action.
193    private boolean mKeyAlreadyProcessed;
194
195    // true if this pointer has been long-pressed and is showing a more keys panel.
196    private boolean mIsShowingMoreKeysPanel;
197
198    // true if this pointer is in sliding key input
199    boolean mIsInSlidingKeyInput;
200
201    // true if sliding key is allowed.
202    private boolean mIsAllowedSlidingKeyInput;
203
204    // ignore modifier key if true
205    private boolean mIgnoreModifierKey;
206
207    // Empty {@link KeyboardActionListener}
208    private static final KeyboardActionListener EMPTY_LISTENER =
209            new KeyboardActionListener.Adapter();
210
211    private final GestureStrokeWithPreviewTrail mGestureStrokeWithPreviewTrail;
212
213    public static void init(boolean hasDistinctMultitouch,
214            boolean needsPhantomSuddenMoveEventHack) {
215        if (hasDistinctMultitouch) {
216            sPointerTrackerQueue = new PointerTrackerQueue();
217        } else {
218            sPointerTrackerQueue = null;
219        }
220        sNeedsPhantomSuddenMoveEventHack = needsPhantomSuddenMoveEventHack;
221        sParams = PointerTrackerParams.DEFAULT;
222    }
223
224    public static void setParameters(final TypedArray mainKeyboardViewAttr) {
225        sParams = new PointerTrackerParams(mainKeyboardViewAttr);
226    }
227
228    private static void updateGestureHandlingMode() {
229        sShouldHandleGesture = sMainDictionaryAvailable
230                && sGestureHandlingEnabledByInputField
231                && sGestureHandlingEnabledByUser
232                && !AccessibilityUtils.getInstance().isTouchExplorationEnabled();
233    }
234
235    // Note that this method is called from a non-UI thread.
236    public static void setMainDictionaryAvailability(final boolean mainDictionaryAvailable) {
237        sMainDictionaryAvailable = mainDictionaryAvailable;
238        updateGestureHandlingMode();
239    }
240
241    public static void setGestureHandlingEnabledByUser(final boolean gestureHandlingEnabledByUser) {
242        sGestureHandlingEnabledByUser = gestureHandlingEnabledByUser;
243        updateGestureHandlingMode();
244    }
245
246    public static PointerTracker getPointerTracker(final int id, final KeyEventHandler handler) {
247        final ArrayList<PointerTracker> trackers = sTrackers;
248
249        // Create pointer trackers until we can get 'id+1'-th tracker, if needed.
250        for (int i = trackers.size(); i <= id; i++) {
251            final PointerTracker tracker = new PointerTracker(i, handler);
252            trackers.add(tracker);
253        }
254
255        return trackers.get(id);
256    }
257
258    public static boolean isAnyInSlidingKeyInput() {
259        return sPointerTrackerQueue != null ? sPointerTrackerQueue.isAnyInSlidingKeyInput() : false;
260    }
261
262    public static void setKeyboardActionListener(final KeyboardActionListener listener) {
263        final int trackersSize = sTrackers.size();
264        for (int i = 0; i < trackersSize; ++i) {
265            final PointerTracker tracker = sTrackers.get(i);
266            tracker.mListener = listener;
267        }
268    }
269
270    public static void setKeyDetector(final KeyDetector keyDetector) {
271        final int trackersSize = sTrackers.size();
272        for (int i = 0; i < trackersSize; ++i) {
273            final PointerTracker tracker = sTrackers.get(i);
274            tracker.setKeyDetectorInner(keyDetector);
275            // Mark that keyboard layout has been changed.
276            tracker.mKeyboardLayoutHasBeenChanged = true;
277        }
278        final Keyboard keyboard = keyDetector.getKeyboard();
279        sGestureHandlingEnabledByInputField = !keyboard.mId.passwordInput();
280        updateGestureHandlingMode();
281    }
282
283    public static void setReleasedKeyGraphicsToAllKeys() {
284        final int trackersSize = sTrackers.size();
285        for (int i = 0; i < trackersSize; ++i) {
286            final PointerTracker tracker = sTrackers.get(i);
287            tracker.setReleasedKeyGraphics(tracker.mCurrentKey);
288        }
289    }
290
291    private PointerTracker(final int id, final KeyEventHandler handler) {
292        if (handler == null) {
293            throw new NullPointerException();
294        }
295        mPointerId = id;
296        mGestureStrokeWithPreviewTrail = new GestureStrokeWithPreviewTrail(id);
297        setKeyDetectorInner(handler.getKeyDetector());
298        mListener = handler.getKeyboardActionListener();
299        mDrawingProxy = handler.getDrawingProxy();
300        mTimerProxy = handler.getTimerProxy();
301    }
302
303    // Returns true if keyboard has been changed by this callback.
304    private boolean callListenerOnPressAndCheckKeyboardLayoutChange(final Key key) {
305        if (sInGesture) {
306            return false;
307        }
308        final boolean ignoreModifierKey = mIgnoreModifierKey && key.isModifier();
309        if (DEBUG_LISTENER) {
310            Log.d(TAG, "onPress    : " + KeyDetector.printableCode(key)
311                    + " ignoreModifier=" + ignoreModifierKey
312                    + " enabled=" + key.isEnabled());
313        }
314        if (ignoreModifierKey) {
315            return false;
316        }
317        if (key.isEnabled()) {
318            mListener.onPressKey(key.mCode);
319            final boolean keyboardLayoutHasBeenChanged = mKeyboardLayoutHasBeenChanged;
320            mKeyboardLayoutHasBeenChanged = false;
321            mTimerProxy.startTypingStateTimer(key);
322            return keyboardLayoutHasBeenChanged;
323        }
324        return false;
325    }
326
327    // Note that we need primaryCode argument because the keyboard may in shifted state and the
328    // primaryCode is different from {@link Key#mCode}.
329    private void callListenerOnCodeInput(final Key key, final int primaryCode, final int x,
330            final int y) {
331        final boolean ignoreModifierKey = mIgnoreModifierKey && key.isModifier();
332        final boolean altersCode = key.altCodeWhileTyping() && mTimerProxy.isTypingState();
333        final int code = altersCode ? key.mAltCode : primaryCode;
334        if (DEBUG_LISTENER) {
335            Log.d(TAG, "onCodeInput: " + Keyboard.printableCode(code) + " text=" + key.mOutputText
336                    + " x=" + x + " y=" + y
337                    + " ignoreModifier=" + ignoreModifierKey + " altersCode=" + altersCode
338                    + " enabled=" + key.isEnabled());
339        }
340        if (ProductionFlag.IS_EXPERIMENTAL) {
341            ResearchLogger.pointerTracker_callListenerOnCodeInput(key, x, y, ignoreModifierKey,
342                    altersCode, code);
343        }
344        if (ignoreModifierKey) {
345            return;
346        }
347        // Even if the key is disabled, it should respond if it is in the altCodeWhileTyping state.
348        if (key.isEnabled() || altersCode) {
349            if (code == Keyboard.CODE_OUTPUT_TEXT) {
350                mListener.onTextInput(key.mOutputText);
351            } else if (code != Keyboard.CODE_UNSPECIFIED) {
352                mListener.onCodeInput(code, x, y);
353            }
354        }
355    }
356
357    // Note that we need primaryCode argument because the keyboard may in shifted state and the
358    // primaryCode is different from {@link Key#mCode}.
359    private void callListenerOnRelease(final Key key, final int primaryCode,
360            final boolean withSliding) {
361        if (sInGesture) {
362            return;
363        }
364        final boolean ignoreModifierKey = mIgnoreModifierKey && key.isModifier();
365        if (DEBUG_LISTENER) {
366            Log.d(TAG, "onRelease  : " + Keyboard.printableCode(primaryCode)
367                    + " sliding=" + withSliding + " ignoreModifier=" + ignoreModifierKey
368                    + " enabled="+ key.isEnabled());
369        }
370        if (ProductionFlag.IS_EXPERIMENTAL) {
371            ResearchLogger.pointerTracker_callListenerOnRelease(key, primaryCode, withSliding,
372                    ignoreModifierKey);
373        }
374        if (ignoreModifierKey) {
375            return;
376        }
377        if (key.isEnabled()) {
378            mListener.onReleaseKey(primaryCode, withSliding);
379        }
380    }
381
382    private void callListenerOnCancelInput() {
383        if (DEBUG_LISTENER) {
384            Log.d(TAG, "onCancelInput");
385        }
386        if (ProductionFlag.IS_EXPERIMENTAL) {
387            ResearchLogger.pointerTracker_callListenerOnCancelInput();
388        }
389        mListener.onCancelInput();
390    }
391
392    private void setKeyDetectorInner(final KeyDetector keyDetector) {
393        mKeyDetector = keyDetector;
394        mKeyboard = keyDetector.getKeyboard();
395        mGestureStrokeWithPreviewTrail.setGestureSampleLength(mKeyboard.mMostCommonKeyWidth);
396        final Key newKey = mKeyDetector.detectHitKey(mKeyX, mKeyY);
397        if (newKey != mCurrentKey) {
398            if (mDrawingProxy != null) {
399                setReleasedKeyGraphics(mCurrentKey);
400            }
401            // Keep {@link #mCurrentKey} that comes from previous keyboard.
402        }
403        final int keyQuarterWidth = mKeyboard.mMostCommonKeyWidth / 4;
404        mKeyQuarterWidthSquared = keyQuarterWidth * keyQuarterWidth;
405    }
406
407    @Override
408    public boolean isInSlidingKeyInput() {
409        return mIsInSlidingKeyInput;
410    }
411
412    public Key getKey() {
413        return mCurrentKey;
414    }
415
416    @Override
417    public boolean isModifier() {
418        return mCurrentKey != null && mCurrentKey.isModifier();
419    }
420
421    public Key getKeyOn(final int x, final int y) {
422        return mKeyDetector.detectHitKey(x, y);
423    }
424
425    private void setReleasedKeyGraphics(final Key key) {
426        mDrawingProxy.dismissKeyPreview(this);
427        if (key == null) {
428            return;
429        }
430
431        // Even if the key is disabled, update the key release graphics just in case.
432        updateReleaseKeyGraphics(key);
433
434        if (key.isShift()) {
435            for (final Key shiftKey : mKeyboard.mShiftKeys) {
436                if (shiftKey != key) {
437                    updateReleaseKeyGraphics(shiftKey);
438                }
439            }
440        }
441
442        if (key.altCodeWhileTyping()) {
443            final int altCode = key.mAltCode;
444            final Key altKey = mKeyboard.getKey(altCode);
445            if (altKey != null) {
446                updateReleaseKeyGraphics(altKey);
447            }
448            for (final Key k : mKeyboard.mAltCodeKeysWhileTyping) {
449                if (k != key && k.mAltCode == altCode) {
450                    updateReleaseKeyGraphics(k);
451                }
452            }
453        }
454    }
455
456    private void setPressedKeyGraphics(final Key key) {
457        if (key == null) {
458            return;
459        }
460
461        // Even if the key is disabled, it should respond if it is in the altCodeWhileTyping state.
462        final boolean altersCode = key.altCodeWhileTyping() && mTimerProxy.isTypingState();
463        final boolean needsToUpdateGraphics = key.isEnabled() || altersCode;
464        if (!needsToUpdateGraphics) {
465            return;
466        }
467
468        if (!key.noKeyPreview() && !sInGesture) {
469            mDrawingProxy.showKeyPreview(this);
470        }
471        updatePressKeyGraphics(key);
472
473        if (key.isShift()) {
474            for (final Key shiftKey : mKeyboard.mShiftKeys) {
475                if (shiftKey != key) {
476                    updatePressKeyGraphics(shiftKey);
477                }
478            }
479        }
480
481        if (key.altCodeWhileTyping() && mTimerProxy.isTypingState()) {
482            final int altCode = key.mAltCode;
483            final Key altKey = mKeyboard.getKey(altCode);
484            if (altKey != null) {
485                updatePressKeyGraphics(altKey);
486            }
487            for (final Key k : mKeyboard.mAltCodeKeysWhileTyping) {
488                if (k != key && k.mAltCode == altCode) {
489                    updatePressKeyGraphics(k);
490                }
491            }
492        }
493    }
494
495    private void updateReleaseKeyGraphics(final Key key) {
496        key.onReleased();
497        mDrawingProxy.invalidateKey(key);
498    }
499
500    private void updatePressKeyGraphics(final Key key) {
501        key.onPressed();
502        mDrawingProxy.invalidateKey(key);
503    }
504
505    public GestureStrokeWithPreviewTrail getGestureStrokeWithPreviewTrail() {
506        return mGestureStrokeWithPreviewTrail;
507    }
508
509    public int getLastX() {
510        return mLastX;
511    }
512
513    public int getLastY() {
514        return mLastY;
515    }
516
517    public long getDownTime() {
518        return mDownTime;
519    }
520
521    private Key onDownKey(final int x, final int y, final long eventTime) {
522        mDownTime = eventTime;
523        return onMoveToNewKey(onMoveKeyInternal(x, y), x, y);
524    }
525
526    private Key onMoveKeyInternal(final int x, final int y) {
527        mLastX = x;
528        mLastY = y;
529        return mKeyDetector.detectHitKey(x, y);
530    }
531
532    private Key onMoveKey(final int x, final int y) {
533        return onMoveKeyInternal(x, y);
534    }
535
536    private Key onMoveToNewKey(final Key newKey, final int x, final int y) {
537        mCurrentKey = newKey;
538        mKeyX = x;
539        mKeyY = y;
540        return newKey;
541    }
542
543    private static int getActivePointerTrackerCount() {
544        return (sPointerTrackerQueue == null) ? 1 : sPointerTrackerQueue.size();
545    }
546
547    private void startBatchInput() {
548        if (DEBUG_LISTENER) {
549            Log.d(TAG, "onStartBatchInput");
550        }
551        sInGesture = true;
552        mListener.onStartBatchInput();
553        mDrawingProxy.showGesturePreviewTrail(this);
554    }
555
556    private void updateBatchInput(final long eventTime) {
557        synchronized (sAggregratedPointers) {
558            mGestureStrokeWithPreviewTrail.appendIncrementalBatchPoints(sAggregratedPointers);
559            final int size = sAggregratedPointers.getPointerSize();
560            if (size > sLastRecognitionPointSize
561                    && eventTime > sLastRecognitionTime + MIN_GESTURE_RECOGNITION_TIME) {
562                sLastRecognitionPointSize = size;
563                sLastRecognitionTime = eventTime;
564                if (DEBUG_LISTENER) {
565                    Log.d(TAG, "onUpdateBatchInput: batchPoints=" + size);
566                }
567                mListener.onUpdateBatchInput(sAggregratedPointers);
568            }
569        }
570        mDrawingProxy.showGesturePreviewTrail(this);
571    }
572
573    private void endBatchInput() {
574        synchronized (sAggregratedPointers) {
575            mGestureStrokeWithPreviewTrail.appendAllBatchPoints(sAggregratedPointers);
576            if (getActivePointerTrackerCount() == 1) {
577                if (DEBUG_LISTENER) {
578                    Log.d(TAG, "onEndBatchInput: batchPoints="
579                            + sAggregratedPointers.getPointerSize());
580                }
581                sInGesture = false;
582                mListener.onEndBatchInput(sAggregratedPointers);
583                clearBatchInputPointsOfAllPointerTrackers();
584            }
585        }
586        mDrawingProxy.showGesturePreviewTrail(this);
587    }
588
589    private static void abortBatchInput() {
590        clearBatchInputPointsOfAllPointerTrackers();
591    }
592
593    private static void clearBatchInputPointsOfAllPointerTrackers() {
594        final int trackersSize = sTrackers.size();
595        for (int i = 0; i < trackersSize; ++i) {
596            final PointerTracker tracker = sTrackers.get(i);
597            tracker.mGestureStrokeWithPreviewTrail.reset();
598        }
599        sAggregratedPointers.reset();
600        sLastRecognitionPointSize = 0;
601        sLastRecognitionTime = 0;
602    }
603
604    public void processMotionEvent(final int action, final int x, final int y, final long eventTime,
605            final KeyEventHandler handler) {
606        switch (action) {
607        case MotionEvent.ACTION_DOWN:
608        case MotionEvent.ACTION_POINTER_DOWN:
609            onDownEvent(x, y, eventTime, handler);
610            break;
611        case MotionEvent.ACTION_UP:
612        case MotionEvent.ACTION_POINTER_UP:
613            onUpEvent(x, y, eventTime);
614            break;
615        case MotionEvent.ACTION_MOVE:
616            onMoveEvent(x, y, eventTime, null);
617            break;
618        case MotionEvent.ACTION_CANCEL:
619            onCancelEvent(x, y, eventTime);
620            break;
621        }
622    }
623
624    public void onDownEvent(final int x, final int y, final long eventTime,
625            final KeyEventHandler handler) {
626        if (DEBUG_EVENT) {
627            printTouchEvent("onDownEvent:", x, y, eventTime);
628        }
629
630        mDrawingProxy = handler.getDrawingProxy();
631        mTimerProxy = handler.getTimerProxy();
632        setKeyboardActionListener(handler.getKeyboardActionListener());
633        setKeyDetectorInner(handler.getKeyDetector());
634        // Naive up-to-down noise filter.
635        final long deltaT = eventTime - mUpTime;
636        if (deltaT < sParams.mTouchNoiseThresholdTime) {
637            final int dx = x - mLastX;
638            final int dy = y - mLastY;
639            final int distanceSquared = (dx * dx + dy * dy);
640            if (distanceSquared < sParams.mTouchNoiseThresholdDistanceSquared) {
641                if (DEBUG_MODE)
642                    Log.w(TAG, "onDownEvent: ignore potential noise: time=" + deltaT
643                            + " distance=" + distanceSquared);
644                if (ProductionFlag.IS_EXPERIMENTAL) {
645                    ResearchLogger.pointerTracker_onDownEvent(deltaT, distanceSquared);
646                }
647                mKeyAlreadyProcessed = true;
648                return;
649            }
650        }
651
652        final Key key = getKeyOn(x, y);
653        final PointerTrackerQueue queue = sPointerTrackerQueue;
654        if (queue != null) {
655            if (key != null && key.isModifier()) {
656                // Before processing a down event of modifier key, all pointers already being
657                // tracked should be released.
658                queue.releaseAllPointers(eventTime);
659            }
660            queue.add(this);
661        }
662        onDownEventInternal(x, y, eventTime);
663        if (!sShouldHandleGesture) {
664            return;
665        }
666        final int activePointerTrackerCount = getActivePointerTrackerCount();
667        if (activePointerTrackerCount == 1) {
668            mIsDetectingGesture = false;
669            // A gesture should start only from the letter key.
670            final boolean isAlphabetKeyboard = (mKeyboard != null)
671                    && mKeyboard.mId.isAlphabetKeyboard();
672            if (isAlphabetKeyboard && !mIsShowingMoreKeysPanel && key != null
673                    && Keyboard.isLetterCode(key.mCode)) {
674                mIsDetectingGesture = true;
675                sGestureFirstDownTime = eventTime;
676                mGestureStrokeWithPreviewTrail.addPoint(x, y, 0, false /* isHistorical */);
677            }
678        } else if (sInGesture && activePointerTrackerCount > 1) {
679            mIsDetectingGesture = true;
680            final int elapsedTimeFromFirstDown = (int)(eventTime - sGestureFirstDownTime);
681            mGestureStrokeWithPreviewTrail.addPoint(x, y, elapsedTimeFromFirstDown,
682                    false /* isHistorical */);
683        }
684    }
685
686    private void onDownEventInternal(final int x, final int y, final long eventTime) {
687        Key key = onDownKey(x, y, eventTime);
688        // Sliding key is allowed when 1) enabled by configuration, 2) this pointer starts sliding
689        // from modifier key, or 3) this pointer's KeyDetector always allows sliding input.
690        mIsAllowedSlidingKeyInput = sParams.mSlidingKeyInputEnabled
691                || (key != null && key.isModifier())
692                || mKeyDetector.alwaysAllowsSlidingInput();
693        mKeyboardLayoutHasBeenChanged = false;
694        mKeyAlreadyProcessed = false;
695        mIsInSlidingKeyInput = false;
696        mIgnoreModifierKey = false;
697        if (key != null) {
698            // This onPress call may have changed keyboard layout. Those cases are detected at
699            // {@link #setKeyboard}. In those cases, we should update key according to the new
700            // keyboard layout.
701            if (callListenerOnPressAndCheckKeyboardLayoutChange(key)) {
702                key = onDownKey(x, y, eventTime);
703            }
704
705            startRepeatKey(key);
706            startLongPressTimer(key);
707            setPressedKeyGraphics(key);
708        }
709    }
710
711    private void startSlidingKeyInput(final Key key) {
712        if (!mIsInSlidingKeyInput) {
713            mIgnoreModifierKey = key.isModifier();
714        }
715        mIsInSlidingKeyInput = true;
716    }
717
718    private void onGestureMoveEvent(final int x, final int y, final long eventTime,
719            final boolean isHistorical, final Key key) {
720        final int gestureTime = (int)(eventTime - sGestureFirstDownTime);
721        if (mIsDetectingGesture) {
722            final GestureStroke stroke = mGestureStrokeWithPreviewTrail;
723            stroke.addPoint(x, y, gestureTime, isHistorical);
724            if (!sInGesture && stroke.isStartOfAGesture()) {
725                startBatchInput();
726            }
727
728            if (sInGesture && key != null) {
729                updateBatchInput(eventTime);
730            }
731        }
732    }
733
734    public void onMoveEvent(final int x, final int y, final long eventTime, final MotionEvent me) {
735        if (DEBUG_MOVE_EVENT) {
736            printTouchEvent("onMoveEvent:", x, y, eventTime);
737        }
738        if (mKeyAlreadyProcessed) {
739            return;
740        }
741
742        if (sShouldHandleGesture && me != null) {
743            // Add historical points to gesture path.
744            final int pointerIndex = me.findPointerIndex(mPointerId);
745            final int historicalSize = me.getHistorySize();
746            for (int h = 0; h < historicalSize; h++) {
747                final int historicalX = (int)me.getHistoricalX(pointerIndex, h);
748                final int historicalY = (int)me.getHistoricalY(pointerIndex, h);
749                final long historicalTime = me.getHistoricalEventTime(h);
750                onGestureMoveEvent(historicalX, historicalY, historicalTime,
751                        true /* isHistorical */, null);
752            }
753        }
754
755        onMoveEventInternal(x, y, eventTime);
756    }
757
758    private void onMoveEventInternal(final int x, final int y, final long eventTime) {
759        final int lastX = mLastX;
760        final int lastY = mLastY;
761        final Key oldKey = mCurrentKey;
762        Key key = onMoveKey(x, y);
763
764        if (sShouldHandleGesture) {
765            // Register move event on gesture tracker.
766            onGestureMoveEvent(x, y, eventTime, false /* isHistorical */, key);
767            if (sInGesture) {
768                mIgnoreModifierKey = true;
769                mTimerProxy.cancelLongPressTimer();
770                mIsInSlidingKeyInput = true;
771                mCurrentKey = null;
772                setReleasedKeyGraphics(oldKey);
773                return;
774            }
775        }
776
777        if (key != null) {
778            if (oldKey == null) {
779                // The pointer has been slid in to the new key, but the finger was not on any keys.
780                // In this case, we must call onPress() to notify that the new key is being pressed.
781                // This onPress call may have changed keyboard layout. Those cases are detected at
782                // {@link #setKeyboard}. In those cases, we should update key according to the
783                // new keyboard layout.
784                if (callListenerOnPressAndCheckKeyboardLayoutChange(key)) {
785                    key = onMoveKey(x, y);
786                }
787                onMoveToNewKey(key, x, y);
788                startLongPressTimer(key);
789                setPressedKeyGraphics(key);
790            } else if (isMajorEnoughMoveToBeOnNewKey(x, y, key)) {
791                // The pointer has been slid in to the new key from the previous key, we must call
792                // onRelease() first to notify that the previous key has been released, then call
793                // onPress() to notify that the new key is being pressed.
794                setReleasedKeyGraphics(oldKey);
795                callListenerOnRelease(oldKey, oldKey.mCode, true);
796                startSlidingKeyInput(oldKey);
797                mTimerProxy.cancelKeyTimers();
798                startRepeatKey(key);
799                if (mIsAllowedSlidingKeyInput) {
800                    // This onPress call may have changed keyboard layout. Those cases are detected
801                    // at {@link #setKeyboard}. In those cases, we should update key according
802                    // to the new keyboard layout.
803                    if (callListenerOnPressAndCheckKeyboardLayoutChange(key)) {
804                        key = onMoveKey(x, y);
805                    }
806                    onMoveToNewKey(key, x, y);
807                    startLongPressTimer(key);
808                    setPressedKeyGraphics(key);
809                } else {
810                    // HACK: On some devices, quick successive touches may be translated to sudden
811                    // move by touch panel firmware. This hack detects the case and translates the
812                    // move event to successive up and down events.
813                    final int dx = x - lastX;
814                    final int dy = y - lastY;
815                    final int lastMoveSquared = dx * dx + dy * dy;
816                    // TODO: Should find a way to balance gesture detection and this hack.
817                    if (sNeedsPhantomSuddenMoveEventHack
818                            && lastMoveSquared >= mKeyQuarterWidthSquared
819                            && !mIsDetectingGesture) {
820                        if (DEBUG_MODE) {
821                            Log.w(TAG, String.format("onMoveEvent:"
822                                    + " phantom sudden move event is translated to "
823                                    + "up[%d,%d]/down[%d,%d] events", lastX, lastY, x, y));
824                        }
825                        // TODO: This should be moved to outside of this nested if-clause?
826                        if (ProductionFlag.IS_EXPERIMENTAL) {
827                            ResearchLogger.pointerTracker_onMoveEvent(x, y, lastX, lastY);
828                        }
829                        onUpEventInternal();
830                        onDownEventInternal(x, y, eventTime);
831                    } else {
832                        // HACK: If there are currently multiple touches, register the key even if
833                        // the finger slides off the key. This defends against noise from some
834                        // touch panels when there are close multiple touches.
835                        // Caveat: When in chording input mode with a modifier key, we don't use
836                        // this hack.
837                        if (getActivePointerTrackerCount() > 1 && sPointerTrackerQueue != null
838                                && !sPointerTrackerQueue.hasModifierKeyOlderThan(this)) {
839                            onUpEventInternal();
840                        }
841                        if (!mIsDetectingGesture) {
842                            mKeyAlreadyProcessed = true;
843                        }
844                        setReleasedKeyGraphics(oldKey);
845                    }
846                }
847            }
848        } else {
849            if (oldKey != null && isMajorEnoughMoveToBeOnNewKey(x, y, key)) {
850                // The pointer has been slid out from the previous key, we must call onRelease() to
851                // notify that the previous key has been released.
852                setReleasedKeyGraphics(oldKey);
853                callListenerOnRelease(oldKey, oldKey.mCode, true);
854                startSlidingKeyInput(oldKey);
855                mTimerProxy.cancelLongPressTimer();
856                if (mIsAllowedSlidingKeyInput) {
857                    onMoveToNewKey(key, x, y);
858                } else {
859                    if (!mIsDetectingGesture) {
860                        mKeyAlreadyProcessed = true;
861                    }
862                }
863            }
864        }
865    }
866
867    public void onUpEvent(final int x, final int y, final long eventTime) {
868        if (DEBUG_EVENT) {
869            printTouchEvent("onUpEvent  :", x, y, eventTime);
870        }
871
872        final PointerTrackerQueue queue = sPointerTrackerQueue;
873        if (queue != null) {
874            if (!sInGesture) {
875                if (mCurrentKey != null && mCurrentKey.isModifier()) {
876                    // Before processing an up event of modifier key, all pointers already being
877                    // tracked should be released.
878                    queue.releaseAllPointersExcept(this, eventTime);
879                } else {
880                    queue.releaseAllPointersOlderThan(this, eventTime);
881                }
882            }
883        }
884        onUpEventInternal();
885        if (queue != null) {
886            queue.remove(this);
887        }
888    }
889
890    // Let this pointer tracker know that one of newer-than-this pointer trackers got an up event.
891    // This pointer tracker needs to keep the key top graphics "pressed", but needs to get a
892    // "virtual" up event.
893    @Override
894    public void onPhantomUpEvent(final long eventTime) {
895        if (DEBUG_EVENT) {
896            printTouchEvent("onPhntEvent:", getLastX(), getLastY(), eventTime);
897        }
898        onUpEventInternal();
899        mKeyAlreadyProcessed = true;
900    }
901
902    private void onUpEventInternal() {
903        mTimerProxy.cancelKeyTimers();
904        mIsInSlidingKeyInput = false;
905        mIsDetectingGesture = false;
906        final Key currentKey = mCurrentKey;
907        mCurrentKey = null;
908        // Release the last pressed key.
909        setReleasedKeyGraphics(currentKey);
910        if (mIsShowingMoreKeysPanel) {
911            mDrawingProxy.dismissMoreKeysPanel();
912            mIsShowingMoreKeysPanel = false;
913        }
914
915        if (sInGesture) {
916            if (currentKey != null) {
917                callListenerOnRelease(currentKey, currentKey.mCode, true);
918            }
919            endBatchInput();
920            return;
921        }
922        // This event will be recognized as a regular code input. Clear unused possible batch points
923        // so they are not mistakenly displayed as preview.
924        clearBatchInputPointsOfAllPointerTrackers();
925        if (mKeyAlreadyProcessed) {
926            return;
927        }
928        if (currentKey != null && !currentKey.isRepeatable()) {
929            detectAndSendKey(currentKey, mKeyX, mKeyY);
930        }
931    }
932
933    public void onShowMoreKeysPanel(final int x, final int y, final KeyEventHandler handler) {
934        abortBatchInput();
935        onLongPressed();
936        mIsShowingMoreKeysPanel = true;
937        onDownEvent(x, y, SystemClock.uptimeMillis(), handler);
938    }
939
940    public void onLongPressed() {
941        mKeyAlreadyProcessed = true;
942        setReleasedKeyGraphics(mCurrentKey);
943        final PointerTrackerQueue queue = sPointerTrackerQueue;
944        if (queue != null) {
945            queue.remove(this);
946        }
947    }
948
949    public void onCancelEvent(final int x, final int y, final long eventTime) {
950        if (DEBUG_EVENT) {
951            printTouchEvent("onCancelEvt:", x, y, eventTime);
952        }
953
954        final PointerTrackerQueue queue = sPointerTrackerQueue;
955        if (queue != null) {
956            queue.releaseAllPointersExcept(this, eventTime);
957            queue.remove(this);
958        }
959        onCancelEventInternal();
960    }
961
962    private void onCancelEventInternal() {
963        mTimerProxy.cancelKeyTimers();
964        setReleasedKeyGraphics(mCurrentKey);
965        mIsInSlidingKeyInput = false;
966        if (mIsShowingMoreKeysPanel) {
967            mDrawingProxy.dismissMoreKeysPanel();
968            mIsShowingMoreKeysPanel = false;
969        }
970    }
971
972    private void startRepeatKey(final Key key) {
973        if (key != null && key.isRepeatable() && !sInGesture) {
974            onRegisterKey(key);
975            mTimerProxy.startKeyRepeatTimer(this);
976        }
977    }
978
979    public void onRegisterKey(final Key key) {
980        if (key != null) {
981            detectAndSendKey(key, key.mX, key.mY);
982            mTimerProxy.startTypingStateTimer(key);
983        }
984    }
985
986    private boolean isMajorEnoughMoveToBeOnNewKey(final int x, final int y, final Key newKey) {
987        if (mKeyDetector == null) {
988            throw new NullPointerException("keyboard and/or key detector not set");
989        }
990        final Key curKey = mCurrentKey;
991        if (newKey == curKey) {
992            return false;
993        } else if (curKey != null) {
994            return curKey.squaredDistanceToEdge(x, y)
995                    >= mKeyDetector.getKeyHysteresisDistanceSquared();
996        } else {
997            return true;
998        }
999    }
1000
1001    private void startLongPressTimer(final Key key) {
1002        if (key != null && key.isLongPressEnabled() && !sInGesture) {
1003            mTimerProxy.startLongPressTimer(this);
1004        }
1005    }
1006
1007    private void detectAndSendKey(final Key key, final int x, final int y) {
1008        if (key == null) {
1009            callListenerOnCancelInput();
1010            return;
1011        }
1012
1013        final int code = key.mCode;
1014        callListenerOnCodeInput(key, code, x, y);
1015        callListenerOnRelease(key, code, false);
1016    }
1017
1018    private void printTouchEvent(final String title, final int x, final int y,
1019            final long eventTime) {
1020        final Key key = mKeyDetector.detectHitKey(x, y);
1021        final String code = KeyDetector.printableCode(key);
1022        Log.d(TAG, String.format("%s%s[%d] %4d %4d %5d %s", title,
1023                (mKeyAlreadyProcessed ? "-" : " "), mPointerId, x, y, eventTime, code));
1024    }
1025}
1026