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