KeyboardView.java revision 8b37eb0c2a94d32c012a2709ddb0effc985b1d65
1/*
2 * Copyright (C) 2008-2009 Google Inc.
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 android.inputmethodservice;
18
19import android.content.Context;
20import android.content.res.TypedArray;
21import android.graphics.Bitmap;
22import android.graphics.Canvas;
23import android.graphics.Paint;
24import android.graphics.PorterDuff;
25import android.graphics.Rect;
26import android.graphics.Typeface;
27import android.graphics.Paint.Align;
28import android.graphics.Region.Op;
29import android.graphics.drawable.Drawable;
30import android.inputmethodservice.Keyboard.Key;
31import android.os.Handler;
32import android.os.Message;
33import android.util.AttributeSet;
34import android.util.TypedValue;
35import android.view.GestureDetector;
36import android.view.Gravity;
37import android.view.LayoutInflater;
38import android.view.MotionEvent;
39import android.view.View;
40import android.view.ViewConfiguration;
41import android.view.ViewGroup.LayoutParams;
42import android.widget.PopupWindow;
43import android.widget.TextView;
44
45import com.android.internal.R;
46
47import java.util.Arrays;
48import java.util.HashMap;
49import java.util.List;
50import java.util.Map;
51
52/**
53 * A view that renders a virtual {@link Keyboard}. It handles rendering of keys and
54 * detecting key presses and touch movements.
55 *
56 * @attr ref android.R.styleable#KeyboardView_keyBackground
57 * @attr ref android.R.styleable#KeyboardView_keyPreviewLayout
58 * @attr ref android.R.styleable#KeyboardView_keyPreviewOffset
59 * @attr ref android.R.styleable#KeyboardView_labelTextSize
60 * @attr ref android.R.styleable#KeyboardView_keyTextSize
61 * @attr ref android.R.styleable#KeyboardView_keyTextColor
62 * @attr ref android.R.styleable#KeyboardView_verticalCorrection
63 * @attr ref android.R.styleable#KeyboardView_popupLayout
64 */
65public class KeyboardView extends View implements View.OnClickListener {
66
67    /**
68     * Listener for virtual keyboard events.
69     */
70    public interface OnKeyboardActionListener {
71
72        /**
73         * Called when the user presses a key. This is sent before the {@link #onKey} is called.
74         * For keys that repeat, this is only called once.
75         * @param primaryCode the unicode of the key being pressed. If the touch is not on a valid
76         * key, the value will be zero.
77         */
78        void onPress(int primaryCode);
79
80        /**
81         * Called when the user releases a key. This is sent after the {@link #onKey} is called.
82         * For keys that repeat, this is only called once.
83         * @param primaryCode the code of the key that was released
84         */
85        void onRelease(int primaryCode);
86
87        /**
88         * Send a key press to the listener.
89         * @param primaryCode this is the key that was pressed
90         * @param keyCodes the codes for all the possible alternative keys
91         * with the primary code being the first. If the primary key code is
92         * a single character such as an alphabet or number or symbol, the alternatives
93         * will include other characters that may be on the same key or adjacent keys.
94         * These codes are useful to correct for accidental presses of a key adjacent to
95         * the intended key.
96         */
97        void onKey(int primaryCode, int[] keyCodes);
98
99        /**
100         * Sends a sequence of characters to the listener.
101         * @param text the sequence of characters to be displayed.
102         */
103        void onText(CharSequence text);
104
105        /**
106         * Called when the user quickly moves the finger from right to left.
107         */
108        void swipeLeft();
109
110        /**
111         * Called when the user quickly moves the finger from left to right.
112         */
113        void swipeRight();
114
115        /**
116         * Called when the user quickly moves the finger from up to down.
117         */
118        void swipeDown();
119
120        /**
121         * Called when the user quickly moves the finger from down to up.
122         */
123        void swipeUp();
124    }
125
126    private static final boolean DEBUG = false;
127    private static final int NOT_A_KEY = -1;
128    private static final int[] KEY_DELETE = { Keyboard.KEYCODE_DELETE };
129    private static final int[] LONG_PRESSABLE_STATE_SET = { R.attr.state_long_pressable };
130
131    private Keyboard mKeyboard;
132    private int mCurrentKeyIndex = NOT_A_KEY;
133    private int mLabelTextSize;
134    private int mKeyTextSize;
135    private int mKeyTextColor;
136    private float mShadowRadius;
137    private int mShadowColor;
138    private float mBackgroundDimAmount;
139
140    private TextView mPreviewText;
141    private PopupWindow mPreviewPopup;
142    private int mPreviewTextSizeLarge;
143    private int mPreviewOffset;
144    private int mPreviewHeight;
145    private int[] mOffsetInWindow;
146
147    private PopupWindow mPopupKeyboard;
148    private View mMiniKeyboardContainer;
149    private KeyboardView mMiniKeyboard;
150    private boolean mMiniKeyboardOnScreen;
151    private View mPopupParent;
152    private int mMiniKeyboardOffsetX;
153    private int mMiniKeyboardOffsetY;
154    private Map<Key,View> mMiniKeyboardCache;
155    private int[] mWindowOffset;
156    private Key[] mKeys;
157
158    /** Listener for {@link OnKeyboardActionListener}. */
159    private OnKeyboardActionListener mKeyboardActionListener;
160
161    private static final int MSG_SHOW_PREVIEW = 1;
162    private static final int MSG_REMOVE_PREVIEW = 2;
163    private static final int MSG_REPEAT = 3;
164    private static final int MSG_LONGPRESS = 4;
165
166    private static final int DELAY_BEFORE_PREVIEW = 0;
167    private static final int DELAY_AFTER_PREVIEW = 70;
168
169    private int mVerticalCorrection;
170    private int mProximityThreshold;
171
172    private boolean mPreviewCentered = false;
173    private boolean mShowPreview = true;
174    private boolean mShowTouchPoints = true;
175    private int mPopupPreviewX;
176    private int mPopupPreviewY;
177
178    private int mLastX;
179    private int mLastY;
180    private int mStartX;
181    private int mStartY;
182
183    private boolean mProximityCorrectOn;
184
185    private Paint mPaint;
186    private Rect mPadding;
187
188    private long mDownTime;
189    private long mLastMoveTime;
190    private int mLastKey;
191    private int mLastCodeX;
192    private int mLastCodeY;
193    private int mCurrentKey = NOT_A_KEY;
194    private long mLastKeyTime;
195    private long mCurrentKeyTime;
196    private int[] mKeyIndices = new int[12];
197    private GestureDetector mGestureDetector;
198    private int mPopupX;
199    private int mPopupY;
200    private int mRepeatKeyIndex = NOT_A_KEY;
201    private int mPopupLayout;
202    private boolean mAbortKey;
203    private Key mInvalidatedKey;
204    private Rect mClipRegion = new Rect(0, 0, 0, 0);
205
206    // Variables for dealing with multiple pointers
207    private int mOldPointerCount = 1;
208    private float mOldPointerX;
209    private float mOldPointerY;
210
211    private Drawable mKeyBackground;
212
213    private static final int REPEAT_INTERVAL = 50; // ~20 keys per second
214    private static final int REPEAT_START_DELAY = 400;
215    private static final int LONGPRESS_TIMEOUT = ViewConfiguration.getLongPressTimeout();
216
217    private static int MAX_NEARBY_KEYS = 12;
218    private int[] mDistances = new int[MAX_NEARBY_KEYS];
219
220    // For multi-tap
221    private int mLastSentIndex;
222    private int mTapCount;
223    private long mLastTapTime;
224    private boolean mInMultiTap;
225    private static final int MULTITAP_INTERVAL = 800; // milliseconds
226    private StringBuilder mPreviewLabel = new StringBuilder(1);
227
228    /** Whether the keyboard bitmap needs to be redrawn before it's blitted. **/
229    private boolean mDrawPending;
230    /** The dirty region in the keyboard bitmap */
231    private Rect mDirtyRect = new Rect();
232    /** The keyboard bitmap for faster updates */
233    private Bitmap mBuffer;
234    /** Notes if the keyboard just changed, so that we could possibly reallocate the mBuffer. */
235    private boolean mKeyboardChanged;
236    /** The canvas for the above mutable keyboard bitmap */
237    private Canvas mCanvas;
238
239    Handler mHandler = new Handler() {
240        @Override
241        public void handleMessage(Message msg) {
242            switch (msg.what) {
243                case MSG_SHOW_PREVIEW:
244                    showKey(msg.arg1);
245                    break;
246                case MSG_REMOVE_PREVIEW:
247                    mPreviewText.setVisibility(INVISIBLE);
248                    break;
249                case MSG_REPEAT:
250                    if (repeatKey()) {
251                        Message repeat = Message.obtain(this, MSG_REPEAT);
252                        sendMessageDelayed(repeat, REPEAT_INTERVAL);
253                    }
254                    break;
255                case MSG_LONGPRESS:
256                    openPopupIfRequired((MotionEvent) msg.obj);
257                    break;
258            }
259        }
260    };
261
262    public KeyboardView(Context context, AttributeSet attrs) {
263        this(context, attrs, com.android.internal.R.attr.keyboardViewStyle);
264    }
265
266    public KeyboardView(Context context, AttributeSet attrs, int defStyle) {
267        super(context, attrs, defStyle);
268
269        TypedArray a =
270            context.obtainStyledAttributes(
271                attrs, android.R.styleable.KeyboardView, defStyle, 0);
272
273        LayoutInflater inflate =
274                (LayoutInflater) context
275                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
276
277        int previewLayout = 0;
278        int keyTextSize = 0;
279
280        int n = a.getIndexCount();
281
282        for (int i = 0; i < n; i++) {
283            int attr = a.getIndex(i);
284
285            switch (attr) {
286            case com.android.internal.R.styleable.KeyboardView_keyBackground:
287                mKeyBackground = a.getDrawable(attr);
288                break;
289            case com.android.internal.R.styleable.KeyboardView_verticalCorrection:
290                mVerticalCorrection = a.getDimensionPixelOffset(attr, 0);
291                break;
292            case com.android.internal.R.styleable.KeyboardView_keyPreviewLayout:
293                previewLayout = a.getResourceId(attr, 0);
294                break;
295            case com.android.internal.R.styleable.KeyboardView_keyPreviewOffset:
296                mPreviewOffset = a.getDimensionPixelOffset(attr, 0);
297                break;
298            case com.android.internal.R.styleable.KeyboardView_keyPreviewHeight:
299                mPreviewHeight = a.getDimensionPixelSize(attr, 80);
300                break;
301            case com.android.internal.R.styleable.KeyboardView_keyTextSize:
302                mKeyTextSize = a.getDimensionPixelSize(attr, 18);
303                break;
304            case com.android.internal.R.styleable.KeyboardView_keyTextColor:
305                mKeyTextColor = a.getColor(attr, 0xFF000000);
306                break;
307            case com.android.internal.R.styleable.KeyboardView_labelTextSize:
308                mLabelTextSize = a.getDimensionPixelSize(attr, 14);
309                break;
310            case com.android.internal.R.styleable.KeyboardView_popupLayout:
311                mPopupLayout = a.getResourceId(attr, 0);
312                break;
313            case com.android.internal.R.styleable.KeyboardView_shadowColor:
314                mShadowColor = a.getColor(attr, 0);
315                break;
316            case com.android.internal.R.styleable.KeyboardView_shadowRadius:
317                mShadowRadius = a.getFloat(attr, 0f);
318                break;
319            }
320        }
321
322        a = mContext.obtainStyledAttributes(
323                com.android.internal.R.styleable.Theme);
324        mBackgroundDimAmount = a.getFloat(android.R.styleable.Theme_backgroundDimAmount, 0.5f);
325
326        mPreviewPopup = new PopupWindow(context);
327        if (previewLayout != 0) {
328            mPreviewText = (TextView) inflate.inflate(previewLayout, null);
329            mPreviewTextSizeLarge = (int) mPreviewText.getTextSize();
330            mPreviewPopup.setContentView(mPreviewText);
331            mPreviewPopup.setBackgroundDrawable(null);
332        } else {
333            mShowPreview = false;
334        }
335
336        mPreviewPopup.setTouchable(false);
337
338        mPopupKeyboard = new PopupWindow(context);
339        mPopupKeyboard.setBackgroundDrawable(null);
340        //mPopupKeyboard.setClippingEnabled(false);
341
342        mPopupParent = this;
343        //mPredicting = true;
344
345        mPaint = new Paint();
346        mPaint.setAntiAlias(true);
347        mPaint.setTextSize(keyTextSize);
348        mPaint.setTextAlign(Align.CENTER);
349        mPaint.setAlpha(255);
350
351        mPadding = new Rect(0, 0, 0, 0);
352        mMiniKeyboardCache = new HashMap<Key,View>();
353        mKeyBackground.getPadding(mPadding);
354
355        resetMultiTap();
356        initGestureDetector();
357    }
358
359    private void initGestureDetector() {
360        mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
361            @Override
362            public boolean onFling(MotionEvent me1, MotionEvent me2,
363                    float velocityX, float velocityY) {
364                final float absX = Math.abs(velocityX);
365                final float absY = Math.abs(velocityY);
366                if (velocityX > 500 && absY < absX) {
367                    swipeRight();
368                    return true;
369                } else if (velocityX < -500 && absY < absX) {
370                    swipeLeft();
371                    return true;
372                } else if (velocityY < -500 && absX < absY) {
373                    swipeUp();
374                    return true;
375                } else if (velocityY > 500 && absX < 200) {
376                    swipeDown();
377                    return true;
378                } else if (absX > 800 || absY > 800) {
379                    return true;
380                }
381                return false;
382            }
383        });
384
385        mGestureDetector.setIsLongpressEnabled(false);
386    }
387
388    public void setOnKeyboardActionListener(OnKeyboardActionListener listener) {
389        mKeyboardActionListener = listener;
390    }
391
392    /**
393     * Returns the {@link OnKeyboardActionListener} object.
394     * @return the listener attached to this keyboard
395     */
396    protected OnKeyboardActionListener getOnKeyboardActionListener() {
397        return mKeyboardActionListener;
398    }
399
400    /**
401     * Attaches a keyboard to this view. The keyboard can be switched at any time and the
402     * view will re-layout itself to accommodate the keyboard.
403     * @see Keyboard
404     * @see #getKeyboard()
405     * @param keyboard the keyboard to display in this view
406     */
407    public void setKeyboard(Keyboard keyboard) {
408        if (mKeyboard != null) {
409            showPreview(NOT_A_KEY);
410        }
411        mKeyboard = keyboard;
412        List<Key> keys = mKeyboard.getKeys();
413        mKeys = keys.toArray(new Key[keys.size()]);
414        requestLayout();
415        // Hint to reallocate the buffer if the size changed
416        mKeyboardChanged = true;
417        invalidateAllKeys();
418        computeProximityThreshold(keyboard);
419        mMiniKeyboardCache.clear(); // Not really necessary to do every time, but will free up views
420        // Switching to a different keyboard should abort any pending keys so that the key up
421        // doesn't get delivered to the old or new keyboard
422        mAbortKey = true; // Until the next ACTION_DOWN
423    }
424
425    /**
426     * Returns the current keyboard being displayed by this view.
427     * @return the currently attached keyboard
428     * @see #setKeyboard(Keyboard)
429     */
430    public Keyboard getKeyboard() {
431        return mKeyboard;
432    }
433
434    /**
435     * Sets the state of the shift key of the keyboard, if any.
436     * @param shifted whether or not to enable the state of the shift key
437     * @return true if the shift key state changed, false if there was no change
438     * @see KeyboardView#isShifted()
439     */
440    public boolean setShifted(boolean shifted) {
441        if (mKeyboard != null) {
442            if (mKeyboard.setShifted(shifted)) {
443                // The whole keyboard probably needs to be redrawn
444                invalidateAllKeys();
445                return true;
446            }
447        }
448        return false;
449    }
450
451    /**
452     * Returns the state of the shift key of the keyboard, if any.
453     * @return true if the shift is in a pressed state, false otherwise. If there is
454     * no shift key on the keyboard or there is no keyboard attached, it returns false.
455     * @see KeyboardView#setShifted(boolean)
456     */
457    public boolean isShifted() {
458        if (mKeyboard != null) {
459            return mKeyboard.isShifted();
460        }
461        return false;
462    }
463
464    /**
465     * Enables or disables the key feedback popup. This is a popup that shows a magnified
466     * version of the depressed key. By default the preview is enabled.
467     * @param previewEnabled whether or not to enable the key feedback popup
468     * @see #isPreviewEnabled()
469     */
470    public void setPreviewEnabled(boolean previewEnabled) {
471        mShowPreview = previewEnabled;
472    }
473
474    /**
475     * Returns the enabled state of the key feedback popup.
476     * @return whether or not the key feedback popup is enabled
477     * @see #setPreviewEnabled(boolean)
478     */
479    public boolean isPreviewEnabled() {
480        return mShowPreview;
481    }
482
483    public void setVerticalCorrection(int verticalOffset) {
484
485    }
486    public void setPopupParent(View v) {
487        mPopupParent = v;
488    }
489
490    public void setPopupOffset(int x, int y) {
491        mMiniKeyboardOffsetX = x;
492        mMiniKeyboardOffsetY = y;
493        if (mPreviewPopup.isShowing()) {
494            mPreviewPopup.dismiss();
495        }
496    }
497
498    /**
499     * When enabled, calls to {@link OnKeyboardActionListener#onKey} will include key
500     * codes for adjacent keys.  When disabled, only the primary key code will be
501     * reported.
502     * @param enabled whether or not the proximity correction is enabled
503     */
504    public void setProximityCorrectionEnabled(boolean enabled) {
505        mProximityCorrectOn = enabled;
506    }
507
508    /**
509     * Returns true if proximity correction is enabled.
510     */
511    public boolean isProximityCorrectionEnabled() {
512        return mProximityCorrectOn;
513    }
514
515    /**
516     * Popup keyboard close button clicked.
517     * @hide
518     */
519    public void onClick(View v) {
520        dismissPopupKeyboard();
521    }
522
523    private CharSequence adjustCase(CharSequence label) {
524        if (mKeyboard.isShifted() && label != null && label.length() < 3
525                && Character.isLowerCase(label.charAt(0))) {
526            label = label.toString().toUpperCase();
527        }
528        return label;
529    }
530
531    @Override
532    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
533        // Round up a little
534        if (mKeyboard == null) {
535            setMeasuredDimension(mPaddingLeft + mPaddingRight, mPaddingTop + mPaddingBottom);
536        } else {
537            int width = mKeyboard.getMinWidth() + mPaddingLeft + mPaddingRight;
538            if (MeasureSpec.getSize(widthMeasureSpec) < width + 10) {
539                width = MeasureSpec.getSize(widthMeasureSpec);
540            }
541            setMeasuredDimension(width, mKeyboard.getHeight() + mPaddingTop + mPaddingBottom);
542        }
543    }
544
545    /**
546     * Compute the average distance between adjacent keys (horizontally and vertically)
547     * and square it to get the proximity threshold. We use a square here and in computing
548     * the touch distance from a key's center to avoid taking a square root.
549     * @param keyboard
550     */
551    private void computeProximityThreshold(Keyboard keyboard) {
552        if (keyboard == null) return;
553        final Key[] keys = mKeys;
554        if (keys == null) return;
555        int length = keys.length;
556        int dimensionSum = 0;
557        for (int i = 0; i < length; i++) {
558            Key key = keys[i];
559            dimensionSum += Math.min(key.width, key.height) + key.gap;
560        }
561        if (dimensionSum < 0 || length == 0) return;
562        mProximityThreshold = (int) (dimensionSum * 1.4f / length);
563        mProximityThreshold *= mProximityThreshold; // Square it
564    }
565
566    @Override
567    public void onSizeChanged(int w, int h, int oldw, int oldh) {
568        super.onSizeChanged(w, h, oldw, oldh);
569        // Release the buffer, if any and it will be reallocated on the next draw
570        mBuffer = null;
571    }
572
573    @Override
574    public void onDraw(Canvas canvas) {
575        super.onDraw(canvas);
576        if (mDrawPending || mBuffer == null || mKeyboardChanged) {
577            onBufferDraw();
578        }
579        canvas.drawBitmap(mBuffer, 0, 0, null);
580    }
581
582    private void onBufferDraw() {
583        if (mBuffer == null || mKeyboardChanged) {
584            if (mBuffer == null || mKeyboardChanged &&
585                    (mBuffer.getWidth() != getWidth() || mBuffer.getHeight() != getHeight())) {
586                mBuffer = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
587                mCanvas = new Canvas(mBuffer);
588            }
589            invalidateAllKeys();
590            mKeyboardChanged = false;
591        }
592        final Canvas canvas = mCanvas;
593        canvas.clipRect(mDirtyRect, Op.REPLACE);
594
595        if (mKeyboard == null) return;
596
597        final Paint paint = mPaint;
598        final Drawable keyBackground = mKeyBackground;
599        final Rect clipRegion = mClipRegion;
600        final Rect padding = mPadding;
601        final int kbdPaddingLeft = mPaddingLeft;
602        final int kbdPaddingTop = mPaddingTop;
603        final Key[] keys = mKeys;
604        final Key invalidKey = mInvalidatedKey;
605
606        paint.setColor(mKeyTextColor);
607        boolean drawSingleKey = false;
608        if (invalidKey != null && canvas.getClipBounds(clipRegion)) {
609          // Is clipRegion completely contained within the invalidated key?
610          if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left &&
611                  invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top &&
612                  invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right &&
613                  invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) {
614              drawSingleKey = true;
615          }
616        }
617        canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
618        final int keyCount = keys.length;
619        for (int i = 0; i < keyCount; i++) {
620            final Key key = keys[i];
621            if (drawSingleKey && invalidKey != key) {
622                continue;
623            }
624            int[] drawableState = key.getCurrentDrawableState();
625            keyBackground.setState(drawableState);
626
627            // Switch the character to uppercase if shift is pressed
628            String label = key.label == null? null : adjustCase(key.label).toString();
629
630            final Rect bounds = keyBackground.getBounds();
631            if (key.width != bounds.right ||
632                    key.height != bounds.bottom) {
633                keyBackground.setBounds(0, 0, key.width, key.height);
634            }
635            canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop);
636            keyBackground.draw(canvas);
637
638            if (label != null) {
639                // For characters, use large font. For labels like "Done", use small font.
640                if (label.length() > 1 && key.codes.length < 2) {
641                    paint.setTextSize(mLabelTextSize);
642                    paint.setTypeface(Typeface.DEFAULT_BOLD);
643                } else {
644                    paint.setTextSize(mKeyTextSize);
645                    paint.setTypeface(Typeface.DEFAULT);
646                }
647                // Draw a drop shadow for the text
648                paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor);
649                // Draw the text
650                canvas.drawText(label,
651                    (key.width - padding.left - padding.right) / 2
652                            + padding.left,
653                    (key.height - padding.top - padding.bottom) / 2
654                            + (paint.getTextSize() - paint.descent()) / 2 + padding.top,
655                    paint);
656                // Turn off drop shadow
657                paint.setShadowLayer(0, 0, 0, 0);
658            } else if (key.icon != null) {
659                final int drawableX = (key.width - padding.left - padding.right
660                                - key.icon.getIntrinsicWidth()) / 2 + padding.left;
661                final int drawableY = (key.height - padding.top - padding.bottom
662                        - key.icon.getIntrinsicHeight()) / 2 + padding.top;
663                canvas.translate(drawableX, drawableY);
664                key.icon.setBounds(0, 0,
665                        key.icon.getIntrinsicWidth(), key.icon.getIntrinsicHeight());
666                key.icon.draw(canvas);
667                canvas.translate(-drawableX, -drawableY);
668            }
669            canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop);
670        }
671        mInvalidatedKey = null;
672        // Overlay a dark rectangle to dim the keyboard
673        if (mMiniKeyboardOnScreen) {
674            paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24);
675            canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
676        }
677
678        if (DEBUG && mShowTouchPoints) {
679            paint.setAlpha(128);
680            paint.setColor(0xFFFF0000);
681            canvas.drawCircle(mStartX, mStartY, 3, paint);
682            canvas.drawLine(mStartX, mStartY, mLastX, mLastY, paint);
683            paint.setColor(0xFF0000FF);
684            canvas.drawCircle(mLastX, mLastY, 3, paint);
685            paint.setColor(0xFF00FF00);
686            canvas.drawCircle((mStartX + mLastX) / 2, (mStartY + mLastY) / 2, 2, paint);
687        }
688
689        mDrawPending = false;
690        mDirtyRect.setEmpty();
691    }
692
693    private int getKeyIndices(int x, int y, int[] allKeys) {
694        final Key[] keys = mKeys;
695        int primaryIndex = NOT_A_KEY;
696        int closestKey = NOT_A_KEY;
697        int closestKeyDist = mProximityThreshold + 1;
698        java.util.Arrays.fill(mDistances, Integer.MAX_VALUE);
699        int [] nearestKeyIndices = mKeyboard.getNearestKeys(x, y);
700        final int keyCount = nearestKeyIndices.length;
701        for (int i = 0; i < keyCount; i++) {
702            final Key key = keys[nearestKeyIndices[i]];
703            int dist = 0;
704            boolean isInside = key.isInside(x,y);
705            if (((mProximityCorrectOn
706                    && (dist = key.squaredDistanceFrom(x, y)) < mProximityThreshold)
707                    || isInside)
708                    && key.codes[0] > 32) {
709                // Find insertion point
710                final int nCodes = key.codes.length;
711                if (dist < closestKeyDist) {
712                    closestKeyDist = dist;
713                    closestKey = nearestKeyIndices[i];
714                }
715
716                if (allKeys == null) continue;
717
718                for (int j = 0; j < mDistances.length; j++) {
719                    if (mDistances[j] > dist) {
720                        // Make space for nCodes codes
721                        System.arraycopy(mDistances, j, mDistances, j + nCodes,
722                                mDistances.length - j - nCodes);
723                        System.arraycopy(allKeys, j, allKeys, j + nCodes,
724                                allKeys.length - j - nCodes);
725                        for (int c = 0; c < nCodes; c++) {
726                            allKeys[j + c] = key.codes[c];
727                            mDistances[j + c] = dist;
728                        }
729                        break;
730                    }
731                }
732            }
733
734            if (isInside) {
735                primaryIndex = nearestKeyIndices[i];
736            }
737        }
738        if (primaryIndex == NOT_A_KEY) {
739            primaryIndex = closestKey;
740        }
741        return primaryIndex;
742    }
743
744    private void detectAndSendKey(int x, int y, long eventTime) {
745        int index = mCurrentKey;
746        if (index != NOT_A_KEY && index < mKeys.length) {
747            final Key key = mKeys[index];
748            if (key.text != null) {
749                mKeyboardActionListener.onText(key.text);
750                mKeyboardActionListener.onRelease(NOT_A_KEY);
751            } else {
752                int code = key.codes[0];
753                //TextEntryState.keyPressedAt(key, x, y);
754                int[] codes = new int[MAX_NEARBY_KEYS];
755                Arrays.fill(codes, NOT_A_KEY);
756                getKeyIndices(x, y, codes);
757                // Multi-tap
758                if (mInMultiTap) {
759                    if (mTapCount != -1) {
760                        mKeyboardActionListener.onKey(Keyboard.KEYCODE_DELETE, KEY_DELETE);
761                    } else {
762                        mTapCount = 0;
763                    }
764                    code = key.codes[mTapCount];
765                }
766                mKeyboardActionListener.onKey(code, codes);
767                mKeyboardActionListener.onRelease(code);
768            }
769            mLastSentIndex = index;
770            mLastTapTime = eventTime;
771        }
772    }
773
774    /**
775     * Handle multi-tap keys by producing the key label for the current multi-tap state.
776     */
777    private CharSequence getPreviewText(Key key) {
778        if (mInMultiTap) {
779            // Multi-tap
780            mPreviewLabel.setLength(0);
781            mPreviewLabel.append((char) key.codes[mTapCount < 0 ? 0 : mTapCount]);
782            return adjustCase(mPreviewLabel);
783        } else {
784            return adjustCase(key.label);
785        }
786    }
787
788    private void showPreview(int keyIndex) {
789        int oldKeyIndex = mCurrentKeyIndex;
790        final PopupWindow previewPopup = mPreviewPopup;
791
792        mCurrentKeyIndex = keyIndex;
793        // Release the old key and press the new key
794        final Key[] keys = mKeys;
795        if (oldKeyIndex != mCurrentKeyIndex) {
796            if (oldKeyIndex != NOT_A_KEY && keys.length > oldKeyIndex) {
797                keys[oldKeyIndex].onReleased(mCurrentKeyIndex == NOT_A_KEY);
798                invalidateKey(oldKeyIndex);
799            }
800            if (mCurrentKeyIndex != NOT_A_KEY && keys.length > mCurrentKeyIndex) {
801                keys[mCurrentKeyIndex].onPressed();
802                invalidateKey(mCurrentKeyIndex);
803            }
804        }
805        // If key changed and preview is on ...
806        if (oldKeyIndex != mCurrentKeyIndex && mShowPreview) {
807            mHandler.removeMessages(MSG_SHOW_PREVIEW);
808            if (previewPopup.isShowing()) {
809                if (keyIndex == NOT_A_KEY) {
810                    mHandler.sendMessageDelayed(mHandler
811                            .obtainMessage(MSG_REMOVE_PREVIEW),
812                            DELAY_AFTER_PREVIEW);
813                }
814            }
815            if (keyIndex != NOT_A_KEY) {
816                if (previewPopup.isShowing() && mPreviewText.getVisibility() == VISIBLE) {
817                    // Show right away, if it's already visible and finger is moving around
818                    showKey(keyIndex);
819                } else {
820                    mHandler.sendMessageDelayed(
821                            mHandler.obtainMessage(MSG_SHOW_PREVIEW, keyIndex, 0),
822                            DELAY_BEFORE_PREVIEW);
823                }
824            }
825        }
826    }
827
828    private void showKey(final int keyIndex) {
829        final PopupWindow previewPopup = mPreviewPopup;
830        final Key[] keys = mKeys;
831        Key key = keys[keyIndex];
832        if (key.icon != null) {
833            mPreviewText.setCompoundDrawables(null, null, null,
834                    key.iconPreview != null ? key.iconPreview : key.icon);
835            mPreviewText.setText(null);
836        } else {
837            mPreviewText.setCompoundDrawables(null, null, null, null);
838            mPreviewText.setText(getPreviewText(key));
839            if (key.label.length() > 1 && key.codes.length < 2) {
840                mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mKeyTextSize);
841                mPreviewText.setTypeface(Typeface.DEFAULT_BOLD);
842            } else {
843                mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPreviewTextSizeLarge);
844                mPreviewText.setTypeface(Typeface.DEFAULT);
845            }
846        }
847        mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
848                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
849        int popupWidth = Math.max(mPreviewText.getMeasuredWidth(), key.width
850                + mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight());
851        final int popupHeight = mPreviewHeight;
852        LayoutParams lp = mPreviewText.getLayoutParams();
853        if (lp != null) {
854            lp.width = popupWidth;
855            lp.height = popupHeight;
856        }
857        if (!mPreviewCentered) {
858            mPopupPreviewX = key.x - mPreviewText.getPaddingLeft() + mPaddingLeft;
859            mPopupPreviewY = key.y - popupHeight + mPreviewOffset;
860        } else {
861            // TODO: Fix this if centering is brought back
862            mPopupPreviewX = 160 - mPreviewText.getMeasuredWidth() / 2;
863            mPopupPreviewY = - mPreviewText.getMeasuredHeight();
864        }
865        mHandler.removeMessages(MSG_REMOVE_PREVIEW);
866        if (mOffsetInWindow == null) {
867            mOffsetInWindow = new int[2];
868            getLocationInWindow(mOffsetInWindow);
869            mOffsetInWindow[0] += mMiniKeyboardOffsetX; // Offset may be zero
870            mOffsetInWindow[1] += mMiniKeyboardOffsetY; // Offset may be zero
871        }
872        // Set the preview background state
873        mPreviewText.getBackground().setState(
874                key.popupResId != 0 ? LONG_PRESSABLE_STATE_SET : EMPTY_STATE_SET);
875        if (previewPopup.isShowing()) {
876            previewPopup.update(mPopupPreviewX + mOffsetInWindow[0],
877                    mPopupPreviewY + mOffsetInWindow[1],
878                    popupWidth, popupHeight);
879        } else {
880            previewPopup.setWidth(popupWidth);
881            previewPopup.setHeight(popupHeight);
882            previewPopup.showAtLocation(mPopupParent, Gravity.NO_GRAVITY,
883                    mPopupPreviewX + mOffsetInWindow[0],
884                    mPopupPreviewY + mOffsetInWindow[1]);
885        }
886        mPreviewText.setVisibility(VISIBLE);
887    }
888
889    /**
890     * Requests a redraw of the entire keyboard. Calling {@link #invalidate} is not sufficient
891     * because the keyboard renders the keys to an off-screen buffer and an invalidate() only
892     * draws the cached buffer.
893     * @see #invalidateKey(int)
894     */
895    public void invalidateAllKeys() {
896        mDirtyRect.union(0, 0, getWidth(), getHeight());
897        mDrawPending = true;
898        invalidate();
899    }
900
901    /**
902     * Invalidates a key so that it will be redrawn on the next repaint. Use this method if only
903     * one key is changing it's content. Any changes that affect the position or size of the key
904     * may not be honored.
905     * @param keyIndex the index of the key in the attached {@link Keyboard}.
906     * @see #invalidateAllKeys
907     */
908    public void invalidateKey(int keyIndex) {
909        if (mKeys == null) return;
910        if (keyIndex < 0 || keyIndex >= mKeys.length) {
911            return;
912        }
913        final Key key = mKeys[keyIndex];
914        mInvalidatedKey = key;
915        mDirtyRect.union(key.x + mPaddingLeft, key.y + mPaddingTop,
916                key.x + key.width + mPaddingLeft, key.y + key.height + mPaddingTop);
917        onBufferDraw();
918        invalidate(key.x + mPaddingLeft, key.y + mPaddingTop,
919                key.x + key.width + mPaddingLeft, key.y + key.height + mPaddingTop);
920    }
921
922    private boolean openPopupIfRequired(MotionEvent me) {
923        // Check if we have a popup layout specified first.
924        if (mPopupLayout == 0) {
925            return false;
926        }
927        if (mCurrentKey < 0 || mCurrentKey >= mKeys.length) {
928            return false;
929        }
930
931        Key popupKey = mKeys[mCurrentKey];
932        boolean result = onLongPress(popupKey);
933        if (result) {
934            mAbortKey = true;
935            showPreview(NOT_A_KEY);
936        }
937        return result;
938    }
939
940    /**
941     * Called when a key is long pressed. By default this will open any popup keyboard associated
942     * with this key through the attributes popupLayout and popupCharacters.
943     * @param popupKey the key that was long pressed
944     * @return true if the long press is handled, false otherwise. Subclasses should call the
945     * method on the base class if the subclass doesn't wish to handle the call.
946     */
947    protected boolean onLongPress(Key popupKey) {
948        int popupKeyboardId = popupKey.popupResId;
949
950        if (popupKeyboardId != 0) {
951            mMiniKeyboardContainer = mMiniKeyboardCache.get(popupKey);
952            if (mMiniKeyboardContainer == null) {
953                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(
954                        Context.LAYOUT_INFLATER_SERVICE);
955                mMiniKeyboardContainer = inflater.inflate(mPopupLayout, null);
956                mMiniKeyboard = (KeyboardView) mMiniKeyboardContainer.findViewById(
957                        com.android.internal.R.id.keyboardView);
958                View closeButton = mMiniKeyboardContainer.findViewById(
959                        com.android.internal.R.id.closeButton);
960                if (closeButton != null) closeButton.setOnClickListener(this);
961                mMiniKeyboard.setOnKeyboardActionListener(new OnKeyboardActionListener() {
962                    public void onKey(int primaryCode, int[] keyCodes) {
963                        mKeyboardActionListener.onKey(primaryCode, keyCodes);
964                        dismissPopupKeyboard();
965                    }
966
967                    public void onText(CharSequence text) {
968                        mKeyboardActionListener.onText(text);
969                        dismissPopupKeyboard();
970                    }
971
972                    public void swipeLeft() { }
973                    public void swipeRight() { }
974                    public void swipeUp() { }
975                    public void swipeDown() { }
976                    public void onPress(int primaryCode) {
977                        mKeyboardActionListener.onPress(primaryCode);
978                    }
979                    public void onRelease(int primaryCode) {
980                        mKeyboardActionListener.onRelease(primaryCode);
981                    }
982                });
983                //mInputView.setSuggest(mSuggest);
984                Keyboard keyboard;
985                if (popupKey.popupCharacters != null) {
986                    keyboard = new Keyboard(getContext(), popupKeyboardId,
987                            popupKey.popupCharacters, -1, getPaddingLeft() + getPaddingRight());
988                } else {
989                    keyboard = new Keyboard(getContext(), popupKeyboardId);
990                }
991                mMiniKeyboard.setKeyboard(keyboard);
992                mMiniKeyboard.setPopupParent(this);
993                mMiniKeyboardContainer.measure(
994                        MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
995                        MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
996
997                mMiniKeyboardCache.put(popupKey, mMiniKeyboardContainer);
998            } else {
999                mMiniKeyboard = (KeyboardView) mMiniKeyboardContainer.findViewById(
1000                        com.android.internal.R.id.keyboardView);
1001            }
1002            if (mWindowOffset == null) {
1003                mWindowOffset = new int[2];
1004                getLocationInWindow(mWindowOffset);
1005            }
1006            mPopupX = popupKey.x + mPaddingLeft;
1007            mPopupY = popupKey.y + mPaddingTop;
1008            mPopupX = mPopupX + popupKey.width - mMiniKeyboardContainer.getMeasuredWidth();
1009            mPopupY = mPopupY - mMiniKeyboardContainer.getMeasuredHeight();
1010            final int x = mPopupX + mMiniKeyboardContainer.getPaddingRight() + mWindowOffset[0];
1011            final int y = mPopupY + mMiniKeyboardContainer.getPaddingBottom() + mWindowOffset[1];
1012            mMiniKeyboard.setPopupOffset(x < 0 ? 0 : x, y);
1013            mMiniKeyboard.setShifted(isShifted());
1014            mPopupKeyboard.setContentView(mMiniKeyboardContainer);
1015            mPopupKeyboard.setWidth(mMiniKeyboardContainer.getMeasuredWidth());
1016            mPopupKeyboard.setHeight(mMiniKeyboardContainer.getMeasuredHeight());
1017            mPopupKeyboard.showAtLocation(this, Gravity.NO_GRAVITY, x, y);
1018            mMiniKeyboardOnScreen = true;
1019            //mMiniKeyboard.onTouchEvent(getTranslatedEvent(me));
1020            invalidateAllKeys();
1021            return true;
1022        }
1023        return false;
1024    }
1025
1026    @Override
1027    public boolean onTouchEvent(MotionEvent me) {
1028        // Convert multi-pointer up/down events to single up/down events to
1029        // deal with the typical multi-pointer behavior of two-thumb typing
1030        int pointerCount = me.getPointerCount();
1031        boolean result = false;
1032        if (pointerCount != mOldPointerCount) {
1033            long now = me.getEventTime();
1034            if (pointerCount == 1) {
1035                // Send a down event for the latest pointer
1036                MotionEvent down = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN,
1037                        me.getX(), me.getY(), me.getMetaState());
1038                result = onModifiedTouchEvent(down);
1039                down.recycle();
1040                // If it's an up action, then deliver the up as well.
1041                if (me.getAction() == MotionEvent.ACTION_UP) {
1042                    result = onModifiedTouchEvent(me);
1043                }
1044            } else {
1045                // Send an up event for the last pointer
1046                MotionEvent up = MotionEvent.obtain(now, now, MotionEvent.ACTION_UP,
1047                        mOldPointerX, mOldPointerY, me.getMetaState());
1048                result = onModifiedTouchEvent(up);
1049                up.recycle();
1050            }
1051        } else {
1052            if (pointerCount == 1) {
1053                mOldPointerX = me.getX();
1054                mOldPointerY = me.getY();
1055                result = onModifiedTouchEvent(me);
1056            } else {
1057                // Don't do anything when 2 pointers are down and moving.
1058                result = true;
1059            }
1060        }
1061        mOldPointerCount = pointerCount;
1062        return result;
1063    }
1064
1065    private boolean onModifiedTouchEvent(MotionEvent me) {
1066        int touchX = (int) me.getX() - mPaddingLeft;
1067        int touchY = (int) me.getY() + mVerticalCorrection - mPaddingTop;
1068        int action = me.getAction();
1069        long eventTime = me.getEventTime();
1070        int keyIndex = getKeyIndices(touchX, touchY, null);
1071        if (mGestureDetector.onTouchEvent(me)) {
1072            showPreview(NOT_A_KEY);
1073            mHandler.removeMessages(MSG_REPEAT);
1074            mHandler.removeMessages(MSG_LONGPRESS);
1075            return true;
1076        }
1077
1078        // Needs to be called after the gesture detector gets a turn, as it may have
1079        // displayed the mini keyboard
1080        if (mMiniKeyboardOnScreen) {
1081            return true;
1082        }
1083
1084        switch (action) {
1085            case MotionEvent.ACTION_DOWN:
1086                mAbortKey = false;
1087                mStartX = touchX;
1088                mStartY = touchY;
1089                mLastCodeX = touchX;
1090                mLastCodeY = touchY;
1091                mLastKeyTime = 0;
1092                mCurrentKeyTime = 0;
1093                mLastKey = NOT_A_KEY;
1094                mCurrentKey = keyIndex;
1095                mDownTime = me.getEventTime();
1096                mLastMoveTime = mDownTime;
1097                checkMultiTap(eventTime, keyIndex);
1098                mKeyboardActionListener.onPress(keyIndex != NOT_A_KEY ?
1099                        mKeys[keyIndex].codes[0] : 0);
1100                if (mCurrentKey >= 0 && mKeys[mCurrentKey].repeatable) {
1101                    mRepeatKeyIndex = mCurrentKey;
1102                    repeatKey();
1103                    Message msg = mHandler.obtainMessage(MSG_REPEAT);
1104                    mHandler.sendMessageDelayed(msg, REPEAT_START_DELAY);
1105                }
1106                if (mCurrentKey != NOT_A_KEY) {
1107                    Message msg = mHandler.obtainMessage(MSG_LONGPRESS, me);
1108                    mHandler.sendMessageDelayed(msg, LONGPRESS_TIMEOUT);
1109                }
1110                showPreview(keyIndex);
1111                break;
1112
1113            case MotionEvent.ACTION_MOVE:
1114                boolean continueLongPress = false;
1115                if (keyIndex != NOT_A_KEY) {
1116                    if (mCurrentKey == NOT_A_KEY) {
1117                        mCurrentKey = keyIndex;
1118                        mCurrentKeyTime = eventTime - mDownTime;
1119                    } else {
1120                        if (keyIndex == mCurrentKey) {
1121                            mCurrentKeyTime += eventTime - mLastMoveTime;
1122                            continueLongPress = true;
1123                        } else if (mRepeatKeyIndex == NOT_A_KEY) {
1124                            resetMultiTap();
1125                            mLastKey = mCurrentKey;
1126                            mLastCodeX = mLastX;
1127                            mLastCodeY = mLastY;
1128                            mLastKeyTime =
1129                                    mCurrentKeyTime + eventTime - mLastMoveTime;
1130                            mCurrentKey = keyIndex;
1131                            mCurrentKeyTime = 0;
1132                        }
1133                    }
1134                }
1135                if (!continueLongPress) {
1136                    // Cancel old longpress
1137                    mHandler.removeMessages(MSG_LONGPRESS);
1138                    // Start new longpress if key has changed
1139                    if (keyIndex != NOT_A_KEY) {
1140                        Message msg = mHandler.obtainMessage(MSG_LONGPRESS, me);
1141                        mHandler.sendMessageDelayed(msg, LONGPRESS_TIMEOUT);
1142                    }
1143                }
1144                showPreview(mCurrentKey);
1145                break;
1146
1147            case MotionEvent.ACTION_UP:
1148                mHandler.removeMessages(MSG_SHOW_PREVIEW);
1149                mHandler.removeMessages(MSG_REPEAT);
1150                mHandler.removeMessages(MSG_LONGPRESS);
1151                if (keyIndex == mCurrentKey) {
1152                    mCurrentKeyTime += eventTime - mLastMoveTime;
1153                } else {
1154                    resetMultiTap();
1155                    mLastKey = mCurrentKey;
1156                    mLastKeyTime = mCurrentKeyTime + eventTime - mLastMoveTime;
1157                    mCurrentKey = keyIndex;
1158                    mCurrentKeyTime = 0;
1159                }
1160                if (mCurrentKeyTime < mLastKeyTime && mLastKey != NOT_A_KEY) {
1161                    mCurrentKey = mLastKey;
1162                    touchX = mLastCodeX;
1163                    touchY = mLastCodeY;
1164                }
1165                showPreview(NOT_A_KEY);
1166                Arrays.fill(mKeyIndices, NOT_A_KEY);
1167                // If we're not on a repeating key (which sends on a DOWN event)
1168                if (mRepeatKeyIndex == NOT_A_KEY && !mMiniKeyboardOnScreen && !mAbortKey) {
1169                    detectAndSendKey(touchX, touchY, eventTime);
1170                }
1171                invalidateKey(keyIndex);
1172                mRepeatKeyIndex = NOT_A_KEY;
1173                break;
1174        }
1175        mLastX = touchX;
1176        mLastY = touchY;
1177        return true;
1178    }
1179
1180    private boolean repeatKey() {
1181        Key key = mKeys[mRepeatKeyIndex];
1182        detectAndSendKey(key.x, key.y, mLastTapTime);
1183        return true;
1184    }
1185
1186    protected void swipeRight() {
1187        mKeyboardActionListener.swipeRight();
1188    }
1189
1190    protected void swipeLeft() {
1191        mKeyboardActionListener.swipeLeft();
1192    }
1193
1194    protected void swipeUp() {
1195        mKeyboardActionListener.swipeUp();
1196    }
1197
1198    protected void swipeDown() {
1199        mKeyboardActionListener.swipeDown();
1200    }
1201
1202    public void closing() {
1203        if (mPreviewPopup.isShowing()) {
1204            mPreviewPopup.dismiss();
1205        }
1206        mHandler.removeMessages(MSG_REPEAT);
1207        mHandler.removeMessages(MSG_LONGPRESS);
1208        mHandler.removeMessages(MSG_SHOW_PREVIEW);
1209
1210        dismissPopupKeyboard();
1211        mBuffer = null;
1212        mCanvas = null;
1213        mMiniKeyboardCache.clear();
1214    }
1215
1216    @Override
1217    public void onDetachedFromWindow() {
1218        super.onDetachedFromWindow();
1219        closing();
1220    }
1221
1222    private void dismissPopupKeyboard() {
1223        if (mPopupKeyboard.isShowing()) {
1224            mPopupKeyboard.dismiss();
1225            mMiniKeyboardOnScreen = false;
1226            invalidateAllKeys();
1227        }
1228    }
1229
1230    public boolean handleBack() {
1231        if (mPopupKeyboard.isShowing()) {
1232            dismissPopupKeyboard();
1233            return true;
1234        }
1235        return false;
1236    }
1237
1238    private void resetMultiTap() {
1239        mLastSentIndex = NOT_A_KEY;
1240        mTapCount = 0;
1241        mLastTapTime = -1;
1242        mInMultiTap = false;
1243    }
1244
1245    private void checkMultiTap(long eventTime, int keyIndex) {
1246        if (keyIndex == NOT_A_KEY) return;
1247        Key key = mKeys[keyIndex];
1248        if (key.codes.length > 1) {
1249            mInMultiTap = true;
1250            if (eventTime < mLastTapTime + MULTITAP_INTERVAL
1251                    && keyIndex == mLastSentIndex) {
1252                mTapCount = (mTapCount + 1) % key.codes.length;
1253                return;
1254            } else {
1255                mTapCount = -1;
1256                return;
1257            }
1258        }
1259        if (eventTime > mLastTapTime + MULTITAP_INTERVAL || keyIndex != mLastSentIndex) {
1260            resetMultiTap();
1261        }
1262    }
1263}
1264