Editor.java revision 9122187fca67c7509ba2a040b602f67928fc9a98
1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of 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, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.widget; 18 19import com.android.internal.util.ArrayUtils; 20import com.android.internal.widget.EditableInputConnection; 21 22import android.R; 23import android.content.ClipData; 24import android.content.ClipData.Item; 25import android.content.Context; 26import android.content.Intent; 27import android.content.pm.PackageManager; 28import android.content.res.TypedArray; 29import android.graphics.Canvas; 30import android.graphics.Color; 31import android.graphics.Paint; 32import android.graphics.Path; 33import android.graphics.Rect; 34import android.graphics.RectF; 35import android.graphics.drawable.Drawable; 36import android.inputmethodservice.ExtractEditText; 37import android.os.Bundle; 38import android.os.Handler; 39import android.os.Message; 40import android.os.Messenger; 41import android.os.SystemClock; 42import android.provider.Settings; 43import android.text.DynamicLayout; 44import android.text.Editable; 45import android.text.InputType; 46import android.text.Layout; 47import android.text.ParcelableSpan; 48import android.text.Selection; 49import android.text.SpanWatcher; 50import android.text.Spannable; 51import android.text.SpannableStringBuilder; 52import android.text.Spanned; 53import android.text.StaticLayout; 54import android.text.TextUtils; 55import android.text.method.KeyListener; 56import android.text.method.MetaKeyKeyListener; 57import android.text.method.MovementMethod; 58import android.text.method.PasswordTransformationMethod; 59import android.text.method.WordIterator; 60import android.text.style.EasyEditSpan; 61import android.text.style.SuggestionRangeSpan; 62import android.text.style.SuggestionSpan; 63import android.text.style.TextAppearanceSpan; 64import android.text.style.URLSpan; 65import android.util.DisplayMetrics; 66import android.util.Log; 67import android.view.ActionMode; 68import android.view.ActionMode.Callback; 69import android.view.DisplayList; 70import android.view.DragEvent; 71import android.view.Gravity; 72import android.view.HardwareCanvas; 73import android.view.LayoutInflater; 74import android.view.Menu; 75import android.view.MenuItem; 76import android.view.MotionEvent; 77import android.view.View; 78import android.view.View.DragShadowBuilder; 79import android.view.View.OnClickListener; 80import android.view.ViewConfiguration; 81import android.view.ViewGroup; 82import android.view.ViewGroup.LayoutParams; 83import android.view.ViewParent; 84import android.view.ViewTreeObserver; 85import android.view.WindowManager; 86import android.view.inputmethod.CorrectionInfo; 87import android.view.inputmethod.EditorInfo; 88import android.view.inputmethod.ExtractedText; 89import android.view.inputmethod.ExtractedTextRequest; 90import android.view.inputmethod.InputConnection; 91import android.view.inputmethod.InputMethodManager; 92import android.widget.AdapterView.OnItemClickListener; 93import android.widget.TextView.Drawables; 94import android.widget.TextView.OnEditorActionListener; 95 96import java.text.BreakIterator; 97import java.util.Arrays; 98import java.util.Comparator; 99import java.util.HashMap; 100 101/** 102 * Helper class used by TextView to handle editable text views. 103 * 104 * @hide 105 */ 106public class Editor { 107 private static final String TAG = "Editor"; 108 109 static final int BLINK = 500; 110 private static final float[] TEMP_POSITION = new float[2]; 111 private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20; 112 113 // Cursor Controllers. 114 InsertionPointCursorController mInsertionPointCursorController; 115 SelectionModifierCursorController mSelectionModifierCursorController; 116 ActionMode mSelectionActionMode; 117 boolean mInsertionControllerEnabled; 118 boolean mSelectionControllerEnabled; 119 120 // Used to highlight a word when it is corrected by the IME 121 CorrectionHighlighter mCorrectionHighlighter; 122 123 InputContentType mInputContentType; 124 InputMethodState mInputMethodState; 125 126 DisplayList[] mTextDisplayLists; 127 128 boolean mFrozenWithFocus; 129 boolean mSelectionMoved; 130 boolean mTouchFocusSelected; 131 132 KeyListener mKeyListener; 133 int mInputType = EditorInfo.TYPE_NULL; 134 135 boolean mDiscardNextActionUp; 136 boolean mIgnoreActionUpEvent; 137 138 long mShowCursor; 139 Blink mBlink; 140 141 boolean mCursorVisible = true; 142 boolean mSelectAllOnFocus; 143 boolean mTextIsSelectable; 144 145 CharSequence mError; 146 boolean mErrorWasChanged; 147 ErrorPopup mErrorPopup; 148 149 /** 150 * This flag is set if the TextView tries to display an error before it 151 * is attached to the window (so its position is still unknown). 152 * It causes the error to be shown later, when onAttachedToWindow() 153 * is called. 154 */ 155 boolean mShowErrorAfterAttach; 156 157 boolean mInBatchEditControllers; 158 boolean mShowSoftInputOnFocus = true; 159 boolean mPreserveDetachedSelection; 160 boolean mTemporaryDetach; 161 162 SuggestionsPopupWindow mSuggestionsPopupWindow; 163 SuggestionRangeSpan mSuggestionRangeSpan; 164 Runnable mShowSuggestionRunnable; 165 166 final Drawable[] mCursorDrawable = new Drawable[2]; 167 int mCursorCount; // Current number of used mCursorDrawable: 0 (resource=0), 1 or 2 (split) 168 169 private Drawable mSelectHandleLeft; 170 private Drawable mSelectHandleRight; 171 private Drawable mSelectHandleCenter; 172 173 // Global listener that detects changes in the global position of the TextView 174 private PositionListener mPositionListener; 175 176 float mLastDownPositionX, mLastDownPositionY; 177 Callback mCustomSelectionActionModeCallback; 178 179 // Set when this TextView gained focus with some text selected. Will start selection mode. 180 boolean mCreatedWithASelection; 181 182 private EasyEditSpanController mEasyEditSpanController; 183 184 WordIterator mWordIterator; 185 SpellChecker mSpellChecker; 186 187 private Rect mTempRect; 188 189 private TextView mTextView; 190 191 private final UserDictionaryListener mUserDictionaryListener = new UserDictionaryListener(); 192 193 Editor(TextView textView) { 194 mTextView = textView; 195 } 196 197 void onAttachedToWindow() { 198 if (mShowErrorAfterAttach) { 199 showError(); 200 mShowErrorAfterAttach = false; 201 } 202 mTemporaryDetach = false; 203 204 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 205 // No need to create the controller. 206 // The get method will add the listener on controller creation. 207 if (mInsertionPointCursorController != null) { 208 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 209 } 210 if (mSelectionModifierCursorController != null) { 211 mSelectionModifierCursorController.resetTouchOffsets(); 212 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 213 } 214 updateSpellCheckSpans(0, mTextView.getText().length(), 215 true /* create the spell checker if needed */); 216 217 if (mTextView.hasTransientState() && 218 mTextView.getSelectionStart() != mTextView.getSelectionEnd()) { 219 // Since transient state is reference counted make sure it stays matched 220 // with our own calls to it for managing selection. 221 // The action mode callback will set this back again when/if the action mode starts. 222 mTextView.setHasTransientState(false); 223 224 // We had an active selection from before, start the selection mode. 225 startSelectionActionMode(); 226 } 227 } 228 229 void onDetachedFromWindow() { 230 if (mError != null) { 231 hideError(); 232 } 233 234 if (mBlink != null) { 235 mBlink.removeCallbacks(mBlink); 236 } 237 238 if (mInsertionPointCursorController != null) { 239 mInsertionPointCursorController.onDetached(); 240 } 241 242 if (mSelectionModifierCursorController != null) { 243 mSelectionModifierCursorController.onDetached(); 244 } 245 246 if (mShowSuggestionRunnable != null) { 247 mTextView.removeCallbacks(mShowSuggestionRunnable); 248 } 249 250 invalidateTextDisplayList(); 251 252 if (mSpellChecker != null) { 253 mSpellChecker.closeSession(); 254 // Forces the creation of a new SpellChecker next time this window is created. 255 // Will handle the cases where the settings has been changed in the meantime. 256 mSpellChecker = null; 257 } 258 259 mPreserveDetachedSelection = true; 260 hideControllers(); 261 mPreserveDetachedSelection = false; 262 mTemporaryDetach = false; 263 } 264 265 private void showError() { 266 if (mTextView.getWindowToken() == null) { 267 mShowErrorAfterAttach = true; 268 return; 269 } 270 271 if (mErrorPopup == null) { 272 LayoutInflater inflater = LayoutInflater.from(mTextView.getContext()); 273 final TextView err = (TextView) inflater.inflate( 274 com.android.internal.R.layout.textview_hint, null); 275 276 final float scale = mTextView.getResources().getDisplayMetrics().density; 277 mErrorPopup = new ErrorPopup(err, (int)(200 * scale + 0.5f), (int)(50 * scale + 0.5f)); 278 mErrorPopup.setFocusable(false); 279 // The user is entering text, so the input method is needed. We 280 // don't want the popup to be displayed on top of it. 281 mErrorPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); 282 } 283 284 TextView tv = (TextView) mErrorPopup.getContentView(); 285 chooseSize(mErrorPopup, mError, tv); 286 tv.setText(mError); 287 288 mErrorPopup.showAsDropDown(mTextView, getErrorX(), getErrorY()); 289 mErrorPopup.fixDirection(mErrorPopup.isAboveAnchor()); 290 } 291 292 public void setError(CharSequence error, Drawable icon) { 293 mError = TextUtils.stringOrSpannedString(error); 294 mErrorWasChanged = true; 295 296 if (mError == null) { 297 setErrorIcon(null); 298 if (mErrorPopup != null) { 299 if (mErrorPopup.isShowing()) { 300 mErrorPopup.dismiss(); 301 } 302 303 mErrorPopup = null; 304 } 305 306 } else { 307 setErrorIcon(icon); 308 if (mTextView.isFocused()) { 309 showError(); 310 } 311 } 312 } 313 314 private void setErrorIcon(Drawable icon) { 315 Drawables dr = mTextView.mDrawables; 316 if (dr == null) { 317 mTextView.mDrawables = dr = new Drawables(); 318 } 319 dr.setErrorDrawable(icon, mTextView); 320 321 mTextView.resetResolvedDrawables(); 322 mTextView.invalidate(); 323 mTextView.requestLayout(); 324 } 325 326 private void hideError() { 327 if (mErrorPopup != null) { 328 if (mErrorPopup.isShowing()) { 329 mErrorPopup.dismiss(); 330 } 331 } 332 333 mShowErrorAfterAttach = false; 334 } 335 336 /** 337 * Returns the X offset to make the pointy top of the error point 338 * at the middle of the error icon. 339 */ 340 private int getErrorX() { 341 /* 342 * The "25" is the distance between the point and the right edge 343 * of the background 344 */ 345 final float scale = mTextView.getResources().getDisplayMetrics().density; 346 347 final Drawables dr = mTextView.mDrawables; 348 349 final int layoutDirection = mTextView.getLayoutDirection(); 350 int errorX; 351 int offset; 352 switch (layoutDirection) { 353 default: 354 case View.LAYOUT_DIRECTION_LTR: 355 offset = - (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f); 356 errorX = mTextView.getWidth() - mErrorPopup.getWidth() - 357 mTextView.getPaddingRight() + offset; 358 break; 359 case View.LAYOUT_DIRECTION_RTL: 360 offset = (dr != null ? dr.mDrawableSizeLeft : 0) / 2 - (int) (25 * scale + 0.5f); 361 errorX = mTextView.getPaddingLeft() + offset; 362 break; 363 } 364 return errorX; 365 } 366 367 /** 368 * Returns the Y offset to make the pointy top of the error point 369 * at the bottom of the error icon. 370 */ 371 private int getErrorY() { 372 /* 373 * Compound, not extended, because the icon is not clipped 374 * if the text height is smaller. 375 */ 376 final int compoundPaddingTop = mTextView.getCompoundPaddingTop(); 377 int vspace = mTextView.getBottom() - mTextView.getTop() - 378 mTextView.getCompoundPaddingBottom() - compoundPaddingTop; 379 380 final Drawables dr = mTextView.mDrawables; 381 382 final int layoutDirection = mTextView.getLayoutDirection(); 383 int height; 384 switch (layoutDirection) { 385 default: 386 case View.LAYOUT_DIRECTION_LTR: 387 height = (dr != null ? dr.mDrawableHeightRight : 0); 388 break; 389 case View.LAYOUT_DIRECTION_RTL: 390 height = (dr != null ? dr.mDrawableHeightLeft : 0); 391 break; 392 } 393 394 int icontop = compoundPaddingTop + (vspace - height) / 2; 395 396 /* 397 * The "2" is the distance between the point and the top edge 398 * of the background. 399 */ 400 final float scale = mTextView.getResources().getDisplayMetrics().density; 401 return icontop + height - mTextView.getHeight() - (int) (2 * scale + 0.5f); 402 } 403 404 void createInputContentTypeIfNeeded() { 405 if (mInputContentType == null) { 406 mInputContentType = new InputContentType(); 407 } 408 } 409 410 void createInputMethodStateIfNeeded() { 411 if (mInputMethodState == null) { 412 mInputMethodState = new InputMethodState(); 413 } 414 } 415 416 boolean isCursorVisible() { 417 // The default value is true, even when there is no associated Editor 418 return mCursorVisible && mTextView.isTextEditable(); 419 } 420 421 void prepareCursorControllers() { 422 boolean windowSupportsHandles = false; 423 424 ViewGroup.LayoutParams params = mTextView.getRootView().getLayoutParams(); 425 if (params instanceof WindowManager.LayoutParams) { 426 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params; 427 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW 428 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW; 429 } 430 431 boolean enabled = windowSupportsHandles && mTextView.getLayout() != null; 432 mInsertionControllerEnabled = enabled && isCursorVisible(); 433 mSelectionControllerEnabled = enabled && mTextView.textCanBeSelected(); 434 435 if (!mInsertionControllerEnabled) { 436 hideInsertionPointCursorController(); 437 if (mInsertionPointCursorController != null) { 438 mInsertionPointCursorController.onDetached(); 439 mInsertionPointCursorController = null; 440 } 441 } 442 443 if (!mSelectionControllerEnabled) { 444 stopSelectionActionMode(); 445 if (mSelectionModifierCursorController != null) { 446 mSelectionModifierCursorController.onDetached(); 447 mSelectionModifierCursorController = null; 448 } 449 } 450 } 451 452 private void hideInsertionPointCursorController() { 453 if (mInsertionPointCursorController != null) { 454 mInsertionPointCursorController.hide(); 455 } 456 } 457 458 /** 459 * Hides the insertion controller and stops text selection mode, hiding the selection controller 460 */ 461 void hideControllers() { 462 hideCursorControllers(); 463 hideSpanControllers(); 464 } 465 466 private void hideSpanControllers() { 467 if (mEasyEditSpanController != null) { 468 mEasyEditSpanController.hide(); 469 } 470 } 471 472 private void hideCursorControllers() { 473 if (mSuggestionsPopupWindow != null && !mSuggestionsPopupWindow.isShowingUp()) { 474 // Should be done before hide insertion point controller since it triggers a show of it 475 mSuggestionsPopupWindow.hide(); 476 } 477 hideInsertionPointCursorController(); 478 stopSelectionActionMode(); 479 } 480 481 /** 482 * Create new SpellCheckSpans on the modified region. 483 */ 484 private void updateSpellCheckSpans(int start, int end, boolean createSpellChecker) { 485 if (mTextView.isTextEditable() && mTextView.isSuggestionsEnabled() && 486 !(mTextView instanceof ExtractEditText)) { 487 if (mSpellChecker == null && createSpellChecker) { 488 mSpellChecker = new SpellChecker(mTextView); 489 } 490 if (mSpellChecker != null) { 491 mSpellChecker.spellCheck(start, end); 492 } 493 } 494 } 495 496 void onScreenStateChanged(int screenState) { 497 switch (screenState) { 498 case View.SCREEN_STATE_ON: 499 resumeBlink(); 500 break; 501 case View.SCREEN_STATE_OFF: 502 suspendBlink(); 503 break; 504 } 505 } 506 507 private void suspendBlink() { 508 if (mBlink != null) { 509 mBlink.cancel(); 510 } 511 } 512 513 private void resumeBlink() { 514 if (mBlink != null) { 515 mBlink.uncancel(); 516 makeBlink(); 517 } 518 } 519 520 void adjustInputType(boolean password, boolean passwordInputType, 521 boolean webPasswordInputType, boolean numberPasswordInputType) { 522 // mInputType has been set from inputType, possibly modified by mInputMethod. 523 // Specialize mInputType to [web]password if we have a text class and the original input 524 // type was a password. 525 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 526 if (password || passwordInputType) { 527 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 528 | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD; 529 } 530 if (webPasswordInputType) { 531 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 532 | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD; 533 } 534 } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) { 535 if (numberPasswordInputType) { 536 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 537 | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD; 538 } 539 } 540 } 541 542 private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) { 543 int wid = tv.getPaddingLeft() + tv.getPaddingRight(); 544 int ht = tv.getPaddingTop() + tv.getPaddingBottom(); 545 546 int defaultWidthInPixels = mTextView.getResources().getDimensionPixelSize( 547 com.android.internal.R.dimen.textview_error_popup_default_width); 548 Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels, 549 Layout.Alignment.ALIGN_NORMAL, 1, 0, true); 550 float max = 0; 551 for (int i = 0; i < l.getLineCount(); i++) { 552 max = Math.max(max, l.getLineWidth(i)); 553 } 554 555 /* 556 * Now set the popup size to be big enough for the text plus the border capped 557 * to DEFAULT_MAX_POPUP_WIDTH 558 */ 559 pop.setWidth(wid + (int) Math.ceil(max)); 560 pop.setHeight(ht + l.getHeight()); 561 } 562 563 void setFrame() { 564 if (mErrorPopup != null) { 565 TextView tv = (TextView) mErrorPopup.getContentView(); 566 chooseSize(mErrorPopup, mError, tv); 567 mErrorPopup.update(mTextView, getErrorX(), getErrorY(), 568 mErrorPopup.getWidth(), mErrorPopup.getHeight()); 569 } 570 } 571 572 /** 573 * Unlike {@link TextView#textCanBeSelected()}, this method is based on the <i>current</i> state 574 * of the TextView. textCanBeSelected() has to be true (this is one of the conditions to have 575 * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient. 576 */ 577 private boolean canSelectText() { 578 return hasSelectionController() && mTextView.getText().length() != 0; 579 } 580 581 /** 582 * It would be better to rely on the input type for everything. A password inputType should have 583 * a password transformation. We should hence use isPasswordInputType instead of this method. 584 * 585 * We should: 586 * - Call setInputType in setKeyListener instead of changing the input type directly (which 587 * would install the correct transformation). 588 * - Refuse the installation of a non-password transformation in setTransformation if the input 589 * type is password. 590 * 591 * However, this is like this for legacy reasons and we cannot break existing apps. This method 592 * is useful since it matches what the user can see (obfuscated text or not). 593 * 594 * @return true if the current transformation method is of the password type. 595 */ 596 private boolean hasPasswordTransformationMethod() { 597 return mTextView.getTransformationMethod() instanceof PasswordTransformationMethod; 598 } 599 600 /** 601 * Adjusts selection to the word under last touch offset. 602 * Return true if the operation was successfully performed. 603 */ 604 private boolean selectCurrentWord() { 605 if (!canSelectText()) { 606 return false; 607 } 608 609 if (hasPasswordTransformationMethod()) { 610 // Always select all on a password field. 611 // Cut/copy menu entries are not available for passwords, but being able to select all 612 // is however useful to delete or paste to replace the entire content. 613 return mTextView.selectAllText(); 614 } 615 616 int inputType = mTextView.getInputType(); 617 int klass = inputType & InputType.TYPE_MASK_CLASS; 618 int variation = inputType & InputType.TYPE_MASK_VARIATION; 619 620 // Specific text field types: select the entire text for these 621 if (klass == InputType.TYPE_CLASS_NUMBER || 622 klass == InputType.TYPE_CLASS_PHONE || 623 klass == InputType.TYPE_CLASS_DATETIME || 624 variation == InputType.TYPE_TEXT_VARIATION_URI || 625 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 626 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS || 627 variation == InputType.TYPE_TEXT_VARIATION_FILTER) { 628 return mTextView.selectAllText(); 629 } 630 631 long lastTouchOffsets = getLastTouchOffsets(); 632 final int minOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets); 633 final int maxOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets); 634 635 // Safety check in case standard touch event handling has been bypassed 636 if (minOffset < 0 || minOffset >= mTextView.getText().length()) return false; 637 if (maxOffset < 0 || maxOffset >= mTextView.getText().length()) return false; 638 639 int selectionStart, selectionEnd; 640 641 // If a URLSpan (web address, email, phone...) is found at that position, select it. 642 URLSpan[] urlSpans = ((Spanned) mTextView.getText()). 643 getSpans(minOffset, maxOffset, URLSpan.class); 644 if (urlSpans.length >= 1) { 645 URLSpan urlSpan = urlSpans[0]; 646 selectionStart = ((Spanned) mTextView.getText()).getSpanStart(urlSpan); 647 selectionEnd = ((Spanned) mTextView.getText()).getSpanEnd(urlSpan); 648 } else { 649 final WordIterator wordIterator = getWordIterator(); 650 wordIterator.setCharSequence(mTextView.getText(), minOffset, maxOffset); 651 652 selectionStart = wordIterator.getBeginning(minOffset); 653 selectionEnd = wordIterator.getEnd(maxOffset); 654 655 if (selectionStart == BreakIterator.DONE || selectionEnd == BreakIterator.DONE || 656 selectionStart == selectionEnd) { 657 // Possible when the word iterator does not properly handle the text's language 658 long range = getCharRange(minOffset); 659 selectionStart = TextUtils.unpackRangeStartFromLong(range); 660 selectionEnd = TextUtils.unpackRangeEndFromLong(range); 661 } 662 } 663 664 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd); 665 return selectionEnd > selectionStart; 666 } 667 668 void onLocaleChanged() { 669 // Will be re-created on demand in getWordIterator with the proper new locale 670 mWordIterator = null; 671 } 672 673 /** 674 * @hide 675 */ 676 public WordIterator getWordIterator() { 677 if (mWordIterator == null) { 678 mWordIterator = new WordIterator(mTextView.getTextServicesLocale()); 679 } 680 return mWordIterator; 681 } 682 683 private long getCharRange(int offset) { 684 final int textLength = mTextView.getText().length(); 685 if (offset + 1 < textLength) { 686 final char currentChar = mTextView.getText().charAt(offset); 687 final char nextChar = mTextView.getText().charAt(offset + 1); 688 if (Character.isSurrogatePair(currentChar, nextChar)) { 689 return TextUtils.packRangeInLong(offset, offset + 2); 690 } 691 } 692 if (offset < textLength) { 693 return TextUtils.packRangeInLong(offset, offset + 1); 694 } 695 if (offset - 2 >= 0) { 696 final char previousChar = mTextView.getText().charAt(offset - 1); 697 final char previousPreviousChar = mTextView.getText().charAt(offset - 2); 698 if (Character.isSurrogatePair(previousPreviousChar, previousChar)) { 699 return TextUtils.packRangeInLong(offset - 2, offset); 700 } 701 } 702 if (offset - 1 >= 0) { 703 return TextUtils.packRangeInLong(offset - 1, offset); 704 } 705 return TextUtils.packRangeInLong(offset, offset); 706 } 707 708 private boolean touchPositionIsInSelection() { 709 int selectionStart = mTextView.getSelectionStart(); 710 int selectionEnd = mTextView.getSelectionEnd(); 711 712 if (selectionStart == selectionEnd) { 713 return false; 714 } 715 716 if (selectionStart > selectionEnd) { 717 int tmp = selectionStart; 718 selectionStart = selectionEnd; 719 selectionEnd = tmp; 720 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd); 721 } 722 723 SelectionModifierCursorController selectionController = getSelectionController(); 724 int minOffset = selectionController.getMinTouchOffset(); 725 int maxOffset = selectionController.getMaxTouchOffset(); 726 727 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd)); 728 } 729 730 private PositionListener getPositionListener() { 731 if (mPositionListener == null) { 732 mPositionListener = new PositionListener(); 733 } 734 return mPositionListener; 735 } 736 737 private interface TextViewPositionListener { 738 public void updatePosition(int parentPositionX, int parentPositionY, 739 boolean parentPositionChanged, boolean parentScrolled); 740 } 741 742 private boolean isPositionVisible(int positionX, int positionY) { 743 synchronized (TEMP_POSITION) { 744 final float[] position = TEMP_POSITION; 745 position[0] = positionX; 746 position[1] = positionY; 747 View view = mTextView; 748 749 while (view != null) { 750 if (view != mTextView) { 751 // Local scroll is already taken into account in positionX/Y 752 position[0] -= view.getScrollX(); 753 position[1] -= view.getScrollY(); 754 } 755 756 if (position[0] < 0 || position[1] < 0 || 757 position[0] > view.getWidth() || position[1] > view.getHeight()) { 758 return false; 759 } 760 761 if (!view.getMatrix().isIdentity()) { 762 view.getMatrix().mapPoints(position); 763 } 764 765 position[0] += view.getLeft(); 766 position[1] += view.getTop(); 767 768 final ViewParent parent = view.getParent(); 769 if (parent instanceof View) { 770 view = (View) parent; 771 } else { 772 // We've reached the ViewRoot, stop iterating 773 view = null; 774 } 775 } 776 } 777 778 // We've been able to walk up the view hierarchy and the position was never clipped 779 return true; 780 } 781 782 private boolean isOffsetVisible(int offset) { 783 Layout layout = mTextView.getLayout(); 784 final int line = layout.getLineForOffset(offset); 785 final int lineBottom = layout.getLineBottom(line); 786 final int primaryHorizontal = (int) layout.getPrimaryHorizontal(offset); 787 return isPositionVisible(primaryHorizontal + mTextView.viewportToContentHorizontalOffset(), 788 lineBottom + mTextView.viewportToContentVerticalOffset()); 789 } 790 791 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed 792 * in the view. Returns false when the position is in the empty space of left/right of text. 793 */ 794 private boolean isPositionOnText(float x, float y) { 795 Layout layout = mTextView.getLayout(); 796 if (layout == null) return false; 797 798 final int line = mTextView.getLineAtCoordinate(y); 799 x = mTextView.convertToLocalHorizontalCoordinate(x); 800 801 if (x < layout.getLineLeft(line)) return false; 802 if (x > layout.getLineRight(line)) return false; 803 return true; 804 } 805 806 public boolean performLongClick(boolean handled) { 807 // Long press in empty space moves cursor and shows the Paste affordance if available. 808 if (!handled && !isPositionOnText(mLastDownPositionX, mLastDownPositionY) && 809 mInsertionControllerEnabled) { 810 final int offset = mTextView.getOffsetForPosition(mLastDownPositionX, 811 mLastDownPositionY); 812 stopSelectionActionMode(); 813 Selection.setSelection((Spannable) mTextView.getText(), offset); 814 getInsertionController().showWithActionPopup(); 815 handled = true; 816 } 817 818 if (!handled && mSelectionActionMode != null) { 819 if (touchPositionIsInSelection()) { 820 // Start a drag 821 final int start = mTextView.getSelectionStart(); 822 final int end = mTextView.getSelectionEnd(); 823 CharSequence selectedText = mTextView.getTransformedText(start, end); 824 ClipData data = ClipData.newPlainText(null, selectedText); 825 DragLocalState localState = new DragLocalState(mTextView, start, end); 826 mTextView.startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0); 827 stopSelectionActionMode(); 828 } else { 829 getSelectionController().hide(); 830 selectCurrentWord(); 831 getSelectionController().show(); 832 } 833 handled = true; 834 } 835 836 // Start a new selection 837 if (!handled) { 838 handled = startSelectionActionMode(); 839 } 840 841 return handled; 842 } 843 844 private long getLastTouchOffsets() { 845 SelectionModifierCursorController selectionController = getSelectionController(); 846 final int minOffset = selectionController.getMinTouchOffset(); 847 final int maxOffset = selectionController.getMaxTouchOffset(); 848 return TextUtils.packRangeInLong(minOffset, maxOffset); 849 } 850 851 void onFocusChanged(boolean focused, int direction) { 852 mShowCursor = SystemClock.uptimeMillis(); 853 ensureEndedBatchEdit(); 854 855 if (focused) { 856 int selStart = mTextView.getSelectionStart(); 857 int selEnd = mTextView.getSelectionEnd(); 858 859 // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection 860 // mode for these, unless there was a specific selection already started. 861 final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 && 862 selEnd == mTextView.getText().length(); 863 864 mCreatedWithASelection = mFrozenWithFocus && mTextView.hasSelection() && 865 !isFocusHighlighted; 866 867 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) { 868 // If a tap was used to give focus to that view, move cursor at tap position. 869 // Has to be done before onTakeFocus, which can be overloaded. 870 final int lastTapPosition = getLastTapPosition(); 871 if (lastTapPosition >= 0) { 872 Selection.setSelection((Spannable) mTextView.getText(), lastTapPosition); 873 } 874 875 // Note this may have to be moved out of the Editor class 876 MovementMethod mMovement = mTextView.getMovementMethod(); 877 if (mMovement != null) { 878 mMovement.onTakeFocus(mTextView, (Spannable) mTextView.getText(), direction); 879 } 880 881 // The DecorView does not have focus when the 'Done' ExtractEditText button is 882 // pressed. Since it is the ViewAncestor's mView, it requests focus before 883 // ExtractEditText clears focus, which gives focus to the ExtractEditText. 884 // This special case ensure that we keep current selection in that case. 885 // It would be better to know why the DecorView does not have focus at that time. 886 if (((mTextView instanceof ExtractEditText) || mSelectionMoved) && 887 selStart >= 0 && selEnd >= 0) { 888 /* 889 * Someone intentionally set the selection, so let them 890 * do whatever it is that they wanted to do instead of 891 * the default on-focus behavior. We reset the selection 892 * here instead of just skipping the onTakeFocus() call 893 * because some movement methods do something other than 894 * just setting the selection in theirs and we still 895 * need to go through that path. 896 */ 897 Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd); 898 } 899 900 if (mSelectAllOnFocus) { 901 mTextView.selectAllText(); 902 } 903 904 mTouchFocusSelected = true; 905 } 906 907 mFrozenWithFocus = false; 908 mSelectionMoved = false; 909 910 if (mError != null) { 911 showError(); 912 } 913 914 makeBlink(); 915 } else { 916 if (mError != null) { 917 hideError(); 918 } 919 // Don't leave us in the middle of a batch edit. 920 mTextView.onEndBatchEdit(); 921 922 if (mTextView instanceof ExtractEditText) { 923 // terminateTextSelectionMode removes selection, which we want to keep when 924 // ExtractEditText goes out of focus. 925 final int selStart = mTextView.getSelectionStart(); 926 final int selEnd = mTextView.getSelectionEnd(); 927 hideControllers(); 928 Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd); 929 } else { 930 if (mTemporaryDetach) mPreserveDetachedSelection = true; 931 hideControllers(); 932 if (mTemporaryDetach) mPreserveDetachedSelection = false; 933 downgradeEasyCorrectionSpans(); 934 } 935 936 // No need to create the controller 937 if (mSelectionModifierCursorController != null) { 938 mSelectionModifierCursorController.resetTouchOffsets(); 939 } 940 } 941 } 942 943 /** 944 * Downgrades to simple suggestions all the easy correction spans that are not a spell check 945 * span. 946 */ 947 private void downgradeEasyCorrectionSpans() { 948 CharSequence text = mTextView.getText(); 949 if (text instanceof Spannable) { 950 Spannable spannable = (Spannable) text; 951 SuggestionSpan[] suggestionSpans = spannable.getSpans(0, 952 spannable.length(), SuggestionSpan.class); 953 for (int i = 0; i < suggestionSpans.length; i++) { 954 int flags = suggestionSpans[i].getFlags(); 955 if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0 956 && (flags & SuggestionSpan.FLAG_MISSPELLED) == 0) { 957 flags &= ~SuggestionSpan.FLAG_EASY_CORRECT; 958 suggestionSpans[i].setFlags(flags); 959 } 960 } 961 } 962 } 963 964 void sendOnTextChanged(int start, int after) { 965 updateSpellCheckSpans(start, start + after, false); 966 967 // Hide the controllers as soon as text is modified (typing, procedural...) 968 // We do not hide the span controllers, since they can be added when a new text is 969 // inserted into the text view (voice IME). 970 hideCursorControllers(); 971 } 972 973 private int getLastTapPosition() { 974 // No need to create the controller at that point, no last tap position saved 975 if (mSelectionModifierCursorController != null) { 976 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset(); 977 if (lastTapPosition >= 0) { 978 // Safety check, should not be possible. 979 if (lastTapPosition > mTextView.getText().length()) { 980 lastTapPosition = mTextView.getText().length(); 981 } 982 return lastTapPosition; 983 } 984 } 985 986 return -1; 987 } 988 989 void onWindowFocusChanged(boolean hasWindowFocus) { 990 if (hasWindowFocus) { 991 if (mBlink != null) { 992 mBlink.uncancel(); 993 makeBlink(); 994 } 995 } else { 996 if (mBlink != null) { 997 mBlink.cancel(); 998 } 999 if (mInputContentType != null) { 1000 mInputContentType.enterDown = false; 1001 } 1002 // Order matters! Must be done before onParentLostFocus to rely on isShowingUp 1003 hideControllers(); 1004 if (mSuggestionsPopupWindow != null) { 1005 mSuggestionsPopupWindow.onParentLostFocus(); 1006 } 1007 1008 // Don't leave us in the middle of a batch edit. Same as in onFocusChanged 1009 ensureEndedBatchEdit(); 1010 } 1011 } 1012 1013 void onTouchEvent(MotionEvent event) { 1014 if (hasSelectionController()) { 1015 getSelectionController().onTouchEvent(event); 1016 } 1017 1018 if (mShowSuggestionRunnable != null) { 1019 mTextView.removeCallbacks(mShowSuggestionRunnable); 1020 mShowSuggestionRunnable = null; 1021 } 1022 1023 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { 1024 mLastDownPositionX = event.getX(); 1025 mLastDownPositionY = event.getY(); 1026 1027 // Reset this state; it will be re-set if super.onTouchEvent 1028 // causes focus to move to the view. 1029 mTouchFocusSelected = false; 1030 mIgnoreActionUpEvent = false; 1031 } 1032 } 1033 1034 public void beginBatchEdit() { 1035 mInBatchEditControllers = true; 1036 final InputMethodState ims = mInputMethodState; 1037 if (ims != null) { 1038 int nesting = ++ims.mBatchEditNesting; 1039 if (nesting == 1) { 1040 ims.mCursorChanged = false; 1041 ims.mChangedDelta = 0; 1042 if (ims.mContentChanged) { 1043 // We already have a pending change from somewhere else, 1044 // so turn this into a full update. 1045 ims.mChangedStart = 0; 1046 ims.mChangedEnd = mTextView.getText().length(); 1047 } else { 1048 ims.mChangedStart = EXTRACT_UNKNOWN; 1049 ims.mChangedEnd = EXTRACT_UNKNOWN; 1050 ims.mContentChanged = false; 1051 } 1052 mTextView.onBeginBatchEdit(); 1053 } 1054 } 1055 } 1056 1057 public void endBatchEdit() { 1058 mInBatchEditControllers = false; 1059 final InputMethodState ims = mInputMethodState; 1060 if (ims != null) { 1061 int nesting = --ims.mBatchEditNesting; 1062 if (nesting == 0) { 1063 finishBatchEdit(ims); 1064 } 1065 } 1066 } 1067 1068 void ensureEndedBatchEdit() { 1069 final InputMethodState ims = mInputMethodState; 1070 if (ims != null && ims.mBatchEditNesting != 0) { 1071 ims.mBatchEditNesting = 0; 1072 finishBatchEdit(ims); 1073 } 1074 } 1075 1076 void finishBatchEdit(final InputMethodState ims) { 1077 mTextView.onEndBatchEdit(); 1078 1079 if (ims.mContentChanged || ims.mSelectionModeChanged) { 1080 mTextView.updateAfterEdit(); 1081 reportExtractedText(); 1082 } else if (ims.mCursorChanged) { 1083 // Cheezy way to get us to report the current cursor location. 1084 mTextView.invalidateCursor(); 1085 } 1086 } 1087 1088 static final int EXTRACT_NOTHING = -2; 1089 static final int EXTRACT_UNKNOWN = -1; 1090 1091 boolean extractText(ExtractedTextRequest request, ExtractedText outText) { 1092 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN, 1093 EXTRACT_UNKNOWN, outText); 1094 } 1095 1096 private boolean extractTextInternal(ExtractedTextRequest request, 1097 int partialStartOffset, int partialEndOffset, int delta, 1098 ExtractedText outText) { 1099 final CharSequence content = mTextView.getText(); 1100 if (content != null) { 1101 if (partialStartOffset != EXTRACT_NOTHING) { 1102 final int N = content.length(); 1103 if (partialStartOffset < 0) { 1104 outText.partialStartOffset = outText.partialEndOffset = -1; 1105 partialStartOffset = 0; 1106 partialEndOffset = N; 1107 } else { 1108 // Now use the delta to determine the actual amount of text 1109 // we need. 1110 partialEndOffset += delta; 1111 // Adjust offsets to ensure we contain full spans. 1112 if (content instanceof Spanned) { 1113 Spanned spanned = (Spanned)content; 1114 Object[] spans = spanned.getSpans(partialStartOffset, 1115 partialEndOffset, ParcelableSpan.class); 1116 int i = spans.length; 1117 while (i > 0) { 1118 i--; 1119 int j = spanned.getSpanStart(spans[i]); 1120 if (j < partialStartOffset) partialStartOffset = j; 1121 j = spanned.getSpanEnd(spans[i]); 1122 if (j > partialEndOffset) partialEndOffset = j; 1123 } 1124 } 1125 outText.partialStartOffset = partialStartOffset; 1126 outText.partialEndOffset = partialEndOffset - delta; 1127 1128 if (partialStartOffset > N) { 1129 partialStartOffset = N; 1130 } else if (partialStartOffset < 0) { 1131 partialStartOffset = 0; 1132 } 1133 if (partialEndOffset > N) { 1134 partialEndOffset = N; 1135 } else if (partialEndOffset < 0) { 1136 partialEndOffset = 0; 1137 } 1138 } 1139 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) { 1140 outText.text = content.subSequence(partialStartOffset, 1141 partialEndOffset); 1142 } else { 1143 outText.text = TextUtils.substring(content, partialStartOffset, 1144 partialEndOffset); 1145 } 1146 } else { 1147 outText.partialStartOffset = 0; 1148 outText.partialEndOffset = 0; 1149 outText.text = ""; 1150 } 1151 outText.flags = 0; 1152 if (MetaKeyKeyListener.getMetaState(content, MetaKeyKeyListener.META_SELECTING) != 0) { 1153 outText.flags |= ExtractedText.FLAG_SELECTING; 1154 } 1155 if (mTextView.isSingleLine()) { 1156 outText.flags |= ExtractedText.FLAG_SINGLE_LINE; 1157 } 1158 outText.startOffset = 0; 1159 outText.selectionStart = mTextView.getSelectionStart(); 1160 outText.selectionEnd = mTextView.getSelectionEnd(); 1161 return true; 1162 } 1163 return false; 1164 } 1165 1166 boolean reportExtractedText() { 1167 final Editor.InputMethodState ims = mInputMethodState; 1168 if (ims != null) { 1169 final boolean contentChanged = ims.mContentChanged; 1170 if (contentChanged || ims.mSelectionModeChanged) { 1171 ims.mContentChanged = false; 1172 ims.mSelectionModeChanged = false; 1173 final ExtractedTextRequest req = ims.mExtractedTextRequest; 1174 if (req != null) { 1175 InputMethodManager imm = InputMethodManager.peekInstance(); 1176 if (imm != null) { 1177 if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG, 1178 "Retrieving extracted start=" + ims.mChangedStart + 1179 " end=" + ims.mChangedEnd + 1180 " delta=" + ims.mChangedDelta); 1181 if (ims.mChangedStart < 0 && !contentChanged) { 1182 ims.mChangedStart = EXTRACT_NOTHING; 1183 } 1184 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd, 1185 ims.mChangedDelta, ims.mExtractedText)) { 1186 if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG, 1187 "Reporting extracted start=" + 1188 ims.mExtractedText.partialStartOffset + 1189 " end=" + ims.mExtractedText.partialEndOffset + 1190 ": " + ims.mExtractedText.text); 1191 1192 imm.updateExtractedText(mTextView, req.token, ims.mExtractedText); 1193 ims.mChangedStart = EXTRACT_UNKNOWN; 1194 ims.mChangedEnd = EXTRACT_UNKNOWN; 1195 ims.mChangedDelta = 0; 1196 ims.mContentChanged = false; 1197 return true; 1198 } 1199 } 1200 } 1201 } 1202 } 1203 return false; 1204 } 1205 1206 void onDraw(Canvas canvas, Layout layout, Path highlight, Paint highlightPaint, 1207 int cursorOffsetVertical) { 1208 final int selectionStart = mTextView.getSelectionStart(); 1209 final int selectionEnd = mTextView.getSelectionEnd(); 1210 1211 final InputMethodState ims = mInputMethodState; 1212 if (ims != null && ims.mBatchEditNesting == 0) { 1213 InputMethodManager imm = InputMethodManager.peekInstance(); 1214 if (imm != null) { 1215 if (imm.isActive(mTextView)) { 1216 boolean reported = false; 1217 if (ims.mContentChanged || ims.mSelectionModeChanged) { 1218 // We are in extract mode and the content has changed 1219 // in some way... just report complete new text to the 1220 // input method. 1221 reported = reportExtractedText(); 1222 } 1223 if (!reported && highlight != null) { 1224 int candStart = -1; 1225 int candEnd = -1; 1226 if (mTextView.getText() instanceof Spannable) { 1227 Spannable sp = (Spannable) mTextView.getText(); 1228 candStart = EditableInputConnection.getComposingSpanStart(sp); 1229 candEnd = EditableInputConnection.getComposingSpanEnd(sp); 1230 } 1231 imm.updateSelection(mTextView, 1232 selectionStart, selectionEnd, candStart, candEnd); 1233 } 1234 } 1235 1236 if (imm.isWatchingCursor(mTextView) && highlight != null) { 1237 highlight.computeBounds(ims.mTmpRectF, true); 1238 ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0; 1239 1240 canvas.getMatrix().mapPoints(ims.mTmpOffset); 1241 ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]); 1242 1243 ims.mTmpRectF.offset(0, cursorOffsetVertical); 1244 1245 ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5), 1246 (int)(ims.mTmpRectF.top + 0.5), 1247 (int)(ims.mTmpRectF.right + 0.5), 1248 (int)(ims.mTmpRectF.bottom + 0.5)); 1249 1250 imm.updateCursor(mTextView, 1251 ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top, 1252 ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom); 1253 } 1254 } 1255 } 1256 1257 if (mCorrectionHighlighter != null) { 1258 mCorrectionHighlighter.draw(canvas, cursorOffsetVertical); 1259 } 1260 1261 if (highlight != null && selectionStart == selectionEnd && mCursorCount > 0) { 1262 drawCursor(canvas, cursorOffsetVertical); 1263 // Rely on the drawable entirely, do not draw the cursor line. 1264 // Has to be done after the IMM related code above which relies on the highlight. 1265 highlight = null; 1266 } 1267 1268 if (mTextView.canHaveDisplayList() && canvas.isHardwareAccelerated()) { 1269 drawHardwareAccelerated(canvas, layout, highlight, highlightPaint, 1270 cursorOffsetVertical); 1271 } else { 1272 layout.draw(canvas, highlight, highlightPaint, cursorOffsetVertical); 1273 } 1274 } 1275 1276 private void drawHardwareAccelerated(Canvas canvas, Layout layout, Path highlight, 1277 Paint highlightPaint, int cursorOffsetVertical) { 1278 final long lineRange = layout.getLineRangeForDraw(canvas); 1279 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange); 1280 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange); 1281 if (lastLine < 0) return; 1282 1283 layout.drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical, 1284 firstLine, lastLine); 1285 1286 if (layout instanceof DynamicLayout) { 1287 if (mTextDisplayLists == null) { 1288 mTextDisplayLists = new DisplayList[ArrayUtils.idealObjectArraySize(0)]; 1289 } 1290 1291 DynamicLayout dynamicLayout = (DynamicLayout) layout; 1292 int[] blockEndLines = dynamicLayout.getBlockEndLines(); 1293 int[] blockIndices = dynamicLayout.getBlockIndices(); 1294 final int numberOfBlocks = dynamicLayout.getNumberOfBlocks(); 1295 final int indexFirstChangedBlock = dynamicLayout.getIndexFirstChangedBlock(); 1296 1297 int endOfPreviousBlock = -1; 1298 int searchStartIndex = 0; 1299 for (int i = 0; i < numberOfBlocks; i++) { 1300 int blockEndLine = blockEndLines[i]; 1301 int blockIndex = blockIndices[i]; 1302 1303 final boolean blockIsInvalid = blockIndex == DynamicLayout.INVALID_BLOCK_INDEX; 1304 if (blockIsInvalid) { 1305 blockIndex = getAvailableDisplayListIndex(blockIndices, numberOfBlocks, 1306 searchStartIndex); 1307 // Note how dynamic layout's internal block indices get updated from Editor 1308 blockIndices[i] = blockIndex; 1309 searchStartIndex = blockIndex + 1; 1310 } 1311 1312 DisplayList blockDisplayList = mTextDisplayLists[blockIndex]; 1313 if (blockDisplayList == null) { 1314 blockDisplayList = mTextDisplayLists[blockIndex] = 1315 mTextView.getHardwareRenderer().createDisplayList("Text " + blockIndex); 1316 } else { 1317 if (blockIsInvalid) blockDisplayList.invalidate(); 1318 } 1319 1320 final boolean blockDisplayListIsInvalid = !blockDisplayList.isValid(); 1321 if (i >= indexFirstChangedBlock || blockDisplayListIsInvalid) { 1322 final int blockBeginLine = endOfPreviousBlock + 1; 1323 final int top = layout.getLineTop(blockBeginLine); 1324 final int bottom = layout.getLineBottom(blockEndLine); 1325 int left = 0; 1326 int right = mTextView.getWidth(); 1327 if (mTextView.getHorizontallyScrolling()) { 1328 float min = Float.MAX_VALUE; 1329 float max = Float.MIN_VALUE; 1330 for (int line = blockBeginLine; line <= blockEndLine; line++) { 1331 min = Math.min(min, layout.getLineLeft(line)); 1332 max = Math.max(max, layout.getLineRight(line)); 1333 } 1334 left = (int) min; 1335 right = (int) (max + 0.5f); 1336 } 1337 1338 // Rebuild display list if it is invalid 1339 if (blockDisplayListIsInvalid) { 1340 final HardwareCanvas hardwareCanvas = blockDisplayList.start(); 1341 try { 1342 // Tighten the bounds of the viewport to the actual text size 1343 hardwareCanvas.setViewport(right - left, bottom - top); 1344 // The dirty rect should always be null for a display list 1345 hardwareCanvas.onPreDraw(null); 1346 // drawText is always relative to TextView's origin, this translation brings 1347 // this range of text back to the top left corner of the viewport 1348 hardwareCanvas.translate(-left, -top); 1349 layout.drawText(hardwareCanvas, blockBeginLine, blockEndLine); 1350 // No need to untranslate, previous context is popped after drawDisplayList 1351 } finally { 1352 hardwareCanvas.onPostDraw(); 1353 blockDisplayList.end(); 1354 // Same as drawDisplayList below, handled by our TextView's parent 1355 blockDisplayList.setClipChildren(false); 1356 } 1357 } 1358 1359 // Valid disply list whose index is >= indexFirstChangedBlock 1360 // only needs to update its drawing location. 1361 blockDisplayList.setLeftTopRightBottom(left, top, right, bottom); 1362 } 1363 1364 ((HardwareCanvas) canvas).drawDisplayList(blockDisplayList, null, 1365 0 /* no child clipping, our TextView parent enforces it */); 1366 1367 endOfPreviousBlock = blockEndLine; 1368 } 1369 1370 dynamicLayout.setIndexFirstChangedBlock(numberOfBlocks); 1371 } else { 1372 // Boring layout is used for empty and hint text 1373 layout.drawText(canvas, firstLine, lastLine); 1374 } 1375 } 1376 1377 private int getAvailableDisplayListIndex(int[] blockIndices, int numberOfBlocks, 1378 int searchStartIndex) { 1379 int length = mTextDisplayLists.length; 1380 for (int i = searchStartIndex; i < length; i++) { 1381 boolean blockIndexFound = false; 1382 for (int j = 0; j < numberOfBlocks; j++) { 1383 if (blockIndices[j] == i) { 1384 blockIndexFound = true; 1385 break; 1386 } 1387 } 1388 if (blockIndexFound) continue; 1389 return i; 1390 } 1391 1392 // No available index found, the pool has to grow 1393 int newSize = ArrayUtils.idealIntArraySize(length + 1); 1394 DisplayList[] displayLists = new DisplayList[newSize]; 1395 System.arraycopy(mTextDisplayLists, 0, displayLists, 0, length); 1396 mTextDisplayLists = displayLists; 1397 return length; 1398 } 1399 1400 private void drawCursor(Canvas canvas, int cursorOffsetVertical) { 1401 final boolean translate = cursorOffsetVertical != 0; 1402 if (translate) canvas.translate(0, cursorOffsetVertical); 1403 for (int i = 0; i < mCursorCount; i++) { 1404 mCursorDrawable[i].draw(canvas); 1405 } 1406 if (translate) canvas.translate(0, -cursorOffsetVertical); 1407 } 1408 1409 /** 1410 * Invalidates all the sub-display lists that overlap the specified character range 1411 */ 1412 void invalidateTextDisplayList(Layout layout, int start, int end) { 1413 if (mTextDisplayLists != null && layout instanceof DynamicLayout) { 1414 final int firstLine = layout.getLineForOffset(start); 1415 final int lastLine = layout.getLineForOffset(end); 1416 1417 DynamicLayout dynamicLayout = (DynamicLayout) layout; 1418 int[] blockEndLines = dynamicLayout.getBlockEndLines(); 1419 int[] blockIndices = dynamicLayout.getBlockIndices(); 1420 final int numberOfBlocks = dynamicLayout.getNumberOfBlocks(); 1421 1422 int i = 0; 1423 // Skip the blocks before firstLine 1424 while (i < numberOfBlocks) { 1425 if (blockEndLines[i] >= firstLine) break; 1426 i++; 1427 } 1428 1429 // Invalidate all subsequent blocks until lastLine is passed 1430 while (i < numberOfBlocks) { 1431 final int blockIndex = blockIndices[i]; 1432 if (blockIndex != DynamicLayout.INVALID_BLOCK_INDEX) { 1433 mTextDisplayLists[blockIndex].invalidate(); 1434 } 1435 if (blockEndLines[i] >= lastLine) break; 1436 i++; 1437 } 1438 } 1439 } 1440 1441 void invalidateTextDisplayList() { 1442 if (mTextDisplayLists != null) { 1443 for (int i = 0; i < mTextDisplayLists.length; i++) { 1444 if (mTextDisplayLists[i] != null) mTextDisplayLists[i].invalidate(); 1445 } 1446 } 1447 } 1448 1449 void updateCursorsPositions() { 1450 if (mTextView.mCursorDrawableRes == 0) { 1451 mCursorCount = 0; 1452 return; 1453 } 1454 1455 Layout layout = mTextView.getLayout(); 1456 Layout hintLayout = mTextView.getHintLayout(); 1457 final int offset = mTextView.getSelectionStart(); 1458 final int line = layout.getLineForOffset(offset); 1459 final int top = layout.getLineTop(line); 1460 final int bottom = layout.getLineTop(line + 1); 1461 1462 mCursorCount = layout.isLevelBoundary(offset) ? 2 : 1; 1463 1464 int middle = bottom; 1465 if (mCursorCount == 2) { 1466 // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)} 1467 middle = (top + bottom) >> 1; 1468 } 1469 1470 boolean clamped = layout.shouldClampCursor(line); 1471 updateCursorPosition(0, top, middle, 1472 getPrimaryHorizontal(layout, hintLayout, offset, clamped)); 1473 1474 if (mCursorCount == 2) { 1475 updateCursorPosition(1, middle, bottom, 1476 layout.getSecondaryHorizontal(offset, clamped)); 1477 } 1478 } 1479 1480 private float getPrimaryHorizontal(Layout layout, Layout hintLayout, int offset, 1481 boolean clamped) { 1482 if (TextUtils.isEmpty(layout.getText()) && 1483 hintLayout != null && 1484 !TextUtils.isEmpty(hintLayout.getText())) { 1485 return hintLayout.getPrimaryHorizontal(offset, clamped); 1486 } else { 1487 return layout.getPrimaryHorizontal(offset, clamped); 1488 } 1489 } 1490 1491 /** 1492 * @return true if the selection mode was actually started. 1493 */ 1494 boolean startSelectionActionMode() { 1495 if (mSelectionActionMode != null) { 1496 // Selection action mode is already started 1497 return false; 1498 } 1499 1500 if (!canSelectText() || !mTextView.requestFocus()) { 1501 Log.w(TextView.LOG_TAG, 1502 "TextView does not support text selection. Action mode cancelled."); 1503 return false; 1504 } 1505 1506 if (!mTextView.hasSelection()) { 1507 // There may already be a selection on device rotation 1508 if (!selectCurrentWord()) { 1509 // No word found under cursor or text selection not permitted. 1510 return false; 1511 } 1512 } 1513 1514 boolean willExtract = extractedTextModeWillBeStarted(); 1515 1516 // Do not start the action mode when extracted text will show up full screen, which would 1517 // immediately hide the newly created action bar and would be visually distracting. 1518 if (!willExtract) { 1519 ActionMode.Callback actionModeCallback = new SelectionActionModeCallback(); 1520 mSelectionActionMode = mTextView.startActionMode(actionModeCallback); 1521 } 1522 1523 final boolean selectionStarted = mSelectionActionMode != null || willExtract; 1524 if (selectionStarted && !mTextView.isTextSelectable() && mShowSoftInputOnFocus) { 1525 // Show the IME to be able to replace text, except when selecting non editable text. 1526 final InputMethodManager imm = InputMethodManager.peekInstance(); 1527 if (imm != null) { 1528 imm.showSoftInput(mTextView, 0, null); 1529 } 1530 } 1531 1532 return selectionStarted; 1533 } 1534 1535 private boolean extractedTextModeWillBeStarted() { 1536 if (!(mTextView instanceof ExtractEditText)) { 1537 final InputMethodManager imm = InputMethodManager.peekInstance(); 1538 return imm != null && imm.isFullscreenMode(); 1539 } 1540 return false; 1541 } 1542 1543 /** 1544 * @return <code>true</code> if the cursor/current selection overlaps a {@link SuggestionSpan}. 1545 */ 1546 private boolean isCursorInsideSuggestionSpan() { 1547 CharSequence text = mTextView.getText(); 1548 if (!(text instanceof Spannable)) return false; 1549 1550 SuggestionSpan[] suggestionSpans = ((Spannable) text).getSpans( 1551 mTextView.getSelectionStart(), mTextView.getSelectionEnd(), SuggestionSpan.class); 1552 return (suggestionSpans.length > 0); 1553 } 1554 1555 /** 1556 * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with 1557 * {@link SuggestionSpan#FLAG_EASY_CORRECT} set. 1558 */ 1559 private boolean isCursorInsideEasyCorrectionSpan() { 1560 Spannable spannable = (Spannable) mTextView.getText(); 1561 SuggestionSpan[] suggestionSpans = spannable.getSpans(mTextView.getSelectionStart(), 1562 mTextView.getSelectionEnd(), SuggestionSpan.class); 1563 for (int i = 0; i < suggestionSpans.length; i++) { 1564 if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) { 1565 return true; 1566 } 1567 } 1568 return false; 1569 } 1570 1571 void onTouchUpEvent(MotionEvent event) { 1572 boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect(); 1573 hideControllers(); 1574 CharSequence text = mTextView.getText(); 1575 if (!selectAllGotFocus && text.length() > 0) { 1576 // Move cursor 1577 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY()); 1578 Selection.setSelection((Spannable) text, offset); 1579 if (mSpellChecker != null) { 1580 // When the cursor moves, the word that was typed may need spell check 1581 mSpellChecker.onSelectionChanged(); 1582 } 1583 if (!extractedTextModeWillBeStarted()) { 1584 if (isCursorInsideEasyCorrectionSpan()) { 1585 mShowSuggestionRunnable = new Runnable() { 1586 public void run() { 1587 showSuggestions(); 1588 } 1589 }; 1590 // removeCallbacks is performed on every touch 1591 mTextView.postDelayed(mShowSuggestionRunnable, 1592 ViewConfiguration.getDoubleTapTimeout()); 1593 } else if (hasInsertionController()) { 1594 getInsertionController().show(); 1595 } 1596 } 1597 } 1598 } 1599 1600 protected void stopSelectionActionMode() { 1601 if (mSelectionActionMode != null) { 1602 // This will hide the mSelectionModifierCursorController 1603 mSelectionActionMode.finish(); 1604 } 1605 } 1606 1607 /** 1608 * @return True if this view supports insertion handles. 1609 */ 1610 boolean hasInsertionController() { 1611 return mInsertionControllerEnabled; 1612 } 1613 1614 /** 1615 * @return True if this view supports selection handles. 1616 */ 1617 boolean hasSelectionController() { 1618 return mSelectionControllerEnabled; 1619 } 1620 1621 InsertionPointCursorController getInsertionController() { 1622 if (!mInsertionControllerEnabled) { 1623 return null; 1624 } 1625 1626 if (mInsertionPointCursorController == null) { 1627 mInsertionPointCursorController = new InsertionPointCursorController(); 1628 1629 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 1630 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 1631 } 1632 1633 return mInsertionPointCursorController; 1634 } 1635 1636 SelectionModifierCursorController getSelectionController() { 1637 if (!mSelectionControllerEnabled) { 1638 return null; 1639 } 1640 1641 if (mSelectionModifierCursorController == null) { 1642 mSelectionModifierCursorController = new SelectionModifierCursorController(); 1643 1644 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 1645 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 1646 } 1647 1648 return mSelectionModifierCursorController; 1649 } 1650 1651 private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) { 1652 if (mCursorDrawable[cursorIndex] == null) 1653 mCursorDrawable[cursorIndex] = mTextView.getResources().getDrawable( 1654 mTextView.mCursorDrawableRes); 1655 1656 if (mTempRect == null) mTempRect = new Rect(); 1657 mCursorDrawable[cursorIndex].getPadding(mTempRect); 1658 final int width = mCursorDrawable[cursorIndex].getIntrinsicWidth(); 1659 horizontal = Math.max(0.5f, horizontal - 0.5f); 1660 final int left = (int) (horizontal) - mTempRect.left; 1661 mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width, 1662 bottom + mTempRect.bottom); 1663 } 1664 1665 /** 1666 * Called by the framework in response to a text auto-correction (such as fixing a typo using a 1667 * a dictionnary) from the current input method, provided by it calling 1668 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default 1669 * implementation flashes the background of the corrected word to provide feedback to the user. 1670 * 1671 * @param info The auto correct info about the text that was corrected. 1672 */ 1673 public void onCommitCorrection(CorrectionInfo info) { 1674 if (mCorrectionHighlighter == null) { 1675 mCorrectionHighlighter = new CorrectionHighlighter(); 1676 } else { 1677 mCorrectionHighlighter.invalidate(false); 1678 } 1679 1680 mCorrectionHighlighter.highlight(info); 1681 } 1682 1683 void showSuggestions() { 1684 if (mSuggestionsPopupWindow == null) { 1685 mSuggestionsPopupWindow = new SuggestionsPopupWindow(); 1686 } 1687 hideControllers(); 1688 mSuggestionsPopupWindow.show(); 1689 } 1690 1691 boolean areSuggestionsShown() { 1692 return mSuggestionsPopupWindow != null && mSuggestionsPopupWindow.isShowing(); 1693 } 1694 1695 void onScrollChanged() { 1696 if (mPositionListener != null) { 1697 mPositionListener.onScrollChanged(); 1698 } 1699 } 1700 1701 /** 1702 * @return True when the TextView isFocused and has a valid zero-length selection (cursor). 1703 */ 1704 private boolean shouldBlink() { 1705 if (!isCursorVisible() || !mTextView.isFocused()) return false; 1706 1707 final int start = mTextView.getSelectionStart(); 1708 if (start < 0) return false; 1709 1710 final int end = mTextView.getSelectionEnd(); 1711 if (end < 0) return false; 1712 1713 return start == end; 1714 } 1715 1716 void makeBlink() { 1717 if (shouldBlink()) { 1718 mShowCursor = SystemClock.uptimeMillis(); 1719 if (mBlink == null) mBlink = new Blink(); 1720 mBlink.removeCallbacks(mBlink); 1721 mBlink.postAtTime(mBlink, mShowCursor + BLINK); 1722 } else { 1723 if (mBlink != null) mBlink.removeCallbacks(mBlink); 1724 } 1725 } 1726 1727 private class Blink extends Handler implements Runnable { 1728 private boolean mCancelled; 1729 1730 public void run() { 1731 if (mCancelled) { 1732 return; 1733 } 1734 1735 removeCallbacks(Blink.this); 1736 1737 if (shouldBlink()) { 1738 if (mTextView.getLayout() != null) { 1739 mTextView.invalidateCursorPath(); 1740 } 1741 1742 postAtTime(this, SystemClock.uptimeMillis() + BLINK); 1743 } 1744 } 1745 1746 void cancel() { 1747 if (!mCancelled) { 1748 removeCallbacks(Blink.this); 1749 mCancelled = true; 1750 } 1751 } 1752 1753 void uncancel() { 1754 mCancelled = false; 1755 } 1756 } 1757 1758 private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) { 1759 TextView shadowView = (TextView) View.inflate(mTextView.getContext(), 1760 com.android.internal.R.layout.text_drag_thumbnail, null); 1761 1762 if (shadowView == null) { 1763 throw new IllegalArgumentException("Unable to inflate text drag thumbnail"); 1764 } 1765 1766 if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) { 1767 text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH); 1768 } 1769 shadowView.setText(text); 1770 shadowView.setTextColor(mTextView.getTextColors()); 1771 1772 shadowView.setTextAppearance(mTextView.getContext(), R.styleable.Theme_textAppearanceLarge); 1773 shadowView.setGravity(Gravity.CENTER); 1774 1775 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 1776 ViewGroup.LayoutParams.WRAP_CONTENT)); 1777 1778 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 1779 shadowView.measure(size, size); 1780 1781 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight()); 1782 shadowView.invalidate(); 1783 return new DragShadowBuilder(shadowView); 1784 } 1785 1786 private static class DragLocalState { 1787 public TextView sourceTextView; 1788 public int start, end; 1789 1790 public DragLocalState(TextView sourceTextView, int start, int end) { 1791 this.sourceTextView = sourceTextView; 1792 this.start = start; 1793 this.end = end; 1794 } 1795 } 1796 1797 void onDrop(DragEvent event) { 1798 StringBuilder content = new StringBuilder(""); 1799 ClipData clipData = event.getClipData(); 1800 final int itemCount = clipData.getItemCount(); 1801 for (int i=0; i < itemCount; i++) { 1802 Item item = clipData.getItemAt(i); 1803 content.append(item.coerceToStyledText(mTextView.getContext())); 1804 } 1805 1806 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY()); 1807 1808 Object localState = event.getLocalState(); 1809 DragLocalState dragLocalState = null; 1810 if (localState instanceof DragLocalState) { 1811 dragLocalState = (DragLocalState) localState; 1812 } 1813 boolean dragDropIntoItself = dragLocalState != null && 1814 dragLocalState.sourceTextView == mTextView; 1815 1816 if (dragDropIntoItself) { 1817 if (offset >= dragLocalState.start && offset < dragLocalState.end) { 1818 // A drop inside the original selection discards the drop. 1819 return; 1820 } 1821 } 1822 1823 final int originalLength = mTextView.getText().length(); 1824 long minMax = mTextView.prepareSpacesAroundPaste(offset, offset, content); 1825 int min = TextUtils.unpackRangeStartFromLong(minMax); 1826 int max = TextUtils.unpackRangeEndFromLong(minMax); 1827 1828 Selection.setSelection((Spannable) mTextView.getText(), max); 1829 mTextView.replaceText_internal(min, max, content); 1830 1831 if (dragDropIntoItself) { 1832 int dragSourceStart = dragLocalState.start; 1833 int dragSourceEnd = dragLocalState.end; 1834 if (max <= dragSourceStart) { 1835 // Inserting text before selection has shifted positions 1836 final int shift = mTextView.getText().length() - originalLength; 1837 dragSourceStart += shift; 1838 dragSourceEnd += shift; 1839 } 1840 1841 // Delete original selection 1842 mTextView.deleteText_internal(dragSourceStart, dragSourceEnd); 1843 1844 // Make sure we do not leave two adjacent spaces. 1845 final int prevCharIdx = Math.max(0, dragSourceStart - 1); 1846 final int nextCharIdx = Math.min(mTextView.getText().length(), dragSourceStart + 1); 1847 if (nextCharIdx > prevCharIdx + 1) { 1848 CharSequence t = mTextView.getTransformedText(prevCharIdx, nextCharIdx); 1849 if (Character.isSpaceChar(t.charAt(0)) && Character.isSpaceChar(t.charAt(1))) { 1850 mTextView.deleteText_internal(prevCharIdx, prevCharIdx + 1); 1851 } 1852 } 1853 } 1854 } 1855 1856 public void addSpanWatchers(Spannable text) { 1857 final int textLength = text.length(); 1858 1859 if (mKeyListener != null) { 1860 text.setSpan(mKeyListener, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 1861 } 1862 1863 if (mEasyEditSpanController == null) { 1864 mEasyEditSpanController = new EasyEditSpanController(); 1865 } 1866 text.setSpan(mEasyEditSpanController, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 1867 } 1868 1869 /** 1870 * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related 1871 * pop-up should be displayed. 1872 */ 1873 class EasyEditSpanController implements SpanWatcher { 1874 1875 private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs 1876 1877 private EasyEditPopupWindow mPopupWindow; 1878 1879 private Runnable mHidePopup; 1880 1881 @Override 1882 public void onSpanAdded(Spannable text, Object span, int start, int end) { 1883 if (span instanceof EasyEditSpan) { 1884 if (mPopupWindow == null) { 1885 mPopupWindow = new EasyEditPopupWindow(); 1886 mHidePopup = new Runnable() { 1887 @Override 1888 public void run() { 1889 hide(); 1890 } 1891 }; 1892 } 1893 1894 // Make sure there is only at most one EasyEditSpan in the text 1895 if (mPopupWindow.mEasyEditSpan != null) { 1896 text.removeSpan(mPopupWindow.mEasyEditSpan); 1897 } 1898 1899 mPopupWindow.setEasyEditSpan((EasyEditSpan) span); 1900 1901 if (mTextView.getWindowVisibility() != View.VISIBLE) { 1902 // The window is not visible yet, ignore the text change. 1903 return; 1904 } 1905 1906 if (mTextView.getLayout() == null) { 1907 // The view has not been laid out yet, ignore the text change 1908 return; 1909 } 1910 1911 if (extractedTextModeWillBeStarted()) { 1912 // The input is in extract mode. Do not handle the easy edit in 1913 // the original TextView, as the ExtractEditText will do 1914 return; 1915 } 1916 1917 mPopupWindow.show(); 1918 mTextView.removeCallbacks(mHidePopup); 1919 mTextView.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS); 1920 } 1921 } 1922 1923 @Override 1924 public void onSpanRemoved(Spannable text, Object span, int start, int end) { 1925 if (mPopupWindow != null && span == mPopupWindow.mEasyEditSpan) { 1926 hide(); 1927 } 1928 } 1929 1930 @Override 1931 public void onSpanChanged(Spannable text, Object span, int previousStart, int previousEnd, 1932 int newStart, int newEnd) { 1933 if (mPopupWindow != null && span == mPopupWindow.mEasyEditSpan) { 1934 text.removeSpan(mPopupWindow.mEasyEditSpan); 1935 } 1936 } 1937 1938 public void hide() { 1939 if (mPopupWindow != null) { 1940 mPopupWindow.hide(); 1941 mTextView.removeCallbacks(mHidePopup); 1942 } 1943 } 1944 } 1945 1946 /** 1947 * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled 1948 * by {@link EasyEditSpanController}. 1949 */ 1950 private class EasyEditPopupWindow extends PinnedPopupWindow 1951 implements OnClickListener { 1952 private static final int POPUP_TEXT_LAYOUT = 1953 com.android.internal.R.layout.text_edit_action_popup_text; 1954 private TextView mDeleteTextView; 1955 private EasyEditSpan mEasyEditSpan; 1956 1957 @Override 1958 protected void createPopupWindow() { 1959 mPopupWindow = new PopupWindow(mTextView.getContext(), null, 1960 com.android.internal.R.attr.textSelectHandleWindowStyle); 1961 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 1962 mPopupWindow.setClippingEnabled(true); 1963 } 1964 1965 @Override 1966 protected void initContentView() { 1967 LinearLayout linearLayout = new LinearLayout(mTextView.getContext()); 1968 linearLayout.setOrientation(LinearLayout.HORIZONTAL); 1969 mContentView = linearLayout; 1970 mContentView.setBackgroundResource( 1971 com.android.internal.R.drawable.text_edit_side_paste_window); 1972 1973 LayoutInflater inflater = (LayoutInflater)mTextView.getContext(). 1974 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 1975 1976 LayoutParams wrapContent = new LayoutParams( 1977 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 1978 1979 mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 1980 mDeleteTextView.setLayoutParams(wrapContent); 1981 mDeleteTextView.setText(com.android.internal.R.string.delete); 1982 mDeleteTextView.setOnClickListener(this); 1983 mContentView.addView(mDeleteTextView); 1984 } 1985 1986 public void setEasyEditSpan(EasyEditSpan easyEditSpan) { 1987 mEasyEditSpan = easyEditSpan; 1988 } 1989 1990 @Override 1991 public void onClick(View view) { 1992 if (view == mDeleteTextView) { 1993 Editable editable = (Editable) mTextView.getText(); 1994 int start = editable.getSpanStart(mEasyEditSpan); 1995 int end = editable.getSpanEnd(mEasyEditSpan); 1996 if (start >= 0 && end >= 0) { 1997 mTextView.deleteText_internal(start, end); 1998 } 1999 } 2000 } 2001 2002 @Override 2003 protected int getTextOffset() { 2004 // Place the pop-up at the end of the span 2005 Editable editable = (Editable) mTextView.getText(); 2006 return editable.getSpanEnd(mEasyEditSpan); 2007 } 2008 2009 @Override 2010 protected int getVerticalLocalPosition(int line) { 2011 return mTextView.getLayout().getLineBottom(line); 2012 } 2013 2014 @Override 2015 protected int clipVertically(int positionY) { 2016 // As we display the pop-up below the span, no vertical clipping is required. 2017 return positionY; 2018 } 2019 } 2020 2021 private class PositionListener implements ViewTreeObserver.OnPreDrawListener { 2022 // 3 handles 2023 // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others) 2024 private final int MAXIMUM_NUMBER_OF_LISTENERS = 6; 2025 private TextViewPositionListener[] mPositionListeners = 2026 new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS]; 2027 private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS]; 2028 private boolean mPositionHasChanged = true; 2029 // Absolute position of the TextView with respect to its parent window 2030 private int mPositionX, mPositionY; 2031 private int mNumberOfListeners; 2032 private boolean mScrollHasChanged; 2033 final int[] mTempCoords = new int[2]; 2034 2035 public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) { 2036 if (mNumberOfListeners == 0) { 2037 updatePosition(); 2038 ViewTreeObserver vto = mTextView.getViewTreeObserver(); 2039 vto.addOnPreDrawListener(this); 2040 } 2041 2042 int emptySlotIndex = -1; 2043 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 2044 TextViewPositionListener listener = mPositionListeners[i]; 2045 if (listener == positionListener) { 2046 return; 2047 } else if (emptySlotIndex < 0 && listener == null) { 2048 emptySlotIndex = i; 2049 } 2050 } 2051 2052 mPositionListeners[emptySlotIndex] = positionListener; 2053 mCanMove[emptySlotIndex] = canMove; 2054 mNumberOfListeners++; 2055 } 2056 2057 public void removeSubscriber(TextViewPositionListener positionListener) { 2058 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 2059 if (mPositionListeners[i] == positionListener) { 2060 mPositionListeners[i] = null; 2061 mNumberOfListeners--; 2062 break; 2063 } 2064 } 2065 2066 if (mNumberOfListeners == 0) { 2067 ViewTreeObserver vto = mTextView.getViewTreeObserver(); 2068 vto.removeOnPreDrawListener(this); 2069 } 2070 } 2071 2072 public int getPositionX() { 2073 return mPositionX; 2074 } 2075 2076 public int getPositionY() { 2077 return mPositionY; 2078 } 2079 2080 @Override 2081 public boolean onPreDraw() { 2082 updatePosition(); 2083 2084 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 2085 if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) { 2086 TextViewPositionListener positionListener = mPositionListeners[i]; 2087 if (positionListener != null) { 2088 positionListener.updatePosition(mPositionX, mPositionY, 2089 mPositionHasChanged, mScrollHasChanged); 2090 } 2091 } 2092 } 2093 2094 mScrollHasChanged = false; 2095 return true; 2096 } 2097 2098 private void updatePosition() { 2099 mTextView.getLocationInWindow(mTempCoords); 2100 2101 mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY; 2102 2103 mPositionX = mTempCoords[0]; 2104 mPositionY = mTempCoords[1]; 2105 } 2106 2107 public void onScrollChanged() { 2108 mScrollHasChanged = true; 2109 } 2110 } 2111 2112 private abstract class PinnedPopupWindow implements TextViewPositionListener { 2113 protected PopupWindow mPopupWindow; 2114 protected ViewGroup mContentView; 2115 int mPositionX, mPositionY; 2116 2117 protected abstract void createPopupWindow(); 2118 protected abstract void initContentView(); 2119 protected abstract int getTextOffset(); 2120 protected abstract int getVerticalLocalPosition(int line); 2121 protected abstract int clipVertically(int positionY); 2122 2123 public PinnedPopupWindow() { 2124 createPopupWindow(); 2125 2126 mPopupWindow.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 2127 mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 2128 mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 2129 2130 initContentView(); 2131 2132 LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 2133 ViewGroup.LayoutParams.WRAP_CONTENT); 2134 mContentView.setLayoutParams(wrapContent); 2135 2136 mPopupWindow.setContentView(mContentView); 2137 } 2138 2139 public void show() { 2140 getPositionListener().addSubscriber(this, false /* offset is fixed */); 2141 2142 computeLocalPosition(); 2143 2144 final PositionListener positionListener = getPositionListener(); 2145 updatePosition(positionListener.getPositionX(), positionListener.getPositionY()); 2146 } 2147 2148 protected void measureContent() { 2149 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 2150 mContentView.measure( 2151 View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, 2152 View.MeasureSpec.AT_MOST), 2153 View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, 2154 View.MeasureSpec.AT_MOST)); 2155 } 2156 2157 /* The popup window will be horizontally centered on the getTextOffset() and vertically 2158 * positioned according to viewportToContentHorizontalOffset. 2159 * 2160 * This method assumes that mContentView has properly been measured from its content. */ 2161 private void computeLocalPosition() { 2162 measureContent(); 2163 final int width = mContentView.getMeasuredWidth(); 2164 final int offset = getTextOffset(); 2165 mPositionX = (int) (mTextView.getLayout().getPrimaryHorizontal(offset) - width / 2.0f); 2166 mPositionX += mTextView.viewportToContentHorizontalOffset(); 2167 2168 final int line = mTextView.getLayout().getLineForOffset(offset); 2169 mPositionY = getVerticalLocalPosition(line); 2170 mPositionY += mTextView.viewportToContentVerticalOffset(); 2171 } 2172 2173 private void updatePosition(int parentPositionX, int parentPositionY) { 2174 int positionX = parentPositionX + mPositionX; 2175 int positionY = parentPositionY + mPositionY; 2176 2177 positionY = clipVertically(positionY); 2178 2179 // Horizontal clipping 2180 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 2181 final int width = mContentView.getMeasuredWidth(); 2182 positionX = Math.min(displayMetrics.widthPixels - width, positionX); 2183 positionX = Math.max(0, positionX); 2184 2185 if (isShowing()) { 2186 mPopupWindow.update(positionX, positionY, -1, -1); 2187 } else { 2188 mPopupWindow.showAtLocation(mTextView, Gravity.NO_GRAVITY, 2189 positionX, positionY); 2190 } 2191 } 2192 2193 public void hide() { 2194 mPopupWindow.dismiss(); 2195 getPositionListener().removeSubscriber(this); 2196 } 2197 2198 @Override 2199 public void updatePosition(int parentPositionX, int parentPositionY, 2200 boolean parentPositionChanged, boolean parentScrolled) { 2201 // Either parentPositionChanged or parentScrolled is true, check if still visible 2202 if (isShowing() && isOffsetVisible(getTextOffset())) { 2203 if (parentScrolled) computeLocalPosition(); 2204 updatePosition(parentPositionX, parentPositionY); 2205 } else { 2206 hide(); 2207 } 2208 } 2209 2210 public boolean isShowing() { 2211 return mPopupWindow.isShowing(); 2212 } 2213 } 2214 2215 private class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener { 2216 private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE; 2217 private static final int ADD_TO_DICTIONARY = -1; 2218 private static final int DELETE_TEXT = -2; 2219 private SuggestionInfo[] mSuggestionInfos; 2220 private int mNumberOfSuggestions; 2221 private boolean mCursorWasVisibleBeforeSuggestions; 2222 private boolean mIsShowingUp = false; 2223 private SuggestionAdapter mSuggestionsAdapter; 2224 private final Comparator<SuggestionSpan> mSuggestionSpanComparator; 2225 private final HashMap<SuggestionSpan, Integer> mSpansLengths; 2226 2227 private class CustomPopupWindow extends PopupWindow { 2228 public CustomPopupWindow(Context context, int defStyle) { 2229 super(context, null, defStyle); 2230 } 2231 2232 @Override 2233 public void dismiss() { 2234 super.dismiss(); 2235 2236 getPositionListener().removeSubscriber(SuggestionsPopupWindow.this); 2237 2238 // Safe cast since show() checks that mTextView.getText() is an Editable 2239 ((Spannable) mTextView.getText()).removeSpan(mSuggestionRangeSpan); 2240 2241 mTextView.setCursorVisible(mCursorWasVisibleBeforeSuggestions); 2242 if (hasInsertionController()) { 2243 getInsertionController().show(); 2244 } 2245 } 2246 } 2247 2248 public SuggestionsPopupWindow() { 2249 mCursorWasVisibleBeforeSuggestions = mCursorVisible; 2250 mSuggestionSpanComparator = new SuggestionSpanComparator(); 2251 mSpansLengths = new HashMap<SuggestionSpan, Integer>(); 2252 } 2253 2254 @Override 2255 protected void createPopupWindow() { 2256 mPopupWindow = new CustomPopupWindow(mTextView.getContext(), 2257 com.android.internal.R.attr.textSuggestionsWindowStyle); 2258 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 2259 mPopupWindow.setFocusable(true); 2260 mPopupWindow.setClippingEnabled(false); 2261 } 2262 2263 @Override 2264 protected void initContentView() { 2265 ListView listView = new ListView(mTextView.getContext()); 2266 mSuggestionsAdapter = new SuggestionAdapter(); 2267 listView.setAdapter(mSuggestionsAdapter); 2268 listView.setOnItemClickListener(this); 2269 mContentView = listView; 2270 2271 // Inflate the suggestion items once and for all. + 2 for add to dictionary and delete 2272 mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS + 2]; 2273 for (int i = 0; i < mSuggestionInfos.length; i++) { 2274 mSuggestionInfos[i] = new SuggestionInfo(); 2275 } 2276 } 2277 2278 public boolean isShowingUp() { 2279 return mIsShowingUp; 2280 } 2281 2282 public void onParentLostFocus() { 2283 mIsShowingUp = false; 2284 } 2285 2286 private class SuggestionInfo { 2287 int suggestionStart, suggestionEnd; // range of actual suggestion within text 2288 SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents 2289 int suggestionIndex; // the index of this suggestion inside suggestionSpan 2290 SpannableStringBuilder text = new SpannableStringBuilder(); 2291 TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mTextView.getContext(), 2292 android.R.style.TextAppearance_SuggestionHighlight); 2293 } 2294 2295 private class SuggestionAdapter extends BaseAdapter { 2296 private LayoutInflater mInflater = (LayoutInflater) mTextView.getContext(). 2297 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 2298 2299 @Override 2300 public int getCount() { 2301 return mNumberOfSuggestions; 2302 } 2303 2304 @Override 2305 public Object getItem(int position) { 2306 return mSuggestionInfos[position]; 2307 } 2308 2309 @Override 2310 public long getItemId(int position) { 2311 return position; 2312 } 2313 2314 @Override 2315 public View getView(int position, View convertView, ViewGroup parent) { 2316 TextView textView = (TextView) convertView; 2317 2318 if (textView == null) { 2319 textView = (TextView) mInflater.inflate(mTextView.mTextEditSuggestionItemLayout, 2320 parent, false); 2321 } 2322 2323 final SuggestionInfo suggestionInfo = mSuggestionInfos[position]; 2324 textView.setText(suggestionInfo.text); 2325 2326 if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY || 2327 suggestionInfo.suggestionIndex == DELETE_TEXT) { 2328 textView.setBackgroundColor(Color.TRANSPARENT); 2329 } else { 2330 textView.setBackgroundColor(Color.WHITE); 2331 } 2332 2333 return textView; 2334 } 2335 } 2336 2337 private class SuggestionSpanComparator implements Comparator<SuggestionSpan> { 2338 public int compare(SuggestionSpan span1, SuggestionSpan span2) { 2339 final int flag1 = span1.getFlags(); 2340 final int flag2 = span2.getFlags(); 2341 if (flag1 != flag2) { 2342 // The order here should match what is used in updateDrawState 2343 final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0; 2344 final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0; 2345 final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0; 2346 final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0; 2347 if (easy1 && !misspelled1) return -1; 2348 if (easy2 && !misspelled2) return 1; 2349 if (misspelled1) return -1; 2350 if (misspelled2) return 1; 2351 } 2352 2353 return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue(); 2354 } 2355 } 2356 2357 /** 2358 * Returns the suggestion spans that cover the current cursor position. The suggestion 2359 * spans are sorted according to the length of text that they are attached to. 2360 */ 2361 private SuggestionSpan[] getSuggestionSpans() { 2362 int pos = mTextView.getSelectionStart(); 2363 Spannable spannable = (Spannable) mTextView.getText(); 2364 SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class); 2365 2366 mSpansLengths.clear(); 2367 for (SuggestionSpan suggestionSpan : suggestionSpans) { 2368 int start = spannable.getSpanStart(suggestionSpan); 2369 int end = spannable.getSpanEnd(suggestionSpan); 2370 mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start)); 2371 } 2372 2373 // The suggestions are sorted according to their types (easy correction first, then 2374 // misspelled) and to the length of the text that they cover (shorter first). 2375 Arrays.sort(suggestionSpans, mSuggestionSpanComparator); 2376 return suggestionSpans; 2377 } 2378 2379 @Override 2380 public void show() { 2381 if (!(mTextView.getText() instanceof Editable)) return; 2382 2383 if (updateSuggestions()) { 2384 mCursorWasVisibleBeforeSuggestions = mCursorVisible; 2385 mTextView.setCursorVisible(false); 2386 mIsShowingUp = true; 2387 super.show(); 2388 } 2389 } 2390 2391 @Override 2392 protected void measureContent() { 2393 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 2394 final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec( 2395 displayMetrics.widthPixels, View.MeasureSpec.AT_MOST); 2396 final int verticalMeasure = View.MeasureSpec.makeMeasureSpec( 2397 displayMetrics.heightPixels, View.MeasureSpec.AT_MOST); 2398 2399 int width = 0; 2400 View view = null; 2401 for (int i = 0; i < mNumberOfSuggestions; i++) { 2402 view = mSuggestionsAdapter.getView(i, view, mContentView); 2403 view.getLayoutParams().width = LayoutParams.WRAP_CONTENT; 2404 view.measure(horizontalMeasure, verticalMeasure); 2405 width = Math.max(width, view.getMeasuredWidth()); 2406 } 2407 2408 // Enforce the width based on actual text widths 2409 mContentView.measure( 2410 View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), 2411 verticalMeasure); 2412 2413 Drawable popupBackground = mPopupWindow.getBackground(); 2414 if (popupBackground != null) { 2415 if (mTempRect == null) mTempRect = new Rect(); 2416 popupBackground.getPadding(mTempRect); 2417 width += mTempRect.left + mTempRect.right; 2418 } 2419 mPopupWindow.setWidth(width); 2420 } 2421 2422 @Override 2423 protected int getTextOffset() { 2424 return mTextView.getSelectionStart(); 2425 } 2426 2427 @Override 2428 protected int getVerticalLocalPosition(int line) { 2429 return mTextView.getLayout().getLineBottom(line); 2430 } 2431 2432 @Override 2433 protected int clipVertically(int positionY) { 2434 final int height = mContentView.getMeasuredHeight(); 2435 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 2436 return Math.min(positionY, displayMetrics.heightPixels - height); 2437 } 2438 2439 @Override 2440 public void hide() { 2441 super.hide(); 2442 } 2443 2444 private boolean updateSuggestions() { 2445 Spannable spannable = (Spannable) mTextView.getText(); 2446 SuggestionSpan[] suggestionSpans = getSuggestionSpans(); 2447 2448 final int nbSpans = suggestionSpans.length; 2449 // Suggestions are shown after a delay: the underlying spans may have been removed 2450 if (nbSpans == 0) return false; 2451 2452 mNumberOfSuggestions = 0; 2453 int spanUnionStart = mTextView.getText().length(); 2454 int spanUnionEnd = 0; 2455 2456 SuggestionSpan misspelledSpan = null; 2457 int underlineColor = 0; 2458 2459 for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) { 2460 SuggestionSpan suggestionSpan = suggestionSpans[spanIndex]; 2461 final int spanStart = spannable.getSpanStart(suggestionSpan); 2462 final int spanEnd = spannable.getSpanEnd(suggestionSpan); 2463 spanUnionStart = Math.min(spanStart, spanUnionStart); 2464 spanUnionEnd = Math.max(spanEnd, spanUnionEnd); 2465 2466 if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) { 2467 misspelledSpan = suggestionSpan; 2468 } 2469 2470 // The first span dictates the background color of the highlighted text 2471 if (spanIndex == 0) underlineColor = suggestionSpan.getUnderlineColor(); 2472 2473 String[] suggestions = suggestionSpan.getSuggestions(); 2474 int nbSuggestions = suggestions.length; 2475 for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) { 2476 String suggestion = suggestions[suggestionIndex]; 2477 2478 boolean suggestionIsDuplicate = false; 2479 for (int i = 0; i < mNumberOfSuggestions; i++) { 2480 if (mSuggestionInfos[i].text.toString().equals(suggestion)) { 2481 SuggestionSpan otherSuggestionSpan = mSuggestionInfos[i].suggestionSpan; 2482 final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan); 2483 final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan); 2484 if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) { 2485 suggestionIsDuplicate = true; 2486 break; 2487 } 2488 } 2489 } 2490 2491 if (!suggestionIsDuplicate) { 2492 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 2493 suggestionInfo.suggestionSpan = suggestionSpan; 2494 suggestionInfo.suggestionIndex = suggestionIndex; 2495 suggestionInfo.text.replace(0, suggestionInfo.text.length(), suggestion); 2496 2497 mNumberOfSuggestions++; 2498 2499 if (mNumberOfSuggestions == MAX_NUMBER_SUGGESTIONS) { 2500 // Also end outer for loop 2501 spanIndex = nbSpans; 2502 break; 2503 } 2504 } 2505 } 2506 } 2507 2508 for (int i = 0; i < mNumberOfSuggestions; i++) { 2509 highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd); 2510 } 2511 2512 // Add "Add to dictionary" item if there is a span with the misspelled flag 2513 if (misspelledSpan != null) { 2514 final int misspelledStart = spannable.getSpanStart(misspelledSpan); 2515 final int misspelledEnd = spannable.getSpanEnd(misspelledSpan); 2516 if (misspelledStart >= 0 && misspelledEnd > misspelledStart) { 2517 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 2518 suggestionInfo.suggestionSpan = misspelledSpan; 2519 suggestionInfo.suggestionIndex = ADD_TO_DICTIONARY; 2520 suggestionInfo.text.replace(0, suggestionInfo.text.length(), mTextView. 2521 getContext().getString(com.android.internal.R.string.addToDictionary)); 2522 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0, 2523 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2524 2525 mNumberOfSuggestions++; 2526 } 2527 } 2528 2529 // Delete item 2530 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 2531 suggestionInfo.suggestionSpan = null; 2532 suggestionInfo.suggestionIndex = DELETE_TEXT; 2533 suggestionInfo.text.replace(0, suggestionInfo.text.length(), 2534 mTextView.getContext().getString(com.android.internal.R.string.deleteText)); 2535 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0, 2536 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2537 mNumberOfSuggestions++; 2538 2539 if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan(); 2540 if (underlineColor == 0) { 2541 // Fallback on the default highlight color when the first span does not provide one 2542 mSuggestionRangeSpan.setBackgroundColor(mTextView.mHighlightColor); 2543 } else { 2544 final float BACKGROUND_TRANSPARENCY = 0.4f; 2545 final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY); 2546 mSuggestionRangeSpan.setBackgroundColor( 2547 (underlineColor & 0x00FFFFFF) + (newAlpha << 24)); 2548 } 2549 spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd, 2550 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2551 2552 mSuggestionsAdapter.notifyDataSetChanged(); 2553 return true; 2554 } 2555 2556 private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart, 2557 int unionEnd) { 2558 final Spannable text = (Spannable) mTextView.getText(); 2559 final int spanStart = text.getSpanStart(suggestionInfo.suggestionSpan); 2560 final int spanEnd = text.getSpanEnd(suggestionInfo.suggestionSpan); 2561 2562 // Adjust the start/end of the suggestion span 2563 suggestionInfo.suggestionStart = spanStart - unionStart; 2564 suggestionInfo.suggestionEnd = suggestionInfo.suggestionStart 2565 + suggestionInfo.text.length(); 2566 2567 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 2568 suggestionInfo.text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2569 2570 // Add the text before and after the span. 2571 final String textAsString = text.toString(); 2572 suggestionInfo.text.insert(0, textAsString.substring(unionStart, spanStart)); 2573 suggestionInfo.text.append(textAsString.substring(spanEnd, unionEnd)); 2574 } 2575 2576 @Override 2577 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 2578 Editable editable = (Editable) mTextView.getText(); 2579 SuggestionInfo suggestionInfo = mSuggestionInfos[position]; 2580 2581 if (suggestionInfo.suggestionIndex == DELETE_TEXT) { 2582 final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan); 2583 int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan); 2584 if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) { 2585 // Do not leave two adjacent spaces after deletion, or one at beginning of text 2586 if (spanUnionEnd < editable.length() && 2587 Character.isSpaceChar(editable.charAt(spanUnionEnd)) && 2588 (spanUnionStart == 0 || 2589 Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) { 2590 spanUnionEnd = spanUnionEnd + 1; 2591 } 2592 mTextView.deleteText_internal(spanUnionStart, spanUnionEnd); 2593 } 2594 hide(); 2595 return; 2596 } 2597 2598 final int spanStart = editable.getSpanStart(suggestionInfo.suggestionSpan); 2599 final int spanEnd = editable.getSpanEnd(suggestionInfo.suggestionSpan); 2600 if (spanStart < 0 || spanEnd <= spanStart) { 2601 // Span has been removed 2602 hide(); 2603 return; 2604 } 2605 2606 final String originalText = editable.toString().substring(spanStart, spanEnd); 2607 2608 if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) { 2609 Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT); 2610 intent.putExtra("word", originalText); 2611 intent.putExtra("locale", mTextView.getTextServicesLocale().toString()); 2612 // Put a listener to replace the original text with a word which the user 2613 // modified in a user dictionary dialog. 2614 mUserDictionaryListener.waitForUserDictionaryAdded( 2615 mTextView, originalText, spanStart, spanEnd); 2616 intent.putExtra("listener", new Messenger(mUserDictionaryListener)); 2617 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 2618 mTextView.getContext().startActivity(intent); 2619 // There is no way to know if the word was indeed added. Re-check. 2620 // TODO The ExtractEditText should remove the span in the original text instead 2621 editable.removeSpan(suggestionInfo.suggestionSpan); 2622 Selection.setSelection(editable, spanEnd); 2623 updateSpellCheckSpans(spanStart, spanEnd, false); 2624 } else { 2625 // SuggestionSpans are removed by replace: save them before 2626 SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd, 2627 SuggestionSpan.class); 2628 final int length = suggestionSpans.length; 2629 int[] suggestionSpansStarts = new int[length]; 2630 int[] suggestionSpansEnds = new int[length]; 2631 int[] suggestionSpansFlags = new int[length]; 2632 for (int i = 0; i < length; i++) { 2633 final SuggestionSpan suggestionSpan = suggestionSpans[i]; 2634 suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan); 2635 suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan); 2636 suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan); 2637 2638 // Remove potential misspelled flags 2639 int suggestionSpanFlags = suggestionSpan.getFlags(); 2640 if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) > 0) { 2641 suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED; 2642 suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT; 2643 suggestionSpan.setFlags(suggestionSpanFlags); 2644 } 2645 } 2646 2647 final int suggestionStart = suggestionInfo.suggestionStart; 2648 final int suggestionEnd = suggestionInfo.suggestionEnd; 2649 final String suggestion = suggestionInfo.text.subSequence( 2650 suggestionStart, suggestionEnd).toString(); 2651 mTextView.replaceText_internal(spanStart, spanEnd, suggestion); 2652 2653 // Notify source IME of the suggestion pick. Do this before 2654 // swaping texts. 2655 suggestionInfo.suggestionSpan.notifySelection( 2656 mTextView.getContext(), originalText, suggestionInfo.suggestionIndex); 2657 2658 // Swap text content between actual text and Suggestion span 2659 String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions(); 2660 suggestions[suggestionInfo.suggestionIndex] = originalText; 2661 2662 // Restore previous SuggestionSpans 2663 final int lengthDifference = suggestion.length() - (spanEnd - spanStart); 2664 for (int i = 0; i < length; i++) { 2665 // Only spans that include the modified region make sense after replacement 2666 // Spans partially included in the replaced region are removed, there is no 2667 // way to assign them a valid range after replacement 2668 if (suggestionSpansStarts[i] <= spanStart && 2669 suggestionSpansEnds[i] >= spanEnd) { 2670 mTextView.setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i], 2671 suggestionSpansEnds[i] + lengthDifference, suggestionSpansFlags[i]); 2672 } 2673 } 2674 2675 // Move cursor at the end of the replaced word 2676 final int newCursorPosition = spanEnd + lengthDifference; 2677 mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition); 2678 } 2679 2680 hide(); 2681 } 2682 } 2683 2684 /** 2685 * An ActionMode Callback class that is used to provide actions while in text selection mode. 2686 * 2687 * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending 2688 * on which of these this TextView supports. 2689 */ 2690 private class SelectionActionModeCallback implements ActionMode.Callback { 2691 2692 @Override 2693 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 2694 TypedArray styledAttributes = mTextView.getContext().obtainStyledAttributes( 2695 com.android.internal.R.styleable.SelectionModeDrawables); 2696 2697 mode.setTitle(mTextView.getContext().getString( 2698 com.android.internal.R.string.textSelectionCABTitle)); 2699 mode.setSubtitle(null); 2700 mode.setTitleOptionalHint(true); 2701 2702 menu.add(0, TextView.ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll). 2703 setIcon(styledAttributes.getResourceId( 2704 R.styleable.SelectionModeDrawables_actionModeSelectAllDrawable, 0)). 2705 setAlphabeticShortcut('a'). 2706 setShowAsAction( 2707 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 2708 2709 if (mTextView.canCut()) { 2710 menu.add(0, TextView.ID_CUT, 0, com.android.internal.R.string.cut). 2711 setIcon(styledAttributes.getResourceId( 2712 R.styleable.SelectionModeDrawables_actionModeCutDrawable, 0)). 2713 setAlphabeticShortcut('x'). 2714 setShowAsAction( 2715 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 2716 } 2717 2718 if (mTextView.canCopy()) { 2719 menu.add(0, TextView.ID_COPY, 0, com.android.internal.R.string.copy). 2720 setIcon(styledAttributes.getResourceId( 2721 R.styleable.SelectionModeDrawables_actionModeCopyDrawable, 0)). 2722 setAlphabeticShortcut('c'). 2723 setShowAsAction( 2724 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 2725 } 2726 2727 if (mTextView.canPaste()) { 2728 menu.add(0, TextView.ID_PASTE, 0, com.android.internal.R.string.paste). 2729 setIcon(styledAttributes.getResourceId( 2730 R.styleable.SelectionModeDrawables_actionModePasteDrawable, 0)). 2731 setAlphabeticShortcut('v'). 2732 setShowAsAction( 2733 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 2734 } 2735 2736 styledAttributes.recycle(); 2737 2738 if (mCustomSelectionActionModeCallback != null) { 2739 if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) { 2740 // The custom mode can choose to cancel the action mode 2741 return false; 2742 } 2743 } 2744 2745 if (menu.hasVisibleItems() || mode.getCustomView() != null) { 2746 getSelectionController().show(); 2747 mTextView.setHasTransientState(true); 2748 return true; 2749 } else { 2750 return false; 2751 } 2752 } 2753 2754 @Override 2755 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 2756 if (mCustomSelectionActionModeCallback != null) { 2757 return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu); 2758 } 2759 return true; 2760 } 2761 2762 @Override 2763 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 2764 if (mCustomSelectionActionModeCallback != null && 2765 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) { 2766 return true; 2767 } 2768 return mTextView.onTextContextMenuItem(item.getItemId()); 2769 } 2770 2771 @Override 2772 public void onDestroyActionMode(ActionMode mode) { 2773 if (mCustomSelectionActionModeCallback != null) { 2774 mCustomSelectionActionModeCallback.onDestroyActionMode(mode); 2775 } 2776 2777 /* 2778 * If we're ending this mode because we're detaching from a window, 2779 * we still have selection state to preserve. Don't clear it, we'll 2780 * bring back the selection mode when (if) we get reattached. 2781 */ 2782 if (!mPreserveDetachedSelection) { 2783 Selection.setSelection((Spannable) mTextView.getText(), 2784 mTextView.getSelectionEnd()); 2785 mTextView.setHasTransientState(false); 2786 } 2787 2788 if (mSelectionModifierCursorController != null) { 2789 mSelectionModifierCursorController.hide(); 2790 } 2791 2792 mSelectionActionMode = null; 2793 } 2794 } 2795 2796 private class ActionPopupWindow extends PinnedPopupWindow implements OnClickListener { 2797 private static final int POPUP_TEXT_LAYOUT = 2798 com.android.internal.R.layout.text_edit_action_popup_text; 2799 private TextView mPasteTextView; 2800 private TextView mReplaceTextView; 2801 2802 @Override 2803 protected void createPopupWindow() { 2804 mPopupWindow = new PopupWindow(mTextView.getContext(), null, 2805 com.android.internal.R.attr.textSelectHandleWindowStyle); 2806 mPopupWindow.setClippingEnabled(true); 2807 } 2808 2809 @Override 2810 protected void initContentView() { 2811 LinearLayout linearLayout = new LinearLayout(mTextView.getContext()); 2812 linearLayout.setOrientation(LinearLayout.HORIZONTAL); 2813 mContentView = linearLayout; 2814 mContentView.setBackgroundResource( 2815 com.android.internal.R.drawable.text_edit_paste_window); 2816 2817 LayoutInflater inflater = (LayoutInflater) mTextView.getContext(). 2818 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 2819 2820 LayoutParams wrapContent = new LayoutParams( 2821 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 2822 2823 mPasteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 2824 mPasteTextView.setLayoutParams(wrapContent); 2825 mContentView.addView(mPasteTextView); 2826 mPasteTextView.setText(com.android.internal.R.string.paste); 2827 mPasteTextView.setOnClickListener(this); 2828 2829 mReplaceTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 2830 mReplaceTextView.setLayoutParams(wrapContent); 2831 mContentView.addView(mReplaceTextView); 2832 mReplaceTextView.setText(com.android.internal.R.string.replace); 2833 mReplaceTextView.setOnClickListener(this); 2834 } 2835 2836 @Override 2837 public void show() { 2838 boolean canPaste = mTextView.canPaste(); 2839 boolean canSuggest = mTextView.isSuggestionsEnabled() && isCursorInsideSuggestionSpan(); 2840 mPasteTextView.setVisibility(canPaste ? View.VISIBLE : View.GONE); 2841 mReplaceTextView.setVisibility(canSuggest ? View.VISIBLE : View.GONE); 2842 2843 if (!canPaste && !canSuggest) return; 2844 2845 super.show(); 2846 } 2847 2848 @Override 2849 public void onClick(View view) { 2850 if (view == mPasteTextView && mTextView.canPaste()) { 2851 mTextView.onTextContextMenuItem(TextView.ID_PASTE); 2852 hide(); 2853 } else if (view == mReplaceTextView) { 2854 int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2; 2855 stopSelectionActionMode(); 2856 Selection.setSelection((Spannable) mTextView.getText(), middle); 2857 showSuggestions(); 2858 } 2859 } 2860 2861 @Override 2862 protected int getTextOffset() { 2863 return (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2; 2864 } 2865 2866 @Override 2867 protected int getVerticalLocalPosition(int line) { 2868 return mTextView.getLayout().getLineTop(line) - mContentView.getMeasuredHeight(); 2869 } 2870 2871 @Override 2872 protected int clipVertically(int positionY) { 2873 if (positionY < 0) { 2874 final int offset = getTextOffset(); 2875 final Layout layout = mTextView.getLayout(); 2876 final int line = layout.getLineForOffset(offset); 2877 positionY += layout.getLineBottom(line) - layout.getLineTop(line); 2878 positionY += mContentView.getMeasuredHeight(); 2879 2880 // Assumes insertion and selection handles share the same height 2881 final Drawable handle = mTextView.getResources().getDrawable( 2882 mTextView.mTextSelectHandleRes); 2883 positionY += handle.getIntrinsicHeight(); 2884 } 2885 2886 return positionY; 2887 } 2888 } 2889 2890 private abstract class HandleView extends View implements TextViewPositionListener { 2891 protected Drawable mDrawable; 2892 protected Drawable mDrawableLtr; 2893 protected Drawable mDrawableRtl; 2894 private final PopupWindow mContainer; 2895 // Position with respect to the parent TextView 2896 private int mPositionX, mPositionY; 2897 private boolean mIsDragging; 2898 // Offset from touch position to mPosition 2899 private float mTouchToWindowOffsetX, mTouchToWindowOffsetY; 2900 protected int mHotspotX; 2901 // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up 2902 private float mTouchOffsetY; 2903 // Where the touch position should be on the handle to ensure a maximum cursor visibility 2904 private float mIdealVerticalOffset; 2905 // Parent's (TextView) previous position in window 2906 private int mLastParentX, mLastParentY; 2907 // Transient action popup window for Paste and Replace actions 2908 protected ActionPopupWindow mActionPopupWindow; 2909 // Previous text character offset 2910 private int mPreviousOffset = -1; 2911 // Previous text character offset 2912 private boolean mPositionHasChanged = true; 2913 // Used to delay the appearance of the action popup window 2914 private Runnable mActionPopupShower; 2915 2916 public HandleView(Drawable drawableLtr, Drawable drawableRtl) { 2917 super(mTextView.getContext()); 2918 mContainer = new PopupWindow(mTextView.getContext(), null, 2919 com.android.internal.R.attr.textSelectHandleWindowStyle); 2920 mContainer.setSplitTouchEnabled(true); 2921 mContainer.setClippingEnabled(false); 2922 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 2923 mContainer.setContentView(this); 2924 2925 mDrawableLtr = drawableLtr; 2926 mDrawableRtl = drawableRtl; 2927 2928 updateDrawable(); 2929 2930 final int handleHeight = mDrawable.getIntrinsicHeight(); 2931 mTouchOffsetY = -0.3f * handleHeight; 2932 mIdealVerticalOffset = 0.7f * handleHeight; 2933 } 2934 2935 protected void updateDrawable() { 2936 final int offset = getCurrentCursorOffset(); 2937 final boolean isRtlCharAtOffset = mTextView.getLayout().isRtlCharAt(offset); 2938 mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr; 2939 mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset); 2940 } 2941 2942 protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun); 2943 2944 // Touch-up filter: number of previous positions remembered 2945 private static final int HISTORY_SIZE = 5; 2946 private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150; 2947 private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350; 2948 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE]; 2949 private final int[] mPreviousOffsets = new int[HISTORY_SIZE]; 2950 private int mPreviousOffsetIndex = 0; 2951 private int mNumberPreviousOffsets = 0; 2952 2953 private void startTouchUpFilter(int offset) { 2954 mNumberPreviousOffsets = 0; 2955 addPositionToTouchUpFilter(offset); 2956 } 2957 2958 private void addPositionToTouchUpFilter(int offset) { 2959 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE; 2960 mPreviousOffsets[mPreviousOffsetIndex] = offset; 2961 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis(); 2962 mNumberPreviousOffsets++; 2963 } 2964 2965 private void filterOnTouchUp() { 2966 final long now = SystemClock.uptimeMillis(); 2967 int i = 0; 2968 int index = mPreviousOffsetIndex; 2969 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE); 2970 while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) { 2971 i++; 2972 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE; 2973 } 2974 2975 if (i > 0 && i < iMax && 2976 (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) { 2977 positionAtCursorOffset(mPreviousOffsets[index], false); 2978 } 2979 } 2980 2981 public boolean offsetHasBeenChanged() { 2982 return mNumberPreviousOffsets > 1; 2983 } 2984 2985 @Override 2986 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 2987 setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight()); 2988 } 2989 2990 public void show() { 2991 if (isShowing()) return; 2992 2993 getPositionListener().addSubscriber(this, true /* local position may change */); 2994 2995 // Make sure the offset is always considered new, even when focusing at same position 2996 mPreviousOffset = -1; 2997 positionAtCursorOffset(getCurrentCursorOffset(), false); 2998 2999 hideActionPopupWindow(); 3000 } 3001 3002 protected void dismiss() { 3003 mIsDragging = false; 3004 mContainer.dismiss(); 3005 onDetached(); 3006 } 3007 3008 public void hide() { 3009 dismiss(); 3010 3011 getPositionListener().removeSubscriber(this); 3012 } 3013 3014 void showActionPopupWindow(int delay) { 3015 if (mActionPopupWindow == null) { 3016 mActionPopupWindow = new ActionPopupWindow(); 3017 } 3018 if (mActionPopupShower == null) { 3019 mActionPopupShower = new Runnable() { 3020 public void run() { 3021 mActionPopupWindow.show(); 3022 } 3023 }; 3024 } else { 3025 mTextView.removeCallbacks(mActionPopupShower); 3026 } 3027 mTextView.postDelayed(mActionPopupShower, delay); 3028 } 3029 3030 protected void hideActionPopupWindow() { 3031 if (mActionPopupShower != null) { 3032 mTextView.removeCallbacks(mActionPopupShower); 3033 } 3034 if (mActionPopupWindow != null) { 3035 mActionPopupWindow.hide(); 3036 } 3037 } 3038 3039 public boolean isShowing() { 3040 return mContainer.isShowing(); 3041 } 3042 3043 private boolean isVisible() { 3044 // Always show a dragging handle. 3045 if (mIsDragging) { 3046 return true; 3047 } 3048 3049 if (mTextView.isInBatchEditMode()) { 3050 return false; 3051 } 3052 3053 return isPositionVisible(mPositionX + mHotspotX, mPositionY); 3054 } 3055 3056 public abstract int getCurrentCursorOffset(); 3057 3058 protected abstract void updateSelection(int offset); 3059 3060 public abstract void updatePosition(float x, float y); 3061 3062 protected void positionAtCursorOffset(int offset, boolean parentScrolled) { 3063 // A HandleView relies on the layout, which may be nulled by external methods 3064 Layout layout = mTextView.getLayout(); 3065 if (layout == null) { 3066 // Will update controllers' state, hiding them and stopping selection mode if needed 3067 prepareCursorControllers(); 3068 return; 3069 } 3070 3071 boolean offsetChanged = offset != mPreviousOffset; 3072 if (offsetChanged || parentScrolled) { 3073 if (offsetChanged) { 3074 updateSelection(offset); 3075 addPositionToTouchUpFilter(offset); 3076 } 3077 final int line = layout.getLineForOffset(offset); 3078 3079 mPositionX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX); 3080 mPositionY = layout.getLineBottom(line); 3081 3082 // Take TextView's padding and scroll into account. 3083 mPositionX += mTextView.viewportToContentHorizontalOffset(); 3084 mPositionY += mTextView.viewportToContentVerticalOffset(); 3085 3086 mPreviousOffset = offset; 3087 mPositionHasChanged = true; 3088 } 3089 } 3090 3091 public void updatePosition(int parentPositionX, int parentPositionY, 3092 boolean parentPositionChanged, boolean parentScrolled) { 3093 positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled); 3094 if (parentPositionChanged || mPositionHasChanged) { 3095 if (mIsDragging) { 3096 // Update touchToWindow offset in case of parent scrolling while dragging 3097 if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) { 3098 mTouchToWindowOffsetX += parentPositionX - mLastParentX; 3099 mTouchToWindowOffsetY += parentPositionY - mLastParentY; 3100 mLastParentX = parentPositionX; 3101 mLastParentY = parentPositionY; 3102 } 3103 3104 onHandleMoved(); 3105 } 3106 3107 if (isVisible()) { 3108 final int positionX = parentPositionX + mPositionX; 3109 final int positionY = parentPositionY + mPositionY; 3110 if (isShowing()) { 3111 mContainer.update(positionX, positionY, -1, -1); 3112 } else { 3113 mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY, 3114 positionX, positionY); 3115 } 3116 } else { 3117 if (isShowing()) { 3118 dismiss(); 3119 } 3120 } 3121 3122 mPositionHasChanged = false; 3123 } 3124 } 3125 3126 @Override 3127 protected void onDraw(Canvas c) { 3128 mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 3129 mDrawable.draw(c); 3130 } 3131 3132 @Override 3133 public boolean onTouchEvent(MotionEvent ev) { 3134 switch (ev.getActionMasked()) { 3135 case MotionEvent.ACTION_DOWN: { 3136 startTouchUpFilter(getCurrentCursorOffset()); 3137 mTouchToWindowOffsetX = ev.getRawX() - mPositionX; 3138 mTouchToWindowOffsetY = ev.getRawY() - mPositionY; 3139 3140 final PositionListener positionListener = getPositionListener(); 3141 mLastParentX = positionListener.getPositionX(); 3142 mLastParentY = positionListener.getPositionY(); 3143 mIsDragging = true; 3144 break; 3145 } 3146 3147 case MotionEvent.ACTION_MOVE: { 3148 final float rawX = ev.getRawX(); 3149 final float rawY = ev.getRawY(); 3150 3151 // Vertical hysteresis: vertical down movement tends to snap to ideal offset 3152 final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY; 3153 final float currentVerticalOffset = rawY - mPositionY - mLastParentY; 3154 float newVerticalOffset; 3155 if (previousVerticalOffset < mIdealVerticalOffset) { 3156 newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset); 3157 newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset); 3158 } else { 3159 newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset); 3160 newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset); 3161 } 3162 mTouchToWindowOffsetY = newVerticalOffset + mLastParentY; 3163 3164 final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX; 3165 final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY; 3166 3167 updatePosition(newPosX, newPosY); 3168 break; 3169 } 3170 3171 case MotionEvent.ACTION_UP: 3172 filterOnTouchUp(); 3173 mIsDragging = false; 3174 break; 3175 3176 case MotionEvent.ACTION_CANCEL: 3177 mIsDragging = false; 3178 break; 3179 } 3180 return true; 3181 } 3182 3183 public boolean isDragging() { 3184 return mIsDragging; 3185 } 3186 3187 void onHandleMoved() { 3188 hideActionPopupWindow(); 3189 } 3190 3191 public void onDetached() { 3192 hideActionPopupWindow(); 3193 } 3194 } 3195 3196 private class InsertionHandleView extends HandleView { 3197 private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000; 3198 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds 3199 3200 // Used to detect taps on the insertion handle, which will affect the ActionPopupWindow 3201 private float mDownPositionX, mDownPositionY; 3202 private Runnable mHider; 3203 3204 public InsertionHandleView(Drawable drawable) { 3205 super(drawable, drawable); 3206 } 3207 3208 @Override 3209 public void show() { 3210 super.show(); 3211 3212 final long durationSinceCutOrCopy = 3213 SystemClock.uptimeMillis() - TextView.LAST_CUT_OR_COPY_TIME; 3214 if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) { 3215 showActionPopupWindow(0); 3216 } 3217 3218 hideAfterDelay(); 3219 } 3220 3221 public void showWithActionPopup() { 3222 show(); 3223 showActionPopupWindow(0); 3224 } 3225 3226 private void hideAfterDelay() { 3227 if (mHider == null) { 3228 mHider = new Runnable() { 3229 public void run() { 3230 hide(); 3231 } 3232 }; 3233 } else { 3234 removeHiderCallback(); 3235 } 3236 mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT); 3237 } 3238 3239 private void removeHiderCallback() { 3240 if (mHider != null) { 3241 mTextView.removeCallbacks(mHider); 3242 } 3243 } 3244 3245 @Override 3246 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 3247 return drawable.getIntrinsicWidth() / 2; 3248 } 3249 3250 @Override 3251 public boolean onTouchEvent(MotionEvent ev) { 3252 final boolean result = super.onTouchEvent(ev); 3253 3254 switch (ev.getActionMasked()) { 3255 case MotionEvent.ACTION_DOWN: 3256 mDownPositionX = ev.getRawX(); 3257 mDownPositionY = ev.getRawY(); 3258 break; 3259 3260 case MotionEvent.ACTION_UP: 3261 if (!offsetHasBeenChanged()) { 3262 final float deltaX = mDownPositionX - ev.getRawX(); 3263 final float deltaY = mDownPositionY - ev.getRawY(); 3264 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 3265 3266 final ViewConfiguration viewConfiguration = ViewConfiguration.get( 3267 mTextView.getContext()); 3268 final int touchSlop = viewConfiguration.getScaledTouchSlop(); 3269 3270 if (distanceSquared < touchSlop * touchSlop) { 3271 if (mActionPopupWindow != null && mActionPopupWindow.isShowing()) { 3272 // Tapping on the handle dismisses the displayed action popup 3273 mActionPopupWindow.hide(); 3274 } else { 3275 showWithActionPopup(); 3276 } 3277 } 3278 } 3279 hideAfterDelay(); 3280 break; 3281 3282 case MotionEvent.ACTION_CANCEL: 3283 hideAfterDelay(); 3284 break; 3285 3286 default: 3287 break; 3288 } 3289 3290 return result; 3291 } 3292 3293 @Override 3294 public int getCurrentCursorOffset() { 3295 return mTextView.getSelectionStart(); 3296 } 3297 3298 @Override 3299 public void updateSelection(int offset) { 3300 Selection.setSelection((Spannable) mTextView.getText(), offset); 3301 } 3302 3303 @Override 3304 public void updatePosition(float x, float y) { 3305 positionAtCursorOffset(mTextView.getOffsetForPosition(x, y), false); 3306 } 3307 3308 @Override 3309 void onHandleMoved() { 3310 super.onHandleMoved(); 3311 removeHiderCallback(); 3312 } 3313 3314 @Override 3315 public void onDetached() { 3316 super.onDetached(); 3317 removeHiderCallback(); 3318 } 3319 } 3320 3321 private class SelectionStartHandleView extends HandleView { 3322 3323 public SelectionStartHandleView(Drawable drawableLtr, Drawable drawableRtl) { 3324 super(drawableLtr, drawableRtl); 3325 } 3326 3327 @Override 3328 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 3329 if (isRtlRun) { 3330 return drawable.getIntrinsicWidth() / 4; 3331 } else { 3332 return (drawable.getIntrinsicWidth() * 3) / 4; 3333 } 3334 } 3335 3336 @Override 3337 public int getCurrentCursorOffset() { 3338 return mTextView.getSelectionStart(); 3339 } 3340 3341 @Override 3342 public void updateSelection(int offset) { 3343 Selection.setSelection((Spannable) mTextView.getText(), offset, 3344 mTextView.getSelectionEnd()); 3345 updateDrawable(); 3346 } 3347 3348 @Override 3349 public void updatePosition(float x, float y) { 3350 int offset = mTextView.getOffsetForPosition(x, y); 3351 3352 // Handles can not cross and selection is at least one character 3353 final int selectionEnd = mTextView.getSelectionEnd(); 3354 if (offset >= selectionEnd) offset = Math.max(0, selectionEnd - 1); 3355 3356 positionAtCursorOffset(offset, false); 3357 } 3358 3359 public ActionPopupWindow getActionPopupWindow() { 3360 return mActionPopupWindow; 3361 } 3362 } 3363 3364 private class SelectionEndHandleView extends HandleView { 3365 3366 public SelectionEndHandleView(Drawable drawableLtr, Drawable drawableRtl) { 3367 super(drawableLtr, drawableRtl); 3368 } 3369 3370 @Override 3371 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 3372 if (isRtlRun) { 3373 return (drawable.getIntrinsicWidth() * 3) / 4; 3374 } else { 3375 return drawable.getIntrinsicWidth() / 4; 3376 } 3377 } 3378 3379 @Override 3380 public int getCurrentCursorOffset() { 3381 return mTextView.getSelectionEnd(); 3382 } 3383 3384 @Override 3385 public void updateSelection(int offset) { 3386 Selection.setSelection((Spannable) mTextView.getText(), 3387 mTextView.getSelectionStart(), offset); 3388 updateDrawable(); 3389 } 3390 3391 @Override 3392 public void updatePosition(float x, float y) { 3393 int offset = mTextView.getOffsetForPosition(x, y); 3394 3395 // Handles can not cross and selection is at least one character 3396 final int selectionStart = mTextView.getSelectionStart(); 3397 if (offset <= selectionStart) { 3398 offset = Math.min(selectionStart + 1, mTextView.getText().length()); 3399 } 3400 3401 positionAtCursorOffset(offset, false); 3402 } 3403 3404 public void setActionPopupWindow(ActionPopupWindow actionPopupWindow) { 3405 mActionPopupWindow = actionPopupWindow; 3406 } 3407 } 3408 3409 /** 3410 * A CursorController instance can be used to control a cursor in the text. 3411 */ 3412 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener { 3413 /** 3414 * Makes the cursor controller visible on screen. 3415 * See also {@link #hide()}. 3416 */ 3417 public void show(); 3418 3419 /** 3420 * Hide the cursor controller from screen. 3421 * See also {@link #show()}. 3422 */ 3423 public void hide(); 3424 3425 /** 3426 * Called when the view is detached from window. Perform house keeping task, such as 3427 * stopping Runnable thread that would otherwise keep a reference on the context, thus 3428 * preventing the activity from being recycled. 3429 */ 3430 public void onDetached(); 3431 } 3432 3433 private class InsertionPointCursorController implements CursorController { 3434 private InsertionHandleView mHandle; 3435 3436 public void show() { 3437 getHandle().show(); 3438 } 3439 3440 public void showWithActionPopup() { 3441 getHandle().showWithActionPopup(); 3442 } 3443 3444 public void hide() { 3445 if (mHandle != null) { 3446 mHandle.hide(); 3447 } 3448 } 3449 3450 public void onTouchModeChanged(boolean isInTouchMode) { 3451 if (!isInTouchMode) { 3452 hide(); 3453 } 3454 } 3455 3456 private InsertionHandleView getHandle() { 3457 if (mSelectHandleCenter == null) { 3458 mSelectHandleCenter = mTextView.getResources().getDrawable( 3459 mTextView.mTextSelectHandleRes); 3460 } 3461 if (mHandle == null) { 3462 mHandle = new InsertionHandleView(mSelectHandleCenter); 3463 } 3464 return mHandle; 3465 } 3466 3467 @Override 3468 public void onDetached() { 3469 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 3470 observer.removeOnTouchModeChangeListener(this); 3471 3472 if (mHandle != null) mHandle.onDetached(); 3473 } 3474 } 3475 3476 class SelectionModifierCursorController implements CursorController { 3477 private static final int DELAY_BEFORE_REPLACE_ACTION = 200; // milliseconds 3478 // The cursor controller handles, lazily created when shown. 3479 private SelectionStartHandleView mStartHandle; 3480 private SelectionEndHandleView mEndHandle; 3481 // The offsets of that last touch down event. Remembered to start selection there. 3482 private int mMinTouchOffset, mMaxTouchOffset; 3483 3484 // Double tap detection 3485 private long mPreviousTapUpTime = 0; 3486 private float mDownPositionX, mDownPositionY; 3487 private boolean mGestureStayedInTapRegion; 3488 3489 SelectionModifierCursorController() { 3490 resetTouchOffsets(); 3491 } 3492 3493 public void show() { 3494 if (mTextView.isInBatchEditMode()) { 3495 return; 3496 } 3497 initDrawables(); 3498 initHandles(); 3499 hideInsertionPointCursorController(); 3500 } 3501 3502 private void initDrawables() { 3503 if (mSelectHandleLeft == null) { 3504 mSelectHandleLeft = mTextView.getContext().getResources().getDrawable( 3505 mTextView.mTextSelectHandleLeftRes); 3506 } 3507 if (mSelectHandleRight == null) { 3508 mSelectHandleRight = mTextView.getContext().getResources().getDrawable( 3509 mTextView.mTextSelectHandleRightRes); 3510 } 3511 } 3512 3513 private void initHandles() { 3514 // Lazy object creation has to be done before updatePosition() is called. 3515 if (mStartHandle == null) { 3516 mStartHandle = new SelectionStartHandleView(mSelectHandleLeft, mSelectHandleRight); 3517 } 3518 if (mEndHandle == null) { 3519 mEndHandle = new SelectionEndHandleView(mSelectHandleRight, mSelectHandleLeft); 3520 } 3521 3522 mStartHandle.show(); 3523 mEndHandle.show(); 3524 3525 // Make sure both left and right handles share the same ActionPopupWindow (so that 3526 // moving any of the handles hides the action popup). 3527 mStartHandle.showActionPopupWindow(DELAY_BEFORE_REPLACE_ACTION); 3528 mEndHandle.setActionPopupWindow(mStartHandle.getActionPopupWindow()); 3529 3530 hideInsertionPointCursorController(); 3531 } 3532 3533 public void hide() { 3534 if (mStartHandle != null) mStartHandle.hide(); 3535 if (mEndHandle != null) mEndHandle.hide(); 3536 } 3537 3538 public void onTouchEvent(MotionEvent event) { 3539 // This is done even when the View does not have focus, so that long presses can start 3540 // selection and tap can move cursor from this tap position. 3541 switch (event.getActionMasked()) { 3542 case MotionEvent.ACTION_DOWN: 3543 final float x = event.getX(); 3544 final float y = event.getY(); 3545 3546 // Remember finger down position, to be able to start selection from there 3547 mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(x, y); 3548 3549 // Double tap detection 3550 if (mGestureStayedInTapRegion) { 3551 long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime; 3552 if (duration <= ViewConfiguration.getDoubleTapTimeout()) { 3553 final float deltaX = x - mDownPositionX; 3554 final float deltaY = y - mDownPositionY; 3555 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 3556 3557 ViewConfiguration viewConfiguration = ViewConfiguration.get( 3558 mTextView.getContext()); 3559 int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop(); 3560 boolean stayedInArea = distanceSquared < doubleTapSlop * doubleTapSlop; 3561 3562 if (stayedInArea && isPositionOnText(x, y)) { 3563 startSelectionActionMode(); 3564 mDiscardNextActionUp = true; 3565 } 3566 } 3567 } 3568 3569 mDownPositionX = x; 3570 mDownPositionY = y; 3571 mGestureStayedInTapRegion = true; 3572 break; 3573 3574 case MotionEvent.ACTION_POINTER_DOWN: 3575 case MotionEvent.ACTION_POINTER_UP: 3576 // Handle multi-point gestures. Keep min and max offset positions. 3577 // Only activated for devices that correctly handle multi-touch. 3578 if (mTextView.getContext().getPackageManager().hasSystemFeature( 3579 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) { 3580 updateMinAndMaxOffsets(event); 3581 } 3582 break; 3583 3584 case MotionEvent.ACTION_MOVE: 3585 if (mGestureStayedInTapRegion) { 3586 final float deltaX = event.getX() - mDownPositionX; 3587 final float deltaY = event.getY() - mDownPositionY; 3588 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 3589 3590 final ViewConfiguration viewConfiguration = ViewConfiguration.get( 3591 mTextView.getContext()); 3592 int doubleTapTouchSlop = viewConfiguration.getScaledDoubleTapTouchSlop(); 3593 3594 if (distanceSquared > doubleTapTouchSlop * doubleTapTouchSlop) { 3595 mGestureStayedInTapRegion = false; 3596 } 3597 } 3598 break; 3599 3600 case MotionEvent.ACTION_UP: 3601 mPreviousTapUpTime = SystemClock.uptimeMillis(); 3602 break; 3603 } 3604 } 3605 3606 /** 3607 * @param event 3608 */ 3609 private void updateMinAndMaxOffsets(MotionEvent event) { 3610 int pointerCount = event.getPointerCount(); 3611 for (int index = 0; index < pointerCount; index++) { 3612 int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index)); 3613 if (offset < mMinTouchOffset) mMinTouchOffset = offset; 3614 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset; 3615 } 3616 } 3617 3618 public int getMinTouchOffset() { 3619 return mMinTouchOffset; 3620 } 3621 3622 public int getMaxTouchOffset() { 3623 return mMaxTouchOffset; 3624 } 3625 3626 public void resetTouchOffsets() { 3627 mMinTouchOffset = mMaxTouchOffset = -1; 3628 } 3629 3630 /** 3631 * @return true iff this controller is currently used to move the selection start. 3632 */ 3633 public boolean isSelectionStartDragged() { 3634 return mStartHandle != null && mStartHandle.isDragging(); 3635 } 3636 3637 public void onTouchModeChanged(boolean isInTouchMode) { 3638 if (!isInTouchMode) { 3639 hide(); 3640 } 3641 } 3642 3643 @Override 3644 public void onDetached() { 3645 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 3646 observer.removeOnTouchModeChangeListener(this); 3647 3648 if (mStartHandle != null) mStartHandle.onDetached(); 3649 if (mEndHandle != null) mEndHandle.onDetached(); 3650 } 3651 } 3652 3653 private class CorrectionHighlighter { 3654 private final Path mPath = new Path(); 3655 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 3656 private int mStart, mEnd; 3657 private long mFadingStartTime; 3658 private RectF mTempRectF; 3659 private final static int FADE_OUT_DURATION = 400; 3660 3661 public CorrectionHighlighter() { 3662 mPaint.setCompatibilityScaling(mTextView.getResources().getCompatibilityInfo(). 3663 applicationScale); 3664 mPaint.setStyle(Paint.Style.FILL); 3665 } 3666 3667 public void highlight(CorrectionInfo info) { 3668 mStart = info.getOffset(); 3669 mEnd = mStart + info.getNewText().length(); 3670 mFadingStartTime = SystemClock.uptimeMillis(); 3671 3672 if (mStart < 0 || mEnd < 0) { 3673 stopAnimation(); 3674 } 3675 } 3676 3677 public void draw(Canvas canvas, int cursorOffsetVertical) { 3678 if (updatePath() && updatePaint()) { 3679 if (cursorOffsetVertical != 0) { 3680 canvas.translate(0, cursorOffsetVertical); 3681 } 3682 3683 canvas.drawPath(mPath, mPaint); 3684 3685 if (cursorOffsetVertical != 0) { 3686 canvas.translate(0, -cursorOffsetVertical); 3687 } 3688 invalidate(true); // TODO invalidate cursor region only 3689 } else { 3690 stopAnimation(); 3691 invalidate(false); // TODO invalidate cursor region only 3692 } 3693 } 3694 3695 private boolean updatePaint() { 3696 final long duration = SystemClock.uptimeMillis() - mFadingStartTime; 3697 if (duration > FADE_OUT_DURATION) return false; 3698 3699 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION; 3700 final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor); 3701 final int color = (mTextView.mHighlightColor & 0x00FFFFFF) + 3702 ((int) (highlightColorAlpha * coef) << 24); 3703 mPaint.setColor(color); 3704 return true; 3705 } 3706 3707 private boolean updatePath() { 3708 final Layout layout = mTextView.getLayout(); 3709 if (layout == null) return false; 3710 3711 // Update in case text is edited while the animation is run 3712 final int length = mTextView.getText().length(); 3713 int start = Math.min(length, mStart); 3714 int end = Math.min(length, mEnd); 3715 3716 mPath.reset(); 3717 layout.getSelectionPath(start, end, mPath); 3718 return true; 3719 } 3720 3721 private void invalidate(boolean delayed) { 3722 if (mTextView.getLayout() == null) return; 3723 3724 if (mTempRectF == null) mTempRectF = new RectF(); 3725 mPath.computeBounds(mTempRectF, false); 3726 3727 int left = mTextView.getCompoundPaddingLeft(); 3728 int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true); 3729 3730 if (delayed) { 3731 mTextView.postInvalidateOnAnimation( 3732 left + (int) mTempRectF.left, top + (int) mTempRectF.top, 3733 left + (int) mTempRectF.right, top + (int) mTempRectF.bottom); 3734 } else { 3735 mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top, 3736 (int) mTempRectF.right, (int) mTempRectF.bottom); 3737 } 3738 } 3739 3740 private void stopAnimation() { 3741 Editor.this.mCorrectionHighlighter = null; 3742 } 3743 } 3744 3745 private static class ErrorPopup extends PopupWindow { 3746 private boolean mAbove = false; 3747 private final TextView mView; 3748 private int mPopupInlineErrorBackgroundId = 0; 3749 private int mPopupInlineErrorAboveBackgroundId = 0; 3750 3751 ErrorPopup(TextView v, int width, int height) { 3752 super(v, width, height); 3753 mView = v; 3754 // Make sure the TextView has a background set as it will be used the first time it is 3755 // shown and positioned. Initialized with below background, which should have 3756 // dimensions identical to the above version for this to work (and is more likely). 3757 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 3758 com.android.internal.R.styleable.Theme_errorMessageBackground); 3759 mView.setBackgroundResource(mPopupInlineErrorBackgroundId); 3760 } 3761 3762 void fixDirection(boolean above) { 3763 mAbove = above; 3764 3765 if (above) { 3766 mPopupInlineErrorAboveBackgroundId = 3767 getResourceId(mPopupInlineErrorAboveBackgroundId, 3768 com.android.internal.R.styleable.Theme_errorMessageAboveBackground); 3769 } else { 3770 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 3771 com.android.internal.R.styleable.Theme_errorMessageBackground); 3772 } 3773 3774 mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId : 3775 mPopupInlineErrorBackgroundId); 3776 } 3777 3778 private int getResourceId(int currentId, int index) { 3779 if (currentId == 0) { 3780 TypedArray styledAttributes = mView.getContext().obtainStyledAttributes( 3781 R.styleable.Theme); 3782 currentId = styledAttributes.getResourceId(index, 0); 3783 styledAttributes.recycle(); 3784 } 3785 return currentId; 3786 } 3787 3788 @Override 3789 public void update(int x, int y, int w, int h, boolean force) { 3790 super.update(x, y, w, h, force); 3791 3792 boolean above = isAboveAnchor(); 3793 if (above != mAbove) { 3794 fixDirection(above); 3795 } 3796 } 3797 } 3798 3799 static class InputContentType { 3800 int imeOptions = EditorInfo.IME_NULL; 3801 String privateImeOptions; 3802 CharSequence imeActionLabel; 3803 int imeActionId; 3804 Bundle extras; 3805 OnEditorActionListener onEditorActionListener; 3806 boolean enterDown; 3807 } 3808 3809 static class InputMethodState { 3810 Rect mCursorRectInWindow = new Rect(); 3811 RectF mTmpRectF = new RectF(); 3812 float[] mTmpOffset = new float[2]; 3813 ExtractedTextRequest mExtractedTextRequest; 3814 final ExtractedText mExtractedText = new ExtractedText(); 3815 int mBatchEditNesting; 3816 boolean mCursorChanged; 3817 boolean mSelectionModeChanged; 3818 boolean mContentChanged; 3819 int mChangedStart, mChangedEnd, mChangedDelta; 3820 } 3821 3822 /** 3823 * @hide 3824 */ 3825 public static class UserDictionaryListener extends Handler { 3826 public TextView mTextView; 3827 public String mOriginalWord; 3828 public int mWordStart; 3829 public int mWordEnd; 3830 3831 public void waitForUserDictionaryAdded( 3832 TextView tv, String originalWord, int spanStart, int spanEnd) { 3833 mTextView = tv; 3834 mOriginalWord = originalWord; 3835 mWordStart = spanStart; 3836 mWordEnd = spanEnd; 3837 } 3838 3839 @Override 3840 public void handleMessage(Message msg) { 3841 switch(msg.what) { 3842 case 0: /* CODE_WORD_ADDED */ 3843 case 2: /* CODE_ALREADY_PRESENT */ 3844 if (!(msg.obj instanceof Bundle)) { 3845 Log.w(TAG, "Illegal message. Abort handling onUserDictionaryAdded."); 3846 return; 3847 } 3848 final Bundle bundle = (Bundle)msg.obj; 3849 final String originalWord = bundle.getString("originalWord"); 3850 final String addedWord = bundle.getString("word"); 3851 onUserDictionaryAdded(originalWord, addedWord); 3852 return; 3853 default: 3854 return; 3855 } 3856 } 3857 3858 private void onUserDictionaryAdded(String originalWord, String addedWord) { 3859 if (TextUtils.isEmpty(mOriginalWord) || TextUtils.isEmpty(addedWord)) { 3860 return; 3861 } 3862 if (mWordStart < 0 || mWordEnd >= mTextView.length()) { 3863 return; 3864 } 3865 if (!mOriginalWord.equals(originalWord)) { 3866 return; 3867 } 3868 if (originalWord.equals(addedWord)) { 3869 return; 3870 } 3871 final Editable editable = (Editable) mTextView.getText(); 3872 final String currentWord = editable.toString().substring(mWordStart, mWordEnd); 3873 if (!currentWord.equals(originalWord)) { 3874 return; 3875 } 3876 mTextView.replaceText_internal(mWordStart, mWordEnd, addedWord); 3877 // Move cursor at the end of the replaced word 3878 final int newCursorPosition = mWordStart + addedWord.length(); 3879 mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition); 3880 } 3881 } 3882} 3883