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