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