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