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