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