Editor.java revision 6eecdc934c6050d67a639116cde600c09e5b76bd
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.widget.AdapterView.OnItemClickListener;
110import android.widget.TextView.Drawables;
111import android.widget.TextView.OnEditorActionListener;
112
113import com.android.internal.annotations.VisibleForTesting;
114import com.android.internal.logging.MetricsLogger;
115import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
116import com.android.internal.util.ArrayUtils;
117import com.android.internal.util.GrowingArrayUtils;
118import com.android.internal.util.Preconditions;
119import com.android.internal.widget.EditableInputConnection;
120
121import java.lang.annotation.Retention;
122import java.lang.annotation.RetentionPolicy;
123import java.text.BreakIterator;
124import java.util.ArrayList;
125import java.util.Arrays;
126import java.util.Comparator;
127import java.util.HashMap;
128import java.util.List;
129
130
131/**
132 * Helper class used by TextView to handle editable text views.
133 *
134 * @hide
135 */
136public class Editor {
137    private static final String TAG = "Editor";
138    private static final boolean DEBUG_UNDO = false;
139
140    static final int BLINK = 500;
141    private static final int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
142    private static final float LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS = 0.5f;
143    private static final int UNSET_X_VALUE = -1;
144    private static final int UNSET_LINE = -1;
145    // Tag used when the Editor maintains its own separate UndoManager.
146    private static final String UNDO_OWNER_TAG = "Editor";
147
148    // Ordering constants used to place the Action Mode or context menu items in their menu.
149    private static final int MENU_ITEM_ORDER_ASSIST = 0;
150    private static final int MENU_ITEM_ORDER_UNDO = 2;
151    private static final int MENU_ITEM_ORDER_REDO = 3;
152    private static final int MENU_ITEM_ORDER_CUT = 4;
153    private static final int MENU_ITEM_ORDER_COPY = 5;
154    private static final int MENU_ITEM_ORDER_PASTE = 6;
155    private static final int MENU_ITEM_ORDER_SHARE = 7;
156    private static final int MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT = 8;
157    private static final int MENU_ITEM_ORDER_SELECT_ALL = 9;
158    private static final int MENU_ITEM_ORDER_REPLACE = 10;
159    private static final int MENU_ITEM_ORDER_AUTOFILL = 11;
160    private static final int MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START = 100;
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    private 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 SelectionActionModeHelper mSelectionActionModeHelper;
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 final 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            invalidateActionModeAsync();
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));
1919
1920        if (mCursorCount == 2) {
1921            updateCursorPosition(1, middle, bottom, layout.getSecondaryHorizontal(offset, clamped));
1922        }
1923    }
1924
1925    void refreshTextActionMode() {
1926        if (extractedTextModeWillBeStarted()) {
1927            mRestartActionModeOnNextRefresh = false;
1928            return;
1929        }
1930        final boolean hasSelection = mTextView.hasSelection();
1931        final SelectionModifierCursorController selectionController = getSelectionController();
1932        final InsertionPointCursorController insertionController = getInsertionController();
1933        if ((selectionController != null && selectionController.isCursorBeingModified())
1934                || (insertionController != null && insertionController.isCursorBeingModified())) {
1935            // ActionMode should be managed by the currently active cursor controller.
1936            mRestartActionModeOnNextRefresh = false;
1937            return;
1938        }
1939        if (hasSelection) {
1940            hideInsertionPointCursorController();
1941            if (mTextActionMode == null) {
1942                if (mRestartActionModeOnNextRefresh) {
1943                    // To avoid distraction, newly start action mode only when selection action
1944                    // mode is being restarted.
1945                    startSelectionActionMode();
1946                }
1947            } else if (selectionController == null || !selectionController.isActive()) {
1948                // Insertion action mode is active. Avoid dismissing the selection.
1949                stopTextActionModeWithPreservingSelection();
1950                startSelectionActionMode();
1951            } else {
1952                mTextActionMode.invalidateContentRect();
1953            }
1954        } else {
1955            // Insertion action mode is started only when insertion controller is explicitly
1956            // activated.
1957            if (insertionController == null || !insertionController.isActive()) {
1958                stopTextActionMode();
1959            } else if (mTextActionMode != null) {
1960                mTextActionMode.invalidateContentRect();
1961            }
1962        }
1963        mRestartActionModeOnNextRefresh = false;
1964    }
1965
1966    /**
1967     * Start an Insertion action mode.
1968     */
1969    void startInsertionActionMode() {
1970        if (mInsertionActionModeRunnable != null) {
1971            mTextView.removeCallbacks(mInsertionActionModeRunnable);
1972        }
1973        if (extractedTextModeWillBeStarted()) {
1974            return;
1975        }
1976        stopTextActionMode();
1977
1978        ActionMode.Callback actionModeCallback =
1979                new TextActionModeCallback(false /* hasSelection */);
1980        mTextActionMode = mTextView.startActionMode(
1981                actionModeCallback, ActionMode.TYPE_FLOATING);
1982        if (mTextActionMode != null && getInsertionController() != null) {
1983            getInsertionController().show();
1984        }
1985    }
1986
1987    @NonNull
1988    TextView getTextView() {
1989        return mTextView;
1990    }
1991
1992    @Nullable
1993    ActionMode getTextActionMode() {
1994        return mTextActionMode;
1995    }
1996
1997    void setRestartActionModeOnNextRefresh(boolean value) {
1998        mRestartActionModeOnNextRefresh = value;
1999    }
2000
2001    /**
2002     * Asynchronously starts a selection action mode using the TextClassifier.
2003     */
2004    void startSelectionActionModeAsync() {
2005        getSelectionActionModeHelper().startActionModeAsync();
2006    }
2007
2008    /**
2009     * Synchronously starts a selection action mode without the TextClassifier.
2010     */
2011    void startSelectionActionMode() {
2012        getSelectionActionModeHelper().startActionMode();
2013    }
2014
2015    /**
2016     * Asynchronously invalidates an action mode using the TextClassifier.
2017     */
2018    private void invalidateActionModeAsync() {
2019        getSelectionActionModeHelper().invalidateActionModeAsync();
2020    }
2021
2022    private SelectionActionModeHelper getSelectionActionModeHelper() {
2023        if (mSelectionActionModeHelper == null) {
2024            mSelectionActionModeHelper = new SelectionActionModeHelper(this);
2025        }
2026        return mSelectionActionModeHelper;
2027    }
2028
2029    /**
2030     * If the TextView allows text selection, selects the current word when no existing selection
2031     * was available and starts a drag.
2032     *
2033     * @return true if the drag was started.
2034     */
2035    private boolean selectCurrentWordAndStartDrag() {
2036        if (mInsertionActionModeRunnable != null) {
2037            mTextView.removeCallbacks(mInsertionActionModeRunnable);
2038        }
2039        if (extractedTextModeWillBeStarted()) {
2040            return false;
2041        }
2042        if (!checkField()) {
2043            return false;
2044        }
2045        if (!mTextView.hasSelection() && !selectCurrentWord()) {
2046            // No selection and cannot select a word.
2047            return false;
2048        }
2049        stopTextActionModeWithPreservingSelection();
2050        getSelectionController().enterDrag(
2051                SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_WORD);
2052        return true;
2053    }
2054
2055    /**
2056     * Checks whether a selection can be performed on the current TextView.
2057     *
2058     * @return true if a selection can be performed
2059     */
2060    boolean checkField() {
2061        if (!mTextView.canSelectText() || !mTextView.requestFocus()) {
2062            Log.w(TextView.LOG_TAG,
2063                    "TextView does not support text selection. Selection cancelled.");
2064            return false;
2065        }
2066        return true;
2067    }
2068
2069    boolean startSelectionActionModeInternal() {
2070        if (extractedTextModeWillBeStarted()) {
2071            return false;
2072        }
2073        if (mTextActionMode != null) {
2074            // Text action mode is already started
2075            invalidateActionModeAsync();
2076            return false;
2077        }
2078
2079        if (!checkField() || !mTextView.hasSelection()) {
2080            return false;
2081        }
2082
2083        ActionMode.Callback actionModeCallback =
2084                new TextActionModeCallback(true /* hasSelection */);
2085        mTextActionMode = mTextView.startActionMode(actionModeCallback, ActionMode.TYPE_FLOATING);
2086
2087        final boolean selectionStarted = mTextActionMode != null;
2088        if (selectionStarted && !mTextView.isTextSelectable() && mShowSoftInputOnFocus) {
2089            // Show the IME to be able to replace text, except when selecting non editable text.
2090            final InputMethodManager imm = InputMethodManager.peekInstance();
2091            if (imm != null) {
2092                imm.showSoftInput(mTextView, 0, null);
2093            }
2094        }
2095        return selectionStarted;
2096    }
2097
2098    private boolean extractedTextModeWillBeStarted() {
2099        if (!(mTextView.isInExtractedMode())) {
2100            final InputMethodManager imm = InputMethodManager.peekInstance();
2101            return  imm != null && imm.isFullscreenMode();
2102        }
2103        return false;
2104    }
2105
2106    /**
2107     * @return <code>true</code> if it's reasonable to offer to show suggestions depending on
2108     * the current cursor position or selection range. This method is consistent with the
2109     * method to show suggestions {@link SuggestionsPopupWindow#updateSuggestions}.
2110     */
2111    private boolean shouldOfferToShowSuggestions() {
2112        CharSequence text = mTextView.getText();
2113        if (!(text instanceof Spannable)) return false;
2114
2115        final Spannable spannable = (Spannable) text;
2116        final int selectionStart = mTextView.getSelectionStart();
2117        final int selectionEnd = mTextView.getSelectionEnd();
2118        final SuggestionSpan[] suggestionSpans = spannable.getSpans(selectionStart, selectionEnd,
2119                SuggestionSpan.class);
2120        if (suggestionSpans.length == 0) {
2121            return false;
2122        }
2123        if (selectionStart == selectionEnd) {
2124            // Spans overlap the cursor.
2125            for (int i = 0; i < suggestionSpans.length; i++) {
2126                if (suggestionSpans[i].getSuggestions().length > 0) {
2127                    return true;
2128                }
2129            }
2130            return false;
2131        }
2132        int minSpanStart = mTextView.getText().length();
2133        int maxSpanEnd = 0;
2134        int unionOfSpansCoveringSelectionStartStart = mTextView.getText().length();
2135        int unionOfSpansCoveringSelectionStartEnd = 0;
2136        boolean hasValidSuggestions = false;
2137        for (int i = 0; i < suggestionSpans.length; i++) {
2138            final int spanStart = spannable.getSpanStart(suggestionSpans[i]);
2139            final int spanEnd = spannable.getSpanEnd(suggestionSpans[i]);
2140            minSpanStart = Math.min(minSpanStart, spanStart);
2141            maxSpanEnd = Math.max(maxSpanEnd, spanEnd);
2142            if (selectionStart < spanStart || selectionStart > spanEnd) {
2143                // The span doesn't cover the current selection start point.
2144                continue;
2145            }
2146            hasValidSuggestions =
2147                    hasValidSuggestions || suggestionSpans[i].getSuggestions().length > 0;
2148            unionOfSpansCoveringSelectionStartStart =
2149                    Math.min(unionOfSpansCoveringSelectionStartStart, spanStart);
2150            unionOfSpansCoveringSelectionStartEnd =
2151                    Math.max(unionOfSpansCoveringSelectionStartEnd, spanEnd);
2152        }
2153        if (!hasValidSuggestions) {
2154            return false;
2155        }
2156        if (unionOfSpansCoveringSelectionStartStart >= unionOfSpansCoveringSelectionStartEnd) {
2157            // No spans cover the selection start point.
2158            return false;
2159        }
2160        if (minSpanStart < unionOfSpansCoveringSelectionStartStart
2161                || maxSpanEnd > unionOfSpansCoveringSelectionStartEnd) {
2162            // There is a span that is not covered by the union. In this case, we soouldn't offer
2163            // to show suggestions as it's confusing.
2164            return false;
2165        }
2166        return true;
2167    }
2168
2169    /**
2170     * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with
2171     * {@link SuggestionSpan#FLAG_EASY_CORRECT} set.
2172     */
2173    private boolean isCursorInsideEasyCorrectionSpan() {
2174        Spannable spannable = (Spannable) mTextView.getText();
2175        SuggestionSpan[] suggestionSpans = spannable.getSpans(mTextView.getSelectionStart(),
2176                mTextView.getSelectionEnd(), SuggestionSpan.class);
2177        for (int i = 0; i < suggestionSpans.length; i++) {
2178            if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) {
2179                return true;
2180            }
2181        }
2182        return false;
2183    }
2184
2185    void onTouchUpEvent(MotionEvent event) {
2186        if (getSelectionActionModeHelper().resetOriginalSelection(
2187                getTextView().getOffsetForPosition(event.getX(), event.getY()))) {
2188            return;
2189        }
2190
2191        boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect();
2192        hideCursorAndSpanControllers();
2193        stopTextActionMode();
2194        CharSequence text = mTextView.getText();
2195        if (!selectAllGotFocus && text.length() > 0) {
2196            // Move cursor
2197            final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
2198            Selection.setSelection((Spannable) text, offset);
2199            if (mSpellChecker != null) {
2200                // When the cursor moves, the word that was typed may need spell check
2201                mSpellChecker.onSelectionChanged();
2202            }
2203
2204            if (!extractedTextModeWillBeStarted()) {
2205                if (isCursorInsideEasyCorrectionSpan()) {
2206                    // Cancel the single tap delayed runnable.
2207                    if (mInsertionActionModeRunnable != null) {
2208                        mTextView.removeCallbacks(mInsertionActionModeRunnable);
2209                    }
2210
2211                    mShowSuggestionRunnable = new Runnable() {
2212                        public void run() {
2213                            replace();
2214                        }
2215                    };
2216                    // removeCallbacks is performed on every touch
2217                    mTextView.postDelayed(mShowSuggestionRunnable,
2218                            ViewConfiguration.getDoubleTapTimeout());
2219                } else if (hasInsertionController()) {
2220                    getInsertionController().show();
2221                }
2222            }
2223        }
2224    }
2225
2226    protected void stopTextActionMode() {
2227        if (mTextActionMode != null) {
2228            // This will hide the mSelectionModifierCursorController
2229            mTextActionMode.finish();
2230        }
2231    }
2232
2233    private void stopTextActionModeWithPreservingSelection() {
2234        if (mTextActionMode != null) {
2235            mRestartActionModeOnNextRefresh = true;
2236        }
2237        mPreserveSelection = true;
2238        stopTextActionMode();
2239        mPreserveSelection = false;
2240    }
2241
2242    /**
2243     * @return True if this view supports insertion handles.
2244     */
2245    boolean hasInsertionController() {
2246        return mInsertionControllerEnabled;
2247    }
2248
2249    /**
2250     * @return True if this view supports selection handles.
2251     */
2252    boolean hasSelectionController() {
2253        return mSelectionControllerEnabled;
2254    }
2255
2256    private InsertionPointCursorController getInsertionController() {
2257        if (!mInsertionControllerEnabled) {
2258            return null;
2259        }
2260
2261        if (mInsertionPointCursorController == null) {
2262            mInsertionPointCursorController = new InsertionPointCursorController();
2263
2264            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
2265            observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
2266        }
2267
2268        return mInsertionPointCursorController;
2269    }
2270
2271    @Nullable
2272    SelectionModifierCursorController getSelectionController() {
2273        if (!mSelectionControllerEnabled) {
2274            return null;
2275        }
2276
2277        if (mSelectionModifierCursorController == null) {
2278            mSelectionModifierCursorController = new SelectionModifierCursorController();
2279
2280            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
2281            observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
2282        }
2283
2284        return mSelectionModifierCursorController;
2285    }
2286
2287    @VisibleForTesting
2288    public Drawable[] getCursorDrawable() {
2289        return mCursorDrawable;
2290    }
2291
2292    private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) {
2293        if (mCursorDrawable[cursorIndex] == null) {
2294            mCursorDrawable[cursorIndex] = mTextView.getContext().getDrawable(
2295                    mTextView.mCursorDrawableRes);
2296        }
2297        final Drawable drawable = mCursorDrawable[cursorIndex];
2298        final int left = clampHorizontalPosition(drawable, horizontal);
2299        final int width = drawable.getIntrinsicWidth();
2300        drawable.setBounds(left, top - mTempRect.top, left + width,
2301                bottom + mTempRect.bottom);
2302    }
2303
2304    /**
2305     * Return clamped position for the drawable. If the drawable is within the boundaries of the
2306     * view, then it is offset with the left padding of the cursor drawable. If the drawable is at
2307     * the beginning or the end of the text then its drawable edge is aligned with left or right of
2308     * the view boundary. If the drawable is null, horizontal parameter is aligned to left or right
2309     * of the view.
2310     *
2311     * @param drawable Drawable. Can be null.
2312     * @param horizontal Horizontal position for the drawable.
2313     * @return The clamped horizontal position for the drawable.
2314     */
2315    private int clampHorizontalPosition(@Nullable final Drawable drawable, float horizontal) {
2316        horizontal = Math.max(0.5f, horizontal - 0.5f);
2317        if (mTempRect == null) mTempRect = new Rect();
2318
2319        int drawableWidth = 0;
2320        if (drawable != null) {
2321            drawable.getPadding(mTempRect);
2322            drawableWidth = drawable.getIntrinsicWidth();
2323        } else {
2324            mTempRect.setEmpty();
2325        }
2326
2327        int scrollX = mTextView.getScrollX();
2328        float horizontalDiff = horizontal - scrollX;
2329        int viewClippedWidth = mTextView.getWidth() - mTextView.getCompoundPaddingLeft()
2330                - mTextView.getCompoundPaddingRight();
2331
2332        final int left;
2333        if (horizontalDiff >= (viewClippedWidth - 1f)) {
2334            // at the rightmost position
2335            left = viewClippedWidth + scrollX - (drawableWidth - mTempRect.right);
2336        } else if (Math.abs(horizontalDiff) <= 1f
2337                || (TextUtils.isEmpty(mTextView.getText())
2338                        && (TextView.VERY_WIDE - scrollX) <= (viewClippedWidth + 1f)
2339                        && horizontal <= 1f)) {
2340            // at the leftmost position
2341            left = scrollX - mTempRect.left;
2342        } else {
2343            left = (int) horizontal - mTempRect.left;
2344        }
2345        return left;
2346    }
2347
2348    /**
2349     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
2350     * a dictionary) from the current input method, provided by it calling
2351     * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
2352     * implementation flashes the background of the corrected word to provide feedback to the user.
2353     *
2354     * @param info The auto correct info about the text that was corrected.
2355     */
2356    public void onCommitCorrection(CorrectionInfo info) {
2357        if (mCorrectionHighlighter == null) {
2358            mCorrectionHighlighter = new CorrectionHighlighter();
2359        } else {
2360            mCorrectionHighlighter.invalidate(false);
2361        }
2362
2363        mCorrectionHighlighter.highlight(info);
2364        mUndoInputFilter.freezeLastEdit();
2365    }
2366
2367    void onScrollChanged() {
2368        if (mPositionListener != null) {
2369            mPositionListener.onScrollChanged();
2370        }
2371        if (mTextActionMode != null) {
2372            mTextActionMode.invalidateContentRect();
2373        }
2374    }
2375
2376    /**
2377     * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
2378     */
2379    private boolean shouldBlink() {
2380        if (!isCursorVisible() || !mTextView.isFocused()) return false;
2381
2382        final int start = mTextView.getSelectionStart();
2383        if (start < 0) return false;
2384
2385        final int end = mTextView.getSelectionEnd();
2386        if (end < 0) return false;
2387
2388        return start == end;
2389    }
2390
2391    void makeBlink() {
2392        if (shouldBlink()) {
2393            mShowCursor = SystemClock.uptimeMillis();
2394            if (mBlink == null) mBlink = new Blink();
2395            mTextView.removeCallbacks(mBlink);
2396            mTextView.postDelayed(mBlink, BLINK);
2397        } else {
2398            if (mBlink != null) mTextView.removeCallbacks(mBlink);
2399        }
2400    }
2401
2402    private class Blink implements Runnable {
2403        private boolean mCancelled;
2404
2405        public void run() {
2406            if (mCancelled) {
2407                return;
2408            }
2409
2410            mTextView.removeCallbacks(this);
2411
2412            if (shouldBlink()) {
2413                if (mTextView.getLayout() != null) {
2414                    mTextView.invalidateCursorPath();
2415                }
2416
2417                mTextView.postDelayed(this, BLINK);
2418            }
2419        }
2420
2421        void cancel() {
2422            if (!mCancelled) {
2423                mTextView.removeCallbacks(this);
2424                mCancelled = true;
2425            }
2426        }
2427
2428        void uncancel() {
2429            mCancelled = false;
2430        }
2431    }
2432
2433    private DragShadowBuilder getTextThumbnailBuilder(int start, int end) {
2434        TextView shadowView = (TextView) View.inflate(mTextView.getContext(),
2435                com.android.internal.R.layout.text_drag_thumbnail, null);
2436
2437        if (shadowView == null) {
2438            throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
2439        }
2440
2441        if (end - start > DRAG_SHADOW_MAX_TEXT_LENGTH) {
2442            final long range = getCharClusterRange(start + DRAG_SHADOW_MAX_TEXT_LENGTH);
2443            end = TextUtils.unpackRangeEndFromLong(range);
2444        }
2445        final CharSequence text = mTextView.getTransformedText(start, end);
2446        shadowView.setText(text);
2447        shadowView.setTextColor(mTextView.getTextColors());
2448
2449        shadowView.setTextAppearance(R.styleable.Theme_textAppearanceLarge);
2450        shadowView.setGravity(Gravity.CENTER);
2451
2452        shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2453                ViewGroup.LayoutParams.WRAP_CONTENT));
2454
2455        final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
2456        shadowView.measure(size, size);
2457
2458        shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
2459        shadowView.invalidate();
2460        return new DragShadowBuilder(shadowView);
2461    }
2462
2463    private static class DragLocalState {
2464        public TextView sourceTextView;
2465        public int start, end;
2466
2467        public DragLocalState(TextView sourceTextView, int start, int end) {
2468            this.sourceTextView = sourceTextView;
2469            this.start = start;
2470            this.end = end;
2471        }
2472    }
2473
2474    void onDrop(DragEvent event) {
2475        SpannableStringBuilder content = new SpannableStringBuilder();
2476
2477        final DragAndDropPermissions permissions = DragAndDropPermissions.obtain(event);
2478        if (permissions != null) {
2479            permissions.takeTransient();
2480        }
2481
2482        try {
2483            ClipData clipData = event.getClipData();
2484            final int itemCount = clipData.getItemCount();
2485            for (int i = 0; i < itemCount; i++) {
2486                Item item = clipData.getItemAt(i);
2487                content.append(item.coerceToStyledText(mTextView.getContext()));
2488            }
2489        } finally {
2490            if (permissions != null) {
2491                permissions.release();
2492            }
2493        }
2494
2495        mTextView.beginBatchEdit();
2496        mUndoInputFilter.freezeLastEdit();
2497        try {
2498            final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
2499            Object localState = event.getLocalState();
2500            DragLocalState dragLocalState = null;
2501            if (localState instanceof DragLocalState) {
2502                dragLocalState = (DragLocalState) localState;
2503            }
2504            boolean dragDropIntoItself = dragLocalState != null
2505                    && dragLocalState.sourceTextView == mTextView;
2506
2507            if (dragDropIntoItself) {
2508                if (offset >= dragLocalState.start && offset < dragLocalState.end) {
2509                    // A drop inside the original selection discards the drop.
2510                    return;
2511                }
2512            }
2513
2514            final int originalLength = mTextView.getText().length();
2515            int min = offset;
2516            int max = offset;
2517
2518            Selection.setSelection((Spannable) mTextView.getText(), max);
2519            mTextView.replaceText_internal(min, max, content);
2520
2521            if (dragDropIntoItself) {
2522                int dragSourceStart = dragLocalState.start;
2523                int dragSourceEnd = dragLocalState.end;
2524                if (max <= dragSourceStart) {
2525                    // Inserting text before selection has shifted positions
2526                    final int shift = mTextView.getText().length() - originalLength;
2527                    dragSourceStart += shift;
2528                    dragSourceEnd += shift;
2529                }
2530
2531                // Delete original selection
2532                mTextView.deleteText_internal(dragSourceStart, dragSourceEnd);
2533
2534                // Make sure we do not leave two adjacent spaces.
2535                final int prevCharIdx = Math.max(0,  dragSourceStart - 1);
2536                final int nextCharIdx = Math.min(mTextView.getText().length(), dragSourceStart + 1);
2537                if (nextCharIdx > prevCharIdx + 1) {
2538                    CharSequence t = mTextView.getTransformedText(prevCharIdx, nextCharIdx);
2539                    if (Character.isSpaceChar(t.charAt(0)) && Character.isSpaceChar(t.charAt(1))) {
2540                        mTextView.deleteText_internal(prevCharIdx, prevCharIdx + 1);
2541                    }
2542                }
2543            }
2544        } finally {
2545            mTextView.endBatchEdit();
2546            mUndoInputFilter.freezeLastEdit();
2547        }
2548    }
2549
2550    public void addSpanWatchers(Spannable text) {
2551        final int textLength = text.length();
2552
2553        if (mKeyListener != null) {
2554            text.setSpan(mKeyListener, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2555        }
2556
2557        if (mSpanController == null) {
2558            mSpanController = new SpanController();
2559        }
2560        text.setSpan(mSpanController, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2561    }
2562
2563    void setContextMenuAnchor(float x, float y) {
2564        mContextMenuAnchorX = x;
2565        mContextMenuAnchorY = y;
2566    }
2567
2568    void onCreateContextMenu(ContextMenu menu) {
2569        if (mIsBeingLongClicked || Float.isNaN(mContextMenuAnchorX)
2570                || Float.isNaN(mContextMenuAnchorY)) {
2571            return;
2572        }
2573        final int offset = mTextView.getOffsetForPosition(mContextMenuAnchorX, mContextMenuAnchorY);
2574        if (offset == -1) {
2575            return;
2576        }
2577        stopTextActionModeWithPreservingSelection();
2578        final boolean isOnSelection = mTextView.hasSelection()
2579                && offset >= mTextView.getSelectionStart() && offset <= mTextView.getSelectionEnd();
2580        if (!isOnSelection) {
2581            // Right clicked position is not on the selection. Remove the selection and move the
2582            // cursor to the right clicked position.
2583            Selection.setSelection((Spannable) mTextView.getText(), offset);
2584            stopTextActionMode();
2585        }
2586
2587        if (shouldOfferToShowSuggestions()) {
2588            final SuggestionInfo[] suggestionInfoArray =
2589                    new SuggestionInfo[SuggestionSpan.SUGGESTIONS_MAX_SIZE];
2590            for (int i = 0; i < suggestionInfoArray.length; i++) {
2591                suggestionInfoArray[i] = new SuggestionInfo();
2592            }
2593            final SubMenu subMenu = menu.addSubMenu(Menu.NONE, Menu.NONE, MENU_ITEM_ORDER_REPLACE,
2594                    com.android.internal.R.string.replace);
2595            final int numItems = mSuggestionHelper.getSuggestionInfo(suggestionInfoArray, null);
2596            for (int i = 0; i < numItems; i++) {
2597                final SuggestionInfo info = suggestionInfoArray[i];
2598                subMenu.add(Menu.NONE, Menu.NONE, i, info.mText)
2599                        .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2600                            @Override
2601                            public boolean onMenuItemClick(MenuItem item) {
2602                                replaceWithSuggestion(info);
2603                                return true;
2604                            }
2605                        });
2606            }
2607        }
2608
2609        menu.add(Menu.NONE, TextView.ID_UNDO, MENU_ITEM_ORDER_UNDO,
2610                com.android.internal.R.string.undo)
2611                .setAlphabeticShortcut('z')
2612                .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2613                .setEnabled(mTextView.canUndo());
2614        menu.add(Menu.NONE, TextView.ID_REDO, MENU_ITEM_ORDER_REDO,
2615                com.android.internal.R.string.redo)
2616                .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2617                .setEnabled(mTextView.canRedo());
2618
2619        menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT,
2620                com.android.internal.R.string.cut)
2621                .setAlphabeticShortcut('x')
2622                .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2623                .setEnabled(mTextView.canCut());
2624        menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY,
2625                com.android.internal.R.string.copy)
2626                .setAlphabeticShortcut('c')
2627                .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2628                .setEnabled(mTextView.canCopy());
2629        menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE,
2630                com.android.internal.R.string.paste)
2631                .setAlphabeticShortcut('v')
2632                .setEnabled(mTextView.canPaste())
2633                .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2634        menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT,
2635                com.android.internal.R.string.paste_as_plain_text)
2636                .setEnabled(mTextView.canPaste())
2637                .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2638        menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE,
2639                com.android.internal.R.string.share)
2640                .setEnabled(mTextView.canShare())
2641                .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2642        menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL,
2643                com.android.internal.R.string.selectAll)
2644                .setAlphabeticShortcut('a')
2645                .setEnabled(mTextView.canSelectAllText())
2646                .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2647        menu.add(Menu.NONE, TextView.ID_AUTOFILL, MENU_ITEM_ORDER_AUTOFILL,
2648                com.android.internal.R.string.autofill)
2649                .setEnabled(mTextView.canRequestAutofill())
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);
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            if (mTextView.canRequestAutofill()) {
3836                menu.add(Menu.NONE, TextView.ID_AUTOFILL, MENU_ITEM_ORDER_AUTOFILL,
3837                        com.android.internal.R.string.autofill)
3838                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3839            }
3840
3841            updateSelectAllItem(menu);
3842            updateReplaceItem(menu);
3843        }
3844
3845        @Override
3846        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
3847            updateSelectAllItem(menu);
3848            updateReplaceItem(menu);
3849            updateAssistMenuItem(menu);
3850
3851            Callback customCallback = getCustomCallback();
3852            if (customCallback != null) {
3853                return customCallback.onPrepareActionMode(mode, menu);
3854            }
3855            return true;
3856        }
3857
3858        private void updateSelectAllItem(Menu menu) {
3859            boolean canSelectAll = mTextView.canSelectAllText();
3860            boolean selectAllItemExists = menu.findItem(TextView.ID_SELECT_ALL) != null;
3861            if (canSelectAll && !selectAllItemExists) {
3862                menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL,
3863                        com.android.internal.R.string.selectAll)
3864                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3865            } else if (!canSelectAll && selectAllItemExists) {
3866                menu.removeItem(TextView.ID_SELECT_ALL);
3867            }
3868        }
3869
3870        private void updateReplaceItem(Menu menu) {
3871            boolean canReplace = mTextView.isSuggestionsEnabled() && shouldOfferToShowSuggestions();
3872            boolean replaceItemExists = menu.findItem(TextView.ID_REPLACE) != null;
3873            if (canReplace && !replaceItemExists) {
3874                menu.add(Menu.NONE, TextView.ID_REPLACE, MENU_ITEM_ORDER_REPLACE,
3875                        com.android.internal.R.string.replace)
3876                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3877            } else if (!canReplace && replaceItemExists) {
3878                menu.removeItem(TextView.ID_REPLACE);
3879            }
3880        }
3881
3882        private void updateAssistMenuItem(Menu menu) {
3883            menu.removeItem(TextView.ID_ASSIST);
3884            final TextClassificationResult textClassificationResult =
3885                    getSelectionActionModeHelper().getTextClassificationResult();
3886            if (textClassificationResult != null) {
3887                final Drawable icon = textClassificationResult.getIcon();
3888                final CharSequence label = textClassificationResult.getLabel();
3889                final OnClickListener onClickListener =
3890                        textClassificationResult.getOnClickListener();
3891                final Intent intent = textClassificationResult.getIntent();
3892                if ((icon != null || !TextUtils.isEmpty(label))
3893                        && (onClickListener != null || intent != null)) {
3894                    menu.add(TextView.ID_ASSIST, TextView.ID_ASSIST, MENU_ITEM_ORDER_ASSIST, label)
3895                            .setIcon(icon)
3896                            .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
3897                }
3898            }
3899        }
3900
3901        @Override
3902        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
3903            if (mProcessTextIntentActionsHandler.performMenuItemAction(item)) {
3904                return true;
3905            }
3906            Callback customCallback = getCustomCallback();
3907            if (customCallback != null && customCallback.onActionItemClicked(mode, item)) {
3908                return true;
3909            }
3910            final TextClassificationResult textClassificationResult =
3911                    getSelectionActionModeHelper().getTextClassificationResult();
3912            if (TextView.ID_ASSIST == item.getItemId() && textClassificationResult != null) {
3913                final OnClickListener onClickListener =
3914                        textClassificationResult.getOnClickListener();
3915                if (onClickListener != null) {
3916                    onClickListener.onClick(mTextView);
3917                } else {
3918                    final Intent intent = textClassificationResult.getIntent();
3919                    if (intent != null) {
3920                        TextClassificationResult.createStartActivityOnClickListener(
3921                                mTextView.getContext(), intent)
3922                                .onClick(mTextView);
3923                    }
3924                }
3925                stopTextActionMode();
3926                return true;
3927            }
3928            return mTextView.onTextContextMenuItem(item.getItemId());
3929        }
3930
3931        @Override
3932        public void onDestroyActionMode(ActionMode mode) {
3933            // Clear mTextActionMode not to recursively destroy action mode by clearing selection.
3934            getSelectionActionModeHelper().onDestroyActionMode();
3935            mTextActionMode = null;
3936            Callback customCallback = getCustomCallback();
3937            if (customCallback != null) {
3938                customCallback.onDestroyActionMode(mode);
3939            }
3940
3941            if (!mPreserveSelection) {
3942                /*
3943                 * Leave current selection when we tentatively destroy action mode for the
3944                 * selection. If we're detaching from a window, we'll bring back the selection
3945                 * mode when (if) we get reattached.
3946                 */
3947                Selection.setSelection((Spannable) mTextView.getText(),
3948                        mTextView.getSelectionEnd());
3949            }
3950
3951            if (mSelectionModifierCursorController != null) {
3952                mSelectionModifierCursorController.hide();
3953            }
3954        }
3955
3956        @Override
3957        public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
3958            if (!view.equals(mTextView) || mTextView.getLayout() == null) {
3959                super.onGetContentRect(mode, view, outRect);
3960                return;
3961            }
3962            if (mTextView.getSelectionStart() != mTextView.getSelectionEnd()) {
3963                // We have a selection.
3964                mSelectionPath.reset();
3965                mTextView.getLayout().getSelectionPath(
3966                        mTextView.getSelectionStart(), mTextView.getSelectionEnd(), mSelectionPath);
3967                mSelectionPath.computeBounds(mSelectionBounds, true);
3968                mSelectionBounds.bottom += mHandleHeight;
3969            } else if (mCursorCount == 2) {
3970                // We have a split cursor. In this case, we take the rectangle that includes both
3971                // parts of the cursor to ensure we don't obscure either of them.
3972                Rect firstCursorBounds = mCursorDrawable[0].getBounds();
3973                Rect secondCursorBounds = mCursorDrawable[1].getBounds();
3974                mSelectionBounds.set(
3975                        Math.min(firstCursorBounds.left, secondCursorBounds.left),
3976                        Math.min(firstCursorBounds.top, secondCursorBounds.top),
3977                        Math.max(firstCursorBounds.right, secondCursorBounds.right),
3978                        Math.max(firstCursorBounds.bottom, secondCursorBounds.bottom)
3979                                + mHandleHeight);
3980            } else {
3981                // We have a single cursor.
3982                Layout layout = mTextView.getLayout();
3983                int line = layout.getLineForOffset(mTextView.getSelectionStart());
3984                float primaryHorizontal = clampHorizontalPosition(null,
3985                        layout.getPrimaryHorizontal(mTextView.getSelectionStart()));
3986                mSelectionBounds.set(
3987                        primaryHorizontal,
3988                        layout.getLineTop(line),
3989                        primaryHorizontal,
3990                        layout.getLineTop(line + 1) + mHandleHeight);
3991            }
3992            // Take TextView's padding and scroll into account.
3993            int textHorizontalOffset = mTextView.viewportToContentHorizontalOffset();
3994            int textVerticalOffset = mTextView.viewportToContentVerticalOffset();
3995            outRect.set(
3996                    (int) Math.floor(mSelectionBounds.left + textHorizontalOffset),
3997                    (int) Math.floor(mSelectionBounds.top + textVerticalOffset),
3998                    (int) Math.ceil(mSelectionBounds.right + textHorizontalOffset),
3999                    (int) Math.ceil(mSelectionBounds.bottom + textVerticalOffset));
4000        }
4001    }
4002
4003    /**
4004     * A listener to call {@link InputMethodManager#updateCursorAnchorInfo(View, CursorAnchorInfo)}
4005     * while the input method is requesting the cursor/anchor position. Does nothing as long as
4006     * {@link InputMethodManager#isWatchingCursor(View)} returns false.
4007     */
4008    private final class CursorAnchorInfoNotifier implements TextViewPositionListener {
4009        final CursorAnchorInfo.Builder mSelectionInfoBuilder = new CursorAnchorInfo.Builder();
4010        final int[] mTmpIntOffset = new int[2];
4011        final Matrix mViewToScreenMatrix = new Matrix();
4012
4013        @Override
4014        public void updatePosition(int parentPositionX, int parentPositionY,
4015                boolean parentPositionChanged, boolean parentScrolled) {
4016            final InputMethodState ims = mInputMethodState;
4017            if (ims == null || ims.mBatchEditNesting > 0) {
4018                return;
4019            }
4020            final InputMethodManager imm = InputMethodManager.peekInstance();
4021            if (null == imm) {
4022                return;
4023            }
4024            if (!imm.isActive(mTextView)) {
4025                return;
4026            }
4027            // Skip if the IME has not requested the cursor/anchor position.
4028            if (!imm.isCursorAnchorInfoEnabled()) {
4029                return;
4030            }
4031            Layout layout = mTextView.getLayout();
4032            if (layout == null) {
4033                return;
4034            }
4035
4036            final CursorAnchorInfo.Builder builder = mSelectionInfoBuilder;
4037            builder.reset();
4038
4039            final int selectionStart = mTextView.getSelectionStart();
4040            builder.setSelectionRange(selectionStart, mTextView.getSelectionEnd());
4041
4042            // Construct transformation matrix from view local coordinates to screen coordinates.
4043            mViewToScreenMatrix.set(mTextView.getMatrix());
4044            mTextView.getLocationOnScreen(mTmpIntOffset);
4045            mViewToScreenMatrix.postTranslate(mTmpIntOffset[0], mTmpIntOffset[1]);
4046            builder.setMatrix(mViewToScreenMatrix);
4047
4048            final float viewportToContentHorizontalOffset =
4049                    mTextView.viewportToContentHorizontalOffset();
4050            final float viewportToContentVerticalOffset =
4051                    mTextView.viewportToContentVerticalOffset();
4052
4053            final CharSequence text = mTextView.getText();
4054            if (text instanceof Spannable) {
4055                final Spannable sp = (Spannable) text;
4056                int composingTextStart = EditableInputConnection.getComposingSpanStart(sp);
4057                int composingTextEnd = EditableInputConnection.getComposingSpanEnd(sp);
4058                if (composingTextEnd < composingTextStart) {
4059                    final int temp = composingTextEnd;
4060                    composingTextEnd = composingTextStart;
4061                    composingTextStart = temp;
4062                }
4063                final boolean hasComposingText =
4064                        (0 <= composingTextStart) && (composingTextStart < composingTextEnd);
4065                if (hasComposingText) {
4066                    final CharSequence composingText = text.subSequence(composingTextStart,
4067                            composingTextEnd);
4068                    builder.setComposingText(composingTextStart, composingText);
4069                    mTextView.populateCharacterBounds(builder, composingTextStart,
4070                            composingTextEnd, viewportToContentHorizontalOffset,
4071                            viewportToContentVerticalOffset);
4072                }
4073            }
4074
4075            // Treat selectionStart as the insertion point.
4076            if (0 <= selectionStart) {
4077                final int offset = selectionStart;
4078                final int line = layout.getLineForOffset(offset);
4079                final float insertionMarkerX = layout.getPrimaryHorizontal(offset)
4080                        + viewportToContentHorizontalOffset;
4081                final float insertionMarkerTop = layout.getLineTop(line)
4082                        + viewportToContentVerticalOffset;
4083                final float insertionMarkerBaseline = layout.getLineBaseline(line)
4084                        + viewportToContentVerticalOffset;
4085                final float insertionMarkerBottom = layout.getLineBottom(line)
4086                        + viewportToContentVerticalOffset;
4087                final boolean isTopVisible = mTextView
4088                        .isPositionVisible(insertionMarkerX, insertionMarkerTop);
4089                final boolean isBottomVisible = mTextView
4090                        .isPositionVisible(insertionMarkerX, insertionMarkerBottom);
4091                int insertionMarkerFlags = 0;
4092                if (isTopVisible || isBottomVisible) {
4093                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
4094                }
4095                if (!isTopVisible || !isBottomVisible) {
4096                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
4097                }
4098                if (layout.isRtlCharAt(offset)) {
4099                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_IS_RTL;
4100                }
4101                builder.setInsertionMarkerLocation(insertionMarkerX, insertionMarkerTop,
4102                        insertionMarkerBaseline, insertionMarkerBottom, insertionMarkerFlags);
4103            }
4104
4105            imm.updateCursorAnchorInfo(mTextView, builder.build());
4106        }
4107    }
4108
4109    @VisibleForTesting
4110    public abstract class HandleView extends View implements TextViewPositionListener {
4111        protected Drawable mDrawable;
4112        protected Drawable mDrawableLtr;
4113        protected Drawable mDrawableRtl;
4114        private final PopupWindow mContainer;
4115        // Position with respect to the parent TextView
4116        private int mPositionX, mPositionY;
4117        private boolean mIsDragging;
4118        // Offset from touch position to mPosition
4119        private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
4120        protected int mHotspotX;
4121        protected int mHorizontalGravity;
4122        // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
4123        private float mTouchOffsetY;
4124        // Where the touch position should be on the handle to ensure a maximum cursor visibility
4125        private float mIdealVerticalOffset;
4126        // Parent's (TextView) previous position in window
4127        private int mLastParentX, mLastParentY;
4128        // Parent's (TextView) previous position on screen
4129        private int mLastParentXOnScreen, mLastParentYOnScreen;
4130        // Previous text character offset
4131        protected int mPreviousOffset = -1;
4132        // Previous text character offset
4133        private boolean mPositionHasChanged = true;
4134        // Minimum touch target size for handles
4135        private int mMinSize;
4136        // Indicates the line of text that the handle is on.
4137        protected int mPrevLine = UNSET_LINE;
4138        // Indicates the line of text that the user was touching. This can differ from mPrevLine
4139        // when selecting text when the handles jump to the end / start of words which may be on
4140        // a different line.
4141        protected int mPreviousLineTouched = UNSET_LINE;
4142
4143        private HandleView(Drawable drawableLtr, Drawable drawableRtl, final int id) {
4144            super(mTextView.getContext());
4145            setId(id);
4146            mContainer = new PopupWindow(mTextView.getContext(), null,
4147                    com.android.internal.R.attr.textSelectHandleWindowStyle);
4148            mContainer.setSplitTouchEnabled(true);
4149            mContainer.setClippingEnabled(false);
4150            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
4151            mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
4152            mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
4153            mContainer.setContentView(this);
4154
4155            mDrawableLtr = drawableLtr;
4156            mDrawableRtl = drawableRtl;
4157            mMinSize = mTextView.getContext().getResources().getDimensionPixelSize(
4158                    com.android.internal.R.dimen.text_handle_min_size);
4159
4160            updateDrawable();
4161
4162            final int handleHeight = getPreferredHeight();
4163            mTouchOffsetY = -0.3f * handleHeight;
4164            mIdealVerticalOffset = 0.7f * handleHeight;
4165        }
4166
4167        public float getIdealVerticalOffset() {
4168            return mIdealVerticalOffset;
4169        }
4170
4171        protected void updateDrawable() {
4172            if (mIsDragging) {
4173                // Don't update drawable during dragging.
4174                return;
4175            }
4176            final Layout layout = mTextView.getLayout();
4177            if (layout == null) {
4178                return;
4179            }
4180            final int offset = getCurrentCursorOffset();
4181            final boolean isRtlCharAtOffset = isAtRtlRun(layout, offset);
4182            final Drawable oldDrawable = mDrawable;
4183            mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
4184            mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
4185            mHorizontalGravity = getHorizontalGravity(isRtlCharAtOffset);
4186            if (oldDrawable != mDrawable && isShowing()) {
4187                // Update popup window position.
4188                mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX
4189                        - getHorizontalOffset() + getCursorOffset();
4190                mPositionX += mTextView.viewportToContentHorizontalOffset();
4191                mPositionHasChanged = true;
4192                updatePosition(mLastParentX, mLastParentY, false, false);
4193                postInvalidate();
4194            }
4195        }
4196
4197        protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
4198        protected abstract int getHorizontalGravity(boolean isRtlRun);
4199
4200        // Touch-up filter: number of previous positions remembered
4201        private static final int HISTORY_SIZE = 5;
4202        private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
4203        private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
4204        private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
4205        private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
4206        private int mPreviousOffsetIndex = 0;
4207        private int mNumberPreviousOffsets = 0;
4208
4209        private void startTouchUpFilter(int offset) {
4210            mNumberPreviousOffsets = 0;
4211            addPositionToTouchUpFilter(offset);
4212        }
4213
4214        private void addPositionToTouchUpFilter(int offset) {
4215            mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
4216            mPreviousOffsets[mPreviousOffsetIndex] = offset;
4217            mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
4218            mNumberPreviousOffsets++;
4219        }
4220
4221        private void filterOnTouchUp() {
4222            final long now = SystemClock.uptimeMillis();
4223            int i = 0;
4224            int index = mPreviousOffsetIndex;
4225            final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
4226            while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
4227                i++;
4228                index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
4229            }
4230
4231            if (i > 0 && i < iMax
4232                    && (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
4233                positionAtCursorOffset(mPreviousOffsets[index], false);
4234            }
4235        }
4236
4237        public boolean offsetHasBeenChanged() {
4238            return mNumberPreviousOffsets > 1;
4239        }
4240
4241        @Override
4242        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
4243            setMeasuredDimension(getPreferredWidth(), getPreferredHeight());
4244        }
4245
4246        @Override
4247        public void invalidate() {
4248            super.invalidate();
4249            if (isShowing()) {
4250                positionAtCursorOffset(getCurrentCursorOffset(), true);
4251            }
4252        };
4253
4254        private int getPreferredWidth() {
4255            return Math.max(mDrawable.getIntrinsicWidth(), mMinSize);
4256        }
4257
4258        private int getPreferredHeight() {
4259            return Math.max(mDrawable.getIntrinsicHeight(), mMinSize);
4260        }
4261
4262        public void show() {
4263            if (isShowing()) return;
4264
4265            getPositionListener().addSubscriber(this, true /* local position may change */);
4266
4267            // Make sure the offset is always considered new, even when focusing at same position
4268            mPreviousOffset = -1;
4269            positionAtCursorOffset(getCurrentCursorOffset(), false);
4270        }
4271
4272        protected void dismiss() {
4273            mIsDragging = false;
4274            mContainer.dismiss();
4275            onDetached();
4276        }
4277
4278        public void hide() {
4279            dismiss();
4280
4281            getPositionListener().removeSubscriber(this);
4282        }
4283
4284        public boolean isShowing() {
4285            return mContainer.isShowing();
4286        }
4287
4288        private boolean isVisible() {
4289            // Always show a dragging handle.
4290            if (mIsDragging) {
4291                return true;
4292            }
4293
4294            if (mTextView.isInBatchEditMode()) {
4295                return false;
4296            }
4297
4298            return mTextView.isPositionVisible(
4299                    mPositionX + mHotspotX + getHorizontalOffset(), mPositionY);
4300        }
4301
4302        public abstract int getCurrentCursorOffset();
4303
4304        protected abstract void updateSelection(int offset);
4305
4306        public abstract void updatePosition(float x, float y);
4307
4308        protected boolean isAtRtlRun(@NonNull Layout layout, int offset) {
4309            return layout.isRtlCharAt(offset);
4310        }
4311
4312        @VisibleForTesting
4313        public float getHorizontal(@NonNull Layout layout, int offset) {
4314            return layout.getPrimaryHorizontal(offset);
4315        }
4316
4317        protected int getOffsetAtCoordinate(@NonNull Layout layout, int line, float x) {
4318            return mTextView.getOffsetAtCoordinate(line, x);
4319        }
4320
4321        /**
4322         * @param offset Cursor offset. Must be in [-1, length].
4323         * @param forceUpdatePosition whether to force update the position.  This should be true
4324         * when If the parent has been scrolled, for example.
4325         */
4326        protected void positionAtCursorOffset(int offset, boolean forceUpdatePosition) {
4327            // A HandleView relies on the layout, which may be nulled by external methods
4328            Layout layout = mTextView.getLayout();
4329            if (layout == null) {
4330                // Will update controllers' state, hiding them and stopping selection mode if needed
4331                prepareCursorControllers();
4332                return;
4333            }
4334            layout = mTextView.getLayout();
4335
4336            boolean offsetChanged = offset != mPreviousOffset;
4337            if (offsetChanged || forceUpdatePosition) {
4338                if (offsetChanged) {
4339                    updateSelection(offset);
4340                    addPositionToTouchUpFilter(offset);
4341                }
4342                final int line = layout.getLineForOffset(offset);
4343                mPrevLine = line;
4344
4345                mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX
4346                        - getHorizontalOffset() + getCursorOffset();
4347                mPositionY = layout.getLineBottom(line);
4348
4349                // Take TextView's padding and scroll into account.
4350                mPositionX += mTextView.viewportToContentHorizontalOffset();
4351                mPositionY += mTextView.viewportToContentVerticalOffset();
4352
4353                mPreviousOffset = offset;
4354                mPositionHasChanged = true;
4355            }
4356        }
4357
4358        /**
4359         * Return the clamped horizontal position for the first cursor.
4360         *
4361         * @param layout Text layout.
4362         * @param offset Character offset for the cursor.
4363         * @return The clamped horizontal position for the cursor.
4364         */
4365        int getCursorHorizontalPosition(Layout layout, int offset) {
4366            return (int) (getHorizontal(layout, offset) - 0.5f);
4367        }
4368
4369        @Override
4370        public void updatePosition(int parentPositionX, int parentPositionY,
4371                boolean parentPositionChanged, boolean parentScrolled) {
4372            positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled);
4373            if (parentPositionChanged || mPositionHasChanged) {
4374                if (mIsDragging) {
4375                    // Update touchToWindow offset in case of parent scrolling while dragging
4376                    if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
4377                        mTouchToWindowOffsetX += parentPositionX - mLastParentX;
4378                        mTouchToWindowOffsetY += parentPositionY - mLastParentY;
4379                        mLastParentX = parentPositionX;
4380                        mLastParentY = parentPositionY;
4381                    }
4382
4383                    onHandleMoved();
4384                }
4385
4386                if (isVisible()) {
4387                    // Transform to the window coordinates to follow the view tranformation.
4388                    final int[] pts = { mPositionX + mHotspotX + getHorizontalOffset(), mPositionY};
4389                    mTextView.transformFromViewToWindowSpace(pts);
4390                    pts[0] -= mHotspotX + getHorizontalOffset();
4391
4392                    if (isShowing()) {
4393                        mContainer.update(pts[0], pts[1], -1, -1);
4394                    } else {
4395                        mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY, pts[0], pts[1]);
4396                    }
4397                } else {
4398                    if (isShowing()) {
4399                        dismiss();
4400                    }
4401                }
4402
4403                mPositionHasChanged = false;
4404            }
4405        }
4406
4407        @Override
4408        protected void onDraw(Canvas c) {
4409            final int drawWidth = mDrawable.getIntrinsicWidth();
4410            final int left = getHorizontalOffset();
4411
4412            mDrawable.setBounds(left, 0, left + drawWidth, mDrawable.getIntrinsicHeight());
4413            mDrawable.draw(c);
4414        }
4415
4416        private int getHorizontalOffset() {
4417            final int width = getPreferredWidth();
4418            final int drawWidth = mDrawable.getIntrinsicWidth();
4419            final int left;
4420            switch (mHorizontalGravity) {
4421                case Gravity.LEFT:
4422                    left = 0;
4423                    break;
4424                default:
4425                case Gravity.CENTER:
4426                    left = (width - drawWidth) / 2;
4427                    break;
4428                case Gravity.RIGHT:
4429                    left = width - drawWidth;
4430                    break;
4431            }
4432            return left;
4433        }
4434
4435        protected int getCursorOffset() {
4436            return 0;
4437        }
4438
4439        @Override
4440        public boolean onTouchEvent(MotionEvent ev) {
4441            updateFloatingToolbarVisibility(ev);
4442
4443            switch (ev.getActionMasked()) {
4444                case MotionEvent.ACTION_DOWN: {
4445                    startTouchUpFilter(getCurrentCursorOffset());
4446
4447                    final PositionListener positionListener = getPositionListener();
4448                    mLastParentX = positionListener.getPositionX();
4449                    mLastParentY = positionListener.getPositionY();
4450                    mLastParentXOnScreen = positionListener.getPositionXOnScreen();
4451                    mLastParentYOnScreen = positionListener.getPositionYOnScreen();
4452
4453                    final float xInWindow = ev.getRawX() - mLastParentXOnScreen + mLastParentX;
4454                    final float yInWindow = ev.getRawY() - mLastParentYOnScreen + mLastParentY;
4455                    mTouchToWindowOffsetX = xInWindow - mPositionX;
4456                    mTouchToWindowOffsetY = yInWindow - mPositionY;
4457
4458                    mIsDragging = true;
4459                    mPreviousLineTouched = UNSET_LINE;
4460                    break;
4461                }
4462
4463                case MotionEvent.ACTION_MOVE: {
4464                    final float xInWindow = ev.getRawX() - mLastParentXOnScreen + mLastParentX;
4465                    final float yInWindow = ev.getRawY() - mLastParentYOnScreen + mLastParentY;
4466
4467                    // Vertical hysteresis: vertical down movement tends to snap to ideal offset
4468                    final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
4469                    final float currentVerticalOffset = yInWindow - mPositionY - mLastParentY;
4470                    float newVerticalOffset;
4471                    if (previousVerticalOffset < mIdealVerticalOffset) {
4472                        newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
4473                        newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
4474                    } else {
4475                        newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
4476                        newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
4477                    }
4478                    mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
4479
4480                    final float newPosX =
4481                            xInWindow - mTouchToWindowOffsetX + mHotspotX + getHorizontalOffset();
4482                    final float newPosY = yInWindow - mTouchToWindowOffsetY + mTouchOffsetY;
4483
4484                    updatePosition(newPosX, newPosY);
4485                    break;
4486                }
4487
4488                case MotionEvent.ACTION_UP:
4489                    filterOnTouchUp();
4490                    mIsDragging = false;
4491                    updateDrawable();
4492                    break;
4493
4494                case MotionEvent.ACTION_CANCEL:
4495                    mIsDragging = false;
4496                    updateDrawable();
4497                    break;
4498            }
4499            return true;
4500        }
4501
4502        public boolean isDragging() {
4503            return mIsDragging;
4504        }
4505
4506        void onHandleMoved() {}
4507
4508        public void onDetached() {}
4509    }
4510
4511    private class InsertionHandleView extends HandleView {
4512        private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
4513        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
4514
4515        // Used to detect taps on the insertion handle, which will affect the insertion action mode
4516        private float mDownPositionX, mDownPositionY;
4517        private Runnable mHider;
4518
4519        public InsertionHandleView(Drawable drawable) {
4520            super(drawable, drawable, com.android.internal.R.id.insertion_handle);
4521        }
4522
4523        @Override
4524        public void show() {
4525            super.show();
4526
4527            final long durationSinceCutOrCopy =
4528                    SystemClock.uptimeMillis() - TextView.sLastCutCopyOrTextChangedTime;
4529
4530            // Cancel the single tap delayed runnable.
4531            if (mInsertionActionModeRunnable != null
4532                    && ((mTapState == TAP_STATE_DOUBLE_TAP)
4533                            || (mTapState == TAP_STATE_TRIPLE_CLICK)
4534                            || isCursorInsideEasyCorrectionSpan())) {
4535                mTextView.removeCallbacks(mInsertionActionModeRunnable);
4536            }
4537
4538            // Prepare and schedule the single tap runnable to run exactly after the double tap
4539            // timeout has passed.
4540            if ((mTapState != TAP_STATE_DOUBLE_TAP) && (mTapState != TAP_STATE_TRIPLE_CLICK)
4541                    && !isCursorInsideEasyCorrectionSpan()
4542                    && (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION)) {
4543                if (mTextActionMode == null) {
4544                    if (mInsertionActionModeRunnable == null) {
4545                        mInsertionActionModeRunnable = new Runnable() {
4546                            @Override
4547                            public void run() {
4548                                startInsertionActionMode();
4549                            }
4550                        };
4551                    }
4552                    mTextView.postDelayed(
4553                            mInsertionActionModeRunnable,
4554                            ViewConfiguration.getDoubleTapTimeout() + 1);
4555                }
4556
4557            }
4558
4559            hideAfterDelay();
4560        }
4561
4562        private void hideAfterDelay() {
4563            if (mHider == null) {
4564                mHider = new Runnable() {
4565                    public void run() {
4566                        hide();
4567                    }
4568                };
4569            } else {
4570                removeHiderCallback();
4571            }
4572            mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
4573        }
4574
4575        private void removeHiderCallback() {
4576            if (mHider != null) {
4577                mTextView.removeCallbacks(mHider);
4578            }
4579        }
4580
4581        @Override
4582        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4583            return drawable.getIntrinsicWidth() / 2;
4584        }
4585
4586        @Override
4587        protected int getHorizontalGravity(boolean isRtlRun) {
4588            return Gravity.CENTER_HORIZONTAL;
4589        }
4590
4591        @Override
4592        protected int getCursorOffset() {
4593            int offset = super.getCursorOffset();
4594            final Drawable cursor = mCursorCount > 0 ? mCursorDrawable[0] : null;
4595            if (cursor != null) {
4596                cursor.getPadding(mTempRect);
4597                offset += (cursor.getIntrinsicWidth() - mTempRect.left - mTempRect.right) / 2;
4598            }
4599            return offset;
4600        }
4601
4602        @Override
4603        int getCursorHorizontalPosition(Layout layout, int offset) {
4604            final Drawable drawable = mCursorCount > 0 ? mCursorDrawable[0] : null;
4605            if (drawable != null) {
4606                final float horizontal = getHorizontal(layout, offset);
4607                return clampHorizontalPosition(drawable, horizontal) + mTempRect.left;
4608            }
4609            return super.getCursorHorizontalPosition(layout, offset);
4610        }
4611
4612        @Override
4613        public boolean onTouchEvent(MotionEvent ev) {
4614            final boolean result = super.onTouchEvent(ev);
4615
4616            switch (ev.getActionMasked()) {
4617                case MotionEvent.ACTION_DOWN:
4618                    mDownPositionX = ev.getRawX();
4619                    mDownPositionY = ev.getRawY();
4620                    break;
4621
4622                case MotionEvent.ACTION_UP:
4623                    if (!offsetHasBeenChanged()) {
4624                        final float deltaX = mDownPositionX - ev.getRawX();
4625                        final float deltaY = mDownPositionY - ev.getRawY();
4626                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
4627
4628                        final ViewConfiguration viewConfiguration = ViewConfiguration.get(
4629                                mTextView.getContext());
4630                        final int touchSlop = viewConfiguration.getScaledTouchSlop();
4631
4632                        if (distanceSquared < touchSlop * touchSlop) {
4633                            // Tapping on the handle toggles the insertion action mode.
4634                            if (mTextActionMode != null) {
4635                                stopTextActionMode();
4636                            } else {
4637                                startInsertionActionMode();
4638                            }
4639                        }
4640                    } else {
4641                        if (mTextActionMode != null) {
4642                            mTextActionMode.invalidateContentRect();
4643                        }
4644                    }
4645                    hideAfterDelay();
4646                    break;
4647
4648                case MotionEvent.ACTION_CANCEL:
4649                    hideAfterDelay();
4650                    break;
4651
4652                default:
4653                    break;
4654            }
4655
4656            return result;
4657        }
4658
4659        @Override
4660        public int getCurrentCursorOffset() {
4661            return mTextView.getSelectionStart();
4662        }
4663
4664        @Override
4665        public void updateSelection(int offset) {
4666            Selection.setSelection((Spannable) mTextView.getText(), offset);
4667        }
4668
4669        @Override
4670        public void updatePosition(float x, float y) {
4671            Layout layout = mTextView.getLayout();
4672            int offset;
4673            if (layout != null) {
4674                if (mPreviousLineTouched == UNSET_LINE) {
4675                    mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
4676                }
4677                int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
4678                offset = getOffsetAtCoordinate(layout, currLine, x);
4679                mPreviousLineTouched = currLine;
4680            } else {
4681                offset = -1;
4682            }
4683            positionAtCursorOffset(offset, false);
4684            if (mTextActionMode != null) {
4685                invalidateActionModeAsync();
4686            }
4687        }
4688
4689        @Override
4690        void onHandleMoved() {
4691            super.onHandleMoved();
4692            removeHiderCallback();
4693        }
4694
4695        @Override
4696        public void onDetached() {
4697            super.onDetached();
4698            removeHiderCallback();
4699        }
4700    }
4701
4702    @Retention(RetentionPolicy.SOURCE)
4703    @IntDef({HANDLE_TYPE_SELECTION_START, HANDLE_TYPE_SELECTION_END})
4704    public @interface HandleType {}
4705    public static final int HANDLE_TYPE_SELECTION_START = 0;
4706    public static final int HANDLE_TYPE_SELECTION_END = 1;
4707
4708    private class SelectionHandleView extends HandleView {
4709        // Indicates the handle type, selection start (HANDLE_TYPE_SELECTION_START) or selection
4710        // end (HANDLE_TYPE_SELECTION_END).
4711        @HandleType
4712        private final int mHandleType;
4713        // Indicates whether the cursor is making adjustments within a word.
4714        private boolean mInWord = false;
4715        // Difference between touch position and word boundary position.
4716        private float mTouchWordDelta;
4717        // X value of the previous updatePosition call.
4718        private float mPrevX;
4719        // Indicates if the handle has moved a boundary between LTR and RTL text.
4720        private boolean mLanguageDirectionChanged = false;
4721        // Distance from edge of horizontally scrolling text view
4722        // to use to switch to character mode.
4723        private final float mTextViewEdgeSlop;
4724        // Used to save text view location.
4725        private final int[] mTextViewLocation = new int[2];
4726
4727        public SelectionHandleView(Drawable drawableLtr, Drawable drawableRtl, int id,
4728                @HandleType int handleType) {
4729            super(drawableLtr, drawableRtl, id);
4730            mHandleType = handleType;
4731            ViewConfiguration viewConfiguration = ViewConfiguration.get(mTextView.getContext());
4732            mTextViewEdgeSlop = viewConfiguration.getScaledTouchSlop() * 4;
4733        }
4734
4735        private boolean isStartHandle() {
4736            return mHandleType == HANDLE_TYPE_SELECTION_START;
4737        }
4738
4739        @Override
4740        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4741            if (isRtlRun == isStartHandle()) {
4742                return drawable.getIntrinsicWidth() / 4;
4743            } else {
4744                return (drawable.getIntrinsicWidth() * 3) / 4;
4745            }
4746        }
4747
4748        @Override
4749        protected int getHorizontalGravity(boolean isRtlRun) {
4750            return (isRtlRun == isStartHandle()) ? Gravity.LEFT : Gravity.RIGHT;
4751        }
4752
4753        @Override
4754        public int getCurrentCursorOffset() {
4755            return isStartHandle() ? mTextView.getSelectionStart() : mTextView.getSelectionEnd();
4756        }
4757
4758        @Override
4759        protected void updateSelection(int offset) {
4760            if (isStartHandle()) {
4761                Selection.setSelection((Spannable) mTextView.getText(), offset,
4762                        mTextView.getSelectionEnd());
4763            } else {
4764                Selection.setSelection((Spannable) mTextView.getText(),
4765                        mTextView.getSelectionStart(), offset);
4766            }
4767            updateDrawable();
4768            if (mTextActionMode != null) {
4769                invalidateActionModeAsync();
4770            }
4771        }
4772
4773        @Override
4774        public void updatePosition(float x, float y) {
4775            final Layout layout = mTextView.getLayout();
4776            if (layout == null) {
4777                // HandleView will deal appropriately in positionAtCursorOffset when
4778                // layout is null.
4779                positionAndAdjustForCrossingHandles(mTextView.getOffsetForPosition(x, y));
4780                return;
4781            }
4782
4783            if (mPreviousLineTouched == UNSET_LINE) {
4784                mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
4785            }
4786
4787            boolean positionCursor = false;
4788            final int anotherHandleOffset =
4789                    isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart();
4790            int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
4791            int initialOffset = getOffsetAtCoordinate(layout, currLine, x);
4792
4793            if (isStartHandle() && initialOffset >= anotherHandleOffset
4794                    || !isStartHandle() && initialOffset <= anotherHandleOffset) {
4795                // Handles have crossed, bound it to the first selected line and
4796                // adjust by word / char as normal.
4797                currLine = layout.getLineForOffset(anotherHandleOffset);
4798                initialOffset = getOffsetAtCoordinate(layout, currLine, x);
4799            }
4800
4801            int offset = initialOffset;
4802            final int wordEnd = getWordEnd(offset);
4803            final int wordStart = getWordStart(offset);
4804
4805            if (mPrevX == UNSET_X_VALUE) {
4806                mPrevX = x;
4807            }
4808
4809            final int currentOffset = getCurrentCursorOffset();
4810            final boolean rtlAtCurrentOffset = isAtRtlRun(layout, currentOffset);
4811            final boolean atRtl = isAtRtlRun(layout, offset);
4812            final boolean isLvlBoundary = layout.isLevelBoundary(offset);
4813
4814            // We can't determine if the user is expanding or shrinking the selection if they're
4815            // on a bi-di boundary, so until they've moved past the boundary we'll just place
4816            // the cursor at the current position.
4817            if (isLvlBoundary || (rtlAtCurrentOffset && !atRtl) || (!rtlAtCurrentOffset && atRtl)) {
4818                // We're on a boundary or this is the first direction change -- just update
4819                // to the current position.
4820                mLanguageDirectionChanged = true;
4821                mTouchWordDelta = 0.0f;
4822                positionAndAdjustForCrossingHandles(offset);
4823                return;
4824            } else if (mLanguageDirectionChanged && !isLvlBoundary) {
4825                // We've just moved past the boundary so update the position. After this we can
4826                // figure out if the user is expanding or shrinking to go by word or character.
4827                positionAndAdjustForCrossingHandles(offset);
4828                mTouchWordDelta = 0.0f;
4829                mLanguageDirectionChanged = false;
4830                return;
4831            }
4832
4833            boolean isExpanding;
4834            final float xDiff = x - mPrevX;
4835            if (isStartHandle()) {
4836                isExpanding = currLine < mPreviousLineTouched;
4837            } else {
4838                isExpanding = currLine > mPreviousLineTouched;
4839            }
4840            if (atRtl == isStartHandle()) {
4841                isExpanding |= xDiff > 0;
4842            } else {
4843                isExpanding |= xDiff < 0;
4844            }
4845
4846            if (mTextView.getHorizontallyScrolling()) {
4847                if (positionNearEdgeOfScrollingView(x, atRtl)
4848                        && ((isStartHandle() && mTextView.getScrollX() != 0)
4849                                || (!isStartHandle()
4850                                        && mTextView.canScrollHorizontally(atRtl ? -1 : 1)))
4851                        && ((isExpanding && ((isStartHandle() && offset < currentOffset)
4852                                || (!isStartHandle() && offset > currentOffset)))
4853                                        || !isExpanding)) {
4854                    // If we're expanding ensure that the offset is actually expanding compared to
4855                    // the current offset, if the handle snapped to the word, the finger position
4856                    // may be out of sync and we don't want the selection to jump back.
4857                    mTouchWordDelta = 0.0f;
4858                    final int nextOffset = (atRtl == isStartHandle())
4859                            ? layout.getOffsetToRightOf(mPreviousOffset)
4860                            : layout.getOffsetToLeftOf(mPreviousOffset);
4861                    positionAndAdjustForCrossingHandles(nextOffset);
4862                    return;
4863                }
4864            }
4865
4866            if (isExpanding) {
4867                // User is increasing the selection.
4868                int wordBoundary = isStartHandle() ? wordStart : wordEnd;
4869                final boolean snapToWord = (!mInWord
4870                        || (isStartHandle() ? currLine < mPrevLine : currLine > mPrevLine))
4871                                && atRtl == isAtRtlRun(layout, wordBoundary);
4872                if (snapToWord) {
4873                    // Sometimes words can be broken across lines (Chinese, hyphenation).
4874                    // We still snap to the word boundary but we only use the letters on the
4875                    // current line to determine if the user is far enough into the word to snap.
4876                    if (layout.getLineForOffset(wordBoundary) != currLine) {
4877                        wordBoundary = isStartHandle()
4878                                ? layout.getLineStart(currLine) : layout.getLineEnd(currLine);
4879                    }
4880                    final int offsetThresholdToSnap = isStartHandle()
4881                            ? wordEnd - ((wordEnd - wordBoundary) / 2)
4882                            : wordStart + ((wordBoundary - wordStart) / 2);
4883                    if (isStartHandle()
4884                            && (offset <= offsetThresholdToSnap || currLine < mPrevLine)) {
4885                        // User is far enough into the word or on a different line so we expand by
4886                        // word.
4887                        offset = wordStart;
4888                    } else 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 = wordEnd;
4893                    } else {
4894                        offset = mPreviousOffset;
4895                    }
4896                }
4897                if ((isStartHandle() && offset < initialOffset)
4898                        || (!isStartHandle() && offset > initialOffset)) {
4899                    final float adjustedX = getHorizontal(layout, offset);
4900                    mTouchWordDelta =
4901                            mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
4902                } else {
4903                    mTouchWordDelta = 0.0f;
4904                }
4905                positionCursor = true;
4906            } else {
4907                final int adjustedOffset =
4908                        getOffsetAtCoordinate(layout, currLine, x - mTouchWordDelta);
4909                final boolean shrinking = isStartHandle()
4910                        ? adjustedOffset > mPreviousOffset || currLine > mPrevLine
4911                        : adjustedOffset < mPreviousOffset || currLine < mPrevLine;
4912                if (shrinking) {
4913                    // User is shrinking the selection.
4914                    if (currLine != mPrevLine) {
4915                        // We're on a different line, so we'll snap to word boundaries.
4916                        offset = isStartHandle() ? wordStart : wordEnd;
4917                        if ((isStartHandle() && offset < initialOffset)
4918                                || (!isStartHandle() && offset > initialOffset)) {
4919                            final float adjustedX = getHorizontal(layout, offset);
4920                            mTouchWordDelta =
4921                                    mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
4922                        } else {
4923                            mTouchWordDelta = 0.0f;
4924                        }
4925                    } else {
4926                        offset = adjustedOffset;
4927                    }
4928                    positionCursor = true;
4929                } else if ((isStartHandle() && adjustedOffset < mPreviousOffset)
4930                        || (!isStartHandle() && adjustedOffset > mPreviousOffset)) {
4931                    // Handle has jumped to the word boundary, and the user is moving
4932                    // their finger towards the handle, the delta should be updated.
4933                    mTouchWordDelta = mTextView.convertToLocalHorizontalCoordinate(x)
4934                            - getHorizontal(layout, mPreviousOffset);
4935                }
4936            }
4937
4938            if (positionCursor) {
4939                mPreviousLineTouched = currLine;
4940                positionAndAdjustForCrossingHandles(offset);
4941            }
4942            mPrevX = x;
4943        }
4944
4945        @Override
4946        protected void positionAtCursorOffset(int offset, boolean forceUpdatePosition) {
4947            super.positionAtCursorOffset(offset, forceUpdatePosition);
4948            mInWord = (offset != -1) && !getWordIteratorWithText().isBoundary(offset);
4949        }
4950
4951        @Override
4952        public boolean onTouchEvent(MotionEvent event) {
4953            boolean superResult = super.onTouchEvent(event);
4954            if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
4955                // Reset the touch word offset and x value when the user
4956                // re-engages the handle.
4957                mTouchWordDelta = 0.0f;
4958                mPrevX = UNSET_X_VALUE;
4959            }
4960            return superResult;
4961        }
4962
4963        private void positionAndAdjustForCrossingHandles(int offset) {
4964            final int anotherHandleOffset =
4965                    isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart();
4966            if ((isStartHandle() && offset >= anotherHandleOffset)
4967                    || (!isStartHandle() && offset <= anotherHandleOffset)) {
4968                mTouchWordDelta = 0.0f;
4969                final Layout layout = mTextView.getLayout();
4970                if (layout != null && offset != anotherHandleOffset) {
4971                    final float horiz = getHorizontal(layout, offset);
4972                    final float anotherHandleHoriz = getHorizontal(layout, anotherHandleOffset,
4973                            !isStartHandle());
4974                    final float currentHoriz = getHorizontal(layout, mPreviousOffset);
4975                    if (currentHoriz < anotherHandleHoriz && horiz < anotherHandleHoriz
4976                            || currentHoriz > anotherHandleHoriz && horiz > anotherHandleHoriz) {
4977                        // This handle passes another one as it crossed a direction boundary.
4978                        // Don't minimize the selection, but keep the handle at the run boundary.
4979                        final int currentOffset = getCurrentCursorOffset();
4980                        final int offsetToGetRunRange = isStartHandle()
4981                                ? currentOffset : Math.max(currentOffset - 1, 0);
4982                        final long range = layout.getRunRange(offsetToGetRunRange);
4983                        if (isStartHandle()) {
4984                            offset = TextUtils.unpackRangeStartFromLong(range);
4985                        } else {
4986                            offset = TextUtils.unpackRangeEndFromLong(range);
4987                        }
4988                        positionAtCursorOffset(offset, false);
4989                        return;
4990                    }
4991                }
4992                // Handles can not cross and selection is at least one character.
4993                offset = getNextCursorOffset(anotherHandleOffset, !isStartHandle());
4994            }
4995            positionAtCursorOffset(offset, false);
4996        }
4997
4998        private boolean positionNearEdgeOfScrollingView(float x, boolean atRtl) {
4999            mTextView.getLocationOnScreen(mTextViewLocation);
5000            boolean nearEdge;
5001            if (atRtl == isStartHandle()) {
5002                int rightEdge = mTextViewLocation[0] + mTextView.getWidth()
5003                        - mTextView.getPaddingRight();
5004                nearEdge = x > rightEdge - mTextViewEdgeSlop;
5005            } else {
5006                int leftEdge = mTextViewLocation[0] + mTextView.getPaddingLeft();
5007                nearEdge = x < leftEdge + mTextViewEdgeSlop;
5008            }
5009            return nearEdge;
5010        }
5011
5012        @Override
5013        protected boolean isAtRtlRun(@NonNull Layout layout, int offset) {
5014            final int offsetToCheck = isStartHandle() ? offset : Math.max(offset - 1, 0);
5015            return layout.isRtlCharAt(offsetToCheck);
5016        }
5017
5018        @Override
5019        public float getHorizontal(@NonNull Layout layout, int offset) {
5020            return getHorizontal(layout, offset, isStartHandle());
5021        }
5022
5023        private float getHorizontal(@NonNull Layout layout, int offset, boolean startHandle) {
5024            final int line = layout.getLineForOffset(offset);
5025            final int offsetToCheck = startHandle ? offset : Math.max(offset - 1, 0);
5026            final boolean isRtlChar = layout.isRtlCharAt(offsetToCheck);
5027            final boolean isRtlParagraph = layout.getParagraphDirection(line) == -1;
5028            return (isRtlChar == isRtlParagraph)
5029                    ? layout.getPrimaryHorizontal(offset) : layout.getSecondaryHorizontal(offset);
5030        }
5031
5032        @Override
5033        protected int getOffsetAtCoordinate(@NonNull Layout layout, int line, float x) {
5034            final float localX = mTextView.convertToLocalHorizontalCoordinate(x);
5035            final int primaryOffset = layout.getOffsetForHorizontal(line, localX, true);
5036            if (!layout.isLevelBoundary(primaryOffset)) {
5037                return primaryOffset;
5038            }
5039            final int secondaryOffset = layout.getOffsetForHorizontal(line, localX, false);
5040            final int currentOffset = getCurrentCursorOffset();
5041            final int primaryDiff = Math.abs(primaryOffset - currentOffset);
5042            final int secondaryDiff = Math.abs(secondaryOffset - currentOffset);
5043            if (primaryDiff < secondaryDiff) {
5044                return primaryOffset;
5045            } else if (primaryDiff > secondaryDiff) {
5046                return secondaryOffset;
5047            } else {
5048                final int offsetToCheck = isStartHandle()
5049                        ? currentOffset : Math.max(currentOffset - 1, 0);
5050                final boolean isRtlChar = layout.isRtlCharAt(offsetToCheck);
5051                final boolean isRtlParagraph = layout.getParagraphDirection(line) == -1;
5052                return isRtlChar == isRtlParagraph ? primaryOffset : secondaryOffset;
5053            }
5054        }
5055    }
5056
5057    private int getCurrentLineAdjustedForSlop(Layout layout, int prevLine, float y) {
5058        final int trueLine = mTextView.getLineAtCoordinate(y);
5059        if (layout == null || prevLine > layout.getLineCount()
5060                || layout.getLineCount() <= 0 || prevLine < 0) {
5061            // Invalid parameters, just return whatever line is at y.
5062            return trueLine;
5063        }
5064
5065        if (Math.abs(trueLine - prevLine) >= 2) {
5066            // Only stick to lines if we're within a line of the previous selection.
5067            return trueLine;
5068        }
5069
5070        final float verticalOffset = mTextView.viewportToContentVerticalOffset();
5071        final int lineCount = layout.getLineCount();
5072        final float slop = mTextView.getLineHeight() * LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS;
5073
5074        final float firstLineTop = layout.getLineTop(0) + verticalOffset;
5075        final float prevLineTop = layout.getLineTop(prevLine) + verticalOffset;
5076        final float yTopBound = Math.max(prevLineTop - slop, firstLineTop + slop);
5077
5078        final float lastLineBottom = layout.getLineBottom(lineCount - 1) + verticalOffset;
5079        final float prevLineBottom = layout.getLineBottom(prevLine) + verticalOffset;
5080        final float yBottomBound = Math.min(prevLineBottom + slop, lastLineBottom - slop);
5081
5082        // Determine if we've moved lines based on y position and previous line.
5083        int currLine;
5084        if (y <= yTopBound) {
5085            currLine = Math.max(prevLine - 1, 0);
5086        } else if (y >= yBottomBound) {
5087            currLine = Math.min(prevLine + 1, lineCount - 1);
5088        } else {
5089            currLine = prevLine;
5090        }
5091        return currLine;
5092    }
5093
5094    /**
5095     * A CursorController instance can be used to control a cursor in the text.
5096     */
5097    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
5098        /**
5099         * Makes the cursor controller visible on screen.
5100         * See also {@link #hide()}.
5101         */
5102        public void show();
5103
5104        /**
5105         * Hide the cursor controller from screen.
5106         * See also {@link #show()}.
5107         */
5108        public void hide();
5109
5110        /**
5111         * Called when the view is detached from window. Perform house keeping task, such as
5112         * stopping Runnable thread that would otherwise keep a reference on the context, thus
5113         * preventing the activity from being recycled.
5114         */
5115        public void onDetached();
5116
5117        public boolean isCursorBeingModified();
5118
5119        public boolean isActive();
5120    }
5121
5122    private class InsertionPointCursorController implements CursorController {
5123        private InsertionHandleView mHandle;
5124
5125        public void show() {
5126            getHandle().show();
5127
5128            if (mSelectionModifierCursorController != null) {
5129                mSelectionModifierCursorController.hide();
5130            }
5131        }
5132
5133        public void hide() {
5134            if (mHandle != null) {
5135                mHandle.hide();
5136            }
5137        }
5138
5139        public void onTouchModeChanged(boolean isInTouchMode) {
5140            if (!isInTouchMode) {
5141                hide();
5142            }
5143        }
5144
5145        private InsertionHandleView getHandle() {
5146            if (mSelectHandleCenter == null) {
5147                mSelectHandleCenter = mTextView.getContext().getDrawable(
5148                        mTextView.mTextSelectHandleRes);
5149            }
5150            if (mHandle == null) {
5151                mHandle = new InsertionHandleView(mSelectHandleCenter);
5152            }
5153            return mHandle;
5154        }
5155
5156        @Override
5157        public void onDetached() {
5158            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
5159            observer.removeOnTouchModeChangeListener(this);
5160
5161            if (mHandle != null) mHandle.onDetached();
5162        }
5163
5164        @Override
5165        public boolean isCursorBeingModified() {
5166            return mHandle != null && mHandle.isDragging();
5167        }
5168
5169        @Override
5170        public boolean isActive() {
5171            return mHandle != null && mHandle.isShowing();
5172        }
5173
5174        public void invalidateHandle() {
5175            if (mHandle != null) {
5176                mHandle.invalidate();
5177            }
5178        }
5179    }
5180
5181    class SelectionModifierCursorController implements CursorController {
5182        // The cursor controller handles, lazily created when shown.
5183        private SelectionHandleView mStartHandle;
5184        private SelectionHandleView mEndHandle;
5185        // The offsets of that last touch down event. Remembered to start selection there.
5186        private int mMinTouchOffset, mMaxTouchOffset;
5187
5188        private float mDownPositionX, mDownPositionY;
5189        private boolean mGestureStayedInTapRegion;
5190
5191        // Where the user first starts the drag motion.
5192        private int mStartOffset = -1;
5193
5194        private boolean mHaventMovedEnoughToStartDrag;
5195        // The line that a selection happened most recently with the drag accelerator.
5196        private int mLineSelectionIsOn = -1;
5197        // Whether the drag accelerator has selected past the initial line.
5198        private boolean mSwitchedLines = false;
5199
5200        // Indicates the drag accelerator mode that the user is currently using.
5201        private int mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE;
5202        // Drag accelerator is inactive.
5203        private static final int DRAG_ACCELERATOR_MODE_INACTIVE = 0;
5204        // Character based selection by dragging. Only for mouse.
5205        private static final int DRAG_ACCELERATOR_MODE_CHARACTER = 1;
5206        // Word based selection by dragging. Enabled after long pressing or double tapping.
5207        private static final int DRAG_ACCELERATOR_MODE_WORD = 2;
5208        // Paragraph based selection by dragging. Enabled after mouse triple click.
5209        private static final int DRAG_ACCELERATOR_MODE_PARAGRAPH = 3;
5210
5211        SelectionModifierCursorController() {
5212            resetTouchOffsets();
5213        }
5214
5215        public void show() {
5216            if (mTextView.isInBatchEditMode()) {
5217                return;
5218            }
5219            initDrawables();
5220            initHandles();
5221        }
5222
5223        private void initDrawables() {
5224            if (mSelectHandleLeft == null) {
5225                mSelectHandleLeft = mTextView.getContext().getDrawable(
5226                        mTextView.mTextSelectHandleLeftRes);
5227            }
5228            if (mSelectHandleRight == null) {
5229                mSelectHandleRight = mTextView.getContext().getDrawable(
5230                        mTextView.mTextSelectHandleRightRes);
5231            }
5232        }
5233
5234        private void initHandles() {
5235            // Lazy object creation has to be done before updatePosition() is called.
5236            if (mStartHandle == null) {
5237                mStartHandle = new SelectionHandleView(mSelectHandleLeft, mSelectHandleRight,
5238                        com.android.internal.R.id.selection_start_handle,
5239                        HANDLE_TYPE_SELECTION_START);
5240            }
5241            if (mEndHandle == null) {
5242                mEndHandle = new SelectionHandleView(mSelectHandleRight, mSelectHandleLeft,
5243                        com.android.internal.R.id.selection_end_handle,
5244                        HANDLE_TYPE_SELECTION_END);
5245            }
5246
5247            mStartHandle.show();
5248            mEndHandle.show();
5249
5250            hideInsertionPointCursorController();
5251        }
5252
5253        public void hide() {
5254            if (mStartHandle != null) mStartHandle.hide();
5255            if (mEndHandle != null) mEndHandle.hide();
5256        }
5257
5258        public void enterDrag(int dragAcceleratorMode) {
5259            // Just need to init the handles / hide insertion cursor.
5260            show();
5261            mDragAcceleratorMode = dragAcceleratorMode;
5262            // Start location of selection.
5263            mStartOffset = mTextView.getOffsetForPosition(mLastDownPositionX,
5264                    mLastDownPositionY);
5265            mLineSelectionIsOn = mTextView.getLineAtCoordinate(mLastDownPositionY);
5266            // Don't show the handles until user has lifted finger.
5267            hide();
5268
5269            // This stops scrolling parents from intercepting the touch event, allowing
5270            // the user to continue dragging across the screen to select text; TextView will
5271            // scroll as necessary.
5272            mTextView.getParent().requestDisallowInterceptTouchEvent(true);
5273            mTextView.cancelLongPress();
5274        }
5275
5276        public void onTouchEvent(MotionEvent event) {
5277            // This is done even when the View does not have focus, so that long presses can start
5278            // selection and tap can move cursor from this tap position.
5279            final float eventX = event.getX();
5280            final float eventY = event.getY();
5281            final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
5282            switch (event.getActionMasked()) {
5283                case MotionEvent.ACTION_DOWN:
5284                    if (extractedTextModeWillBeStarted()) {
5285                        // Prevent duplicating the selection handles until the mode starts.
5286                        hide();
5287                    } else {
5288                        // Remember finger down position, to be able to start selection from there.
5289                        mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(
5290                                eventX, eventY);
5291
5292                        // Double tap detection
5293                        if (mGestureStayedInTapRegion) {
5294                            if (mTapState == TAP_STATE_DOUBLE_TAP
5295                                    || mTapState == TAP_STATE_TRIPLE_CLICK) {
5296                                final float deltaX = eventX - mDownPositionX;
5297                                final float deltaY = eventY - mDownPositionY;
5298                                final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
5299
5300                                ViewConfiguration viewConfiguration = ViewConfiguration.get(
5301                                        mTextView.getContext());
5302                                int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop();
5303                                boolean stayedInArea =
5304                                        distanceSquared < doubleTapSlop * doubleTapSlop;
5305
5306                                if (stayedInArea && (isMouse || isPositionOnText(eventX, eventY))) {
5307                                    if (mTapState == TAP_STATE_DOUBLE_TAP) {
5308                                        selectCurrentWordAndStartDrag();
5309                                    } else if (mTapState == TAP_STATE_TRIPLE_CLICK) {
5310                                        selectCurrentParagraphAndStartDrag();
5311                                    }
5312                                    mDiscardNextActionUp = true;
5313                                }
5314                            }
5315                        }
5316
5317                        mDownPositionX = eventX;
5318                        mDownPositionY = eventY;
5319                        mGestureStayedInTapRegion = true;
5320                        mHaventMovedEnoughToStartDrag = true;
5321                    }
5322                    break;
5323
5324                case MotionEvent.ACTION_POINTER_DOWN:
5325                case MotionEvent.ACTION_POINTER_UP:
5326                    // Handle multi-point gestures. Keep min and max offset positions.
5327                    // Only activated for devices that correctly handle multi-touch.
5328                    if (mTextView.getContext().getPackageManager().hasSystemFeature(
5329                            PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
5330                        updateMinAndMaxOffsets(event);
5331                    }
5332                    break;
5333
5334                case MotionEvent.ACTION_MOVE:
5335                    final ViewConfiguration viewConfig = ViewConfiguration.get(
5336                            mTextView.getContext());
5337                    final int touchSlop = viewConfig.getScaledTouchSlop();
5338
5339                    if (mGestureStayedInTapRegion || mHaventMovedEnoughToStartDrag) {
5340                        final float deltaX = eventX - mDownPositionX;
5341                        final float deltaY = eventY - mDownPositionY;
5342                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
5343
5344                        if (mGestureStayedInTapRegion) {
5345                            int doubleTapTouchSlop = viewConfig.getScaledDoubleTapTouchSlop();
5346                            mGestureStayedInTapRegion =
5347                                    distanceSquared <= doubleTapTouchSlop * doubleTapTouchSlop;
5348                        }
5349                        if (mHaventMovedEnoughToStartDrag) {
5350                            // We don't start dragging until the user has moved enough.
5351                            mHaventMovedEnoughToStartDrag =
5352                                    distanceSquared <= touchSlop * touchSlop;
5353                        }
5354                    }
5355
5356                    if (isMouse && !isDragAcceleratorActive()) {
5357                        final int offset = mTextView.getOffsetForPosition(eventX, eventY);
5358                        if (mTextView.hasSelection()
5359                                && (!mHaventMovedEnoughToStartDrag || mStartOffset != offset)
5360                                && offset >= mTextView.getSelectionStart()
5361                                && offset <= mTextView.getSelectionEnd()) {
5362                            startDragAndDrop();
5363                            break;
5364                        }
5365
5366                        if (mStartOffset != offset) {
5367                            // Start character based drag accelerator.
5368                            stopTextActionMode();
5369                            enterDrag(DRAG_ACCELERATOR_MODE_CHARACTER);
5370                            mDiscardNextActionUp = true;
5371                            mHaventMovedEnoughToStartDrag = false;
5372                        }
5373                    }
5374
5375                    if (mStartHandle != null && mStartHandle.isShowing()) {
5376                        // Don't do the drag if the handles are showing already.
5377                        break;
5378                    }
5379
5380                    updateSelection(event);
5381                    break;
5382
5383                case MotionEvent.ACTION_UP:
5384                    if (!isDragAcceleratorActive()) {
5385                        break;
5386                    }
5387                    updateSelection(event);
5388
5389                    // No longer dragging to select text, let the parent intercept events.
5390                    mTextView.getParent().requestDisallowInterceptTouchEvent(false);
5391
5392                    // No longer the first dragging motion, reset.
5393                    resetDragAcceleratorState();
5394
5395                    if (mTextView.hasSelection()) {
5396                        // Do not invoke the text assistant if this was a drag selection.
5397                        if (mHaventMovedEnoughToStartDrag) {
5398                            startSelectionActionModeAsync();
5399                        } else {
5400                            startSelectionActionMode();
5401                        }
5402
5403                    }
5404                    break;
5405            }
5406        }
5407
5408        private void updateSelection(MotionEvent event) {
5409            if (mTextView.getLayout() != null) {
5410                switch (mDragAcceleratorMode) {
5411                    case DRAG_ACCELERATOR_MODE_CHARACTER:
5412                        updateCharacterBasedSelection(event);
5413                        break;
5414                    case DRAG_ACCELERATOR_MODE_WORD:
5415                        updateWordBasedSelection(event);
5416                        break;
5417                    case DRAG_ACCELERATOR_MODE_PARAGRAPH:
5418                        updateParagraphBasedSelection(event);
5419                        break;
5420                }
5421            }
5422        }
5423
5424        /**
5425         * If the TextView allows text selection, selects the current paragraph and starts a drag.
5426         *
5427         * @return true if the drag was started.
5428         */
5429        private boolean selectCurrentParagraphAndStartDrag() {
5430            if (mInsertionActionModeRunnable != null) {
5431                mTextView.removeCallbacks(mInsertionActionModeRunnable);
5432            }
5433            stopTextActionMode();
5434            if (!selectCurrentParagraph()) {
5435                return false;
5436            }
5437            enterDrag(SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_PARAGRAPH);
5438            return true;
5439        }
5440
5441        private void updateCharacterBasedSelection(MotionEvent event) {
5442            final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
5443            Selection.setSelection((Spannable) mTextView.getText(), mStartOffset, offset);
5444        }
5445
5446        private void updateWordBasedSelection(MotionEvent event) {
5447            if (mHaventMovedEnoughToStartDrag) {
5448                return;
5449            }
5450            final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
5451            final ViewConfiguration viewConfig = ViewConfiguration.get(
5452                    mTextView.getContext());
5453            final float eventX = event.getX();
5454            final float eventY = event.getY();
5455            final int currLine;
5456            if (isMouse) {
5457                // No need to offset the y coordinate for mouse input.
5458                currLine = mTextView.getLineAtCoordinate(eventY);
5459            } else {
5460                float y = eventY;
5461                if (mSwitchedLines) {
5462                    // Offset the finger by the same vertical offset as the handles.
5463                    // This improves visibility of the content being selected by
5464                    // shifting the finger below the content, this is applied once
5465                    // the user has switched lines.
5466                    final int touchSlop = viewConfig.getScaledTouchSlop();
5467                    final float fingerOffset = (mStartHandle != null)
5468                            ? mStartHandle.getIdealVerticalOffset()
5469                            : touchSlop;
5470                    y = eventY - fingerOffset;
5471                }
5472
5473                currLine = getCurrentLineAdjustedForSlop(mTextView.getLayout(), mLineSelectionIsOn,
5474                        y);
5475                if (!mSwitchedLines && currLine != mLineSelectionIsOn) {
5476                    // Break early here, we want to offset the finger position from
5477                    // the selection highlight, once the user moved their finger
5478                    // to a different line we should apply the offset and *not* switch
5479                    // lines until recomputing the position with the finger offset.
5480                    mSwitchedLines = true;
5481                    return;
5482                }
5483            }
5484
5485            int startOffset;
5486            int offset = mTextView.getOffsetAtCoordinate(currLine, eventX);
5487            // Snap to word boundaries.
5488            if (mStartOffset < offset) {
5489                // Expanding with end handle.
5490                offset = getWordEnd(offset);
5491                startOffset = getWordStart(mStartOffset);
5492            } else {
5493                // Expanding with start handle.
5494                offset = getWordStart(offset);
5495                startOffset = getWordEnd(mStartOffset);
5496                if (startOffset == offset) {
5497                    offset = getNextCursorOffset(offset, false);
5498                }
5499            }
5500            mLineSelectionIsOn = currLine;
5501            Selection.setSelection((Spannable) mTextView.getText(), startOffset, offset);
5502        }
5503
5504        private void updateParagraphBasedSelection(MotionEvent event) {
5505            final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
5506
5507            final int start = Math.min(offset, mStartOffset);
5508            final int end = Math.max(offset, mStartOffset);
5509            final long paragraphsRange = getParagraphsRange(start, end);
5510            final int selectionStart = TextUtils.unpackRangeStartFromLong(paragraphsRange);
5511            final int selectionEnd = TextUtils.unpackRangeEndFromLong(paragraphsRange);
5512            Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
5513        }
5514
5515        /**
5516         * @param event
5517         */
5518        private void updateMinAndMaxOffsets(MotionEvent event) {
5519            int pointerCount = event.getPointerCount();
5520            for (int index = 0; index < pointerCount; index++) {
5521                int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index));
5522                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
5523                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
5524            }
5525        }
5526
5527        public int getMinTouchOffset() {
5528            return mMinTouchOffset;
5529        }
5530
5531        public int getMaxTouchOffset() {
5532            return mMaxTouchOffset;
5533        }
5534
5535        public void resetTouchOffsets() {
5536            mMinTouchOffset = mMaxTouchOffset = -1;
5537            resetDragAcceleratorState();
5538        }
5539
5540        private void resetDragAcceleratorState() {
5541            mStartOffset = -1;
5542            mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE;
5543            mSwitchedLines = false;
5544            final int selectionStart = mTextView.getSelectionStart();
5545            final int selectionEnd = mTextView.getSelectionEnd();
5546            if (selectionStart > selectionEnd) {
5547                Selection.setSelection((Spannable) mTextView.getText(),
5548                        selectionEnd, selectionStart);
5549            }
5550        }
5551
5552        /**
5553         * @return true iff this controller is currently used to move the selection start.
5554         */
5555        public boolean isSelectionStartDragged() {
5556            return mStartHandle != null && mStartHandle.isDragging();
5557        }
5558
5559        @Override
5560        public boolean isCursorBeingModified() {
5561            return isDragAcceleratorActive() || isSelectionStartDragged()
5562                    || (mEndHandle != null && mEndHandle.isDragging());
5563        }
5564
5565        /**
5566         * @return true if the user is selecting text using the drag accelerator.
5567         */
5568        public boolean isDragAcceleratorActive() {
5569            return mDragAcceleratorMode != DRAG_ACCELERATOR_MODE_INACTIVE;
5570        }
5571
5572        public void onTouchModeChanged(boolean isInTouchMode) {
5573            if (!isInTouchMode) {
5574                hide();
5575            }
5576        }
5577
5578        @Override
5579        public void onDetached() {
5580            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
5581            observer.removeOnTouchModeChangeListener(this);
5582
5583            if (mStartHandle != null) mStartHandle.onDetached();
5584            if (mEndHandle != null) mEndHandle.onDetached();
5585        }
5586
5587        @Override
5588        public boolean isActive() {
5589            return mStartHandle != null && mStartHandle.isShowing();
5590        }
5591
5592        public void invalidateHandles() {
5593            if (mStartHandle != null) {
5594                mStartHandle.invalidate();
5595            }
5596            if (mEndHandle != null) {
5597                mEndHandle.invalidate();
5598            }
5599        }
5600    }
5601
5602    private class CorrectionHighlighter {
5603        private final Path mPath = new Path();
5604        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
5605        private int mStart, mEnd;
5606        private long mFadingStartTime;
5607        private RectF mTempRectF;
5608        private static final int FADE_OUT_DURATION = 400;
5609
5610        public CorrectionHighlighter() {
5611            mPaint.setCompatibilityScaling(
5612                    mTextView.getResources().getCompatibilityInfo().applicationScale);
5613            mPaint.setStyle(Paint.Style.FILL);
5614        }
5615
5616        public void highlight(CorrectionInfo info) {
5617            mStart = info.getOffset();
5618            mEnd = mStart + info.getNewText().length();
5619            mFadingStartTime = SystemClock.uptimeMillis();
5620
5621            if (mStart < 0 || mEnd < 0) {
5622                stopAnimation();
5623            }
5624        }
5625
5626        public void draw(Canvas canvas, int cursorOffsetVertical) {
5627            if (updatePath() && updatePaint()) {
5628                if (cursorOffsetVertical != 0) {
5629                    canvas.translate(0, cursorOffsetVertical);
5630                }
5631
5632                canvas.drawPath(mPath, mPaint);
5633
5634                if (cursorOffsetVertical != 0) {
5635                    canvas.translate(0, -cursorOffsetVertical);
5636                }
5637                invalidate(true); // TODO invalidate cursor region only
5638            } else {
5639                stopAnimation();
5640                invalidate(false); // TODO invalidate cursor region only
5641            }
5642        }
5643
5644        private boolean updatePaint() {
5645            final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
5646            if (duration > FADE_OUT_DURATION) return false;
5647
5648            final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
5649            final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor);
5650            final int color = (mTextView.mHighlightColor & 0x00FFFFFF)
5651                    + ((int) (highlightColorAlpha * coef) << 24);
5652            mPaint.setColor(color);
5653            return true;
5654        }
5655
5656        private boolean updatePath() {
5657            final Layout layout = mTextView.getLayout();
5658            if (layout == null) return false;
5659
5660            // Update in case text is edited while the animation is run
5661            final int length = mTextView.getText().length();
5662            int start = Math.min(length, mStart);
5663            int end = Math.min(length, mEnd);
5664
5665            mPath.reset();
5666            layout.getSelectionPath(start, end, mPath);
5667            return true;
5668        }
5669
5670        private void invalidate(boolean delayed) {
5671            if (mTextView.getLayout() == null) return;
5672
5673            if (mTempRectF == null) mTempRectF = new RectF();
5674            mPath.computeBounds(mTempRectF, false);
5675
5676            int left = mTextView.getCompoundPaddingLeft();
5677            int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true);
5678
5679            if (delayed) {
5680                mTextView.postInvalidateOnAnimation(
5681                        left + (int) mTempRectF.left, top + (int) mTempRectF.top,
5682                        left + (int) mTempRectF.right, top + (int) mTempRectF.bottom);
5683            } else {
5684                mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top,
5685                        (int) mTempRectF.right, (int) mTempRectF.bottom);
5686            }
5687        }
5688
5689        private void stopAnimation() {
5690            Editor.this.mCorrectionHighlighter = null;
5691        }
5692    }
5693
5694    private static class ErrorPopup extends PopupWindow {
5695        private boolean mAbove = false;
5696        private final TextView mView;
5697        private int mPopupInlineErrorBackgroundId = 0;
5698        private int mPopupInlineErrorAboveBackgroundId = 0;
5699
5700        ErrorPopup(TextView v, int width, int height) {
5701            super(v, width, height);
5702            mView = v;
5703            // Make sure the TextView has a background set as it will be used the first time it is
5704            // shown and positioned. Initialized with below background, which should have
5705            // dimensions identical to the above version for this to work (and is more likely).
5706            mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
5707                    com.android.internal.R.styleable.Theme_errorMessageBackground);
5708            mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
5709        }
5710
5711        void fixDirection(boolean above) {
5712            mAbove = above;
5713
5714            if (above) {
5715                mPopupInlineErrorAboveBackgroundId =
5716                    getResourceId(mPopupInlineErrorAboveBackgroundId,
5717                            com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
5718            } else {
5719                mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
5720                        com.android.internal.R.styleable.Theme_errorMessageBackground);
5721            }
5722
5723            mView.setBackgroundResource(
5724                    above ? mPopupInlineErrorAboveBackgroundId : mPopupInlineErrorBackgroundId);
5725        }
5726
5727        private int getResourceId(int currentId, int index) {
5728            if (currentId == 0) {
5729                TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
5730                        R.styleable.Theme);
5731                currentId = styledAttributes.getResourceId(index, 0);
5732                styledAttributes.recycle();
5733            }
5734            return currentId;
5735        }
5736
5737        @Override
5738        public void update(int x, int y, int w, int h, boolean force) {
5739            super.update(x, y, w, h, force);
5740
5741            boolean above = isAboveAnchor();
5742            if (above != mAbove) {
5743                fixDirection(above);
5744            }
5745        }
5746    }
5747
5748    static class InputContentType {
5749        int imeOptions = EditorInfo.IME_NULL;
5750        String privateImeOptions;
5751        CharSequence imeActionLabel;
5752        int imeActionId;
5753        Bundle extras;
5754        OnEditorActionListener onEditorActionListener;
5755        boolean enterDown;
5756        LocaleList imeHintLocales;
5757    }
5758
5759    static class InputMethodState {
5760        ExtractedTextRequest mExtractedTextRequest;
5761        final ExtractedText mExtractedText = new ExtractedText();
5762        int mBatchEditNesting;
5763        boolean mCursorChanged;
5764        boolean mSelectionModeChanged;
5765        boolean mContentChanged;
5766        int mChangedStart, mChangedEnd, mChangedDelta;
5767    }
5768
5769    /**
5770     * @return True iff (start, end) is a valid range within the text.
5771     */
5772    private static boolean isValidRange(CharSequence text, int start, int end) {
5773        return 0 <= start && start <= end && end <= text.length();
5774    }
5775
5776    @VisibleForTesting
5777    public SuggestionsPopupWindow getSuggestionsPopupWindowForTesting() {
5778        return mSuggestionsPopupWindow;
5779    }
5780
5781    /**
5782     * An InputFilter that monitors text input to maintain undo history. It does not modify the
5783     * text being typed (and hence always returns null from the filter() method).
5784     *
5785     * TODO: Make this span aware.
5786     */
5787    public static class UndoInputFilter implements InputFilter {
5788        private final Editor mEditor;
5789
5790        // Whether the current filter pass is directly caused by an end-user text edit.
5791        private boolean mIsUserEdit;
5792
5793        // Whether the text field is handling an IME composition. Must be parceled in case the user
5794        // rotates the screen during composition.
5795        private boolean mHasComposition;
5796
5797        // Whether the user is expanding or shortening the text
5798        private boolean mExpanding;
5799
5800        // Whether the previous edit operation was in the current batch edit.
5801        private boolean mPreviousOperationWasInSameBatchEdit;
5802
5803        public UndoInputFilter(Editor editor) {
5804            mEditor = editor;
5805        }
5806
5807        public void saveInstanceState(Parcel parcel) {
5808            parcel.writeInt(mIsUserEdit ? 1 : 0);
5809            parcel.writeInt(mHasComposition ? 1 : 0);
5810            parcel.writeInt(mExpanding ? 1 : 0);
5811            parcel.writeInt(mPreviousOperationWasInSameBatchEdit ? 1 : 0);
5812        }
5813
5814        public void restoreInstanceState(Parcel parcel) {
5815            mIsUserEdit = parcel.readInt() != 0;
5816            mHasComposition = parcel.readInt() != 0;
5817            mExpanding = parcel.readInt() != 0;
5818            mPreviousOperationWasInSameBatchEdit = parcel.readInt() != 0;
5819        }
5820
5821        /**
5822         * Signals that a user-triggered edit is starting.
5823         */
5824        public void beginBatchEdit() {
5825            if (DEBUG_UNDO) Log.d(TAG, "beginBatchEdit");
5826            mIsUserEdit = true;
5827        }
5828
5829        public void endBatchEdit() {
5830            if (DEBUG_UNDO) Log.d(TAG, "endBatchEdit");
5831            mIsUserEdit = false;
5832            mPreviousOperationWasInSameBatchEdit = false;
5833        }
5834
5835        @Override
5836        public CharSequence filter(CharSequence source, int start, int end,
5837                Spanned dest, int dstart, int dend) {
5838            if (DEBUG_UNDO) {
5839                Log.d(TAG, "filter: source=" + source + " (" + start + "-" + end + ") "
5840                        + "dest=" + dest + " (" + dstart + "-" + dend + ")");
5841            }
5842
5843            // Check to see if this edit should be tracked for undo.
5844            if (!canUndoEdit(source, start, end, dest, dstart, dend)) {
5845                return null;
5846            }
5847
5848            final boolean hadComposition = mHasComposition;
5849            mHasComposition = isComposition(source);
5850            final boolean wasExpanding = mExpanding;
5851            boolean shouldCreateSeparateState = false;
5852            if ((end - start) != (dend - dstart)) {
5853                mExpanding = (end - start) > (dend - dstart);
5854                if (hadComposition && mExpanding != wasExpanding) {
5855                    shouldCreateSeparateState = true;
5856                }
5857            }
5858
5859            // Handle edit.
5860            handleEdit(source, start, end, dest, dstart, dend, shouldCreateSeparateState);
5861            return null;
5862        }
5863
5864        void freezeLastEdit() {
5865            mEditor.mUndoManager.beginUpdate("Edit text");
5866            EditOperation lastEdit = getLastEdit();
5867            if (lastEdit != null) {
5868                lastEdit.mFrozen = true;
5869            }
5870            mEditor.mUndoManager.endUpdate();
5871        }
5872
5873        @Retention(RetentionPolicy.SOURCE)
5874        @IntDef({MERGE_EDIT_MODE_FORCE_MERGE, MERGE_EDIT_MODE_NEVER_MERGE, MERGE_EDIT_MODE_NORMAL})
5875        private @interface MergeMode {}
5876        private static final int MERGE_EDIT_MODE_FORCE_MERGE = 0;
5877        private static final int MERGE_EDIT_MODE_NEVER_MERGE = 1;
5878        /** Use {@link EditOperation#mergeWith} to merge */
5879        private static final int MERGE_EDIT_MODE_NORMAL = 2;
5880
5881        private void handleEdit(CharSequence source, int start, int end,
5882                Spanned dest, int dstart, int dend, boolean shouldCreateSeparateState) {
5883            // An application may install a TextWatcher to provide additional modifications after
5884            // the initial input filters run (e.g. a credit card formatter that adds spaces to a
5885            // string). This results in multiple filter() calls for what the user considers to be
5886            // a single operation. Always undo the whole set of changes in one step.
5887            @MergeMode
5888            final int mergeMode;
5889            if (isInTextWatcher() || mPreviousOperationWasInSameBatchEdit) {
5890                mergeMode = MERGE_EDIT_MODE_FORCE_MERGE;
5891            } else if (shouldCreateSeparateState) {
5892                mergeMode = MERGE_EDIT_MODE_NEVER_MERGE;
5893            } else {
5894                mergeMode = MERGE_EDIT_MODE_NORMAL;
5895            }
5896            // Build a new operation with all the information from this edit.
5897            String newText = TextUtils.substring(source, start, end);
5898            String oldText = TextUtils.substring(dest, dstart, dend);
5899            EditOperation edit = new EditOperation(mEditor, oldText, dstart, newText,
5900                    mHasComposition);
5901            if (mHasComposition && TextUtils.equals(edit.mNewText, edit.mOldText)) {
5902                return;
5903            }
5904            recordEdit(edit, mergeMode);
5905        }
5906
5907        private EditOperation getLastEdit() {
5908            final UndoManager um = mEditor.mUndoManager;
5909            return um.getLastOperation(
5910                  EditOperation.class, mEditor.mUndoOwner, UndoManager.MERGE_MODE_UNIQUE);
5911        }
5912        /**
5913         * Fetches the last undo operation and checks to see if a new edit should be merged into it.
5914         * If forceMerge is true then the new edit is always merged.
5915         */
5916        private void recordEdit(EditOperation edit, @MergeMode int mergeMode) {
5917            // Fetch the last edit operation and attempt to merge in the new edit.
5918            final UndoManager um = mEditor.mUndoManager;
5919            um.beginUpdate("Edit text");
5920            EditOperation lastEdit = getLastEdit();
5921            if (lastEdit == null) {
5922                // Add this as the first edit.
5923                if (DEBUG_UNDO) Log.d(TAG, "filter: adding first op " + edit);
5924                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
5925            } else if (mergeMode == MERGE_EDIT_MODE_FORCE_MERGE) {
5926                // Forced merges take priority because they could be the result of a non-user-edit
5927                // change and this case should not create a new undo operation.
5928                if (DEBUG_UNDO) Log.d(TAG, "filter: force merge " + edit);
5929                lastEdit.forceMergeWith(edit);
5930            } else if (!mIsUserEdit) {
5931                // An application directly modified the Editable outside of a text edit. Treat this
5932                // as a new change and don't attempt to merge.
5933                if (DEBUG_UNDO) Log.d(TAG, "non-user edit, new op " + edit);
5934                um.commitState(mEditor.mUndoOwner);
5935                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
5936            } else if (mergeMode == MERGE_EDIT_MODE_NORMAL && lastEdit.mergeWith(edit)) {
5937                // Merge succeeded, nothing else to do.
5938                if (DEBUG_UNDO) Log.d(TAG, "filter: merge succeeded, created " + lastEdit);
5939            } else {
5940                // Could not merge with the last edit, so commit the last edit and add this edit.
5941                if (DEBUG_UNDO) Log.d(TAG, "filter: merge failed, adding " + edit);
5942                um.commitState(mEditor.mUndoOwner);
5943                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
5944            }
5945            mPreviousOperationWasInSameBatchEdit = mIsUserEdit;
5946            um.endUpdate();
5947        }
5948
5949        private boolean canUndoEdit(CharSequence source, int start, int end,
5950                Spanned dest, int dstart, int dend) {
5951            if (!mEditor.mAllowUndo) {
5952                if (DEBUG_UNDO) Log.d(TAG, "filter: undo is disabled");
5953                return false;
5954            }
5955
5956            if (mEditor.mUndoManager.isInUndo()) {
5957                if (DEBUG_UNDO) Log.d(TAG, "filter: skipping, currently performing undo/redo");
5958                return false;
5959            }
5960
5961            // Text filters run before input operations are applied. However, some input operations
5962            // are invalid and will throw exceptions when applied. This is common in tests. Don't
5963            // attempt to undo invalid operations.
5964            if (!isValidRange(source, start, end) || !isValidRange(dest, dstart, dend)) {
5965                if (DEBUG_UNDO) Log.d(TAG, "filter: invalid op");
5966                return false;
5967            }
5968
5969            // Earlier filters can rewrite input to be a no-op, for example due to a length limit
5970            // on an input field. Skip no-op changes.
5971            if (start == end && dstart == dend) {
5972                if (DEBUG_UNDO) Log.d(TAG, "filter: skipping no-op");
5973                return false;
5974            }
5975
5976            return true;
5977        }
5978
5979        private static boolean isComposition(CharSequence source) {
5980            if (!(source instanceof Spannable)) {
5981                return false;
5982            }
5983            // This is a composition edit if the source has a non-zero-length composing span.
5984            Spannable text = (Spannable) source;
5985            int composeBegin = EditableInputConnection.getComposingSpanStart(text);
5986            int composeEnd = EditableInputConnection.getComposingSpanEnd(text);
5987            return composeBegin < composeEnd;
5988        }
5989
5990        private boolean isInTextWatcher() {
5991            CharSequence text = mEditor.mTextView.getText();
5992            return (text instanceof SpannableStringBuilder)
5993                    && ((SpannableStringBuilder) text).getTextWatcherDepth() > 0;
5994        }
5995    }
5996
5997    /**
5998     * An operation to undo a single "edit" to a text view.
5999     */
6000    public static class EditOperation extends UndoOperation<Editor> {
6001        private static final int TYPE_INSERT = 0;
6002        private static final int TYPE_DELETE = 1;
6003        private static final int TYPE_REPLACE = 2;
6004
6005        private int mType;
6006        private String mOldText;
6007        private String mNewText;
6008        private int mStart;
6009
6010        private int mOldCursorPos;
6011        private int mNewCursorPos;
6012        private boolean mFrozen;
6013        private boolean mIsComposition;
6014
6015        /**
6016         * Constructs an edit operation from a text input operation on editor that replaces the
6017         * oldText starting at dstart with newText.
6018         */
6019        public EditOperation(Editor editor, String oldText, int dstart, String newText,
6020                boolean isComposition) {
6021            super(editor.mUndoOwner);
6022            mOldText = oldText;
6023            mNewText = newText;
6024
6025            // Determine the type of the edit.
6026            if (mNewText.length() > 0 && mOldText.length() == 0) {
6027                mType = TYPE_INSERT;
6028            } else if (mNewText.length() == 0 && mOldText.length() > 0) {
6029                mType = TYPE_DELETE;
6030            } else {
6031                mType = TYPE_REPLACE;
6032            }
6033
6034            mStart = dstart;
6035            // Store cursor data.
6036            mOldCursorPos = editor.mTextView.getSelectionStart();
6037            mNewCursorPos = dstart + mNewText.length();
6038            mIsComposition = isComposition;
6039        }
6040
6041        public EditOperation(Parcel src, ClassLoader loader) {
6042            super(src, loader);
6043            mType = src.readInt();
6044            mOldText = src.readString();
6045            mNewText = src.readString();
6046            mStart = src.readInt();
6047            mOldCursorPos = src.readInt();
6048            mNewCursorPos = src.readInt();
6049            mFrozen = src.readInt() == 1;
6050            mIsComposition = src.readInt() == 1;
6051        }
6052
6053        @Override
6054        public void writeToParcel(Parcel dest, int flags) {
6055            dest.writeInt(mType);
6056            dest.writeString(mOldText);
6057            dest.writeString(mNewText);
6058            dest.writeInt(mStart);
6059            dest.writeInt(mOldCursorPos);
6060            dest.writeInt(mNewCursorPos);
6061            dest.writeInt(mFrozen ? 1 : 0);
6062            dest.writeInt(mIsComposition ? 1 : 0);
6063        }
6064
6065        private int getNewTextEnd() {
6066            return mStart + mNewText.length();
6067        }
6068
6069        private int getOldTextEnd() {
6070            return mStart + mOldText.length();
6071        }
6072
6073        @Override
6074        public void commit() {
6075        }
6076
6077        @Override
6078        public void undo() {
6079            if (DEBUG_UNDO) Log.d(TAG, "undo");
6080            // Remove the new text and insert the old.
6081            Editor editor = getOwnerData();
6082            Editable text = (Editable) editor.mTextView.getText();
6083            modifyText(text, mStart, getNewTextEnd(), mOldText, mStart, mOldCursorPos);
6084        }
6085
6086        @Override
6087        public void redo() {
6088            if (DEBUG_UNDO) Log.d(TAG, "redo");
6089            // Remove the old text and insert the new.
6090            Editor editor = getOwnerData();
6091            Editable text = (Editable) editor.mTextView.getText();
6092            modifyText(text, mStart, getOldTextEnd(), mNewText, mStart, mNewCursorPos);
6093        }
6094
6095        /**
6096         * Attempts to merge this existing operation with a new edit.
6097         * @param edit The new edit operation.
6098         * @return If the merge succeeded, returns true. Otherwise returns false and leaves this
6099         * object unchanged.
6100         */
6101        private boolean mergeWith(EditOperation edit) {
6102            if (DEBUG_UNDO) {
6103                Log.d(TAG, "mergeWith old " + this);
6104                Log.d(TAG, "mergeWith new " + edit);
6105            }
6106
6107            if (mFrozen) {
6108                return false;
6109            }
6110
6111            switch (mType) {
6112                case TYPE_INSERT:
6113                    return mergeInsertWith(edit);
6114                case TYPE_DELETE:
6115                    return mergeDeleteWith(edit);
6116                case TYPE_REPLACE:
6117                    return mergeReplaceWith(edit);
6118                default:
6119                    return false;
6120            }
6121        }
6122
6123        private boolean mergeInsertWith(EditOperation edit) {
6124            if (edit.mType == TYPE_INSERT) {
6125                // Merge insertions that are contiguous even when it's frozen.
6126                if (getNewTextEnd() != edit.mStart) {
6127                    return false;
6128                }
6129                mNewText += edit.mNewText;
6130                mNewCursorPos = edit.mNewCursorPos;
6131                mFrozen = edit.mFrozen;
6132                mIsComposition = edit.mIsComposition;
6133                return true;
6134            }
6135            if (mIsComposition && edit.mType == TYPE_REPLACE
6136                    && mStart <= edit.mStart && getNewTextEnd() >= edit.getOldTextEnd()) {
6137                // Merge insertion with replace as they can be single insertion.
6138                mNewText = mNewText.substring(0, edit.mStart - mStart) + edit.mNewText
6139                        + mNewText.substring(edit.getOldTextEnd() - mStart, mNewText.length());
6140                mNewCursorPos = edit.mNewCursorPos;
6141                mIsComposition = edit.mIsComposition;
6142                return true;
6143            }
6144            return false;
6145        }
6146
6147        // TODO: Support forward delete.
6148        private boolean mergeDeleteWith(EditOperation edit) {
6149            // Only merge continuous deletes.
6150            if (edit.mType != TYPE_DELETE) {
6151                return false;
6152            }
6153            // Only merge deletions that are contiguous.
6154            if (mStart != edit.getOldTextEnd()) {
6155                return false;
6156            }
6157            mStart = edit.mStart;
6158            mOldText = edit.mOldText + mOldText;
6159            mNewCursorPos = edit.mNewCursorPos;
6160            mIsComposition = edit.mIsComposition;
6161            return true;
6162        }
6163
6164        private boolean mergeReplaceWith(EditOperation edit) {
6165            if (edit.mType == TYPE_INSERT && getNewTextEnd() == edit.mStart) {
6166                // Merge with adjacent insert.
6167                mNewText += edit.mNewText;
6168                mNewCursorPos = edit.mNewCursorPos;
6169                return true;
6170            }
6171            if (!mIsComposition) {
6172                return false;
6173            }
6174            if (edit.mType == TYPE_DELETE && mStart <= edit.mStart
6175                    && getNewTextEnd() >= edit.getOldTextEnd()) {
6176                // Merge with delete as they can be single operation.
6177                mNewText = mNewText.substring(0, edit.mStart - mStart)
6178                        + mNewText.substring(edit.getOldTextEnd() - mStart, mNewText.length());
6179                if (mNewText.isEmpty()) {
6180                    mType = TYPE_DELETE;
6181                }
6182                mNewCursorPos = edit.mNewCursorPos;
6183                mIsComposition = edit.mIsComposition;
6184                return true;
6185            }
6186            if (edit.mType == TYPE_REPLACE && mStart == edit.mStart
6187                    && TextUtils.equals(mNewText, edit.mOldText)) {
6188                // Merge with the replace that replaces the same region.
6189                mNewText = edit.mNewText;
6190                mNewCursorPos = edit.mNewCursorPos;
6191                mIsComposition = edit.mIsComposition;
6192                return true;
6193            }
6194            return false;
6195        }
6196
6197        /**
6198         * Forcibly creates a single merged edit operation by simulating the entire text
6199         * contents being replaced.
6200         */
6201        public void forceMergeWith(EditOperation edit) {
6202            if (DEBUG_UNDO) Log.d(TAG, "forceMerge");
6203            if (mergeWith(edit)) {
6204                return;
6205            }
6206            Editor editor = getOwnerData();
6207
6208            // Copy the text of the current field.
6209            // NOTE: Using StringBuilder instead of SpannableStringBuilder would be somewhat faster,
6210            // but would require two parallel implementations of modifyText() because Editable and
6211            // StringBuilder do not share an interface for replace/delete/insert.
6212            Editable editable = (Editable) editor.mTextView.getText();
6213            Editable originalText = new SpannableStringBuilder(editable.toString());
6214
6215            // Roll back the last operation.
6216            modifyText(originalText, mStart, getNewTextEnd(), mOldText, mStart, mOldCursorPos);
6217
6218            // Clone the text again and apply the new operation.
6219            Editable finalText = new SpannableStringBuilder(editable.toString());
6220            modifyText(finalText, edit.mStart, edit.getOldTextEnd(),
6221                    edit.mNewText, edit.mStart, edit.mNewCursorPos);
6222
6223            // Convert this operation into a replace operation.
6224            mType = TYPE_REPLACE;
6225            mNewText = finalText.toString();
6226            mOldText = originalText.toString();
6227            mStart = 0;
6228            mNewCursorPos = edit.mNewCursorPos;
6229            mIsComposition = edit.mIsComposition;
6230            // mOldCursorPos is unchanged.
6231        }
6232
6233        private static void modifyText(Editable text, int deleteFrom, int deleteTo,
6234                CharSequence newText, int newTextInsertAt, int newCursorPos) {
6235            // Apply the edit if it is still valid.
6236            if (isValidRange(text, deleteFrom, deleteTo)
6237                    && newTextInsertAt <= text.length() - (deleteTo - deleteFrom)) {
6238                if (deleteFrom != deleteTo) {
6239                    text.delete(deleteFrom, deleteTo);
6240                }
6241                if (newText.length() != 0) {
6242                    text.insert(newTextInsertAt, newText);
6243                }
6244            }
6245            // Restore the cursor position. If there wasn't an old cursor (newCursorPos == -1) then
6246            // don't explicitly set it and rely on SpannableStringBuilder to position it.
6247            // TODO: Select all the text that was undone.
6248            if (0 <= newCursorPos && newCursorPos <= text.length()) {
6249                Selection.setSelection(text, newCursorPos);
6250            }
6251        }
6252
6253        private String getTypeString() {
6254            switch (mType) {
6255                case TYPE_INSERT:
6256                    return "insert";
6257                case TYPE_DELETE:
6258                    return "delete";
6259                case TYPE_REPLACE:
6260                    return "replace";
6261                default:
6262                    return "";
6263            }
6264        }
6265
6266        @Override
6267        public String toString() {
6268            return "[mType=" + getTypeString() + ", "
6269                    + "mOldText=" + mOldText + ", "
6270                    + "mNewText=" + mNewText + ", "
6271                    + "mStart=" + mStart + ", "
6272                    + "mOldCursorPos=" + mOldCursorPos + ", "
6273                    + "mNewCursorPos=" + mNewCursorPos + ", "
6274                    + "mFrozen=" + mFrozen + ", "
6275                    + "mIsComposition=" + mIsComposition + "]";
6276        }
6277
6278        public static final Parcelable.ClassLoaderCreator<EditOperation> CREATOR =
6279                new Parcelable.ClassLoaderCreator<EditOperation>() {
6280            @Override
6281            public EditOperation createFromParcel(Parcel in) {
6282                return new EditOperation(in, null);
6283            }
6284
6285            @Override
6286            public EditOperation createFromParcel(Parcel in, ClassLoader loader) {
6287                return new EditOperation(in, loader);
6288            }
6289
6290            @Override
6291            public EditOperation[] newArray(int size) {
6292                return new EditOperation[size];
6293            }
6294        };
6295    }
6296
6297    /**
6298     * A helper for enabling and handling "PROCESS_TEXT" menu actions.
6299     * These allow external applications to plug into currently selected text.
6300     */
6301    static final class ProcessTextIntentActionsHandler {
6302
6303        private final Editor mEditor;
6304        private final TextView mTextView;
6305        private final Context mContext;
6306        private final PackageManager mPackageManager;
6307        private final String mPackageName;
6308        private final SparseArray<Intent> mAccessibilityIntents = new SparseArray<>();
6309        private final SparseArray<AccessibilityNodeInfo.AccessibilityAction> mAccessibilityActions =
6310                new SparseArray<>();
6311        private final List<ResolveInfo> mSupportedActivities = new ArrayList<>();
6312
6313        private ProcessTextIntentActionsHandler(Editor editor) {
6314            mEditor = Preconditions.checkNotNull(editor);
6315            mTextView = Preconditions.checkNotNull(mEditor.mTextView);
6316            mContext = Preconditions.checkNotNull(mTextView.getContext());
6317            mPackageManager = Preconditions.checkNotNull(mContext.getPackageManager());
6318            mPackageName = Preconditions.checkNotNull(mContext.getPackageName());
6319        }
6320
6321        /**
6322         * Adds "PROCESS_TEXT" menu items to the specified menu.
6323         */
6324        public void onInitializeMenu(Menu menu) {
6325            final int size = mSupportedActivities.size();
6326            loadSupportedActivities();
6327            for (int i = 0; i < size; i++) {
6328                final ResolveInfo resolveInfo = mSupportedActivities.get(i);
6329                menu.add(Menu.NONE, Menu.NONE,
6330                        Editor.MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START + i++,
6331                        getLabel(resolveInfo))
6332                        .setIntent(createProcessTextIntentForResolveInfo(resolveInfo))
6333                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
6334            }
6335        }
6336
6337        /**
6338         * Performs a "PROCESS_TEXT" action if there is one associated with the specified
6339         * menu item.
6340         *
6341         * @return True if the action was performed, false otherwise.
6342         */
6343        public boolean performMenuItemAction(MenuItem item) {
6344            return fireIntent(item.getIntent());
6345        }
6346
6347        /**
6348         * Initializes and caches "PROCESS_TEXT" accessibility actions.
6349         */
6350        public void initializeAccessibilityActions() {
6351            mAccessibilityIntents.clear();
6352            mAccessibilityActions.clear();
6353            int i = 0;
6354            loadSupportedActivities();
6355            for (ResolveInfo resolveInfo : mSupportedActivities) {
6356                int actionId = TextView.ACCESSIBILITY_ACTION_PROCESS_TEXT_START_ID + i++;
6357                mAccessibilityActions.put(
6358                        actionId,
6359                        new AccessibilityNodeInfo.AccessibilityAction(
6360                                actionId, getLabel(resolveInfo)));
6361                mAccessibilityIntents.put(
6362                        actionId, createProcessTextIntentForResolveInfo(resolveInfo));
6363            }
6364        }
6365
6366        /**
6367         * Adds "PROCESS_TEXT" accessibility actions to the specified accessibility node info.
6368         * NOTE: This needs a prior call to {@link #initializeAccessibilityActions()} to make the
6369         * latest accessibility actions available for this call.
6370         */
6371        public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo nodeInfo) {
6372            for (int i = 0; i < mAccessibilityActions.size(); i++) {
6373                nodeInfo.addAction(mAccessibilityActions.valueAt(i));
6374            }
6375        }
6376
6377        /**
6378         * Performs a "PROCESS_TEXT" action if there is one associated with the specified
6379         * accessibility action id.
6380         *
6381         * @return True if the action was performed, false otherwise.
6382         */
6383        public boolean performAccessibilityAction(int actionId) {
6384            return fireIntent(mAccessibilityIntents.get(actionId));
6385        }
6386
6387        private boolean fireIntent(Intent intent) {
6388            if (intent != null && Intent.ACTION_PROCESS_TEXT.equals(intent.getAction())) {
6389                intent.putExtra(Intent.EXTRA_PROCESS_TEXT, mTextView.getSelectedText());
6390                mEditor.mPreserveSelection = true;
6391                mTextView.startActivityForResult(intent, TextView.PROCESS_TEXT_REQUEST_CODE);
6392                return true;
6393            }
6394            return false;
6395        }
6396
6397        private void loadSupportedActivities() {
6398            mSupportedActivities.clear();
6399            PackageManager packageManager = mTextView.getContext().getPackageManager();
6400            List<ResolveInfo> unfiltered =
6401                    packageManager.queryIntentActivities(createProcessTextIntent(), 0);
6402            for (ResolveInfo info : unfiltered) {
6403                if (isSupportedActivity(info)) {
6404                    mSupportedActivities.add(info);
6405                }
6406            }
6407        }
6408
6409        private boolean isSupportedActivity(ResolveInfo info) {
6410            return mPackageName.equals(info.activityInfo.packageName)
6411                    || info.activityInfo.exported
6412                            && (info.activityInfo.permission == null
6413                                    || mContext.checkSelfPermission(info.activityInfo.permission)
6414                                            == PackageManager.PERMISSION_GRANTED);
6415        }
6416
6417        private Intent createProcessTextIntentForResolveInfo(ResolveInfo info) {
6418            return createProcessTextIntent()
6419                    .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, !mTextView.isTextEditable())
6420                    .setClassName(info.activityInfo.packageName, info.activityInfo.name);
6421        }
6422
6423        private Intent createProcessTextIntent() {
6424            return new Intent()
6425                    .setAction(Intent.ACTION_PROCESS_TEXT)
6426                    .setType("text/plain");
6427        }
6428
6429        private CharSequence getLabel(ResolveInfo resolveInfo) {
6430            return resolveInfo.loadLabel(mPackageManager);
6431        }
6432    }
6433}
6434