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