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