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