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