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