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