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