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