Editor.java revision deb2f49f2ca57226e1e49a623718a1e0f1c083fe
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;
132import java.util.Map;
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 = true;
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_SECONDARY_ASSIST_ACTIONS_START = 50;
167    private static final int MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START = 100;
168
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 mDrawableForCursor = 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 && mDrawableForCursor != 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 (mDrawableForCursor != null) {
1896            mDrawableForCursor.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            mDrawableForCursor = 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 mDrawableForCursor;
2337    }
2338
2339    private void updateCursorPosition(int top, int bottom, float horizontal) {
2340        if (mDrawableForCursor == null) {
2341            mDrawableForCursor = mTextView.getContext().getDrawable(
2342                    mTextView.mCursorDrawableRes);
2343        }
2344        final int left = clampHorizontalPosition(mDrawableForCursor, horizontal);
2345        final int width = mDrawableForCursor.getIntrinsicWidth();
2346        mDrawableForCursor.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        private final Map<MenuItem, OnClickListener> mAssistClickHandlers = new HashMap<>();
3797
3798        public TextActionModeCallback(boolean hasSelection) {
3799            mHasSelection = hasSelection;
3800            if (mHasSelection) {
3801                SelectionModifierCursorController selectionController = getSelectionController();
3802                if (selectionController.mStartHandle == null) {
3803                    // As these are for initializing selectionController, hide() must be called.
3804                    selectionController.initDrawables();
3805                    selectionController.initHandles();
3806                    selectionController.hide();
3807                }
3808                mHandleHeight = Math.max(
3809                        mSelectHandleLeft.getMinimumHeight(),
3810                        mSelectHandleRight.getMinimumHeight());
3811            } else {
3812                InsertionPointCursorController insertionController = getInsertionController();
3813                if (insertionController != null) {
3814                    insertionController.getHandle();
3815                    mHandleHeight = mSelectHandleCenter.getMinimumHeight();
3816                } else {
3817                    mHandleHeight = 0;
3818                }
3819            }
3820        }
3821
3822        @Override
3823        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
3824            mAssistClickHandlers.clear();
3825
3826            mode.setTitle(null);
3827            mode.setSubtitle(null);
3828            mode.setTitleOptionalHint(true);
3829            populateMenuWithItems(menu);
3830
3831            Callback customCallback = getCustomCallback();
3832            if (customCallback != null) {
3833                if (!customCallback.onCreateActionMode(mode, menu)) {
3834                    // The custom mode can choose to cancel the action mode, dismiss selection.
3835                    Selection.setSelection((Spannable) mTextView.getText(),
3836                            mTextView.getSelectionEnd());
3837                    return false;
3838                }
3839            }
3840
3841            if (mTextView.canProcessText()) {
3842                mProcessTextIntentActionsHandler.onInitializeMenu(menu);
3843            }
3844
3845            if (mHasSelection && !mTextView.hasTransientState()) {
3846                mTextView.setHasTransientState(true);
3847            }
3848            return true;
3849        }
3850
3851        private Callback getCustomCallback() {
3852            return mHasSelection
3853                    ? mCustomSelectionActionModeCallback
3854                    : mCustomInsertionActionModeCallback;
3855        }
3856
3857        private void populateMenuWithItems(Menu menu) {
3858            if (mTextView.canCut()) {
3859                menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT,
3860                        com.android.internal.R.string.cut)
3861                                .setAlphabeticShortcut('x')
3862                                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
3863            }
3864
3865            if (mTextView.canCopy()) {
3866                menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY,
3867                        com.android.internal.R.string.copy)
3868                                .setAlphabeticShortcut('c')
3869                                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
3870            }
3871
3872            if (mTextView.canPaste()) {
3873                menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE,
3874                        com.android.internal.R.string.paste)
3875                                .setAlphabeticShortcut('v')
3876                                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
3877            }
3878
3879            if (mTextView.canShare()) {
3880                menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE,
3881                        com.android.internal.R.string.share)
3882                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3883            }
3884
3885            if (mTextView.canRequestAutofill()) {
3886                final String selected = mTextView.getSelectedText();
3887                if (selected == null || selected.isEmpty()) {
3888                    menu.add(Menu.NONE, TextView.ID_AUTOFILL, MENU_ITEM_ORDER_AUTOFILL,
3889                            com.android.internal.R.string.autofill)
3890                            .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
3891                }
3892            }
3893
3894            if (mTextView.canPasteAsPlainText()) {
3895                menu.add(
3896                        Menu.NONE,
3897                        TextView.ID_PASTE_AS_PLAIN_TEXT,
3898                        MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT,
3899                        com.android.internal.R.string.paste_as_plain_text)
3900                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3901            }
3902
3903            updateSelectAllItem(menu);
3904            updateReplaceItem(menu);
3905            updateAssistMenuItems(menu);
3906        }
3907
3908        @Override
3909        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
3910            updateSelectAllItem(menu);
3911            updateReplaceItem(menu);
3912            updateAssistMenuItems(menu);
3913
3914            Callback customCallback = getCustomCallback();
3915            if (customCallback != null) {
3916                return customCallback.onPrepareActionMode(mode, menu);
3917            }
3918            return true;
3919        }
3920
3921        private void updateSelectAllItem(Menu menu) {
3922            boolean canSelectAll = mTextView.canSelectAllText();
3923            boolean selectAllItemExists = menu.findItem(TextView.ID_SELECT_ALL) != null;
3924            if (canSelectAll && !selectAllItemExists) {
3925                menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL,
3926                        com.android.internal.R.string.selectAll)
3927                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3928            } else if (!canSelectAll && selectAllItemExists) {
3929                menu.removeItem(TextView.ID_SELECT_ALL);
3930            }
3931        }
3932
3933        private void updateReplaceItem(Menu menu) {
3934            boolean canReplace = mTextView.isSuggestionsEnabled() && shouldOfferToShowSuggestions();
3935            boolean replaceItemExists = menu.findItem(TextView.ID_REPLACE) != null;
3936            if (canReplace && !replaceItemExists) {
3937                menu.add(Menu.NONE, TextView.ID_REPLACE, MENU_ITEM_ORDER_REPLACE,
3938                        com.android.internal.R.string.replace)
3939                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3940            } else if (!canReplace && replaceItemExists) {
3941                menu.removeItem(TextView.ID_REPLACE);
3942            }
3943        }
3944
3945        private void updateAssistMenuItems(Menu menu) {
3946            clearAssistMenuItems(menu);
3947            if (!mTextView.isDeviceProvisioned()) {
3948                return;
3949            }
3950            final TextClassification textClassification =
3951                    getSelectionActionModeHelper().getTextClassification();
3952            final int count = textClassification != null ? textClassification.getActionCount() : 0;
3953            for (int i = 0; i < count; i++) {
3954                if (!isValidAssistMenuItem(i)) {
3955                    continue;
3956                }
3957                final int groupId = TextView.ID_ASSIST;
3958                final int order = (i == 0)
3959                        ? MENU_ITEM_ORDER_ASSIST
3960                        : MENU_ITEM_ORDER_SECONDARY_ASSIST_ACTIONS_START + i;
3961                final int id = (i == 0) ? TextView.ID_ASSIST : Menu.NONE;
3962                final int showAsFlag = (i == 0)
3963                        ? MenuItem.SHOW_AS_ACTION_ALWAYS
3964                        : MenuItem.SHOW_AS_ACTION_NEVER;
3965                final MenuItem item = menu.add(
3966                        groupId, id, order, textClassification.getLabel(i))
3967                        .setIcon(textClassification.getIcon(i))
3968                        .setIntent(textClassification.getIntent(i));
3969                item.setShowAsAction(showAsFlag);
3970                mAssistClickHandlers.put(item, textClassification.getOnClickListener(i));
3971                if (id == TextView.ID_ASSIST) {
3972                    mMetricsLogger.write(
3973                            new LogMaker(MetricsEvent.TEXT_SELECTION_MENU_ITEM_ASSIST)
3974                                    .setType(MetricsEvent.TYPE_OPEN)
3975                                    .setSubtype(textClassification.getLogType()));
3976                }
3977            }
3978        }
3979
3980        private void clearAssistMenuItems(Menu menu) {
3981            int i = 0;
3982            while (i < menu.size()) {
3983                final MenuItem menuItem = menu.getItem(i);
3984                if (menuItem.getGroupId() == TextView.ID_ASSIST) {
3985                    menu.removeItem(menuItem.getItemId());
3986                    continue;
3987                }
3988                i++;
3989            }
3990        }
3991
3992        private boolean isValidAssistMenuItem(int index) {
3993            final TextClassification textClassification =
3994                    getSelectionActionModeHelper().getTextClassification();
3995            if (!mTextView.isDeviceProvisioned() || textClassification == null
3996                    || index < 0 || index >= textClassification.getActionCount()) {
3997                return false;
3998            }
3999            final Drawable icon = textClassification.getIcon(index);
4000            final CharSequence label = textClassification.getLabel(index);
4001            final boolean hasUi = icon != null || !TextUtils.isEmpty(label);
4002            final OnClickListener onClick = textClassification.getOnClickListener(index);
4003            final Intent intent = textClassification.getIntent(index);
4004            final boolean hasAction = onClick != null || isSupportedIntent(intent);
4005            return hasUi && hasAction;
4006        }
4007
4008        private boolean isSupportedIntent(Intent intent) {
4009            if (intent == null) {
4010                return false;
4011            }
4012            final Context context = mTextView.getContext();
4013            final ResolveInfo info = context.getPackageManager().resolveActivity(intent, 0);
4014            final boolean samePackage = context.getPackageName().equals(
4015                    info.activityInfo.packageName);
4016            if (samePackage) {
4017                return true;
4018            }
4019
4020            final boolean exported =  info.activityInfo.exported;
4021            final boolean requiresPermission = info.activityInfo.permission != null;
4022            final boolean hasPermission = !requiresPermission
4023                    || context.checkSelfPermission(info.activityInfo.permission)
4024                            == PackageManager.PERMISSION_GRANTED;
4025            return exported && hasPermission;
4026        }
4027
4028        private boolean onAssistMenuItemClicked(MenuItem assistMenuItem) {
4029            Preconditions.checkArgument(assistMenuItem.getGroupId() == TextView.ID_ASSIST);
4030
4031            final TextClassification textClassification =
4032                    getSelectionActionModeHelper().getTextClassification();
4033            if (!mTextView.isDeviceProvisioned() || textClassification == null) {
4034                // No textClassification result to handle the click. Eat the click.
4035                return true;
4036            }
4037
4038            OnClickListener onClickListener = mAssistClickHandlers.get(assistMenuItem);
4039            if (onClickListener == null) {
4040                final Intent intent = assistMenuItem.getIntent();
4041                if (intent != null) {
4042                    onClickListener = TextClassification.createStartActivityOnClickListener(
4043                            mTextView.getContext(), intent);
4044                }
4045            }
4046            if (onClickListener != null) {
4047                onClickListener.onClick(mTextView);
4048                stopTextActionMode();
4049                if (assistMenuItem.getItemId() == TextView.ID_ASSIST) {
4050                    mMetricsLogger.action(
4051                            MetricsEvent.ACTION_TEXT_SELECTION_MENU_ITEM_ASSIST,
4052                            textClassification.getLogType());
4053                }
4054            }
4055            // We tried our best.
4056            return true;
4057        }
4058
4059        @Override
4060        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
4061            getSelectionActionModeHelper().onSelectionAction(item.getItemId());
4062
4063            if (mProcessTextIntentActionsHandler.performMenuItemAction(item)) {
4064                return true;
4065            }
4066            Callback customCallback = getCustomCallback();
4067            if (customCallback != null && customCallback.onActionItemClicked(mode, item)) {
4068                return true;
4069            }
4070            if (item.getGroupId() == TextView.ID_ASSIST && onAssistMenuItemClicked(item)) {
4071                return true;
4072            }
4073            return mTextView.onTextContextMenuItem(item.getItemId());
4074        }
4075
4076        @Override
4077        public void onDestroyActionMode(ActionMode mode) {
4078            // Clear mTextActionMode not to recursively destroy action mode by clearing selection.
4079            getSelectionActionModeHelper().onDestroyActionMode();
4080            mTextActionMode = null;
4081            Callback customCallback = getCustomCallback();
4082            if (customCallback != null) {
4083                customCallback.onDestroyActionMode(mode);
4084            }
4085
4086            if (!mPreserveSelection) {
4087                /*
4088                 * Leave current selection when we tentatively destroy action mode for the
4089                 * selection. If we're detaching from a window, we'll bring back the selection
4090                 * mode when (if) we get reattached.
4091                 */
4092                Selection.setSelection((Spannable) mTextView.getText(),
4093                        mTextView.getSelectionEnd());
4094            }
4095
4096            if (mSelectionModifierCursorController != null) {
4097                mSelectionModifierCursorController.hide();
4098            }
4099
4100            mAssistClickHandlers.clear();
4101        }
4102
4103        @Override
4104        public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
4105            if (!view.equals(mTextView) || mTextView.getLayout() == null) {
4106                super.onGetContentRect(mode, view, outRect);
4107                return;
4108            }
4109            if (mTextView.getSelectionStart() != mTextView.getSelectionEnd()) {
4110                // We have a selection.
4111                mSelectionPath.reset();
4112                mTextView.getLayout().getSelectionPath(
4113                        mTextView.getSelectionStart(), mTextView.getSelectionEnd(), mSelectionPath);
4114                mSelectionPath.computeBounds(mSelectionBounds, true);
4115                mSelectionBounds.bottom += mHandleHeight;
4116            } else {
4117                // We have a cursor.
4118                Layout layout = mTextView.getLayout();
4119                int line = layout.getLineForOffset(mTextView.getSelectionStart());
4120                float primaryHorizontal = clampHorizontalPosition(null,
4121                        layout.getPrimaryHorizontal(mTextView.getSelectionStart()));
4122                mSelectionBounds.set(
4123                        primaryHorizontal,
4124                        layout.getLineTop(line),
4125                        primaryHorizontal,
4126                        layout.getLineBottom(line) - layout.getLineBottom(line) + mHandleHeight);
4127            }
4128            // Take TextView's padding and scroll into account.
4129            int textHorizontalOffset = mTextView.viewportToContentHorizontalOffset();
4130            int textVerticalOffset = mTextView.viewportToContentVerticalOffset();
4131            outRect.set(
4132                    (int) Math.floor(mSelectionBounds.left + textHorizontalOffset),
4133                    (int) Math.floor(mSelectionBounds.top + textVerticalOffset),
4134                    (int) Math.ceil(mSelectionBounds.right + textHorizontalOffset),
4135                    (int) Math.ceil(mSelectionBounds.bottom + textVerticalOffset));
4136        }
4137    }
4138
4139    /**
4140     * A listener to call {@link InputMethodManager#updateCursorAnchorInfo(View, CursorAnchorInfo)}
4141     * while the input method is requesting the cursor/anchor position. Does nothing as long as
4142     * {@link InputMethodManager#isWatchingCursor(View)} returns false.
4143     */
4144    private final class CursorAnchorInfoNotifier implements TextViewPositionListener {
4145        final CursorAnchorInfo.Builder mSelectionInfoBuilder = new CursorAnchorInfo.Builder();
4146        final int[] mTmpIntOffset = new int[2];
4147        final Matrix mViewToScreenMatrix = new Matrix();
4148
4149        @Override
4150        public void updatePosition(int parentPositionX, int parentPositionY,
4151                boolean parentPositionChanged, boolean parentScrolled) {
4152            final InputMethodState ims = mInputMethodState;
4153            if (ims == null || ims.mBatchEditNesting > 0) {
4154                return;
4155            }
4156            final InputMethodManager imm = InputMethodManager.peekInstance();
4157            if (null == imm) {
4158                return;
4159            }
4160            if (!imm.isActive(mTextView)) {
4161                return;
4162            }
4163            // Skip if the IME has not requested the cursor/anchor position.
4164            if (!imm.isCursorAnchorInfoEnabled()) {
4165                return;
4166            }
4167            Layout layout = mTextView.getLayout();
4168            if (layout == null) {
4169                return;
4170            }
4171
4172            final CursorAnchorInfo.Builder builder = mSelectionInfoBuilder;
4173            builder.reset();
4174
4175            final int selectionStart = mTextView.getSelectionStart();
4176            builder.setSelectionRange(selectionStart, mTextView.getSelectionEnd());
4177
4178            // Construct transformation matrix from view local coordinates to screen coordinates.
4179            mViewToScreenMatrix.set(mTextView.getMatrix());
4180            mTextView.getLocationOnScreen(mTmpIntOffset);
4181            mViewToScreenMatrix.postTranslate(mTmpIntOffset[0], mTmpIntOffset[1]);
4182            builder.setMatrix(mViewToScreenMatrix);
4183
4184            final float viewportToContentHorizontalOffset =
4185                    mTextView.viewportToContentHorizontalOffset();
4186            final float viewportToContentVerticalOffset =
4187                    mTextView.viewportToContentVerticalOffset();
4188
4189            final CharSequence text = mTextView.getText();
4190            if (text instanceof Spannable) {
4191                final Spannable sp = (Spannable) text;
4192                int composingTextStart = EditableInputConnection.getComposingSpanStart(sp);
4193                int composingTextEnd = EditableInputConnection.getComposingSpanEnd(sp);
4194                if (composingTextEnd < composingTextStart) {
4195                    final int temp = composingTextEnd;
4196                    composingTextEnd = composingTextStart;
4197                    composingTextStart = temp;
4198                }
4199                final boolean hasComposingText =
4200                        (0 <= composingTextStart) && (composingTextStart < composingTextEnd);
4201                if (hasComposingText) {
4202                    final CharSequence composingText = text.subSequence(composingTextStart,
4203                            composingTextEnd);
4204                    builder.setComposingText(composingTextStart, composingText);
4205                    mTextView.populateCharacterBounds(builder, composingTextStart,
4206                            composingTextEnd, viewportToContentHorizontalOffset,
4207                            viewportToContentVerticalOffset);
4208                }
4209            }
4210
4211            // Treat selectionStart as the insertion point.
4212            if (0 <= selectionStart) {
4213                final int offset = selectionStart;
4214                final int line = layout.getLineForOffset(offset);
4215                final float insertionMarkerX = layout.getPrimaryHorizontal(offset)
4216                        + viewportToContentHorizontalOffset;
4217                final float insertionMarkerTop = layout.getLineTop(line)
4218                        + viewportToContentVerticalOffset;
4219                final float insertionMarkerBaseline = layout.getLineBaseline(line)
4220                        + viewportToContentVerticalOffset;
4221                final float insertionMarkerBottom = layout.getLineBottomWithoutSpacing(line)
4222                        + viewportToContentVerticalOffset;
4223                final boolean isTopVisible = mTextView
4224                        .isPositionVisible(insertionMarkerX, insertionMarkerTop);
4225                final boolean isBottomVisible = mTextView
4226                        .isPositionVisible(insertionMarkerX, insertionMarkerBottom);
4227                int insertionMarkerFlags = 0;
4228                if (isTopVisible || isBottomVisible) {
4229                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
4230                }
4231                if (!isTopVisible || !isBottomVisible) {
4232                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
4233                }
4234                if (layout.isRtlCharAt(offset)) {
4235                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_IS_RTL;
4236                }
4237                builder.setInsertionMarkerLocation(insertionMarkerX, insertionMarkerTop,
4238                        insertionMarkerBaseline, insertionMarkerBottom, insertionMarkerFlags);
4239            }
4240
4241            imm.updateCursorAnchorInfo(mTextView, builder.build());
4242        }
4243    }
4244
4245    @VisibleForTesting
4246    public abstract class HandleView extends View implements TextViewPositionListener {
4247        protected Drawable mDrawable;
4248        protected Drawable mDrawableLtr;
4249        protected Drawable mDrawableRtl;
4250        private final PopupWindow mContainer;
4251        // Position with respect to the parent TextView
4252        private int mPositionX, mPositionY;
4253        private boolean mIsDragging;
4254        // Offset from touch position to mPosition
4255        private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
4256        protected int mHotspotX;
4257        protected int mHorizontalGravity;
4258        // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
4259        private float mTouchOffsetY;
4260        // Where the touch position should be on the handle to ensure a maximum cursor visibility
4261        private float mIdealVerticalOffset;
4262        // Parent's (TextView) previous position in window
4263        private int mLastParentX, mLastParentY;
4264        // Parent's (TextView) previous position on screen
4265        private int mLastParentXOnScreen, mLastParentYOnScreen;
4266        // Previous text character offset
4267        protected int mPreviousOffset = -1;
4268        // Previous text character offset
4269        private boolean mPositionHasChanged = true;
4270        // Minimum touch target size for handles
4271        private int mMinSize;
4272        // Indicates the line of text that the handle is on.
4273        protected int mPrevLine = UNSET_LINE;
4274        // Indicates the line of text that the user was touching. This can differ from mPrevLine
4275        // when selecting text when the handles jump to the end / start of words which may be on
4276        // a different line.
4277        protected int mPreviousLineTouched = UNSET_LINE;
4278
4279        private HandleView(Drawable drawableLtr, Drawable drawableRtl, final int id) {
4280            super(mTextView.getContext());
4281            setId(id);
4282            mContainer = new PopupWindow(mTextView.getContext(), null,
4283                    com.android.internal.R.attr.textSelectHandleWindowStyle);
4284            mContainer.setSplitTouchEnabled(true);
4285            mContainer.setClippingEnabled(false);
4286            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
4287            mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
4288            mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
4289            mContainer.setContentView(this);
4290
4291            mDrawableLtr = drawableLtr;
4292            mDrawableRtl = drawableRtl;
4293            mMinSize = mTextView.getContext().getResources().getDimensionPixelSize(
4294                    com.android.internal.R.dimen.text_handle_min_size);
4295
4296            updateDrawable();
4297
4298            final int handleHeight = getPreferredHeight();
4299            mTouchOffsetY = -0.3f * handleHeight;
4300            mIdealVerticalOffset = 0.7f * handleHeight;
4301        }
4302
4303        public float getIdealVerticalOffset() {
4304            return mIdealVerticalOffset;
4305        }
4306
4307        protected void updateDrawable() {
4308            if (mIsDragging) {
4309                // Don't update drawable during dragging.
4310                return;
4311            }
4312            final Layout layout = mTextView.getLayout();
4313            if (layout == null) {
4314                return;
4315            }
4316            final int offset = getCurrentCursorOffset();
4317            final boolean isRtlCharAtOffset = isAtRtlRun(layout, offset);
4318            final Drawable oldDrawable = mDrawable;
4319            mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
4320            mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
4321            mHorizontalGravity = getHorizontalGravity(isRtlCharAtOffset);
4322            if (oldDrawable != mDrawable && isShowing()) {
4323                // Update popup window position.
4324                mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX
4325                        - getHorizontalOffset() + getCursorOffset();
4326                mPositionX += mTextView.viewportToContentHorizontalOffset();
4327                mPositionHasChanged = true;
4328                updatePosition(mLastParentX, mLastParentY, false, false);
4329                postInvalidate();
4330            }
4331        }
4332
4333        protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
4334        protected abstract int getHorizontalGravity(boolean isRtlRun);
4335
4336        // Touch-up filter: number of previous positions remembered
4337        private static final int HISTORY_SIZE = 5;
4338        private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
4339        private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
4340        private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
4341        private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
4342        private int mPreviousOffsetIndex = 0;
4343        private int mNumberPreviousOffsets = 0;
4344
4345        private void startTouchUpFilter(int offset) {
4346            mNumberPreviousOffsets = 0;
4347            addPositionToTouchUpFilter(offset);
4348        }
4349
4350        private void addPositionToTouchUpFilter(int offset) {
4351            mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
4352            mPreviousOffsets[mPreviousOffsetIndex] = offset;
4353            mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
4354            mNumberPreviousOffsets++;
4355        }
4356
4357        private void filterOnTouchUp(boolean fromTouchScreen) {
4358            final long now = SystemClock.uptimeMillis();
4359            int i = 0;
4360            int index = mPreviousOffsetIndex;
4361            final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
4362            while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
4363                i++;
4364                index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
4365            }
4366
4367            if (i > 0 && i < iMax
4368                    && (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
4369                positionAtCursorOffset(mPreviousOffsets[index], false, fromTouchScreen);
4370            }
4371        }
4372
4373        public boolean offsetHasBeenChanged() {
4374            return mNumberPreviousOffsets > 1;
4375        }
4376
4377        @Override
4378        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
4379            setMeasuredDimension(getPreferredWidth(), getPreferredHeight());
4380        }
4381
4382        @Override
4383        public void invalidate() {
4384            super.invalidate();
4385            if (isShowing()) {
4386                positionAtCursorOffset(getCurrentCursorOffset(), true, false);
4387            }
4388        };
4389
4390        private int getPreferredWidth() {
4391            return Math.max(mDrawable.getIntrinsicWidth(), mMinSize);
4392        }
4393
4394        private int getPreferredHeight() {
4395            return Math.max(mDrawable.getIntrinsicHeight(), mMinSize);
4396        }
4397
4398        public void show() {
4399            if (isShowing()) return;
4400
4401            getPositionListener().addSubscriber(this, true /* local position may change */);
4402
4403            // Make sure the offset is always considered new, even when focusing at same position
4404            mPreviousOffset = -1;
4405            positionAtCursorOffset(getCurrentCursorOffset(), false, false);
4406        }
4407
4408        protected void dismiss() {
4409            mIsDragging = false;
4410            mContainer.dismiss();
4411            onDetached();
4412        }
4413
4414        public void hide() {
4415            dismiss();
4416
4417            getPositionListener().removeSubscriber(this);
4418        }
4419
4420        public boolean isShowing() {
4421            return mContainer.isShowing();
4422        }
4423
4424        private boolean isVisible() {
4425            // Always show a dragging handle.
4426            if (mIsDragging) {
4427                return true;
4428            }
4429
4430            if (mTextView.isInBatchEditMode()) {
4431                return false;
4432            }
4433
4434            return mTextView.isPositionVisible(
4435                    mPositionX + mHotspotX + getHorizontalOffset(), mPositionY);
4436        }
4437
4438        public abstract int getCurrentCursorOffset();
4439
4440        protected abstract void updateSelection(int offset);
4441
4442        protected abstract void updatePosition(float x, float y, boolean fromTouchScreen);
4443
4444        @MagnifierHandleTrigger
4445        protected abstract int getMagnifierHandleTrigger();
4446
4447        protected boolean isAtRtlRun(@NonNull Layout layout, int offset) {
4448            return layout.isRtlCharAt(offset);
4449        }
4450
4451        @VisibleForTesting
4452        public float getHorizontal(@NonNull Layout layout, int offset) {
4453            return layout.getPrimaryHorizontal(offset);
4454        }
4455
4456        protected int getOffsetAtCoordinate(@NonNull Layout layout, int line, float x) {
4457            return mTextView.getOffsetAtCoordinate(line, x);
4458        }
4459
4460        /**
4461         * @param offset Cursor offset. Must be in [-1, length].
4462         * @param forceUpdatePosition whether to force update the position.  This should be true
4463         * when If the parent has been scrolled, for example.
4464         * @param fromTouchScreen {@code true} if the cursor is moved with motion events from the
4465         * touch screen.
4466         */
4467        protected void positionAtCursorOffset(int offset, boolean forceUpdatePosition,
4468                boolean fromTouchScreen) {
4469            // A HandleView relies on the layout, which may be nulled by external methods
4470            Layout layout = mTextView.getLayout();
4471            if (layout == null) {
4472                // Will update controllers' state, hiding them and stopping selection mode if needed
4473                prepareCursorControllers();
4474                return;
4475            }
4476            layout = mTextView.getLayout();
4477
4478            boolean offsetChanged = offset != mPreviousOffset;
4479            if (offsetChanged || forceUpdatePosition) {
4480                if (offsetChanged) {
4481                    updateSelection(offset);
4482                    if (fromTouchScreen && mHapticTextHandleEnabled) {
4483                        mTextView.performHapticFeedback(HapticFeedbackConstants.TEXT_HANDLE_MOVE);
4484                    }
4485                    addPositionToTouchUpFilter(offset);
4486                }
4487                final int line = layout.getLineForOffset(offset);
4488                mPrevLine = line;
4489
4490                mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX
4491                        - getHorizontalOffset() + getCursorOffset();
4492                mPositionY = layout.getLineBottomWithoutSpacing(line);
4493
4494                // Take TextView's padding and scroll into account.
4495                mPositionX += mTextView.viewportToContentHorizontalOffset();
4496                mPositionY += mTextView.viewportToContentVerticalOffset();
4497
4498                mPreviousOffset = offset;
4499                mPositionHasChanged = true;
4500            }
4501        }
4502
4503        /**
4504         * Return the clamped horizontal position for the cursor.
4505         *
4506         * @param layout Text layout.
4507         * @param offset Character offset for the cursor.
4508         * @return The clamped horizontal position for the cursor.
4509         */
4510        int getCursorHorizontalPosition(Layout layout, int offset) {
4511            return (int) (getHorizontal(layout, offset) - 0.5f);
4512        }
4513
4514        @Override
4515        public void updatePosition(int parentPositionX, int parentPositionY,
4516                boolean parentPositionChanged, boolean parentScrolled) {
4517            positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled, false);
4518            if (parentPositionChanged || mPositionHasChanged) {
4519                if (mIsDragging) {
4520                    // Update touchToWindow offset in case of parent scrolling while dragging
4521                    if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
4522                        mTouchToWindowOffsetX += parentPositionX - mLastParentX;
4523                        mTouchToWindowOffsetY += parentPositionY - mLastParentY;
4524                        mLastParentX = parentPositionX;
4525                        mLastParentY = parentPositionY;
4526                    }
4527
4528                    onHandleMoved();
4529                }
4530
4531                if (isVisible()) {
4532                    // Transform to the window coordinates to follow the view tranformation.
4533                    final int[] pts = { mPositionX + mHotspotX + getHorizontalOffset(), mPositionY};
4534                    mTextView.transformFromViewToWindowSpace(pts);
4535                    pts[0] -= mHotspotX + getHorizontalOffset();
4536
4537                    if (isShowing()) {
4538                        mContainer.update(pts[0], pts[1], -1, -1);
4539                    } else {
4540                        mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY, pts[0], pts[1]);
4541                    }
4542                } else {
4543                    if (isShowing()) {
4544                        dismiss();
4545                    }
4546                }
4547
4548                mPositionHasChanged = false;
4549            }
4550        }
4551
4552        @Override
4553        protected void onDraw(Canvas c) {
4554            final int drawWidth = mDrawable.getIntrinsicWidth();
4555            final int left = getHorizontalOffset();
4556
4557            mDrawable.setBounds(left, 0, left + drawWidth, mDrawable.getIntrinsicHeight());
4558            mDrawable.draw(c);
4559        }
4560
4561        private int getHorizontalOffset() {
4562            final int width = getPreferredWidth();
4563            final int drawWidth = mDrawable.getIntrinsicWidth();
4564            final int left;
4565            switch (mHorizontalGravity) {
4566                case Gravity.LEFT:
4567                    left = 0;
4568                    break;
4569                default:
4570                case Gravity.CENTER:
4571                    left = (width - drawWidth) / 2;
4572                    break;
4573                case Gravity.RIGHT:
4574                    left = width - drawWidth;
4575                    break;
4576            }
4577            return left;
4578        }
4579
4580        protected int getCursorOffset() {
4581            return 0;
4582        }
4583
4584        protected final void showMagnifier() {
4585            if (mMagnifier == null) {
4586                return;
4587            }
4588
4589            final int trigger = getMagnifierHandleTrigger();
4590            final int offset;
4591            switch (trigger) {
4592                case MagnifierHandleTrigger.INSERTION: // Fall through.
4593                case MagnifierHandleTrigger.SELECTION_START:
4594                    offset = mTextView.getSelectionStart();
4595                    break;
4596                case MagnifierHandleTrigger.SELECTION_END:
4597                    offset = mTextView.getSelectionEnd();
4598                    break;
4599                default:
4600                    offset = -1;
4601                    break;
4602            }
4603
4604            if (offset == -1) {
4605                dismissMagnifier();
4606            }
4607
4608            final Layout layout = mTextView.getLayout();
4609            final int lineNumber = layout.getLineForOffset(offset);
4610            // Horizontally snap to character offset.
4611            final float xPosInView = getHorizontal(mTextView.getLayout(), offset)
4612                    + mTextView.getTotalPaddingLeft() - mTextView.getScrollX();
4613            // Vertically snap to middle of current line.
4614            final float yPosInView = (mTextView.getLayout().getLineTop(lineNumber)
4615                    + mTextView.getLayout().getLineBottom(lineNumber)) / 2.0f
4616                    + mTextView.getTotalPaddingTop() - mTextView.getScrollY();
4617
4618            suspendBlink();
4619            mMagnifier.show(xPosInView, yPosInView);
4620        }
4621
4622        protected final void dismissMagnifier() {
4623            if (mMagnifier != null) {
4624                mMagnifier.dismiss();
4625                resumeBlink();
4626            }
4627        }
4628
4629        @Override
4630        public boolean onTouchEvent(MotionEvent ev) {
4631            updateFloatingToolbarVisibility(ev);
4632
4633            switch (ev.getActionMasked()) {
4634                case MotionEvent.ACTION_DOWN: {
4635                    startTouchUpFilter(getCurrentCursorOffset());
4636
4637                    final PositionListener positionListener = getPositionListener();
4638                    mLastParentX = positionListener.getPositionX();
4639                    mLastParentY = positionListener.getPositionY();
4640                    mLastParentXOnScreen = positionListener.getPositionXOnScreen();
4641                    mLastParentYOnScreen = positionListener.getPositionYOnScreen();
4642
4643                    final float xInWindow = ev.getRawX() - mLastParentXOnScreen + mLastParentX;
4644                    final float yInWindow = ev.getRawY() - mLastParentYOnScreen + mLastParentY;
4645                    mTouchToWindowOffsetX = xInWindow - mPositionX;
4646                    mTouchToWindowOffsetY = yInWindow - mPositionY;
4647
4648                    mIsDragging = true;
4649                    mPreviousLineTouched = UNSET_LINE;
4650                    break;
4651                }
4652
4653                case MotionEvent.ACTION_MOVE: {
4654                    final float xInWindow = ev.getRawX() - mLastParentXOnScreen + mLastParentX;
4655                    final float yInWindow = ev.getRawY() - mLastParentYOnScreen + mLastParentY;
4656
4657                    // Vertical hysteresis: vertical down movement tends to snap to ideal offset
4658                    final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
4659                    final float currentVerticalOffset = yInWindow - mPositionY - mLastParentY;
4660                    float newVerticalOffset;
4661                    if (previousVerticalOffset < mIdealVerticalOffset) {
4662                        newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
4663                        newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
4664                    } else {
4665                        newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
4666                        newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
4667                    }
4668                    mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
4669
4670                    final float newPosX =
4671                            xInWindow - mTouchToWindowOffsetX + mHotspotX + getHorizontalOffset();
4672                    final float newPosY = yInWindow - mTouchToWindowOffsetY + mTouchOffsetY;
4673
4674                    updatePosition(newPosX, newPosY,
4675                            ev.isFromSource(InputDevice.SOURCE_TOUCHSCREEN));
4676                    break;
4677                }
4678
4679                case MotionEvent.ACTION_UP:
4680                    filterOnTouchUp(ev.isFromSource(InputDevice.SOURCE_TOUCHSCREEN));
4681                    // Fall through.
4682                case MotionEvent.ACTION_CANCEL:
4683                    mIsDragging = false;
4684                    updateDrawable();
4685                    break;
4686            }
4687            return true;
4688        }
4689
4690        public boolean isDragging() {
4691            return mIsDragging;
4692        }
4693
4694        void onHandleMoved() {}
4695
4696        public void onDetached() {}
4697    }
4698
4699    private class InsertionHandleView extends HandleView {
4700        private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
4701        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
4702
4703        // Used to detect taps on the insertion handle, which will affect the insertion action mode
4704        private float mDownPositionX, mDownPositionY;
4705        private Runnable mHider;
4706
4707        public InsertionHandleView(Drawable drawable) {
4708            super(drawable, drawable, com.android.internal.R.id.insertion_handle);
4709        }
4710
4711        @Override
4712        public void show() {
4713            super.show();
4714
4715            final long durationSinceCutOrCopy =
4716                    SystemClock.uptimeMillis() - TextView.sLastCutCopyOrTextChangedTime;
4717
4718            // Cancel the single tap delayed runnable.
4719            if (mInsertionActionModeRunnable != null
4720                    && ((mTapState == TAP_STATE_DOUBLE_TAP)
4721                            || (mTapState == TAP_STATE_TRIPLE_CLICK)
4722                            || isCursorInsideEasyCorrectionSpan())) {
4723                mTextView.removeCallbacks(mInsertionActionModeRunnable);
4724            }
4725
4726            // Prepare and schedule the single tap runnable to run exactly after the double tap
4727            // timeout has passed.
4728            if ((mTapState != TAP_STATE_DOUBLE_TAP) && (mTapState != TAP_STATE_TRIPLE_CLICK)
4729                    && !isCursorInsideEasyCorrectionSpan()
4730                    && (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION)) {
4731                if (mTextActionMode == null) {
4732                    if (mInsertionActionModeRunnable == null) {
4733                        mInsertionActionModeRunnable = new Runnable() {
4734                            @Override
4735                            public void run() {
4736                                startInsertionActionMode();
4737                            }
4738                        };
4739                    }
4740                    mTextView.postDelayed(
4741                            mInsertionActionModeRunnable,
4742                            ViewConfiguration.getDoubleTapTimeout() + 1);
4743                }
4744
4745            }
4746
4747            hideAfterDelay();
4748        }
4749
4750        private void hideAfterDelay() {
4751            if (mHider == null) {
4752                mHider = new Runnable() {
4753                    public void run() {
4754                        hide();
4755                    }
4756                };
4757            } else {
4758                removeHiderCallback();
4759            }
4760            mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
4761        }
4762
4763        private void removeHiderCallback() {
4764            if (mHider != null) {
4765                mTextView.removeCallbacks(mHider);
4766            }
4767        }
4768
4769        @Override
4770        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4771            return drawable.getIntrinsicWidth() / 2;
4772        }
4773
4774        @Override
4775        protected int getHorizontalGravity(boolean isRtlRun) {
4776            return Gravity.CENTER_HORIZONTAL;
4777        }
4778
4779        @Override
4780        protected int getCursorOffset() {
4781            int offset = super.getCursorOffset();
4782            if (mDrawableForCursor != null) {
4783                mDrawableForCursor.getPadding(mTempRect);
4784                offset += (mDrawableForCursor.getIntrinsicWidth()
4785                           - mTempRect.left - mTempRect.right) / 2;
4786            }
4787            return offset;
4788        }
4789
4790        @Override
4791        int getCursorHorizontalPosition(Layout layout, int offset) {
4792            if (mDrawableForCursor != null) {
4793                final float horizontal = getHorizontal(layout, offset);
4794                return clampHorizontalPosition(mDrawableForCursor, horizontal) + mTempRect.left;
4795            }
4796            return super.getCursorHorizontalPosition(layout, offset);
4797        }
4798
4799        @Override
4800        public boolean onTouchEvent(MotionEvent ev) {
4801            final boolean result = super.onTouchEvent(ev);
4802
4803            switch (ev.getActionMasked()) {
4804                case MotionEvent.ACTION_DOWN:
4805                    mDownPositionX = ev.getRawX();
4806                    mDownPositionY = ev.getRawY();
4807                    showMagnifier();
4808                    break;
4809
4810                case MotionEvent.ACTION_MOVE:
4811                    showMagnifier();
4812                    break;
4813
4814                case MotionEvent.ACTION_UP:
4815                    if (!offsetHasBeenChanged()) {
4816                        final float deltaX = mDownPositionX - ev.getRawX();
4817                        final float deltaY = mDownPositionY - ev.getRawY();
4818                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
4819
4820                        final ViewConfiguration viewConfiguration = ViewConfiguration.get(
4821                                mTextView.getContext());
4822                        final int touchSlop = viewConfiguration.getScaledTouchSlop();
4823
4824                        if (distanceSquared < touchSlop * touchSlop) {
4825                            // Tapping on the handle toggles the insertion action mode.
4826                            if (mTextActionMode != null) {
4827                                stopTextActionMode();
4828                            } else {
4829                                startInsertionActionMode();
4830                            }
4831                        }
4832                    } else {
4833                        if (mTextActionMode != null) {
4834                            mTextActionMode.invalidateContentRect();
4835                        }
4836                    }
4837                    // Fall through.
4838                case MotionEvent.ACTION_CANCEL:
4839                    hideAfterDelay();
4840                    dismissMagnifier();
4841                    break;
4842
4843                default:
4844                    break;
4845            }
4846
4847            return result;
4848        }
4849
4850        @Override
4851        public int getCurrentCursorOffset() {
4852            return mTextView.getSelectionStart();
4853        }
4854
4855        @Override
4856        public void updateSelection(int offset) {
4857            Selection.setSelection((Spannable) mTextView.getText(), offset);
4858        }
4859
4860        @Override
4861        protected void updatePosition(float x, float y, boolean fromTouchScreen) {
4862            Layout layout = mTextView.getLayout();
4863            int offset;
4864            if (layout != null) {
4865                if (mPreviousLineTouched == UNSET_LINE) {
4866                    mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
4867                }
4868                int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
4869                offset = getOffsetAtCoordinate(layout, currLine, x);
4870                mPreviousLineTouched = currLine;
4871            } else {
4872                offset = -1;
4873            }
4874            positionAtCursorOffset(offset, false, fromTouchScreen);
4875            if (mTextActionMode != null) {
4876                invalidateActionMode();
4877            }
4878        }
4879
4880        @Override
4881        void onHandleMoved() {
4882            super.onHandleMoved();
4883            removeHiderCallback();
4884        }
4885
4886        @Override
4887        public void onDetached() {
4888            super.onDetached();
4889            removeHiderCallback();
4890        }
4891
4892        @Override
4893        @MagnifierHandleTrigger
4894        protected int getMagnifierHandleTrigger() {
4895            return MagnifierHandleTrigger.INSERTION;
4896        }
4897    }
4898
4899    @Retention(RetentionPolicy.SOURCE)
4900    @IntDef({HANDLE_TYPE_SELECTION_START, HANDLE_TYPE_SELECTION_END})
4901    public @interface HandleType {}
4902    public static final int HANDLE_TYPE_SELECTION_START = 0;
4903    public static final int HANDLE_TYPE_SELECTION_END = 1;
4904
4905    /** For selection handles */
4906    @VisibleForTesting
4907    public final class SelectionHandleView extends HandleView {
4908        // Indicates the handle type, selection start (HANDLE_TYPE_SELECTION_START) or selection
4909        // end (HANDLE_TYPE_SELECTION_END).
4910        @HandleType
4911        private final int mHandleType;
4912        // Indicates whether the cursor is making adjustments within a word.
4913        private boolean mInWord = false;
4914        // Difference between touch position and word boundary position.
4915        private float mTouchWordDelta;
4916        // X value of the previous updatePosition call.
4917        private float mPrevX;
4918        // Indicates if the handle has moved a boundary between LTR and RTL text.
4919        private boolean mLanguageDirectionChanged = false;
4920        // Distance from edge of horizontally scrolling text view
4921        // to use to switch to character mode.
4922        private final float mTextViewEdgeSlop;
4923        // Used to save text view location.
4924        private final int[] mTextViewLocation = new int[2];
4925
4926        public SelectionHandleView(Drawable drawableLtr, Drawable drawableRtl, int id,
4927                @HandleType int handleType) {
4928            super(drawableLtr, drawableRtl, id);
4929            mHandleType = handleType;
4930            ViewConfiguration viewConfiguration = ViewConfiguration.get(mTextView.getContext());
4931            mTextViewEdgeSlop = viewConfiguration.getScaledTouchSlop() * 4;
4932        }
4933
4934        private boolean isStartHandle() {
4935            return mHandleType == HANDLE_TYPE_SELECTION_START;
4936        }
4937
4938        @Override
4939        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4940            if (isRtlRun == isStartHandle()) {
4941                return drawable.getIntrinsicWidth() / 4;
4942            } else {
4943                return (drawable.getIntrinsicWidth() * 3) / 4;
4944            }
4945        }
4946
4947        @Override
4948        protected int getHorizontalGravity(boolean isRtlRun) {
4949            return (isRtlRun == isStartHandle()) ? Gravity.LEFT : Gravity.RIGHT;
4950        }
4951
4952        @Override
4953        public int getCurrentCursorOffset() {
4954            return isStartHandle() ? mTextView.getSelectionStart() : mTextView.getSelectionEnd();
4955        }
4956
4957        @Override
4958        protected void updateSelection(int offset) {
4959            if (isStartHandle()) {
4960                Selection.setSelection((Spannable) mTextView.getText(), offset,
4961                        mTextView.getSelectionEnd());
4962            } else {
4963                Selection.setSelection((Spannable) mTextView.getText(),
4964                        mTextView.getSelectionStart(), offset);
4965            }
4966            updateDrawable();
4967            if (mTextActionMode != null) {
4968                invalidateActionMode();
4969            }
4970        }
4971
4972        @Override
4973        protected void updatePosition(float x, float y, boolean fromTouchScreen) {
4974            final Layout layout = mTextView.getLayout();
4975            if (layout == null) {
4976                // HandleView will deal appropriately in positionAtCursorOffset when
4977                // layout is null.
4978                positionAndAdjustForCrossingHandles(mTextView.getOffsetForPosition(x, y),
4979                        fromTouchScreen);
4980                return;
4981            }
4982
4983            if (mPreviousLineTouched == UNSET_LINE) {
4984                mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
4985            }
4986
4987            boolean positionCursor = false;
4988            final int anotherHandleOffset =
4989                    isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart();
4990            int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
4991            int initialOffset = getOffsetAtCoordinate(layout, currLine, x);
4992
4993            if (isStartHandle() && initialOffset >= anotherHandleOffset
4994                    || !isStartHandle() && initialOffset <= anotherHandleOffset) {
4995                // Handles have crossed, bound it to the first selected line and
4996                // adjust by word / char as normal.
4997                currLine = layout.getLineForOffset(anotherHandleOffset);
4998                initialOffset = getOffsetAtCoordinate(layout, currLine, x);
4999            }
5000
5001            int offset = initialOffset;
5002            final int wordEnd = getWordEnd(offset);
5003            final int wordStart = getWordStart(offset);
5004
5005            if (mPrevX == UNSET_X_VALUE) {
5006                mPrevX = x;
5007            }
5008
5009            final int currentOffset = getCurrentCursorOffset();
5010            final boolean rtlAtCurrentOffset = isAtRtlRun(layout, currentOffset);
5011            final boolean atRtl = isAtRtlRun(layout, offset);
5012            final boolean isLvlBoundary = layout.isLevelBoundary(offset);
5013
5014            // We can't determine if the user is expanding or shrinking the selection if they're
5015            // on a bi-di boundary, so until they've moved past the boundary we'll just place
5016            // the cursor at the current position.
5017            if (isLvlBoundary || (rtlAtCurrentOffset && !atRtl) || (!rtlAtCurrentOffset && atRtl)) {
5018                // We're on a boundary or this is the first direction change -- just update
5019                // to the current position.
5020                mLanguageDirectionChanged = true;
5021                mTouchWordDelta = 0.0f;
5022                positionAndAdjustForCrossingHandles(offset, fromTouchScreen);
5023                return;
5024            } else if (mLanguageDirectionChanged && !isLvlBoundary) {
5025                // We've just moved past the boundary so update the position. After this we can
5026                // figure out if the user is expanding or shrinking to go by word or character.
5027                positionAndAdjustForCrossingHandles(offset, fromTouchScreen);
5028                mTouchWordDelta = 0.0f;
5029                mLanguageDirectionChanged = false;
5030                return;
5031            }
5032
5033            boolean isExpanding;
5034            final float xDiff = x - mPrevX;
5035            if (isStartHandle()) {
5036                isExpanding = currLine < mPreviousLineTouched;
5037            } else {
5038                isExpanding = currLine > mPreviousLineTouched;
5039            }
5040            if (atRtl == isStartHandle()) {
5041                isExpanding |= xDiff > 0;
5042            } else {
5043                isExpanding |= xDiff < 0;
5044            }
5045
5046            if (mTextView.getHorizontallyScrolling()) {
5047                if (positionNearEdgeOfScrollingView(x, atRtl)
5048                        && ((isStartHandle() && mTextView.getScrollX() != 0)
5049                                || (!isStartHandle()
5050                                        && mTextView.canScrollHorizontally(atRtl ? -1 : 1)))
5051                        && ((isExpanding && ((isStartHandle() && offset < currentOffset)
5052                                || (!isStartHandle() && offset > currentOffset)))
5053                                        || !isExpanding)) {
5054                    // If we're expanding ensure that the offset is actually expanding compared to
5055                    // the current offset, if the handle snapped to the word, the finger position
5056                    // may be out of sync and we don't want the selection to jump back.
5057                    mTouchWordDelta = 0.0f;
5058                    final int nextOffset = (atRtl == isStartHandle())
5059                            ? layout.getOffsetToRightOf(mPreviousOffset)
5060                            : layout.getOffsetToLeftOf(mPreviousOffset);
5061                    positionAndAdjustForCrossingHandles(nextOffset, fromTouchScreen);
5062                    return;
5063                }
5064            }
5065
5066            if (isExpanding) {
5067                // User is increasing the selection.
5068                int wordBoundary = isStartHandle() ? wordStart : wordEnd;
5069                final boolean snapToWord = (!mInWord
5070                        || (isStartHandle() ? currLine < mPrevLine : currLine > mPrevLine))
5071                                && atRtl == isAtRtlRun(layout, wordBoundary);
5072                if (snapToWord) {
5073                    // Sometimes words can be broken across lines (Chinese, hyphenation).
5074                    // We still snap to the word boundary but we only use the letters on the
5075                    // current line to determine if the user is far enough into the word to snap.
5076                    if (layout.getLineForOffset(wordBoundary) != currLine) {
5077                        wordBoundary = isStartHandle()
5078                                ? layout.getLineStart(currLine) : layout.getLineEnd(currLine);
5079                    }
5080                    final int offsetThresholdToSnap = isStartHandle()
5081                            ? wordEnd - ((wordEnd - wordBoundary) / 2)
5082                            : wordStart + ((wordBoundary - wordStart) / 2);
5083                    if (isStartHandle()
5084                            && (offset <= offsetThresholdToSnap || currLine < mPrevLine)) {
5085                        // User is far enough into the word or on a different line so we expand by
5086                        // word.
5087                        offset = wordStart;
5088                    } else if (!isStartHandle()
5089                            && (offset >= offsetThresholdToSnap || currLine > mPrevLine)) {
5090                        // User is far enough into the word or on a different line so we expand by
5091                        // word.
5092                        offset = wordEnd;
5093                    } else {
5094                        offset = mPreviousOffset;
5095                    }
5096                }
5097                if ((isStartHandle() && offset < initialOffset)
5098                        || (!isStartHandle() && offset > initialOffset)) {
5099                    final float adjustedX = getHorizontal(layout, offset);
5100                    mTouchWordDelta =
5101                            mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
5102                } else {
5103                    mTouchWordDelta = 0.0f;
5104                }
5105                positionCursor = true;
5106            } else {
5107                final int adjustedOffset =
5108                        getOffsetAtCoordinate(layout, currLine, x - mTouchWordDelta);
5109                final boolean shrinking = isStartHandle()
5110                        ? adjustedOffset > mPreviousOffset || currLine > mPrevLine
5111                        : adjustedOffset < mPreviousOffset || currLine < mPrevLine;
5112                if (shrinking) {
5113                    // User is shrinking the selection.
5114                    if (currLine != mPrevLine) {
5115                        // We're on a different line, so we'll snap to word boundaries.
5116                        offset = isStartHandle() ? wordStart : wordEnd;
5117                        if ((isStartHandle() && offset < initialOffset)
5118                                || (!isStartHandle() && offset > initialOffset)) {
5119                            final float adjustedX = getHorizontal(layout, offset);
5120                            mTouchWordDelta =
5121                                    mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
5122                        } else {
5123                            mTouchWordDelta = 0.0f;
5124                        }
5125                    } else {
5126                        offset = adjustedOffset;
5127                    }
5128                    positionCursor = true;
5129                } else if ((isStartHandle() && adjustedOffset < mPreviousOffset)
5130                        || (!isStartHandle() && adjustedOffset > mPreviousOffset)) {
5131                    // Handle has jumped to the word boundary, and the user is moving
5132                    // their finger towards the handle, the delta should be updated.
5133                    mTouchWordDelta = mTextView.convertToLocalHorizontalCoordinate(x)
5134                            - getHorizontal(layout, mPreviousOffset);
5135                }
5136            }
5137
5138            if (positionCursor) {
5139                mPreviousLineTouched = currLine;
5140                positionAndAdjustForCrossingHandles(offset, fromTouchScreen);
5141            }
5142            mPrevX = x;
5143        }
5144
5145        @Override
5146        protected void positionAtCursorOffset(int offset, boolean forceUpdatePosition,
5147                boolean fromTouchScreen) {
5148            super.positionAtCursorOffset(offset, forceUpdatePosition, fromTouchScreen);
5149            mInWord = (offset != -1) && !getWordIteratorWithText().isBoundary(offset);
5150        }
5151
5152        @Override
5153        public boolean onTouchEvent(MotionEvent event) {
5154            boolean superResult = super.onTouchEvent(event);
5155
5156            switch (event.getActionMasked()) {
5157                case MotionEvent.ACTION_DOWN:
5158                    // Reset the touch word offset and x value when the user
5159                    // re-engages the handle.
5160                    mTouchWordDelta = 0.0f;
5161                    mPrevX = UNSET_X_VALUE;
5162                    showMagnifier();
5163                    break;
5164
5165                case MotionEvent.ACTION_MOVE:
5166                    showMagnifier();
5167                    break;
5168
5169                case MotionEvent.ACTION_UP:
5170                case MotionEvent.ACTION_CANCEL:
5171                    dismissMagnifier();
5172                    break;
5173            }
5174
5175            return superResult;
5176        }
5177
5178        private void positionAndAdjustForCrossingHandles(int offset, boolean fromTouchScreen) {
5179            final int anotherHandleOffset =
5180                    isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart();
5181            if ((isStartHandle() && offset >= anotherHandleOffset)
5182                    || (!isStartHandle() && offset <= anotherHandleOffset)) {
5183                mTouchWordDelta = 0.0f;
5184                final Layout layout = mTextView.getLayout();
5185                if (layout != null && offset != anotherHandleOffset) {
5186                    final float horiz = getHorizontal(layout, offset);
5187                    final float anotherHandleHoriz = getHorizontal(layout, anotherHandleOffset,
5188                            !isStartHandle());
5189                    final float currentHoriz = getHorizontal(layout, mPreviousOffset);
5190                    if (currentHoriz < anotherHandleHoriz && horiz < anotherHandleHoriz
5191                            || currentHoriz > anotherHandleHoriz && horiz > anotherHandleHoriz) {
5192                        // This handle passes another one as it crossed a direction boundary.
5193                        // Don't minimize the selection, but keep the handle at the run boundary.
5194                        final int currentOffset = getCurrentCursorOffset();
5195                        final int offsetToGetRunRange = isStartHandle()
5196                                ? currentOffset : Math.max(currentOffset - 1, 0);
5197                        final long range = layout.getRunRange(offsetToGetRunRange);
5198                        if (isStartHandle()) {
5199                            offset = TextUtils.unpackRangeStartFromLong(range);
5200                        } else {
5201                            offset = TextUtils.unpackRangeEndFromLong(range);
5202                        }
5203                        positionAtCursorOffset(offset, false, fromTouchScreen);
5204                        return;
5205                    }
5206                }
5207                // Handles can not cross and selection is at least one character.
5208                offset = getNextCursorOffset(anotherHandleOffset, !isStartHandle());
5209            }
5210            positionAtCursorOffset(offset, false, fromTouchScreen);
5211        }
5212
5213        private boolean positionNearEdgeOfScrollingView(float x, boolean atRtl) {
5214            mTextView.getLocationOnScreen(mTextViewLocation);
5215            boolean nearEdge;
5216            if (atRtl == isStartHandle()) {
5217                int rightEdge = mTextViewLocation[0] + mTextView.getWidth()
5218                        - mTextView.getPaddingRight();
5219                nearEdge = x > rightEdge - mTextViewEdgeSlop;
5220            } else {
5221                int leftEdge = mTextViewLocation[0] + mTextView.getPaddingLeft();
5222                nearEdge = x < leftEdge + mTextViewEdgeSlop;
5223            }
5224            return nearEdge;
5225        }
5226
5227        @Override
5228        protected boolean isAtRtlRun(@NonNull Layout layout, int offset) {
5229            final int offsetToCheck = isStartHandle() ? offset : Math.max(offset - 1, 0);
5230            return layout.isRtlCharAt(offsetToCheck);
5231        }
5232
5233        @Override
5234        public float getHorizontal(@NonNull Layout layout, int offset) {
5235            return getHorizontal(layout, offset, isStartHandle());
5236        }
5237
5238        private float getHorizontal(@NonNull Layout layout, int offset, boolean startHandle) {
5239            final int line = layout.getLineForOffset(offset);
5240            final int offsetToCheck = startHandle ? offset : Math.max(offset - 1, 0);
5241            final boolean isRtlChar = layout.isRtlCharAt(offsetToCheck);
5242            final boolean isRtlParagraph = layout.getParagraphDirection(line) == -1;
5243            return (isRtlChar == isRtlParagraph)
5244                    ? layout.getPrimaryHorizontal(offset) : layout.getSecondaryHorizontal(offset);
5245        }
5246
5247        @Override
5248        protected int getOffsetAtCoordinate(@NonNull Layout layout, int line, float x) {
5249            final float localX = mTextView.convertToLocalHorizontalCoordinate(x);
5250            final int primaryOffset = layout.getOffsetForHorizontal(line, localX, true);
5251            if (!layout.isLevelBoundary(primaryOffset)) {
5252                return primaryOffset;
5253            }
5254            final int secondaryOffset = layout.getOffsetForHorizontal(line, localX, false);
5255            final int currentOffset = getCurrentCursorOffset();
5256            final int primaryDiff = Math.abs(primaryOffset - currentOffset);
5257            final int secondaryDiff = Math.abs(secondaryOffset - currentOffset);
5258            if (primaryDiff < secondaryDiff) {
5259                return primaryOffset;
5260            } else if (primaryDiff > secondaryDiff) {
5261                return secondaryOffset;
5262            } else {
5263                final int offsetToCheck = isStartHandle()
5264                        ? currentOffset : Math.max(currentOffset - 1, 0);
5265                final boolean isRtlChar = layout.isRtlCharAt(offsetToCheck);
5266                final boolean isRtlParagraph = layout.getParagraphDirection(line) == -1;
5267                return isRtlChar == isRtlParagraph ? primaryOffset : secondaryOffset;
5268            }
5269        }
5270
5271        @MagnifierHandleTrigger
5272        protected int getMagnifierHandleTrigger() {
5273            return isStartHandle()
5274                    ? MagnifierHandleTrigger.SELECTION_START
5275                    : MagnifierHandleTrigger.SELECTION_END;
5276        }
5277    }
5278
5279    private int getCurrentLineAdjustedForSlop(Layout layout, int prevLine, float y) {
5280        final int trueLine = mTextView.getLineAtCoordinate(y);
5281        if (layout == null || prevLine > layout.getLineCount()
5282                || layout.getLineCount() <= 0 || prevLine < 0) {
5283            // Invalid parameters, just return whatever line is at y.
5284            return trueLine;
5285        }
5286
5287        if (Math.abs(trueLine - prevLine) >= 2) {
5288            // Only stick to lines if we're within a line of the previous selection.
5289            return trueLine;
5290        }
5291
5292        final float verticalOffset = mTextView.viewportToContentVerticalOffset();
5293        final int lineCount = layout.getLineCount();
5294        final float slop = mTextView.getLineHeight() * LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS;
5295
5296        final float firstLineTop = layout.getLineTop(0) + verticalOffset;
5297        final float prevLineTop = layout.getLineTop(prevLine) + verticalOffset;
5298        final float yTopBound = Math.max(prevLineTop - slop, firstLineTop + slop);
5299
5300        final float lastLineBottom = layout.getLineBottom(lineCount - 1) + verticalOffset;
5301        final float prevLineBottom = layout.getLineBottom(prevLine) + verticalOffset;
5302        final float yBottomBound = Math.min(prevLineBottom + slop, lastLineBottom - slop);
5303
5304        // Determine if we've moved lines based on y position and previous line.
5305        int currLine;
5306        if (y <= yTopBound) {
5307            currLine = Math.max(prevLine - 1, 0);
5308        } else if (y >= yBottomBound) {
5309            currLine = Math.min(prevLine + 1, lineCount - 1);
5310        } else {
5311            currLine = prevLine;
5312        }
5313        return currLine;
5314    }
5315
5316    /**
5317     * A CursorController instance can be used to control a cursor in the text.
5318     */
5319    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
5320        /**
5321         * Makes the cursor controller visible on screen.
5322         * See also {@link #hide()}.
5323         */
5324        public void show();
5325
5326        /**
5327         * Hide the cursor controller from screen.
5328         * See also {@link #show()}.
5329         */
5330        public void hide();
5331
5332        /**
5333         * Called when the view is detached from window. Perform house keeping task, such as
5334         * stopping Runnable thread that would otherwise keep a reference on the context, thus
5335         * preventing the activity from being recycled.
5336         */
5337        public void onDetached();
5338
5339        public boolean isCursorBeingModified();
5340
5341        public boolean isActive();
5342    }
5343
5344    private class InsertionPointCursorController implements CursorController {
5345        private InsertionHandleView mHandle;
5346
5347        public void show() {
5348            getHandle().show();
5349
5350            if (mSelectionModifierCursorController != null) {
5351                mSelectionModifierCursorController.hide();
5352            }
5353        }
5354
5355        public void hide() {
5356            if (mHandle != null) {
5357                mHandle.hide();
5358            }
5359        }
5360
5361        public void onTouchModeChanged(boolean isInTouchMode) {
5362            if (!isInTouchMode) {
5363                hide();
5364            }
5365        }
5366
5367        private InsertionHandleView getHandle() {
5368            if (mSelectHandleCenter == null) {
5369                mSelectHandleCenter = mTextView.getContext().getDrawable(
5370                        mTextView.mTextSelectHandleRes);
5371            }
5372            if (mHandle == null) {
5373                mHandle = new InsertionHandleView(mSelectHandleCenter);
5374            }
5375            return mHandle;
5376        }
5377
5378        @Override
5379        public void onDetached() {
5380            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
5381            observer.removeOnTouchModeChangeListener(this);
5382
5383            if (mHandle != null) mHandle.onDetached();
5384        }
5385
5386        @Override
5387        public boolean isCursorBeingModified() {
5388            return mHandle != null && mHandle.isDragging();
5389        }
5390
5391        @Override
5392        public boolean isActive() {
5393            return mHandle != null && mHandle.isShowing();
5394        }
5395
5396        public void invalidateHandle() {
5397            if (mHandle != null) {
5398                mHandle.invalidate();
5399            }
5400        }
5401    }
5402
5403    class SelectionModifierCursorController implements CursorController {
5404        // The cursor controller handles, lazily created when shown.
5405        private SelectionHandleView mStartHandle;
5406        private SelectionHandleView mEndHandle;
5407        // The offsets of that last touch down event. Remembered to start selection there.
5408        private int mMinTouchOffset, mMaxTouchOffset;
5409
5410        private float mDownPositionX, mDownPositionY;
5411        private boolean mGestureStayedInTapRegion;
5412
5413        // Where the user first starts the drag motion.
5414        private int mStartOffset = -1;
5415
5416        private boolean mHaventMovedEnoughToStartDrag;
5417        // The line that a selection happened most recently with the drag accelerator.
5418        private int mLineSelectionIsOn = -1;
5419        // Whether the drag accelerator has selected past the initial line.
5420        private boolean mSwitchedLines = false;
5421
5422        // Indicates the drag accelerator mode that the user is currently using.
5423        private int mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE;
5424        // Drag accelerator is inactive.
5425        private static final int DRAG_ACCELERATOR_MODE_INACTIVE = 0;
5426        // Character based selection by dragging. Only for mouse.
5427        private static final int DRAG_ACCELERATOR_MODE_CHARACTER = 1;
5428        // Word based selection by dragging. Enabled after long pressing or double tapping.
5429        private static final int DRAG_ACCELERATOR_MODE_WORD = 2;
5430        // Paragraph based selection by dragging. Enabled after mouse triple click.
5431        private static final int DRAG_ACCELERATOR_MODE_PARAGRAPH = 3;
5432
5433        SelectionModifierCursorController() {
5434            resetTouchOffsets();
5435        }
5436
5437        public void show() {
5438            if (mTextView.isInBatchEditMode()) {
5439                return;
5440            }
5441            initDrawables();
5442            initHandles();
5443        }
5444
5445        private void initDrawables() {
5446            if (mSelectHandleLeft == null) {
5447                mSelectHandleLeft = mTextView.getContext().getDrawable(
5448                        mTextView.mTextSelectHandleLeftRes);
5449            }
5450            if (mSelectHandleRight == null) {
5451                mSelectHandleRight = mTextView.getContext().getDrawable(
5452                        mTextView.mTextSelectHandleRightRes);
5453            }
5454        }
5455
5456        private void initHandles() {
5457            // Lazy object creation has to be done before updatePosition() is called.
5458            if (mStartHandle == null) {
5459                mStartHandle = new SelectionHandleView(mSelectHandleLeft, mSelectHandleRight,
5460                        com.android.internal.R.id.selection_start_handle,
5461                        HANDLE_TYPE_SELECTION_START);
5462            }
5463            if (mEndHandle == null) {
5464                mEndHandle = new SelectionHandleView(mSelectHandleRight, mSelectHandleLeft,
5465                        com.android.internal.R.id.selection_end_handle,
5466                        HANDLE_TYPE_SELECTION_END);
5467            }
5468
5469            mStartHandle.show();
5470            mEndHandle.show();
5471
5472            hideInsertionPointCursorController();
5473        }
5474
5475        public void hide() {
5476            if (mStartHandle != null) mStartHandle.hide();
5477            if (mEndHandle != null) mEndHandle.hide();
5478        }
5479
5480        public void enterDrag(int dragAcceleratorMode) {
5481            // Just need to init the handles / hide insertion cursor.
5482            show();
5483            mDragAcceleratorMode = dragAcceleratorMode;
5484            // Start location of selection.
5485            mStartOffset = mTextView.getOffsetForPosition(mLastDownPositionX,
5486                    mLastDownPositionY);
5487            mLineSelectionIsOn = mTextView.getLineAtCoordinate(mLastDownPositionY);
5488            // Don't show the handles until user has lifted finger.
5489            hide();
5490
5491            // This stops scrolling parents from intercepting the touch event, allowing
5492            // the user to continue dragging across the screen to select text; TextView will
5493            // scroll as necessary.
5494            mTextView.getParent().requestDisallowInterceptTouchEvent(true);
5495            mTextView.cancelLongPress();
5496        }
5497
5498        public void onTouchEvent(MotionEvent event) {
5499            // This is done even when the View does not have focus, so that long presses can start
5500            // selection and tap can move cursor from this tap position.
5501            final float eventX = event.getX();
5502            final float eventY = event.getY();
5503            final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
5504            switch (event.getActionMasked()) {
5505                case MotionEvent.ACTION_DOWN:
5506                    if (extractedTextModeWillBeStarted()) {
5507                        // Prevent duplicating the selection handles until the mode starts.
5508                        hide();
5509                    } else {
5510                        // Remember finger down position, to be able to start selection from there.
5511                        mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(
5512                                eventX, eventY);
5513
5514                        // Double tap detection
5515                        if (mGestureStayedInTapRegion) {
5516                            if (mTapState == TAP_STATE_DOUBLE_TAP
5517                                    || mTapState == TAP_STATE_TRIPLE_CLICK) {
5518                                final float deltaX = eventX - mDownPositionX;
5519                                final float deltaY = eventY - mDownPositionY;
5520                                final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
5521
5522                                ViewConfiguration viewConfiguration = ViewConfiguration.get(
5523                                        mTextView.getContext());
5524                                int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop();
5525                                boolean stayedInArea =
5526                                        distanceSquared < doubleTapSlop * doubleTapSlop;
5527
5528                                if (stayedInArea && (isMouse || isPositionOnText(eventX, eventY))) {
5529                                    if (mTapState == TAP_STATE_DOUBLE_TAP) {
5530                                        selectCurrentWordAndStartDrag();
5531                                    } else if (mTapState == TAP_STATE_TRIPLE_CLICK) {
5532                                        selectCurrentParagraphAndStartDrag();
5533                                    }
5534                                    mDiscardNextActionUp = true;
5535                                }
5536                            }
5537                        }
5538
5539                        mDownPositionX = eventX;
5540                        mDownPositionY = eventY;
5541                        mGestureStayedInTapRegion = true;
5542                        mHaventMovedEnoughToStartDrag = true;
5543                    }
5544                    break;
5545
5546                case MotionEvent.ACTION_POINTER_DOWN:
5547                case MotionEvent.ACTION_POINTER_UP:
5548                    // Handle multi-point gestures. Keep min and max offset positions.
5549                    // Only activated for devices that correctly handle multi-touch.
5550                    if (mTextView.getContext().getPackageManager().hasSystemFeature(
5551                            PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
5552                        updateMinAndMaxOffsets(event);
5553                    }
5554                    break;
5555
5556                case MotionEvent.ACTION_MOVE:
5557                    final ViewConfiguration viewConfig = ViewConfiguration.get(
5558                            mTextView.getContext());
5559                    final int touchSlop = viewConfig.getScaledTouchSlop();
5560
5561                    if (mGestureStayedInTapRegion || mHaventMovedEnoughToStartDrag) {
5562                        final float deltaX = eventX - mDownPositionX;
5563                        final float deltaY = eventY - mDownPositionY;
5564                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
5565
5566                        if (mGestureStayedInTapRegion) {
5567                            int doubleTapTouchSlop = viewConfig.getScaledDoubleTapTouchSlop();
5568                            mGestureStayedInTapRegion =
5569                                    distanceSquared <= doubleTapTouchSlop * doubleTapTouchSlop;
5570                        }
5571                        if (mHaventMovedEnoughToStartDrag) {
5572                            // We don't start dragging until the user has moved enough.
5573                            mHaventMovedEnoughToStartDrag =
5574                                    distanceSquared <= touchSlop * touchSlop;
5575                        }
5576                    }
5577
5578                    if (isMouse && !isDragAcceleratorActive()) {
5579                        final int offset = mTextView.getOffsetForPosition(eventX, eventY);
5580                        if (mTextView.hasSelection()
5581                                && (!mHaventMovedEnoughToStartDrag || mStartOffset != offset)
5582                                && offset >= mTextView.getSelectionStart()
5583                                && offset <= mTextView.getSelectionEnd()) {
5584                            startDragAndDrop();
5585                            break;
5586                        }
5587
5588                        if (mStartOffset != offset) {
5589                            // Start character based drag accelerator.
5590                            stopTextActionMode();
5591                            enterDrag(DRAG_ACCELERATOR_MODE_CHARACTER);
5592                            mDiscardNextActionUp = true;
5593                            mHaventMovedEnoughToStartDrag = false;
5594                        }
5595                    }
5596
5597                    if (mStartHandle != null && mStartHandle.isShowing()) {
5598                        // Don't do the drag if the handles are showing already.
5599                        break;
5600                    }
5601
5602                    updateSelection(event);
5603                    break;
5604
5605                case MotionEvent.ACTION_UP:
5606                    if (!isDragAcceleratorActive()) {
5607                        break;
5608                    }
5609                    updateSelection(event);
5610
5611                    // No longer dragging to select text, let the parent intercept events.
5612                    mTextView.getParent().requestDisallowInterceptTouchEvent(false);
5613
5614                    // No longer the first dragging motion, reset.
5615                    resetDragAcceleratorState();
5616
5617                    if (mTextView.hasSelection()) {
5618                        // Drag selection should not be adjusted by the text classifier.
5619                        startSelectionActionModeAsync(mHaventMovedEnoughToStartDrag);
5620                    }
5621                    break;
5622            }
5623        }
5624
5625        private void updateSelection(MotionEvent event) {
5626            if (mTextView.getLayout() != null) {
5627                switch (mDragAcceleratorMode) {
5628                    case DRAG_ACCELERATOR_MODE_CHARACTER:
5629                        updateCharacterBasedSelection(event);
5630                        break;
5631                    case DRAG_ACCELERATOR_MODE_WORD:
5632                        updateWordBasedSelection(event);
5633                        break;
5634                    case DRAG_ACCELERATOR_MODE_PARAGRAPH:
5635                        updateParagraphBasedSelection(event);
5636                        break;
5637                }
5638            }
5639        }
5640
5641        /**
5642         * If the TextView allows text selection, selects the current paragraph and starts a drag.
5643         *
5644         * @return true if the drag was started.
5645         */
5646        private boolean selectCurrentParagraphAndStartDrag() {
5647            if (mInsertionActionModeRunnable != null) {
5648                mTextView.removeCallbacks(mInsertionActionModeRunnable);
5649            }
5650            stopTextActionMode();
5651            if (!selectCurrentParagraph()) {
5652                return false;
5653            }
5654            enterDrag(SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_PARAGRAPH);
5655            return true;
5656        }
5657
5658        private void updateCharacterBasedSelection(MotionEvent event) {
5659            final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
5660            updateSelectionInternal(mStartOffset, offset,
5661                    event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN));
5662        }
5663
5664        private void updateWordBasedSelection(MotionEvent event) {
5665            if (mHaventMovedEnoughToStartDrag) {
5666                return;
5667            }
5668            final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
5669            final ViewConfiguration viewConfig = ViewConfiguration.get(
5670                    mTextView.getContext());
5671            final float eventX = event.getX();
5672            final float eventY = event.getY();
5673            final int currLine;
5674            if (isMouse) {
5675                // No need to offset the y coordinate for mouse input.
5676                currLine = mTextView.getLineAtCoordinate(eventY);
5677            } else {
5678                float y = eventY;
5679                if (mSwitchedLines) {
5680                    // Offset the finger by the same vertical offset as the handles.
5681                    // This improves visibility of the content being selected by
5682                    // shifting the finger below the content, this is applied once
5683                    // the user has switched lines.
5684                    final int touchSlop = viewConfig.getScaledTouchSlop();
5685                    final float fingerOffset = (mStartHandle != null)
5686                            ? mStartHandle.getIdealVerticalOffset()
5687                            : touchSlop;
5688                    y = eventY - fingerOffset;
5689                }
5690
5691                currLine = getCurrentLineAdjustedForSlop(mTextView.getLayout(), mLineSelectionIsOn,
5692                        y);
5693                if (!mSwitchedLines && currLine != mLineSelectionIsOn) {
5694                    // Break early here, we want to offset the finger position from
5695                    // the selection highlight, once the user moved their finger
5696                    // to a different line we should apply the offset and *not* switch
5697                    // lines until recomputing the position with the finger offset.
5698                    mSwitchedLines = true;
5699                    return;
5700                }
5701            }
5702
5703            int startOffset;
5704            int offset = mTextView.getOffsetAtCoordinate(currLine, eventX);
5705            // Snap to word boundaries.
5706            if (mStartOffset < offset) {
5707                // Expanding with end handle.
5708                offset = getWordEnd(offset);
5709                startOffset = getWordStart(mStartOffset);
5710            } else {
5711                // Expanding with start handle.
5712                offset = getWordStart(offset);
5713                startOffset = getWordEnd(mStartOffset);
5714                if (startOffset == offset) {
5715                    offset = getNextCursorOffset(offset, false);
5716                }
5717            }
5718            mLineSelectionIsOn = currLine;
5719            updateSelectionInternal(startOffset, offset,
5720                    event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN));
5721        }
5722
5723        private void updateParagraphBasedSelection(MotionEvent event) {
5724            final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
5725
5726            final int start = Math.min(offset, mStartOffset);
5727            final int end = Math.max(offset, mStartOffset);
5728            final long paragraphsRange = getParagraphsRange(start, end);
5729            final int selectionStart = TextUtils.unpackRangeStartFromLong(paragraphsRange);
5730            final int selectionEnd = TextUtils.unpackRangeEndFromLong(paragraphsRange);
5731            updateSelectionInternal(selectionStart, selectionEnd,
5732                    event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN));
5733        }
5734
5735        private void updateSelectionInternal(int selectionStart, int selectionEnd,
5736                boolean fromTouchScreen) {
5737            final boolean performHapticFeedback = fromTouchScreen && mHapticTextHandleEnabled
5738                    && ((mTextView.getSelectionStart() != selectionStart)
5739                            || (mTextView.getSelectionEnd() != selectionEnd));
5740            Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
5741            if (performHapticFeedback) {
5742                mTextView.performHapticFeedback(HapticFeedbackConstants.TEXT_HANDLE_MOVE);
5743            }
5744        }
5745
5746        /**
5747         * @param event
5748         */
5749        private void updateMinAndMaxOffsets(MotionEvent event) {
5750            int pointerCount = event.getPointerCount();
5751            for (int index = 0; index < pointerCount; index++) {
5752                int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index));
5753                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
5754                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
5755            }
5756        }
5757
5758        public int getMinTouchOffset() {
5759            return mMinTouchOffset;
5760        }
5761
5762        public int getMaxTouchOffset() {
5763            return mMaxTouchOffset;
5764        }
5765
5766        public void resetTouchOffsets() {
5767            mMinTouchOffset = mMaxTouchOffset = -1;
5768            resetDragAcceleratorState();
5769        }
5770
5771        private void resetDragAcceleratorState() {
5772            mStartOffset = -1;
5773            mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE;
5774            mSwitchedLines = false;
5775            final int selectionStart = mTextView.getSelectionStart();
5776            final int selectionEnd = mTextView.getSelectionEnd();
5777            if (selectionStart > selectionEnd) {
5778                Selection.setSelection((Spannable) mTextView.getText(),
5779                        selectionEnd, selectionStart);
5780            }
5781        }
5782
5783        /**
5784         * @return true iff this controller is currently used to move the selection start.
5785         */
5786        public boolean isSelectionStartDragged() {
5787            return mStartHandle != null && mStartHandle.isDragging();
5788        }
5789
5790        @Override
5791        public boolean isCursorBeingModified() {
5792            return isDragAcceleratorActive() || isSelectionStartDragged()
5793                    || (mEndHandle != null && mEndHandle.isDragging());
5794        }
5795
5796        /**
5797         * @return true if the user is selecting text using the drag accelerator.
5798         */
5799        public boolean isDragAcceleratorActive() {
5800            return mDragAcceleratorMode != DRAG_ACCELERATOR_MODE_INACTIVE;
5801        }
5802
5803        public void onTouchModeChanged(boolean isInTouchMode) {
5804            if (!isInTouchMode) {
5805                hide();
5806            }
5807        }
5808
5809        @Override
5810        public void onDetached() {
5811            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
5812            observer.removeOnTouchModeChangeListener(this);
5813
5814            if (mStartHandle != null) mStartHandle.onDetached();
5815            if (mEndHandle != null) mEndHandle.onDetached();
5816        }
5817
5818        @Override
5819        public boolean isActive() {
5820            return mStartHandle != null && mStartHandle.isShowing();
5821        }
5822
5823        public void invalidateHandles() {
5824            if (mStartHandle != null) {
5825                mStartHandle.invalidate();
5826            }
5827            if (mEndHandle != null) {
5828                mEndHandle.invalidate();
5829            }
5830        }
5831    }
5832
5833    private class CorrectionHighlighter {
5834        private final Path mPath = new Path();
5835        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
5836        private int mStart, mEnd;
5837        private long mFadingStartTime;
5838        private RectF mTempRectF;
5839        private static final int FADE_OUT_DURATION = 400;
5840
5841        public CorrectionHighlighter() {
5842            mPaint.setCompatibilityScaling(
5843                    mTextView.getResources().getCompatibilityInfo().applicationScale);
5844            mPaint.setStyle(Paint.Style.FILL);
5845        }
5846
5847        public void highlight(CorrectionInfo info) {
5848            mStart = info.getOffset();
5849            mEnd = mStart + info.getNewText().length();
5850            mFadingStartTime = SystemClock.uptimeMillis();
5851
5852            if (mStart < 0 || mEnd < 0) {
5853                stopAnimation();
5854            }
5855        }
5856
5857        public void draw(Canvas canvas, int cursorOffsetVertical) {
5858            if (updatePath() && updatePaint()) {
5859                if (cursorOffsetVertical != 0) {
5860                    canvas.translate(0, cursorOffsetVertical);
5861                }
5862
5863                canvas.drawPath(mPath, mPaint);
5864
5865                if (cursorOffsetVertical != 0) {
5866                    canvas.translate(0, -cursorOffsetVertical);
5867                }
5868                invalidate(true); // TODO invalidate cursor region only
5869            } else {
5870                stopAnimation();
5871                invalidate(false); // TODO invalidate cursor region only
5872            }
5873        }
5874
5875        private boolean updatePaint() {
5876            final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
5877            if (duration > FADE_OUT_DURATION) return false;
5878
5879            final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
5880            final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor);
5881            final int color = (mTextView.mHighlightColor & 0x00FFFFFF)
5882                    + ((int) (highlightColorAlpha * coef) << 24);
5883            mPaint.setColor(color);
5884            return true;
5885        }
5886
5887        private boolean updatePath() {
5888            final Layout layout = mTextView.getLayout();
5889            if (layout == null) return false;
5890
5891            // Update in case text is edited while the animation is run
5892            final int length = mTextView.getText().length();
5893            int start = Math.min(length, mStart);
5894            int end = Math.min(length, mEnd);
5895
5896            mPath.reset();
5897            layout.getSelectionPath(start, end, mPath);
5898            return true;
5899        }
5900
5901        private void invalidate(boolean delayed) {
5902            if (mTextView.getLayout() == null) return;
5903
5904            if (mTempRectF == null) mTempRectF = new RectF();
5905            mPath.computeBounds(mTempRectF, false);
5906
5907            int left = mTextView.getCompoundPaddingLeft();
5908            int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true);
5909
5910            if (delayed) {
5911                mTextView.postInvalidateOnAnimation(
5912                        left + (int) mTempRectF.left, top + (int) mTempRectF.top,
5913                        left + (int) mTempRectF.right, top + (int) mTempRectF.bottom);
5914            } else {
5915                mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top,
5916                        (int) mTempRectF.right, (int) mTempRectF.bottom);
5917            }
5918        }
5919
5920        private void stopAnimation() {
5921            Editor.this.mCorrectionHighlighter = null;
5922        }
5923    }
5924
5925    private static class ErrorPopup extends PopupWindow {
5926        private boolean mAbove = false;
5927        private final TextView mView;
5928        private int mPopupInlineErrorBackgroundId = 0;
5929        private int mPopupInlineErrorAboveBackgroundId = 0;
5930
5931        ErrorPopup(TextView v, int width, int height) {
5932            super(v, width, height);
5933            mView = v;
5934            // Make sure the TextView has a background set as it will be used the first time it is
5935            // shown and positioned. Initialized with below background, which should have
5936            // dimensions identical to the above version for this to work (and is more likely).
5937            mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
5938                    com.android.internal.R.styleable.Theme_errorMessageBackground);
5939            mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
5940        }
5941
5942        void fixDirection(boolean above) {
5943            mAbove = above;
5944
5945            if (above) {
5946                mPopupInlineErrorAboveBackgroundId =
5947                    getResourceId(mPopupInlineErrorAboveBackgroundId,
5948                            com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
5949            } else {
5950                mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
5951                        com.android.internal.R.styleable.Theme_errorMessageBackground);
5952            }
5953
5954            mView.setBackgroundResource(
5955                    above ? mPopupInlineErrorAboveBackgroundId : mPopupInlineErrorBackgroundId);
5956        }
5957
5958        private int getResourceId(int currentId, int index) {
5959            if (currentId == 0) {
5960                TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
5961                        R.styleable.Theme);
5962                currentId = styledAttributes.getResourceId(index, 0);
5963                styledAttributes.recycle();
5964            }
5965            return currentId;
5966        }
5967
5968        @Override
5969        public void update(int x, int y, int w, int h, boolean force) {
5970            super.update(x, y, w, h, force);
5971
5972            boolean above = isAboveAnchor();
5973            if (above != mAbove) {
5974                fixDirection(above);
5975            }
5976        }
5977    }
5978
5979    static class InputContentType {
5980        int imeOptions = EditorInfo.IME_NULL;
5981        String privateImeOptions;
5982        CharSequence imeActionLabel;
5983        int imeActionId;
5984        Bundle extras;
5985        OnEditorActionListener onEditorActionListener;
5986        boolean enterDown;
5987        LocaleList imeHintLocales;
5988    }
5989
5990    static class InputMethodState {
5991        ExtractedTextRequest mExtractedTextRequest;
5992        final ExtractedText mExtractedText = new ExtractedText();
5993        int mBatchEditNesting;
5994        boolean mCursorChanged;
5995        boolean mSelectionModeChanged;
5996        boolean mContentChanged;
5997        int mChangedStart, mChangedEnd, mChangedDelta;
5998    }
5999
6000    /**
6001     * @return True iff (start, end) is a valid range within the text.
6002     */
6003    private static boolean isValidRange(CharSequence text, int start, int end) {
6004        return 0 <= start && start <= end && end <= text.length();
6005    }
6006
6007    @VisibleForTesting
6008    public SuggestionsPopupWindow getSuggestionsPopupWindowForTesting() {
6009        return mSuggestionsPopupWindow;
6010    }
6011
6012    /**
6013     * An InputFilter that monitors text input to maintain undo history. It does not modify the
6014     * text being typed (and hence always returns null from the filter() method).
6015     *
6016     * TODO: Make this span aware.
6017     */
6018    public static class UndoInputFilter implements InputFilter {
6019        private final Editor mEditor;
6020
6021        // Whether the current filter pass is directly caused by an end-user text edit.
6022        private boolean mIsUserEdit;
6023
6024        // Whether the text field is handling an IME composition. Must be parceled in case the user
6025        // rotates the screen during composition.
6026        private boolean mHasComposition;
6027
6028        // Whether the user is expanding or shortening the text
6029        private boolean mExpanding;
6030
6031        // Whether the previous edit operation was in the current batch edit.
6032        private boolean mPreviousOperationWasInSameBatchEdit;
6033
6034        public UndoInputFilter(Editor editor) {
6035            mEditor = editor;
6036        }
6037
6038        public void saveInstanceState(Parcel parcel) {
6039            parcel.writeInt(mIsUserEdit ? 1 : 0);
6040            parcel.writeInt(mHasComposition ? 1 : 0);
6041            parcel.writeInt(mExpanding ? 1 : 0);
6042            parcel.writeInt(mPreviousOperationWasInSameBatchEdit ? 1 : 0);
6043        }
6044
6045        public void restoreInstanceState(Parcel parcel) {
6046            mIsUserEdit = parcel.readInt() != 0;
6047            mHasComposition = parcel.readInt() != 0;
6048            mExpanding = parcel.readInt() != 0;
6049            mPreviousOperationWasInSameBatchEdit = parcel.readInt() != 0;
6050        }
6051
6052        /**
6053         * Signals that a user-triggered edit is starting.
6054         */
6055        public void beginBatchEdit() {
6056            if (DEBUG_UNDO) Log.d(TAG, "beginBatchEdit");
6057            mIsUserEdit = true;
6058        }
6059
6060        public void endBatchEdit() {
6061            if (DEBUG_UNDO) Log.d(TAG, "endBatchEdit");
6062            mIsUserEdit = false;
6063            mPreviousOperationWasInSameBatchEdit = false;
6064        }
6065
6066        @Override
6067        public CharSequence filter(CharSequence source, int start, int end,
6068                Spanned dest, int dstart, int dend) {
6069            if (DEBUG_UNDO) {
6070                Log.d(TAG, "filter: source=" + source + " (" + start + "-" + end + ") "
6071                        + "dest=" + dest + " (" + dstart + "-" + dend + ")");
6072            }
6073
6074            // Check to see if this edit should be tracked for undo.
6075            if (!canUndoEdit(source, start, end, dest, dstart, dend)) {
6076                return null;
6077            }
6078
6079            final boolean hadComposition = mHasComposition;
6080            mHasComposition = isComposition(source);
6081            final boolean wasExpanding = mExpanding;
6082            boolean shouldCreateSeparateState = false;
6083            if ((end - start) != (dend - dstart)) {
6084                mExpanding = (end - start) > (dend - dstart);
6085                if (hadComposition && mExpanding != wasExpanding) {
6086                    shouldCreateSeparateState = true;
6087                }
6088            }
6089
6090            // Handle edit.
6091            handleEdit(source, start, end, dest, dstart, dend, shouldCreateSeparateState);
6092            return null;
6093        }
6094
6095        void freezeLastEdit() {
6096            mEditor.mUndoManager.beginUpdate("Edit text");
6097            EditOperation lastEdit = getLastEdit();
6098            if (lastEdit != null) {
6099                lastEdit.mFrozen = true;
6100            }
6101            mEditor.mUndoManager.endUpdate();
6102        }
6103
6104        @Retention(RetentionPolicy.SOURCE)
6105        @IntDef({MERGE_EDIT_MODE_FORCE_MERGE, MERGE_EDIT_MODE_NEVER_MERGE, MERGE_EDIT_MODE_NORMAL})
6106        private @interface MergeMode {}
6107        private static final int MERGE_EDIT_MODE_FORCE_MERGE = 0;
6108        private static final int MERGE_EDIT_MODE_NEVER_MERGE = 1;
6109        /** Use {@link EditOperation#mergeWith} to merge */
6110        private static final int MERGE_EDIT_MODE_NORMAL = 2;
6111
6112        private void handleEdit(CharSequence source, int start, int end,
6113                Spanned dest, int dstart, int dend, boolean shouldCreateSeparateState) {
6114            // An application may install a TextWatcher to provide additional modifications after
6115            // the initial input filters run (e.g. a credit card formatter that adds spaces to a
6116            // string). This results in multiple filter() calls for what the user considers to be
6117            // a single operation. Always undo the whole set of changes in one step.
6118            @MergeMode
6119            final int mergeMode;
6120            if (isInTextWatcher() || mPreviousOperationWasInSameBatchEdit) {
6121                mergeMode = MERGE_EDIT_MODE_FORCE_MERGE;
6122            } else if (shouldCreateSeparateState) {
6123                mergeMode = MERGE_EDIT_MODE_NEVER_MERGE;
6124            } else {
6125                mergeMode = MERGE_EDIT_MODE_NORMAL;
6126            }
6127            // Build a new operation with all the information from this edit.
6128            String newText = TextUtils.substring(source, start, end);
6129            String oldText = TextUtils.substring(dest, dstart, dend);
6130            EditOperation edit = new EditOperation(mEditor, oldText, dstart, newText,
6131                    mHasComposition);
6132            if (mHasComposition && TextUtils.equals(edit.mNewText, edit.mOldText)) {
6133                return;
6134            }
6135            recordEdit(edit, mergeMode);
6136        }
6137
6138        private EditOperation getLastEdit() {
6139            final UndoManager um = mEditor.mUndoManager;
6140            return um.getLastOperation(
6141                  EditOperation.class, mEditor.mUndoOwner, UndoManager.MERGE_MODE_UNIQUE);
6142        }
6143        /**
6144         * Fetches the last undo operation and checks to see if a new edit should be merged into it.
6145         * If forceMerge is true then the new edit is always merged.
6146         */
6147        private void recordEdit(EditOperation edit, @MergeMode int mergeMode) {
6148            // Fetch the last edit operation and attempt to merge in the new edit.
6149            final UndoManager um = mEditor.mUndoManager;
6150            um.beginUpdate("Edit text");
6151            EditOperation lastEdit = getLastEdit();
6152            if (lastEdit == null) {
6153                // Add this as the first edit.
6154                if (DEBUG_UNDO) Log.d(TAG, "filter: adding first op " + edit);
6155                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
6156            } else if (mergeMode == MERGE_EDIT_MODE_FORCE_MERGE) {
6157                // Forced merges take priority because they could be the result of a non-user-edit
6158                // change and this case should not create a new undo operation.
6159                if (DEBUG_UNDO) Log.d(TAG, "filter: force merge " + edit);
6160                lastEdit.forceMergeWith(edit);
6161            } else if (!mIsUserEdit) {
6162                // An application directly modified the Editable outside of a text edit. Treat this
6163                // as a new change and don't attempt to merge.
6164                if (DEBUG_UNDO) Log.d(TAG, "non-user edit, new op " + edit);
6165                um.commitState(mEditor.mUndoOwner);
6166                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
6167            } else if (mergeMode == MERGE_EDIT_MODE_NORMAL && lastEdit.mergeWith(edit)) {
6168                // Merge succeeded, nothing else to do.
6169                if (DEBUG_UNDO) Log.d(TAG, "filter: merge succeeded, created " + lastEdit);
6170            } else {
6171                // Could not merge with the last edit, so commit the last edit and add this edit.
6172                if (DEBUG_UNDO) Log.d(TAG, "filter: merge failed, adding " + edit);
6173                um.commitState(mEditor.mUndoOwner);
6174                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
6175            }
6176            mPreviousOperationWasInSameBatchEdit = mIsUserEdit;
6177            um.endUpdate();
6178        }
6179
6180        private boolean canUndoEdit(CharSequence source, int start, int end,
6181                Spanned dest, int dstart, int dend) {
6182            if (!mEditor.mAllowUndo) {
6183                if (DEBUG_UNDO) Log.d(TAG, "filter: undo is disabled");
6184                return false;
6185            }
6186
6187            if (mEditor.mUndoManager.isInUndo()) {
6188                if (DEBUG_UNDO) Log.d(TAG, "filter: skipping, currently performing undo/redo");
6189                return false;
6190            }
6191
6192            // Text filters run before input operations are applied. However, some input operations
6193            // are invalid and will throw exceptions when applied. This is common in tests. Don't
6194            // attempt to undo invalid operations.
6195            if (!isValidRange(source, start, end) || !isValidRange(dest, dstart, dend)) {
6196                if (DEBUG_UNDO) Log.d(TAG, "filter: invalid op");
6197                return false;
6198            }
6199
6200            // Earlier filters can rewrite input to be a no-op, for example due to a length limit
6201            // on an input field. Skip no-op changes.
6202            if (start == end && dstart == dend) {
6203                if (DEBUG_UNDO) Log.d(TAG, "filter: skipping no-op");
6204                return false;
6205            }
6206
6207            return true;
6208        }
6209
6210        private static boolean isComposition(CharSequence source) {
6211            if (!(source instanceof Spannable)) {
6212                return false;
6213            }
6214            // This is a composition edit if the source has a non-zero-length composing span.
6215            Spannable text = (Spannable) source;
6216            int composeBegin = EditableInputConnection.getComposingSpanStart(text);
6217            int composeEnd = EditableInputConnection.getComposingSpanEnd(text);
6218            return composeBegin < composeEnd;
6219        }
6220
6221        private boolean isInTextWatcher() {
6222            CharSequence text = mEditor.mTextView.getText();
6223            return (text instanceof SpannableStringBuilder)
6224                    && ((SpannableStringBuilder) text).getTextWatcherDepth() > 0;
6225        }
6226    }
6227
6228    /**
6229     * An operation to undo a single "edit" to a text view.
6230     */
6231    public static class EditOperation extends UndoOperation<Editor> {
6232        private static final int TYPE_INSERT = 0;
6233        private static final int TYPE_DELETE = 1;
6234        private static final int TYPE_REPLACE = 2;
6235
6236        private int mType;
6237        private String mOldText;
6238        private String mNewText;
6239        private int mStart;
6240
6241        private int mOldCursorPos;
6242        private int mNewCursorPos;
6243        private boolean mFrozen;
6244        private boolean mIsComposition;
6245
6246        /**
6247         * Constructs an edit operation from a text input operation on editor that replaces the
6248         * oldText starting at dstart with newText.
6249         */
6250        public EditOperation(Editor editor, String oldText, int dstart, String newText,
6251                boolean isComposition) {
6252            super(editor.mUndoOwner);
6253            mOldText = oldText;
6254            mNewText = newText;
6255
6256            // Determine the type of the edit.
6257            if (mNewText.length() > 0 && mOldText.length() == 0) {
6258                mType = TYPE_INSERT;
6259            } else if (mNewText.length() == 0 && mOldText.length() > 0) {
6260                mType = TYPE_DELETE;
6261            } else {
6262                mType = TYPE_REPLACE;
6263            }
6264
6265            mStart = dstart;
6266            // Store cursor data.
6267            mOldCursorPos = editor.mTextView.getSelectionStart();
6268            mNewCursorPos = dstart + mNewText.length();
6269            mIsComposition = isComposition;
6270        }
6271
6272        public EditOperation(Parcel src, ClassLoader loader) {
6273            super(src, loader);
6274            mType = src.readInt();
6275            mOldText = src.readString();
6276            mNewText = src.readString();
6277            mStart = src.readInt();
6278            mOldCursorPos = src.readInt();
6279            mNewCursorPos = src.readInt();
6280            mFrozen = src.readInt() == 1;
6281            mIsComposition = src.readInt() == 1;
6282        }
6283
6284        @Override
6285        public void writeToParcel(Parcel dest, int flags) {
6286            dest.writeInt(mType);
6287            dest.writeString(mOldText);
6288            dest.writeString(mNewText);
6289            dest.writeInt(mStart);
6290            dest.writeInt(mOldCursorPos);
6291            dest.writeInt(mNewCursorPos);
6292            dest.writeInt(mFrozen ? 1 : 0);
6293            dest.writeInt(mIsComposition ? 1 : 0);
6294        }
6295
6296        private int getNewTextEnd() {
6297            return mStart + mNewText.length();
6298        }
6299
6300        private int getOldTextEnd() {
6301            return mStart + mOldText.length();
6302        }
6303
6304        @Override
6305        public void commit() {
6306        }
6307
6308        @Override
6309        public void undo() {
6310            if (DEBUG_UNDO) Log.d(TAG, "undo");
6311            // Remove the new text and insert the old.
6312            Editor editor = getOwnerData();
6313            Editable text = (Editable) editor.mTextView.getText();
6314            modifyText(text, mStart, getNewTextEnd(), mOldText, mStart, mOldCursorPos);
6315        }
6316
6317        @Override
6318        public void redo() {
6319            if (DEBUG_UNDO) Log.d(TAG, "redo");
6320            // Remove the old text and insert the new.
6321            Editor editor = getOwnerData();
6322            Editable text = (Editable) editor.mTextView.getText();
6323            modifyText(text, mStart, getOldTextEnd(), mNewText, mStart, mNewCursorPos);
6324        }
6325
6326        /**
6327         * Attempts to merge this existing operation with a new edit.
6328         * @param edit The new edit operation.
6329         * @return If the merge succeeded, returns true. Otherwise returns false and leaves this
6330         * object unchanged.
6331         */
6332        private boolean mergeWith(EditOperation edit) {
6333            if (DEBUG_UNDO) {
6334                Log.d(TAG, "mergeWith old " + this);
6335                Log.d(TAG, "mergeWith new " + edit);
6336            }
6337
6338            if (mFrozen) {
6339                return false;
6340            }
6341
6342            switch (mType) {
6343                case TYPE_INSERT:
6344                    return mergeInsertWith(edit);
6345                case TYPE_DELETE:
6346                    return mergeDeleteWith(edit);
6347                case TYPE_REPLACE:
6348                    return mergeReplaceWith(edit);
6349                default:
6350                    return false;
6351            }
6352        }
6353
6354        private boolean mergeInsertWith(EditOperation edit) {
6355            if (edit.mType == TYPE_INSERT) {
6356                // Merge insertions that are contiguous even when it's frozen.
6357                if (getNewTextEnd() != edit.mStart) {
6358                    return false;
6359                }
6360                mNewText += edit.mNewText;
6361                mNewCursorPos = edit.mNewCursorPos;
6362                mFrozen = edit.mFrozen;
6363                mIsComposition = edit.mIsComposition;
6364                return true;
6365            }
6366            if (mIsComposition && edit.mType == TYPE_REPLACE
6367                    && mStart <= edit.mStart && getNewTextEnd() >= edit.getOldTextEnd()) {
6368                // Merge insertion with replace as they can be single insertion.
6369                mNewText = mNewText.substring(0, edit.mStart - mStart) + edit.mNewText
6370                        + mNewText.substring(edit.getOldTextEnd() - mStart, mNewText.length());
6371                mNewCursorPos = edit.mNewCursorPos;
6372                mIsComposition = edit.mIsComposition;
6373                return true;
6374            }
6375            return false;
6376        }
6377
6378        // TODO: Support forward delete.
6379        private boolean mergeDeleteWith(EditOperation edit) {
6380            // Only merge continuous deletes.
6381            if (edit.mType != TYPE_DELETE) {
6382                return false;
6383            }
6384            // Only merge deletions that are contiguous.
6385            if (mStart != edit.getOldTextEnd()) {
6386                return false;
6387            }
6388            mStart = edit.mStart;
6389            mOldText = edit.mOldText + mOldText;
6390            mNewCursorPos = edit.mNewCursorPos;
6391            mIsComposition = edit.mIsComposition;
6392            return true;
6393        }
6394
6395        private boolean mergeReplaceWith(EditOperation edit) {
6396            if (edit.mType == TYPE_INSERT && getNewTextEnd() == edit.mStart) {
6397                // Merge with adjacent insert.
6398                mNewText += edit.mNewText;
6399                mNewCursorPos = edit.mNewCursorPos;
6400                return true;
6401            }
6402            if (!mIsComposition) {
6403                return false;
6404            }
6405            if (edit.mType == TYPE_DELETE && mStart <= edit.mStart
6406                    && getNewTextEnd() >= edit.getOldTextEnd()) {
6407                // Merge with delete as they can be single operation.
6408                mNewText = mNewText.substring(0, edit.mStart - mStart)
6409                        + mNewText.substring(edit.getOldTextEnd() - mStart, mNewText.length());
6410                if (mNewText.isEmpty()) {
6411                    mType = TYPE_DELETE;
6412                }
6413                mNewCursorPos = edit.mNewCursorPos;
6414                mIsComposition = edit.mIsComposition;
6415                return true;
6416            }
6417            if (edit.mType == TYPE_REPLACE && mStart == edit.mStart
6418                    && TextUtils.equals(mNewText, edit.mOldText)) {
6419                // Merge with the replace that replaces the same region.
6420                mNewText = edit.mNewText;
6421                mNewCursorPos = edit.mNewCursorPos;
6422                mIsComposition = edit.mIsComposition;
6423                return true;
6424            }
6425            return false;
6426        }
6427
6428        /**
6429         * Forcibly creates a single merged edit operation by simulating the entire text
6430         * contents being replaced.
6431         */
6432        public void forceMergeWith(EditOperation edit) {
6433            if (DEBUG_UNDO) Log.d(TAG, "forceMerge");
6434            if (mergeWith(edit)) {
6435                return;
6436            }
6437            Editor editor = getOwnerData();
6438
6439            // Copy the text of the current field.
6440            // NOTE: Using StringBuilder instead of SpannableStringBuilder would be somewhat faster,
6441            // but would require two parallel implementations of modifyText() because Editable and
6442            // StringBuilder do not share an interface for replace/delete/insert.
6443            Editable editable = (Editable) editor.mTextView.getText();
6444            Editable originalText = new SpannableStringBuilder(editable.toString());
6445
6446            // Roll back the last operation.
6447            modifyText(originalText, mStart, getNewTextEnd(), mOldText, mStart, mOldCursorPos);
6448
6449            // Clone the text again and apply the new operation.
6450            Editable finalText = new SpannableStringBuilder(editable.toString());
6451            modifyText(finalText, edit.mStart, edit.getOldTextEnd(),
6452                    edit.mNewText, edit.mStart, edit.mNewCursorPos);
6453
6454            // Convert this operation into a replace operation.
6455            mType = TYPE_REPLACE;
6456            mNewText = finalText.toString();
6457            mOldText = originalText.toString();
6458            mStart = 0;
6459            mNewCursorPos = edit.mNewCursorPos;
6460            mIsComposition = edit.mIsComposition;
6461            // mOldCursorPos is unchanged.
6462        }
6463
6464        private static void modifyText(Editable text, int deleteFrom, int deleteTo,
6465                CharSequence newText, int newTextInsertAt, int newCursorPos) {
6466            // Apply the edit if it is still valid.
6467            if (isValidRange(text, deleteFrom, deleteTo)
6468                    && newTextInsertAt <= text.length() - (deleteTo - deleteFrom)) {
6469                if (deleteFrom != deleteTo) {
6470                    text.delete(deleteFrom, deleteTo);
6471                }
6472                if (newText.length() != 0) {
6473                    text.insert(newTextInsertAt, newText);
6474                }
6475            }
6476            // Restore the cursor position. If there wasn't an old cursor (newCursorPos == -1) then
6477            // don't explicitly set it and rely on SpannableStringBuilder to position it.
6478            // TODO: Select all the text that was undone.
6479            if (0 <= newCursorPos && newCursorPos <= text.length()) {
6480                Selection.setSelection(text, newCursorPos);
6481            }
6482        }
6483
6484        private String getTypeString() {
6485            switch (mType) {
6486                case TYPE_INSERT:
6487                    return "insert";
6488                case TYPE_DELETE:
6489                    return "delete";
6490                case TYPE_REPLACE:
6491                    return "replace";
6492                default:
6493                    return "";
6494            }
6495        }
6496
6497        @Override
6498        public String toString() {
6499            return "[mType=" + getTypeString() + ", "
6500                    + "mOldText=" + mOldText + ", "
6501                    + "mNewText=" + mNewText + ", "
6502                    + "mStart=" + mStart + ", "
6503                    + "mOldCursorPos=" + mOldCursorPos + ", "
6504                    + "mNewCursorPos=" + mNewCursorPos + ", "
6505                    + "mFrozen=" + mFrozen + ", "
6506                    + "mIsComposition=" + mIsComposition + "]";
6507        }
6508
6509        public static final Parcelable.ClassLoaderCreator<EditOperation> CREATOR =
6510                new Parcelable.ClassLoaderCreator<EditOperation>() {
6511            @Override
6512            public EditOperation createFromParcel(Parcel in) {
6513                return new EditOperation(in, null);
6514            }
6515
6516            @Override
6517            public EditOperation createFromParcel(Parcel in, ClassLoader loader) {
6518                return new EditOperation(in, loader);
6519            }
6520
6521            @Override
6522            public EditOperation[] newArray(int size) {
6523                return new EditOperation[size];
6524            }
6525        };
6526    }
6527
6528    /**
6529     * A helper for enabling and handling "PROCESS_TEXT" menu actions.
6530     * These allow external applications to plug into currently selected text.
6531     */
6532    static final class ProcessTextIntentActionsHandler {
6533
6534        private final Editor mEditor;
6535        private final TextView mTextView;
6536        private final Context mContext;
6537        private final PackageManager mPackageManager;
6538        private final String mPackageName;
6539        private final SparseArray<Intent> mAccessibilityIntents = new SparseArray<>();
6540        private final SparseArray<AccessibilityNodeInfo.AccessibilityAction> mAccessibilityActions =
6541                new SparseArray<>();
6542        private final List<ResolveInfo> mSupportedActivities = new ArrayList<>();
6543
6544        private ProcessTextIntentActionsHandler(Editor editor) {
6545            mEditor = Preconditions.checkNotNull(editor);
6546            mTextView = Preconditions.checkNotNull(mEditor.mTextView);
6547            mContext = Preconditions.checkNotNull(mTextView.getContext());
6548            mPackageManager = Preconditions.checkNotNull(mContext.getPackageManager());
6549            mPackageName = Preconditions.checkNotNull(mContext.getPackageName());
6550        }
6551
6552        /**
6553         * Adds "PROCESS_TEXT" menu items to the specified menu.
6554         */
6555        public void onInitializeMenu(Menu menu) {
6556            final int size = mSupportedActivities.size();
6557            loadSupportedActivities();
6558            for (int i = 0; i < size; i++) {
6559                final ResolveInfo resolveInfo = mSupportedActivities.get(i);
6560                menu.add(Menu.NONE, Menu.NONE,
6561                        Editor.MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START + i++,
6562                        getLabel(resolveInfo))
6563                        .setIntent(createProcessTextIntentForResolveInfo(resolveInfo))
6564                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
6565            }
6566        }
6567
6568        /**
6569         * Performs a "PROCESS_TEXT" action if there is one associated with the specified
6570         * menu item.
6571         *
6572         * @return True if the action was performed, false otherwise.
6573         */
6574        public boolean performMenuItemAction(MenuItem item) {
6575            return fireIntent(item.getIntent());
6576        }
6577
6578        /**
6579         * Initializes and caches "PROCESS_TEXT" accessibility actions.
6580         */
6581        public void initializeAccessibilityActions() {
6582            mAccessibilityIntents.clear();
6583            mAccessibilityActions.clear();
6584            int i = 0;
6585            loadSupportedActivities();
6586            for (ResolveInfo resolveInfo : mSupportedActivities) {
6587                int actionId = TextView.ACCESSIBILITY_ACTION_PROCESS_TEXT_START_ID + i++;
6588                mAccessibilityActions.put(
6589                        actionId,
6590                        new AccessibilityNodeInfo.AccessibilityAction(
6591                                actionId, getLabel(resolveInfo)));
6592                mAccessibilityIntents.put(
6593                        actionId, createProcessTextIntentForResolveInfo(resolveInfo));
6594            }
6595        }
6596
6597        /**
6598         * Adds "PROCESS_TEXT" accessibility actions to the specified accessibility node info.
6599         * NOTE: This needs a prior call to {@link #initializeAccessibilityActions()} to make the
6600         * latest accessibility actions available for this call.
6601         */
6602        public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo nodeInfo) {
6603            for (int i = 0; i < mAccessibilityActions.size(); i++) {
6604                nodeInfo.addAction(mAccessibilityActions.valueAt(i));
6605            }
6606        }
6607
6608        /**
6609         * Performs a "PROCESS_TEXT" action if there is one associated with the specified
6610         * accessibility action id.
6611         *
6612         * @return True if the action was performed, false otherwise.
6613         */
6614        public boolean performAccessibilityAction(int actionId) {
6615            return fireIntent(mAccessibilityIntents.get(actionId));
6616        }
6617
6618        private boolean fireIntent(Intent intent) {
6619            if (intent != null && Intent.ACTION_PROCESS_TEXT.equals(intent.getAction())) {
6620                String selectedText = mTextView.getSelectedText();
6621                selectedText = TextUtils.trimToParcelableSize(selectedText);
6622                intent.putExtra(Intent.EXTRA_PROCESS_TEXT, selectedText);
6623                mEditor.mPreserveSelection = true;
6624                mTextView.startActivityForResult(intent, TextView.PROCESS_TEXT_REQUEST_CODE);
6625                return true;
6626            }
6627            return false;
6628        }
6629
6630        private void loadSupportedActivities() {
6631            mSupportedActivities.clear();
6632            if (!mContext.canStartActivityForResult()) {
6633                return;
6634            }
6635            PackageManager packageManager = mTextView.getContext().getPackageManager();
6636            List<ResolveInfo> unfiltered =
6637                    packageManager.queryIntentActivities(createProcessTextIntent(), 0);
6638            for (ResolveInfo info : unfiltered) {
6639                if (isSupportedActivity(info)) {
6640                    mSupportedActivities.add(info);
6641                }
6642            }
6643        }
6644
6645        private boolean isSupportedActivity(ResolveInfo info) {
6646            return mPackageName.equals(info.activityInfo.packageName)
6647                    || info.activityInfo.exported
6648                            && (info.activityInfo.permission == null
6649                                    || mContext.checkSelfPermission(info.activityInfo.permission)
6650                                            == PackageManager.PERMISSION_GRANTED);
6651        }
6652
6653        private Intent createProcessTextIntentForResolveInfo(ResolveInfo info) {
6654            return createProcessTextIntent()
6655                    .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, !mTextView.isTextEditable())
6656                    .setClassName(info.activityInfo.packageName, info.activityInfo.name);
6657        }
6658
6659        private Intent createProcessTextIntent() {
6660            return new Intent()
6661                    .setAction(Intent.ACTION_PROCESS_TEXT)
6662                    .setType("text/plain");
6663        }
6664
6665        private CharSequence getLabel(ResolveInfo resolveInfo) {
6666            return resolveInfo.loadLabel(mPackageManager);
6667        }
6668    }
6669}
6670