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