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