Editor.java revision 1b916301e044d1f6f672c9708c993090ecdf30cf
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.clear(); 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 right - left, bottom - top); 1342 try { 1343 // drawText is always relative to TextView's origin, this translation 1344 // brings this range of text back to the top left corner of the viewport 1345 hardwareCanvas.translate(-left, -top); 1346 layout.drawText(hardwareCanvas, blockBeginLine, blockEndLine); 1347 // No need to untranslate, previous context is popped after 1348 // drawDisplayList 1349 } finally { 1350 blockDisplayList.end(); 1351 // Same as drawDisplayList below, handled by our TextView's parent 1352 blockDisplayList.setClipChildren(false); 1353 } 1354 } 1355 1356 // Valid disply list whose index is >= indexFirstChangedBlock 1357 // only needs to update its drawing location. 1358 blockDisplayList.setLeftTopRightBottom(left, top, right, bottom); 1359 } 1360 1361 ((HardwareCanvas) canvas).drawDisplayList(blockDisplayList, null, 1362 0 /* no child clipping, our TextView parent enforces it */); 1363 1364 endOfPreviousBlock = blockEndLine; 1365 } 1366 1367 dynamicLayout.setIndexFirstChangedBlock(numberOfBlocks); 1368 } else { 1369 // Boring layout is used for empty and hint text 1370 layout.drawText(canvas, firstLine, lastLine); 1371 } 1372 } 1373 1374 private int getAvailableDisplayListIndex(int[] blockIndices, int numberOfBlocks, 1375 int searchStartIndex) { 1376 int length = mTextDisplayLists.length; 1377 for (int i = searchStartIndex; i < length; i++) { 1378 boolean blockIndexFound = false; 1379 for (int j = 0; j < numberOfBlocks; j++) { 1380 if (blockIndices[j] == i) { 1381 blockIndexFound = true; 1382 break; 1383 } 1384 } 1385 if (blockIndexFound) continue; 1386 return i; 1387 } 1388 1389 // No available index found, the pool has to grow 1390 int newSize = ArrayUtils.idealIntArraySize(length + 1); 1391 DisplayList[] displayLists = new DisplayList[newSize]; 1392 System.arraycopy(mTextDisplayLists, 0, displayLists, 0, length); 1393 mTextDisplayLists = displayLists; 1394 return length; 1395 } 1396 1397 private void drawCursor(Canvas canvas, int cursorOffsetVertical) { 1398 final boolean translate = cursorOffsetVertical != 0; 1399 if (translate) canvas.translate(0, cursorOffsetVertical); 1400 for (int i = 0; i < mCursorCount; i++) { 1401 mCursorDrawable[i].draw(canvas); 1402 } 1403 if (translate) canvas.translate(0, -cursorOffsetVertical); 1404 } 1405 1406 /** 1407 * Invalidates all the sub-display lists that overlap the specified character range 1408 */ 1409 void invalidateTextDisplayList(Layout layout, int start, int end) { 1410 if (mTextDisplayLists != null && layout instanceof DynamicLayout) { 1411 final int firstLine = layout.getLineForOffset(start); 1412 final int lastLine = layout.getLineForOffset(end); 1413 1414 DynamicLayout dynamicLayout = (DynamicLayout) layout; 1415 int[] blockEndLines = dynamicLayout.getBlockEndLines(); 1416 int[] blockIndices = dynamicLayout.getBlockIndices(); 1417 final int numberOfBlocks = dynamicLayout.getNumberOfBlocks(); 1418 1419 int i = 0; 1420 // Skip the blocks before firstLine 1421 while (i < numberOfBlocks) { 1422 if (blockEndLines[i] >= firstLine) break; 1423 i++; 1424 } 1425 1426 // Invalidate all subsequent blocks until lastLine is passed 1427 while (i < numberOfBlocks) { 1428 final int blockIndex = blockIndices[i]; 1429 if (blockIndex != DynamicLayout.INVALID_BLOCK_INDEX) { 1430 mTextDisplayLists[blockIndex].clear(); 1431 } 1432 if (blockEndLines[i] >= lastLine) break; 1433 i++; 1434 } 1435 } 1436 } 1437 1438 void invalidateTextDisplayList() { 1439 if (mTextDisplayLists != null) { 1440 for (int i = 0; i < mTextDisplayLists.length; i++) { 1441 if (mTextDisplayLists[i] != null) mTextDisplayLists[i].clear(); 1442 } 1443 } 1444 } 1445 1446 void updateCursorsPositions() { 1447 if (mTextView.mCursorDrawableRes == 0) { 1448 mCursorCount = 0; 1449 return; 1450 } 1451 1452 Layout layout = mTextView.getLayout(); 1453 Layout hintLayout = mTextView.getHintLayout(); 1454 final int offset = mTextView.getSelectionStart(); 1455 final int line = layout.getLineForOffset(offset); 1456 final int top = layout.getLineTop(line); 1457 final int bottom = layout.getLineTop(line + 1); 1458 1459 mCursorCount = layout.isLevelBoundary(offset) ? 2 : 1; 1460 1461 int middle = bottom; 1462 if (mCursorCount == 2) { 1463 // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)} 1464 middle = (top + bottom) >> 1; 1465 } 1466 1467 boolean clamped = layout.shouldClampCursor(line); 1468 updateCursorPosition(0, top, middle, 1469 getPrimaryHorizontal(layout, hintLayout, offset, clamped)); 1470 1471 if (mCursorCount == 2) { 1472 updateCursorPosition(1, middle, bottom, 1473 layout.getSecondaryHorizontal(offset, clamped)); 1474 } 1475 } 1476 1477 private float getPrimaryHorizontal(Layout layout, Layout hintLayout, int offset, 1478 boolean clamped) { 1479 if (TextUtils.isEmpty(layout.getText()) && 1480 hintLayout != null && 1481 !TextUtils.isEmpty(hintLayout.getText())) { 1482 return hintLayout.getPrimaryHorizontal(offset, clamped); 1483 } else { 1484 return layout.getPrimaryHorizontal(offset, clamped); 1485 } 1486 } 1487 1488 /** 1489 * @return true if the selection mode was actually started. 1490 */ 1491 boolean startSelectionActionMode() { 1492 if (mSelectionActionMode != null) { 1493 // Selection action mode is already started 1494 return false; 1495 } 1496 1497 if (!canSelectText() || !mTextView.requestFocus()) { 1498 Log.w(TextView.LOG_TAG, 1499 "TextView does not support text selection. Action mode cancelled."); 1500 return false; 1501 } 1502 1503 if (!mTextView.hasSelection()) { 1504 // There may already be a selection on device rotation 1505 if (!selectCurrentWord()) { 1506 // No word found under cursor or text selection not permitted. 1507 return false; 1508 } 1509 } 1510 1511 boolean willExtract = extractedTextModeWillBeStarted(); 1512 1513 // Do not start the action mode when extracted text will show up full screen, which would 1514 // immediately hide the newly created action bar and would be visually distracting. 1515 if (!willExtract) { 1516 ActionMode.Callback actionModeCallback = new SelectionActionModeCallback(); 1517 mSelectionActionMode = mTextView.startActionMode(actionModeCallback); 1518 } 1519 1520 final boolean selectionStarted = mSelectionActionMode != null || willExtract; 1521 if (selectionStarted && !mTextView.isTextSelectable() && mShowSoftInputOnFocus) { 1522 // Show the IME to be able to replace text, except when selecting non editable text. 1523 final InputMethodManager imm = InputMethodManager.peekInstance(); 1524 if (imm != null) { 1525 imm.showSoftInput(mTextView, 0, null); 1526 } 1527 } 1528 1529 return selectionStarted; 1530 } 1531 1532 private boolean extractedTextModeWillBeStarted() { 1533 if (!(mTextView instanceof ExtractEditText)) { 1534 final InputMethodManager imm = InputMethodManager.peekInstance(); 1535 return imm != null && imm.isFullscreenMode(); 1536 } 1537 return false; 1538 } 1539 1540 /** 1541 * @return <code>true</code> if the cursor/current selection overlaps a {@link SuggestionSpan}. 1542 */ 1543 private boolean isCursorInsideSuggestionSpan() { 1544 CharSequence text = mTextView.getText(); 1545 if (!(text instanceof Spannable)) return false; 1546 1547 SuggestionSpan[] suggestionSpans = ((Spannable) text).getSpans( 1548 mTextView.getSelectionStart(), mTextView.getSelectionEnd(), SuggestionSpan.class); 1549 return (suggestionSpans.length > 0); 1550 } 1551 1552 /** 1553 * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with 1554 * {@link SuggestionSpan#FLAG_EASY_CORRECT} set. 1555 */ 1556 private boolean isCursorInsideEasyCorrectionSpan() { 1557 Spannable spannable = (Spannable) mTextView.getText(); 1558 SuggestionSpan[] suggestionSpans = spannable.getSpans(mTextView.getSelectionStart(), 1559 mTextView.getSelectionEnd(), SuggestionSpan.class); 1560 for (int i = 0; i < suggestionSpans.length; i++) { 1561 if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) { 1562 return true; 1563 } 1564 } 1565 return false; 1566 } 1567 1568 void onTouchUpEvent(MotionEvent event) { 1569 boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect(); 1570 hideControllers(); 1571 CharSequence text = mTextView.getText(); 1572 if (!selectAllGotFocus && text.length() > 0) { 1573 // Move cursor 1574 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY()); 1575 Selection.setSelection((Spannable) text, offset); 1576 if (mSpellChecker != null) { 1577 // When the cursor moves, the word that was typed may need spell check 1578 mSpellChecker.onSelectionChanged(); 1579 } 1580 if (!extractedTextModeWillBeStarted()) { 1581 if (isCursorInsideEasyCorrectionSpan()) { 1582 mShowSuggestionRunnable = new Runnable() { 1583 public void run() { 1584 showSuggestions(); 1585 } 1586 }; 1587 // removeCallbacks is performed on every touch 1588 mTextView.postDelayed(mShowSuggestionRunnable, 1589 ViewConfiguration.getDoubleTapTimeout()); 1590 } else if (hasInsertionController()) { 1591 getInsertionController().show(); 1592 } 1593 } 1594 } 1595 } 1596 1597 protected void stopSelectionActionMode() { 1598 if (mSelectionActionMode != null) { 1599 // This will hide the mSelectionModifierCursorController 1600 mSelectionActionMode.finish(); 1601 } 1602 } 1603 1604 /** 1605 * @return True if this view supports insertion handles. 1606 */ 1607 boolean hasInsertionController() { 1608 return mInsertionControllerEnabled; 1609 } 1610 1611 /** 1612 * @return True if this view supports selection handles. 1613 */ 1614 boolean hasSelectionController() { 1615 return mSelectionControllerEnabled; 1616 } 1617 1618 InsertionPointCursorController getInsertionController() { 1619 if (!mInsertionControllerEnabled) { 1620 return null; 1621 } 1622 1623 if (mInsertionPointCursorController == null) { 1624 mInsertionPointCursorController = new InsertionPointCursorController(); 1625 1626 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 1627 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 1628 } 1629 1630 return mInsertionPointCursorController; 1631 } 1632 1633 SelectionModifierCursorController getSelectionController() { 1634 if (!mSelectionControllerEnabled) { 1635 return null; 1636 } 1637 1638 if (mSelectionModifierCursorController == null) { 1639 mSelectionModifierCursorController = new SelectionModifierCursorController(); 1640 1641 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 1642 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 1643 } 1644 1645 return mSelectionModifierCursorController; 1646 } 1647 1648 private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) { 1649 if (mCursorDrawable[cursorIndex] == null) 1650 mCursorDrawable[cursorIndex] = mTextView.getResources().getDrawable( 1651 mTextView.mCursorDrawableRes); 1652 1653 if (mTempRect == null) mTempRect = new Rect(); 1654 mCursorDrawable[cursorIndex].getPadding(mTempRect); 1655 final int width = mCursorDrawable[cursorIndex].getIntrinsicWidth(); 1656 horizontal = Math.max(0.5f, horizontal - 0.5f); 1657 final int left = (int) (horizontal) - mTempRect.left; 1658 mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width, 1659 bottom + mTempRect.bottom); 1660 } 1661 1662 /** 1663 * Called by the framework in response to a text auto-correction (such as fixing a typo using a 1664 * a dictionnary) from the current input method, provided by it calling 1665 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default 1666 * implementation flashes the background of the corrected word to provide feedback to the user. 1667 * 1668 * @param info The auto correct info about the text that was corrected. 1669 */ 1670 public void onCommitCorrection(CorrectionInfo info) { 1671 if (mCorrectionHighlighter == null) { 1672 mCorrectionHighlighter = new CorrectionHighlighter(); 1673 } else { 1674 mCorrectionHighlighter.invalidate(false); 1675 } 1676 1677 mCorrectionHighlighter.highlight(info); 1678 } 1679 1680 void showSuggestions() { 1681 if (mSuggestionsPopupWindow == null) { 1682 mSuggestionsPopupWindow = new SuggestionsPopupWindow(); 1683 } 1684 hideControllers(); 1685 mSuggestionsPopupWindow.show(); 1686 } 1687 1688 boolean areSuggestionsShown() { 1689 return mSuggestionsPopupWindow != null && mSuggestionsPopupWindow.isShowing(); 1690 } 1691 1692 void onScrollChanged() { 1693 if (mPositionListener != null) { 1694 mPositionListener.onScrollChanged(); 1695 } 1696 } 1697 1698 /** 1699 * @return True when the TextView isFocused and has a valid zero-length selection (cursor). 1700 */ 1701 private boolean shouldBlink() { 1702 if (!isCursorVisible() || !mTextView.isFocused()) return false; 1703 1704 final int start = mTextView.getSelectionStart(); 1705 if (start < 0) return false; 1706 1707 final int end = mTextView.getSelectionEnd(); 1708 if (end < 0) return false; 1709 1710 return start == end; 1711 } 1712 1713 void makeBlink() { 1714 if (shouldBlink()) { 1715 mShowCursor = SystemClock.uptimeMillis(); 1716 if (mBlink == null) mBlink = new Blink(); 1717 mBlink.removeCallbacks(mBlink); 1718 mBlink.postAtTime(mBlink, mShowCursor + BLINK); 1719 } else { 1720 if (mBlink != null) mBlink.removeCallbacks(mBlink); 1721 } 1722 } 1723 1724 private class Blink extends Handler implements Runnable { 1725 private boolean mCancelled; 1726 1727 public void run() { 1728 if (mCancelled) { 1729 return; 1730 } 1731 1732 removeCallbacks(Blink.this); 1733 1734 if (shouldBlink()) { 1735 if (mTextView.getLayout() != null) { 1736 mTextView.invalidateCursorPath(); 1737 } 1738 1739 postAtTime(this, SystemClock.uptimeMillis() + BLINK); 1740 } 1741 } 1742 1743 void cancel() { 1744 if (!mCancelled) { 1745 removeCallbacks(Blink.this); 1746 mCancelled = true; 1747 } 1748 } 1749 1750 void uncancel() { 1751 mCancelled = false; 1752 } 1753 } 1754 1755 private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) { 1756 TextView shadowView = (TextView) View.inflate(mTextView.getContext(), 1757 com.android.internal.R.layout.text_drag_thumbnail, null); 1758 1759 if (shadowView == null) { 1760 throw new IllegalArgumentException("Unable to inflate text drag thumbnail"); 1761 } 1762 1763 if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) { 1764 text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH); 1765 } 1766 shadowView.setText(text); 1767 shadowView.setTextColor(mTextView.getTextColors()); 1768 1769 shadowView.setTextAppearance(mTextView.getContext(), R.styleable.Theme_textAppearanceLarge); 1770 shadowView.setGravity(Gravity.CENTER); 1771 1772 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 1773 ViewGroup.LayoutParams.WRAP_CONTENT)); 1774 1775 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 1776 shadowView.measure(size, size); 1777 1778 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight()); 1779 shadowView.invalidate(); 1780 return new DragShadowBuilder(shadowView); 1781 } 1782 1783 private static class DragLocalState { 1784 public TextView sourceTextView; 1785 public int start, end; 1786 1787 public DragLocalState(TextView sourceTextView, int start, int end) { 1788 this.sourceTextView = sourceTextView; 1789 this.start = start; 1790 this.end = end; 1791 } 1792 } 1793 1794 void onDrop(DragEvent event) { 1795 StringBuilder content = new StringBuilder(""); 1796 ClipData clipData = event.getClipData(); 1797 final int itemCount = clipData.getItemCount(); 1798 for (int i=0; i < itemCount; i++) { 1799 Item item = clipData.getItemAt(i); 1800 content.append(item.coerceToStyledText(mTextView.getContext())); 1801 } 1802 1803 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY()); 1804 1805 Object localState = event.getLocalState(); 1806 DragLocalState dragLocalState = null; 1807 if (localState instanceof DragLocalState) { 1808 dragLocalState = (DragLocalState) localState; 1809 } 1810 boolean dragDropIntoItself = dragLocalState != null && 1811 dragLocalState.sourceTextView == mTextView; 1812 1813 if (dragDropIntoItself) { 1814 if (offset >= dragLocalState.start && offset < dragLocalState.end) { 1815 // A drop inside the original selection discards the drop. 1816 return; 1817 } 1818 } 1819 1820 final int originalLength = mTextView.getText().length(); 1821 long minMax = mTextView.prepareSpacesAroundPaste(offset, offset, content); 1822 int min = TextUtils.unpackRangeStartFromLong(minMax); 1823 int max = TextUtils.unpackRangeEndFromLong(minMax); 1824 1825 Selection.setSelection((Spannable) mTextView.getText(), max); 1826 mTextView.replaceText_internal(min, max, content); 1827 1828 if (dragDropIntoItself) { 1829 int dragSourceStart = dragLocalState.start; 1830 int dragSourceEnd = dragLocalState.end; 1831 if (max <= dragSourceStart) { 1832 // Inserting text before selection has shifted positions 1833 final int shift = mTextView.getText().length() - originalLength; 1834 dragSourceStart += shift; 1835 dragSourceEnd += shift; 1836 } 1837 1838 // Delete original selection 1839 mTextView.deleteText_internal(dragSourceStart, dragSourceEnd); 1840 1841 // Make sure we do not leave two adjacent spaces. 1842 final int prevCharIdx = Math.max(0, dragSourceStart - 1); 1843 final int nextCharIdx = Math.min(mTextView.getText().length(), dragSourceStart + 1); 1844 if (nextCharIdx > prevCharIdx + 1) { 1845 CharSequence t = mTextView.getTransformedText(prevCharIdx, nextCharIdx); 1846 if (Character.isSpaceChar(t.charAt(0)) && Character.isSpaceChar(t.charAt(1))) { 1847 mTextView.deleteText_internal(prevCharIdx, prevCharIdx + 1); 1848 } 1849 } 1850 } 1851 } 1852 1853 public void addSpanWatchers(Spannable text) { 1854 final int textLength = text.length(); 1855 1856 if (mKeyListener != null) { 1857 text.setSpan(mKeyListener, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 1858 } 1859 1860 if (mEasyEditSpanController == null) { 1861 mEasyEditSpanController = new EasyEditSpanController(); 1862 } 1863 text.setSpan(mEasyEditSpanController, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 1864 } 1865 1866 /** 1867 * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related 1868 * pop-up should be displayed. 1869 */ 1870 class EasyEditSpanController implements SpanWatcher { 1871 1872 private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs 1873 1874 private EasyEditPopupWindow mPopupWindow; 1875 1876 private Runnable mHidePopup; 1877 1878 @Override 1879 public void onSpanAdded(Spannable text, Object span, int start, int end) { 1880 if (span instanceof EasyEditSpan) { 1881 if (mPopupWindow == null) { 1882 mPopupWindow = new EasyEditPopupWindow(); 1883 mHidePopup = new Runnable() { 1884 @Override 1885 public void run() { 1886 hide(); 1887 } 1888 }; 1889 } 1890 1891 // Make sure there is only at most one EasyEditSpan in the text 1892 if (mPopupWindow.mEasyEditSpan != null) { 1893 text.removeSpan(mPopupWindow.mEasyEditSpan); 1894 } 1895 1896 mPopupWindow.setEasyEditSpan((EasyEditSpan) span); 1897 1898 if (mTextView.getWindowVisibility() != View.VISIBLE) { 1899 // The window is not visible yet, ignore the text change. 1900 return; 1901 } 1902 1903 if (mTextView.getLayout() == null) { 1904 // The view has not been laid out yet, ignore the text change 1905 return; 1906 } 1907 1908 if (extractedTextModeWillBeStarted()) { 1909 // The input is in extract mode. Do not handle the easy edit in 1910 // the original TextView, as the ExtractEditText will do 1911 return; 1912 } 1913 1914 mPopupWindow.show(); 1915 mTextView.removeCallbacks(mHidePopup); 1916 mTextView.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS); 1917 } 1918 } 1919 1920 @Override 1921 public void onSpanRemoved(Spannable text, Object span, int start, int end) { 1922 if (mPopupWindow != null && span == mPopupWindow.mEasyEditSpan) { 1923 hide(); 1924 } 1925 } 1926 1927 @Override 1928 public void onSpanChanged(Spannable text, Object span, int previousStart, int previousEnd, 1929 int newStart, int newEnd) { 1930 if (mPopupWindow != null && span == mPopupWindow.mEasyEditSpan) { 1931 text.removeSpan(mPopupWindow.mEasyEditSpan); 1932 } 1933 } 1934 1935 public void hide() { 1936 if (mPopupWindow != null) { 1937 mPopupWindow.hide(); 1938 mTextView.removeCallbacks(mHidePopup); 1939 } 1940 } 1941 } 1942 1943 /** 1944 * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled 1945 * by {@link EasyEditSpanController}. 1946 */ 1947 private class EasyEditPopupWindow extends PinnedPopupWindow 1948 implements OnClickListener { 1949 private static final int POPUP_TEXT_LAYOUT = 1950 com.android.internal.R.layout.text_edit_action_popup_text; 1951 private TextView mDeleteTextView; 1952 private EasyEditSpan mEasyEditSpan; 1953 1954 @Override 1955 protected void createPopupWindow() { 1956 mPopupWindow = new PopupWindow(mTextView.getContext(), null, 1957 com.android.internal.R.attr.textSelectHandleWindowStyle); 1958 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 1959 mPopupWindow.setClippingEnabled(true); 1960 } 1961 1962 @Override 1963 protected void initContentView() { 1964 LinearLayout linearLayout = new LinearLayout(mTextView.getContext()); 1965 linearLayout.setOrientation(LinearLayout.HORIZONTAL); 1966 mContentView = linearLayout; 1967 mContentView.setBackgroundResource( 1968 com.android.internal.R.drawable.text_edit_side_paste_window); 1969 1970 LayoutInflater inflater = (LayoutInflater)mTextView.getContext(). 1971 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 1972 1973 LayoutParams wrapContent = new LayoutParams( 1974 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 1975 1976 mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 1977 mDeleteTextView.setLayoutParams(wrapContent); 1978 mDeleteTextView.setText(com.android.internal.R.string.delete); 1979 mDeleteTextView.setOnClickListener(this); 1980 mContentView.addView(mDeleteTextView); 1981 } 1982 1983 public void setEasyEditSpan(EasyEditSpan easyEditSpan) { 1984 mEasyEditSpan = easyEditSpan; 1985 } 1986 1987 @Override 1988 public void onClick(View view) { 1989 if (view == mDeleteTextView) { 1990 Editable editable = (Editable) mTextView.getText(); 1991 int start = editable.getSpanStart(mEasyEditSpan); 1992 int end = editable.getSpanEnd(mEasyEditSpan); 1993 if (start >= 0 && end >= 0) { 1994 mTextView.deleteText_internal(start, end); 1995 } 1996 } 1997 } 1998 1999 @Override 2000 protected int getTextOffset() { 2001 // Place the pop-up at the end of the span 2002 Editable editable = (Editable) mTextView.getText(); 2003 return editable.getSpanEnd(mEasyEditSpan); 2004 } 2005 2006 @Override 2007 protected int getVerticalLocalPosition(int line) { 2008 return mTextView.getLayout().getLineBottom(line); 2009 } 2010 2011 @Override 2012 protected int clipVertically(int positionY) { 2013 // As we display the pop-up below the span, no vertical clipping is required. 2014 return positionY; 2015 } 2016 } 2017 2018 private class PositionListener implements ViewTreeObserver.OnPreDrawListener { 2019 // 3 handles 2020 // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others) 2021 private final int MAXIMUM_NUMBER_OF_LISTENERS = 6; 2022 private TextViewPositionListener[] mPositionListeners = 2023 new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS]; 2024 private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS]; 2025 private boolean mPositionHasChanged = true; 2026 // Absolute position of the TextView with respect to its parent window 2027 private int mPositionX, mPositionY; 2028 private int mNumberOfListeners; 2029 private boolean mScrollHasChanged; 2030 final int[] mTempCoords = new int[2]; 2031 2032 public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) { 2033 if (mNumberOfListeners == 0) { 2034 updatePosition(); 2035 ViewTreeObserver vto = mTextView.getViewTreeObserver(); 2036 vto.addOnPreDrawListener(this); 2037 } 2038 2039 int emptySlotIndex = -1; 2040 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 2041 TextViewPositionListener listener = mPositionListeners[i]; 2042 if (listener == positionListener) { 2043 return; 2044 } else if (emptySlotIndex < 0 && listener == null) { 2045 emptySlotIndex = i; 2046 } 2047 } 2048 2049 mPositionListeners[emptySlotIndex] = positionListener; 2050 mCanMove[emptySlotIndex] = canMove; 2051 mNumberOfListeners++; 2052 } 2053 2054 public void removeSubscriber(TextViewPositionListener positionListener) { 2055 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 2056 if (mPositionListeners[i] == positionListener) { 2057 mPositionListeners[i] = null; 2058 mNumberOfListeners--; 2059 break; 2060 } 2061 } 2062 2063 if (mNumberOfListeners == 0) { 2064 ViewTreeObserver vto = mTextView.getViewTreeObserver(); 2065 vto.removeOnPreDrawListener(this); 2066 } 2067 } 2068 2069 public int getPositionX() { 2070 return mPositionX; 2071 } 2072 2073 public int getPositionY() { 2074 return mPositionY; 2075 } 2076 2077 @Override 2078 public boolean onPreDraw() { 2079 updatePosition(); 2080 2081 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 2082 if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) { 2083 TextViewPositionListener positionListener = mPositionListeners[i]; 2084 if (positionListener != null) { 2085 positionListener.updatePosition(mPositionX, mPositionY, 2086 mPositionHasChanged, mScrollHasChanged); 2087 } 2088 } 2089 } 2090 2091 mScrollHasChanged = false; 2092 return true; 2093 } 2094 2095 private void updatePosition() { 2096 mTextView.getLocationInWindow(mTempCoords); 2097 2098 mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY; 2099 2100 mPositionX = mTempCoords[0]; 2101 mPositionY = mTempCoords[1]; 2102 } 2103 2104 public void onScrollChanged() { 2105 mScrollHasChanged = true; 2106 } 2107 } 2108 2109 private abstract class PinnedPopupWindow implements TextViewPositionListener { 2110 protected PopupWindow mPopupWindow; 2111 protected ViewGroup mContentView; 2112 int mPositionX, mPositionY; 2113 2114 protected abstract void createPopupWindow(); 2115 protected abstract void initContentView(); 2116 protected abstract int getTextOffset(); 2117 protected abstract int getVerticalLocalPosition(int line); 2118 protected abstract int clipVertically(int positionY); 2119 2120 public PinnedPopupWindow() { 2121 createPopupWindow(); 2122 2123 mPopupWindow.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 2124 mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 2125 mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 2126 2127 initContentView(); 2128 2129 LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 2130 ViewGroup.LayoutParams.WRAP_CONTENT); 2131 mContentView.setLayoutParams(wrapContent); 2132 2133 mPopupWindow.setContentView(mContentView); 2134 } 2135 2136 public void show() { 2137 getPositionListener().addSubscriber(this, false /* offset is fixed */); 2138 2139 computeLocalPosition(); 2140 2141 final PositionListener positionListener = getPositionListener(); 2142 updatePosition(positionListener.getPositionX(), positionListener.getPositionY()); 2143 } 2144 2145 protected void measureContent() { 2146 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 2147 mContentView.measure( 2148 View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, 2149 View.MeasureSpec.AT_MOST), 2150 View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, 2151 View.MeasureSpec.AT_MOST)); 2152 } 2153 2154 /* The popup window will be horizontally centered on the getTextOffset() and vertically 2155 * positioned according to viewportToContentHorizontalOffset. 2156 * 2157 * This method assumes that mContentView has properly been measured from its content. */ 2158 private void computeLocalPosition() { 2159 measureContent(); 2160 final int width = mContentView.getMeasuredWidth(); 2161 final int offset = getTextOffset(); 2162 mPositionX = (int) (mTextView.getLayout().getPrimaryHorizontal(offset) - width / 2.0f); 2163 mPositionX += mTextView.viewportToContentHorizontalOffset(); 2164 2165 final int line = mTextView.getLayout().getLineForOffset(offset); 2166 mPositionY = getVerticalLocalPosition(line); 2167 mPositionY += mTextView.viewportToContentVerticalOffset(); 2168 } 2169 2170 private void updatePosition(int parentPositionX, int parentPositionY) { 2171 int positionX = parentPositionX + mPositionX; 2172 int positionY = parentPositionY + mPositionY; 2173 2174 positionY = clipVertically(positionY); 2175 2176 // Horizontal clipping 2177 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 2178 final int width = mContentView.getMeasuredWidth(); 2179 positionX = Math.min(displayMetrics.widthPixels - width, positionX); 2180 positionX = Math.max(0, positionX); 2181 2182 if (isShowing()) { 2183 mPopupWindow.update(positionX, positionY, -1, -1); 2184 } else { 2185 mPopupWindow.showAtLocation(mTextView, Gravity.NO_GRAVITY, 2186 positionX, positionY); 2187 } 2188 } 2189 2190 public void hide() { 2191 mPopupWindow.dismiss(); 2192 getPositionListener().removeSubscriber(this); 2193 } 2194 2195 @Override 2196 public void updatePosition(int parentPositionX, int parentPositionY, 2197 boolean parentPositionChanged, boolean parentScrolled) { 2198 // Either parentPositionChanged or parentScrolled is true, check if still visible 2199 if (isShowing() && isOffsetVisible(getTextOffset())) { 2200 if (parentScrolled) computeLocalPosition(); 2201 updatePosition(parentPositionX, parentPositionY); 2202 } else { 2203 hide(); 2204 } 2205 } 2206 2207 public boolean isShowing() { 2208 return mPopupWindow.isShowing(); 2209 } 2210 } 2211 2212 private class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener { 2213 private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE; 2214 private static final int ADD_TO_DICTIONARY = -1; 2215 private static final int DELETE_TEXT = -2; 2216 private SuggestionInfo[] mSuggestionInfos; 2217 private int mNumberOfSuggestions; 2218 private boolean mCursorWasVisibleBeforeSuggestions; 2219 private boolean mIsShowingUp = false; 2220 private SuggestionAdapter mSuggestionsAdapter; 2221 private final Comparator<SuggestionSpan> mSuggestionSpanComparator; 2222 private final HashMap<SuggestionSpan, Integer> mSpansLengths; 2223 2224 private class CustomPopupWindow extends PopupWindow { 2225 public CustomPopupWindow(Context context, int defStyle) { 2226 super(context, null, defStyle); 2227 } 2228 2229 @Override 2230 public void dismiss() { 2231 super.dismiss(); 2232 2233 getPositionListener().removeSubscriber(SuggestionsPopupWindow.this); 2234 2235 // Safe cast since show() checks that mTextView.getText() is an Editable 2236 ((Spannable) mTextView.getText()).removeSpan(mSuggestionRangeSpan); 2237 2238 mTextView.setCursorVisible(mCursorWasVisibleBeforeSuggestions); 2239 if (hasInsertionController()) { 2240 getInsertionController().show(); 2241 } 2242 } 2243 } 2244 2245 public SuggestionsPopupWindow() { 2246 mCursorWasVisibleBeforeSuggestions = mCursorVisible; 2247 mSuggestionSpanComparator = new SuggestionSpanComparator(); 2248 mSpansLengths = new HashMap<SuggestionSpan, Integer>(); 2249 } 2250 2251 @Override 2252 protected void createPopupWindow() { 2253 mPopupWindow = new CustomPopupWindow(mTextView.getContext(), 2254 com.android.internal.R.attr.textSuggestionsWindowStyle); 2255 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 2256 mPopupWindow.setFocusable(true); 2257 mPopupWindow.setClippingEnabled(false); 2258 } 2259 2260 @Override 2261 protected void initContentView() { 2262 ListView listView = new ListView(mTextView.getContext()); 2263 mSuggestionsAdapter = new SuggestionAdapter(); 2264 listView.setAdapter(mSuggestionsAdapter); 2265 listView.setOnItemClickListener(this); 2266 mContentView = listView; 2267 2268 // Inflate the suggestion items once and for all. + 2 for add to dictionary and delete 2269 mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS + 2]; 2270 for (int i = 0; i < mSuggestionInfos.length; i++) { 2271 mSuggestionInfos[i] = new SuggestionInfo(); 2272 } 2273 } 2274 2275 public boolean isShowingUp() { 2276 return mIsShowingUp; 2277 } 2278 2279 public void onParentLostFocus() { 2280 mIsShowingUp = false; 2281 } 2282 2283 private class SuggestionInfo { 2284 int suggestionStart, suggestionEnd; // range of actual suggestion within text 2285 SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents 2286 int suggestionIndex; // the index of this suggestion inside suggestionSpan 2287 SpannableStringBuilder text = new SpannableStringBuilder(); 2288 TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mTextView.getContext(), 2289 android.R.style.TextAppearance_SuggestionHighlight); 2290 } 2291 2292 private class SuggestionAdapter extends BaseAdapter { 2293 private LayoutInflater mInflater = (LayoutInflater) mTextView.getContext(). 2294 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 2295 2296 @Override 2297 public int getCount() { 2298 return mNumberOfSuggestions; 2299 } 2300 2301 @Override 2302 public Object getItem(int position) { 2303 return mSuggestionInfos[position]; 2304 } 2305 2306 @Override 2307 public long getItemId(int position) { 2308 return position; 2309 } 2310 2311 @Override 2312 public View getView(int position, View convertView, ViewGroup parent) { 2313 TextView textView = (TextView) convertView; 2314 2315 if (textView == null) { 2316 textView = (TextView) mInflater.inflate(mTextView.mTextEditSuggestionItemLayout, 2317 parent, false); 2318 } 2319 2320 final SuggestionInfo suggestionInfo = mSuggestionInfos[position]; 2321 textView.setText(suggestionInfo.text); 2322 2323 if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY || 2324 suggestionInfo.suggestionIndex == DELETE_TEXT) { 2325 textView.setBackgroundColor(Color.TRANSPARENT); 2326 } else { 2327 textView.setBackgroundColor(Color.WHITE); 2328 } 2329 2330 return textView; 2331 } 2332 } 2333 2334 private class SuggestionSpanComparator implements Comparator<SuggestionSpan> { 2335 public int compare(SuggestionSpan span1, SuggestionSpan span2) { 2336 final int flag1 = span1.getFlags(); 2337 final int flag2 = span2.getFlags(); 2338 if (flag1 != flag2) { 2339 // The order here should match what is used in updateDrawState 2340 final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0; 2341 final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0; 2342 final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0; 2343 final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0; 2344 if (easy1 && !misspelled1) return -1; 2345 if (easy2 && !misspelled2) return 1; 2346 if (misspelled1) return -1; 2347 if (misspelled2) return 1; 2348 } 2349 2350 return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue(); 2351 } 2352 } 2353 2354 /** 2355 * Returns the suggestion spans that cover the current cursor position. The suggestion 2356 * spans are sorted according to the length of text that they are attached to. 2357 */ 2358 private SuggestionSpan[] getSuggestionSpans() { 2359 int pos = mTextView.getSelectionStart(); 2360 Spannable spannable = (Spannable) mTextView.getText(); 2361 SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class); 2362 2363 mSpansLengths.clear(); 2364 for (SuggestionSpan suggestionSpan : suggestionSpans) { 2365 int start = spannable.getSpanStart(suggestionSpan); 2366 int end = spannable.getSpanEnd(suggestionSpan); 2367 mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start)); 2368 } 2369 2370 // The suggestions are sorted according to their types (easy correction first, then 2371 // misspelled) and to the length of the text that they cover (shorter first). 2372 Arrays.sort(suggestionSpans, mSuggestionSpanComparator); 2373 return suggestionSpans; 2374 } 2375 2376 @Override 2377 public void show() { 2378 if (!(mTextView.getText() instanceof Editable)) return; 2379 2380 if (updateSuggestions()) { 2381 mCursorWasVisibleBeforeSuggestions = mCursorVisible; 2382 mTextView.setCursorVisible(false); 2383 mIsShowingUp = true; 2384 super.show(); 2385 } 2386 } 2387 2388 @Override 2389 protected void measureContent() { 2390 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 2391 final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec( 2392 displayMetrics.widthPixels, View.MeasureSpec.AT_MOST); 2393 final int verticalMeasure = View.MeasureSpec.makeMeasureSpec( 2394 displayMetrics.heightPixels, View.MeasureSpec.AT_MOST); 2395 2396 int width = 0; 2397 View view = null; 2398 for (int i = 0; i < mNumberOfSuggestions; i++) { 2399 view = mSuggestionsAdapter.getView(i, view, mContentView); 2400 view.getLayoutParams().width = LayoutParams.WRAP_CONTENT; 2401 view.measure(horizontalMeasure, verticalMeasure); 2402 width = Math.max(width, view.getMeasuredWidth()); 2403 } 2404 2405 // Enforce the width based on actual text widths 2406 mContentView.measure( 2407 View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), 2408 verticalMeasure); 2409 2410 Drawable popupBackground = mPopupWindow.getBackground(); 2411 if (popupBackground != null) { 2412 if (mTempRect == null) mTempRect = new Rect(); 2413 popupBackground.getPadding(mTempRect); 2414 width += mTempRect.left + mTempRect.right; 2415 } 2416 mPopupWindow.setWidth(width); 2417 } 2418 2419 @Override 2420 protected int getTextOffset() { 2421 return mTextView.getSelectionStart(); 2422 } 2423 2424 @Override 2425 protected int getVerticalLocalPosition(int line) { 2426 return mTextView.getLayout().getLineBottom(line); 2427 } 2428 2429 @Override 2430 protected int clipVertically(int positionY) { 2431 final int height = mContentView.getMeasuredHeight(); 2432 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 2433 return Math.min(positionY, displayMetrics.heightPixels - height); 2434 } 2435 2436 @Override 2437 public void hide() { 2438 super.hide(); 2439 } 2440 2441 private boolean updateSuggestions() { 2442 Spannable spannable = (Spannable) mTextView.getText(); 2443 SuggestionSpan[] suggestionSpans = getSuggestionSpans(); 2444 2445 final int nbSpans = suggestionSpans.length; 2446 // Suggestions are shown after a delay: the underlying spans may have been removed 2447 if (nbSpans == 0) return false; 2448 2449 mNumberOfSuggestions = 0; 2450 int spanUnionStart = mTextView.getText().length(); 2451 int spanUnionEnd = 0; 2452 2453 SuggestionSpan misspelledSpan = null; 2454 int underlineColor = 0; 2455 2456 for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) { 2457 SuggestionSpan suggestionSpan = suggestionSpans[spanIndex]; 2458 final int spanStart = spannable.getSpanStart(suggestionSpan); 2459 final int spanEnd = spannable.getSpanEnd(suggestionSpan); 2460 spanUnionStart = Math.min(spanStart, spanUnionStart); 2461 spanUnionEnd = Math.max(spanEnd, spanUnionEnd); 2462 2463 if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) { 2464 misspelledSpan = suggestionSpan; 2465 } 2466 2467 // The first span dictates the background color of the highlighted text 2468 if (spanIndex == 0) underlineColor = suggestionSpan.getUnderlineColor(); 2469 2470 String[] suggestions = suggestionSpan.getSuggestions(); 2471 int nbSuggestions = suggestions.length; 2472 for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) { 2473 String suggestion = suggestions[suggestionIndex]; 2474 2475 boolean suggestionIsDuplicate = false; 2476 for (int i = 0; i < mNumberOfSuggestions; i++) { 2477 if (mSuggestionInfos[i].text.toString().equals(suggestion)) { 2478 SuggestionSpan otherSuggestionSpan = mSuggestionInfos[i].suggestionSpan; 2479 final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan); 2480 final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan); 2481 if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) { 2482 suggestionIsDuplicate = true; 2483 break; 2484 } 2485 } 2486 } 2487 2488 if (!suggestionIsDuplicate) { 2489 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 2490 suggestionInfo.suggestionSpan = suggestionSpan; 2491 suggestionInfo.suggestionIndex = suggestionIndex; 2492 suggestionInfo.text.replace(0, suggestionInfo.text.length(), suggestion); 2493 2494 mNumberOfSuggestions++; 2495 2496 if (mNumberOfSuggestions == MAX_NUMBER_SUGGESTIONS) { 2497 // Also end outer for loop 2498 spanIndex = nbSpans; 2499 break; 2500 } 2501 } 2502 } 2503 } 2504 2505 for (int i = 0; i < mNumberOfSuggestions; i++) { 2506 highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd); 2507 } 2508 2509 // Add "Add to dictionary" item if there is a span with the misspelled flag 2510 if (misspelledSpan != null) { 2511 final int misspelledStart = spannable.getSpanStart(misspelledSpan); 2512 final int misspelledEnd = spannable.getSpanEnd(misspelledSpan); 2513 if (misspelledStart >= 0 && misspelledEnd > misspelledStart) { 2514 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 2515 suggestionInfo.suggestionSpan = misspelledSpan; 2516 suggestionInfo.suggestionIndex = ADD_TO_DICTIONARY; 2517 suggestionInfo.text.replace(0, suggestionInfo.text.length(), mTextView. 2518 getContext().getString(com.android.internal.R.string.addToDictionary)); 2519 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0, 2520 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2521 2522 mNumberOfSuggestions++; 2523 } 2524 } 2525 2526 // Delete item 2527 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 2528 suggestionInfo.suggestionSpan = null; 2529 suggestionInfo.suggestionIndex = DELETE_TEXT; 2530 suggestionInfo.text.replace(0, suggestionInfo.text.length(), 2531 mTextView.getContext().getString(com.android.internal.R.string.deleteText)); 2532 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0, 2533 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2534 mNumberOfSuggestions++; 2535 2536 if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan(); 2537 if (underlineColor == 0) { 2538 // Fallback on the default highlight color when the first span does not provide one 2539 mSuggestionRangeSpan.setBackgroundColor(mTextView.mHighlightColor); 2540 } else { 2541 final float BACKGROUND_TRANSPARENCY = 0.4f; 2542 final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY); 2543 mSuggestionRangeSpan.setBackgroundColor( 2544 (underlineColor & 0x00FFFFFF) + (newAlpha << 24)); 2545 } 2546 spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd, 2547 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2548 2549 mSuggestionsAdapter.notifyDataSetChanged(); 2550 return true; 2551 } 2552 2553 private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart, 2554 int unionEnd) { 2555 final Spannable text = (Spannable) mTextView.getText(); 2556 final int spanStart = text.getSpanStart(suggestionInfo.suggestionSpan); 2557 final int spanEnd = text.getSpanEnd(suggestionInfo.suggestionSpan); 2558 2559 // Adjust the start/end of the suggestion span 2560 suggestionInfo.suggestionStart = spanStart - unionStart; 2561 suggestionInfo.suggestionEnd = suggestionInfo.suggestionStart 2562 + suggestionInfo.text.length(); 2563 2564 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 2565 suggestionInfo.text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2566 2567 // Add the text before and after the span. 2568 final String textAsString = text.toString(); 2569 suggestionInfo.text.insert(0, textAsString.substring(unionStart, spanStart)); 2570 suggestionInfo.text.append(textAsString.substring(spanEnd, unionEnd)); 2571 } 2572 2573 @Override 2574 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 2575 Editable editable = (Editable) mTextView.getText(); 2576 SuggestionInfo suggestionInfo = mSuggestionInfos[position]; 2577 2578 if (suggestionInfo.suggestionIndex == DELETE_TEXT) { 2579 final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan); 2580 int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan); 2581 if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) { 2582 // Do not leave two adjacent spaces after deletion, or one at beginning of text 2583 if (spanUnionEnd < editable.length() && 2584 Character.isSpaceChar(editable.charAt(spanUnionEnd)) && 2585 (spanUnionStart == 0 || 2586 Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) { 2587 spanUnionEnd = spanUnionEnd + 1; 2588 } 2589 mTextView.deleteText_internal(spanUnionStart, spanUnionEnd); 2590 } 2591 hide(); 2592 return; 2593 } 2594 2595 final int spanStart = editable.getSpanStart(suggestionInfo.suggestionSpan); 2596 final int spanEnd = editable.getSpanEnd(suggestionInfo.suggestionSpan); 2597 if (spanStart < 0 || spanEnd <= spanStart) { 2598 // Span has been removed 2599 hide(); 2600 return; 2601 } 2602 2603 final String originalText = editable.toString().substring(spanStart, spanEnd); 2604 2605 if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) { 2606 Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT); 2607 intent.putExtra("word", originalText); 2608 intent.putExtra("locale", mTextView.getTextServicesLocale().toString()); 2609 // Put a listener to replace the original text with a word which the user 2610 // modified in a user dictionary dialog. 2611 mUserDictionaryListener.waitForUserDictionaryAdded( 2612 mTextView, originalText, spanStart, spanEnd); 2613 intent.putExtra("listener", new Messenger(mUserDictionaryListener)); 2614 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 2615 mTextView.getContext().startActivity(intent); 2616 // There is no way to know if the word was indeed added. Re-check. 2617 // TODO The ExtractEditText should remove the span in the original text instead 2618 editable.removeSpan(suggestionInfo.suggestionSpan); 2619 Selection.setSelection(editable, spanEnd); 2620 updateSpellCheckSpans(spanStart, spanEnd, false); 2621 } else { 2622 // SuggestionSpans are removed by replace: save them before 2623 SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd, 2624 SuggestionSpan.class); 2625 final int length = suggestionSpans.length; 2626 int[] suggestionSpansStarts = new int[length]; 2627 int[] suggestionSpansEnds = new int[length]; 2628 int[] suggestionSpansFlags = new int[length]; 2629 for (int i = 0; i < length; i++) { 2630 final SuggestionSpan suggestionSpan = suggestionSpans[i]; 2631 suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan); 2632 suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan); 2633 suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan); 2634 2635 // Remove potential misspelled flags 2636 int suggestionSpanFlags = suggestionSpan.getFlags(); 2637 if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) > 0) { 2638 suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED; 2639 suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT; 2640 suggestionSpan.setFlags(suggestionSpanFlags); 2641 } 2642 } 2643 2644 final int suggestionStart = suggestionInfo.suggestionStart; 2645 final int suggestionEnd = suggestionInfo.suggestionEnd; 2646 final String suggestion = suggestionInfo.text.subSequence( 2647 suggestionStart, suggestionEnd).toString(); 2648 mTextView.replaceText_internal(spanStart, spanEnd, suggestion); 2649 2650 // Notify source IME of the suggestion pick. Do this before 2651 // swaping texts. 2652 suggestionInfo.suggestionSpan.notifySelection( 2653 mTextView.getContext(), originalText, suggestionInfo.suggestionIndex); 2654 2655 // Swap text content between actual text and Suggestion span 2656 String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions(); 2657 suggestions[suggestionInfo.suggestionIndex] = originalText; 2658 2659 // Restore previous SuggestionSpans 2660 final int lengthDifference = suggestion.length() - (spanEnd - spanStart); 2661 for (int i = 0; i < length; i++) { 2662 // Only spans that include the modified region make sense after replacement 2663 // Spans partially included in the replaced region are removed, there is no 2664 // way to assign them a valid range after replacement 2665 if (suggestionSpansStarts[i] <= spanStart && 2666 suggestionSpansEnds[i] >= spanEnd) { 2667 mTextView.setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i], 2668 suggestionSpansEnds[i] + lengthDifference, suggestionSpansFlags[i]); 2669 } 2670 } 2671 2672 // Move cursor at the end of the replaced word 2673 final int newCursorPosition = spanEnd + lengthDifference; 2674 mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition); 2675 } 2676 2677 hide(); 2678 } 2679 } 2680 2681 /** 2682 * An ActionMode Callback class that is used to provide actions while in text selection mode. 2683 * 2684 * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending 2685 * on which of these this TextView supports. 2686 */ 2687 private class SelectionActionModeCallback implements ActionMode.Callback { 2688 2689 @Override 2690 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 2691 TypedArray styledAttributes = mTextView.getContext().obtainStyledAttributes( 2692 com.android.internal.R.styleable.SelectionModeDrawables); 2693 2694 mode.setTitle(mTextView.getContext().getString( 2695 com.android.internal.R.string.textSelectionCABTitle)); 2696 mode.setSubtitle(null); 2697 mode.setTitleOptionalHint(true); 2698 2699 menu.add(0, TextView.ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll). 2700 setIcon(styledAttributes.getResourceId( 2701 R.styleable.SelectionModeDrawables_actionModeSelectAllDrawable, 0)). 2702 setAlphabeticShortcut('a'). 2703 setShowAsAction( 2704 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 2705 2706 if (mTextView.canCut()) { 2707 menu.add(0, TextView.ID_CUT, 0, com.android.internal.R.string.cut). 2708 setIcon(styledAttributes.getResourceId( 2709 R.styleable.SelectionModeDrawables_actionModeCutDrawable, 0)). 2710 setAlphabeticShortcut('x'). 2711 setShowAsAction( 2712 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 2713 } 2714 2715 if (mTextView.canCopy()) { 2716 menu.add(0, TextView.ID_COPY, 0, com.android.internal.R.string.copy). 2717 setIcon(styledAttributes.getResourceId( 2718 R.styleable.SelectionModeDrawables_actionModeCopyDrawable, 0)). 2719 setAlphabeticShortcut('c'). 2720 setShowAsAction( 2721 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 2722 } 2723 2724 if (mTextView.canPaste()) { 2725 menu.add(0, TextView.ID_PASTE, 0, com.android.internal.R.string.paste). 2726 setIcon(styledAttributes.getResourceId( 2727 R.styleable.SelectionModeDrawables_actionModePasteDrawable, 0)). 2728 setAlphabeticShortcut('v'). 2729 setShowAsAction( 2730 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 2731 } 2732 2733 styledAttributes.recycle(); 2734 2735 if (mCustomSelectionActionModeCallback != null) { 2736 if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) { 2737 // The custom mode can choose to cancel the action mode 2738 return false; 2739 } 2740 } 2741 2742 if (menu.hasVisibleItems() || mode.getCustomView() != null) { 2743 getSelectionController().show(); 2744 mTextView.setHasTransientState(true); 2745 return true; 2746 } else { 2747 return false; 2748 } 2749 } 2750 2751 @Override 2752 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 2753 if (mCustomSelectionActionModeCallback != null) { 2754 return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu); 2755 } 2756 return true; 2757 } 2758 2759 @Override 2760 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 2761 if (mCustomSelectionActionModeCallback != null && 2762 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) { 2763 return true; 2764 } 2765 return mTextView.onTextContextMenuItem(item.getItemId()); 2766 } 2767 2768 @Override 2769 public void onDestroyActionMode(ActionMode mode) { 2770 if (mCustomSelectionActionModeCallback != null) { 2771 mCustomSelectionActionModeCallback.onDestroyActionMode(mode); 2772 } 2773 2774 /* 2775 * If we're ending this mode because we're detaching from a window, 2776 * we still have selection state to preserve. Don't clear it, we'll 2777 * bring back the selection mode when (if) we get reattached. 2778 */ 2779 if (!mPreserveDetachedSelection) { 2780 Selection.setSelection((Spannable) mTextView.getText(), 2781 mTextView.getSelectionEnd()); 2782 mTextView.setHasTransientState(false); 2783 } 2784 2785 if (mSelectionModifierCursorController != null) { 2786 mSelectionModifierCursorController.hide(); 2787 } 2788 2789 mSelectionActionMode = null; 2790 } 2791 } 2792 2793 private class ActionPopupWindow extends PinnedPopupWindow implements OnClickListener { 2794 private static final int POPUP_TEXT_LAYOUT = 2795 com.android.internal.R.layout.text_edit_action_popup_text; 2796 private TextView mPasteTextView; 2797 private TextView mReplaceTextView; 2798 2799 @Override 2800 protected void createPopupWindow() { 2801 mPopupWindow = new PopupWindow(mTextView.getContext(), null, 2802 com.android.internal.R.attr.textSelectHandleWindowStyle); 2803 mPopupWindow.setClippingEnabled(true); 2804 } 2805 2806 @Override 2807 protected void initContentView() { 2808 LinearLayout linearLayout = new LinearLayout(mTextView.getContext()); 2809 linearLayout.setOrientation(LinearLayout.HORIZONTAL); 2810 mContentView = linearLayout; 2811 mContentView.setBackgroundResource( 2812 com.android.internal.R.drawable.text_edit_paste_window); 2813 2814 LayoutInflater inflater = (LayoutInflater) mTextView.getContext(). 2815 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 2816 2817 LayoutParams wrapContent = new LayoutParams( 2818 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 2819 2820 mPasteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 2821 mPasteTextView.setLayoutParams(wrapContent); 2822 mContentView.addView(mPasteTextView); 2823 mPasteTextView.setText(com.android.internal.R.string.paste); 2824 mPasteTextView.setOnClickListener(this); 2825 2826 mReplaceTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 2827 mReplaceTextView.setLayoutParams(wrapContent); 2828 mContentView.addView(mReplaceTextView); 2829 mReplaceTextView.setText(com.android.internal.R.string.replace); 2830 mReplaceTextView.setOnClickListener(this); 2831 } 2832 2833 @Override 2834 public void show() { 2835 boolean canPaste = mTextView.canPaste(); 2836 boolean canSuggest = mTextView.isSuggestionsEnabled() && isCursorInsideSuggestionSpan(); 2837 mPasteTextView.setVisibility(canPaste ? View.VISIBLE : View.GONE); 2838 mReplaceTextView.setVisibility(canSuggest ? View.VISIBLE : View.GONE); 2839 2840 if (!canPaste && !canSuggest) return; 2841 2842 super.show(); 2843 } 2844 2845 @Override 2846 public void onClick(View view) { 2847 if (view == mPasteTextView && mTextView.canPaste()) { 2848 mTextView.onTextContextMenuItem(TextView.ID_PASTE); 2849 hide(); 2850 } else if (view == mReplaceTextView) { 2851 int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2; 2852 stopSelectionActionMode(); 2853 Selection.setSelection((Spannable) mTextView.getText(), middle); 2854 showSuggestions(); 2855 } 2856 } 2857 2858 @Override 2859 protected int getTextOffset() { 2860 return (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2; 2861 } 2862 2863 @Override 2864 protected int getVerticalLocalPosition(int line) { 2865 return mTextView.getLayout().getLineTop(line) - mContentView.getMeasuredHeight(); 2866 } 2867 2868 @Override 2869 protected int clipVertically(int positionY) { 2870 if (positionY < 0) { 2871 final int offset = getTextOffset(); 2872 final Layout layout = mTextView.getLayout(); 2873 final int line = layout.getLineForOffset(offset); 2874 positionY += layout.getLineBottom(line) - layout.getLineTop(line); 2875 positionY += mContentView.getMeasuredHeight(); 2876 2877 // Assumes insertion and selection handles share the same height 2878 final Drawable handle = mTextView.getResources().getDrawable( 2879 mTextView.mTextSelectHandleRes); 2880 positionY += handle.getIntrinsicHeight(); 2881 } 2882 2883 return positionY; 2884 } 2885 } 2886 2887 private abstract class HandleView extends View implements TextViewPositionListener { 2888 protected Drawable mDrawable; 2889 protected Drawable mDrawableLtr; 2890 protected Drawable mDrawableRtl; 2891 private final PopupWindow mContainer; 2892 // Position with respect to the parent TextView 2893 private int mPositionX, mPositionY; 2894 private boolean mIsDragging; 2895 // Offset from touch position to mPosition 2896 private float mTouchToWindowOffsetX, mTouchToWindowOffsetY; 2897 protected int mHotspotX; 2898 // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up 2899 private float mTouchOffsetY; 2900 // Where the touch position should be on the handle to ensure a maximum cursor visibility 2901 private float mIdealVerticalOffset; 2902 // Parent's (TextView) previous position in window 2903 private int mLastParentX, mLastParentY; 2904 // Transient action popup window for Paste and Replace actions 2905 protected ActionPopupWindow mActionPopupWindow; 2906 // Previous text character offset 2907 private int mPreviousOffset = -1; 2908 // Previous text character offset 2909 private boolean mPositionHasChanged = true; 2910 // Used to delay the appearance of the action popup window 2911 private Runnable mActionPopupShower; 2912 2913 public HandleView(Drawable drawableLtr, Drawable drawableRtl) { 2914 super(mTextView.getContext()); 2915 mContainer = new PopupWindow(mTextView.getContext(), null, 2916 com.android.internal.R.attr.textSelectHandleWindowStyle); 2917 mContainer.setSplitTouchEnabled(true); 2918 mContainer.setClippingEnabled(false); 2919 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 2920 mContainer.setContentView(this); 2921 2922 mDrawableLtr = drawableLtr; 2923 mDrawableRtl = drawableRtl; 2924 2925 updateDrawable(); 2926 2927 final int handleHeight = mDrawable.getIntrinsicHeight(); 2928 mTouchOffsetY = -0.3f * handleHeight; 2929 mIdealVerticalOffset = 0.7f * handleHeight; 2930 } 2931 2932 protected void updateDrawable() { 2933 final int offset = getCurrentCursorOffset(); 2934 final boolean isRtlCharAtOffset = mTextView.getLayout().isRtlCharAt(offset); 2935 mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr; 2936 mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset); 2937 } 2938 2939 protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun); 2940 2941 // Touch-up filter: number of previous positions remembered 2942 private static final int HISTORY_SIZE = 5; 2943 private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150; 2944 private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350; 2945 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE]; 2946 private final int[] mPreviousOffsets = new int[HISTORY_SIZE]; 2947 private int mPreviousOffsetIndex = 0; 2948 private int mNumberPreviousOffsets = 0; 2949 2950 private void startTouchUpFilter(int offset) { 2951 mNumberPreviousOffsets = 0; 2952 addPositionToTouchUpFilter(offset); 2953 } 2954 2955 private void addPositionToTouchUpFilter(int offset) { 2956 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE; 2957 mPreviousOffsets[mPreviousOffsetIndex] = offset; 2958 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis(); 2959 mNumberPreviousOffsets++; 2960 } 2961 2962 private void filterOnTouchUp() { 2963 final long now = SystemClock.uptimeMillis(); 2964 int i = 0; 2965 int index = mPreviousOffsetIndex; 2966 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE); 2967 while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) { 2968 i++; 2969 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE; 2970 } 2971 2972 if (i > 0 && i < iMax && 2973 (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) { 2974 positionAtCursorOffset(mPreviousOffsets[index], false); 2975 } 2976 } 2977 2978 public boolean offsetHasBeenChanged() { 2979 return mNumberPreviousOffsets > 1; 2980 } 2981 2982 @Override 2983 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 2984 setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight()); 2985 } 2986 2987 public void show() { 2988 if (isShowing()) return; 2989 2990 getPositionListener().addSubscriber(this, true /* local position may change */); 2991 2992 // Make sure the offset is always considered new, even when focusing at same position 2993 mPreviousOffset = -1; 2994 positionAtCursorOffset(getCurrentCursorOffset(), false); 2995 2996 hideActionPopupWindow(); 2997 } 2998 2999 protected void dismiss() { 3000 mIsDragging = false; 3001 mContainer.dismiss(); 3002 onDetached(); 3003 } 3004 3005 public void hide() { 3006 dismiss(); 3007 3008 getPositionListener().removeSubscriber(this); 3009 } 3010 3011 void showActionPopupWindow(int delay) { 3012 if (mActionPopupWindow == null) { 3013 mActionPopupWindow = new ActionPopupWindow(); 3014 } 3015 if (mActionPopupShower == null) { 3016 mActionPopupShower = new Runnable() { 3017 public void run() { 3018 mActionPopupWindow.show(); 3019 } 3020 }; 3021 } else { 3022 mTextView.removeCallbacks(mActionPopupShower); 3023 } 3024 mTextView.postDelayed(mActionPopupShower, delay); 3025 } 3026 3027 protected void hideActionPopupWindow() { 3028 if (mActionPopupShower != null) { 3029 mTextView.removeCallbacks(mActionPopupShower); 3030 } 3031 if (mActionPopupWindow != null) { 3032 mActionPopupWindow.hide(); 3033 } 3034 } 3035 3036 public boolean isShowing() { 3037 return mContainer.isShowing(); 3038 } 3039 3040 private boolean isVisible() { 3041 // Always show a dragging handle. 3042 if (mIsDragging) { 3043 return true; 3044 } 3045 3046 if (mTextView.isInBatchEditMode()) { 3047 return false; 3048 } 3049 3050 return isPositionVisible(mPositionX + mHotspotX, mPositionY); 3051 } 3052 3053 public abstract int getCurrentCursorOffset(); 3054 3055 protected abstract void updateSelection(int offset); 3056 3057 public abstract void updatePosition(float x, float y); 3058 3059 protected void positionAtCursorOffset(int offset, boolean parentScrolled) { 3060 // A HandleView relies on the layout, which may be nulled by external methods 3061 Layout layout = mTextView.getLayout(); 3062 if (layout == null) { 3063 // Will update controllers' state, hiding them and stopping selection mode if needed 3064 prepareCursorControllers(); 3065 return; 3066 } 3067 3068 boolean offsetChanged = offset != mPreviousOffset; 3069 if (offsetChanged || parentScrolled) { 3070 if (offsetChanged) { 3071 updateSelection(offset); 3072 addPositionToTouchUpFilter(offset); 3073 } 3074 final int line = layout.getLineForOffset(offset); 3075 3076 mPositionX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX); 3077 mPositionY = layout.getLineBottom(line); 3078 3079 // Take TextView's padding and scroll into account. 3080 mPositionX += mTextView.viewportToContentHorizontalOffset(); 3081 mPositionY += mTextView.viewportToContentVerticalOffset(); 3082 3083 mPreviousOffset = offset; 3084 mPositionHasChanged = true; 3085 } 3086 } 3087 3088 public void updatePosition(int parentPositionX, int parentPositionY, 3089 boolean parentPositionChanged, boolean parentScrolled) { 3090 positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled); 3091 if (parentPositionChanged || mPositionHasChanged) { 3092 if (mIsDragging) { 3093 // Update touchToWindow offset in case of parent scrolling while dragging 3094 if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) { 3095 mTouchToWindowOffsetX += parentPositionX - mLastParentX; 3096 mTouchToWindowOffsetY += parentPositionY - mLastParentY; 3097 mLastParentX = parentPositionX; 3098 mLastParentY = parentPositionY; 3099 } 3100 3101 onHandleMoved(); 3102 } 3103 3104 if (isVisible()) { 3105 final int positionX = parentPositionX + mPositionX; 3106 final int positionY = parentPositionY + mPositionY; 3107 if (isShowing()) { 3108 mContainer.update(positionX, positionY, -1, -1); 3109 } else { 3110 mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY, 3111 positionX, positionY); 3112 } 3113 } else { 3114 if (isShowing()) { 3115 dismiss(); 3116 } 3117 } 3118 3119 mPositionHasChanged = false; 3120 } 3121 } 3122 3123 @Override 3124 protected void onDraw(Canvas c) { 3125 mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 3126 mDrawable.draw(c); 3127 } 3128 3129 @Override 3130 public boolean onTouchEvent(MotionEvent ev) { 3131 switch (ev.getActionMasked()) { 3132 case MotionEvent.ACTION_DOWN: { 3133 startTouchUpFilter(getCurrentCursorOffset()); 3134 mTouchToWindowOffsetX = ev.getRawX() - mPositionX; 3135 mTouchToWindowOffsetY = ev.getRawY() - mPositionY; 3136 3137 final PositionListener positionListener = getPositionListener(); 3138 mLastParentX = positionListener.getPositionX(); 3139 mLastParentY = positionListener.getPositionY(); 3140 mIsDragging = true; 3141 break; 3142 } 3143 3144 case MotionEvent.ACTION_MOVE: { 3145 final float rawX = ev.getRawX(); 3146 final float rawY = ev.getRawY(); 3147 3148 // Vertical hysteresis: vertical down movement tends to snap to ideal offset 3149 final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY; 3150 final float currentVerticalOffset = rawY - mPositionY - mLastParentY; 3151 float newVerticalOffset; 3152 if (previousVerticalOffset < mIdealVerticalOffset) { 3153 newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset); 3154 newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset); 3155 } else { 3156 newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset); 3157 newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset); 3158 } 3159 mTouchToWindowOffsetY = newVerticalOffset + mLastParentY; 3160 3161 final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX; 3162 final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY; 3163 3164 updatePosition(newPosX, newPosY); 3165 break; 3166 } 3167 3168 case MotionEvent.ACTION_UP: 3169 filterOnTouchUp(); 3170 mIsDragging = false; 3171 break; 3172 3173 case MotionEvent.ACTION_CANCEL: 3174 mIsDragging = false; 3175 break; 3176 } 3177 return true; 3178 } 3179 3180 public boolean isDragging() { 3181 return mIsDragging; 3182 } 3183 3184 void onHandleMoved() { 3185 hideActionPopupWindow(); 3186 } 3187 3188 public void onDetached() { 3189 hideActionPopupWindow(); 3190 } 3191 } 3192 3193 private class InsertionHandleView extends HandleView { 3194 private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000; 3195 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds 3196 3197 // Used to detect taps on the insertion handle, which will affect the ActionPopupWindow 3198 private float mDownPositionX, mDownPositionY; 3199 private Runnable mHider; 3200 3201 public InsertionHandleView(Drawable drawable) { 3202 super(drawable, drawable); 3203 } 3204 3205 @Override 3206 public void show() { 3207 super.show(); 3208 3209 final long durationSinceCutOrCopy = 3210 SystemClock.uptimeMillis() - TextView.LAST_CUT_OR_COPY_TIME; 3211 if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) { 3212 showActionPopupWindow(0); 3213 } 3214 3215 hideAfterDelay(); 3216 } 3217 3218 public void showWithActionPopup() { 3219 show(); 3220 showActionPopupWindow(0); 3221 } 3222 3223 private void hideAfterDelay() { 3224 if (mHider == null) { 3225 mHider = new Runnable() { 3226 public void run() { 3227 hide(); 3228 } 3229 }; 3230 } else { 3231 removeHiderCallback(); 3232 } 3233 mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT); 3234 } 3235 3236 private void removeHiderCallback() { 3237 if (mHider != null) { 3238 mTextView.removeCallbacks(mHider); 3239 } 3240 } 3241 3242 @Override 3243 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 3244 return drawable.getIntrinsicWidth() / 2; 3245 } 3246 3247 @Override 3248 public boolean onTouchEvent(MotionEvent ev) { 3249 final boolean result = super.onTouchEvent(ev); 3250 3251 switch (ev.getActionMasked()) { 3252 case MotionEvent.ACTION_DOWN: 3253 mDownPositionX = ev.getRawX(); 3254 mDownPositionY = ev.getRawY(); 3255 break; 3256 3257 case MotionEvent.ACTION_UP: 3258 if (!offsetHasBeenChanged()) { 3259 final float deltaX = mDownPositionX - ev.getRawX(); 3260 final float deltaY = mDownPositionY - ev.getRawY(); 3261 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 3262 3263 final ViewConfiguration viewConfiguration = ViewConfiguration.get( 3264 mTextView.getContext()); 3265 final int touchSlop = viewConfiguration.getScaledTouchSlop(); 3266 3267 if (distanceSquared < touchSlop * touchSlop) { 3268 if (mActionPopupWindow != null && mActionPopupWindow.isShowing()) { 3269 // Tapping on the handle dismisses the displayed action popup 3270 mActionPopupWindow.hide(); 3271 } else { 3272 showWithActionPopup(); 3273 } 3274 } 3275 } 3276 hideAfterDelay(); 3277 break; 3278 3279 case MotionEvent.ACTION_CANCEL: 3280 hideAfterDelay(); 3281 break; 3282 3283 default: 3284 break; 3285 } 3286 3287 return result; 3288 } 3289 3290 @Override 3291 public int getCurrentCursorOffset() { 3292 return mTextView.getSelectionStart(); 3293 } 3294 3295 @Override 3296 public void updateSelection(int offset) { 3297 Selection.setSelection((Spannable) mTextView.getText(), offset); 3298 } 3299 3300 @Override 3301 public void updatePosition(float x, float y) { 3302 positionAtCursorOffset(mTextView.getOffsetForPosition(x, y), false); 3303 } 3304 3305 @Override 3306 void onHandleMoved() { 3307 super.onHandleMoved(); 3308 removeHiderCallback(); 3309 } 3310 3311 @Override 3312 public void onDetached() { 3313 super.onDetached(); 3314 removeHiderCallback(); 3315 } 3316 } 3317 3318 private class SelectionStartHandleView extends HandleView { 3319 3320 public SelectionStartHandleView(Drawable drawableLtr, Drawable drawableRtl) { 3321 super(drawableLtr, drawableRtl); 3322 } 3323 3324 @Override 3325 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 3326 if (isRtlRun) { 3327 return drawable.getIntrinsicWidth() / 4; 3328 } else { 3329 return (drawable.getIntrinsicWidth() * 3) / 4; 3330 } 3331 } 3332 3333 @Override 3334 public int getCurrentCursorOffset() { 3335 return mTextView.getSelectionStart(); 3336 } 3337 3338 @Override 3339 public void updateSelection(int offset) { 3340 Selection.setSelection((Spannable) mTextView.getText(), offset, 3341 mTextView.getSelectionEnd()); 3342 updateDrawable(); 3343 } 3344 3345 @Override 3346 public void updatePosition(float x, float y) { 3347 int offset = mTextView.getOffsetForPosition(x, y); 3348 3349 // Handles can not cross and selection is at least one character 3350 final int selectionEnd = mTextView.getSelectionEnd(); 3351 if (offset >= selectionEnd) offset = Math.max(0, selectionEnd - 1); 3352 3353 positionAtCursorOffset(offset, false); 3354 } 3355 3356 public ActionPopupWindow getActionPopupWindow() { 3357 return mActionPopupWindow; 3358 } 3359 } 3360 3361 private class SelectionEndHandleView extends HandleView { 3362 3363 public SelectionEndHandleView(Drawable drawableLtr, Drawable drawableRtl) { 3364 super(drawableLtr, drawableRtl); 3365 } 3366 3367 @Override 3368 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 3369 if (isRtlRun) { 3370 return (drawable.getIntrinsicWidth() * 3) / 4; 3371 } else { 3372 return drawable.getIntrinsicWidth() / 4; 3373 } 3374 } 3375 3376 @Override 3377 public int getCurrentCursorOffset() { 3378 return mTextView.getSelectionEnd(); 3379 } 3380 3381 @Override 3382 public void updateSelection(int offset) { 3383 Selection.setSelection((Spannable) mTextView.getText(), 3384 mTextView.getSelectionStart(), offset); 3385 updateDrawable(); 3386 } 3387 3388 @Override 3389 public void updatePosition(float x, float y) { 3390 int offset = mTextView.getOffsetForPosition(x, y); 3391 3392 // Handles can not cross and selection is at least one character 3393 final int selectionStart = mTextView.getSelectionStart(); 3394 if (offset <= selectionStart) { 3395 offset = Math.min(selectionStart + 1, mTextView.getText().length()); 3396 } 3397 3398 positionAtCursorOffset(offset, false); 3399 } 3400 3401 public void setActionPopupWindow(ActionPopupWindow actionPopupWindow) { 3402 mActionPopupWindow = actionPopupWindow; 3403 } 3404 } 3405 3406 /** 3407 * A CursorController instance can be used to control a cursor in the text. 3408 */ 3409 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener { 3410 /** 3411 * Makes the cursor controller visible on screen. 3412 * See also {@link #hide()}. 3413 */ 3414 public void show(); 3415 3416 /** 3417 * Hide the cursor controller from screen. 3418 * See also {@link #show()}. 3419 */ 3420 public void hide(); 3421 3422 /** 3423 * Called when the view is detached from window. Perform house keeping task, such as 3424 * stopping Runnable thread that would otherwise keep a reference on the context, thus 3425 * preventing the activity from being recycled. 3426 */ 3427 public void onDetached(); 3428 } 3429 3430 private class InsertionPointCursorController implements CursorController { 3431 private InsertionHandleView mHandle; 3432 3433 public void show() { 3434 getHandle().show(); 3435 } 3436 3437 public void showWithActionPopup() { 3438 getHandle().showWithActionPopup(); 3439 } 3440 3441 public void hide() { 3442 if (mHandle != null) { 3443 mHandle.hide(); 3444 } 3445 } 3446 3447 public void onTouchModeChanged(boolean isInTouchMode) { 3448 if (!isInTouchMode) { 3449 hide(); 3450 } 3451 } 3452 3453 private InsertionHandleView getHandle() { 3454 if (mSelectHandleCenter == null) { 3455 mSelectHandleCenter = mTextView.getResources().getDrawable( 3456 mTextView.mTextSelectHandleRes); 3457 } 3458 if (mHandle == null) { 3459 mHandle = new InsertionHandleView(mSelectHandleCenter); 3460 } 3461 return mHandle; 3462 } 3463 3464 @Override 3465 public void onDetached() { 3466 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 3467 observer.removeOnTouchModeChangeListener(this); 3468 3469 if (mHandle != null) mHandle.onDetached(); 3470 } 3471 } 3472 3473 class SelectionModifierCursorController implements CursorController { 3474 private static final int DELAY_BEFORE_REPLACE_ACTION = 200; // milliseconds 3475 // The cursor controller handles, lazily created when shown. 3476 private SelectionStartHandleView mStartHandle; 3477 private SelectionEndHandleView mEndHandle; 3478 // The offsets of that last touch down event. Remembered to start selection there. 3479 private int mMinTouchOffset, mMaxTouchOffset; 3480 3481 // Double tap detection 3482 private long mPreviousTapUpTime = 0; 3483 private float mDownPositionX, mDownPositionY; 3484 private boolean mGestureStayedInTapRegion; 3485 3486 SelectionModifierCursorController() { 3487 resetTouchOffsets(); 3488 } 3489 3490 public void show() { 3491 if (mTextView.isInBatchEditMode()) { 3492 return; 3493 } 3494 initDrawables(); 3495 initHandles(); 3496 hideInsertionPointCursorController(); 3497 } 3498 3499 private void initDrawables() { 3500 if (mSelectHandleLeft == null) { 3501 mSelectHandleLeft = mTextView.getContext().getResources().getDrawable( 3502 mTextView.mTextSelectHandleLeftRes); 3503 } 3504 if (mSelectHandleRight == null) { 3505 mSelectHandleRight = mTextView.getContext().getResources().getDrawable( 3506 mTextView.mTextSelectHandleRightRes); 3507 } 3508 } 3509 3510 private void initHandles() { 3511 // Lazy object creation has to be done before updatePosition() is called. 3512 if (mStartHandle == null) { 3513 mStartHandle = new SelectionStartHandleView(mSelectHandleLeft, mSelectHandleRight); 3514 } 3515 if (mEndHandle == null) { 3516 mEndHandle = new SelectionEndHandleView(mSelectHandleRight, mSelectHandleLeft); 3517 } 3518 3519 mStartHandle.show(); 3520 mEndHandle.show(); 3521 3522 // Make sure both left and right handles share the same ActionPopupWindow (so that 3523 // moving any of the handles hides the action popup). 3524 mStartHandle.showActionPopupWindow(DELAY_BEFORE_REPLACE_ACTION); 3525 mEndHandle.setActionPopupWindow(mStartHandle.getActionPopupWindow()); 3526 3527 hideInsertionPointCursorController(); 3528 } 3529 3530 public void hide() { 3531 if (mStartHandle != null) mStartHandle.hide(); 3532 if (mEndHandle != null) mEndHandle.hide(); 3533 } 3534 3535 public void onTouchEvent(MotionEvent event) { 3536 // This is done even when the View does not have focus, so that long presses can start 3537 // selection and tap can move cursor from this tap position. 3538 switch (event.getActionMasked()) { 3539 case MotionEvent.ACTION_DOWN: 3540 final float x = event.getX(); 3541 final float y = event.getY(); 3542 3543 // Remember finger down position, to be able to start selection from there 3544 mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(x, y); 3545 3546 // Double tap detection 3547 if (mGestureStayedInTapRegion) { 3548 long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime; 3549 if (duration <= ViewConfiguration.getDoubleTapTimeout()) { 3550 final float deltaX = x - mDownPositionX; 3551 final float deltaY = y - mDownPositionY; 3552 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 3553 3554 ViewConfiguration viewConfiguration = ViewConfiguration.get( 3555 mTextView.getContext()); 3556 int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop(); 3557 boolean stayedInArea = distanceSquared < doubleTapSlop * doubleTapSlop; 3558 3559 if (stayedInArea && isPositionOnText(x, y)) { 3560 startSelectionActionMode(); 3561 mDiscardNextActionUp = true; 3562 } 3563 } 3564 } 3565 3566 mDownPositionX = x; 3567 mDownPositionY = y; 3568 mGestureStayedInTapRegion = true; 3569 break; 3570 3571 case MotionEvent.ACTION_POINTER_DOWN: 3572 case MotionEvent.ACTION_POINTER_UP: 3573 // Handle multi-point gestures. Keep min and max offset positions. 3574 // Only activated for devices that correctly handle multi-touch. 3575 if (mTextView.getContext().getPackageManager().hasSystemFeature( 3576 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) { 3577 updateMinAndMaxOffsets(event); 3578 } 3579 break; 3580 3581 case MotionEvent.ACTION_MOVE: 3582 if (mGestureStayedInTapRegion) { 3583 final float deltaX = event.getX() - mDownPositionX; 3584 final float deltaY = event.getY() - mDownPositionY; 3585 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 3586 3587 final ViewConfiguration viewConfiguration = ViewConfiguration.get( 3588 mTextView.getContext()); 3589 int doubleTapTouchSlop = viewConfiguration.getScaledDoubleTapTouchSlop(); 3590 3591 if (distanceSquared > doubleTapTouchSlop * doubleTapTouchSlop) { 3592 mGestureStayedInTapRegion = false; 3593 } 3594 } 3595 break; 3596 3597 case MotionEvent.ACTION_UP: 3598 mPreviousTapUpTime = SystemClock.uptimeMillis(); 3599 break; 3600 } 3601 } 3602 3603 /** 3604 * @param event 3605 */ 3606 private void updateMinAndMaxOffsets(MotionEvent event) { 3607 int pointerCount = event.getPointerCount(); 3608 for (int index = 0; index < pointerCount; index++) { 3609 int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index)); 3610 if (offset < mMinTouchOffset) mMinTouchOffset = offset; 3611 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset; 3612 } 3613 } 3614 3615 public int getMinTouchOffset() { 3616 return mMinTouchOffset; 3617 } 3618 3619 public int getMaxTouchOffset() { 3620 return mMaxTouchOffset; 3621 } 3622 3623 public void resetTouchOffsets() { 3624 mMinTouchOffset = mMaxTouchOffset = -1; 3625 } 3626 3627 /** 3628 * @return true iff this controller is currently used to move the selection start. 3629 */ 3630 public boolean isSelectionStartDragged() { 3631 return mStartHandle != null && mStartHandle.isDragging(); 3632 } 3633 3634 public void onTouchModeChanged(boolean isInTouchMode) { 3635 if (!isInTouchMode) { 3636 hide(); 3637 } 3638 } 3639 3640 @Override 3641 public void onDetached() { 3642 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 3643 observer.removeOnTouchModeChangeListener(this); 3644 3645 if (mStartHandle != null) mStartHandle.onDetached(); 3646 if (mEndHandle != null) mEndHandle.onDetached(); 3647 } 3648 } 3649 3650 private class CorrectionHighlighter { 3651 private final Path mPath = new Path(); 3652 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 3653 private int mStart, mEnd; 3654 private long mFadingStartTime; 3655 private RectF mTempRectF; 3656 private final static int FADE_OUT_DURATION = 400; 3657 3658 public CorrectionHighlighter() { 3659 mPaint.setCompatibilityScaling(mTextView.getResources().getCompatibilityInfo(). 3660 applicationScale); 3661 mPaint.setStyle(Paint.Style.FILL); 3662 } 3663 3664 public void highlight(CorrectionInfo info) { 3665 mStart = info.getOffset(); 3666 mEnd = mStart + info.getNewText().length(); 3667 mFadingStartTime = SystemClock.uptimeMillis(); 3668 3669 if (mStart < 0 || mEnd < 0) { 3670 stopAnimation(); 3671 } 3672 } 3673 3674 public void draw(Canvas canvas, int cursorOffsetVertical) { 3675 if (updatePath() && updatePaint()) { 3676 if (cursorOffsetVertical != 0) { 3677 canvas.translate(0, cursorOffsetVertical); 3678 } 3679 3680 canvas.drawPath(mPath, mPaint); 3681 3682 if (cursorOffsetVertical != 0) { 3683 canvas.translate(0, -cursorOffsetVertical); 3684 } 3685 invalidate(true); // TODO invalidate cursor region only 3686 } else { 3687 stopAnimation(); 3688 invalidate(false); // TODO invalidate cursor region only 3689 } 3690 } 3691 3692 private boolean updatePaint() { 3693 final long duration = SystemClock.uptimeMillis() - mFadingStartTime; 3694 if (duration > FADE_OUT_DURATION) return false; 3695 3696 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION; 3697 final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor); 3698 final int color = (mTextView.mHighlightColor & 0x00FFFFFF) + 3699 ((int) (highlightColorAlpha * coef) << 24); 3700 mPaint.setColor(color); 3701 return true; 3702 } 3703 3704 private boolean updatePath() { 3705 final Layout layout = mTextView.getLayout(); 3706 if (layout == null) return false; 3707 3708 // Update in case text is edited while the animation is run 3709 final int length = mTextView.getText().length(); 3710 int start = Math.min(length, mStart); 3711 int end = Math.min(length, mEnd); 3712 3713 mPath.reset(); 3714 layout.getSelectionPath(start, end, mPath); 3715 return true; 3716 } 3717 3718 private void invalidate(boolean delayed) { 3719 if (mTextView.getLayout() == null) return; 3720 3721 if (mTempRectF == null) mTempRectF = new RectF(); 3722 mPath.computeBounds(mTempRectF, false); 3723 3724 int left = mTextView.getCompoundPaddingLeft(); 3725 int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true); 3726 3727 if (delayed) { 3728 mTextView.postInvalidateOnAnimation( 3729 left + (int) mTempRectF.left, top + (int) mTempRectF.top, 3730 left + (int) mTempRectF.right, top + (int) mTempRectF.bottom); 3731 } else { 3732 mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top, 3733 (int) mTempRectF.right, (int) mTempRectF.bottom); 3734 } 3735 } 3736 3737 private void stopAnimation() { 3738 Editor.this.mCorrectionHighlighter = null; 3739 } 3740 } 3741 3742 private static class ErrorPopup extends PopupWindow { 3743 private boolean mAbove = false; 3744 private final TextView mView; 3745 private int mPopupInlineErrorBackgroundId = 0; 3746 private int mPopupInlineErrorAboveBackgroundId = 0; 3747 3748 ErrorPopup(TextView v, int width, int height) { 3749 super(v, width, height); 3750 mView = v; 3751 // Make sure the TextView has a background set as it will be used the first time it is 3752 // shown and positioned. Initialized with below background, which should have 3753 // dimensions identical to the above version for this to work (and is more likely). 3754 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 3755 com.android.internal.R.styleable.Theme_errorMessageBackground); 3756 mView.setBackgroundResource(mPopupInlineErrorBackgroundId); 3757 } 3758 3759 void fixDirection(boolean above) { 3760 mAbove = above; 3761 3762 if (above) { 3763 mPopupInlineErrorAboveBackgroundId = 3764 getResourceId(mPopupInlineErrorAboveBackgroundId, 3765 com.android.internal.R.styleable.Theme_errorMessageAboveBackground); 3766 } else { 3767 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 3768 com.android.internal.R.styleable.Theme_errorMessageBackground); 3769 } 3770 3771 mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId : 3772 mPopupInlineErrorBackgroundId); 3773 } 3774 3775 private int getResourceId(int currentId, int index) { 3776 if (currentId == 0) { 3777 TypedArray styledAttributes = mView.getContext().obtainStyledAttributes( 3778 R.styleable.Theme); 3779 currentId = styledAttributes.getResourceId(index, 0); 3780 styledAttributes.recycle(); 3781 } 3782 return currentId; 3783 } 3784 3785 @Override 3786 public void update(int x, int y, int w, int h, boolean force) { 3787 super.update(x, y, w, h, force); 3788 3789 boolean above = isAboveAnchor(); 3790 if (above != mAbove) { 3791 fixDirection(above); 3792 } 3793 } 3794 } 3795 3796 static class InputContentType { 3797 int imeOptions = EditorInfo.IME_NULL; 3798 String privateImeOptions; 3799 CharSequence imeActionLabel; 3800 int imeActionId; 3801 Bundle extras; 3802 OnEditorActionListener onEditorActionListener; 3803 boolean enterDown; 3804 } 3805 3806 static class InputMethodState { 3807 Rect mCursorRectInWindow = new Rect(); 3808 RectF mTmpRectF = new RectF(); 3809 float[] mTmpOffset = new float[2]; 3810 ExtractedTextRequest mExtractedTextRequest; 3811 final ExtractedText mExtractedText = new ExtractedText(); 3812 int mBatchEditNesting; 3813 boolean mCursorChanged; 3814 boolean mSelectionModeChanged; 3815 boolean mContentChanged; 3816 int mChangedStart, mChangedEnd, mChangedDelta; 3817 } 3818 3819 /** 3820 * @hide 3821 */ 3822 public static class UserDictionaryListener extends Handler { 3823 public TextView mTextView; 3824 public String mOriginalWord; 3825 public int mWordStart; 3826 public int mWordEnd; 3827 3828 public void waitForUserDictionaryAdded( 3829 TextView tv, String originalWord, int spanStart, int spanEnd) { 3830 mTextView = tv; 3831 mOriginalWord = originalWord; 3832 mWordStart = spanStart; 3833 mWordEnd = spanEnd; 3834 } 3835 3836 @Override 3837 public void handleMessage(Message msg) { 3838 switch(msg.what) { 3839 case 0: /* CODE_WORD_ADDED */ 3840 case 2: /* CODE_ALREADY_PRESENT */ 3841 if (!(msg.obj instanceof Bundle)) { 3842 Log.w(TAG, "Illegal message. Abort handling onUserDictionaryAdded."); 3843 return; 3844 } 3845 final Bundle bundle = (Bundle)msg.obj; 3846 final String originalWord = bundle.getString("originalWord"); 3847 final String addedWord = bundle.getString("word"); 3848 onUserDictionaryAdded(originalWord, addedWord); 3849 return; 3850 default: 3851 return; 3852 } 3853 } 3854 3855 private void onUserDictionaryAdded(String originalWord, String addedWord) { 3856 if (TextUtils.isEmpty(mOriginalWord) || TextUtils.isEmpty(addedWord)) { 3857 return; 3858 } 3859 if (mWordStart < 0 || mWordEnd >= mTextView.length()) { 3860 return; 3861 } 3862 if (!mOriginalWord.equals(originalWord)) { 3863 return; 3864 } 3865 if (originalWord.equals(addedWord)) { 3866 return; 3867 } 3868 final Editable editable = (Editable) mTextView.getText(); 3869 final String currentWord = editable.toString().substring(mWordStart, mWordEnd); 3870 if (!currentWord.equals(originalWord)) { 3871 return; 3872 } 3873 mTextView.replaceText_internal(mWordStart, mWordEnd, addedWord); 3874 // Move cursor at the end of the replaced word 3875 final int newCursorPosition = mWordStart + addedWord.length(); 3876 mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition); 3877 } 3878 } 3879} 3880