Editor.java revision 40fd5fac48836aa85d45f8b6c729baed3b625b13
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.annotation.IntDef; 21import android.annotation.Nullable; 22import android.app.PendingIntent; 23import android.app.PendingIntent.CanceledException; 24import android.content.ClipData; 25import android.content.ClipData.Item; 26import android.content.Context; 27import android.content.Intent; 28import android.content.UndoManager; 29import android.content.UndoOperation; 30import android.content.UndoOwner; 31import android.content.pm.PackageManager; 32import android.content.pm.ResolveInfo; 33import android.content.res.TypedArray; 34import android.graphics.Canvas; 35import android.graphics.Color; 36import android.graphics.Matrix; 37import android.graphics.Paint; 38import android.graphics.Path; 39import android.graphics.Rect; 40import android.graphics.RectF; 41import android.graphics.drawable.ColorDrawable; 42import android.graphics.drawable.Drawable; 43import android.os.Bundle; 44import android.os.Parcel; 45import android.os.Parcelable; 46import android.os.ParcelableParcel; 47import android.os.SystemClock; 48import android.provider.Settings; 49import android.text.DynamicLayout; 50import android.text.Editable; 51import android.text.InputFilter; 52import android.text.InputType; 53import android.text.Layout; 54import android.text.ParcelableSpan; 55import android.text.Selection; 56import android.text.SpanWatcher; 57import android.text.Spannable; 58import android.text.SpannableStringBuilder; 59import android.text.Spanned; 60import android.text.StaticLayout; 61import android.text.TextUtils; 62import android.text.method.KeyListener; 63import android.text.method.MetaKeyKeyListener; 64import android.text.method.MovementMethod; 65import android.text.method.WordIterator; 66import android.text.style.EasyEditSpan; 67import android.text.style.SuggestionRangeSpan; 68import android.text.style.SuggestionSpan; 69import android.text.style.TextAppearanceSpan; 70import android.text.style.URLSpan; 71import android.util.DisplayMetrics; 72import android.util.LocaleList; 73import android.util.Log; 74import android.util.SparseArray; 75import android.view.ActionMode; 76import android.view.ActionMode.Callback; 77import android.view.ContextMenu; 78import android.view.DisplayListCanvas; 79import android.view.DragEvent; 80import android.view.DropPermissions; 81import android.view.Gravity; 82import android.view.InputDevice; 83import android.view.LayoutInflater; 84import android.view.Menu; 85import android.view.MenuItem; 86import android.view.MotionEvent; 87import android.view.RenderNode; 88import android.view.SubMenu; 89import android.view.View; 90import android.view.View.DragShadowBuilder; 91import android.view.View.OnClickListener; 92import android.view.ViewConfiguration; 93import android.view.ViewGroup; 94import android.view.ViewGroup.LayoutParams; 95import android.view.ViewParent; 96import android.view.ViewTreeObserver; 97import android.view.WindowManager; 98import android.view.accessibility.AccessibilityNodeInfo; 99import android.view.inputmethod.CorrectionInfo; 100import android.view.inputmethod.CursorAnchorInfo; 101import android.view.inputmethod.EditorInfo; 102import android.view.inputmethod.ExtractedText; 103import android.view.inputmethod.ExtractedTextRequest; 104import android.view.inputmethod.InputConnection; 105import android.view.inputmethod.InputMethodManager; 106import android.widget.AdapterView.OnItemClickListener; 107import android.widget.TextView.Drawables; 108import android.widget.TextView.OnEditorActionListener; 109 110import com.android.internal.annotations.VisibleForTesting; 111import com.android.internal.util.ArrayUtils; 112import com.android.internal.util.GrowingArrayUtils; 113import com.android.internal.util.Preconditions; 114import com.android.internal.widget.EditableInputConnection; 115 116import java.lang.annotation.Retention; 117import java.lang.annotation.RetentionPolicy; 118import java.text.BreakIterator; 119import java.util.Arrays; 120import java.util.Comparator; 121import java.util.HashMap; 122import java.util.List; 123 124 125/** 126 * Helper class used by TextView to handle editable text views. 127 * 128 * @hide 129 */ 130public class Editor { 131 private static final String TAG = "Editor"; 132 private static final boolean DEBUG_UNDO = false; 133 134 static final int BLINK = 500; 135 private static final float[] TEMP_POSITION = new float[2]; 136 private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20; 137 private static final float LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS = 0.5f; 138 private static final int UNSET_X_VALUE = -1; 139 private static final int UNSET_LINE = -1; 140 // Tag used when the Editor maintains its own separate UndoManager. 141 private static final String UNDO_OWNER_TAG = "Editor"; 142 143 // Ordering constants used to place the Action Mode or context menu items in their menu. 144 private static final int MENU_ITEM_ORDER_UNDO = 1; 145 private static final int MENU_ITEM_ORDER_REDO = 2; 146 private static final int MENU_ITEM_ORDER_CUT = 3; 147 private static final int MENU_ITEM_ORDER_COPY = 4; 148 private static final int MENU_ITEM_ORDER_PASTE = 5; 149 private static final int MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT = 6; 150 private static final int MENU_ITEM_ORDER_SHARE = 7; 151 private static final int MENU_ITEM_ORDER_SELECT_ALL = 8; 152 private static final int MENU_ITEM_ORDER_REPLACE = 9; 153 private static final int MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START = 10; 154 155 // Each Editor manages its own undo stack. 156 private final UndoManager mUndoManager = new UndoManager(); 157 private UndoOwner mUndoOwner = mUndoManager.getOwner(UNDO_OWNER_TAG, this); 158 final UndoInputFilter mUndoInputFilter = new UndoInputFilter(this); 159 boolean mAllowUndo = true; 160 161 // Cursor Controllers. 162 InsertionPointCursorController mInsertionPointCursorController; 163 SelectionModifierCursorController mSelectionModifierCursorController; 164 // Action mode used when text is selected or when actions on an insertion cursor are triggered. 165 ActionMode mTextActionMode; 166 boolean mInsertionControllerEnabled; 167 boolean mSelectionControllerEnabled; 168 169 // Used to highlight a word when it is corrected by the IME 170 CorrectionHighlighter mCorrectionHighlighter; 171 172 InputContentType mInputContentType; 173 InputMethodState mInputMethodState; 174 175 private static class TextRenderNode { 176 RenderNode renderNode; 177 boolean isDirty; 178 public TextRenderNode(String name) { 179 isDirty = true; 180 renderNode = RenderNode.create(name, null); 181 } 182 boolean needsRecord() { return isDirty || !renderNode.isValid(); } 183 } 184 TextRenderNode[] mTextRenderNodes; 185 186 boolean mFrozenWithFocus; 187 boolean mSelectionMoved; 188 boolean mTouchFocusSelected; 189 190 KeyListener mKeyListener; 191 int mInputType = EditorInfo.TYPE_NULL; 192 193 boolean mDiscardNextActionUp; 194 boolean mIgnoreActionUpEvent; 195 private boolean mIgnoreNextMouseActionUpOrDown; 196 197 long mShowCursor; 198 Blink mBlink; 199 200 boolean mCursorVisible = true; 201 boolean mSelectAllOnFocus; 202 boolean mTextIsSelectable; 203 204 CharSequence mError; 205 boolean mErrorWasChanged; 206 ErrorPopup mErrorPopup; 207 208 /** 209 * This flag is set if the TextView tries to display an error before it 210 * is attached to the window (so its position is still unknown). 211 * It causes the error to be shown later, when onAttachedToWindow() 212 * is called. 213 */ 214 boolean mShowErrorAfterAttach; 215 216 boolean mInBatchEditControllers; 217 boolean mShowSoftInputOnFocus = true; 218 private boolean mPreserveSelection; 219 boolean mTemporaryDetach; 220 221 boolean mIsBeingLongClicked; 222 223 SuggestionsPopupWindow mSuggestionsPopupWindow; 224 SuggestionRangeSpan mSuggestionRangeSpan; 225 Runnable mShowSuggestionRunnable; 226 227 final Drawable[] mCursorDrawable = new Drawable[2]; 228 int mCursorCount; // Current number of used mCursorDrawable: 0 (resource=0), 1 or 2 (split) 229 230 private Drawable mSelectHandleLeft; 231 private Drawable mSelectHandleRight; 232 private Drawable mSelectHandleCenter; 233 234 // Global listener that detects changes in the global position of the TextView 235 private PositionListener mPositionListener; 236 237 float mLastDownPositionX, mLastDownPositionY; 238 private float mContextMenuAnchorX, mContextMenuAnchorY; 239 Callback mCustomSelectionActionModeCallback; 240 Callback mCustomInsertionActionModeCallback; 241 242 // Set when this TextView gained focus with some text selected. Will start selection mode. 243 boolean mCreatedWithASelection; 244 245 // Indicates the current tap state (first tap, double tap, or triple click). 246 private int mTapState = TAP_STATE_INITIAL; 247 private long mLastTouchUpTime = 0; 248 private static final int TAP_STATE_INITIAL = 0; 249 private static final int TAP_STATE_FIRST_TAP = 1; 250 private static final int TAP_STATE_DOUBLE_TAP = 2; 251 // Only for mouse input. 252 private static final int TAP_STATE_TRIPLE_CLICK = 3; 253 254 // The button state as of the last time #onTouchEvent is called. 255 private int mLastButtonState; 256 257 private Runnable mInsertionActionModeRunnable; 258 259 // The span controller helps monitoring the changes to which the Editor needs to react: 260 // - EasyEditSpans, for which we have some UI to display on attach and on hide 261 // - SelectionSpans, for which we need to call updateSelection if an IME is attached 262 private SpanController mSpanController; 263 264 WordIterator mWordIterator; 265 SpellChecker mSpellChecker; 266 267 // This word iterator is set with text and used to determine word boundaries 268 // when a user is selecting text. 269 private WordIterator mWordIteratorWithText; 270 // Indicate that the text in the word iterator needs to be updated. 271 private boolean mUpdateWordIteratorText; 272 273 private Rect mTempRect; 274 275 private TextView mTextView; 276 277 final ProcessTextIntentActionsHandler mProcessTextIntentActionsHandler; 278 279 final CursorAnchorInfoNotifier mCursorAnchorInfoNotifier = new CursorAnchorInfoNotifier(); 280 281 private final Runnable mShowFloatingToolbar = new Runnable() { 282 @Override 283 public void run() { 284 if (mTextActionMode != null) { 285 mTextActionMode.hide(0); // hide off. 286 } 287 } 288 }; 289 290 boolean mIsInsertionActionModeStartPending = false; 291 292 private final SuggestionHelper mSuggestionHelper = new SuggestionHelper(); 293 private SuggestionInfo[] mSuggestionInfosInContextMenu; 294 295 Editor(TextView textView) { 296 mTextView = textView; 297 // Synchronize the filter list, which places the undo input filter at the end. 298 mTextView.setFilters(mTextView.getFilters()); 299 mProcessTextIntentActionsHandler = new ProcessTextIntentActionsHandler(this); 300 } 301 302 ParcelableParcel saveInstanceState() { 303 ParcelableParcel state = new ParcelableParcel(getClass().getClassLoader()); 304 Parcel parcel = state.getParcel(); 305 mUndoManager.saveInstanceState(parcel); 306 mUndoInputFilter.saveInstanceState(parcel); 307 return state; 308 } 309 310 void restoreInstanceState(ParcelableParcel state) { 311 Parcel parcel = state.getParcel(); 312 mUndoManager.restoreInstanceState(parcel, state.getClassLoader()); 313 mUndoInputFilter.restoreInstanceState(parcel); 314 // Re-associate this object as the owner of undo state. 315 mUndoOwner = mUndoManager.getOwner(UNDO_OWNER_TAG, this); 316 } 317 318 /** 319 * Forgets all undo and redo operations for this Editor. 320 */ 321 void forgetUndoRedo() { 322 UndoOwner[] owners = { mUndoOwner }; 323 mUndoManager.forgetUndos(owners, -1 /* all */); 324 mUndoManager.forgetRedos(owners, -1 /* all */); 325 } 326 327 boolean canUndo() { 328 UndoOwner[] owners = { mUndoOwner }; 329 return mAllowUndo && mUndoManager.countUndos(owners) > 0; 330 } 331 332 boolean canRedo() { 333 UndoOwner[] owners = { mUndoOwner }; 334 return mAllowUndo && mUndoManager.countRedos(owners) > 0; 335 } 336 337 void undo() { 338 if (!mAllowUndo) { 339 return; 340 } 341 UndoOwner[] owners = { mUndoOwner }; 342 mUndoManager.undo(owners, 1); // Undo 1 action. 343 } 344 345 void redo() { 346 if (!mAllowUndo) { 347 return; 348 } 349 UndoOwner[] owners = { mUndoOwner }; 350 mUndoManager.redo(owners, 1); // Redo 1 action. 351 } 352 353 void replace() { 354 int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2; 355 Selection.setSelection((Spannable) mTextView.getText(), middle); 356 showSuggestions(); 357 } 358 359 void onAttachedToWindow() { 360 if (mShowErrorAfterAttach) { 361 showError(); 362 mShowErrorAfterAttach = false; 363 } 364 mTemporaryDetach = false; 365 366 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 367 // No need to create the controller. 368 // The get method will add the listener on controller creation. 369 if (mInsertionPointCursorController != null) { 370 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 371 } 372 if (mSelectionModifierCursorController != null) { 373 mSelectionModifierCursorController.resetTouchOffsets(); 374 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 375 } 376 updateSpellCheckSpans(0, mTextView.getText().length(), 377 true /* create the spell checker if needed */); 378 379 if (mTextView.getSelectionStart() != mTextView.getSelectionEnd()) { 380 // We had an active selection from before, start the selection mode. 381 startSelectionActionMode(); 382 } 383 384 getPositionListener().addSubscriber(mCursorAnchorInfoNotifier, true); 385 resumeBlink(); 386 } 387 388 void onDetachedFromWindow() { 389 getPositionListener().removeSubscriber(mCursorAnchorInfoNotifier); 390 391 if (mError != null) { 392 hideError(); 393 } 394 395 suspendBlink(); 396 397 if (mInsertionPointCursorController != null) { 398 mInsertionPointCursorController.onDetached(); 399 } 400 401 if (mSelectionModifierCursorController != null) { 402 mSelectionModifierCursorController.onDetached(); 403 } 404 405 if (mShowSuggestionRunnable != null) { 406 mTextView.removeCallbacks(mShowSuggestionRunnable); 407 } 408 409 // Cancel the single tap delayed runnable. 410 if (mInsertionActionModeRunnable != null) { 411 mTextView.removeCallbacks(mInsertionActionModeRunnable); 412 } 413 414 mTextView.removeCallbacks(mShowFloatingToolbar); 415 416 discardTextDisplayLists(); 417 418 if (mSpellChecker != null) { 419 mSpellChecker.closeSession(); 420 // Forces the creation of a new SpellChecker next time this window is created. 421 // Will handle the cases where the settings has been changed in the meantime. 422 mSpellChecker = null; 423 } 424 425 hideCursorAndSpanControllers(); 426 stopTextActionModeWithPreservingSelection(); 427 mTemporaryDetach = false; 428 } 429 430 private void discardTextDisplayLists() { 431 if (mTextRenderNodes != null) { 432 for (int i = 0; i < mTextRenderNodes.length; i++) { 433 RenderNode displayList = mTextRenderNodes[i] != null 434 ? mTextRenderNodes[i].renderNode : null; 435 if (displayList != null && displayList.isValid()) { 436 displayList.discardDisplayList(); 437 } 438 } 439 } 440 } 441 442 private void showError() { 443 if (mTextView.getWindowToken() == null) { 444 mShowErrorAfterAttach = true; 445 return; 446 } 447 448 if (mErrorPopup == null) { 449 LayoutInflater inflater = LayoutInflater.from(mTextView.getContext()); 450 final TextView err = (TextView) inflater.inflate( 451 com.android.internal.R.layout.textview_hint, null); 452 453 final float scale = mTextView.getResources().getDisplayMetrics().density; 454 mErrorPopup = new ErrorPopup(err, (int)(200 * scale + 0.5f), (int)(50 * scale + 0.5f)); 455 mErrorPopup.setFocusable(false); 456 // The user is entering text, so the input method is needed. We 457 // don't want the popup to be displayed on top of it. 458 mErrorPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); 459 } 460 461 TextView tv = (TextView) mErrorPopup.getContentView(); 462 chooseSize(mErrorPopup, mError, tv); 463 tv.setText(mError); 464 465 mErrorPopup.showAsDropDown(mTextView, getErrorX(), getErrorY()); 466 mErrorPopup.fixDirection(mErrorPopup.isAboveAnchor()); 467 } 468 469 public void setError(CharSequence error, Drawable icon) { 470 mError = TextUtils.stringOrSpannedString(error); 471 mErrorWasChanged = true; 472 473 if (mError == null) { 474 setErrorIcon(null); 475 if (mErrorPopup != null) { 476 if (mErrorPopup.isShowing()) { 477 mErrorPopup.dismiss(); 478 } 479 480 mErrorPopup = null; 481 } 482 mShowErrorAfterAttach = false; 483 } else { 484 setErrorIcon(icon); 485 if (mTextView.isFocused()) { 486 showError(); 487 } 488 } 489 } 490 491 private void setErrorIcon(Drawable icon) { 492 Drawables dr = mTextView.mDrawables; 493 if (dr == null) { 494 mTextView.mDrawables = dr = new Drawables(mTextView.getContext()); 495 } 496 dr.setErrorDrawable(icon, mTextView); 497 498 mTextView.resetResolvedDrawables(); 499 mTextView.invalidate(); 500 mTextView.requestLayout(); 501 } 502 503 private void hideError() { 504 if (mErrorPopup != null) { 505 if (mErrorPopup.isShowing()) { 506 mErrorPopup.dismiss(); 507 } 508 } 509 510 mShowErrorAfterAttach = false; 511 } 512 513 /** 514 * Returns the X offset to make the pointy top of the error point 515 * at the middle of the error icon. 516 */ 517 private int getErrorX() { 518 /* 519 * The "25" is the distance between the point and the right edge 520 * of the background 521 */ 522 final float scale = mTextView.getResources().getDisplayMetrics().density; 523 524 final Drawables dr = mTextView.mDrawables; 525 526 final int layoutDirection = mTextView.getLayoutDirection(); 527 int errorX; 528 int offset; 529 switch (layoutDirection) { 530 default: 531 case View.LAYOUT_DIRECTION_LTR: 532 offset = - (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f); 533 errorX = mTextView.getWidth() - mErrorPopup.getWidth() - 534 mTextView.getPaddingRight() + offset; 535 break; 536 case View.LAYOUT_DIRECTION_RTL: 537 offset = (dr != null ? dr.mDrawableSizeLeft : 0) / 2 - (int) (25 * scale + 0.5f); 538 errorX = mTextView.getPaddingLeft() + offset; 539 break; 540 } 541 return errorX; 542 } 543 544 /** 545 * Returns the Y offset to make the pointy top of the error point 546 * at the bottom of the error icon. 547 */ 548 private int getErrorY() { 549 /* 550 * Compound, not extended, because the icon is not clipped 551 * if the text height is smaller. 552 */ 553 final int compoundPaddingTop = mTextView.getCompoundPaddingTop(); 554 int vspace = mTextView.getBottom() - mTextView.getTop() - 555 mTextView.getCompoundPaddingBottom() - compoundPaddingTop; 556 557 final Drawables dr = mTextView.mDrawables; 558 559 final int layoutDirection = mTextView.getLayoutDirection(); 560 int height; 561 switch (layoutDirection) { 562 default: 563 case View.LAYOUT_DIRECTION_LTR: 564 height = (dr != null ? dr.mDrawableHeightRight : 0); 565 break; 566 case View.LAYOUT_DIRECTION_RTL: 567 height = (dr != null ? dr.mDrawableHeightLeft : 0); 568 break; 569 } 570 571 int icontop = compoundPaddingTop + (vspace - height) / 2; 572 573 /* 574 * The "2" is the distance between the point and the top edge 575 * of the background. 576 */ 577 final float scale = mTextView.getResources().getDisplayMetrics().density; 578 return icontop + height - mTextView.getHeight() - (int) (2 * scale + 0.5f); 579 } 580 581 void createInputContentTypeIfNeeded() { 582 if (mInputContentType == null) { 583 mInputContentType = new InputContentType(); 584 } 585 } 586 587 void createInputMethodStateIfNeeded() { 588 if (mInputMethodState == null) { 589 mInputMethodState = new InputMethodState(); 590 } 591 } 592 593 boolean isCursorVisible() { 594 // The default value is true, even when there is no associated Editor 595 return mCursorVisible && mTextView.isTextEditable(); 596 } 597 598 void prepareCursorControllers() { 599 boolean windowSupportsHandles = false; 600 601 ViewGroup.LayoutParams params = mTextView.getRootView().getLayoutParams(); 602 if (params instanceof WindowManager.LayoutParams) { 603 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params; 604 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW 605 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW; 606 } 607 608 boolean enabled = windowSupportsHandles && mTextView.getLayout() != null; 609 mInsertionControllerEnabled = enabled && isCursorVisible(); 610 mSelectionControllerEnabled = enabled && mTextView.textCanBeSelected(); 611 612 if (!mInsertionControllerEnabled) { 613 hideInsertionPointCursorController(); 614 if (mInsertionPointCursorController != null) { 615 mInsertionPointCursorController.onDetached(); 616 mInsertionPointCursorController = null; 617 } 618 } 619 620 if (!mSelectionControllerEnabled) { 621 stopTextActionMode(); 622 if (mSelectionModifierCursorController != null) { 623 mSelectionModifierCursorController.onDetached(); 624 mSelectionModifierCursorController = null; 625 } 626 } 627 } 628 629 void hideInsertionPointCursorController() { 630 if (mInsertionPointCursorController != null) { 631 mInsertionPointCursorController.hide(); 632 } 633 } 634 635 /** 636 * Hides the insertion and span controllers. 637 */ 638 void hideCursorAndSpanControllers() { 639 hideCursorControllers(); 640 hideSpanControllers(); 641 } 642 643 private void hideSpanControllers() { 644 if (mSpanController != null) { 645 mSpanController.hide(); 646 } 647 } 648 649 private void hideCursorControllers() { 650 // When mTextView is not ExtractEditText, we need to distinguish two kinds of focus-lost. 651 // One is the true focus lost where suggestions pop-up (if any) should be dismissed, and the 652 // other is an side effect of showing the suggestions pop-up itself. We use isShowingUp() 653 // to distinguish one from the other. 654 if (mSuggestionsPopupWindow != null && ((mTextView.isInExtractedMode()) || 655 !mSuggestionsPopupWindow.isShowingUp())) { 656 // Should be done before hide insertion point controller since it triggers a show of it 657 mSuggestionsPopupWindow.hide(); 658 } 659 hideInsertionPointCursorController(); 660 } 661 662 /** 663 * Create new SpellCheckSpans on the modified region. 664 */ 665 private void updateSpellCheckSpans(int start, int end, boolean createSpellChecker) { 666 // Remove spans whose adjacent characters are text not punctuation 667 mTextView.removeAdjacentSuggestionSpans(start); 668 mTextView.removeAdjacentSuggestionSpans(end); 669 670 if (mTextView.isTextEditable() && mTextView.isSuggestionsEnabled() && 671 !(mTextView.isInExtractedMode())) { 672 if (mSpellChecker == null && createSpellChecker) { 673 mSpellChecker = new SpellChecker(mTextView); 674 } 675 if (mSpellChecker != null) { 676 mSpellChecker.spellCheck(start, end); 677 } 678 } 679 } 680 681 void onScreenStateChanged(int screenState) { 682 switch (screenState) { 683 case View.SCREEN_STATE_ON: 684 resumeBlink(); 685 break; 686 case View.SCREEN_STATE_OFF: 687 suspendBlink(); 688 break; 689 } 690 } 691 692 private void suspendBlink() { 693 if (mBlink != null) { 694 mBlink.cancel(); 695 } 696 } 697 698 private void resumeBlink() { 699 if (mBlink != null) { 700 mBlink.uncancel(); 701 makeBlink(); 702 } 703 } 704 705 void adjustInputType(boolean password, boolean passwordInputType, 706 boolean webPasswordInputType, boolean numberPasswordInputType) { 707 // mInputType has been set from inputType, possibly modified by mInputMethod. 708 // Specialize mInputType to [web]password if we have a text class and the original input 709 // type was a password. 710 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 711 if (password || passwordInputType) { 712 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 713 | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD; 714 } 715 if (webPasswordInputType) { 716 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 717 | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD; 718 } 719 } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) { 720 if (numberPasswordInputType) { 721 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 722 | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD; 723 } 724 } 725 } 726 727 private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) { 728 int wid = tv.getPaddingLeft() + tv.getPaddingRight(); 729 int ht = tv.getPaddingTop() + tv.getPaddingBottom(); 730 731 int defaultWidthInPixels = mTextView.getResources().getDimensionPixelSize( 732 com.android.internal.R.dimen.textview_error_popup_default_width); 733 Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels, 734 Layout.Alignment.ALIGN_NORMAL, 1, 0, true); 735 float max = 0; 736 for (int i = 0; i < l.getLineCount(); i++) { 737 max = Math.max(max, l.getLineWidth(i)); 738 } 739 740 /* 741 * Now set the popup size to be big enough for the text plus the border capped 742 * to DEFAULT_MAX_POPUP_WIDTH 743 */ 744 pop.setWidth(wid + (int) Math.ceil(max)); 745 pop.setHeight(ht + l.getHeight()); 746 } 747 748 void setFrame() { 749 if (mErrorPopup != null) { 750 TextView tv = (TextView) mErrorPopup.getContentView(); 751 chooseSize(mErrorPopup, mError, tv); 752 mErrorPopup.update(mTextView, getErrorX(), getErrorY(), 753 mErrorPopup.getWidth(), mErrorPopup.getHeight()); 754 } 755 } 756 757 private int getWordStart(int offset) { 758 // FIXME - For this and similar methods we're not doing anything to check if there's 759 // a LocaleSpan in the text, this may be something we should try handling or checking for. 760 int retOffset = getWordIteratorWithText().prevBoundary(offset); 761 if (getWordIteratorWithText().isOnPunctuation(retOffset)) { 762 // On punctuation boundary or within group of punctuation, find punctuation start. 763 retOffset = getWordIteratorWithText().getPunctuationBeginning(offset); 764 } else { 765 // Not on a punctuation boundary, find the word start. 766 retOffset = getWordIteratorWithText().getPrevWordBeginningOnTwoWordsBoundary(offset); 767 } 768 if (retOffset == BreakIterator.DONE) { 769 return offset; 770 } 771 return retOffset; 772 } 773 774 private int getWordEnd(int offset) { 775 int retOffset = getWordIteratorWithText().nextBoundary(offset); 776 if (getWordIteratorWithText().isAfterPunctuation(retOffset)) { 777 // On punctuation boundary or within group of punctuation, find punctuation end. 778 retOffset = getWordIteratorWithText().getPunctuationEnd(offset); 779 } else { 780 // Not on a punctuation boundary, find the word end. 781 retOffset = getWordIteratorWithText().getNextWordEndOnTwoWordBoundary(offset); 782 } 783 if (retOffset == BreakIterator.DONE) { 784 return offset; 785 } 786 return retOffset; 787 } 788 789 private boolean needsToSelectAllToSelectWordOrParagraph() { 790 if (mTextView.hasPasswordTransformationMethod()) { 791 // Always select all on a password field. 792 // Cut/copy menu entries are not available for passwords, but being able to select all 793 // is however useful to delete or paste to replace the entire content. 794 return true; 795 } 796 797 int inputType = mTextView.getInputType(); 798 int klass = inputType & InputType.TYPE_MASK_CLASS; 799 int variation = inputType & InputType.TYPE_MASK_VARIATION; 800 801 // Specific text field types: select the entire text for these 802 if (klass == InputType.TYPE_CLASS_NUMBER || 803 klass == InputType.TYPE_CLASS_PHONE || 804 klass == InputType.TYPE_CLASS_DATETIME || 805 variation == InputType.TYPE_TEXT_VARIATION_URI || 806 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 807 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS || 808 variation == InputType.TYPE_TEXT_VARIATION_FILTER) { 809 return true; 810 } 811 return false; 812 } 813 814 /** 815 * Adjusts selection to the word under last touch offset. Return true if the operation was 816 * successfully performed. 817 */ 818 private boolean selectCurrentWord() { 819 if (!mTextView.canSelectText()) { 820 return false; 821 } 822 823 if (needsToSelectAllToSelectWordOrParagraph()) { 824 return mTextView.selectAllText(); 825 } 826 827 long lastTouchOffsets = getLastTouchOffsets(); 828 final int minOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets); 829 final int maxOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets); 830 831 // Safety check in case standard touch event handling has been bypassed 832 if (minOffset < 0 || minOffset > mTextView.getText().length()) return false; 833 if (maxOffset < 0 || maxOffset > mTextView.getText().length()) return false; 834 835 int selectionStart, selectionEnd; 836 837 // If a URLSpan (web address, email, phone...) is found at that position, select it. 838 URLSpan[] urlSpans = ((Spanned) mTextView.getText()). 839 getSpans(minOffset, maxOffset, URLSpan.class); 840 if (urlSpans.length >= 1) { 841 URLSpan urlSpan = urlSpans[0]; 842 selectionStart = ((Spanned) mTextView.getText()).getSpanStart(urlSpan); 843 selectionEnd = ((Spanned) mTextView.getText()).getSpanEnd(urlSpan); 844 } else { 845 // FIXME - We should check if there's a LocaleSpan in the text, this may be 846 // something we should try handling or checking for. 847 final WordIterator wordIterator = getWordIterator(); 848 wordIterator.setCharSequence(mTextView.getText(), minOffset, maxOffset); 849 850 selectionStart = wordIterator.getBeginning(minOffset); 851 selectionEnd = wordIterator.getEnd(maxOffset); 852 853 if (selectionStart == BreakIterator.DONE || selectionEnd == BreakIterator.DONE || 854 selectionStart == selectionEnd) { 855 // Possible when the word iterator does not properly handle the text's language 856 long range = getCharClusterRange(minOffset); 857 selectionStart = TextUtils.unpackRangeStartFromLong(range); 858 selectionEnd = TextUtils.unpackRangeEndFromLong(range); 859 } 860 } 861 862 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd); 863 return selectionEnd > selectionStart; 864 } 865 866 /** 867 * Adjusts selection to the paragraph under last touch offset. Return true if the operation was 868 * successfully performed. 869 */ 870 private boolean selectCurrentParagraph() { 871 if (!mTextView.canSelectText()) { 872 return false; 873 } 874 875 if (needsToSelectAllToSelectWordOrParagraph()) { 876 return mTextView.selectAllText(); 877 } 878 879 long lastTouchOffsets = getLastTouchOffsets(); 880 final int minLastTouchOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets); 881 final int maxLastTouchOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets); 882 883 final long paragraphsRange = getParagraphsRange(minLastTouchOffset, maxLastTouchOffset); 884 final int start = TextUtils.unpackRangeStartFromLong(paragraphsRange); 885 final int end = TextUtils.unpackRangeEndFromLong(paragraphsRange); 886 if (start < end) { 887 Selection.setSelection((Spannable) mTextView.getText(), start, end); 888 return true; 889 } 890 return false; 891 } 892 893 /** 894 * Get the minimum range of paragraphs that contains startOffset and endOffset. 895 */ 896 private long getParagraphsRange(int startOffset, int endOffset) { 897 final Layout layout = mTextView.getLayout(); 898 if (layout == null) { 899 return TextUtils.packRangeInLong(-1, -1); 900 } 901 final CharSequence text = mTextView.getText(); 902 int minLine = layout.getLineForOffset(startOffset); 903 // Search paragraph start. 904 while (minLine > 0) { 905 final int prevLineEndOffset = layout.getLineEnd(minLine - 1); 906 if (text.charAt(prevLineEndOffset - 1) == '\n') { 907 break; 908 } 909 minLine--; 910 } 911 int maxLine = layout.getLineForOffset(endOffset); 912 // Search paragraph end. 913 while (maxLine < layout.getLineCount() - 1) { 914 final int lineEndOffset = layout.getLineEnd(maxLine); 915 if (text.charAt(lineEndOffset - 1) == '\n') { 916 break; 917 } 918 maxLine++; 919 } 920 return TextUtils.packRangeInLong(layout.getLineStart(minLine), layout.getLineEnd(maxLine)); 921 } 922 923 void onLocaleChanged() { 924 // Will be re-created on demand in getWordIterator with the proper new locale 925 mWordIterator = null; 926 mWordIteratorWithText = null; 927 } 928 929 /** 930 * @hide 931 */ 932 public WordIterator getWordIterator() { 933 if (mWordIterator == null) { 934 mWordIterator = new WordIterator(mTextView.getTextServicesLocale()); 935 } 936 return mWordIterator; 937 } 938 939 private WordIterator getWordIteratorWithText() { 940 if (mWordIteratorWithText == null) { 941 mWordIteratorWithText = new WordIterator(mTextView.getTextServicesLocale()); 942 mUpdateWordIteratorText = true; 943 } 944 if (mUpdateWordIteratorText) { 945 // FIXME - Shouldn't copy all of the text as only the area of the text relevant 946 // to the user's selection is needed. A possible solution would be to 947 // copy some number N of characters near the selection and then when the 948 // user approaches N then we'd do another copy of the next N characters. 949 CharSequence text = mTextView.getText(); 950 mWordIteratorWithText.setCharSequence(text, 0, text.length()); 951 mUpdateWordIteratorText = false; 952 } 953 return mWordIteratorWithText; 954 } 955 956 private int getNextCursorOffset(int offset, boolean findAfterGivenOffset) { 957 final Layout layout = mTextView.getLayout(); 958 if (layout == null) return offset; 959 return findAfterGivenOffset == layout.isRtlCharAt(offset) ? 960 layout.getOffsetToLeftOf(offset) : layout.getOffsetToRightOf(offset); 961 } 962 963 private long getCharClusterRange(int offset) { 964 final int textLength = mTextView.getText().length(); 965 if (offset < textLength) { 966 final int clusterEndOffset = getNextCursorOffset(offset, true); 967 return TextUtils.packRangeInLong( 968 getNextCursorOffset(clusterEndOffset, false), clusterEndOffset); 969 } 970 if (offset - 1 >= 0) { 971 final int clusterStartOffset = getNextCursorOffset(offset, false); 972 return TextUtils.packRangeInLong(clusterStartOffset, 973 getNextCursorOffset(clusterStartOffset, true)); 974 } 975 return TextUtils.packRangeInLong(offset, offset); 976 } 977 978 private boolean touchPositionIsInSelection() { 979 int selectionStart = mTextView.getSelectionStart(); 980 int selectionEnd = mTextView.getSelectionEnd(); 981 982 if (selectionStart == selectionEnd) { 983 return false; 984 } 985 986 if (selectionStart > selectionEnd) { 987 int tmp = selectionStart; 988 selectionStart = selectionEnd; 989 selectionEnd = tmp; 990 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd); 991 } 992 993 SelectionModifierCursorController selectionController = getSelectionController(); 994 int minOffset = selectionController.getMinTouchOffset(); 995 int maxOffset = selectionController.getMaxTouchOffset(); 996 997 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd)); 998 } 999 1000 private PositionListener getPositionListener() { 1001 if (mPositionListener == null) { 1002 mPositionListener = new PositionListener(); 1003 } 1004 return mPositionListener; 1005 } 1006 1007 private interface TextViewPositionListener { 1008 public void updatePosition(int parentPositionX, int parentPositionY, 1009 boolean parentPositionChanged, boolean parentScrolled); 1010 } 1011 1012 private boolean isPositionVisible(final float positionX, final float positionY) { 1013 synchronized (TEMP_POSITION) { 1014 final float[] position = TEMP_POSITION; 1015 position[0] = positionX; 1016 position[1] = positionY; 1017 View view = mTextView; 1018 1019 while (view != null) { 1020 if (view != mTextView) { 1021 // Local scroll is already taken into account in positionX/Y 1022 position[0] -= view.getScrollX(); 1023 position[1] -= view.getScrollY(); 1024 } 1025 1026 if (position[0] < 0 || position[1] < 0 || 1027 position[0] > view.getWidth() || position[1] > view.getHeight()) { 1028 return false; 1029 } 1030 1031 if (!view.getMatrix().isIdentity()) { 1032 view.getMatrix().mapPoints(position); 1033 } 1034 1035 position[0] += view.getLeft(); 1036 position[1] += view.getTop(); 1037 1038 final ViewParent parent = view.getParent(); 1039 if (parent instanceof View) { 1040 view = (View) parent; 1041 } else { 1042 // We've reached the ViewRoot, stop iterating 1043 view = null; 1044 } 1045 } 1046 } 1047 1048 // We've been able to walk up the view hierarchy and the position was never clipped 1049 return true; 1050 } 1051 1052 private boolean isOffsetVisible(int offset) { 1053 Layout layout = mTextView.getLayout(); 1054 if (layout == null) return false; 1055 1056 final int line = layout.getLineForOffset(offset); 1057 final int lineBottom = layout.getLineBottom(line); 1058 final int primaryHorizontal = (int) layout.getPrimaryHorizontal(offset); 1059 return isPositionVisible(primaryHorizontal + mTextView.viewportToContentHorizontalOffset(), 1060 lineBottom + mTextView.viewportToContentVerticalOffset()); 1061 } 1062 1063 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed 1064 * in the view. Returns false when the position is in the empty space of left/right of text. 1065 */ 1066 private boolean isPositionOnText(float x, float y) { 1067 Layout layout = mTextView.getLayout(); 1068 if (layout == null) return false; 1069 1070 final int line = mTextView.getLineAtCoordinate(y); 1071 x = mTextView.convertToLocalHorizontalCoordinate(x); 1072 1073 if (x < layout.getLineLeft(line)) return false; 1074 if (x > layout.getLineRight(line)) return false; 1075 return true; 1076 } 1077 1078 private void startDragAndDrop() { 1079 final int start = mTextView.getSelectionStart(); 1080 final int end = mTextView.getSelectionEnd(); 1081 CharSequence selectedText = mTextView.getTransformedText(start, end); 1082 ClipData data = ClipData.newPlainText(null, selectedText); 1083 DragLocalState localState = new DragLocalState(mTextView, start, end); 1084 mTextView.startDragAndDrop(data, getTextThumbnailBuilder(start, end), localState, 1085 View.DRAG_FLAG_GLOBAL); 1086 stopTextActionMode(); 1087 if (hasSelectionController()) { 1088 getSelectionController().resetTouchOffsets(); 1089 } 1090 } 1091 1092 public boolean performLongClick(boolean handled) { 1093 // Long press in empty space moves cursor and starts the insertion action mode. 1094 if (!handled && !isPositionOnText(mLastDownPositionX, mLastDownPositionY) && 1095 mInsertionControllerEnabled) { 1096 final int offset = mTextView.getOffsetForPosition(mLastDownPositionX, 1097 mLastDownPositionY); 1098 Selection.setSelection((Spannable) mTextView.getText(), offset); 1099 getInsertionController().show(); 1100 mIsInsertionActionModeStartPending = true; 1101 handled = true; 1102 } 1103 1104 if (!handled && mTextActionMode != null) { 1105 if (touchPositionIsInSelection()) { 1106 startDragAndDrop(); 1107 } else { 1108 stopTextActionMode(); 1109 selectCurrentWordAndStartDrag(); 1110 } 1111 handled = true; 1112 } 1113 1114 // Start a new selection 1115 if (!handled) { 1116 handled = selectCurrentWordAndStartDrag(); 1117 } 1118 1119 return handled; 1120 } 1121 1122 private long getLastTouchOffsets() { 1123 SelectionModifierCursorController selectionController = getSelectionController(); 1124 final int minOffset = selectionController.getMinTouchOffset(); 1125 final int maxOffset = selectionController.getMaxTouchOffset(); 1126 return TextUtils.packRangeInLong(minOffset, maxOffset); 1127 } 1128 1129 void onFocusChanged(boolean focused, int direction) { 1130 mShowCursor = SystemClock.uptimeMillis(); 1131 ensureEndedBatchEdit(); 1132 1133 if (focused) { 1134 int selStart = mTextView.getSelectionStart(); 1135 int selEnd = mTextView.getSelectionEnd(); 1136 1137 // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection 1138 // mode for these, unless there was a specific selection already started. 1139 final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 && 1140 selEnd == mTextView.getText().length(); 1141 1142 mCreatedWithASelection = mFrozenWithFocus && mTextView.hasSelection() && 1143 !isFocusHighlighted; 1144 1145 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) { 1146 // If a tap was used to give focus to that view, move cursor at tap position. 1147 // Has to be done before onTakeFocus, which can be overloaded. 1148 final int lastTapPosition = getLastTapPosition(); 1149 if (lastTapPosition >= 0) { 1150 Selection.setSelection((Spannable) mTextView.getText(), lastTapPosition); 1151 } 1152 1153 // Note this may have to be moved out of the Editor class 1154 MovementMethod mMovement = mTextView.getMovementMethod(); 1155 if (mMovement != null) { 1156 mMovement.onTakeFocus(mTextView, (Spannable) mTextView.getText(), direction); 1157 } 1158 1159 // The DecorView does not have focus when the 'Done' ExtractEditText button is 1160 // pressed. Since it is the ViewAncestor's mView, it requests focus before 1161 // ExtractEditText clears focus, which gives focus to the ExtractEditText. 1162 // This special case ensure that we keep current selection in that case. 1163 // It would be better to know why the DecorView does not have focus at that time. 1164 if (((mTextView.isInExtractedMode()) || mSelectionMoved) && 1165 selStart >= 0 && selEnd >= 0) { 1166 /* 1167 * Someone intentionally set the selection, so let them 1168 * do whatever it is that they wanted to do instead of 1169 * the default on-focus behavior. We reset the selection 1170 * here instead of just skipping the onTakeFocus() call 1171 * because some movement methods do something other than 1172 * just setting the selection in theirs and we still 1173 * need to go through that path. 1174 */ 1175 Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd); 1176 } 1177 1178 if (mSelectAllOnFocus) { 1179 mTextView.selectAllText(); 1180 } 1181 1182 mTouchFocusSelected = true; 1183 } 1184 1185 mFrozenWithFocus = false; 1186 mSelectionMoved = false; 1187 1188 if (mError != null) { 1189 showError(); 1190 } 1191 1192 makeBlink(); 1193 } else { 1194 if (mError != null) { 1195 hideError(); 1196 } 1197 // Don't leave us in the middle of a batch edit. 1198 mTextView.onEndBatchEdit(); 1199 1200 if (mTextView.isInExtractedMode()) { 1201 hideCursorAndSpanControllers(); 1202 stopTextActionModeWithPreservingSelection(); 1203 } else { 1204 hideCursorAndSpanControllers(); 1205 if (mTemporaryDetach) { 1206 stopTextActionModeWithPreservingSelection(); 1207 } else { 1208 stopTextActionMode(); 1209 } 1210 downgradeEasyCorrectionSpans(); 1211 } 1212 // No need to create the controller 1213 if (mSelectionModifierCursorController != null) { 1214 mSelectionModifierCursorController.resetTouchOffsets(); 1215 } 1216 } 1217 } 1218 1219 /** 1220 * Downgrades to simple suggestions all the easy correction spans that are not a spell check 1221 * span. 1222 */ 1223 private void downgradeEasyCorrectionSpans() { 1224 CharSequence text = mTextView.getText(); 1225 if (text instanceof Spannable) { 1226 Spannable spannable = (Spannable) text; 1227 SuggestionSpan[] suggestionSpans = spannable.getSpans(0, 1228 spannable.length(), SuggestionSpan.class); 1229 for (int i = 0; i < suggestionSpans.length; i++) { 1230 int flags = suggestionSpans[i].getFlags(); 1231 if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0 1232 && (flags & SuggestionSpan.FLAG_MISSPELLED) == 0) { 1233 flags &= ~SuggestionSpan.FLAG_EASY_CORRECT; 1234 suggestionSpans[i].setFlags(flags); 1235 } 1236 } 1237 } 1238 } 1239 1240 void sendOnTextChanged(int start, int after) { 1241 updateSpellCheckSpans(start, start + after, false); 1242 1243 // Flip flag to indicate the word iterator needs to have the text reset. 1244 mUpdateWordIteratorText = true; 1245 1246 // Hide the controllers as soon as text is modified (typing, procedural...) 1247 // We do not hide the span controllers, since they can be added when a new text is 1248 // inserted into the text view (voice IME). 1249 hideCursorControllers(); 1250 // Reset drag accelerator. 1251 if (mSelectionModifierCursorController != null) { 1252 mSelectionModifierCursorController.resetTouchOffsets(); 1253 } 1254 stopTextActionMode(); 1255 } 1256 1257 private int getLastTapPosition() { 1258 // No need to create the controller at that point, no last tap position saved 1259 if (mSelectionModifierCursorController != null) { 1260 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset(); 1261 if (lastTapPosition >= 0) { 1262 // Safety check, should not be possible. 1263 if (lastTapPosition > mTextView.getText().length()) { 1264 lastTapPosition = mTextView.getText().length(); 1265 } 1266 return lastTapPosition; 1267 } 1268 } 1269 1270 return -1; 1271 } 1272 1273 void onWindowFocusChanged(boolean hasWindowFocus) { 1274 if (hasWindowFocus) { 1275 if (mBlink != null) { 1276 mBlink.uncancel(); 1277 makeBlink(); 1278 } 1279 final InputMethodManager imm = InputMethodManager.peekInstance(); 1280 if (mTextView.hasSelection() && !extractedTextModeWillBeStarted()) { 1281 startSelectionActionMode(); 1282 } 1283 } else { 1284 if (mBlink != null) { 1285 mBlink.cancel(); 1286 } 1287 if (mInputContentType != null) { 1288 mInputContentType.enterDown = false; 1289 } 1290 // Order matters! Must be done before onParentLostFocus to rely on isShowingUp 1291 hideCursorAndSpanControllers(); 1292 stopTextActionModeWithPreservingSelection(); 1293 if (mSuggestionsPopupWindow != null) { 1294 mSuggestionsPopupWindow.onParentLostFocus(); 1295 } 1296 1297 // Don't leave us in the middle of a batch edit. Same as in onFocusChanged 1298 ensureEndedBatchEdit(); 1299 } 1300 } 1301 1302 private void updateTapState(MotionEvent event) { 1303 final int action = event.getActionMasked(); 1304 if (action == MotionEvent.ACTION_DOWN) { 1305 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE); 1306 // Detect double tap and triple click. 1307 if (((mTapState == TAP_STATE_FIRST_TAP) 1308 || ((mTapState == TAP_STATE_DOUBLE_TAP) && isMouse)) 1309 && (SystemClock.uptimeMillis() - mLastTouchUpTime) <= 1310 ViewConfiguration.getDoubleTapTimeout()) { 1311 if (mTapState == TAP_STATE_FIRST_TAP) { 1312 mTapState = TAP_STATE_DOUBLE_TAP; 1313 } else { 1314 mTapState = TAP_STATE_TRIPLE_CLICK; 1315 } 1316 } else { 1317 mTapState = TAP_STATE_FIRST_TAP; 1318 } 1319 } 1320 if (action == MotionEvent.ACTION_UP) { 1321 mLastTouchUpTime = SystemClock.uptimeMillis(); 1322 } 1323 } 1324 1325 private boolean shouldFilterOutTouchEvent(MotionEvent event) { 1326 if (!event.isFromSource(InputDevice.SOURCE_MOUSE)) { 1327 return false; 1328 } 1329 final boolean primaryButtonStateChanged = 1330 ((mLastButtonState ^ event.getButtonState()) & MotionEvent.BUTTON_PRIMARY) != 0; 1331 final int action = event.getActionMasked(); 1332 if ((action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) 1333 && !primaryButtonStateChanged) { 1334 return true; 1335 } 1336 if (action == MotionEvent.ACTION_MOVE 1337 && !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 1338 return true; 1339 } 1340 return false; 1341 } 1342 1343 void onTouchEvent(MotionEvent event) { 1344 final boolean filterOutEvent = shouldFilterOutTouchEvent(event); 1345 mLastButtonState = event.getButtonState(); 1346 if (filterOutEvent) { 1347 if (event.getActionMasked() == MotionEvent.ACTION_UP) { 1348 mDiscardNextActionUp = true; 1349 } 1350 return; 1351 } 1352 updateTapState(event); 1353 updateFloatingToolbarVisibility(event); 1354 1355 if (hasSelectionController()) { 1356 getSelectionController().onTouchEvent(event); 1357 } 1358 1359 if (mShowSuggestionRunnable != null) { 1360 mTextView.removeCallbacks(mShowSuggestionRunnable); 1361 mShowSuggestionRunnable = null; 1362 } 1363 1364 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { 1365 mLastDownPositionX = event.getX(); 1366 mLastDownPositionY = event.getY(); 1367 1368 // Reset this state; it will be re-set if super.onTouchEvent 1369 // causes focus to move to the view. 1370 mTouchFocusSelected = false; 1371 mIgnoreActionUpEvent = false; 1372 } 1373 } 1374 1375 private void updateFloatingToolbarVisibility(MotionEvent event) { 1376 if (mTextActionMode != null) { 1377 switch (event.getActionMasked()) { 1378 case MotionEvent.ACTION_MOVE: 1379 hideFloatingToolbar(); 1380 break; 1381 case MotionEvent.ACTION_UP: // fall through 1382 case MotionEvent.ACTION_CANCEL: 1383 showFloatingToolbar(); 1384 } 1385 } 1386 } 1387 1388 private void hideFloatingToolbar() { 1389 if (mTextActionMode != null) { 1390 mTextView.removeCallbacks(mShowFloatingToolbar); 1391 mTextActionMode.hide(ActionMode.DEFAULT_HIDE_DURATION); 1392 } 1393 } 1394 1395 private void showFloatingToolbar() { 1396 if (mTextActionMode != null) { 1397 // Delay "show" so it doesn't interfere with click confirmations 1398 // or double-clicks that could "dismiss" the floating toolbar. 1399 int delay = ViewConfiguration.getDoubleTapTimeout(); 1400 mTextView.postDelayed(mShowFloatingToolbar, delay); 1401 } 1402 } 1403 1404 public void beginBatchEdit() { 1405 mInBatchEditControllers = true; 1406 final InputMethodState ims = mInputMethodState; 1407 if (ims != null) { 1408 int nesting = ++ims.mBatchEditNesting; 1409 if (nesting == 1) { 1410 ims.mCursorChanged = false; 1411 ims.mChangedDelta = 0; 1412 if (ims.mContentChanged) { 1413 // We already have a pending change from somewhere else, 1414 // so turn this into a full update. 1415 ims.mChangedStart = 0; 1416 ims.mChangedEnd = mTextView.getText().length(); 1417 } else { 1418 ims.mChangedStart = EXTRACT_UNKNOWN; 1419 ims.mChangedEnd = EXTRACT_UNKNOWN; 1420 ims.mContentChanged = false; 1421 } 1422 mUndoInputFilter.beginBatchEdit(); 1423 mTextView.onBeginBatchEdit(); 1424 } 1425 } 1426 } 1427 1428 public void endBatchEdit() { 1429 mInBatchEditControllers = false; 1430 final InputMethodState ims = mInputMethodState; 1431 if (ims != null) { 1432 int nesting = --ims.mBatchEditNesting; 1433 if (nesting == 0) { 1434 finishBatchEdit(ims); 1435 } 1436 } 1437 } 1438 1439 void ensureEndedBatchEdit() { 1440 final InputMethodState ims = mInputMethodState; 1441 if (ims != null && ims.mBatchEditNesting != 0) { 1442 ims.mBatchEditNesting = 0; 1443 finishBatchEdit(ims); 1444 } 1445 } 1446 1447 void finishBatchEdit(final InputMethodState ims) { 1448 mTextView.onEndBatchEdit(); 1449 mUndoInputFilter.endBatchEdit(); 1450 1451 if (ims.mContentChanged || ims.mSelectionModeChanged) { 1452 mTextView.updateAfterEdit(); 1453 reportExtractedText(); 1454 } else if (ims.mCursorChanged) { 1455 // Cheesy way to get us to report the current cursor location. 1456 mTextView.invalidateCursor(); 1457 } 1458 // sendUpdateSelection knows to avoid sending if the selection did 1459 // not actually change. 1460 sendUpdateSelection(); 1461 } 1462 1463 static final int EXTRACT_NOTHING = -2; 1464 static final int EXTRACT_UNKNOWN = -1; 1465 1466 boolean extractText(ExtractedTextRequest request, ExtractedText outText) { 1467 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN, 1468 EXTRACT_UNKNOWN, outText); 1469 } 1470 1471 private boolean extractTextInternal(@Nullable ExtractedTextRequest request, 1472 int partialStartOffset, int partialEndOffset, int delta, 1473 @Nullable ExtractedText outText) { 1474 if (request == null || outText == null) { 1475 return false; 1476 } 1477 1478 final CharSequence content = mTextView.getText(); 1479 if (content == null) { 1480 return false; 1481 } 1482 1483 if (partialStartOffset != EXTRACT_NOTHING) { 1484 final int N = content.length(); 1485 if (partialStartOffset < 0) { 1486 outText.partialStartOffset = outText.partialEndOffset = -1; 1487 partialStartOffset = 0; 1488 partialEndOffset = N; 1489 } else { 1490 // Now use the delta to determine the actual amount of text 1491 // we need. 1492 partialEndOffset += delta; 1493 // Adjust offsets to ensure we contain full spans. 1494 if (content instanceof Spanned) { 1495 Spanned spanned = (Spanned)content; 1496 Object[] spans = spanned.getSpans(partialStartOffset, 1497 partialEndOffset, ParcelableSpan.class); 1498 int i = spans.length; 1499 while (i > 0) { 1500 i--; 1501 int j = spanned.getSpanStart(spans[i]); 1502 if (j < partialStartOffset) partialStartOffset = j; 1503 j = spanned.getSpanEnd(spans[i]); 1504 if (j > partialEndOffset) partialEndOffset = j; 1505 } 1506 } 1507 outText.partialStartOffset = partialStartOffset; 1508 outText.partialEndOffset = partialEndOffset - delta; 1509 1510 if (partialStartOffset > N) { 1511 partialStartOffset = N; 1512 } else if (partialStartOffset < 0) { 1513 partialStartOffset = 0; 1514 } 1515 if (partialEndOffset > N) { 1516 partialEndOffset = N; 1517 } else if (partialEndOffset < 0) { 1518 partialEndOffset = 0; 1519 } 1520 } 1521 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) { 1522 outText.text = content.subSequence(partialStartOffset, 1523 partialEndOffset); 1524 } else { 1525 outText.text = TextUtils.substring(content, partialStartOffset, 1526 partialEndOffset); 1527 } 1528 } else { 1529 outText.partialStartOffset = 0; 1530 outText.partialEndOffset = 0; 1531 outText.text = ""; 1532 } 1533 outText.flags = 0; 1534 if (MetaKeyKeyListener.getMetaState(content, MetaKeyKeyListener.META_SELECTING) != 0) { 1535 outText.flags |= ExtractedText.FLAG_SELECTING; 1536 } 1537 if (mTextView.isSingleLine()) { 1538 outText.flags |= ExtractedText.FLAG_SINGLE_LINE; 1539 } 1540 outText.startOffset = 0; 1541 outText.selectionStart = mTextView.getSelectionStart(); 1542 outText.selectionEnd = mTextView.getSelectionEnd(); 1543 return true; 1544 } 1545 1546 boolean reportExtractedText() { 1547 final Editor.InputMethodState ims = mInputMethodState; 1548 if (ims != null) { 1549 final boolean contentChanged = ims.mContentChanged; 1550 if (contentChanged || ims.mSelectionModeChanged) { 1551 ims.mContentChanged = false; 1552 ims.mSelectionModeChanged = false; 1553 final ExtractedTextRequest req = ims.mExtractedTextRequest; 1554 if (req != null) { 1555 InputMethodManager imm = InputMethodManager.peekInstance(); 1556 if (imm != null) { 1557 if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG, 1558 "Retrieving extracted start=" + ims.mChangedStart + 1559 " end=" + ims.mChangedEnd + 1560 " delta=" + ims.mChangedDelta); 1561 if (ims.mChangedStart < 0 && !contentChanged) { 1562 ims.mChangedStart = EXTRACT_NOTHING; 1563 } 1564 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd, 1565 ims.mChangedDelta, ims.mExtractedText)) { 1566 if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG, 1567 "Reporting extracted start=" + 1568 ims.mExtractedText.partialStartOffset + 1569 " end=" + ims.mExtractedText.partialEndOffset + 1570 ": " + ims.mExtractedText.text); 1571 1572 imm.updateExtractedText(mTextView, req.token, ims.mExtractedText); 1573 ims.mChangedStart = EXTRACT_UNKNOWN; 1574 ims.mChangedEnd = EXTRACT_UNKNOWN; 1575 ims.mChangedDelta = 0; 1576 ims.mContentChanged = false; 1577 return true; 1578 } 1579 } 1580 } 1581 } 1582 } 1583 return false; 1584 } 1585 1586 private void sendUpdateSelection() { 1587 if (null != mInputMethodState && mInputMethodState.mBatchEditNesting <= 0) { 1588 final InputMethodManager imm = InputMethodManager.peekInstance(); 1589 if (null != imm) { 1590 final int selectionStart = mTextView.getSelectionStart(); 1591 final int selectionEnd = mTextView.getSelectionEnd(); 1592 int candStart = -1; 1593 int candEnd = -1; 1594 if (mTextView.getText() instanceof Spannable) { 1595 final Spannable sp = (Spannable) mTextView.getText(); 1596 candStart = EditableInputConnection.getComposingSpanStart(sp); 1597 candEnd = EditableInputConnection.getComposingSpanEnd(sp); 1598 } 1599 // InputMethodManager#updateSelection skips sending the message if 1600 // none of the parameters have changed since the last time we called it. 1601 imm.updateSelection(mTextView, 1602 selectionStart, selectionEnd, candStart, candEnd); 1603 } 1604 } 1605 } 1606 1607 void onDraw(Canvas canvas, Layout layout, Path highlight, Paint highlightPaint, 1608 int cursorOffsetVertical) { 1609 final int selectionStart = mTextView.getSelectionStart(); 1610 final int selectionEnd = mTextView.getSelectionEnd(); 1611 1612 final InputMethodState ims = mInputMethodState; 1613 if (ims != null && ims.mBatchEditNesting == 0) { 1614 InputMethodManager imm = InputMethodManager.peekInstance(); 1615 if (imm != null) { 1616 if (imm.isActive(mTextView)) { 1617 if (ims.mContentChanged || ims.mSelectionModeChanged) { 1618 // We are in extract mode and the content has changed 1619 // in some way... just report complete new text to the 1620 // input method. 1621 reportExtractedText(); 1622 } 1623 } 1624 } 1625 } 1626 1627 if (mCorrectionHighlighter != null) { 1628 mCorrectionHighlighter.draw(canvas, cursorOffsetVertical); 1629 } 1630 1631 if (highlight != null && selectionStart == selectionEnd && mCursorCount > 0) { 1632 drawCursor(canvas, cursorOffsetVertical); 1633 // Rely on the drawable entirely, do not draw the cursor line. 1634 // Has to be done after the IMM related code above which relies on the highlight. 1635 highlight = null; 1636 } 1637 1638 if (mTextView.canHaveDisplayList() && canvas.isHardwareAccelerated()) { 1639 drawHardwareAccelerated(canvas, layout, highlight, highlightPaint, 1640 cursorOffsetVertical); 1641 } else { 1642 layout.draw(canvas, highlight, highlightPaint, cursorOffsetVertical); 1643 } 1644 } 1645 1646 private void drawHardwareAccelerated(Canvas canvas, Layout layout, Path highlight, 1647 Paint highlightPaint, int cursorOffsetVertical) { 1648 final long lineRange = layout.getLineRangeForDraw(canvas); 1649 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange); 1650 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange); 1651 if (lastLine < 0) return; 1652 1653 layout.drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical, 1654 firstLine, lastLine); 1655 1656 if (layout instanceof DynamicLayout) { 1657 if (mTextRenderNodes == null) { 1658 mTextRenderNodes = ArrayUtils.emptyArray(TextRenderNode.class); 1659 } 1660 1661 DynamicLayout dynamicLayout = (DynamicLayout) layout; 1662 int[] blockEndLines = dynamicLayout.getBlockEndLines(); 1663 int[] blockIndices = dynamicLayout.getBlockIndices(); 1664 final int numberOfBlocks = dynamicLayout.getNumberOfBlocks(); 1665 final int indexFirstChangedBlock = dynamicLayout.getIndexFirstChangedBlock(); 1666 1667 int endOfPreviousBlock = -1; 1668 int searchStartIndex = 0; 1669 for (int i = 0; i < numberOfBlocks; i++) { 1670 int blockEndLine = blockEndLines[i]; 1671 int blockIndex = blockIndices[i]; 1672 1673 final boolean blockIsInvalid = blockIndex == DynamicLayout.INVALID_BLOCK_INDEX; 1674 if (blockIsInvalid) { 1675 blockIndex = getAvailableDisplayListIndex(blockIndices, numberOfBlocks, 1676 searchStartIndex); 1677 // Note how dynamic layout's internal block indices get updated from Editor 1678 blockIndices[i] = blockIndex; 1679 if (mTextRenderNodes[blockIndex] != null) { 1680 mTextRenderNodes[blockIndex].isDirty = true; 1681 } 1682 searchStartIndex = blockIndex + 1; 1683 } 1684 1685 if (mTextRenderNodes[blockIndex] == null) { 1686 mTextRenderNodes[blockIndex] = 1687 new TextRenderNode("Text " + blockIndex); 1688 } 1689 1690 final boolean blockDisplayListIsInvalid = mTextRenderNodes[blockIndex].needsRecord(); 1691 RenderNode blockDisplayList = mTextRenderNodes[blockIndex].renderNode; 1692 if (i >= indexFirstChangedBlock || blockDisplayListIsInvalid) { 1693 final int blockBeginLine = endOfPreviousBlock + 1; 1694 final int top = layout.getLineTop(blockBeginLine); 1695 final int bottom = layout.getLineBottom(blockEndLine); 1696 int left = 0; 1697 int right = mTextView.getWidth(); 1698 if (mTextView.getHorizontallyScrolling()) { 1699 float min = Float.MAX_VALUE; 1700 float max = Float.MIN_VALUE; 1701 for (int line = blockBeginLine; line <= blockEndLine; line++) { 1702 min = Math.min(min, layout.getLineLeft(line)); 1703 max = Math.max(max, layout.getLineRight(line)); 1704 } 1705 left = (int) min; 1706 right = (int) (max + 0.5f); 1707 } 1708 1709 // Rebuild display list if it is invalid 1710 if (blockDisplayListIsInvalid) { 1711 final DisplayListCanvas displayListCanvas = blockDisplayList.start( 1712 right - left, bottom - top); 1713 try { 1714 // drawText is always relative to TextView's origin, this translation 1715 // brings this range of text back to the top left corner of the viewport 1716 displayListCanvas.translate(-left, -top); 1717 layout.drawText(displayListCanvas, blockBeginLine, blockEndLine); 1718 mTextRenderNodes[blockIndex].isDirty = false; 1719 // No need to untranslate, previous context is popped after 1720 // drawDisplayList 1721 } finally { 1722 blockDisplayList.end(displayListCanvas); 1723 // Same as drawDisplayList below, handled by our TextView's parent 1724 blockDisplayList.setClipToBounds(false); 1725 } 1726 } 1727 1728 // Valid disply list whose index is >= indexFirstChangedBlock 1729 // only needs to update its drawing location. 1730 blockDisplayList.setLeftTopRightBottom(left, top, right, bottom); 1731 } 1732 1733 ((DisplayListCanvas) canvas).drawRenderNode(blockDisplayList); 1734 1735 endOfPreviousBlock = blockEndLine; 1736 } 1737 1738 dynamicLayout.setIndexFirstChangedBlock(numberOfBlocks); 1739 } else { 1740 // Boring layout is used for empty and hint text 1741 layout.drawText(canvas, firstLine, lastLine); 1742 } 1743 } 1744 1745 private int getAvailableDisplayListIndex(int[] blockIndices, int numberOfBlocks, 1746 int searchStartIndex) { 1747 int length = mTextRenderNodes.length; 1748 for (int i = searchStartIndex; i < length; i++) { 1749 boolean blockIndexFound = false; 1750 for (int j = 0; j < numberOfBlocks; j++) { 1751 if (blockIndices[j] == i) { 1752 blockIndexFound = true; 1753 break; 1754 } 1755 } 1756 if (blockIndexFound) continue; 1757 return i; 1758 } 1759 1760 // No available index found, the pool has to grow 1761 mTextRenderNodes = GrowingArrayUtils.append(mTextRenderNodes, length, null); 1762 return length; 1763 } 1764 1765 private void drawCursor(Canvas canvas, int cursorOffsetVertical) { 1766 final boolean translate = cursorOffsetVertical != 0; 1767 if (translate) canvas.translate(0, cursorOffsetVertical); 1768 for (int i = 0; i < mCursorCount; i++) { 1769 mCursorDrawable[i].draw(canvas); 1770 } 1771 if (translate) canvas.translate(0, -cursorOffsetVertical); 1772 } 1773 1774 /** 1775 * Invalidates all the sub-display lists that overlap the specified character range 1776 */ 1777 void invalidateTextDisplayList(Layout layout, int start, int end) { 1778 if (mTextRenderNodes != null && layout instanceof DynamicLayout) { 1779 final int firstLine = layout.getLineForOffset(start); 1780 final int lastLine = layout.getLineForOffset(end); 1781 1782 DynamicLayout dynamicLayout = (DynamicLayout) layout; 1783 int[] blockEndLines = dynamicLayout.getBlockEndLines(); 1784 int[] blockIndices = dynamicLayout.getBlockIndices(); 1785 final int numberOfBlocks = dynamicLayout.getNumberOfBlocks(); 1786 1787 int i = 0; 1788 // Skip the blocks before firstLine 1789 while (i < numberOfBlocks) { 1790 if (blockEndLines[i] >= firstLine) break; 1791 i++; 1792 } 1793 1794 // Invalidate all subsequent blocks until lastLine is passed 1795 while (i < numberOfBlocks) { 1796 final int blockIndex = blockIndices[i]; 1797 if (blockIndex != DynamicLayout.INVALID_BLOCK_INDEX) { 1798 mTextRenderNodes[blockIndex].isDirty = true; 1799 } 1800 if (blockEndLines[i] >= lastLine) break; 1801 i++; 1802 } 1803 } 1804 } 1805 1806 void invalidateTextDisplayList() { 1807 if (mTextRenderNodes != null) { 1808 for (int i = 0; i < mTextRenderNodes.length; i++) { 1809 if (mTextRenderNodes[i] != null) mTextRenderNodes[i].isDirty = true; 1810 } 1811 } 1812 } 1813 1814 void updateCursorsPositions() { 1815 if (mTextView.mCursorDrawableRes == 0) { 1816 mCursorCount = 0; 1817 return; 1818 } 1819 1820 Layout layout = getActiveLayout(); 1821 final int offset = mTextView.getSelectionStart(); 1822 final int line = layout.getLineForOffset(offset); 1823 final int top = layout.getLineTop(line); 1824 final int bottom = layout.getLineTop(line + 1); 1825 1826 mCursorCount = layout.isLevelBoundary(offset) ? 2 : 1; 1827 1828 int middle = bottom; 1829 if (mCursorCount == 2) { 1830 // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)} 1831 middle = (top + bottom) >> 1; 1832 } 1833 1834 boolean clamped = layout.shouldClampCursor(line); 1835 updateCursorPosition(0, top, middle, layout.getPrimaryHorizontal(offset, clamped)); 1836 1837 if (mCursorCount == 2) { 1838 updateCursorPosition(1, middle, bottom, layout.getSecondaryHorizontal(offset, clamped)); 1839 } 1840 } 1841 1842 void refreshTextActionMode() { 1843 if (extractedTextModeWillBeStarted()) { 1844 return; 1845 } 1846 final boolean hasSelection = mTextView.hasSelection(); 1847 final SelectionModifierCursorController selectionController = getSelectionController(); 1848 final InsertionPointCursorController insertionController = getInsertionController(); 1849 if ((selectionController != null && selectionController.isCursorBeingModified()) 1850 || (insertionController != null && insertionController.isCursorBeingModified())) { 1851 // ActionMode should be managed by the currently active cursor controller. 1852 return; 1853 } 1854 if (hasSelection) { 1855 if (mTextActionMode == null || selectionController == null 1856 || !selectionController.isActive()) { 1857 // Avoid dismissing the selection if it exists. 1858 stopTextActionModeWithPreservingSelection(); 1859 startSelectionActionMode(); 1860 } else { 1861 mTextActionMode.invalidateContentRect(); 1862 } 1863 } else { 1864 // Insertion action mode is started only when insertion controller is explicitly 1865 // activated. 1866 if (insertionController == null || !insertionController.isActive()) { 1867 stopTextActionMode(); 1868 } else if (mTextActionMode != null) { 1869 mTextActionMode.invalidateContentRect(); 1870 } 1871 } 1872 } 1873 1874 /** 1875 * Start an Insertion action mode. 1876 */ 1877 void startInsertionActionMode() { 1878 if (mInsertionActionModeRunnable != null) { 1879 mTextView.removeCallbacks(mInsertionActionModeRunnable); 1880 } 1881 if (extractedTextModeWillBeStarted()) { 1882 return; 1883 } 1884 stopTextActionMode(); 1885 1886 ActionMode.Callback actionModeCallback = 1887 new TextActionModeCallback(false /* hasSelection */); 1888 mTextActionMode = mTextView.startActionMode( 1889 actionModeCallback, ActionMode.TYPE_FLOATING); 1890 if (mTextActionMode != null && getInsertionController() != null) { 1891 getInsertionController().show(); 1892 } 1893 } 1894 1895 /** 1896 * Starts a Selection Action Mode with the current selection and ensures the selection handles 1897 * are shown if there is a selection. This should be used when the mode is started from a 1898 * non-touch event. 1899 * 1900 * @return true if the selection mode was actually started. 1901 */ 1902 private boolean startSelectionActionMode() { 1903 boolean selectionStarted = startSelectionActionModeInternal(); 1904 if (selectionStarted) { 1905 getSelectionController().show(); 1906 } 1907 return selectionStarted; 1908 } 1909 1910 /** 1911 * If the TextView allows text selection, selects the current word when no existing selection 1912 * was available and starts a drag. 1913 * 1914 * @return true if the drag was started. 1915 */ 1916 private boolean selectCurrentWordAndStartDrag() { 1917 if (mInsertionActionModeRunnable != null) { 1918 mTextView.removeCallbacks(mInsertionActionModeRunnable); 1919 } 1920 if (extractedTextModeWillBeStarted()) { 1921 return false; 1922 } 1923 if (!checkField()) { 1924 return false; 1925 } 1926 if (!mTextView.hasSelection() && !selectCurrentWord()) { 1927 // No selection and cannot select a word. 1928 return false; 1929 } 1930 stopTextActionModeWithPreservingSelection(); 1931 getSelectionController().enterDrag( 1932 SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_WORD); 1933 return true; 1934 } 1935 1936 /** 1937 * Checks whether a selection can be performed on the current TextView. 1938 * 1939 * @return true if a selection can be performed 1940 */ 1941 boolean checkField() { 1942 if (!mTextView.canSelectText() || !mTextView.requestFocus()) { 1943 Log.w(TextView.LOG_TAG, 1944 "TextView does not support text selection. Selection cancelled."); 1945 return false; 1946 } 1947 return true; 1948 } 1949 1950 private boolean startSelectionActionModeInternal() { 1951 if (extractedTextModeWillBeStarted()) { 1952 return false; 1953 } 1954 if (mTextActionMode != null) { 1955 // Text action mode is already started 1956 mTextActionMode.invalidate(); 1957 return false; 1958 } 1959 1960 if (!checkField() || !mTextView.hasSelection()) { 1961 return false; 1962 } 1963 1964 ActionMode.Callback actionModeCallback = 1965 new TextActionModeCallback(true /* hasSelection */); 1966 mTextActionMode = mTextView.startActionMode(actionModeCallback, ActionMode.TYPE_FLOATING); 1967 1968 final boolean selectionStarted = mTextActionMode != null; 1969 if (selectionStarted && !mTextView.isTextSelectable() && mShowSoftInputOnFocus) { 1970 // Show the IME to be able to replace text, except when selecting non editable text. 1971 final InputMethodManager imm = InputMethodManager.peekInstance(); 1972 if (imm != null) { 1973 imm.showSoftInput(mTextView, 0, null); 1974 } 1975 } 1976 return selectionStarted; 1977 } 1978 1979 boolean extractedTextModeWillBeStarted() { 1980 if (!(mTextView.isInExtractedMode())) { 1981 final InputMethodManager imm = InputMethodManager.peekInstance(); 1982 return imm != null && imm.isFullscreenMode(); 1983 } 1984 return false; 1985 } 1986 1987 /** 1988 * @return <code>true</code> if it's reasonable to offer to show suggestions depending on 1989 * the current cursor position or selection range. This method is consistent with the 1990 * method to show suggestions {@link SuggestionsPopupWindow#updateSuggestions}. 1991 */ 1992 private boolean shouldOfferToShowSuggestions() { 1993 CharSequence text = mTextView.getText(); 1994 if (!(text instanceof Spannable)) return false; 1995 1996 final Spannable spannable = (Spannable) text; 1997 final int selectionStart = mTextView.getSelectionStart(); 1998 final int selectionEnd = mTextView.getSelectionEnd(); 1999 final SuggestionSpan[] suggestionSpans = spannable.getSpans(selectionStart, selectionEnd, 2000 SuggestionSpan.class); 2001 if (suggestionSpans.length == 0) { 2002 return false; 2003 } 2004 if (selectionStart == selectionEnd) { 2005 // Spans overlap the cursor. 2006 for (int i = 0; i < suggestionSpans.length; i++) { 2007 if (suggestionSpans[i].getSuggestions().length > 0) { 2008 return true; 2009 } 2010 } 2011 return false; 2012 } 2013 int minSpanStart = mTextView.getText().length(); 2014 int maxSpanEnd = 0; 2015 int unionOfSpansCoveringSelectionStartStart = mTextView.getText().length(); 2016 int unionOfSpansCoveringSelectionStartEnd = 0; 2017 boolean hasValidSuggestions = false; 2018 for (int i = 0; i < suggestionSpans.length; i++) { 2019 final int spanStart = spannable.getSpanStart(suggestionSpans[i]); 2020 final int spanEnd = spannable.getSpanEnd(suggestionSpans[i]); 2021 minSpanStart = Math.min(minSpanStart, spanStart); 2022 maxSpanEnd = Math.max(maxSpanEnd, spanEnd); 2023 if (selectionStart < spanStart || selectionStart > spanEnd) { 2024 // The span doesn't cover the current selection start point. 2025 continue; 2026 } 2027 hasValidSuggestions = 2028 hasValidSuggestions || suggestionSpans[i].getSuggestions().length > 0; 2029 unionOfSpansCoveringSelectionStartStart = 2030 Math.min(unionOfSpansCoveringSelectionStartStart, spanStart); 2031 unionOfSpansCoveringSelectionStartEnd = 2032 Math.max(unionOfSpansCoveringSelectionStartEnd, spanEnd); 2033 } 2034 if (!hasValidSuggestions) { 2035 return false; 2036 } 2037 if (unionOfSpansCoveringSelectionStartStart >= unionOfSpansCoveringSelectionStartEnd) { 2038 // No spans cover the selection start point. 2039 return false; 2040 } 2041 if (minSpanStart < unionOfSpansCoveringSelectionStartStart 2042 || maxSpanEnd > unionOfSpansCoveringSelectionStartEnd) { 2043 // There is a span that is not covered by the union. In this case, we soouldn't offer 2044 // to show suggestions as it's confusing. 2045 return false; 2046 } 2047 return true; 2048 } 2049 2050 /** 2051 * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with 2052 * {@link SuggestionSpan#FLAG_EASY_CORRECT} set. 2053 */ 2054 private boolean isCursorInsideEasyCorrectionSpan() { 2055 Spannable spannable = (Spannable) mTextView.getText(); 2056 SuggestionSpan[] suggestionSpans = spannable.getSpans(mTextView.getSelectionStart(), 2057 mTextView.getSelectionEnd(), SuggestionSpan.class); 2058 for (int i = 0; i < suggestionSpans.length; i++) { 2059 if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) { 2060 return true; 2061 } 2062 } 2063 return false; 2064 } 2065 2066 void onTouchUpEvent(MotionEvent event) { 2067 boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect(); 2068 hideCursorAndSpanControllers(); 2069 stopTextActionMode(); 2070 CharSequence text = mTextView.getText(); 2071 if (!selectAllGotFocus && text.length() > 0) { 2072 // Move cursor 2073 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY()); 2074 Selection.setSelection((Spannable) text, offset); 2075 if (mSpellChecker != null) { 2076 // When the cursor moves, the word that was typed may need spell check 2077 mSpellChecker.onSelectionChanged(); 2078 } 2079 2080 if (!extractedTextModeWillBeStarted()) { 2081 if (isCursorInsideEasyCorrectionSpan()) { 2082 // Cancel the single tap delayed runnable. 2083 if (mInsertionActionModeRunnable != null) { 2084 mTextView.removeCallbacks(mInsertionActionModeRunnable); 2085 } 2086 2087 mShowSuggestionRunnable = new Runnable() { 2088 public void run() { 2089 showSuggestions(); 2090 } 2091 }; 2092 // removeCallbacks is performed on every touch 2093 mTextView.postDelayed(mShowSuggestionRunnable, 2094 ViewConfiguration.getDoubleTapTimeout()); 2095 } else if (hasInsertionController()) { 2096 getInsertionController().show(); 2097 } 2098 } 2099 } 2100 } 2101 2102 protected void stopTextActionMode() { 2103 if (mTextActionMode != null) { 2104 // This will hide the mSelectionModifierCursorController 2105 mTextActionMode.finish(); 2106 } 2107 } 2108 2109 private void stopTextActionModeWithPreservingSelection() { 2110 mPreserveSelection = true; 2111 stopTextActionMode(); 2112 mPreserveSelection = false; 2113 } 2114 2115 /** 2116 * @return True if this view supports insertion handles. 2117 */ 2118 boolean hasInsertionController() { 2119 return mInsertionControllerEnabled; 2120 } 2121 2122 /** 2123 * @return True if this view supports selection handles. 2124 */ 2125 boolean hasSelectionController() { 2126 return mSelectionControllerEnabled; 2127 } 2128 2129 InsertionPointCursorController getInsertionController() { 2130 if (!mInsertionControllerEnabled) { 2131 return null; 2132 } 2133 2134 if (mInsertionPointCursorController == null) { 2135 mInsertionPointCursorController = new InsertionPointCursorController(); 2136 2137 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 2138 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 2139 } 2140 2141 return mInsertionPointCursorController; 2142 } 2143 2144 SelectionModifierCursorController getSelectionController() { 2145 if (!mSelectionControllerEnabled) { 2146 return null; 2147 } 2148 2149 if (mSelectionModifierCursorController == null) { 2150 mSelectionModifierCursorController = new SelectionModifierCursorController(); 2151 2152 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 2153 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 2154 } 2155 2156 return mSelectionModifierCursorController; 2157 } 2158 2159 /** 2160 * @hide 2161 */ 2162 @VisibleForTesting 2163 public Drawable[] getCursorDrawable() { 2164 return mCursorDrawable; 2165 } 2166 2167 private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) { 2168 if (mCursorDrawable[cursorIndex] == null) 2169 mCursorDrawable[cursorIndex] = mTextView.getContext().getDrawable( 2170 mTextView.mCursorDrawableRes); 2171 final Drawable drawable = mCursorDrawable[cursorIndex]; 2172 final int left = clampCursorHorizontalPosition(drawable, horizontal); 2173 final int width = drawable.getIntrinsicWidth(); 2174 drawable.setBounds(left, top - mTempRect.top, left + width, 2175 bottom + mTempRect.bottom); 2176 } 2177 2178 /** 2179 * Return clamped position for the cursor. If the cursor is within the boundaries of the view, 2180 * then it is offset with the left padding of the cursor drawable. If the cursor is at 2181 * the beginning or the end of the text then its drawable edge is aligned with left or right of 2182 * the view boundary. 2183 * 2184 * @param drawable Cursor drawable. 2185 * @param horizontal Horizontal position for the cursor. 2186 * @return The clamped horizontal position for the cursor. 2187 */ 2188 private final int clampCursorHorizontalPosition(final Drawable drawable, float 2189 horizontal) { 2190 horizontal = Math.max(0.5f, horizontal - 0.5f); 2191 if (mTempRect == null) mTempRect = new Rect(); 2192 drawable.getPadding(mTempRect); 2193 int scrollX = mTextView.getScrollX(); 2194 float horizontalDiff = horizontal - scrollX; 2195 int viewClippedWidth = mTextView.getWidth() - mTextView.getCompoundPaddingLeft() 2196 - mTextView.getCompoundPaddingRight(); 2197 2198 final int left; 2199 if (horizontalDiff >= (viewClippedWidth - 1f)) { 2200 // at the rightmost position 2201 final int cursorWidth = drawable.getIntrinsicWidth(); 2202 left = viewClippedWidth + scrollX - (cursorWidth - mTempRect.right); 2203 } else if (Math.abs(horizontalDiff) <= 1f) { 2204 // at the leftmost position 2205 left = scrollX - mTempRect.left; 2206 } else { 2207 left = (int) horizontal - mTempRect.left; 2208 } 2209 return left; 2210 } 2211 2212 /** 2213 * Called by the framework in response to a text auto-correction (such as fixing a typo using a 2214 * a dictionary) from the current input method, provided by it calling 2215 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default 2216 * implementation flashes the background of the corrected word to provide feedback to the user. 2217 * 2218 * @param info The auto correct info about the text that was corrected. 2219 */ 2220 public void onCommitCorrection(CorrectionInfo info) { 2221 if (mCorrectionHighlighter == null) { 2222 mCorrectionHighlighter = new CorrectionHighlighter(); 2223 } else { 2224 mCorrectionHighlighter.invalidate(false); 2225 } 2226 2227 mCorrectionHighlighter.highlight(info); 2228 } 2229 2230 void showSuggestions() { 2231 if (mSuggestionsPopupWindow == null) { 2232 mSuggestionsPopupWindow = new SuggestionsPopupWindow(); 2233 } 2234 hideCursorAndSpanControllers(); 2235 stopTextActionMode(); 2236 mSuggestionsPopupWindow.show(); 2237 } 2238 2239 void onScrollChanged() { 2240 if (mPositionListener != null) { 2241 mPositionListener.onScrollChanged(); 2242 } 2243 if (mTextActionMode != null) { 2244 mTextActionMode.invalidateContentRect(); 2245 } 2246 } 2247 2248 /** 2249 * @return True when the TextView isFocused and has a valid zero-length selection (cursor). 2250 */ 2251 private boolean shouldBlink() { 2252 if (!isCursorVisible() || !mTextView.isFocused()) return false; 2253 2254 final int start = mTextView.getSelectionStart(); 2255 if (start < 0) return false; 2256 2257 final int end = mTextView.getSelectionEnd(); 2258 if (end < 0) return false; 2259 2260 return start == end; 2261 } 2262 2263 void makeBlink() { 2264 if (shouldBlink()) { 2265 mShowCursor = SystemClock.uptimeMillis(); 2266 if (mBlink == null) mBlink = new Blink(); 2267 mTextView.removeCallbacks(mBlink); 2268 mTextView.postDelayed(mBlink, BLINK); 2269 } else { 2270 if (mBlink != null) mTextView.removeCallbacks(mBlink); 2271 } 2272 } 2273 2274 private class Blink implements Runnable { 2275 private boolean mCancelled; 2276 2277 public void run() { 2278 if (mCancelled) { 2279 return; 2280 } 2281 2282 mTextView.removeCallbacks(this); 2283 2284 if (shouldBlink()) { 2285 if (mTextView.getLayout() != null) { 2286 mTextView.invalidateCursorPath(); 2287 } 2288 2289 mTextView.postDelayed(this, BLINK); 2290 } 2291 } 2292 2293 void cancel() { 2294 if (!mCancelled) { 2295 mTextView.removeCallbacks(this); 2296 mCancelled = true; 2297 } 2298 } 2299 2300 void uncancel() { 2301 mCancelled = false; 2302 } 2303 } 2304 2305 private DragShadowBuilder getTextThumbnailBuilder(int start, int end) { 2306 TextView shadowView = (TextView) View.inflate(mTextView.getContext(), 2307 com.android.internal.R.layout.text_drag_thumbnail, null); 2308 2309 if (shadowView == null) { 2310 throw new IllegalArgumentException("Unable to inflate text drag thumbnail"); 2311 } 2312 2313 if (end - start > DRAG_SHADOW_MAX_TEXT_LENGTH) { 2314 final long range = getCharClusterRange(start + DRAG_SHADOW_MAX_TEXT_LENGTH); 2315 end = TextUtils.unpackRangeEndFromLong(range); 2316 } 2317 final CharSequence text = mTextView.getTransformedText(start, end); 2318 shadowView.setText(text); 2319 shadowView.setTextColor(mTextView.getTextColors()); 2320 2321 shadowView.setTextAppearance(R.styleable.Theme_textAppearanceLarge); 2322 shadowView.setGravity(Gravity.CENTER); 2323 2324 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 2325 ViewGroup.LayoutParams.WRAP_CONTENT)); 2326 2327 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 2328 shadowView.measure(size, size); 2329 2330 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight()); 2331 shadowView.invalidate(); 2332 return new DragShadowBuilder(shadowView); 2333 } 2334 2335 private static class DragLocalState { 2336 public TextView sourceTextView; 2337 public int start, end; 2338 2339 public DragLocalState(TextView sourceTextView, int start, int end) { 2340 this.sourceTextView = sourceTextView; 2341 this.start = start; 2342 this.end = end; 2343 } 2344 } 2345 2346 void onDrop(DragEvent event) { 2347 StringBuilder content = new StringBuilder(""); 2348 2349 final DropPermissions dropPermissions = DropPermissions.obtain(event); 2350 if (dropPermissions != null) { 2351 dropPermissions.takeTransient(); 2352 } 2353 2354 try { 2355 ClipData clipData = event.getClipData(); 2356 final int itemCount = clipData.getItemCount(); 2357 for (int i=0; i < itemCount; i++) { 2358 Item item = clipData.getItemAt(i); 2359 content.append(item.coerceToStyledText(mTextView.getContext())); 2360 } 2361 } 2362 finally { 2363 if (dropPermissions != null) { 2364 dropPermissions.release(); 2365 } 2366 } 2367 2368 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY()); 2369 2370 Object localState = event.getLocalState(); 2371 DragLocalState dragLocalState = null; 2372 if (localState instanceof DragLocalState) { 2373 dragLocalState = (DragLocalState) localState; 2374 } 2375 boolean dragDropIntoItself = dragLocalState != null && 2376 dragLocalState.sourceTextView == mTextView; 2377 2378 if (dragDropIntoItself) { 2379 if (offset >= dragLocalState.start && offset < dragLocalState.end) { 2380 // A drop inside the original selection discards the drop. 2381 return; 2382 } 2383 } 2384 2385 final int originalLength = mTextView.getText().length(); 2386 int min = offset; 2387 int max = offset; 2388 2389 Selection.setSelection((Spannable) mTextView.getText(), max); 2390 mTextView.replaceText_internal(min, max, content); 2391 2392 if (dragDropIntoItself) { 2393 int dragSourceStart = dragLocalState.start; 2394 int dragSourceEnd = dragLocalState.end; 2395 if (max <= dragSourceStart) { 2396 // Inserting text before selection has shifted positions 2397 final int shift = mTextView.getText().length() - originalLength; 2398 dragSourceStart += shift; 2399 dragSourceEnd += shift; 2400 } 2401 2402 // Delete original selection 2403 mTextView.deleteText_internal(dragSourceStart, dragSourceEnd); 2404 2405 // Make sure we do not leave two adjacent spaces. 2406 final int prevCharIdx = Math.max(0, dragSourceStart - 1); 2407 final int nextCharIdx = Math.min(mTextView.getText().length(), dragSourceStart + 1); 2408 if (nextCharIdx > prevCharIdx + 1) { 2409 CharSequence t = mTextView.getTransformedText(prevCharIdx, nextCharIdx); 2410 if (Character.isSpaceChar(t.charAt(0)) && Character.isSpaceChar(t.charAt(1))) { 2411 mTextView.deleteText_internal(prevCharIdx, prevCharIdx + 1); 2412 } 2413 } 2414 } 2415 } 2416 2417 public void addSpanWatchers(Spannable text) { 2418 final int textLength = text.length(); 2419 2420 if (mKeyListener != null) { 2421 text.setSpan(mKeyListener, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 2422 } 2423 2424 if (mSpanController == null) { 2425 mSpanController = new SpanController(); 2426 } 2427 text.setSpan(mSpanController, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 2428 } 2429 2430 void setContextMenuAnchor(float x, float y) { 2431 mContextMenuAnchorX = x; 2432 mContextMenuAnchorY = y; 2433 } 2434 2435 void onCreateContextMenu(ContextMenu menu) { 2436 if (mIsBeingLongClicked || Float.isNaN(mContextMenuAnchorX) 2437 || Float.isNaN(mContextMenuAnchorY)) { 2438 return; 2439 } 2440 final int offset = mTextView.getOffsetForPosition(mContextMenuAnchorX, mContextMenuAnchorY); 2441 if (offset == -1) { 2442 return; 2443 } 2444 stopTextActionModeWithPreservingSelection(); 2445 final boolean isOnSelection = mTextView.hasSelection() 2446 && offset >= mTextView.getSelectionStart() && offset <= mTextView.getSelectionEnd(); 2447 if (!isOnSelection) { 2448 // Right clicked position is not on the selection. Remove the selection and move the 2449 // cursor to the right clicked position. 2450 Selection.setSelection((Spannable) mTextView.getText(), offset); 2451 stopTextActionMode(); 2452 } 2453 2454 if (shouldOfferToShowSuggestions()) { 2455 if (mSuggestionInfosInContextMenu == null) { 2456 mSuggestionInfosInContextMenu = 2457 new SuggestionInfo[SuggestionSpan.SUGGESTIONS_MAX_SIZE]; 2458 for (int i = 0; i < mSuggestionInfosInContextMenu.length; i++) { 2459 mSuggestionInfosInContextMenu[i] = new SuggestionInfo(); 2460 } 2461 } 2462 final SubMenu subMenu = menu.addSubMenu(Menu.NONE, Menu.NONE, MENU_ITEM_ORDER_REPLACE, 2463 com.android.internal.R.string.replace); 2464 mSuggestionHelper.getSuggestionInfo(mSuggestionInfosInContextMenu); 2465 int i = 0; 2466 for (final SuggestionInfo info : mSuggestionInfosInContextMenu) { 2467 info.mSuggestionEnd = info.mText.length(); 2468 subMenu.add(Menu.NONE, Menu.NONE, i++, info.mText) 2469 .setOnMenuItemClickListener(mOnContextMenuReplaceItemClickListener); 2470 } 2471 } 2472 2473 menu.add(Menu.NONE, TextView.ID_UNDO, MENU_ITEM_ORDER_UNDO, 2474 com.android.internal.R.string.undo) 2475 .setAlphabeticShortcut('z') 2476 .setOnMenuItemClickListener(mOnContextMenuItemClickListener) 2477 .setEnabled(mTextView.canUndo()); 2478 menu.add(Menu.NONE, TextView.ID_REDO, MENU_ITEM_ORDER_REDO, 2479 com.android.internal.R.string.redo) 2480 .setOnMenuItemClickListener(mOnContextMenuItemClickListener) 2481 .setEnabled(mTextView.canRedo()); 2482 2483 menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT, 2484 com.android.internal.R.string.cut) 2485 .setAlphabeticShortcut('x') 2486 .setOnMenuItemClickListener(mOnContextMenuItemClickListener) 2487 .setEnabled(mTextView.canCut()); 2488 menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY, 2489 com.android.internal.R.string.copy) 2490 .setAlphabeticShortcut('c') 2491 .setOnMenuItemClickListener(mOnContextMenuItemClickListener) 2492 .setEnabled(mTextView.canCopy()); 2493 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE, 2494 com.android.internal.R.string.paste) 2495 .setAlphabeticShortcut('v') 2496 .setEnabled(mTextView.canPaste()) 2497 .setOnMenuItemClickListener(mOnContextMenuItemClickListener); 2498 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT, 2499 com.android.internal.R.string.paste_as_plain_text) 2500 .setEnabled(mTextView.canPaste()) 2501 .setOnMenuItemClickListener(mOnContextMenuItemClickListener); 2502 menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE, 2503 com.android.internal.R.string.share) 2504 .setEnabled(mTextView.canShare()) 2505 .setOnMenuItemClickListener(mOnContextMenuItemClickListener); 2506 menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL, 2507 com.android.internal.R.string.selectAll) 2508 .setAlphabeticShortcut('a') 2509 .setEnabled(mTextView.canSelectAllText()) 2510 .setOnMenuItemClickListener(mOnContextMenuItemClickListener); 2511 2512 mPreserveSelection = true; 2513 } 2514 2515 private void replaceWithSuggestion(final SuggestionInfo suggestionInfo) { 2516 final Editable editable = (Editable) mTextView.getText(); 2517 if (editable.getSpanStart(suggestionInfo.mSuggestionSpan) < 0) { 2518 // Suggestion span coundn't be found. Try to find a suggestion span that has the same 2519 // contents. 2520 final SuggestionSpan[] suggestionSpans = editable.getSpans( 2521 suggestionInfo.mSuggestionSpanStart, suggestionInfo.mSuggestionSpanEnd, 2522 SuggestionSpan.class); 2523 for (final SuggestionSpan suggestionSpan : suggestionSpans) { 2524 final int spanStart = editable.getSpanStart(suggestionSpan); 2525 if (spanStart != suggestionInfo.mSuggestionSpanStart) { 2526 continue; 2527 } 2528 int spanEnd = editable.getSpanEnd(suggestionSpan); 2529 if (spanEnd != suggestionInfo.mSuggestionSpanEnd) { 2530 continue; 2531 } 2532 if (suggestionSpan.equals(suggestionInfo.mSuggestionSpan)) { 2533 // Found. 2534 suggestionInfo.mSuggestionSpan = suggestionSpan; 2535 break; 2536 } 2537 } 2538 } 2539 final int spanStart = editable.getSpanStart(suggestionInfo.mSuggestionSpan); 2540 final int spanEnd = editable.getSpanEnd(suggestionInfo.mSuggestionSpan); 2541 if (spanStart < 0 || spanEnd <= spanStart) { 2542 // Span has been removed 2543 return; 2544 } 2545 2546 final String originalText = TextUtils.substring(editable, spanStart, spanEnd); 2547 // SuggestionSpans are removed by replace: save them before 2548 SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd, 2549 SuggestionSpan.class); 2550 final int length = suggestionSpans.length; 2551 int[] suggestionSpansStarts = new int[length]; 2552 int[] suggestionSpansEnds = new int[length]; 2553 int[] suggestionSpansFlags = new int[length]; 2554 for (int i = 0; i < length; i++) { 2555 final SuggestionSpan suggestionSpan = suggestionSpans[i]; 2556 suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan); 2557 suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan); 2558 suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan); 2559 2560 // Remove potential misspelled flags 2561 int suggestionSpanFlags = suggestionSpan.getFlags(); 2562 if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) != 0) { 2563 suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED; 2564 suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT; 2565 suggestionSpan.setFlags(suggestionSpanFlags); 2566 } 2567 } 2568 2569 // Notify source IME of the suggestion pick. Do this before swapping texts. 2570 suggestionInfo.mSuggestionSpan.notifySelection( 2571 mTextView.getContext(), originalText, suggestionInfo.mSuggestionIndex); 2572 2573 // Swap text content between actual text and Suggestion span 2574 final int suggestionStart = suggestionInfo.mSuggestionStart; 2575 final int suggestionEnd = suggestionInfo.mSuggestionEnd; 2576 final String suggestion = suggestionInfo.mText.subSequence( 2577 suggestionStart, suggestionEnd).toString(); 2578 mTextView.replaceText_internal(spanStart, spanEnd, suggestion); 2579 2580 String[] suggestions = suggestionInfo.mSuggestionSpan.getSuggestions(); 2581 suggestions[suggestionInfo.mSuggestionIndex] = originalText; 2582 2583 // Restore previous SuggestionSpans 2584 final int lengthDelta = suggestion.length() - (spanEnd - spanStart); 2585 for (int i = 0; i < length; i++) { 2586 // Only spans that include the modified region make sense after replacement 2587 // Spans partially included in the replaced region are removed, there is no 2588 // way to assign them a valid range after replacement 2589 if (suggestionSpansStarts[i] <= spanStart && suggestionSpansEnds[i] >= spanEnd) { 2590 mTextView.setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i], 2591 suggestionSpansEnds[i] + lengthDelta, suggestionSpansFlags[i]); 2592 } 2593 } 2594 // Move cursor at the end of the replaced word 2595 final int newCursorPosition = spanEnd + lengthDelta; 2596 mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition); 2597 } 2598 2599 private final MenuItem.OnMenuItemClickListener mOnContextMenuItemClickListener = 2600 new MenuItem.OnMenuItemClickListener() { 2601 @Override 2602 public boolean onMenuItemClick(MenuItem item) { 2603 if (mProcessTextIntentActionsHandler.performMenuItemAction(item)) { 2604 return true; 2605 } 2606 return mTextView.onTextContextMenuItem(item.getItemId()); 2607 } 2608 }; 2609 2610 private final MenuItem.OnMenuItemClickListener mOnContextMenuReplaceItemClickListener = 2611 new MenuItem.OnMenuItemClickListener() { 2612 @Override 2613 public boolean onMenuItemClick(MenuItem item) { 2614 int index = item.getOrder(); 2615 if (index < 0 || index >= mSuggestionInfosInContextMenu.length) { 2616 clear(); 2617 return false; 2618 } 2619 replaceWithSuggestion(mSuggestionInfosInContextMenu[index]); 2620 clear(); 2621 return true; 2622 } 2623 2624 private void clear() { 2625 for (final SuggestionInfo info : mSuggestionInfosInContextMenu) { 2626 info.clear(); 2627 } 2628 } 2629 }; 2630 2631 /** 2632 * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related 2633 * pop-up should be displayed. 2634 * Also monitors {@link Selection} to call back to the attached input method. 2635 */ 2636 class SpanController implements SpanWatcher { 2637 2638 private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs 2639 2640 private EasyEditPopupWindow mPopupWindow; 2641 2642 private Runnable mHidePopup; 2643 2644 // This function is pure but inner classes can't have static functions 2645 private boolean isNonIntermediateSelectionSpan(final Spannable text, 2646 final Object span) { 2647 return (Selection.SELECTION_START == span || Selection.SELECTION_END == span) 2648 && (text.getSpanFlags(span) & Spanned.SPAN_INTERMEDIATE) == 0; 2649 } 2650 2651 @Override 2652 public void onSpanAdded(Spannable text, Object span, int start, int end) { 2653 if (isNonIntermediateSelectionSpan(text, span)) { 2654 sendUpdateSelection(); 2655 } else if (span instanceof EasyEditSpan) { 2656 if (mPopupWindow == null) { 2657 mPopupWindow = new EasyEditPopupWindow(); 2658 mHidePopup = new Runnable() { 2659 @Override 2660 public void run() { 2661 hide(); 2662 } 2663 }; 2664 } 2665 2666 // Make sure there is only at most one EasyEditSpan in the text 2667 if (mPopupWindow.mEasyEditSpan != null) { 2668 mPopupWindow.mEasyEditSpan.setDeleteEnabled(false); 2669 } 2670 2671 mPopupWindow.setEasyEditSpan((EasyEditSpan) span); 2672 mPopupWindow.setOnDeleteListener(new EasyEditDeleteListener() { 2673 @Override 2674 public void onDeleteClick(EasyEditSpan span) { 2675 Editable editable = (Editable) mTextView.getText(); 2676 int start = editable.getSpanStart(span); 2677 int end = editable.getSpanEnd(span); 2678 if (start >= 0 && end >= 0) { 2679 sendEasySpanNotification(EasyEditSpan.TEXT_DELETED, span); 2680 mTextView.deleteText_internal(start, end); 2681 } 2682 editable.removeSpan(span); 2683 } 2684 }); 2685 2686 if (mTextView.getWindowVisibility() != View.VISIBLE) { 2687 // The window is not visible yet, ignore the text change. 2688 return; 2689 } 2690 2691 if (mTextView.getLayout() == null) { 2692 // The view has not been laid out yet, ignore the text change 2693 return; 2694 } 2695 2696 if (extractedTextModeWillBeStarted()) { 2697 // The input is in extract mode. Do not handle the easy edit in 2698 // the original TextView, as the ExtractEditText will do 2699 return; 2700 } 2701 2702 mPopupWindow.show(); 2703 mTextView.removeCallbacks(mHidePopup); 2704 mTextView.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS); 2705 } 2706 } 2707 2708 @Override 2709 public void onSpanRemoved(Spannable text, Object span, int start, int end) { 2710 if (isNonIntermediateSelectionSpan(text, span)) { 2711 sendUpdateSelection(); 2712 } else if (mPopupWindow != null && span == mPopupWindow.mEasyEditSpan) { 2713 hide(); 2714 } 2715 } 2716 2717 @Override 2718 public void onSpanChanged(Spannable text, Object span, int previousStart, int previousEnd, 2719 int newStart, int newEnd) { 2720 if (isNonIntermediateSelectionSpan(text, span)) { 2721 sendUpdateSelection(); 2722 } else if (mPopupWindow != null && span instanceof EasyEditSpan) { 2723 EasyEditSpan easyEditSpan = (EasyEditSpan) span; 2724 sendEasySpanNotification(EasyEditSpan.TEXT_MODIFIED, easyEditSpan); 2725 text.removeSpan(easyEditSpan); 2726 } 2727 } 2728 2729 public void hide() { 2730 if (mPopupWindow != null) { 2731 mPopupWindow.hide(); 2732 mTextView.removeCallbacks(mHidePopup); 2733 } 2734 } 2735 2736 private void sendEasySpanNotification(int textChangedType, EasyEditSpan span) { 2737 try { 2738 PendingIntent pendingIntent = span.getPendingIntent(); 2739 if (pendingIntent != null) { 2740 Intent intent = new Intent(); 2741 intent.putExtra(EasyEditSpan.EXTRA_TEXT_CHANGED_TYPE, textChangedType); 2742 pendingIntent.send(mTextView.getContext(), 0, intent); 2743 } 2744 } catch (CanceledException e) { 2745 // This should not happen, as we should try to send the intent only once. 2746 Log.w(TAG, "PendingIntent for notification cannot be sent", e); 2747 } 2748 } 2749 } 2750 2751 /** 2752 * Listens for the delete event triggered by {@link EasyEditPopupWindow}. 2753 */ 2754 private interface EasyEditDeleteListener { 2755 2756 /** 2757 * Clicks the delete pop-up. 2758 */ 2759 void onDeleteClick(EasyEditSpan span); 2760 } 2761 2762 /** 2763 * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled 2764 * by {@link SpanController}. 2765 */ 2766 private class EasyEditPopupWindow extends PinnedPopupWindow 2767 implements OnClickListener { 2768 private static final int POPUP_TEXT_LAYOUT = 2769 com.android.internal.R.layout.text_edit_action_popup_text; 2770 private TextView mDeleteTextView; 2771 private EasyEditSpan mEasyEditSpan; 2772 private EasyEditDeleteListener mOnDeleteListener; 2773 2774 @Override 2775 protected void createPopupWindow() { 2776 mPopupWindow = new PopupWindow(mTextView.getContext(), null, 2777 com.android.internal.R.attr.textSelectHandleWindowStyle); 2778 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 2779 mPopupWindow.setClippingEnabled(true); 2780 } 2781 2782 @Override 2783 protected void initContentView() { 2784 LinearLayout linearLayout = new LinearLayout(mTextView.getContext()); 2785 linearLayout.setOrientation(LinearLayout.HORIZONTAL); 2786 mContentView = linearLayout; 2787 mContentView.setBackgroundResource( 2788 com.android.internal.R.drawable.text_edit_side_paste_window); 2789 2790 LayoutInflater inflater = (LayoutInflater)mTextView.getContext(). 2791 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 2792 2793 LayoutParams wrapContent = new LayoutParams( 2794 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 2795 2796 mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 2797 mDeleteTextView.setLayoutParams(wrapContent); 2798 mDeleteTextView.setText(com.android.internal.R.string.delete); 2799 mDeleteTextView.setOnClickListener(this); 2800 mContentView.addView(mDeleteTextView); 2801 } 2802 2803 public void setEasyEditSpan(EasyEditSpan easyEditSpan) { 2804 mEasyEditSpan = easyEditSpan; 2805 } 2806 2807 private void setOnDeleteListener(EasyEditDeleteListener listener) { 2808 mOnDeleteListener = listener; 2809 } 2810 2811 @Override 2812 public void onClick(View view) { 2813 if (view == mDeleteTextView 2814 && mEasyEditSpan != null && mEasyEditSpan.isDeleteEnabled() 2815 && mOnDeleteListener != null) { 2816 mOnDeleteListener.onDeleteClick(mEasyEditSpan); 2817 } 2818 } 2819 2820 @Override 2821 public void hide() { 2822 if (mEasyEditSpan != null) { 2823 mEasyEditSpan.setDeleteEnabled(false); 2824 } 2825 mOnDeleteListener = null; 2826 super.hide(); 2827 } 2828 2829 @Override 2830 protected int getTextOffset() { 2831 // Place the pop-up at the end of the span 2832 Editable editable = (Editable) mTextView.getText(); 2833 return editable.getSpanEnd(mEasyEditSpan); 2834 } 2835 2836 @Override 2837 protected int getVerticalLocalPosition(int line) { 2838 return mTextView.getLayout().getLineBottom(line); 2839 } 2840 2841 @Override 2842 protected int clipVertically(int positionY) { 2843 // As we display the pop-up below the span, no vertical clipping is required. 2844 return positionY; 2845 } 2846 } 2847 2848 private class PositionListener implements ViewTreeObserver.OnPreDrawListener { 2849 // 3 handles 2850 // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others) 2851 // 1 CursorAnchorInfoNotifier 2852 private final int MAXIMUM_NUMBER_OF_LISTENERS = 7; 2853 private TextViewPositionListener[] mPositionListeners = 2854 new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS]; 2855 private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS]; 2856 private boolean mPositionHasChanged = true; 2857 // Absolute position of the TextView with respect to its parent window 2858 private int mPositionX, mPositionY; 2859 private int mNumberOfListeners; 2860 private boolean mScrollHasChanged; 2861 final int[] mTempCoords = new int[2]; 2862 2863 public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) { 2864 if (mNumberOfListeners == 0) { 2865 updatePosition(); 2866 ViewTreeObserver vto = mTextView.getViewTreeObserver(); 2867 vto.addOnPreDrawListener(this); 2868 } 2869 2870 int emptySlotIndex = -1; 2871 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 2872 TextViewPositionListener listener = mPositionListeners[i]; 2873 if (listener == positionListener) { 2874 return; 2875 } else if (emptySlotIndex < 0 && listener == null) { 2876 emptySlotIndex = i; 2877 } 2878 } 2879 2880 mPositionListeners[emptySlotIndex] = positionListener; 2881 mCanMove[emptySlotIndex] = canMove; 2882 mNumberOfListeners++; 2883 } 2884 2885 public void removeSubscriber(TextViewPositionListener positionListener) { 2886 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 2887 if (mPositionListeners[i] == positionListener) { 2888 mPositionListeners[i] = null; 2889 mNumberOfListeners--; 2890 break; 2891 } 2892 } 2893 2894 if (mNumberOfListeners == 0) { 2895 ViewTreeObserver vto = mTextView.getViewTreeObserver(); 2896 vto.removeOnPreDrawListener(this); 2897 } 2898 } 2899 2900 public int getPositionX() { 2901 return mPositionX; 2902 } 2903 2904 public int getPositionY() { 2905 return mPositionY; 2906 } 2907 2908 @Override 2909 public boolean onPreDraw() { 2910 updatePosition(); 2911 2912 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 2913 if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) { 2914 TextViewPositionListener positionListener = mPositionListeners[i]; 2915 if (positionListener != null) { 2916 positionListener.updatePosition(mPositionX, mPositionY, 2917 mPositionHasChanged, mScrollHasChanged); 2918 } 2919 } 2920 } 2921 2922 mScrollHasChanged = false; 2923 return true; 2924 } 2925 2926 private void updatePosition() { 2927 mTextView.getLocationInWindow(mTempCoords); 2928 2929 mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY; 2930 2931 mPositionX = mTempCoords[0]; 2932 mPositionY = mTempCoords[1]; 2933 } 2934 2935 public void onScrollChanged() { 2936 mScrollHasChanged = true; 2937 } 2938 } 2939 2940 private abstract class PinnedPopupWindow implements TextViewPositionListener { 2941 protected PopupWindow mPopupWindow; 2942 protected ViewGroup mContentView; 2943 int mPositionX, mPositionY; 2944 int mClippingLimitLeft, mClippingLimitRight; 2945 2946 protected abstract void createPopupWindow(); 2947 protected abstract void initContentView(); 2948 protected abstract int getTextOffset(); 2949 protected abstract int getVerticalLocalPosition(int line); 2950 protected abstract int clipVertically(int positionY); 2951 2952 public PinnedPopupWindow() { 2953 createPopupWindow(); 2954 2955 mPopupWindow.setWindowLayoutType( 2956 WindowManager.LayoutParams.TYPE_APPLICATION_ABOVE_SUB_PANEL); 2957 mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 2958 mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 2959 2960 initContentView(); 2961 2962 LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 2963 ViewGroup.LayoutParams.WRAP_CONTENT); 2964 mContentView.setLayoutParams(wrapContent); 2965 2966 mPopupWindow.setContentView(mContentView); 2967 } 2968 2969 public void show() { 2970 getPositionListener().addSubscriber(this, false /* offset is fixed */); 2971 2972 computeLocalPosition(); 2973 2974 final PositionListener positionListener = getPositionListener(); 2975 updatePosition(positionListener.getPositionX(), positionListener.getPositionY()); 2976 } 2977 2978 protected void measureContent() { 2979 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 2980 mContentView.measure( 2981 View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, 2982 View.MeasureSpec.AT_MOST), 2983 View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, 2984 View.MeasureSpec.AT_MOST)); 2985 } 2986 2987 /* The popup window will be horizontally centered on the getTextOffset() and vertically 2988 * positioned according to viewportToContentHorizontalOffset. 2989 * 2990 * This method assumes that mContentView has properly been measured from its content. */ 2991 private void computeLocalPosition() { 2992 measureContent(); 2993 final int width = mContentView.getMeasuredWidth(); 2994 final int offset = getTextOffset(); 2995 mPositionX = (int) (mTextView.getLayout().getPrimaryHorizontal(offset) - width / 2.0f); 2996 mPositionX += mTextView.viewportToContentHorizontalOffset(); 2997 2998 final int line = mTextView.getLayout().getLineForOffset(offset); 2999 mPositionY = getVerticalLocalPosition(line); 3000 mPositionY += mTextView.viewportToContentVerticalOffset(); 3001 } 3002 3003 private void updatePosition(int parentPositionX, int parentPositionY) { 3004 int positionX = parentPositionX + mPositionX; 3005 int positionY = parentPositionY + mPositionY; 3006 3007 positionY = clipVertically(positionY); 3008 3009 // Horizontal clipping 3010 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 3011 final int width = mContentView.getMeasuredWidth(); 3012 positionX = Math.min( 3013 displayMetrics.widthPixels - width + mClippingLimitRight, positionX); 3014 positionX = Math.max(-mClippingLimitLeft, positionX); 3015 3016 if (isShowing()) { 3017 mPopupWindow.update(positionX, positionY, -1, -1); 3018 } else { 3019 mPopupWindow.showAtLocation(mTextView, Gravity.NO_GRAVITY, 3020 positionX, positionY); 3021 } 3022 } 3023 3024 public void hide() { 3025 if (!isShowing()) { 3026 return; 3027 } 3028 mPopupWindow.dismiss(); 3029 getPositionListener().removeSubscriber(this); 3030 } 3031 3032 @Override 3033 public void updatePosition(int parentPositionX, int parentPositionY, 3034 boolean parentPositionChanged, boolean parentScrolled) { 3035 // Either parentPositionChanged or parentScrolled is true, check if still visible 3036 if (isShowing() && isOffsetVisible(getTextOffset())) { 3037 if (parentScrolled) computeLocalPosition(); 3038 updatePosition(parentPositionX, parentPositionY); 3039 } else { 3040 hide(); 3041 } 3042 } 3043 3044 public boolean isShowing() { 3045 return mPopupWindow.isShowing(); 3046 } 3047 } 3048 3049 private static class SuggestionInfo { 3050 // Range of actual suggestion within mText 3051 int mSuggestionStart, mSuggestionEnd; 3052 3053 // The SuggestionSpan that this TextView represents 3054 @Nullable 3055 SuggestionSpan mSuggestionSpan; 3056 3057 // The SuggestionSpan start position 3058 int mSuggestionSpanStart; 3059 3060 // The SuggestionSpan end position 3061 int mSuggestionSpanEnd; 3062 3063 // The index of this suggestion inside suggestionSpan 3064 int mSuggestionIndex; 3065 3066 final SpannableStringBuilder mText = new SpannableStringBuilder(); 3067 3068 void clear() { 3069 mSuggestionSpan = null; 3070 mText.clear(); 3071 } 3072 } 3073 3074 private class SuggestionHelper { 3075 private final Comparator<SuggestionSpan> mSuggestionSpanComparator = 3076 new SuggestionSpanComparator(); 3077 private final HashMap<SuggestionSpan, Integer> mSpansLengths = 3078 new HashMap<SuggestionSpan, Integer>(); 3079 3080 private class SuggestionSpanComparator implements Comparator<SuggestionSpan> { 3081 public int compare(SuggestionSpan span1, SuggestionSpan span2) { 3082 final int flag1 = span1.getFlags(); 3083 final int flag2 = span2.getFlags(); 3084 if (flag1 != flag2) { 3085 // The order here should match what is used in updateDrawState 3086 final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0; 3087 final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0; 3088 final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0; 3089 final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0; 3090 if (easy1 && !misspelled1) return -1; 3091 if (easy2 && !misspelled2) return 1; 3092 if (misspelled1) return -1; 3093 if (misspelled2) return 1; 3094 } 3095 3096 return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue(); 3097 } 3098 } 3099 3100 /** 3101 * Returns the suggestion spans that cover the current cursor position. The suggestion 3102 * spans are sorted according to the length of text that they are attached to. 3103 */ 3104 private SuggestionSpan[] getSortedSuggestionSpans() { 3105 int pos = mTextView.getSelectionStart(); 3106 Spannable spannable = (Spannable) mTextView.getText(); 3107 SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class); 3108 3109 mSpansLengths.clear(); 3110 for (SuggestionSpan suggestionSpan : suggestionSpans) { 3111 int start = spannable.getSpanStart(suggestionSpan); 3112 int end = spannable.getSpanEnd(suggestionSpan); 3113 mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start)); 3114 } 3115 3116 // The suggestions are sorted according to their types (easy correction first, then 3117 // misspelled) and to the length of the text that they cover (shorter first). 3118 Arrays.sort(suggestionSpans, mSuggestionSpanComparator); 3119 mSpansLengths.clear(); 3120 3121 return suggestionSpans; 3122 } 3123 3124 /** 3125 * Gets the SuggestionInfo list that contains suggestion information at the current cursor 3126 * position. 3127 * 3128 * @param suggestionInfos SuggestionInfo array the results will be set. 3129 * @return the number of suggestions actually fetched. 3130 */ 3131 public int getSuggestionInfo(SuggestionInfo[] suggestionInfos) { 3132 final Spannable spannable = (Spannable) mTextView.getText(); 3133 final SuggestionSpan[] suggestionSpans = getSortedSuggestionSpans(); 3134 final int nbSpans = suggestionSpans.length; 3135 if (nbSpans == 0) return 0; 3136 3137 int numberOfSuggestions = 0; 3138 for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) { 3139 final SuggestionSpan suggestionSpan = suggestionSpans[spanIndex]; 3140 final int spanStart = spannable.getSpanStart(suggestionSpan); 3141 final int spanEnd = spannable.getSpanEnd(suggestionSpan); 3142 3143 final String[] suggestions = suggestionSpan.getSuggestions(); 3144 final int nbSuggestions = suggestions.length; 3145 for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) { 3146 final String suggestion = suggestions[suggestionIndex]; 3147 boolean suggestionIsDuplicate = false; 3148 for (int i = 0; i < numberOfSuggestions; i++) { 3149 if (suggestionInfos[i].mText.toString().equals(suggestion)) { 3150 final SuggestionSpan otherSuggestionSpan = 3151 suggestionInfos[i].mSuggestionSpan; 3152 final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan); 3153 final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan); 3154 if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) { 3155 suggestionIsDuplicate = true; 3156 break; 3157 } 3158 } 3159 } 3160 3161 if (suggestionIsDuplicate) { 3162 continue; 3163 } 3164 SuggestionInfo suggestionInfo = suggestionInfos[numberOfSuggestions]; 3165 suggestionInfo.mSuggestionSpan = suggestionSpan; 3166 suggestionInfo.mSuggestionIndex = suggestionIndex; 3167 suggestionInfo.mSuggestionStart = 0; 3168 suggestionInfo.mSuggestionEnd = suggestion.length(); 3169 suggestionInfo.mSuggestionSpanStart = spanStart; 3170 suggestionInfo.mSuggestionSpanEnd = spanEnd; 3171 suggestionInfo.mText.replace(0, suggestionInfo.mText.length(), suggestion); 3172 numberOfSuggestions++; 3173 if (numberOfSuggestions >= suggestionInfos.length) { 3174 return numberOfSuggestions; 3175 } 3176 } 3177 } 3178 return numberOfSuggestions; 3179 } 3180 } 3181 3182 @VisibleForTesting 3183 public class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener { 3184 private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE; 3185 3186 // Key of intent extras for inserting new word into user dictionary. 3187 private static final String USER_DICTIONARY_EXTRA_WORD = "word"; 3188 private static final String USER_DICTIONARY_EXTRA_LOCALE = "locale"; 3189 3190 private SuggestionInfo[] mSuggestionInfos; 3191 private int mNumberOfSuggestions; 3192 private boolean mCursorWasVisibleBeforeSuggestions; 3193 private boolean mIsShowingUp = false; 3194 private SuggestionAdapter mSuggestionsAdapter; 3195 private final TextAppearanceSpan mHighlightSpan = new TextAppearanceSpan( 3196 mTextView.getContext(), mTextView.mTextEditSuggestionHighlightStyle); 3197 private TextView mAddToDictionaryButton; 3198 private TextView mDeleteButton; 3199 private ListView mSuggestionListView; 3200 private SuggestionSpan mMisspelledSpan; 3201 private int mContainerMarginWidth; 3202 private int mContainerMarginTop; 3203 3204 private class CustomPopupWindow extends PopupWindow { 3205 @Override 3206 public void dismiss() { 3207 if (!isShowing()) { 3208 return; 3209 } 3210 super.dismiss(); 3211 getPositionListener().removeSubscriber(SuggestionsPopupWindow.this); 3212 3213 // Safe cast since show() checks that mTextView.getText() is an Editable 3214 ((Spannable) mTextView.getText()).removeSpan(mSuggestionRangeSpan); 3215 3216 mTextView.setCursorVisible(mCursorWasVisibleBeforeSuggestions); 3217 if (hasInsertionController() && !extractedTextModeWillBeStarted()) { 3218 getInsertionController().show(); 3219 } 3220 } 3221 } 3222 3223 public SuggestionsPopupWindow() { 3224 mCursorWasVisibleBeforeSuggestions = mCursorVisible; 3225 } 3226 3227 @Override 3228 protected void createPopupWindow() { 3229 mPopupWindow = new CustomPopupWindow(); 3230 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 3231 mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); 3232 mPopupWindow.setFocusable(true); 3233 mPopupWindow.setClippingEnabled(false); 3234 } 3235 3236 @Override 3237 protected void initContentView() { 3238 final LayoutInflater inflater = (LayoutInflater) mTextView.getContext(). 3239 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 3240 final ViewGroup relativeLayout = (ViewGroup) inflater.inflate( 3241 mTextView.mTextEditSuggestionContainerLayout, null); 3242 3243 final LinearLayout suggestionWindowContainer = 3244 (LinearLayout) relativeLayout.findViewById( 3245 com.android.internal.R.id.suggestionWindowContainer); 3246 ViewGroup.MarginLayoutParams lp = 3247 (ViewGroup.MarginLayoutParams) suggestionWindowContainer.getLayoutParams(); 3248 mContainerMarginWidth = lp.leftMargin + lp.rightMargin; 3249 mContainerMarginTop = lp.topMargin; 3250 mClippingLimitLeft = lp.leftMargin; 3251 mClippingLimitRight = lp.rightMargin; 3252 3253 mSuggestionListView = (ListView) relativeLayout.findViewById( 3254 com.android.internal.R.id.suggestionContainer); 3255 3256 mSuggestionsAdapter = new SuggestionAdapter(); 3257 mSuggestionListView.setAdapter(mSuggestionsAdapter); 3258 mSuggestionListView.setOnItemClickListener(this); 3259 3260 // Inflate the suggestion items once and for all. 3261 mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS]; 3262 for (int i = 0; i < mSuggestionInfos.length; i++) { 3263 mSuggestionInfos[i] = new SuggestionInfo(); 3264 } 3265 3266 mContentView = relativeLayout; 3267 3268 mAddToDictionaryButton = (TextView) relativeLayout.findViewById( 3269 com.android.internal.R.id.addToDictionaryButton); 3270 mAddToDictionaryButton.setOnClickListener(new View.OnClickListener() { 3271 public void onClick(View v) { 3272 final Editable editable = (Editable) mTextView.getText(); 3273 final int spanStart = editable.getSpanStart(mMisspelledSpan); 3274 final int spanEnd = editable.getSpanEnd(mMisspelledSpan); 3275 final String originalText = TextUtils.substring(editable, spanStart, spanEnd); 3276 3277 final Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT); 3278 intent.putExtra(USER_DICTIONARY_EXTRA_WORD, originalText); 3279 intent.putExtra(USER_DICTIONARY_EXTRA_LOCALE, 3280 mTextView.getTextServicesLocale().toString()); 3281 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 3282 mTextView.getContext().startActivity(intent); 3283 // There is no way to know if the word was indeed added. Re-check. 3284 // TODO The ExtractEditText should remove the span in the original text instead 3285 editable.removeSpan(mMisspelledSpan); 3286 Selection.setSelection(editable, spanEnd); 3287 updateSpellCheckSpans(spanStart, spanEnd, false); 3288 hideWithCleanUp(); 3289 } 3290 }); 3291 3292 mDeleteButton = (TextView) relativeLayout.findViewById( 3293 com.android.internal.R.id.deleteButton); 3294 mDeleteButton.setOnClickListener(new View.OnClickListener() { 3295 public void onClick(View v) { 3296 final Editable editable = (Editable) mTextView.getText(); 3297 3298 final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan); 3299 int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan); 3300 if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) { 3301 // Do not leave two adjacent spaces after deletion, or one at beginning of 3302 // text 3303 if (spanUnionEnd < editable.length() && 3304 Character.isSpaceChar(editable.charAt(spanUnionEnd)) && 3305 (spanUnionStart == 0 || 3306 Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) { 3307 spanUnionEnd = spanUnionEnd + 1; 3308 } 3309 mTextView.deleteText_internal(spanUnionStart, spanUnionEnd); 3310 } 3311 hideWithCleanUp(); 3312 } 3313 }); 3314 3315 } 3316 3317 public boolean isShowingUp() { 3318 return mIsShowingUp; 3319 } 3320 3321 public void onParentLostFocus() { 3322 mIsShowingUp = false; 3323 } 3324 3325 private class SuggestionAdapter extends BaseAdapter { 3326 private LayoutInflater mInflater = (LayoutInflater) mTextView.getContext(). 3327 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 3328 3329 @Override 3330 public int getCount() { 3331 return mNumberOfSuggestions; 3332 } 3333 3334 @Override 3335 public Object getItem(int position) { 3336 return mSuggestionInfos[position]; 3337 } 3338 3339 @Override 3340 public long getItemId(int position) { 3341 return position; 3342 } 3343 3344 @Override 3345 public View getView(int position, View convertView, ViewGroup parent) { 3346 TextView textView = (TextView) convertView; 3347 3348 if (textView == null) { 3349 textView = (TextView) mInflater.inflate(mTextView.mTextEditSuggestionItemLayout, 3350 parent, false); 3351 } 3352 3353 final SuggestionInfo suggestionInfo = mSuggestionInfos[position]; 3354 textView.setText(suggestionInfo.mText); 3355 return textView; 3356 } 3357 } 3358 3359 @VisibleForTesting 3360 public ViewGroup getContentViewForTesting() { 3361 return mContentView; 3362 } 3363 3364 @Override 3365 public void show() { 3366 if (!(mTextView.getText() instanceof Editable)) return; 3367 if (extractedTextModeWillBeStarted()) { 3368 return; 3369 } 3370 3371 if (updateSuggestions()) { 3372 mCursorWasVisibleBeforeSuggestions = mCursorVisible; 3373 mTextView.setCursorVisible(false); 3374 mIsShowingUp = true; 3375 super.show(); 3376 } 3377 } 3378 3379 @Override 3380 protected void measureContent() { 3381 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 3382 final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec( 3383 displayMetrics.widthPixels, View.MeasureSpec.AT_MOST); 3384 final int verticalMeasure = View.MeasureSpec.makeMeasureSpec( 3385 displayMetrics.heightPixels, View.MeasureSpec.AT_MOST); 3386 3387 int width = 0; 3388 View view = null; 3389 for (int i = 0; i < mNumberOfSuggestions; i++) { 3390 view = mSuggestionsAdapter.getView(i, view, mContentView); 3391 view.getLayoutParams().width = LayoutParams.WRAP_CONTENT; 3392 view.measure(horizontalMeasure, verticalMeasure); 3393 width = Math.max(width, view.getMeasuredWidth()); 3394 } 3395 3396 if (mAddToDictionaryButton.getVisibility() != View.GONE) { 3397 mAddToDictionaryButton.measure(horizontalMeasure, verticalMeasure); 3398 width = Math.max(width, mAddToDictionaryButton.getMeasuredWidth()); 3399 } 3400 3401 mDeleteButton.measure(horizontalMeasure, verticalMeasure); 3402 width = Math.max(width, mDeleteButton.getMeasuredWidth()); 3403 3404 width += mContainerMarginWidth; 3405 3406 // Enforce the width based on actual text widths 3407 mContentView.measure( 3408 View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), 3409 verticalMeasure); 3410 3411 Drawable popupBackground = mPopupWindow.getBackground(); 3412 if (popupBackground != null) { 3413 if (mTempRect == null) mTempRect = new Rect(); 3414 popupBackground.getPadding(mTempRect); 3415 width += mTempRect.left + mTempRect.right; 3416 } 3417 mSuggestionListView.getLayoutParams().width = width; 3418 mPopupWindow.setWidth(width); 3419 } 3420 3421 @Override 3422 protected int getTextOffset() { 3423 return mTextView.getSelectionStart(); 3424 } 3425 3426 @Override 3427 protected int getVerticalLocalPosition(int line) { 3428 return mTextView.getLayout().getLineBottom(line) - mContainerMarginTop; 3429 } 3430 3431 @Override 3432 protected int clipVertically(int positionY) { 3433 final int height = mContentView.getMeasuredHeight(); 3434 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics(); 3435 return Math.min(positionY, displayMetrics.heightPixels - height); 3436 } 3437 3438 private void hideWithCleanUp() { 3439 for (final SuggestionInfo info : mSuggestionInfos) { 3440 info.clear(); 3441 } 3442 mMisspelledSpan = null; 3443 hide(); 3444 } 3445 3446 private boolean updateSuggestions() { 3447 Spannable spannable = (Spannable) mTextView.getText(); 3448 mNumberOfSuggestions = 3449 mSuggestionHelper.getSuggestionInfo(mSuggestionInfos); 3450 if (mNumberOfSuggestions == 0) { 3451 return false; 3452 } 3453 3454 int spanUnionStart = mTextView.getText().length(); 3455 int spanUnionEnd = 0; 3456 3457 mMisspelledSpan = null; 3458 for (int i = 0; i < mNumberOfSuggestions; i++) { 3459 final SuggestionInfo suggestionInfo = mSuggestionInfos[i]; 3460 final SuggestionSpan suggestionSpan = suggestionInfo.mSuggestionSpan; 3461 if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) { 3462 mMisspelledSpan = suggestionSpan; 3463 } 3464 spanUnionStart = Math.min(spanUnionStart, suggestionInfo.mSuggestionSpanStart); 3465 spanUnionEnd = Math.max(spanUnionEnd, suggestionInfo.mSuggestionSpanEnd); 3466 } 3467 3468 for (int i = 0; i < mNumberOfSuggestions; i++) { 3469 highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd); 3470 } 3471 3472 // Make "Add to dictionary" item visible if there is a span with the misspelled flag 3473 int addToDictionaryButtonVisibility = View.GONE; 3474 if (mMisspelledSpan != null) { 3475 final int misspelledStart = spannable.getSpanStart(mMisspelledSpan); 3476 final int misspelledEnd = spannable.getSpanEnd(mMisspelledSpan); 3477 if (misspelledStart >= 0 && misspelledEnd > misspelledStart) { 3478 addToDictionaryButtonVisibility = View.VISIBLE; 3479 } 3480 } 3481 mAddToDictionaryButton.setVisibility(addToDictionaryButtonVisibility); 3482 3483 if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan(); 3484 final int underlineColor = mSuggestionInfos[0].mSuggestionSpan.getUnderlineColor(); 3485 if (underlineColor == 0) { 3486 // Fallback on the default highlight color when the first span does not provide one 3487 mSuggestionRangeSpan.setBackgroundColor(mTextView.mHighlightColor); 3488 } else { 3489 final float BACKGROUND_TRANSPARENCY = 0.4f; 3490 final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY); 3491 mSuggestionRangeSpan.setBackgroundColor( 3492 (underlineColor & 0x00FFFFFF) + (newAlpha << 24)); 3493 } 3494 spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd, 3495 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 3496 3497 mSuggestionsAdapter.notifyDataSetChanged(); 3498 return true; 3499 } 3500 3501 private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart, 3502 int unionEnd) { 3503 final Spannable text = (Spannable) mTextView.getText(); 3504 final int spanStart = suggestionInfo.mSuggestionSpanStart; 3505 final int spanEnd = suggestionInfo.mSuggestionSpanEnd; 3506 3507 // Adjust the start/end of the suggestion span 3508 suggestionInfo.mSuggestionStart = spanStart - unionStart; 3509 suggestionInfo.mSuggestionEnd = suggestionInfo.mSuggestionStart 3510 + suggestionInfo.mText.length(); 3511 3512 suggestionInfo.mText.setSpan(mHighlightSpan, 0, suggestionInfo.mText.length(), 3513 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 3514 3515 // Add the text before and after the span. 3516 final String textAsString = text.toString(); 3517 suggestionInfo.mText.insert(0, textAsString.substring(unionStart, spanStart)); 3518 suggestionInfo.mText.append(textAsString.substring(spanEnd, unionEnd)); 3519 } 3520 3521 @Override 3522 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 3523 SuggestionInfo suggestionInfo = mSuggestionInfos[position]; 3524 replaceWithSuggestion(suggestionInfo); 3525 hideWithCleanUp(); 3526 } 3527 } 3528 3529 /** 3530 * An ActionMode Callback class that is used to provide actions while in text insertion or 3531 * selection mode. 3532 * 3533 * The default callback provides a subset of Select All, Cut, Copy, Paste, Share and Replace 3534 * actions, depending on which of these this TextView supports and the current selection. 3535 */ 3536 private class TextActionModeCallback extends ActionMode.Callback2 { 3537 private final Path mSelectionPath = new Path(); 3538 private final RectF mSelectionBounds = new RectF(); 3539 private final boolean mHasSelection; 3540 3541 private int mHandleHeight; 3542 3543 public TextActionModeCallback(boolean hasSelection) { 3544 mHasSelection = hasSelection; 3545 if (mHasSelection) { 3546 SelectionModifierCursorController selectionController = getSelectionController(); 3547 if (selectionController.mStartHandle == null) { 3548 // As these are for initializing selectionController, hide() must be called. 3549 selectionController.initDrawables(); 3550 selectionController.initHandles(); 3551 selectionController.hide(); 3552 } 3553 mHandleHeight = Math.max( 3554 mSelectHandleLeft.getMinimumHeight(), 3555 mSelectHandleRight.getMinimumHeight()); 3556 } else { 3557 InsertionPointCursorController insertionController = getInsertionController(); 3558 if (insertionController != null) { 3559 insertionController.getHandle(); 3560 mHandleHeight = mSelectHandleCenter.getMinimumHeight(); 3561 } 3562 } 3563 } 3564 3565 @Override 3566 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 3567 mode.setTitle(null); 3568 mode.setSubtitle(null); 3569 mode.setTitleOptionalHint(true); 3570 populateMenuWithItems(menu); 3571 3572 Callback customCallback = getCustomCallback(); 3573 if (customCallback != null) { 3574 if (!customCallback.onCreateActionMode(mode, menu)) { 3575 // The custom mode can choose to cancel the action mode, dismiss selection. 3576 Selection.setSelection((Spannable) mTextView.getText(), 3577 mTextView.getSelectionEnd()); 3578 return false; 3579 } 3580 } 3581 3582 if (mTextView.canProcessText()) { 3583 mProcessTextIntentActionsHandler.onInitializeMenu(menu); 3584 } 3585 3586 if (menu.hasVisibleItems() || mode.getCustomView() != null) { 3587 return true; 3588 } else { 3589 return false; 3590 } 3591 } 3592 3593 private Callback getCustomCallback() { 3594 return mHasSelection 3595 ? mCustomSelectionActionModeCallback 3596 : mCustomInsertionActionModeCallback; 3597 } 3598 3599 private void populateMenuWithItems(Menu menu) { 3600 if (mTextView.canCut()) { 3601 menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT, 3602 com.android.internal.R.string.cut). 3603 setAlphabeticShortcut('x'). 3604 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 3605 } 3606 3607 if (mTextView.canCopy()) { 3608 menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY, 3609 com.android.internal.R.string.copy). 3610 setAlphabeticShortcut('c'). 3611 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 3612 } 3613 3614 if (mTextView.canPaste()) { 3615 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE, 3616 com.android.internal.R.string.paste). 3617 setAlphabeticShortcut('v'). 3618 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 3619 } 3620 3621 if (mTextView.canShare()) { 3622 menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE, 3623 com.android.internal.R.string.share). 3624 setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); 3625 } 3626 3627 updateSelectAllItem(menu); 3628 updateReplaceItem(menu); 3629 } 3630 3631 @Override 3632 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 3633 updateSelectAllItem(menu); 3634 updateReplaceItem(menu); 3635 3636 Callback customCallback = getCustomCallback(); 3637 if (customCallback != null) { 3638 return customCallback.onPrepareActionMode(mode, menu); 3639 } 3640 return true; 3641 } 3642 3643 private void updateSelectAllItem(Menu menu) { 3644 boolean canSelectAll = mTextView.canSelectAllText(); 3645 boolean selectAllItemExists = menu.findItem(TextView.ID_SELECT_ALL) != null; 3646 if (canSelectAll && !selectAllItemExists) { 3647 menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL, 3648 com.android.internal.R.string.selectAll) 3649 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); 3650 } else if (!canSelectAll && selectAllItemExists) { 3651 menu.removeItem(TextView.ID_SELECT_ALL); 3652 } 3653 } 3654 3655 private void updateReplaceItem(Menu menu) { 3656 boolean canReplace = mTextView.isSuggestionsEnabled() && shouldOfferToShowSuggestions(); 3657 boolean replaceItemExists = menu.findItem(TextView.ID_REPLACE) != null; 3658 if (canReplace && !replaceItemExists) { 3659 menu.add(Menu.NONE, TextView.ID_REPLACE, MENU_ITEM_ORDER_REPLACE, 3660 com.android.internal.R.string.replace) 3661 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); 3662 } else if (!canReplace && replaceItemExists) { 3663 menu.removeItem(TextView.ID_REPLACE); 3664 } 3665 } 3666 3667 @Override 3668 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 3669 if (mProcessTextIntentActionsHandler.performMenuItemAction(item)) { 3670 return true; 3671 } 3672 Callback customCallback = getCustomCallback(); 3673 if (customCallback != null && customCallback.onActionItemClicked(mode, item)) { 3674 return true; 3675 } 3676 return mTextView.onTextContextMenuItem(item.getItemId()); 3677 } 3678 3679 @Override 3680 public void onDestroyActionMode(ActionMode mode) { 3681 Callback customCallback = getCustomCallback(); 3682 if (customCallback != null) { 3683 customCallback.onDestroyActionMode(mode); 3684 } 3685 3686 if (!mPreserveSelection) { 3687 /* 3688 * Leave current selection when we tentatively destroy action mode for the 3689 * selection. If we're detaching from a window, we'll bring back the selection 3690 * mode when (if) we get reattached. 3691 */ 3692 Selection.setSelection((Spannable) mTextView.getText(), 3693 mTextView.getSelectionEnd()); 3694 } 3695 3696 if (mSelectionModifierCursorController != null) { 3697 mSelectionModifierCursorController.hide(); 3698 } 3699 3700 mTextActionMode = null; 3701 } 3702 3703 @Override 3704 public void onGetContentRect(ActionMode mode, View view, Rect outRect) { 3705 if (!view.equals(mTextView) || mTextView.getLayout() == null) { 3706 super.onGetContentRect(mode, view, outRect); 3707 return; 3708 } 3709 if (mTextView.getSelectionStart() != mTextView.getSelectionEnd()) { 3710 // We have a selection. 3711 mSelectionPath.reset(); 3712 mTextView.getLayout().getSelectionPath( 3713 mTextView.getSelectionStart(), mTextView.getSelectionEnd(), mSelectionPath); 3714 mSelectionPath.computeBounds(mSelectionBounds, true); 3715 mSelectionBounds.bottom += mHandleHeight; 3716 } else if (mCursorCount == 2) { 3717 // We have a split cursor. In this case, we take the rectangle that includes both 3718 // parts of the cursor to ensure we don't obscure either of them. 3719 Rect firstCursorBounds = mCursorDrawable[0].getBounds(); 3720 Rect secondCursorBounds = mCursorDrawable[1].getBounds(); 3721 mSelectionBounds.set( 3722 Math.min(firstCursorBounds.left, secondCursorBounds.left), 3723 Math.min(firstCursorBounds.top, secondCursorBounds.top), 3724 Math.max(firstCursorBounds.right, secondCursorBounds.right), 3725 Math.max(firstCursorBounds.bottom, secondCursorBounds.bottom) 3726 + mHandleHeight); 3727 } else { 3728 // We have a single cursor. 3729 Layout layout = getActiveLayout(); 3730 int line = layout.getLineForOffset(mTextView.getSelectionStart()); 3731 float primaryHorizontal = 3732 layout.getPrimaryHorizontal(mTextView.getSelectionStart()); 3733 mSelectionBounds.set( 3734 primaryHorizontal, 3735 layout.getLineTop(line), 3736 primaryHorizontal, 3737 layout.getLineTop(line + 1) + mHandleHeight); 3738 } 3739 // Take TextView's padding and scroll into account. 3740 int textHorizontalOffset = mTextView.viewportToContentHorizontalOffset(); 3741 int textVerticalOffset = mTextView.viewportToContentVerticalOffset(); 3742 outRect.set( 3743 (int) Math.floor(mSelectionBounds.left + textHorizontalOffset), 3744 (int) Math.floor(mSelectionBounds.top + textVerticalOffset), 3745 (int) Math.ceil(mSelectionBounds.right + textHorizontalOffset), 3746 (int) Math.ceil(mSelectionBounds.bottom + textVerticalOffset)); 3747 } 3748 } 3749 3750 /** 3751 * A listener to call {@link InputMethodManager#updateCursorAnchorInfo(View, CursorAnchorInfo)} 3752 * while the input method is requesting the cursor/anchor position. Does nothing as long as 3753 * {@link InputMethodManager#isWatchingCursor(View)} returns false. 3754 */ 3755 private final class CursorAnchorInfoNotifier implements TextViewPositionListener { 3756 final CursorAnchorInfo.Builder mSelectionInfoBuilder = new CursorAnchorInfo.Builder(); 3757 final int[] mTmpIntOffset = new int[2]; 3758 final Matrix mViewToScreenMatrix = new Matrix(); 3759 3760 @Override 3761 public void updatePosition(int parentPositionX, int parentPositionY, 3762 boolean parentPositionChanged, boolean parentScrolled) { 3763 final InputMethodState ims = mInputMethodState; 3764 if (ims == null || ims.mBatchEditNesting > 0) { 3765 return; 3766 } 3767 final InputMethodManager imm = InputMethodManager.peekInstance(); 3768 if (null == imm) { 3769 return; 3770 } 3771 if (!imm.isActive(mTextView)) { 3772 return; 3773 } 3774 // Skip if the IME has not requested the cursor/anchor position. 3775 if (!imm.isCursorAnchorInfoEnabled()) { 3776 return; 3777 } 3778 Layout layout = mTextView.getLayout(); 3779 if (layout == null) { 3780 return; 3781 } 3782 3783 final CursorAnchorInfo.Builder builder = mSelectionInfoBuilder; 3784 builder.reset(); 3785 3786 final int selectionStart = mTextView.getSelectionStart(); 3787 builder.setSelectionRange(selectionStart, mTextView.getSelectionEnd()); 3788 3789 // Construct transformation matrix from view local coordinates to screen coordinates. 3790 mViewToScreenMatrix.set(mTextView.getMatrix()); 3791 mTextView.getLocationOnScreen(mTmpIntOffset); 3792 mViewToScreenMatrix.postTranslate(mTmpIntOffset[0], mTmpIntOffset[1]); 3793 builder.setMatrix(mViewToScreenMatrix); 3794 3795 final float viewportToContentHorizontalOffset = 3796 mTextView.viewportToContentHorizontalOffset(); 3797 final float viewportToContentVerticalOffset = 3798 mTextView.viewportToContentVerticalOffset(); 3799 3800 final CharSequence text = mTextView.getText(); 3801 if (text instanceof Spannable) { 3802 final Spannable sp = (Spannable) text; 3803 int composingTextStart = EditableInputConnection.getComposingSpanStart(sp); 3804 int composingTextEnd = EditableInputConnection.getComposingSpanEnd(sp); 3805 if (composingTextEnd < composingTextStart) { 3806 final int temp = composingTextEnd; 3807 composingTextEnd = composingTextStart; 3808 composingTextStart = temp; 3809 } 3810 final boolean hasComposingText = 3811 (0 <= composingTextStart) && (composingTextStart < composingTextEnd); 3812 if (hasComposingText) { 3813 final CharSequence composingText = text.subSequence(composingTextStart, 3814 composingTextEnd); 3815 builder.setComposingText(composingTextStart, composingText); 3816 3817 final int minLine = layout.getLineForOffset(composingTextStart); 3818 final int maxLine = layout.getLineForOffset(composingTextEnd - 1); 3819 for (int line = minLine; line <= maxLine; ++line) { 3820 final int lineStart = layout.getLineStart(line); 3821 final int lineEnd = layout.getLineEnd(line); 3822 final int offsetStart = Math.max(lineStart, composingTextStart); 3823 final int offsetEnd = Math.min(lineEnd, composingTextEnd); 3824 final boolean ltrLine = 3825 layout.getParagraphDirection(line) == Layout.DIR_LEFT_TO_RIGHT; 3826 final float[] widths = new float[offsetEnd - offsetStart]; 3827 layout.getPaint().getTextWidths(text, offsetStart, offsetEnd, widths); 3828 final float top = layout.getLineTop(line); 3829 final float bottom = layout.getLineBottom(line); 3830 for (int offset = offsetStart; offset < offsetEnd; ++offset) { 3831 final float charWidth = widths[offset - offsetStart]; 3832 final boolean isRtl = layout.isRtlCharAt(offset); 3833 final float primary = layout.getPrimaryHorizontal(offset); 3834 final float secondary = layout.getSecondaryHorizontal(offset); 3835 // TODO: This doesn't work perfectly for text with custom styles and 3836 // TAB chars. 3837 final float left; 3838 final float right; 3839 if (ltrLine) { 3840 if (isRtl) { 3841 left = secondary - charWidth; 3842 right = secondary; 3843 } else { 3844 left = primary; 3845 right = primary + charWidth; 3846 } 3847 } else { 3848 if (!isRtl) { 3849 left = secondary; 3850 right = secondary + charWidth; 3851 } else { 3852 left = primary - charWidth; 3853 right = primary; 3854 } 3855 } 3856 // TODO: Check top-right and bottom-left as well. 3857 final float localLeft = left + viewportToContentHorizontalOffset; 3858 final float localRight = right + viewportToContentHorizontalOffset; 3859 final float localTop = top + viewportToContentVerticalOffset; 3860 final float localBottom = bottom + viewportToContentVerticalOffset; 3861 final boolean isTopLeftVisible = isPositionVisible(localLeft, localTop); 3862 final boolean isBottomRightVisible = 3863 isPositionVisible(localRight, localBottom); 3864 int characterBoundsFlags = 0; 3865 if (isTopLeftVisible || isBottomRightVisible) { 3866 characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION; 3867 } 3868 if (!isTopLeftVisible || !isBottomRightVisible) { 3869 characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION; 3870 } 3871 if (isRtl) { 3872 characterBoundsFlags |= CursorAnchorInfo.FLAG_IS_RTL; 3873 } 3874 // Here offset is the index in Java chars. 3875 builder.addCharacterBounds(offset, localLeft, localTop, localRight, 3876 localBottom, characterBoundsFlags); 3877 } 3878 } 3879 } 3880 } 3881 3882 // Treat selectionStart as the insertion point. 3883 if (0 <= selectionStart) { 3884 final int offset = selectionStart; 3885 final int line = layout.getLineForOffset(offset); 3886 final float insertionMarkerX = layout.getPrimaryHorizontal(offset) 3887 + viewportToContentHorizontalOffset; 3888 final float insertionMarkerTop = layout.getLineTop(line) 3889 + viewportToContentVerticalOffset; 3890 final float insertionMarkerBaseline = layout.getLineBaseline(line) 3891 + viewportToContentVerticalOffset; 3892 final float insertionMarkerBottom = layout.getLineBottom(line) 3893 + viewportToContentVerticalOffset; 3894 final boolean isTopVisible = 3895 isPositionVisible(insertionMarkerX, insertionMarkerTop); 3896 final boolean isBottomVisible = 3897 isPositionVisible(insertionMarkerX, insertionMarkerBottom); 3898 int insertionMarkerFlags = 0; 3899 if (isTopVisible || isBottomVisible) { 3900 insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION; 3901 } 3902 if (!isTopVisible || !isBottomVisible) { 3903 insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION; 3904 } 3905 if (layout.isRtlCharAt(offset)) { 3906 insertionMarkerFlags |= CursorAnchorInfo.FLAG_IS_RTL; 3907 } 3908 builder.setInsertionMarkerLocation(insertionMarkerX, insertionMarkerTop, 3909 insertionMarkerBaseline, insertionMarkerBottom, insertionMarkerFlags); 3910 } 3911 3912 imm.updateCursorAnchorInfo(mTextView, builder.build()); 3913 } 3914 } 3915 3916 @VisibleForTesting 3917 public abstract class HandleView extends View implements TextViewPositionListener { 3918 protected Drawable mDrawable; 3919 protected Drawable mDrawableLtr; 3920 protected Drawable mDrawableRtl; 3921 private final PopupWindow mContainer; 3922 // Position with respect to the parent TextView 3923 private int mPositionX, mPositionY; 3924 private boolean mIsDragging; 3925 // Offset from touch position to mPosition 3926 private float mTouchToWindowOffsetX, mTouchToWindowOffsetY; 3927 protected int mHotspotX; 3928 protected int mHorizontalGravity; 3929 // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up 3930 private float mTouchOffsetY; 3931 // Where the touch position should be on the handle to ensure a maximum cursor visibility 3932 private float mIdealVerticalOffset; 3933 // Parent's (TextView) previous position in window 3934 private int mLastParentX, mLastParentY; 3935 // Previous text character offset 3936 protected int mPreviousOffset = -1; 3937 // Previous text character offset 3938 private boolean mPositionHasChanged = true; 3939 // Minimum touch target size for handles 3940 private int mMinSize; 3941 // Indicates the line of text that the handle is on. 3942 protected int mPrevLine = UNSET_LINE; 3943 // Indicates the line of text that the user was touching. This can differ from mPrevLine 3944 // when selecting text when the handles jump to the end / start of words which may be on 3945 // a different line. 3946 protected int mPreviousLineTouched = UNSET_LINE; 3947 3948 private HandleView(Drawable drawableLtr, Drawable drawableRtl, final int id) { 3949 super(mTextView.getContext()); 3950 setId(id); 3951 mContainer = new PopupWindow(mTextView.getContext(), null, 3952 com.android.internal.R.attr.textSelectHandleWindowStyle); 3953 mContainer.setSplitTouchEnabled(true); 3954 mContainer.setClippingEnabled(false); 3955 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 3956 mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 3957 mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 3958 mContainer.setContentView(this); 3959 3960 mDrawableLtr = drawableLtr; 3961 mDrawableRtl = drawableRtl; 3962 mMinSize = mTextView.getContext().getResources().getDimensionPixelSize( 3963 com.android.internal.R.dimen.text_handle_min_size); 3964 3965 updateDrawable(); 3966 3967 final int handleHeight = getPreferredHeight(); 3968 mTouchOffsetY = -0.3f * handleHeight; 3969 mIdealVerticalOffset = 0.7f * handleHeight; 3970 } 3971 3972 public float getIdealVerticalOffset() { 3973 return mIdealVerticalOffset; 3974 } 3975 3976 protected void updateDrawable() { 3977 if (mIsDragging) { 3978 // Don't update drawable during dragging. 3979 return; 3980 } 3981 final int offset = getCurrentCursorOffset(); 3982 final boolean isRtlCharAtOffset = mTextView.getLayout().isRtlCharAt(offset); 3983 final Drawable oldDrawable = mDrawable; 3984 mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr; 3985 mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset); 3986 mHorizontalGravity = getHorizontalGravity(isRtlCharAtOffset); 3987 final Layout layout = mTextView.getLayout(); 3988 if (layout != null && oldDrawable != mDrawable && isShowing()) { 3989 // Update popup window position. 3990 mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX - 3991 getHorizontalOffset() + getCursorOffset(); 3992 mPositionX += mTextView.viewportToContentHorizontalOffset(); 3993 mPositionHasChanged = true; 3994 updatePosition(mLastParentX, mLastParentY, false, false); 3995 postInvalidate(); 3996 } 3997 } 3998 3999 protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun); 4000 protected abstract int getHorizontalGravity(boolean isRtlRun); 4001 4002 // Touch-up filter: number of previous positions remembered 4003 private static final int HISTORY_SIZE = 5; 4004 private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150; 4005 private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350; 4006 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE]; 4007 private final int[] mPreviousOffsets = new int[HISTORY_SIZE]; 4008 private int mPreviousOffsetIndex = 0; 4009 private int mNumberPreviousOffsets = 0; 4010 4011 private void startTouchUpFilter(int offset) { 4012 mNumberPreviousOffsets = 0; 4013 addPositionToTouchUpFilter(offset); 4014 } 4015 4016 private void addPositionToTouchUpFilter(int offset) { 4017 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE; 4018 mPreviousOffsets[mPreviousOffsetIndex] = offset; 4019 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis(); 4020 mNumberPreviousOffsets++; 4021 } 4022 4023 private void filterOnTouchUp() { 4024 final long now = SystemClock.uptimeMillis(); 4025 int i = 0; 4026 int index = mPreviousOffsetIndex; 4027 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE); 4028 while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) { 4029 i++; 4030 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE; 4031 } 4032 4033 if (i > 0 && i < iMax && 4034 (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) { 4035 positionAtCursorOffset(mPreviousOffsets[index], false); 4036 } 4037 } 4038 4039 public boolean offsetHasBeenChanged() { 4040 return mNumberPreviousOffsets > 1; 4041 } 4042 4043 @Override 4044 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 4045 setMeasuredDimension(getPreferredWidth(), getPreferredHeight()); 4046 } 4047 4048 private int getPreferredWidth() { 4049 return Math.max(mDrawable.getIntrinsicWidth(), mMinSize); 4050 } 4051 4052 private int getPreferredHeight() { 4053 return Math.max(mDrawable.getIntrinsicHeight(), mMinSize); 4054 } 4055 4056 public void show() { 4057 if (isShowing()) return; 4058 4059 getPositionListener().addSubscriber(this, true /* local position may change */); 4060 4061 // Make sure the offset is always considered new, even when focusing at same position 4062 mPreviousOffset = -1; 4063 positionAtCursorOffset(getCurrentCursorOffset(), false); 4064 } 4065 4066 protected void dismiss() { 4067 mIsDragging = false; 4068 mContainer.dismiss(); 4069 onDetached(); 4070 } 4071 4072 public void hide() { 4073 dismiss(); 4074 4075 getPositionListener().removeSubscriber(this); 4076 } 4077 4078 public boolean isShowing() { 4079 return mContainer.isShowing(); 4080 } 4081 4082 private boolean isVisible() { 4083 // Always show a dragging handle. 4084 if (mIsDragging) { 4085 return true; 4086 } 4087 4088 if (mTextView.isInBatchEditMode()) { 4089 return false; 4090 } 4091 4092 return isPositionVisible(mPositionX + mHotspotX + getHorizontalOffset(), mPositionY); 4093 } 4094 4095 public abstract int getCurrentCursorOffset(); 4096 4097 protected abstract void updateSelection(int offset); 4098 4099 public abstract void updatePosition(float x, float y); 4100 4101 protected void positionAtCursorOffset(int offset, boolean parentScrolled) { 4102 // A HandleView relies on the layout, which may be nulled by external methods 4103 Layout layout = mTextView.getLayout(); 4104 if (layout == null) { 4105 // Will update controllers' state, hiding them and stopping selection mode if needed 4106 prepareCursorControllers(); 4107 return; 4108 } 4109 layout = getActiveLayout(); 4110 4111 boolean offsetChanged = offset != mPreviousOffset; 4112 if (offsetChanged || parentScrolled) { 4113 if (offsetChanged) { 4114 updateSelection(offset); 4115 addPositionToTouchUpFilter(offset); 4116 } 4117 final int line = layout.getLineForOffset(offset); 4118 mPrevLine = line; 4119 4120 mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX - 4121 getHorizontalOffset() + getCursorOffset(); 4122 mPositionY = layout.getLineBottom(line); 4123 4124 // Take TextView's padding and scroll into account. 4125 mPositionX += mTextView.viewportToContentHorizontalOffset(); 4126 mPositionY += mTextView.viewportToContentVerticalOffset(); 4127 4128 mPreviousOffset = offset; 4129 mPositionHasChanged = true; 4130 } 4131 } 4132 4133 /** 4134 * Return the clamped horizontal position for the first cursor. 4135 * 4136 * @param layout Text layout. 4137 * @param offset Character offset for the cursor. 4138 * @return The clamped horizontal position for the cursor. 4139 */ 4140 int getCursorHorizontalPosition(Layout layout, int offset) { 4141 return (int) (layout.getPrimaryHorizontal(offset) - 0.5f); 4142 } 4143 4144 public void updatePosition(int parentPositionX, int parentPositionY, 4145 boolean parentPositionChanged, boolean parentScrolled) { 4146 positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled); 4147 if (parentPositionChanged || mPositionHasChanged) { 4148 if (mIsDragging) { 4149 // Update touchToWindow offset in case of parent scrolling while dragging 4150 if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) { 4151 mTouchToWindowOffsetX += parentPositionX - mLastParentX; 4152 mTouchToWindowOffsetY += parentPositionY - mLastParentY; 4153 mLastParentX = parentPositionX; 4154 mLastParentY = parentPositionY; 4155 } 4156 4157 onHandleMoved(); 4158 } 4159 4160 if (isVisible()) { 4161 // Transform to the window coordinates to follow the view tranformation. 4162 final int[] pts = { mPositionX + mHotspotX + getHorizontalOffset(), mPositionY}; 4163 mTextView.transformFromViewToWindowSpace(pts); 4164 pts[0] -= mHotspotX + getHorizontalOffset(); 4165 4166 if (isShowing()) { 4167 mContainer.update(pts[0], pts[1], -1, -1); 4168 } else { 4169 mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY, pts[0], pts[1]); 4170 } 4171 } else { 4172 if (isShowing()) { 4173 dismiss(); 4174 } 4175 } 4176 4177 mPositionHasChanged = false; 4178 } 4179 } 4180 4181 @Override 4182 protected void onDraw(Canvas c) { 4183 final int drawWidth = mDrawable.getIntrinsicWidth(); 4184 final int left = getHorizontalOffset(); 4185 4186 mDrawable.setBounds(left, 0, left + drawWidth, mDrawable.getIntrinsicHeight()); 4187 mDrawable.draw(c); 4188 } 4189 4190 private int getHorizontalOffset() { 4191 final int width = getPreferredWidth(); 4192 final int drawWidth = mDrawable.getIntrinsicWidth(); 4193 final int left; 4194 switch (mHorizontalGravity) { 4195 case Gravity.LEFT: 4196 left = 0; 4197 break; 4198 default: 4199 case Gravity.CENTER: 4200 left = (width - drawWidth) / 2; 4201 break; 4202 case Gravity.RIGHT: 4203 left = width - drawWidth; 4204 break; 4205 } 4206 return left; 4207 } 4208 4209 protected int getCursorOffset() { 4210 return 0; 4211 } 4212 4213 @Override 4214 public boolean onTouchEvent(MotionEvent ev) { 4215 updateFloatingToolbarVisibility(ev); 4216 4217 switch (ev.getActionMasked()) { 4218 case MotionEvent.ACTION_DOWN: { 4219 startTouchUpFilter(getCurrentCursorOffset()); 4220 mTouchToWindowOffsetX = ev.getRawX() - mPositionX; 4221 mTouchToWindowOffsetY = ev.getRawY() - mPositionY; 4222 4223 final PositionListener positionListener = getPositionListener(); 4224 mLastParentX = positionListener.getPositionX(); 4225 mLastParentY = positionListener.getPositionY(); 4226 mIsDragging = true; 4227 mPreviousLineTouched = UNSET_LINE; 4228 break; 4229 } 4230 4231 case MotionEvent.ACTION_MOVE: { 4232 final float rawX = ev.getRawX(); 4233 final float rawY = ev.getRawY(); 4234 4235 // Vertical hysteresis: vertical down movement tends to snap to ideal offset 4236 final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY; 4237 final float currentVerticalOffset = rawY - mPositionY - mLastParentY; 4238 float newVerticalOffset; 4239 if (previousVerticalOffset < mIdealVerticalOffset) { 4240 newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset); 4241 newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset); 4242 } else { 4243 newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset); 4244 newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset); 4245 } 4246 mTouchToWindowOffsetY = newVerticalOffset + mLastParentY; 4247 4248 final float newPosX = 4249 rawX - mTouchToWindowOffsetX + mHotspotX + getHorizontalOffset(); 4250 final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY; 4251 4252 updatePosition(newPosX, newPosY); 4253 break; 4254 } 4255 4256 case MotionEvent.ACTION_UP: 4257 filterOnTouchUp(); 4258 mIsDragging = false; 4259 updateDrawable(); 4260 break; 4261 4262 case MotionEvent.ACTION_CANCEL: 4263 mIsDragging = false; 4264 updateDrawable(); 4265 break; 4266 } 4267 return true; 4268 } 4269 4270 public boolean isDragging() { 4271 return mIsDragging; 4272 } 4273 4274 void onHandleMoved() {} 4275 4276 public void onDetached() {} 4277 } 4278 4279 /** 4280 * Returns the active layout (hint or text layout). Note that the text layout can be null. 4281 */ 4282 private Layout getActiveLayout() { 4283 Layout layout = mTextView.getLayout(); 4284 Layout hintLayout = mTextView.getHintLayout(); 4285 if (TextUtils.isEmpty(layout.getText()) && hintLayout != null && 4286 !TextUtils.isEmpty(hintLayout.getText())) { 4287 layout = hintLayout; 4288 } 4289 return layout; 4290 } 4291 4292 private class InsertionHandleView extends HandleView { 4293 private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000; 4294 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds 4295 4296 // Used to detect taps on the insertion handle, which will affect the insertion action mode 4297 private float mDownPositionX, mDownPositionY; 4298 private Runnable mHider; 4299 4300 public InsertionHandleView(Drawable drawable) { 4301 super(drawable, drawable, com.android.internal.R.id.insertion_handle); 4302 } 4303 4304 @Override 4305 public void show() { 4306 super.show(); 4307 4308 final long durationSinceCutOrCopy = 4309 SystemClock.uptimeMillis() - TextView.sLastCutCopyOrTextChangedTime; 4310 4311 // Cancel the single tap delayed runnable. 4312 if (mInsertionActionModeRunnable != null 4313 && ((mTapState == TAP_STATE_DOUBLE_TAP) 4314 || (mTapState == TAP_STATE_TRIPLE_CLICK) 4315 || isCursorInsideEasyCorrectionSpan())) { 4316 mTextView.removeCallbacks(mInsertionActionModeRunnable); 4317 } 4318 4319 // Prepare and schedule the single tap runnable to run exactly after the double tap 4320 // timeout has passed. 4321 if ((mTapState != TAP_STATE_DOUBLE_TAP) && (mTapState != TAP_STATE_TRIPLE_CLICK) 4322 && !isCursorInsideEasyCorrectionSpan() 4323 && (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION)) { 4324 if (mTextActionMode == null) { 4325 if (mInsertionActionModeRunnable == null) { 4326 mInsertionActionModeRunnable = new Runnable() { 4327 @Override 4328 public void run() { 4329 startInsertionActionMode(); 4330 } 4331 }; 4332 } 4333 mTextView.postDelayed( 4334 mInsertionActionModeRunnable, 4335 ViewConfiguration.getDoubleTapTimeout() + 1); 4336 } 4337 4338 } 4339 4340 hideAfterDelay(); 4341 } 4342 4343 private void hideAfterDelay() { 4344 if (mHider == null) { 4345 mHider = new Runnable() { 4346 public void run() { 4347 hide(); 4348 } 4349 }; 4350 } else { 4351 removeHiderCallback(); 4352 } 4353 mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT); 4354 } 4355 4356 private void removeHiderCallback() { 4357 if (mHider != null) { 4358 mTextView.removeCallbacks(mHider); 4359 } 4360 } 4361 4362 @Override 4363 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 4364 return drawable.getIntrinsicWidth() / 2; 4365 } 4366 4367 @Override 4368 protected int getHorizontalGravity(boolean isRtlRun) { 4369 return Gravity.CENTER_HORIZONTAL; 4370 } 4371 4372 @Override 4373 protected int getCursorOffset() { 4374 int offset = super.getCursorOffset(); 4375 final Drawable cursor = mCursorCount > 0 ? mCursorDrawable[0] : null; 4376 if (cursor != null) { 4377 cursor.getPadding(mTempRect); 4378 offset += (cursor.getIntrinsicWidth() - mTempRect.left - mTempRect.right) / 2; 4379 } 4380 return offset; 4381 } 4382 4383 @Override 4384 int getCursorHorizontalPosition(Layout layout, int offset) { 4385 final Drawable drawable = mCursorCount > 0 ? mCursorDrawable[0] : null; 4386 if (drawable != null) { 4387 final float horizontal = layout.getPrimaryHorizontal(offset); 4388 return clampCursorHorizontalPosition(drawable, horizontal) + mTempRect.left; 4389 } 4390 return super.getCursorHorizontalPosition(layout, offset); 4391 } 4392 4393 @Override 4394 public boolean onTouchEvent(MotionEvent ev) { 4395 final boolean result = super.onTouchEvent(ev); 4396 4397 switch (ev.getActionMasked()) { 4398 case MotionEvent.ACTION_DOWN: 4399 mDownPositionX = ev.getRawX(); 4400 mDownPositionY = ev.getRawY(); 4401 break; 4402 4403 case MotionEvent.ACTION_UP: 4404 if (!offsetHasBeenChanged()) { 4405 final float deltaX = mDownPositionX - ev.getRawX(); 4406 final float deltaY = mDownPositionY - ev.getRawY(); 4407 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 4408 4409 final ViewConfiguration viewConfiguration = ViewConfiguration.get( 4410 mTextView.getContext()); 4411 final int touchSlop = viewConfiguration.getScaledTouchSlop(); 4412 4413 if (distanceSquared < touchSlop * touchSlop) { 4414 // Tapping on the handle toggles the insertion action mode. 4415 if (mTextActionMode != null) { 4416 stopTextActionMode(); 4417 } else { 4418 startInsertionActionMode(); 4419 } 4420 } 4421 } else { 4422 if (mTextActionMode != null) { 4423 mTextActionMode.invalidateContentRect(); 4424 } 4425 } 4426 hideAfterDelay(); 4427 break; 4428 4429 case MotionEvent.ACTION_CANCEL: 4430 hideAfterDelay(); 4431 break; 4432 4433 default: 4434 break; 4435 } 4436 4437 return result; 4438 } 4439 4440 @Override 4441 public int getCurrentCursorOffset() { 4442 return mTextView.getSelectionStart(); 4443 } 4444 4445 @Override 4446 public void updateSelection(int offset) { 4447 Selection.setSelection((Spannable) mTextView.getText(), offset); 4448 } 4449 4450 @Override 4451 public void updatePosition(float x, float y) { 4452 Layout layout = mTextView.getLayout(); 4453 int offset; 4454 if (layout != null) { 4455 if (mPreviousLineTouched == UNSET_LINE) { 4456 mPreviousLineTouched = mTextView.getLineAtCoordinate(y); 4457 } 4458 int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y); 4459 offset = mTextView.getOffsetAtCoordinate(currLine, x); 4460 mPreviousLineTouched = currLine; 4461 } else { 4462 offset = mTextView.getOffsetForPosition(x, y); 4463 } 4464 positionAtCursorOffset(offset, false); 4465 if (mTextActionMode != null) { 4466 mTextActionMode.invalidate(); 4467 } 4468 } 4469 4470 @Override 4471 void onHandleMoved() { 4472 super.onHandleMoved(); 4473 removeHiderCallback(); 4474 } 4475 4476 @Override 4477 public void onDetached() { 4478 super.onDetached(); 4479 removeHiderCallback(); 4480 } 4481 } 4482 4483 @Retention(RetentionPolicy.SOURCE) 4484 @IntDef({HANDLE_TYPE_SELECTION_START, HANDLE_TYPE_SELECTION_END}) 4485 public @interface HandleType {} 4486 public static final int HANDLE_TYPE_SELECTION_START = 0; 4487 public static final int HANDLE_TYPE_SELECTION_END = 1; 4488 4489 private class SelectionHandleView extends HandleView { 4490 // Indicates the handle type, selection start (HANDLE_TYPE_SELECTION_START) or selection 4491 // end (HANDLE_TYPE_SELECTION_END). 4492 @HandleType 4493 private final int mHandleType; 4494 // Indicates whether the cursor is making adjustments within a word. 4495 private boolean mInWord = false; 4496 // Difference between touch position and word boundary position. 4497 private float mTouchWordDelta; 4498 // X value of the previous updatePosition call. 4499 private float mPrevX; 4500 // Indicates if the handle has moved a boundary between LTR and RTL text. 4501 private boolean mLanguageDirectionChanged = false; 4502 // Distance from edge of horizontally scrolling text view 4503 // to use to switch to character mode. 4504 private final float mTextViewEdgeSlop; 4505 // Used to save text view location. 4506 private final int[] mTextViewLocation = new int[2]; 4507 4508 public SelectionHandleView(Drawable drawableLtr, Drawable drawableRtl, int id, 4509 @HandleType int handleType) { 4510 super(drawableLtr, drawableRtl, id); 4511 mHandleType = handleType; 4512 ViewConfiguration viewConfiguration = ViewConfiguration.get(mTextView.getContext()); 4513 mTextViewEdgeSlop = viewConfiguration.getScaledTouchSlop() * 4; 4514 } 4515 4516 private boolean isStartHandle() { 4517 return mHandleType == HANDLE_TYPE_SELECTION_START; 4518 } 4519 4520 @Override 4521 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 4522 if (isRtlRun == isStartHandle()) { 4523 return drawable.getIntrinsicWidth() / 4; 4524 } else { 4525 return (drawable.getIntrinsicWidth() * 3) / 4; 4526 } 4527 } 4528 4529 @Override 4530 protected int getHorizontalGravity(boolean isRtlRun) { 4531 return (isRtlRun == isStartHandle()) ? Gravity.LEFT : Gravity.RIGHT; 4532 } 4533 4534 @Override 4535 public int getCurrentCursorOffset() { 4536 return isStartHandle() ? mTextView.getSelectionStart() : mTextView.getSelectionEnd(); 4537 } 4538 4539 @Override 4540 protected void updateSelection(int offset) { 4541 if (isStartHandle()) { 4542 Selection.setSelection((Spannable) mTextView.getText(), offset, 4543 mTextView.getSelectionEnd()); 4544 } else { 4545 Selection.setSelection((Spannable) mTextView.getText(), 4546 mTextView.getSelectionStart(), offset); 4547 } 4548 updateDrawable(); 4549 if (mTextActionMode != null) { 4550 mTextActionMode.invalidate(); 4551 } 4552 } 4553 4554 @Override 4555 public void updatePosition(float x, float y) { 4556 final Layout layout = mTextView.getLayout(); 4557 if (layout == null) { 4558 // HandleView will deal appropriately in positionAtCursorOffset when 4559 // layout is null. 4560 positionAndAdjustForCrossingHandles(mTextView.getOffsetForPosition(x, y)); 4561 return; 4562 } 4563 4564 if (mPreviousLineTouched == UNSET_LINE) { 4565 mPreviousLineTouched = mTextView.getLineAtCoordinate(y); 4566 } 4567 4568 boolean positionCursor = false; 4569 final int anotherHandleOffset = 4570 isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart(); 4571 int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y); 4572 int initialOffset = mTextView.getOffsetAtCoordinate(currLine, x); 4573 4574 if (isStartHandle() && initialOffset >= anotherHandleOffset 4575 || !isStartHandle() && initialOffset <= anotherHandleOffset) { 4576 // Handles have crossed, bound it to the first selected line and 4577 // adjust by word / char as normal. 4578 currLine = layout.getLineForOffset(anotherHandleOffset); 4579 initialOffset = mTextView.getOffsetAtCoordinate(currLine, x); 4580 } 4581 4582 int offset = initialOffset; 4583 final int wordEnd = getWordEnd(offset); 4584 final int wordStart = getWordStart(offset); 4585 4586 if (mPrevX == UNSET_X_VALUE) { 4587 mPrevX = x; 4588 } 4589 4590 final int currentOffset = getCurrentCursorOffset(); 4591 final boolean rtlAtCurrentOffset = layout.isRtlCharAt(currentOffset); 4592 final boolean atRtl = layout.isRtlCharAt(offset); 4593 final boolean isLvlBoundary = layout.isLevelBoundary(offset); 4594 4595 // We can't determine if the user is expanding or shrinking the selection if they're 4596 // on a bi-di boundary, so until they've moved past the boundary we'll just place 4597 // the cursor at the current position. 4598 if (isLvlBoundary || (rtlAtCurrentOffset && !atRtl) || (!rtlAtCurrentOffset && atRtl)) { 4599 // We're on a boundary or this is the first direction change -- just update 4600 // to the current position. 4601 mLanguageDirectionChanged = true; 4602 mTouchWordDelta = 0.0f; 4603 positionAndAdjustForCrossingHandles(offset); 4604 return; 4605 } else if (mLanguageDirectionChanged && !isLvlBoundary) { 4606 // We've just moved past the boundary so update the position. After this we can 4607 // figure out if the user is expanding or shrinking to go by word or character. 4608 positionAndAdjustForCrossingHandles(offset); 4609 mTouchWordDelta = 0.0f; 4610 mLanguageDirectionChanged = false; 4611 return; 4612 } 4613 4614 boolean isExpanding; 4615 final float xDiff = x - mPrevX; 4616 if (isStartHandle()) { 4617 isExpanding = currLine < mPreviousLineTouched; 4618 } else { 4619 isExpanding = currLine > mPreviousLineTouched; 4620 } 4621 if (atRtl == isStartHandle()) { 4622 isExpanding |= xDiff > 0; 4623 } else { 4624 isExpanding |= xDiff < 0; 4625 } 4626 4627 if (mTextView.getHorizontallyScrolling()) { 4628 if (positionNearEdgeOfScrollingView(x, atRtl) 4629 && ((isStartHandle() && mTextView.getScrollX() != 0) 4630 || (!isStartHandle() 4631 && mTextView.canScrollHorizontally(atRtl ? -1 : 1))) 4632 && ((isExpanding && ((isStartHandle() && offset < currentOffset) 4633 || (!isStartHandle() && offset > currentOffset))) 4634 || !isExpanding)) { 4635 // If we're expanding ensure that the offset is actually expanding compared to 4636 // the current offset, if the handle snapped to the word, the finger position 4637 // may be out of sync and we don't want the selection to jump back. 4638 mTouchWordDelta = 0.0f; 4639 final int nextOffset = (atRtl == isStartHandle()) 4640 ? layout.getOffsetToRightOf(mPreviousOffset) 4641 : layout.getOffsetToLeftOf(mPreviousOffset); 4642 positionAndAdjustForCrossingHandles(nextOffset); 4643 return; 4644 } 4645 } 4646 4647 if (isExpanding) { 4648 // User is increasing the selection. 4649 final boolean snapToWord = !mInWord 4650 || (isStartHandle() ? currLine < mPrevLine : currLine > mPrevLine); 4651 if (snapToWord) { 4652 // Sometimes words can be broken across lines (Chinese, hyphenation). 4653 // We still snap to the word boundary but we only use the letters on the 4654 // current line to determine if the user is far enough into the word to snap. 4655 int wordBoundary = isStartHandle() ? wordStart : wordEnd; 4656 if (layout != null && layout.getLineForOffset(wordBoundary) != currLine) { 4657 wordBoundary = isStartHandle() ? 4658 layout.getLineStart(currLine) : layout.getLineEnd(currLine); 4659 } 4660 final int offsetThresholdToSnap = isStartHandle() 4661 ? wordEnd - ((wordEnd - wordBoundary) / 2) 4662 : wordStart + ((wordBoundary - wordStart) / 2); 4663 if (isStartHandle() 4664 && (offset <= offsetThresholdToSnap || currLine < mPrevLine)) { 4665 // User is far enough into the word or on a different line so we expand by 4666 // word. 4667 offset = wordStart; 4668 } else if (!isStartHandle() 4669 && (offset >= offsetThresholdToSnap || currLine > mPrevLine)) { 4670 // User is far enough into the word or on a different line so we expand by 4671 // word. 4672 offset = wordEnd; 4673 } else { 4674 offset = mPreviousOffset; 4675 } 4676 } 4677 if (layout != null && (isStartHandle() && offset < initialOffset) 4678 || (!isStartHandle() && offset > initialOffset)) { 4679 final float adjustedX = layout.getPrimaryHorizontal(offset); 4680 mTouchWordDelta = 4681 mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX; 4682 } else { 4683 mTouchWordDelta = 0.0f; 4684 } 4685 positionCursor = true; 4686 } else { 4687 final int adjustedOffset = 4688 mTextView.getOffsetAtCoordinate(currLine, x - mTouchWordDelta); 4689 final boolean shrinking = isStartHandle() 4690 ? adjustedOffset > mPreviousOffset || currLine > mPrevLine 4691 : adjustedOffset < mPreviousOffset || currLine < mPrevLine; 4692 if (shrinking) { 4693 // User is shrinking the selection. 4694 if (currLine != mPrevLine) { 4695 // We're on a different line, so we'll snap to word boundaries. 4696 offset = isStartHandle() ? wordStart : wordEnd; 4697 if (layout != null && (isStartHandle() && offset < initialOffset) 4698 || (!isStartHandle() && offset > initialOffset)) { 4699 final float adjustedX = layout.getPrimaryHorizontal(offset); 4700 mTouchWordDelta = 4701 mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX; 4702 } else { 4703 mTouchWordDelta = 0.0f; 4704 } 4705 } else { 4706 offset = adjustedOffset; 4707 } 4708 positionCursor = true; 4709 } else if ((isStartHandle() && adjustedOffset < mPreviousOffset) 4710 || (!isStartHandle() && adjustedOffset > mPreviousOffset)) { 4711 // Handle has jumped to the word boundary, and the user is moving 4712 // their finger towards the handle, the delta should be updated. 4713 mTouchWordDelta = mTextView.convertToLocalHorizontalCoordinate(x) - 4714 layout.getPrimaryHorizontal(mPreviousOffset); 4715 } 4716 } 4717 4718 if (positionCursor) { 4719 mPreviousLineTouched = currLine; 4720 positionAndAdjustForCrossingHandles(offset); 4721 } 4722 mPrevX = x; 4723 } 4724 4725 /** 4726 * @param offset Cursor offset. Must be in [-1, length]. 4727 * @param parentScrolled If the parent has been scrolled or not. 4728 */ 4729 @Override 4730 protected void positionAtCursorOffset(int offset, boolean parentScrolled) { 4731 super.positionAtCursorOffset(offset, parentScrolled); 4732 mInWord = (offset != -1) && !getWordIteratorWithText().isBoundary(offset); 4733 } 4734 4735 @Override 4736 public boolean onTouchEvent(MotionEvent event) { 4737 boolean superResult = super.onTouchEvent(event); 4738 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { 4739 // Reset the touch word offset and x value when the user 4740 // re-engages the handle. 4741 mTouchWordDelta = 0.0f; 4742 mPrevX = UNSET_X_VALUE; 4743 } 4744 return superResult; 4745 } 4746 4747 private void positionAndAdjustForCrossingHandles(int offset) { 4748 final int anotherHandleOffset = 4749 isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart(); 4750 if ((isStartHandle() && offset >= anotherHandleOffset) 4751 || (!isStartHandle() && offset <= anotherHandleOffset)) { 4752 // Handles can not cross and selection is at least one character. 4753 offset = getNextCursorOffset(anotherHandleOffset, !isStartHandle()); 4754 mTouchWordDelta = 0.0f; 4755 } 4756 positionAtCursorOffset(offset, false); 4757 } 4758 4759 private boolean positionNearEdgeOfScrollingView(float x, boolean atRtl) { 4760 mTextView.getLocationOnScreen(mTextViewLocation); 4761 boolean nearEdge; 4762 if (atRtl == isStartHandle()) { 4763 int rightEdge = mTextViewLocation[0] + mTextView.getWidth() 4764 - mTextView.getPaddingRight(); 4765 nearEdge = x > rightEdge - mTextViewEdgeSlop; 4766 } else { 4767 int leftEdge = mTextViewLocation[0] + mTextView.getPaddingLeft(); 4768 nearEdge = x < leftEdge + mTextViewEdgeSlop; 4769 } 4770 return nearEdge; 4771 } 4772 } 4773 4774 private int getCurrentLineAdjustedForSlop(Layout layout, int prevLine, float y) { 4775 final int trueLine = mTextView.getLineAtCoordinate(y); 4776 if (layout == null || prevLine > layout.getLineCount() 4777 || layout.getLineCount() <= 0 || prevLine < 0) { 4778 // Invalid parameters, just return whatever line is at y. 4779 return trueLine; 4780 } 4781 4782 if (Math.abs(trueLine - prevLine) >= 2) { 4783 // Only stick to lines if we're within a line of the previous selection. 4784 return trueLine; 4785 } 4786 4787 final float verticalOffset = mTextView.viewportToContentVerticalOffset(); 4788 final int lineCount = layout.getLineCount(); 4789 final float slop = mTextView.getLineHeight() * LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS; 4790 4791 final float firstLineTop = layout.getLineTop(0) + verticalOffset; 4792 final float prevLineTop = layout.getLineTop(prevLine) + verticalOffset; 4793 final float yTopBound = Math.max(prevLineTop - slop, firstLineTop + slop); 4794 4795 final float lastLineBottom = layout.getLineBottom(lineCount - 1) + verticalOffset; 4796 final float prevLineBottom = layout.getLineBottom(prevLine) + verticalOffset; 4797 final float yBottomBound = Math.min(prevLineBottom + slop, lastLineBottom - slop); 4798 4799 // Determine if we've moved lines based on y position and previous line. 4800 int currLine; 4801 if (y <= yTopBound) { 4802 currLine = Math.max(prevLine - 1, 0); 4803 } else if (y >= yBottomBound) { 4804 currLine = Math.min(prevLine + 1, lineCount - 1); 4805 } else { 4806 currLine = prevLine; 4807 } 4808 return currLine; 4809 } 4810 4811 /** 4812 * A CursorController instance can be used to control a cursor in the text. 4813 */ 4814 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener { 4815 /** 4816 * Makes the cursor controller visible on screen. 4817 * See also {@link #hide()}. 4818 */ 4819 public void show(); 4820 4821 /** 4822 * Hide the cursor controller from screen. 4823 * See also {@link #show()}. 4824 */ 4825 public void hide(); 4826 4827 /** 4828 * Called when the view is detached from window. Perform house keeping task, such as 4829 * stopping Runnable thread that would otherwise keep a reference on the context, thus 4830 * preventing the activity from being recycled. 4831 */ 4832 public void onDetached(); 4833 4834 public boolean isCursorBeingModified(); 4835 4836 public boolean isActive(); 4837 } 4838 4839 private class InsertionPointCursorController implements CursorController { 4840 private InsertionHandleView mHandle; 4841 4842 public void show() { 4843 getHandle().show(); 4844 4845 if (mSelectionModifierCursorController != null) { 4846 mSelectionModifierCursorController.hide(); 4847 } 4848 } 4849 4850 public void hide() { 4851 if (mHandle != null) { 4852 mHandle.hide(); 4853 } 4854 } 4855 4856 public void onTouchModeChanged(boolean isInTouchMode) { 4857 if (!isInTouchMode) { 4858 hide(); 4859 } 4860 } 4861 4862 private InsertionHandleView getHandle() { 4863 if (mSelectHandleCenter == null) { 4864 mSelectHandleCenter = mTextView.getContext().getDrawable( 4865 mTextView.mTextSelectHandleRes); 4866 } 4867 if (mHandle == null) { 4868 mHandle = new InsertionHandleView(mSelectHandleCenter); 4869 } 4870 return mHandle; 4871 } 4872 4873 @Override 4874 public void onDetached() { 4875 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 4876 observer.removeOnTouchModeChangeListener(this); 4877 4878 if (mHandle != null) mHandle.onDetached(); 4879 } 4880 4881 @Override 4882 public boolean isCursorBeingModified() { 4883 return mHandle != null && mHandle.isDragging(); 4884 } 4885 4886 @Override 4887 public boolean isActive() { 4888 return mHandle != null && mHandle.isShowing(); 4889 } 4890 } 4891 4892 class SelectionModifierCursorController implements CursorController { 4893 // The cursor controller handles, lazily created when shown. 4894 private SelectionHandleView mStartHandle; 4895 private SelectionHandleView mEndHandle; 4896 // The offsets of that last touch down event. Remembered to start selection there. 4897 private int mMinTouchOffset, mMaxTouchOffset; 4898 4899 private float mDownPositionX, mDownPositionY; 4900 private boolean mGestureStayedInTapRegion; 4901 4902 // Where the user first starts the drag motion. 4903 private int mStartOffset = -1; 4904 4905 private boolean mHaventMovedEnoughToStartDrag; 4906 // The line that a selection happened most recently with the drag accelerator. 4907 private int mLineSelectionIsOn = -1; 4908 // Whether the drag accelerator has selected past the initial line. 4909 private boolean mSwitchedLines = false; 4910 4911 // Indicates the drag accelerator mode that the user is currently using. 4912 private int mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE; 4913 // Drag accelerator is inactive. 4914 private static final int DRAG_ACCELERATOR_MODE_INACTIVE = 0; 4915 // Character based selection by dragging. Only for mouse. 4916 private static final int DRAG_ACCELERATOR_MODE_CHARACTER = 1; 4917 // Word based selection by dragging. Enabled after long pressing or double tapping. 4918 private static final int DRAG_ACCELERATOR_MODE_WORD = 2; 4919 // Paragraph based selection by dragging. Enabled after mouse triple click. 4920 private static final int DRAG_ACCELERATOR_MODE_PARAGRAPH = 3; 4921 4922 SelectionModifierCursorController() { 4923 resetTouchOffsets(); 4924 } 4925 4926 public void show() { 4927 if (mTextView.isInBatchEditMode()) { 4928 return; 4929 } 4930 initDrawables(); 4931 initHandles(); 4932 } 4933 4934 private void initDrawables() { 4935 if (mSelectHandleLeft == null) { 4936 mSelectHandleLeft = mTextView.getContext().getDrawable( 4937 mTextView.mTextSelectHandleLeftRes); 4938 } 4939 if (mSelectHandleRight == null) { 4940 mSelectHandleRight = mTextView.getContext().getDrawable( 4941 mTextView.mTextSelectHandleRightRes); 4942 } 4943 } 4944 4945 private void initHandles() { 4946 // Lazy object creation has to be done before updatePosition() is called. 4947 if (mStartHandle == null) { 4948 mStartHandle = new SelectionHandleView(mSelectHandleLeft, mSelectHandleRight, 4949 com.android.internal.R.id.selection_start_handle, 4950 HANDLE_TYPE_SELECTION_START); 4951 } 4952 if (mEndHandle == null) { 4953 mEndHandle = new SelectionHandleView(mSelectHandleRight, mSelectHandleLeft, 4954 com.android.internal.R.id.selection_end_handle, 4955 HANDLE_TYPE_SELECTION_END); 4956 } 4957 4958 mStartHandle.show(); 4959 mEndHandle.show(); 4960 4961 hideInsertionPointCursorController(); 4962 } 4963 4964 public void hide() { 4965 if (mStartHandle != null) mStartHandle.hide(); 4966 if (mEndHandle != null) mEndHandle.hide(); 4967 } 4968 4969 public void enterDrag(int dragAcceleratorMode) { 4970 // Just need to init the handles / hide insertion cursor. 4971 show(); 4972 mDragAcceleratorMode = dragAcceleratorMode; 4973 // Start location of selection. 4974 mStartOffset = mTextView.getOffsetForPosition(mLastDownPositionX, 4975 mLastDownPositionY); 4976 mLineSelectionIsOn = mTextView.getLineAtCoordinate(mLastDownPositionY); 4977 // Don't show the handles until user has lifted finger. 4978 hide(); 4979 4980 // This stops scrolling parents from intercepting the touch event, allowing 4981 // the user to continue dragging across the screen to select text; TextView will 4982 // scroll as necessary. 4983 mTextView.getParent().requestDisallowInterceptTouchEvent(true); 4984 mTextView.cancelLongPress(); 4985 } 4986 4987 public void onTouchEvent(MotionEvent event) { 4988 // This is done even when the View does not have focus, so that long presses can start 4989 // selection and tap can move cursor from this tap position. 4990 final float eventX = event.getX(); 4991 final float eventY = event.getY(); 4992 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE); 4993 switch (event.getActionMasked()) { 4994 case MotionEvent.ACTION_DOWN: 4995 if (extractedTextModeWillBeStarted()) { 4996 // Prevent duplicating the selection handles until the mode starts. 4997 hide(); 4998 } else { 4999 // Remember finger down position, to be able to start selection from there. 5000 mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition( 5001 eventX, eventY); 5002 5003 // Double tap detection 5004 if (mGestureStayedInTapRegion) { 5005 if (mTapState == TAP_STATE_DOUBLE_TAP 5006 || mTapState == TAP_STATE_TRIPLE_CLICK) { 5007 final float deltaX = eventX - mDownPositionX; 5008 final float deltaY = eventY - mDownPositionY; 5009 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 5010 5011 ViewConfiguration viewConfiguration = ViewConfiguration.get( 5012 mTextView.getContext()); 5013 int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop(); 5014 boolean stayedInArea = 5015 distanceSquared < doubleTapSlop * doubleTapSlop; 5016 5017 if (stayedInArea && (isMouse || isPositionOnText(eventX, eventY))) { 5018 if (mTapState == TAP_STATE_DOUBLE_TAP) { 5019 selectCurrentWordAndStartDrag(); 5020 } else if (mTapState == TAP_STATE_TRIPLE_CLICK) { 5021 selectCurrentParagraphAndStartDrag(); 5022 } 5023 mDiscardNextActionUp = true; 5024 } 5025 } 5026 } 5027 5028 mDownPositionX = eventX; 5029 mDownPositionY = eventY; 5030 mGestureStayedInTapRegion = true; 5031 mHaventMovedEnoughToStartDrag = true; 5032 } 5033 break; 5034 5035 case MotionEvent.ACTION_POINTER_DOWN: 5036 case MotionEvent.ACTION_POINTER_UP: 5037 // Handle multi-point gestures. Keep min and max offset positions. 5038 // Only activated for devices that correctly handle multi-touch. 5039 if (mTextView.getContext().getPackageManager().hasSystemFeature( 5040 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) { 5041 updateMinAndMaxOffsets(event); 5042 } 5043 break; 5044 5045 case MotionEvent.ACTION_MOVE: 5046 final ViewConfiguration viewConfig = ViewConfiguration.get( 5047 mTextView.getContext()); 5048 final int touchSlop = viewConfig.getScaledTouchSlop(); 5049 5050 if (mGestureStayedInTapRegion || mHaventMovedEnoughToStartDrag) { 5051 final float deltaX = eventX - mDownPositionX; 5052 final float deltaY = eventY - mDownPositionY; 5053 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 5054 5055 if (mGestureStayedInTapRegion) { 5056 int doubleTapTouchSlop = viewConfig.getScaledDoubleTapTouchSlop(); 5057 mGestureStayedInTapRegion = 5058 distanceSquared <= doubleTapTouchSlop * doubleTapTouchSlop; 5059 } 5060 if (mHaventMovedEnoughToStartDrag) { 5061 // We don't start dragging until the user has moved enough. 5062 mHaventMovedEnoughToStartDrag = 5063 distanceSquared <= touchSlop * touchSlop; 5064 } 5065 } 5066 5067 if (isMouse && !isDragAcceleratorActive()) { 5068 final int offset = mTextView.getOffsetForPosition(eventX, eventY); 5069 if (mTextView.hasSelection() 5070 && (!mHaventMovedEnoughToStartDrag || mStartOffset != offset) 5071 && offset >= mTextView.getSelectionStart() 5072 && offset <= mTextView.getSelectionEnd()) { 5073 startDragAndDrop(); 5074 break; 5075 } 5076 5077 if (mStartOffset != offset) { 5078 // Start character based drag accelerator. 5079 stopTextActionMode(); 5080 enterDrag(DRAG_ACCELERATOR_MODE_CHARACTER); 5081 mDiscardNextActionUp = true; 5082 mHaventMovedEnoughToStartDrag = false; 5083 } 5084 } 5085 5086 if (mStartHandle != null && mStartHandle.isShowing()) { 5087 // Don't do the drag if the handles are showing already. 5088 break; 5089 } 5090 5091 updateSelection(event); 5092 break; 5093 5094 case MotionEvent.ACTION_UP: 5095 if (!isDragAcceleratorActive()) { 5096 break; 5097 } 5098 updateSelection(event); 5099 5100 // No longer dragging to select text, let the parent intercept events. 5101 mTextView.getParent().requestDisallowInterceptTouchEvent(false); 5102 5103 int startOffset = mTextView.getSelectionStart(); 5104 int endOffset = mTextView.getSelectionEnd(); 5105 5106 // Since we don't let drag handles pass once they're visible, we need to 5107 // make sure the start / end locations are correct because the user *can* 5108 // switch directions during the initial drag. 5109 if (endOffset < startOffset) { 5110 int tmp = endOffset; 5111 endOffset = startOffset; 5112 startOffset = tmp; 5113 5114 // Also update the selection with the right offsets in this case. 5115 Selection.setSelection((Spannable) mTextView.getText(), 5116 startOffset, endOffset); 5117 } 5118 if (startOffset != endOffset) { 5119 startSelectionActionMode(); 5120 } 5121 5122 // No longer the first dragging motion, reset. 5123 resetDragAcceleratorState(); 5124 break; 5125 } 5126 } 5127 5128 private void updateSelection(MotionEvent event) { 5129 if (mTextView.getLayout() != null) { 5130 switch (mDragAcceleratorMode) { 5131 case DRAG_ACCELERATOR_MODE_CHARACTER: 5132 updateCharacterBasedSelection(event); 5133 break; 5134 case DRAG_ACCELERATOR_MODE_WORD: 5135 updateWordBasedSelection(event); 5136 break; 5137 case DRAG_ACCELERATOR_MODE_PARAGRAPH: 5138 updateParagraphBasedSelection(event); 5139 break; 5140 } 5141 } 5142 } 5143 5144 /** 5145 * If the TextView allows text selection, selects the current paragraph and starts a drag. 5146 * 5147 * @return true if the drag was started. 5148 */ 5149 private boolean selectCurrentParagraphAndStartDrag() { 5150 if (mInsertionActionModeRunnable != null) { 5151 mTextView.removeCallbacks(mInsertionActionModeRunnable); 5152 } 5153 stopTextActionMode(); 5154 if (!selectCurrentParagraph()) { 5155 return false; 5156 } 5157 enterDrag(SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_PARAGRAPH); 5158 return true; 5159 } 5160 5161 private void updateCharacterBasedSelection(MotionEvent event) { 5162 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY()); 5163 Selection.setSelection((Spannable) mTextView.getText(), mStartOffset, offset); 5164 } 5165 5166 private void updateWordBasedSelection(MotionEvent event) { 5167 if (mHaventMovedEnoughToStartDrag) { 5168 return; 5169 } 5170 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE); 5171 final ViewConfiguration viewConfig = ViewConfiguration.get( 5172 mTextView.getContext()); 5173 final float eventX = event.getX(); 5174 final float eventY = event.getY(); 5175 final int currLine; 5176 if (isMouse) { 5177 // No need to offset the y coordinate for mouse input. 5178 currLine = mTextView.getLineAtCoordinate(eventY); 5179 } else { 5180 float y = eventY; 5181 if (mSwitchedLines) { 5182 // Offset the finger by the same vertical offset as the handles. 5183 // This improves visibility of the content being selected by 5184 // shifting the finger below the content, this is applied once 5185 // the user has switched lines. 5186 final int touchSlop = viewConfig.getScaledTouchSlop(); 5187 final float fingerOffset = (mStartHandle != null) 5188 ? mStartHandle.getIdealVerticalOffset() 5189 : touchSlop; 5190 y = eventY - fingerOffset; 5191 } 5192 5193 currLine = getCurrentLineAdjustedForSlop(mTextView.getLayout(), mLineSelectionIsOn, 5194 y); 5195 if (!mSwitchedLines && currLine != mLineSelectionIsOn) { 5196 // Break early here, we want to offset the finger position from 5197 // the selection highlight, once the user moved their finger 5198 // to a different line we should apply the offset and *not* switch 5199 // lines until recomputing the position with the finger offset. 5200 mSwitchedLines = true; 5201 return; 5202 } 5203 } 5204 5205 int startOffset; 5206 int offset = mTextView.getOffsetAtCoordinate(currLine, eventX); 5207 // Snap to word boundaries. 5208 if (mStartOffset < offset) { 5209 // Expanding with end handle. 5210 offset = getWordEnd(offset); 5211 startOffset = getWordStart(mStartOffset); 5212 } else { 5213 // Expanding with start handle. 5214 offset = getWordStart(offset); 5215 startOffset = getWordEnd(mStartOffset); 5216 } 5217 mLineSelectionIsOn = currLine; 5218 Selection.setSelection((Spannable) mTextView.getText(), 5219 startOffset, offset); 5220 } 5221 5222 private void updateParagraphBasedSelection(MotionEvent event) { 5223 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY()); 5224 5225 final int start = Math.min(offset, mStartOffset); 5226 final int end = Math.max(offset, mStartOffset); 5227 final long paragraphsRange = getParagraphsRange(start, end); 5228 final int selectionStart = TextUtils.unpackRangeStartFromLong(paragraphsRange); 5229 final int selectionEnd = TextUtils.unpackRangeEndFromLong(paragraphsRange); 5230 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd); 5231 } 5232 5233 /** 5234 * @param event 5235 */ 5236 private void updateMinAndMaxOffsets(MotionEvent event) { 5237 int pointerCount = event.getPointerCount(); 5238 for (int index = 0; index < pointerCount; index++) { 5239 int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index)); 5240 if (offset < mMinTouchOffset) mMinTouchOffset = offset; 5241 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset; 5242 } 5243 } 5244 5245 public int getMinTouchOffset() { 5246 return mMinTouchOffset; 5247 } 5248 5249 public int getMaxTouchOffset() { 5250 return mMaxTouchOffset; 5251 } 5252 5253 public void resetTouchOffsets() { 5254 mMinTouchOffset = mMaxTouchOffset = -1; 5255 resetDragAcceleratorState(); 5256 } 5257 5258 private void resetDragAcceleratorState() { 5259 mStartOffset = -1; 5260 mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE; 5261 mSwitchedLines = false; 5262 final int selectionStart = mTextView.getSelectionStart(); 5263 final int selectionEnd = mTextView.getSelectionEnd(); 5264 if (selectionStart > selectionEnd) { 5265 Selection.setSelection((Spannable) mTextView.getText(), 5266 selectionEnd, selectionStart); 5267 } 5268 } 5269 5270 /** 5271 * @return true iff this controller is currently used to move the selection start. 5272 */ 5273 public boolean isSelectionStartDragged() { 5274 return mStartHandle != null && mStartHandle.isDragging(); 5275 } 5276 5277 @Override 5278 public boolean isCursorBeingModified() { 5279 return isDragAcceleratorActive() || isSelectionStartDragged() 5280 || (mEndHandle != null && mEndHandle.isDragging()); 5281 } 5282 5283 /** 5284 * @return true if the user is selecting text using the drag accelerator. 5285 */ 5286 public boolean isDragAcceleratorActive() { 5287 return mDragAcceleratorMode != DRAG_ACCELERATOR_MODE_INACTIVE; 5288 } 5289 5290 public void onTouchModeChanged(boolean isInTouchMode) { 5291 if (!isInTouchMode) { 5292 hide(); 5293 } 5294 } 5295 5296 @Override 5297 public void onDetached() { 5298 final ViewTreeObserver observer = mTextView.getViewTreeObserver(); 5299 observer.removeOnTouchModeChangeListener(this); 5300 5301 if (mStartHandle != null) mStartHandle.onDetached(); 5302 if (mEndHandle != null) mEndHandle.onDetached(); 5303 } 5304 5305 @Override 5306 public boolean isActive() { 5307 return mStartHandle != null && mStartHandle.isShowing(); 5308 } 5309 } 5310 5311 private class CorrectionHighlighter { 5312 private final Path mPath = new Path(); 5313 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 5314 private int mStart, mEnd; 5315 private long mFadingStartTime; 5316 private RectF mTempRectF; 5317 private final static int FADE_OUT_DURATION = 400; 5318 5319 public CorrectionHighlighter() { 5320 mPaint.setCompatibilityScaling(mTextView.getResources().getCompatibilityInfo(). 5321 applicationScale); 5322 mPaint.setStyle(Paint.Style.FILL); 5323 } 5324 5325 public void highlight(CorrectionInfo info) { 5326 mStart = info.getOffset(); 5327 mEnd = mStart + info.getNewText().length(); 5328 mFadingStartTime = SystemClock.uptimeMillis(); 5329 5330 if (mStart < 0 || mEnd < 0) { 5331 stopAnimation(); 5332 } 5333 } 5334 5335 public void draw(Canvas canvas, int cursorOffsetVertical) { 5336 if (updatePath() && updatePaint()) { 5337 if (cursorOffsetVertical != 0) { 5338 canvas.translate(0, cursorOffsetVertical); 5339 } 5340 5341 canvas.drawPath(mPath, mPaint); 5342 5343 if (cursorOffsetVertical != 0) { 5344 canvas.translate(0, -cursorOffsetVertical); 5345 } 5346 invalidate(true); // TODO invalidate cursor region only 5347 } else { 5348 stopAnimation(); 5349 invalidate(false); // TODO invalidate cursor region only 5350 } 5351 } 5352 5353 private boolean updatePaint() { 5354 final long duration = SystemClock.uptimeMillis() - mFadingStartTime; 5355 if (duration > FADE_OUT_DURATION) return false; 5356 5357 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION; 5358 final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor); 5359 final int color = (mTextView.mHighlightColor & 0x00FFFFFF) + 5360 ((int) (highlightColorAlpha * coef) << 24); 5361 mPaint.setColor(color); 5362 return true; 5363 } 5364 5365 private boolean updatePath() { 5366 final Layout layout = mTextView.getLayout(); 5367 if (layout == null) return false; 5368 5369 // Update in case text is edited while the animation is run 5370 final int length = mTextView.getText().length(); 5371 int start = Math.min(length, mStart); 5372 int end = Math.min(length, mEnd); 5373 5374 mPath.reset(); 5375 layout.getSelectionPath(start, end, mPath); 5376 return true; 5377 } 5378 5379 private void invalidate(boolean delayed) { 5380 if (mTextView.getLayout() == null) return; 5381 5382 if (mTempRectF == null) mTempRectF = new RectF(); 5383 mPath.computeBounds(mTempRectF, false); 5384 5385 int left = mTextView.getCompoundPaddingLeft(); 5386 int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true); 5387 5388 if (delayed) { 5389 mTextView.postInvalidateOnAnimation( 5390 left + (int) mTempRectF.left, top + (int) mTempRectF.top, 5391 left + (int) mTempRectF.right, top + (int) mTempRectF.bottom); 5392 } else { 5393 mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top, 5394 (int) mTempRectF.right, (int) mTempRectF.bottom); 5395 } 5396 } 5397 5398 private void stopAnimation() { 5399 Editor.this.mCorrectionHighlighter = null; 5400 } 5401 } 5402 5403 private static class ErrorPopup extends PopupWindow { 5404 private boolean mAbove = false; 5405 private final TextView mView; 5406 private int mPopupInlineErrorBackgroundId = 0; 5407 private int mPopupInlineErrorAboveBackgroundId = 0; 5408 5409 ErrorPopup(TextView v, int width, int height) { 5410 super(v, width, height); 5411 mView = v; 5412 // Make sure the TextView has a background set as it will be used the first time it is 5413 // shown and positioned. Initialized with below background, which should have 5414 // dimensions identical to the above version for this to work (and is more likely). 5415 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 5416 com.android.internal.R.styleable.Theme_errorMessageBackground); 5417 mView.setBackgroundResource(mPopupInlineErrorBackgroundId); 5418 } 5419 5420 void fixDirection(boolean above) { 5421 mAbove = above; 5422 5423 if (above) { 5424 mPopupInlineErrorAboveBackgroundId = 5425 getResourceId(mPopupInlineErrorAboveBackgroundId, 5426 com.android.internal.R.styleable.Theme_errorMessageAboveBackground); 5427 } else { 5428 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 5429 com.android.internal.R.styleable.Theme_errorMessageBackground); 5430 } 5431 5432 mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId : 5433 mPopupInlineErrorBackgroundId); 5434 } 5435 5436 private int getResourceId(int currentId, int index) { 5437 if (currentId == 0) { 5438 TypedArray styledAttributes = mView.getContext().obtainStyledAttributes( 5439 R.styleable.Theme); 5440 currentId = styledAttributes.getResourceId(index, 0); 5441 styledAttributes.recycle(); 5442 } 5443 return currentId; 5444 } 5445 5446 @Override 5447 public void update(int x, int y, int w, int h, boolean force) { 5448 super.update(x, y, w, h, force); 5449 5450 boolean above = isAboveAnchor(); 5451 if (above != mAbove) { 5452 fixDirection(above); 5453 } 5454 } 5455 } 5456 5457 static class InputContentType { 5458 int imeOptions = EditorInfo.IME_NULL; 5459 String privateImeOptions; 5460 CharSequence imeActionLabel; 5461 int imeActionId; 5462 Bundle extras; 5463 OnEditorActionListener onEditorActionListener; 5464 boolean enterDown; 5465 LocaleList imeHintLocales; 5466 } 5467 5468 static class InputMethodState { 5469 ExtractedTextRequest mExtractedTextRequest; 5470 final ExtractedText mExtractedText = new ExtractedText(); 5471 int mBatchEditNesting; 5472 boolean mCursorChanged; 5473 boolean mSelectionModeChanged; 5474 boolean mContentChanged; 5475 int mChangedStart, mChangedEnd, mChangedDelta; 5476 } 5477 5478 /** 5479 * @return True iff (start, end) is a valid range within the text. 5480 */ 5481 private static boolean isValidRange(CharSequence text, int start, int end) { 5482 return 0 <= start && start <= end && end <= text.length(); 5483 } 5484 5485 @VisibleForTesting 5486 public SuggestionsPopupWindow getSuggestionsPopupWindowForTesting() { 5487 return mSuggestionsPopupWindow; 5488 } 5489 5490 /** 5491 * An InputFilter that monitors text input to maintain undo history. It does not modify the 5492 * text being typed (and hence always returns null from the filter() method). 5493 */ 5494 public static class UndoInputFilter implements InputFilter { 5495 private final Editor mEditor; 5496 5497 // Whether the current filter pass is directly caused by an end-user text edit. 5498 private boolean mIsUserEdit; 5499 5500 // Whether the text field is handling an IME composition. Must be parceled in case the user 5501 // rotates the screen during composition. 5502 private boolean mHasComposition; 5503 5504 public UndoInputFilter(Editor editor) { 5505 mEditor = editor; 5506 } 5507 5508 public void saveInstanceState(Parcel parcel) { 5509 parcel.writeInt(mIsUserEdit ? 1 : 0); 5510 parcel.writeInt(mHasComposition ? 1 : 0); 5511 } 5512 5513 public void restoreInstanceState(Parcel parcel) { 5514 mIsUserEdit = parcel.readInt() != 0; 5515 mHasComposition = parcel.readInt() != 0; 5516 } 5517 5518 /** 5519 * Signals that a user-triggered edit is starting. 5520 */ 5521 public void beginBatchEdit() { 5522 if (DEBUG_UNDO) Log.d(TAG, "beginBatchEdit"); 5523 mIsUserEdit = true; 5524 } 5525 5526 public void endBatchEdit() { 5527 if (DEBUG_UNDO) Log.d(TAG, "endBatchEdit"); 5528 mIsUserEdit = false; 5529 } 5530 5531 @Override 5532 public CharSequence filter(CharSequence source, int start, int end, 5533 Spanned dest, int dstart, int dend) { 5534 if (DEBUG_UNDO) { 5535 Log.d(TAG, "filter: source=" + source + " (" + start + "-" + end + ") " + 5536 "dest=" + dest + " (" + dstart + "-" + dend + ")"); 5537 } 5538 5539 // Check to see if this edit should be tracked for undo. 5540 if (!canUndoEdit(source, start, end, dest, dstart, dend)) { 5541 return null; 5542 } 5543 5544 // Check for and handle IME composition edits. 5545 if (handleCompositionEdit(source, start, end, dstart)) { 5546 return null; 5547 } 5548 5549 // Handle keyboard edits. 5550 handleKeyboardEdit(source, start, end, dest, dstart, dend); 5551 return null; 5552 } 5553 5554 /** 5555 * Returns true iff the edit was handled, either because it should be ignored or because 5556 * this function created an undo operation for it. 5557 */ 5558 private boolean handleCompositionEdit(CharSequence source, int start, int end, int dstart) { 5559 // Ignore edits while the user is composing. 5560 if (isComposition(source)) { 5561 mHasComposition = true; 5562 return true; 5563 } 5564 final boolean hadComposition = mHasComposition; 5565 mHasComposition = false; 5566 5567 // Check for the transition out of the composing state. 5568 if (hadComposition) { 5569 // If there was no text the user canceled composition. Ignore the edit. 5570 if (start == end) { 5571 return true; 5572 } 5573 5574 // Otherwise the user inserted the composition. 5575 String newText = TextUtils.substring(source, start, end); 5576 EditOperation edit = new EditOperation(mEditor, "", dstart, newText); 5577 recordEdit(edit, false /* forceMerge */); 5578 return true; 5579 } 5580 5581 // This was neither a composition event nor a transition out of composing. 5582 return false; 5583 } 5584 5585 private void handleKeyboardEdit(CharSequence source, int start, int end, 5586 Spanned dest, int dstart, int dend) { 5587 // An application may install a TextWatcher to provide additional modifications after 5588 // the initial input filters run (e.g. a credit card formatter that adds spaces to a 5589 // string). This results in multiple filter() calls for what the user considers to be 5590 // a single operation. Always undo the whole set of changes in one step. 5591 final boolean forceMerge = isInTextWatcher(); 5592 5593 // Build a new operation with all the information from this edit. 5594 String newText = TextUtils.substring(source, start, end); 5595 String oldText = TextUtils.substring(dest, dstart, dend); 5596 EditOperation edit = new EditOperation(mEditor, oldText, dstart, newText); 5597 recordEdit(edit, forceMerge); 5598 } 5599 5600 /** 5601 * Fetches the last undo operation and checks to see if a new edit should be merged into it. 5602 * If forceMerge is true then the new edit is always merged. 5603 */ 5604 private void recordEdit(EditOperation edit, boolean forceMerge) { 5605 // Fetch the last edit operation and attempt to merge in the new edit. 5606 final UndoManager um = mEditor.mUndoManager; 5607 um.beginUpdate("Edit text"); 5608 EditOperation lastEdit = um.getLastOperation( 5609 EditOperation.class, mEditor.mUndoOwner, UndoManager.MERGE_MODE_UNIQUE); 5610 if (lastEdit == null) { 5611 // Add this as the first edit. 5612 if (DEBUG_UNDO) Log.d(TAG, "filter: adding first op " + edit); 5613 um.addOperation(edit, UndoManager.MERGE_MODE_NONE); 5614 } else if (forceMerge) { 5615 // Forced merges take priority because they could be the result of a non-user-edit 5616 // change and this case should not create a new undo operation. 5617 if (DEBUG_UNDO) Log.d(TAG, "filter: force merge " + edit); 5618 lastEdit.forceMergeWith(edit); 5619 } else if (!mIsUserEdit) { 5620 // An application directly modified the Editable outside of a text edit. Treat this 5621 // as a new change and don't attempt to merge. 5622 if (DEBUG_UNDO) Log.d(TAG, "non-user edit, new op " + edit); 5623 um.commitState(mEditor.mUndoOwner); 5624 um.addOperation(edit, UndoManager.MERGE_MODE_NONE); 5625 } else if (lastEdit.mergeWith(edit)) { 5626 // Merge succeeded, nothing else to do. 5627 if (DEBUG_UNDO) Log.d(TAG, "filter: merge succeeded, created " + lastEdit); 5628 } else { 5629 // Could not merge with the last edit, so commit the last edit and add this edit. 5630 if (DEBUG_UNDO) Log.d(TAG, "filter: merge failed, adding " + edit); 5631 um.commitState(mEditor.mUndoOwner); 5632 um.addOperation(edit, UndoManager.MERGE_MODE_NONE); 5633 } 5634 um.endUpdate(); 5635 } 5636 5637 private boolean canUndoEdit(CharSequence source, int start, int end, 5638 Spanned dest, int dstart, int dend) { 5639 if (!mEditor.mAllowUndo) { 5640 if (DEBUG_UNDO) Log.d(TAG, "filter: undo is disabled"); 5641 return false; 5642 } 5643 5644 if (mEditor.mUndoManager.isInUndo()) { 5645 if (DEBUG_UNDO) Log.d(TAG, "filter: skipping, currently performing undo/redo"); 5646 return false; 5647 } 5648 5649 // Text filters run before input operations are applied. However, some input operations 5650 // are invalid and will throw exceptions when applied. This is common in tests. Don't 5651 // attempt to undo invalid operations. 5652 if (!isValidRange(source, start, end) || !isValidRange(dest, dstart, dend)) { 5653 if (DEBUG_UNDO) Log.d(TAG, "filter: invalid op"); 5654 return false; 5655 } 5656 5657 // Earlier filters can rewrite input to be a no-op, for example due to a length limit 5658 // on an input field. Skip no-op changes. 5659 if (start == end && dstart == dend) { 5660 if (DEBUG_UNDO) Log.d(TAG, "filter: skipping no-op"); 5661 return false; 5662 } 5663 5664 return true; 5665 } 5666 5667 private boolean isComposition(CharSequence source) { 5668 if (!(source instanceof Spannable)) { 5669 return false; 5670 } 5671 // This is a composition edit if the source has a non-zero-length composing span. 5672 Spannable text = (Spannable) source; 5673 int composeBegin = EditableInputConnection.getComposingSpanStart(text); 5674 int composeEnd = EditableInputConnection.getComposingSpanEnd(text); 5675 return composeBegin < composeEnd; 5676 } 5677 5678 private boolean isInTextWatcher() { 5679 CharSequence text = mEditor.mTextView.getText(); 5680 return (text instanceof SpannableStringBuilder) 5681 && ((SpannableStringBuilder) text).getTextWatcherDepth() > 0; 5682 } 5683 } 5684 5685 /** 5686 * An operation to undo a single "edit" to a text view. 5687 */ 5688 public static class EditOperation extends UndoOperation<Editor> { 5689 private static final int TYPE_INSERT = 0; 5690 private static final int TYPE_DELETE = 1; 5691 private static final int TYPE_REPLACE = 2; 5692 5693 private int mType; 5694 private String mOldText; 5695 private int mOldTextStart; 5696 private String mNewText; 5697 private int mNewTextStart; 5698 5699 private int mOldCursorPos; 5700 private int mNewCursorPos; 5701 5702 /** 5703 * Constructs an edit operation from a text input operation on editor that replaces the 5704 * oldText starting at dstart with newText. 5705 */ 5706 public EditOperation(Editor editor, String oldText, int dstart, String newText) { 5707 super(editor.mUndoOwner); 5708 mOldText = oldText; 5709 mNewText = newText; 5710 5711 // Determine the type of the edit and store where it occurred. Avoid storing 5712 // irrevelant data (e.g. mNewTextStart for a delete) because that makes the 5713 // merging logic more complex (e.g. merging deletes could lead to mNewTextStart being 5714 // outside the bounds of the final text). 5715 if (mNewText.length() > 0 && mOldText.length() == 0) { 5716 mType = TYPE_INSERT; 5717 mNewTextStart = dstart; 5718 } else if (mNewText.length() == 0 && mOldText.length() > 0) { 5719 mType = TYPE_DELETE; 5720 mOldTextStart = dstart; 5721 } else { 5722 mType = TYPE_REPLACE; 5723 mOldTextStart = mNewTextStart = dstart; 5724 } 5725 5726 // Store cursor data. 5727 mOldCursorPos = editor.mTextView.getSelectionStart(); 5728 mNewCursorPos = dstart + mNewText.length(); 5729 } 5730 5731 public EditOperation(Parcel src, ClassLoader loader) { 5732 super(src, loader); 5733 mType = src.readInt(); 5734 mOldText = src.readString(); 5735 mOldTextStart = src.readInt(); 5736 mNewText = src.readString(); 5737 mNewTextStart = src.readInt(); 5738 mOldCursorPos = src.readInt(); 5739 mNewCursorPos = src.readInt(); 5740 } 5741 5742 @Override 5743 public void writeToParcel(Parcel dest, int flags) { 5744 dest.writeInt(mType); 5745 dest.writeString(mOldText); 5746 dest.writeInt(mOldTextStart); 5747 dest.writeString(mNewText); 5748 dest.writeInt(mNewTextStart); 5749 dest.writeInt(mOldCursorPos); 5750 dest.writeInt(mNewCursorPos); 5751 } 5752 5753 private int getNewTextEnd() { 5754 return mNewTextStart + mNewText.length(); 5755 } 5756 5757 private int getOldTextEnd() { 5758 return mOldTextStart + mOldText.length(); 5759 } 5760 5761 @Override 5762 public void commit() { 5763 } 5764 5765 @Override 5766 public void undo() { 5767 if (DEBUG_UNDO) Log.d(TAG, "undo"); 5768 // Remove the new text and insert the old. 5769 Editor editor = getOwnerData(); 5770 Editable text = (Editable) editor.mTextView.getText(); 5771 modifyText(text, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart, 5772 mOldCursorPos); 5773 } 5774 5775 @Override 5776 public void redo() { 5777 if (DEBUG_UNDO) Log.d(TAG, "redo"); 5778 // Remove the old text and insert the new. 5779 Editor editor = getOwnerData(); 5780 Editable text = (Editable) editor.mTextView.getText(); 5781 modifyText(text, mOldTextStart, getOldTextEnd(), mNewText, mNewTextStart, 5782 mNewCursorPos); 5783 } 5784 5785 /** 5786 * Attempts to merge this existing operation with a new edit. 5787 * @param edit The new edit operation. 5788 * @return If the merge succeeded, returns true. Otherwise returns false and leaves this 5789 * object unchanged. 5790 */ 5791 private boolean mergeWith(EditOperation edit) { 5792 if (DEBUG_UNDO) { 5793 Log.d(TAG, "mergeWith old " + this); 5794 Log.d(TAG, "mergeWith new " + edit); 5795 } 5796 switch (mType) { 5797 case TYPE_INSERT: 5798 return mergeInsertWith(edit); 5799 case TYPE_DELETE: 5800 return mergeDeleteWith(edit); 5801 case TYPE_REPLACE: 5802 return mergeReplaceWith(edit); 5803 default: 5804 return false; 5805 } 5806 } 5807 5808 private boolean mergeInsertWith(EditOperation edit) { 5809 // Only merge continuous insertions. 5810 if (edit.mType != TYPE_INSERT) { 5811 return false; 5812 } 5813 // Only merge insertions that are contiguous. 5814 if (getNewTextEnd() != edit.mNewTextStart) { 5815 return false; 5816 } 5817 mNewText += edit.mNewText; 5818 mNewCursorPos = edit.mNewCursorPos; 5819 return true; 5820 } 5821 5822 // TODO: Support forward delete. 5823 private boolean mergeDeleteWith(EditOperation edit) { 5824 // Only merge continuous deletes. 5825 if (edit.mType != TYPE_DELETE) { 5826 return false; 5827 } 5828 // Only merge deletions that are contiguous. 5829 if (mOldTextStart != edit.getOldTextEnd()) { 5830 return false; 5831 } 5832 mOldTextStart = edit.mOldTextStart; 5833 mOldText = edit.mOldText + mOldText; 5834 mNewCursorPos = edit.mNewCursorPos; 5835 return true; 5836 } 5837 5838 private boolean mergeReplaceWith(EditOperation edit) { 5839 // Replacements can merge only with adjacent inserts. 5840 if (edit.mType != TYPE_INSERT || getNewTextEnd() != edit.mNewTextStart) { 5841 return false; 5842 } 5843 mOldText += edit.mOldText; 5844 mNewText += edit.mNewText; 5845 mNewCursorPos = edit.mNewCursorPos; 5846 return true; 5847 } 5848 5849 /** 5850 * Forcibly creates a single merged edit operation by simulating the entire text 5851 * contents being replaced. 5852 */ 5853 public void forceMergeWith(EditOperation edit) { 5854 if (DEBUG_UNDO) Log.d(TAG, "forceMerge"); 5855 Editor editor = getOwnerData(); 5856 5857 // Copy the text of the current field. 5858 // NOTE: Using StringBuilder instead of SpannableStringBuilder would be somewhat faster, 5859 // but would require two parallel implementations of modifyText() because Editable and 5860 // StringBuilder do not share an interface for replace/delete/insert. 5861 Editable editable = (Editable) editor.mTextView.getText(); 5862 Editable originalText = new SpannableStringBuilder(editable.toString()); 5863 5864 // Roll back the last operation. 5865 modifyText(originalText, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart, 5866 mOldCursorPos); 5867 5868 // Clone the text again and apply the new operation. 5869 Editable finalText = new SpannableStringBuilder(editable.toString()); 5870 modifyText(finalText, edit.mOldTextStart, edit.getOldTextEnd(), edit.mNewText, 5871 edit.mNewTextStart, edit.mNewCursorPos); 5872 5873 // Convert this operation into a non-mergeable replacement of the entire string. 5874 mType = TYPE_REPLACE; 5875 mNewText = finalText.toString(); 5876 mNewTextStart = 0; 5877 mOldText = originalText.toString(); 5878 mOldTextStart = 0; 5879 mNewCursorPos = edit.mNewCursorPos; 5880 // mOldCursorPos is unchanged. 5881 } 5882 5883 private static void modifyText(Editable text, int deleteFrom, int deleteTo, 5884 CharSequence newText, int newTextInsertAt, int newCursorPos) { 5885 // Apply the edit if it is still valid. 5886 if (isValidRange(text, deleteFrom, deleteTo) && 5887 newTextInsertAt <= text.length() - (deleteTo - deleteFrom)) { 5888 if (deleteFrom != deleteTo) { 5889 text.delete(deleteFrom, deleteTo); 5890 } 5891 if (newText.length() != 0) { 5892 text.insert(newTextInsertAt, newText); 5893 } 5894 } 5895 // Restore the cursor position. If there wasn't an old cursor (newCursorPos == -1) then 5896 // don't explicitly set it and rely on SpannableStringBuilder to position it. 5897 // TODO: Select all the text that was undone. 5898 if (0 <= newCursorPos && newCursorPos <= text.length()) { 5899 Selection.setSelection(text, newCursorPos); 5900 } 5901 } 5902 5903 private String getTypeString() { 5904 switch (mType) { 5905 case TYPE_INSERT: 5906 return "insert"; 5907 case TYPE_DELETE: 5908 return "delete"; 5909 case TYPE_REPLACE: 5910 return "replace"; 5911 default: 5912 return ""; 5913 } 5914 } 5915 5916 @Override 5917 public String toString() { 5918 return "[mType=" + getTypeString() + ", " + 5919 "mOldText=" + mOldText + ", " + 5920 "mOldTextStart=" + mOldTextStart + ", " + 5921 "mNewText=" + mNewText + ", " + 5922 "mNewTextStart=" + mNewTextStart + ", " + 5923 "mOldCursorPos=" + mOldCursorPos + ", " + 5924 "mNewCursorPos=" + mNewCursorPos + "]"; 5925 } 5926 5927 public static final Parcelable.ClassLoaderCreator<EditOperation> CREATOR 5928 = new Parcelable.ClassLoaderCreator<EditOperation>() { 5929 @Override 5930 public EditOperation createFromParcel(Parcel in) { 5931 return new EditOperation(in, null); 5932 } 5933 5934 @Override 5935 public EditOperation createFromParcel(Parcel in, ClassLoader loader) { 5936 return new EditOperation(in, loader); 5937 } 5938 5939 @Override 5940 public EditOperation[] newArray(int size) { 5941 return new EditOperation[size]; 5942 } 5943 }; 5944 } 5945 5946 /** 5947 * A helper for enabling and handling "PROCESS_TEXT" menu actions. 5948 * These allow external applications to plug into currently selected text. 5949 */ 5950 static final class ProcessTextIntentActionsHandler { 5951 5952 private final Editor mEditor; 5953 private final TextView mTextView; 5954 private final PackageManager mPackageManager; 5955 private final SparseArray<Intent> mAccessibilityIntents = new SparseArray<Intent>(); 5956 private final SparseArray<AccessibilityNodeInfo.AccessibilityAction> mAccessibilityActions 5957 = new SparseArray<AccessibilityNodeInfo.AccessibilityAction>(); 5958 5959 private ProcessTextIntentActionsHandler(Editor editor) { 5960 mEditor = Preconditions.checkNotNull(editor); 5961 mTextView = Preconditions.checkNotNull(mEditor.mTextView); 5962 mPackageManager = Preconditions.checkNotNull( 5963 mTextView.getContext().getPackageManager()); 5964 } 5965 5966 /** 5967 * Adds "PROCESS_TEXT" menu items to the specified menu. 5968 */ 5969 public void onInitializeMenu(Menu menu) { 5970 int i = 0; 5971 for (ResolveInfo resolveInfo : getSupportedActivities()) { 5972 menu.add(Menu.NONE, Menu.NONE, 5973 Editor.MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START + i++, 5974 getLabel(resolveInfo)) 5975 .setIntent(createProcessTextIntentForResolveInfo(resolveInfo)) 5976 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); 5977 } 5978 } 5979 5980 /** 5981 * Performs a "PROCESS_TEXT" action if there is one associated with the specified 5982 * menu item. 5983 * 5984 * @return True if the action was performed, false otherwise. 5985 */ 5986 public boolean performMenuItemAction(MenuItem item) { 5987 return fireIntent(item.getIntent()); 5988 } 5989 5990 /** 5991 * Initializes and caches "PROCESS_TEXT" accessibility actions. 5992 */ 5993 public void initializeAccessibilityActions() { 5994 mAccessibilityIntents.clear(); 5995 mAccessibilityActions.clear(); 5996 int i = 0; 5997 for (ResolveInfo resolveInfo : getSupportedActivities()) { 5998 int actionId = TextView.ACCESSIBILITY_ACTION_PROCESS_TEXT_START_ID + i++; 5999 mAccessibilityActions.put( 6000 actionId, 6001 new AccessibilityNodeInfo.AccessibilityAction( 6002 actionId, getLabel(resolveInfo))); 6003 mAccessibilityIntents.put( 6004 actionId, createProcessTextIntentForResolveInfo(resolveInfo)); 6005 } 6006 } 6007 6008 /** 6009 * Adds "PROCESS_TEXT" accessibility actions to the specified accessibility node info. 6010 * NOTE: This needs a prior call to {@link #initializeAccessibilityActions()} to make the 6011 * latest accessibility actions available for this call. 6012 */ 6013 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo nodeInfo) { 6014 for (int i = 0; i < mAccessibilityActions.size(); i++) { 6015 nodeInfo.addAction(mAccessibilityActions.valueAt(i)); 6016 } 6017 } 6018 6019 /** 6020 * Performs a "PROCESS_TEXT" action if there is one associated with the specified 6021 * accessibility action id. 6022 * 6023 * @return True if the action was performed, false otherwise. 6024 */ 6025 public boolean performAccessibilityAction(int actionId) { 6026 return fireIntent(mAccessibilityIntents.get(actionId)); 6027 } 6028 6029 private boolean fireIntent(Intent intent) { 6030 if (intent != null && Intent.ACTION_PROCESS_TEXT.equals(intent.getAction())) { 6031 intent.putExtra(Intent.EXTRA_PROCESS_TEXT, mTextView.getSelectedText()); 6032 mEditor.mPreserveSelection = true; 6033 mTextView.startActivityForResult(intent, TextView.PROCESS_TEXT_REQUEST_CODE); 6034 return true; 6035 } 6036 return false; 6037 } 6038 6039 private List<ResolveInfo> getSupportedActivities() { 6040 PackageManager packageManager = mTextView.getContext().getPackageManager(); 6041 return packageManager.queryIntentActivities(createProcessTextIntent(), 0); 6042 } 6043 6044 private Intent createProcessTextIntentForResolveInfo(ResolveInfo info) { 6045 return createProcessTextIntent() 6046 .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, !mTextView.isTextEditable()) 6047 .setClassName(info.activityInfo.packageName, info.activityInfo.name); 6048 } 6049 6050 private Intent createProcessTextIntent() { 6051 return new Intent() 6052 .setAction(Intent.ACTION_PROCESS_TEXT) 6053 .setType("text/plain"); 6054 } 6055 6056 private CharSequence getLabel(ResolveInfo resolveInfo) { 6057 return resolveInfo.loadLabel(mPackageManager); 6058 } 6059 } 6060} 6061