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