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