Editor.java revision 838307275214cb9b51dff15a401013420aa4376a
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.isInExtractedMode()) ||
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.isInExtractedMode())) {
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.isInExtractedMode()) || 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.isInExtractedMode()) {
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.isInExtractedMode())) {
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            if (mIsDragging) {
3572                // Don't update drawable during dragging.
3573                return;
3574            }
3575            final int offset = getCurrentCursorOffset();
3576            final boolean isRtlCharAtOffset = mTextView.getLayout().isRtlCharAt(offset);
3577            final Drawable oldDrawable = mDrawable;
3578            mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
3579            mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
3580            mHorizontalGravity = getHorizontalGravity(isRtlCharAtOffset);
3581            final Layout layout = mTextView.getLayout();
3582            if (layout != null && oldDrawable != mDrawable && isShowing()) {
3583                // Update popup window position.
3584                mPositionX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX -
3585                        getHorizontalOffset() + getCursorOffset());
3586                mPositionX += mTextView.viewportToContentHorizontalOffset();
3587                mPositionHasChanged = true;
3588                updatePosition(mLastParentX, mLastParentY, false, false);
3589                postInvalidate();
3590            }
3591        }
3592
3593        protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
3594        protected abstract int getHorizontalGravity(boolean isRtlRun);
3595
3596        // Touch-up filter: number of previous positions remembered
3597        private static final int HISTORY_SIZE = 5;
3598        private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
3599        private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
3600        private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
3601        private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
3602        private int mPreviousOffsetIndex = 0;
3603        private int mNumberPreviousOffsets = 0;
3604
3605        private void startTouchUpFilter(int offset) {
3606            mNumberPreviousOffsets = 0;
3607            addPositionToTouchUpFilter(offset);
3608        }
3609
3610        private void addPositionToTouchUpFilter(int offset) {
3611            mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
3612            mPreviousOffsets[mPreviousOffsetIndex] = offset;
3613            mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
3614            mNumberPreviousOffsets++;
3615        }
3616
3617        private void filterOnTouchUp() {
3618            final long now = SystemClock.uptimeMillis();
3619            int i = 0;
3620            int index = mPreviousOffsetIndex;
3621            final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
3622            while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
3623                i++;
3624                index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
3625            }
3626
3627            if (i > 0 && i < iMax &&
3628                    (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
3629                positionAtCursorOffset(mPreviousOffsets[index], false);
3630            }
3631        }
3632
3633        public boolean offsetHasBeenChanged() {
3634            return mNumberPreviousOffsets > 1;
3635        }
3636
3637        @Override
3638        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
3639            setMeasuredDimension(getPreferredWidth(), getPreferredHeight());
3640        }
3641
3642        private int getPreferredWidth() {
3643            return Math.max(mDrawable.getIntrinsicWidth(), mMinSize);
3644        }
3645
3646        private int getPreferredHeight() {
3647            return Math.max(mDrawable.getIntrinsicHeight(), mMinSize);
3648        }
3649
3650        public void show() {
3651            if (isShowing()) return;
3652
3653            getPositionListener().addSubscriber(this, true /* local position may change */);
3654
3655            // Make sure the offset is always considered new, even when focusing at same position
3656            mPreviousOffset = -1;
3657            positionAtCursorOffset(getCurrentCursorOffset(), false);
3658        }
3659
3660        protected void dismiss() {
3661            mIsDragging = false;
3662            mContainer.dismiss();
3663            onDetached();
3664        }
3665
3666        public void hide() {
3667            dismiss();
3668
3669            getPositionListener().removeSubscriber(this);
3670        }
3671
3672        public boolean isShowing() {
3673            return mContainer.isShowing();
3674        }
3675
3676        private boolean isVisible() {
3677            // Always show a dragging handle.
3678            if (mIsDragging) {
3679                return true;
3680            }
3681
3682            if (mTextView.isInBatchEditMode()) {
3683                return false;
3684            }
3685
3686            return isPositionVisible(mPositionX + mHotspotX + getHorizontalOffset(), mPositionY);
3687        }
3688
3689        public abstract int getCurrentCursorOffset();
3690
3691        protected abstract void updateSelection(int offset);
3692
3693        public abstract void updatePosition(float x, float y);
3694
3695        protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
3696            // A HandleView relies on the layout, which may be nulled by external methods
3697            Layout layout = mTextView.getLayout();
3698            if (layout == null) {
3699                // Will update controllers' state, hiding them and stopping selection mode if needed
3700                prepareCursorControllers();
3701                return;
3702            }
3703
3704            boolean offsetChanged = offset != mPreviousOffset;
3705            if (offsetChanged || parentScrolled) {
3706                if (offsetChanged) {
3707                    updateSelection(offset);
3708                    addPositionToTouchUpFilter(offset);
3709                }
3710                final int line = layout.getLineForOffset(offset);
3711                mPrevLine = line;
3712
3713                mPositionX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX -
3714                        getHorizontalOffset() + getCursorOffset());
3715                mPositionY = layout.getLineBottom(line);
3716
3717                // Take TextView's padding and scroll into account.
3718                mPositionX += mTextView.viewportToContentHorizontalOffset();
3719                mPositionY += mTextView.viewportToContentVerticalOffset();
3720
3721                mPreviousOffset = offset;
3722                mPositionHasChanged = true;
3723            }
3724        }
3725
3726        public void updatePosition(int parentPositionX, int parentPositionY,
3727                boolean parentPositionChanged, boolean parentScrolled) {
3728            positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled);
3729            if (parentPositionChanged || mPositionHasChanged) {
3730                if (mIsDragging) {
3731                    // Update touchToWindow offset in case of parent scrolling while dragging
3732                    if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
3733                        mTouchToWindowOffsetX += parentPositionX - mLastParentX;
3734                        mTouchToWindowOffsetY += parentPositionY - mLastParentY;
3735                        mLastParentX = parentPositionX;
3736                        mLastParentY = parentPositionY;
3737                    }
3738
3739                    onHandleMoved();
3740                }
3741
3742                if (isVisible()) {
3743                    final int positionX = parentPositionX + mPositionX;
3744                    final int positionY = parentPositionY + mPositionY;
3745                    if (isShowing()) {
3746                        mContainer.update(positionX, positionY, -1, -1);
3747                    } else {
3748                        mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY,
3749                                positionX, positionY);
3750                    }
3751                } else {
3752                    if (isShowing()) {
3753                        dismiss();
3754                    }
3755                }
3756
3757                mPositionHasChanged = false;
3758            }
3759        }
3760
3761        public void showAtLocation(int offset) {
3762            // TODO - investigate if there's a better way to show the handles
3763            // after the drag accelerator has occured.
3764            int[] tmpCords = new int[2];
3765            mTextView.getLocationInWindow(tmpCords);
3766
3767            Layout layout = mTextView.getLayout();
3768            int posX = tmpCords[0];
3769            int posY = tmpCords[1];
3770
3771            final int line = layout.getLineForOffset(offset);
3772
3773            int startX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f
3774                    - mHotspotX - getHorizontalOffset() + getCursorOffset());
3775            int startY = layout.getLineBottom(line);
3776
3777            // Take TextView's padding and scroll into account.
3778            startX += mTextView.viewportToContentHorizontalOffset();
3779            startY += mTextView.viewportToContentVerticalOffset();
3780
3781            mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY,
3782                    startX + posX, startY + posY);
3783        }
3784
3785        @Override
3786        protected void onDraw(Canvas c) {
3787            final int drawWidth = mDrawable.getIntrinsicWidth();
3788            final int left = getHorizontalOffset();
3789
3790            mDrawable.setBounds(left, 0, left + drawWidth, mDrawable.getIntrinsicHeight());
3791            mDrawable.draw(c);
3792        }
3793
3794        private int getHorizontalOffset() {
3795            final int width = getPreferredWidth();
3796            final int drawWidth = mDrawable.getIntrinsicWidth();
3797            final int left;
3798            switch (mHorizontalGravity) {
3799                case Gravity.LEFT:
3800                    left = 0;
3801                    break;
3802                default:
3803                case Gravity.CENTER:
3804                    left = (width - drawWidth) / 2;
3805                    break;
3806                case Gravity.RIGHT:
3807                    left = width - drawWidth;
3808                    break;
3809            }
3810            return left;
3811        }
3812
3813        protected int getCursorOffset() {
3814            return 0;
3815        }
3816
3817        @Override
3818        public boolean onTouchEvent(MotionEvent ev) {
3819            updateFloatingToolbarVisibility(ev);
3820
3821            switch (ev.getActionMasked()) {
3822                case MotionEvent.ACTION_DOWN: {
3823                    startTouchUpFilter(getCurrentCursorOffset());
3824                    mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
3825                    mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
3826
3827                    final PositionListener positionListener = getPositionListener();
3828                    mLastParentX = positionListener.getPositionX();
3829                    mLastParentY = positionListener.getPositionY();
3830                    mIsDragging = true;
3831                    break;
3832                }
3833
3834                case MotionEvent.ACTION_MOVE: {
3835                    final float rawX = ev.getRawX();
3836                    final float rawY = ev.getRawY();
3837
3838                    // Vertical hysteresis: vertical down movement tends to snap to ideal offset
3839                    final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
3840                    final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
3841                    float newVerticalOffset;
3842                    if (previousVerticalOffset < mIdealVerticalOffset) {
3843                        newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
3844                        newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
3845                    } else {
3846                        newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
3847                        newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
3848                    }
3849                    mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
3850
3851                    final float newPosX =
3852                            rawX - mTouchToWindowOffsetX + mHotspotX + getHorizontalOffset();
3853                    final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
3854
3855                    updatePosition(newPosX, newPosY);
3856                    break;
3857                }
3858
3859                case MotionEvent.ACTION_UP:
3860                    filterOnTouchUp();
3861                    mIsDragging = false;
3862                    updateDrawable();
3863                    break;
3864
3865                case MotionEvent.ACTION_CANCEL:
3866                    mIsDragging = false;
3867                    updateDrawable();
3868                    break;
3869            }
3870            return true;
3871        }
3872
3873        public boolean isDragging() {
3874            return mIsDragging;
3875        }
3876
3877        void onHandleMoved() {}
3878
3879        public void onDetached() {}
3880    }
3881
3882    private class InsertionHandleView extends HandleView {
3883        private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
3884        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
3885
3886        // Used to detect taps on the insertion handle, which will affect the insertion action mode
3887        private float mDownPositionX, mDownPositionY;
3888        private Runnable mHider;
3889
3890        public InsertionHandleView(Drawable drawable) {
3891            super(drawable, drawable);
3892        }
3893
3894        @Override
3895        public void show() {
3896            super.show();
3897
3898            final long durationSinceCutOrCopy =
3899                    SystemClock.uptimeMillis() - TextView.sLastCutCopyOrTextChangedTime;
3900
3901            // Cancel the single tap delayed runnable.
3902            if (mInsertionActionModeRunnable != null
3903                    && (mDoubleTap || isCursorInsideEasyCorrectionSpan())) {
3904                mTextView.removeCallbacks(mInsertionActionModeRunnable);
3905            }
3906
3907            // Prepare and schedule the single tap runnable to run exactly after the double tap
3908            // timeout has passed.
3909            if (!mDoubleTap && !isCursorInsideEasyCorrectionSpan()
3910                    && (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION)) {
3911                if (mTextActionMode == null) {
3912                    if (mInsertionActionModeRunnable == null) {
3913                        mInsertionActionModeRunnable = new Runnable() {
3914                            @Override
3915                            public void run() {
3916                                startInsertionActionMode();
3917                            }
3918                        };
3919                    }
3920                    mTextView.postDelayed(
3921                            mInsertionActionModeRunnable,
3922                            ViewConfiguration.getDoubleTapTimeout() + 1);
3923                }
3924
3925            }
3926
3927            hideAfterDelay();
3928        }
3929
3930        private void hideAfterDelay() {
3931            if (mHider == null) {
3932                mHider = new Runnable() {
3933                    public void run() {
3934                        hide();
3935                    }
3936                };
3937            } else {
3938                removeHiderCallback();
3939            }
3940            mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
3941        }
3942
3943        private void removeHiderCallback() {
3944            if (mHider != null) {
3945                mTextView.removeCallbacks(mHider);
3946            }
3947        }
3948
3949        @Override
3950        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
3951            return drawable.getIntrinsicWidth() / 2;
3952        }
3953
3954        @Override
3955        protected int getHorizontalGravity(boolean isRtlRun) {
3956            return Gravity.CENTER_HORIZONTAL;
3957        }
3958
3959        @Override
3960        protected int getCursorOffset() {
3961            int offset = super.getCursorOffset();
3962            final Drawable cursor = mCursorCount > 0 ? mCursorDrawable[0] : null;
3963            if (cursor != null) {
3964                cursor.getPadding(mTempRect);
3965                offset += (cursor.getIntrinsicWidth() - mTempRect.left - mTempRect.right) / 2;
3966            }
3967            return offset;
3968        }
3969
3970        @Override
3971        public boolean onTouchEvent(MotionEvent ev) {
3972            final boolean result = super.onTouchEvent(ev);
3973
3974            switch (ev.getActionMasked()) {
3975                case MotionEvent.ACTION_DOWN:
3976                    mDownPositionX = ev.getRawX();
3977                    mDownPositionY = ev.getRawY();
3978                    break;
3979
3980                case MotionEvent.ACTION_UP:
3981                    if (!offsetHasBeenChanged()) {
3982                        final float deltaX = mDownPositionX - ev.getRawX();
3983                        final float deltaY = mDownPositionY - ev.getRawY();
3984                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
3985
3986                        final ViewConfiguration viewConfiguration = ViewConfiguration.get(
3987                                mTextView.getContext());
3988                        final int touchSlop = viewConfiguration.getScaledTouchSlop();
3989
3990                        if (distanceSquared < touchSlop * touchSlop) {
3991                            // Tapping on the handle toggles the insertion action mode.
3992                            if (mTextActionMode != null) {
3993                                mTextActionMode.finish();
3994                            } else {
3995                                startInsertionActionMode();
3996                            }
3997                        }
3998                    } else {
3999                        if (mTextActionMode != null) {
4000                            mTextActionMode.invalidateContentRect();
4001                        }
4002                    }
4003                    hideAfterDelay();
4004                    break;
4005
4006                case MotionEvent.ACTION_CANCEL:
4007                    hideAfterDelay();
4008                    break;
4009
4010                default:
4011                    break;
4012            }
4013
4014            return result;
4015        }
4016
4017        @Override
4018        public int getCurrentCursorOffset() {
4019            return mTextView.getSelectionStart();
4020        }
4021
4022        @Override
4023        public void updateSelection(int offset) {
4024            Selection.setSelection((Spannable) mTextView.getText(), offset);
4025        }
4026
4027        @Override
4028        public void updatePosition(float x, float y) {
4029            Layout layout = mTextView.getLayout();
4030            int offset;
4031            if (layout != null) {
4032                int currLine = getCurrentLineAdjustedForSlop(layout, mPrevLine, y);
4033                offset = mTextView.getOffsetAtCoordinate(currLine, x);
4034            } else {
4035                offset = mTextView.getOffsetForPosition(x, y);
4036            }
4037            positionAtCursorOffset(offset, false);
4038            if (mTextActionMode != null) {
4039                mTextActionMode.invalidate();
4040            }
4041        }
4042
4043        @Override
4044        void onHandleMoved() {
4045            super.onHandleMoved();
4046            removeHiderCallback();
4047        }
4048
4049        @Override
4050        public void onDetached() {
4051            super.onDetached();
4052            removeHiderCallback();
4053        }
4054    }
4055
4056    private class SelectionStartHandleView extends HandleView {
4057        // Indicates whether the cursor is making adjustments within a word.
4058        private boolean mInWord = false;
4059        // Difference between touch position and word boundary position.
4060        private float mTouchWordDelta;
4061
4062        public SelectionStartHandleView(Drawable drawableLtr, Drawable drawableRtl) {
4063            super(drawableLtr, drawableRtl);
4064        }
4065
4066        @Override
4067        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4068            if (isRtlRun) {
4069                return drawable.getIntrinsicWidth() / 4;
4070            } else {
4071                return (drawable.getIntrinsicWidth() * 3) / 4;
4072            }
4073        }
4074
4075        @Override
4076        protected int getHorizontalGravity(boolean isRtlRun) {
4077            return isRtlRun ? Gravity.LEFT : Gravity.RIGHT;
4078        }
4079
4080        @Override
4081        public int getCurrentCursorOffset() {
4082            return mTextView.getSelectionStart();
4083        }
4084
4085        @Override
4086        public void updateSelection(int offset) {
4087            Selection.setSelection((Spannable) mTextView.getText(), offset,
4088                    mTextView.getSelectionEnd());
4089            updateDrawable();
4090            if (mTextActionMode != null) {
4091                mTextActionMode.invalidate();
4092            }
4093        }
4094
4095        @Override
4096        public void updatePosition(float x, float y) {
4097            final Layout layout = mTextView.getLayout();
4098            if (layout == null) {
4099                // HandleView will deal appropriately in positionAtCursorOffset when
4100                // layout is null.
4101                positionAtCursorOffset(mTextView.getOffsetForPosition(x, y), false);
4102                return;
4103            }
4104
4105            boolean positionCursor = false;
4106            final int selectionEnd = mTextView.getSelectionEnd();
4107            int currLine = getCurrentLineAdjustedForSlop(layout, mPrevLine, y);
4108            int initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
4109
4110            if (initialOffset >= selectionEnd) {
4111                // Handles have crossed, bound it to the last selected line and
4112                // adjust by word / char as normal.
4113                currLine = layout.getLineForOffset(selectionEnd);
4114                initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
4115            }
4116
4117            int offset = initialOffset;
4118            int end = getWordEnd(offset);
4119            int start = getWordStart(offset);
4120
4121            if (offset < mPreviousOffset) {
4122                // User is increasing the selection.
4123                if (!mInWord || currLine < mPrevLine) {
4124                    // We're not in a word, or we're on a different line so we'll expand by
4125                    // word. First ensure the user has at least entered the next word.
4126                    int offsetToWord = Math.min((end - start) / 2, 2);
4127                    if (offset <= end - offsetToWord || currLine < mPrevLine) {
4128                        offset = start;
4129                    } else {
4130                        offset = mPreviousOffset;
4131                    }
4132                }
4133                if (layout != null && offset < initialOffset) {
4134                    final float adjustedX = layout.getPrimaryHorizontal(offset);
4135                    mTouchWordDelta =
4136                            mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
4137                } else {
4138                    mTouchWordDelta = 0.0f;
4139                }
4140                positionCursor = true;
4141            } else {
4142                final int adjustedOffset =
4143                        mTextView.getOffsetAtCoordinate(currLine, x - mTouchWordDelta);
4144                if (adjustedOffset > mPreviousOffset || currLine > mPrevLine) {
4145                    // User is shrinking the selection.
4146                    if (currLine > mPrevLine) {
4147                        // We're on a different line, so we'll snap to word boundaries.
4148                        offset = start;
4149                        if (layout != null && offset < initialOffset) {
4150                            final float adjustedX = layout.getPrimaryHorizontal(offset);
4151                            mTouchWordDelta =
4152                                    mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
4153                        } else {
4154                            mTouchWordDelta = 0.0f;
4155                        }
4156                    } else {
4157                        offset = adjustedOffset;
4158                    }
4159                    positionCursor = true;
4160                } else if (adjustedOffset < mPreviousOffset) {
4161                    // Handle has jumped to the start of the word, and the user is moving
4162                    // their finger towards the handle, the delta should be updated.
4163                    mTouchWordDelta = mTextView.convertToLocalHorizontalCoordinate(x)
4164                            - layout.getPrimaryHorizontal(mPreviousOffset);
4165                }
4166            }
4167
4168            if (positionCursor) {
4169                // Handles can not cross and selection is at least one character.
4170                if (offset >= selectionEnd) {
4171                    offset = getNextCursorOffset(selectionEnd, false);
4172                    mTouchWordDelta = 0.0f;
4173                }
4174                positionAtCursorOffset(offset, false);
4175            }
4176        }
4177
4178        @Override
4179        protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
4180            super.positionAtCursorOffset(offset, parentScrolled);
4181            mInWord = !getWordIteratorWithText().isBoundary(offset);
4182        }
4183
4184        @Override
4185        public boolean onTouchEvent(MotionEvent event) {
4186            boolean superResult = super.onTouchEvent(event);
4187            if (event.getActionMasked() == MotionEvent.ACTION_UP) {
4188                // Reset the touch word offset when the user has lifted their finger.
4189                mTouchWordDelta = 0.0f;
4190            }
4191            return superResult;
4192        }
4193    }
4194
4195    private class SelectionEndHandleView extends HandleView {
4196        // Indicates whether the cursor is making adjustments within a word.
4197        private boolean mInWord = false;
4198        // Difference between touch position and word boundary position.
4199        private float mTouchWordDelta;
4200
4201        public SelectionEndHandleView(Drawable drawableLtr, Drawable drawableRtl) {
4202            super(drawableLtr, drawableRtl);
4203        }
4204
4205        @Override
4206        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4207            if (isRtlRun) {
4208                return (drawable.getIntrinsicWidth() * 3) / 4;
4209            } else {
4210                return drawable.getIntrinsicWidth() / 4;
4211            }
4212        }
4213
4214        @Override
4215        protected int getHorizontalGravity(boolean isRtlRun) {
4216            return isRtlRun ? Gravity.RIGHT : Gravity.LEFT;
4217        }
4218
4219        @Override
4220        public int getCurrentCursorOffset() {
4221            return mTextView.getSelectionEnd();
4222        }
4223
4224        @Override
4225        public void updateSelection(int offset) {
4226            Selection.setSelection((Spannable) mTextView.getText(),
4227                    mTextView.getSelectionStart(), offset);
4228            if (mTextActionMode != null) {
4229                mTextActionMode.invalidate();
4230            }
4231            updateDrawable();
4232        }
4233
4234        @Override
4235        public void updatePosition(float x, float y) {
4236            final Layout layout = mTextView.getLayout();
4237            if (layout == null) {
4238                // HandleView will deal appropriately in positionAtCursorOffset when
4239                // layout is null.
4240                positionAtCursorOffset(mTextView.getOffsetForPosition(x, y), false);
4241                return;
4242            }
4243
4244            boolean positionCursor = false;
4245            final int selectionStart = mTextView.getSelectionStart();
4246            int currLine = getCurrentLineAdjustedForSlop(layout, mPrevLine, y);
4247            int initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
4248
4249            if (initialOffset <= selectionStart) {
4250                // Handles have crossed, bound it to the first selected line and
4251                // adjust by word / char as normal.
4252                currLine = layout.getLineForOffset(selectionStart);
4253                initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
4254            }
4255
4256            int offset = initialOffset;
4257            int end = getWordEnd(offset);
4258            int start = getWordStart(offset);
4259
4260            if (offset > mPreviousOffset) {
4261                // User is increasing the selection.
4262                if (!mInWord || currLine > mPrevLine) {
4263                    // We're not in a word, or we're on a different line so we'll expand by
4264                    // word. First ensure the user has at least entered the next word.
4265                    int midPoint = Math.min((end - start) / 2, 2);
4266                    if (offset >= start + midPoint || currLine > mPrevLine) {
4267                        offset = end;
4268                    } else {
4269                        offset = mPreviousOffset;
4270                    }
4271                }
4272                if (offset > initialOffset) {
4273                    final float adjustedX = layout.getPrimaryHorizontal(offset);
4274                    mTouchWordDelta =
4275                            adjustedX - mTextView.convertToLocalHorizontalCoordinate(x);
4276                } else {
4277                    mTouchWordDelta = 0.0f;
4278                }
4279                positionCursor = true;
4280            } else {
4281                final int adjustedOffset =
4282                        mTextView.getOffsetAtCoordinate(currLine, x + mTouchWordDelta);
4283                if (adjustedOffset < mPreviousOffset || currLine < mPrevLine) {
4284                    // User is shrinking the selection.
4285                    if (currLine < mPrevLine) {
4286                        // We're on a different line, so we'll snap to word boundaries.
4287                        offset = end;
4288                        if (offset > initialOffset) {
4289                            final float adjustedX = layout.getPrimaryHorizontal(offset);
4290                            mTouchWordDelta =
4291                                    adjustedX - mTextView.convertToLocalHorizontalCoordinate(x);
4292                        } else {
4293                            mTouchWordDelta = 0.0f;
4294                        }
4295                    } else {
4296                        offset = adjustedOffset;
4297                    }
4298                    positionCursor = true;
4299                } else if (adjustedOffset > mPreviousOffset) {
4300                    // Handle has jumped to the end of the word, and the user is moving
4301                    // their finger towards the handle, the delta should be updated.
4302                    mTouchWordDelta = layout.getPrimaryHorizontal(mPreviousOffset)
4303                            - mTextView.convertToLocalHorizontalCoordinate(x);
4304                }
4305            }
4306
4307            if (positionCursor) {
4308                // Handles can not cross and selection is at least one character.
4309                if (offset <= selectionStart) {
4310                    offset = getNextCursorOffset(selectionStart, true);
4311                    mTouchWordDelta = 0.0f;
4312                }
4313                positionAtCursorOffset(offset, false);
4314            }
4315        }
4316
4317        @Override
4318        protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
4319            super.positionAtCursorOffset(offset, parentScrolled);
4320            mInWord = !getWordIteratorWithText().isBoundary(offset);
4321        }
4322
4323        @Override
4324        public boolean onTouchEvent(MotionEvent event) {
4325            boolean superResult = super.onTouchEvent(event);
4326            if (event.getActionMasked() == MotionEvent.ACTION_UP) {
4327                // Reset the touch word offset when the user has lifted their finger.
4328                mTouchWordDelta = 0.0f;
4329            }
4330            return superResult;
4331        }
4332    }
4333
4334    private int getCurrentLineAdjustedForSlop(Layout layout, int prevLine, float y) {
4335        if (layout == null || prevLine > layout.getLineCount()
4336                || layout.getLineCount() <= 0 || prevLine < 0) {
4337            // Invalid parameters, just return whatever line is at y.
4338            return mTextView.getLineAtCoordinate(y);
4339        }
4340
4341        final float verticalOffset = mTextView.viewportToContentVerticalOffset();
4342        final int lineCount = layout.getLineCount();
4343        final float slop = mTextView.getLineHeight() * LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS;
4344
4345        final float firstLineTop = layout.getLineTop(0) + verticalOffset;
4346        final float prevLineTop = layout.getLineTop(prevLine) + verticalOffset;
4347        final float yTopBound = Math.max(prevLineTop - slop, firstLineTop + slop);
4348
4349        final float lastLineBottom = layout.getLineBottom(lineCount - 1) + verticalOffset;
4350        final float prevLineBottom = layout.getLineBottom(prevLine) + verticalOffset;
4351        final float yBottomBound = Math.min(prevLineBottom + slop, lastLineBottom - slop);
4352
4353        // Determine if we've moved lines based on y position and previous line.
4354        int currLine;
4355        if (y <= yTopBound) {
4356            currLine = Math.max(prevLine - 1, 0);
4357        } else if (y >= yBottomBound) {
4358            currLine = Math.min(prevLine + 1, lineCount - 1);
4359        } else {
4360            currLine = prevLine;
4361        }
4362        return currLine;
4363    }
4364
4365    /**
4366     * A CursorController instance can be used to control a cursor in the text.
4367     */
4368    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
4369        /**
4370         * Makes the cursor controller visible on screen.
4371         * See also {@link #hide()}.
4372         */
4373        public void show();
4374
4375        /**
4376         * Hide the cursor controller from screen.
4377         * See also {@link #show()}.
4378         */
4379        public void hide();
4380
4381        /**
4382         * Called when the view is detached from window. Perform house keeping task, such as
4383         * stopping Runnable thread that would otherwise keep a reference on the context, thus
4384         * preventing the activity from being recycled.
4385         */
4386        public void onDetached();
4387    }
4388
4389    private class InsertionPointCursorController implements CursorController {
4390        private InsertionHandleView mHandle;
4391
4392        public void show() {
4393            getHandle().show();
4394
4395            if (mSelectionModifierCursorController != null) {
4396                mSelectionModifierCursorController.hide();
4397            }
4398        }
4399
4400        public void hide() {
4401            if (mHandle != null) {
4402                mHandle.hide();
4403            }
4404        }
4405
4406        public void onTouchModeChanged(boolean isInTouchMode) {
4407            if (!isInTouchMode) {
4408                hide();
4409            }
4410        }
4411
4412        private InsertionHandleView getHandle() {
4413            if (mSelectHandleCenter == null) {
4414                mSelectHandleCenter = mTextView.getContext().getDrawable(
4415                        mTextView.mTextSelectHandleRes);
4416            }
4417            if (mHandle == null) {
4418                mHandle = new InsertionHandleView(mSelectHandleCenter);
4419            }
4420            return mHandle;
4421        }
4422
4423        @Override
4424        public void onDetached() {
4425            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
4426            observer.removeOnTouchModeChangeListener(this);
4427
4428            if (mHandle != null) mHandle.onDetached();
4429        }
4430    }
4431
4432    class SelectionModifierCursorController implements CursorController {
4433        // The cursor controller handles, lazily created when shown.
4434        private SelectionStartHandleView mStartHandle;
4435        private SelectionEndHandleView mEndHandle;
4436        // The offsets of that last touch down event. Remembered to start selection there.
4437        private int mMinTouchOffset, mMaxTouchOffset;
4438
4439        private float mDownPositionX, mDownPositionY;
4440        private boolean mGestureStayedInTapRegion;
4441
4442        // Where the user first starts the drag motion.
4443        private int mStartOffset = -1;
4444        // Indicates whether the user is selecting text and using the drag accelerator.
4445        private boolean mDragAcceleratorActive;
4446        private boolean mHaventMovedEnoughToStartDrag;
4447        // The line that a selection happened most recently with the drag accelerator.
4448        private int mLineSelectionIsOn = -1;
4449        // Whether the drag accelerator has selected past the initial line.
4450        private boolean mSwitchedLines = false;
4451
4452        SelectionModifierCursorController() {
4453            resetTouchOffsets();
4454        }
4455
4456        public void show() {
4457            if (mTextView.isInBatchEditMode()) {
4458                return;
4459            }
4460            initDrawables();
4461            initHandles();
4462            hideInsertionPointCursorController();
4463        }
4464
4465        private void initDrawables() {
4466            if (mSelectHandleLeft == null) {
4467                mSelectHandleLeft = mTextView.getContext().getDrawable(
4468                        mTextView.mTextSelectHandleLeftRes);
4469            }
4470            if (mSelectHandleRight == null) {
4471                mSelectHandleRight = mTextView.getContext().getDrawable(
4472                        mTextView.mTextSelectHandleRightRes);
4473            }
4474        }
4475
4476        private void initHandles() {
4477            // Lazy object creation has to be done before updatePosition() is called.
4478            if (mStartHandle == null) {
4479                mStartHandle = new SelectionStartHandleView(mSelectHandleLeft, mSelectHandleRight);
4480            }
4481            if (mEndHandle == null) {
4482                mEndHandle = new SelectionEndHandleView(mSelectHandleRight, mSelectHandleLeft);
4483            }
4484
4485            mStartHandle.show();
4486            mEndHandle.show();
4487
4488            hideInsertionPointCursorController();
4489        }
4490
4491        public void hide() {
4492            if (mStartHandle != null) mStartHandle.hide();
4493            if (mEndHandle != null) mEndHandle.hide();
4494        }
4495
4496        public void enterDrag() {
4497            // Just need to init the handles / hide insertion cursor.
4498            show();
4499            mDragAcceleratorActive = true;
4500            // Start location of selection.
4501            mStartOffset = mTextView.getOffsetForPosition(mLastDownPositionX,
4502                    mLastDownPositionY);
4503            mLineSelectionIsOn = mTextView.getLineAtCoordinate(mLastDownPositionY);
4504            // Don't show the handles until user has lifted finger.
4505            hide();
4506
4507            // This stops scrolling parents from intercepting the touch event, allowing
4508            // the user to continue dragging across the screen to select text; TextView will
4509            // scroll as necessary.
4510            mTextView.getParent().requestDisallowInterceptTouchEvent(true);
4511        }
4512
4513        public void onTouchEvent(MotionEvent event) {
4514            // This is done even when the View does not have focus, so that long presses can start
4515            // selection and tap can move cursor from this tap position.
4516            final float eventX = event.getX();
4517            final float eventY = event.getY();
4518            switch (event.getActionMasked()) {
4519                case MotionEvent.ACTION_DOWN:
4520                    if (extractedTextModeWillBeStarted()) {
4521                        // Prevent duplicating the selection handles until the mode starts.
4522                        hide();
4523                    } else {
4524                        // Remember finger down position, to be able to start selection from there.
4525                        mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(
4526                                eventX, eventY);
4527
4528                        // Double tap detection
4529                        if (mGestureStayedInTapRegion) {
4530                            if (mDoubleTap) {
4531                                final float deltaX = eventX - mDownPositionX;
4532                                final float deltaY = eventY - mDownPositionY;
4533                                final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
4534
4535                                ViewConfiguration viewConfiguration = ViewConfiguration.get(
4536                                        mTextView.getContext());
4537                                int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop();
4538                                boolean stayedInArea =
4539                                        distanceSquared < doubleTapSlop * doubleTapSlop;
4540
4541                                if (stayedInArea && isPositionOnText(eventX, eventY)) {
4542                                    selectCurrentWordAndStartDrag();
4543                                    mDiscardNextActionUp = true;
4544                                }
4545                            }
4546                        }
4547
4548                        mDownPositionX = eventX;
4549                        mDownPositionY = eventY;
4550                        mGestureStayedInTapRegion = true;
4551                        mHaventMovedEnoughToStartDrag = true;
4552                    }
4553                    break;
4554
4555                case MotionEvent.ACTION_POINTER_DOWN:
4556                case MotionEvent.ACTION_POINTER_UP:
4557                    // Handle multi-point gestures. Keep min and max offset positions.
4558                    // Only activated for devices that correctly handle multi-touch.
4559                    if (mTextView.getContext().getPackageManager().hasSystemFeature(
4560                            PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
4561                        updateMinAndMaxOffsets(event);
4562                    }
4563                    break;
4564
4565                case MotionEvent.ACTION_MOVE:
4566                    final ViewConfiguration viewConfig = ViewConfiguration.get(
4567                            mTextView.getContext());
4568                    final int touchSlop = viewConfig.getScaledTouchSlop();
4569
4570                    if (mGestureStayedInTapRegion || mHaventMovedEnoughToStartDrag) {
4571                        final float deltaX = eventX - mDownPositionX;
4572                        final float deltaY = eventY - mDownPositionY;
4573                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
4574
4575                        if (mGestureStayedInTapRegion) {
4576                            int doubleTapTouchSlop = viewConfig.getScaledDoubleTapTouchSlop();
4577                            mGestureStayedInTapRegion =
4578                                    distanceSquared <= doubleTapTouchSlop * doubleTapTouchSlop;
4579                        }
4580                        if (mHaventMovedEnoughToStartDrag) {
4581                            // We don't start dragging until the user has moved enough.
4582                            mHaventMovedEnoughToStartDrag =
4583                                    distanceSquared <= touchSlop * touchSlop;
4584                        }
4585                    }
4586
4587                    if (mStartHandle != null && mStartHandle.isShowing()) {
4588                        // Don't do the drag if the handles are showing already.
4589                        break;
4590                    }
4591
4592                    if (mStartOffset != -1 && mTextView.getLayout() != null) {
4593                        if (!mHaventMovedEnoughToStartDrag) {
4594
4595                            float y = eventY;
4596                            if (mSwitchedLines) {
4597                                // Offset the finger by the same vertical offset as the handles.
4598                                // This improves visibility of the content being selected by
4599                                // shifting the finger below the content, this is applied once
4600                                // the user has switched lines.
4601                                final float fingerOffset = (mStartHandle != null)
4602                                        ? mStartHandle.getIdealVerticalOffset()
4603                                        : touchSlop;
4604                                y = eventY - fingerOffset;
4605                            }
4606
4607                            final int currLine = getCurrentLineAdjustedForSlop(
4608                                    mTextView.getLayout(),
4609                                    mLineSelectionIsOn, y);
4610                            if (!mSwitchedLines && currLine != mLineSelectionIsOn) {
4611                                // Break early here, we want to offset the finger position from
4612                                // the selection highlight, once the user moved their finger
4613                                // to a different line we should apply the offset and *not* switch
4614                                // lines until recomputing the position with the finger offset.
4615                                mSwitchedLines = true;
4616                                break;
4617                            }
4618
4619                            int startOffset;
4620                            int offset = mTextView.getOffsetAtCoordinate(currLine, eventX);
4621                            // Snap to word boundaries.
4622                            if (mStartOffset < offset) {
4623                                // Expanding with end handle.
4624                                offset = getWordEnd(offset);
4625                                startOffset = getWordStart(mStartOffset);
4626                            } else {
4627                                // Expanding with start handle.
4628                                offset = getWordStart(offset);
4629                                startOffset = getWordEnd(mStartOffset);
4630                            }
4631                            mLineSelectionIsOn = currLine;
4632                            Selection.setSelection((Spannable) mTextView.getText(),
4633                                    startOffset, offset);
4634                        }
4635                    }
4636                    break;
4637
4638                case MotionEvent.ACTION_UP:
4639                    if (mDragAcceleratorActive) {
4640                        // No longer dragging to select text, let the parent intercept events.
4641                        mTextView.getParent().requestDisallowInterceptTouchEvent(false);
4642
4643                        show();
4644                        int startOffset = mTextView.getSelectionStart();
4645                        int endOffset = mTextView.getSelectionEnd();
4646
4647                        // Since we don't let drag handles pass once they're visible, we need to
4648                        // make sure the start / end locations are correct because the user *can*
4649                        // switch directions during the initial drag.
4650                        if (endOffset < startOffset) {
4651                            int tmp = endOffset;
4652                            endOffset = startOffset;
4653                            startOffset = tmp;
4654
4655                            // Also update the selection with the right offsets in this case.
4656                            Selection.setSelection((Spannable) mTextView.getText(),
4657                                    startOffset, endOffset);
4658                        }
4659
4660                        // Need to do this to display the handles.
4661                        mStartHandle.showAtLocation(startOffset);
4662                        mEndHandle.showAtLocation(endOffset);
4663
4664                        // No longer the first dragging motion, reset.
4665                        if (!(mTextView.isInExtractedMode())) {
4666                            startSelectionActionMode();
4667                        }
4668                        mDragAcceleratorActive = false;
4669                        mStartOffset = -1;
4670                        mSwitchedLines = false;
4671                    }
4672                    break;
4673            }
4674        }
4675
4676        /**
4677         * @param event
4678         */
4679        private void updateMinAndMaxOffsets(MotionEvent event) {
4680            int pointerCount = event.getPointerCount();
4681            for (int index = 0; index < pointerCount; index++) {
4682                int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index));
4683                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
4684                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
4685            }
4686        }
4687
4688        public int getMinTouchOffset() {
4689            return mMinTouchOffset;
4690        }
4691
4692        public int getMaxTouchOffset() {
4693            return mMaxTouchOffset;
4694        }
4695
4696        public void resetTouchOffsets() {
4697            mMinTouchOffset = mMaxTouchOffset = -1;
4698            mStartOffset = -1;
4699            mDragAcceleratorActive = false;
4700            mSwitchedLines = false;
4701        }
4702
4703        /**
4704         * @return true iff this controller is currently used to move the selection start.
4705         */
4706        public boolean isSelectionStartDragged() {
4707            return mStartHandle != null && mStartHandle.isDragging();
4708        }
4709
4710        /**
4711         * @return true if the user is selecting text using the drag accelerator.
4712         */
4713        public boolean isDragAcceleratorActive() {
4714            return mDragAcceleratorActive;
4715        }
4716
4717        public void onTouchModeChanged(boolean isInTouchMode) {
4718            if (!isInTouchMode) {
4719                hide();
4720            }
4721        }
4722
4723        @Override
4724        public void onDetached() {
4725            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
4726            observer.removeOnTouchModeChangeListener(this);
4727
4728            if (mStartHandle != null) mStartHandle.onDetached();
4729            if (mEndHandle != null) mEndHandle.onDetached();
4730        }
4731    }
4732
4733    private class CorrectionHighlighter {
4734        private final Path mPath = new Path();
4735        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
4736        private int mStart, mEnd;
4737        private long mFadingStartTime;
4738        private RectF mTempRectF;
4739        private final static int FADE_OUT_DURATION = 400;
4740
4741        public CorrectionHighlighter() {
4742            mPaint.setCompatibilityScaling(mTextView.getResources().getCompatibilityInfo().
4743                    applicationScale);
4744            mPaint.setStyle(Paint.Style.FILL);
4745        }
4746
4747        public void highlight(CorrectionInfo info) {
4748            mStart = info.getOffset();
4749            mEnd = mStart + info.getNewText().length();
4750            mFadingStartTime = SystemClock.uptimeMillis();
4751
4752            if (mStart < 0 || mEnd < 0) {
4753                stopAnimation();
4754            }
4755        }
4756
4757        public void draw(Canvas canvas, int cursorOffsetVertical) {
4758            if (updatePath() && updatePaint()) {
4759                if (cursorOffsetVertical != 0) {
4760                    canvas.translate(0, cursorOffsetVertical);
4761                }
4762
4763                canvas.drawPath(mPath, mPaint);
4764
4765                if (cursorOffsetVertical != 0) {
4766                    canvas.translate(0, -cursorOffsetVertical);
4767                }
4768                invalidate(true); // TODO invalidate cursor region only
4769            } else {
4770                stopAnimation();
4771                invalidate(false); // TODO invalidate cursor region only
4772            }
4773        }
4774
4775        private boolean updatePaint() {
4776            final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
4777            if (duration > FADE_OUT_DURATION) return false;
4778
4779            final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
4780            final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor);
4781            final int color = (mTextView.mHighlightColor & 0x00FFFFFF) +
4782                    ((int) (highlightColorAlpha * coef) << 24);
4783            mPaint.setColor(color);
4784            return true;
4785        }
4786
4787        private boolean updatePath() {
4788            final Layout layout = mTextView.getLayout();
4789            if (layout == null) return false;
4790
4791            // Update in case text is edited while the animation is run
4792            final int length = mTextView.getText().length();
4793            int start = Math.min(length, mStart);
4794            int end = Math.min(length, mEnd);
4795
4796            mPath.reset();
4797            layout.getSelectionPath(start, end, mPath);
4798            return true;
4799        }
4800
4801        private void invalidate(boolean delayed) {
4802            if (mTextView.getLayout() == null) return;
4803
4804            if (mTempRectF == null) mTempRectF = new RectF();
4805            mPath.computeBounds(mTempRectF, false);
4806
4807            int left = mTextView.getCompoundPaddingLeft();
4808            int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true);
4809
4810            if (delayed) {
4811                mTextView.postInvalidateOnAnimation(
4812                        left + (int) mTempRectF.left, top + (int) mTempRectF.top,
4813                        left + (int) mTempRectF.right, top + (int) mTempRectF.bottom);
4814            } else {
4815                mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top,
4816                        (int) mTempRectF.right, (int) mTempRectF.bottom);
4817            }
4818        }
4819
4820        private void stopAnimation() {
4821            Editor.this.mCorrectionHighlighter = null;
4822        }
4823    }
4824
4825    private static class ErrorPopup extends PopupWindow {
4826        private boolean mAbove = false;
4827        private final TextView mView;
4828        private int mPopupInlineErrorBackgroundId = 0;
4829        private int mPopupInlineErrorAboveBackgroundId = 0;
4830
4831        ErrorPopup(TextView v, int width, int height) {
4832            super(v, width, height);
4833            mView = v;
4834            // Make sure the TextView has a background set as it will be used the first time it is
4835            // shown and positioned. Initialized with below background, which should have
4836            // dimensions identical to the above version for this to work (and is more likely).
4837            mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
4838                    com.android.internal.R.styleable.Theme_errorMessageBackground);
4839            mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
4840        }
4841
4842        void fixDirection(boolean above) {
4843            mAbove = above;
4844
4845            if (above) {
4846                mPopupInlineErrorAboveBackgroundId =
4847                    getResourceId(mPopupInlineErrorAboveBackgroundId,
4848                            com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
4849            } else {
4850                mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
4851                        com.android.internal.R.styleable.Theme_errorMessageBackground);
4852            }
4853
4854            mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId :
4855                mPopupInlineErrorBackgroundId);
4856        }
4857
4858        private int getResourceId(int currentId, int index) {
4859            if (currentId == 0) {
4860                TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
4861                        R.styleable.Theme);
4862                currentId = styledAttributes.getResourceId(index, 0);
4863                styledAttributes.recycle();
4864            }
4865            return currentId;
4866        }
4867
4868        @Override
4869        public void update(int x, int y, int w, int h, boolean force) {
4870            super.update(x, y, w, h, force);
4871
4872            boolean above = isAboveAnchor();
4873            if (above != mAbove) {
4874                fixDirection(above);
4875            }
4876        }
4877    }
4878
4879    static class InputContentType {
4880        int imeOptions = EditorInfo.IME_NULL;
4881        String privateImeOptions;
4882        CharSequence imeActionLabel;
4883        int imeActionId;
4884        Bundle extras;
4885        OnEditorActionListener onEditorActionListener;
4886        boolean enterDown;
4887    }
4888
4889    static class InputMethodState {
4890        ExtractedTextRequest mExtractedTextRequest;
4891        final ExtractedText mExtractedText = new ExtractedText();
4892        int mBatchEditNesting;
4893        boolean mCursorChanged;
4894        boolean mSelectionModeChanged;
4895        boolean mContentChanged;
4896        int mChangedStart, mChangedEnd, mChangedDelta;
4897    }
4898
4899    /**
4900     * @return True iff (start, end) is a valid range within the text.
4901     */
4902    private static boolean isValidRange(CharSequence text, int start, int end) {
4903        return 0 <= start && start <= end && end <= text.length();
4904    }
4905
4906    /**
4907     * An InputFilter that monitors text input to maintain undo history. It does not modify the
4908     * text being typed (and hence always returns null from the filter() method).
4909     */
4910    public static class UndoInputFilter implements InputFilter {
4911        private final Editor mEditor;
4912
4913        // Whether the current filter pass is directly caused by an end-user text edit.
4914        private boolean mIsUserEdit;
4915
4916        // Whether the text field is handling an IME composition. Must be parceled in case the user
4917        // rotates the screen during composition.
4918        private boolean mHasComposition;
4919
4920        public UndoInputFilter(Editor editor) {
4921            mEditor = editor;
4922        }
4923
4924        public void saveInstanceState(Parcel parcel) {
4925            parcel.writeInt(mIsUserEdit ? 1 : 0);
4926            parcel.writeInt(mHasComposition ? 1 : 0);
4927        }
4928
4929        public void restoreInstanceState(Parcel parcel) {
4930            mIsUserEdit = parcel.readInt() != 0;
4931            mHasComposition = parcel.readInt() != 0;
4932        }
4933
4934        /**
4935         * Signals that a user-triggered edit is starting.
4936         */
4937        public void beginBatchEdit() {
4938            if (DEBUG_UNDO) Log.d(TAG, "beginBatchEdit");
4939            mIsUserEdit = true;
4940        }
4941
4942        public void endBatchEdit() {
4943            if (DEBUG_UNDO) Log.d(TAG, "endBatchEdit");
4944            mIsUserEdit = false;
4945        }
4946
4947        @Override
4948        public CharSequence filter(CharSequence source, int start, int end,
4949                Spanned dest, int dstart, int dend) {
4950            if (DEBUG_UNDO) {
4951                Log.d(TAG, "filter: source=" + source + " (" + start + "-" + end + ") " +
4952                        "dest=" + dest + " (" + dstart + "-" + dend + ")");
4953            }
4954
4955            // Check to see if this edit should be tracked for undo.
4956            if (!canUndoEdit(source, start, end, dest, dstart, dend)) {
4957                return null;
4958            }
4959
4960            // Check for and handle IME composition edits.
4961            if (handleCompositionEdit(source, start, end, dstart)) {
4962                return null;
4963            }
4964
4965            // Handle keyboard edits.
4966            handleKeyboardEdit(source, start, end, dest, dstart, dend);
4967            return null;
4968        }
4969
4970        /**
4971         * Returns true iff the edit was handled, either because it should be ignored or because
4972         * this function created an undo operation for it.
4973         */
4974        private boolean handleCompositionEdit(CharSequence source, int start, int end, int dstart) {
4975            // Ignore edits while the user is composing.
4976            if (isComposition(source)) {
4977                mHasComposition = true;
4978                return true;
4979            }
4980            final boolean hadComposition = mHasComposition;
4981            mHasComposition = false;
4982
4983            // Check for the transition out of the composing state.
4984            if (hadComposition) {
4985                // If there was no text the user canceled composition. Ignore the edit.
4986                if (start == end) {
4987                    return true;
4988                }
4989
4990                // Otherwise the user inserted the composition.
4991                String newText = TextUtils.substring(source, start, end);
4992                EditOperation edit = new EditOperation(mEditor, "", dstart, newText);
4993                recordEdit(edit, false /* forceMerge */);
4994                return true;
4995            }
4996
4997            // This was neither a composition event nor a transition out of composing.
4998            return false;
4999        }
5000
5001        private void handleKeyboardEdit(CharSequence source, int start, int end,
5002                Spanned dest, int dstart, int dend) {
5003            // An application may install a TextWatcher to provide additional modifications after
5004            // the initial input filters run (e.g. a credit card formatter that adds spaces to a
5005            // string). This results in multiple filter() calls for what the user considers to be
5006            // a single operation. Always undo the whole set of changes in one step.
5007            final boolean forceMerge = isInTextWatcher();
5008
5009            // Build a new operation with all the information from this edit.
5010            String newText = TextUtils.substring(source, start, end);
5011            String oldText = TextUtils.substring(dest, dstart, dend);
5012            EditOperation edit = new EditOperation(mEditor, oldText, dstart, newText);
5013            recordEdit(edit, forceMerge);
5014        }
5015
5016        /**
5017         * Fetches the last undo operation and checks to see if a new edit should be merged into it.
5018         * If forceMerge is true then the new edit is always merged.
5019         */
5020        private void recordEdit(EditOperation edit, boolean forceMerge) {
5021            // Fetch the last edit operation and attempt to merge in the new edit.
5022            final UndoManager um = mEditor.mUndoManager;
5023            um.beginUpdate("Edit text");
5024            EditOperation lastEdit = um.getLastOperation(
5025                  EditOperation.class, mEditor.mUndoOwner, UndoManager.MERGE_MODE_UNIQUE);
5026            if (lastEdit == null) {
5027                // Add this as the first edit.
5028                if (DEBUG_UNDO) Log.d(TAG, "filter: adding first op " + edit);
5029                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
5030            } else if (forceMerge) {
5031                // Forced merges take priority because they could be the result of a non-user-edit
5032                // change and this case should not create a new undo operation.
5033                if (DEBUG_UNDO) Log.d(TAG, "filter: force merge " + edit);
5034                lastEdit.forceMergeWith(edit);
5035            } else if (!mIsUserEdit) {
5036                // An application directly modified the Editable outside of a text edit. Treat this
5037                // as a new change and don't attempt to merge.
5038                if (DEBUG_UNDO) Log.d(TAG, "non-user edit, new op " + edit);
5039                um.commitState(mEditor.mUndoOwner);
5040                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
5041            } else if (lastEdit.mergeWith(edit)) {
5042                // Merge succeeded, nothing else to do.
5043                if (DEBUG_UNDO) Log.d(TAG, "filter: merge succeeded, created " + lastEdit);
5044            } else {
5045                // Could not merge with the last edit, so commit the last edit and add this edit.
5046                if (DEBUG_UNDO) Log.d(TAG, "filter: merge failed, adding " + edit);
5047                um.commitState(mEditor.mUndoOwner);
5048                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
5049            }
5050            um.endUpdate();
5051        }
5052
5053        private boolean canUndoEdit(CharSequence source, int start, int end,
5054                Spanned dest, int dstart, int dend) {
5055            if (!mEditor.mAllowUndo) {
5056                if (DEBUG_UNDO) Log.d(TAG, "filter: undo is disabled");
5057                return false;
5058            }
5059
5060            if (mEditor.mUndoManager.isInUndo()) {
5061                if (DEBUG_UNDO) Log.d(TAG, "filter: skipping, currently performing undo/redo");
5062                return false;
5063            }
5064
5065            // Text filters run before input operations are applied. However, some input operations
5066            // are invalid and will throw exceptions when applied. This is common in tests. Don't
5067            // attempt to undo invalid operations.
5068            if (!isValidRange(source, start, end) || !isValidRange(dest, dstart, dend)) {
5069                if (DEBUG_UNDO) Log.d(TAG, "filter: invalid op");
5070                return false;
5071            }
5072
5073            // Earlier filters can rewrite input to be a no-op, for example due to a length limit
5074            // on an input field. Skip no-op changes.
5075            if (start == end && dstart == dend) {
5076                if (DEBUG_UNDO) Log.d(TAG, "filter: skipping no-op");
5077                return false;
5078            }
5079
5080            return true;
5081        }
5082
5083        private boolean isComposition(CharSequence source) {
5084            if (!(source instanceof Spannable)) {
5085                return false;
5086            }
5087            // This is a composition edit if the source has a non-zero-length composing span.
5088            Spannable text = (Spannable) source;
5089            int composeBegin = EditableInputConnection.getComposingSpanStart(text);
5090            int composeEnd = EditableInputConnection.getComposingSpanEnd(text);
5091            return composeBegin < composeEnd;
5092        }
5093
5094        private boolean isInTextWatcher() {
5095            CharSequence text = mEditor.mTextView.getText();
5096            return (text instanceof SpannableStringBuilder)
5097                    && ((SpannableStringBuilder) text).getTextWatcherDepth() > 0;
5098        }
5099    }
5100
5101    /**
5102     * An operation to undo a single "edit" to a text view.
5103     */
5104    public static class EditOperation extends UndoOperation<Editor> {
5105        private static final int TYPE_INSERT = 0;
5106        private static final int TYPE_DELETE = 1;
5107        private static final int TYPE_REPLACE = 2;
5108
5109        private int mType;
5110        private String mOldText;
5111        private int mOldTextStart;
5112        private String mNewText;
5113        private int mNewTextStart;
5114
5115        private int mOldCursorPos;
5116        private int mNewCursorPos;
5117
5118        /**
5119         * Constructs an edit operation from a text input operation on editor that replaces the
5120         * oldText starting at dstart with newText.
5121         */
5122        public EditOperation(Editor editor, String oldText, int dstart, String newText) {
5123            super(editor.mUndoOwner);
5124            mOldText = oldText;
5125            mNewText = newText;
5126
5127            // Determine the type of the edit and store where it occurred. Avoid storing
5128            // irrevelant data (e.g. mNewTextStart for a delete) because that makes the
5129            // merging logic more complex (e.g. merging deletes could lead to mNewTextStart being
5130            // outside the bounds of the final text).
5131            if (mNewText.length() > 0 && mOldText.length() == 0) {
5132                mType = TYPE_INSERT;
5133                mNewTextStart = dstart;
5134            } else if (mNewText.length() == 0 && mOldText.length() > 0) {
5135                mType = TYPE_DELETE;
5136                mOldTextStart = dstart;
5137            } else {
5138                mType = TYPE_REPLACE;
5139                mOldTextStart = mNewTextStart = dstart;
5140            }
5141
5142            // Store cursor data.
5143            mOldCursorPos = editor.mTextView.getSelectionStart();
5144            mNewCursorPos = dstart + mNewText.length();
5145        }
5146
5147        public EditOperation(Parcel src, ClassLoader loader) {
5148            super(src, loader);
5149            mType = src.readInt();
5150            mOldText = src.readString();
5151            mOldTextStart = src.readInt();
5152            mNewText = src.readString();
5153            mNewTextStart = src.readInt();
5154            mOldCursorPos = src.readInt();
5155            mNewCursorPos = src.readInt();
5156        }
5157
5158        @Override
5159        public void writeToParcel(Parcel dest, int flags) {
5160            dest.writeInt(mType);
5161            dest.writeString(mOldText);
5162            dest.writeInt(mOldTextStart);
5163            dest.writeString(mNewText);
5164            dest.writeInt(mNewTextStart);
5165            dest.writeInt(mOldCursorPos);
5166            dest.writeInt(mNewCursorPos);
5167        }
5168
5169        private int getNewTextEnd() {
5170            return mNewTextStart + mNewText.length();
5171        }
5172
5173        private int getOldTextEnd() {
5174            return mOldTextStart + mOldText.length();
5175        }
5176
5177        @Override
5178        public void commit() {
5179        }
5180
5181        @Override
5182        public void undo() {
5183            if (DEBUG_UNDO) Log.d(TAG, "undo");
5184            // Remove the new text and insert the old.
5185            Editor editor = getOwnerData();
5186            Editable text = (Editable) editor.mTextView.getText();
5187            modifyText(text, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
5188                    mOldCursorPos);
5189        }
5190
5191        @Override
5192        public void redo() {
5193            if (DEBUG_UNDO) Log.d(TAG, "redo");
5194            // Remove the old text and insert the new.
5195            Editor editor = getOwnerData();
5196            Editable text = (Editable) editor.mTextView.getText();
5197            modifyText(text, mOldTextStart, getOldTextEnd(), mNewText, mNewTextStart,
5198                    mNewCursorPos);
5199        }
5200
5201        /**
5202         * Attempts to merge this existing operation with a new edit.
5203         * @param edit The new edit operation.
5204         * @return If the merge succeeded, returns true. Otherwise returns false and leaves this
5205         * object unchanged.
5206         */
5207        private boolean mergeWith(EditOperation edit) {
5208            if (DEBUG_UNDO) {
5209                Log.d(TAG, "mergeWith old " + this);
5210                Log.d(TAG, "mergeWith new " + edit);
5211            }
5212            switch (mType) {
5213                case TYPE_INSERT:
5214                    return mergeInsertWith(edit);
5215                case TYPE_DELETE:
5216                    return mergeDeleteWith(edit);
5217                case TYPE_REPLACE:
5218                    return mergeReplaceWith(edit);
5219                default:
5220                    return false;
5221            }
5222        }
5223
5224        private boolean mergeInsertWith(EditOperation edit) {
5225            // Only merge continuous insertions.
5226            if (edit.mType != TYPE_INSERT) {
5227                return false;
5228            }
5229            // Only merge insertions that are contiguous.
5230            if (getNewTextEnd() != edit.mNewTextStart) {
5231                return false;
5232            }
5233            mNewText += edit.mNewText;
5234            mNewCursorPos = edit.mNewCursorPos;
5235            return true;
5236        }
5237
5238        // TODO: Support forward delete.
5239        private boolean mergeDeleteWith(EditOperation edit) {
5240            // Only merge continuous deletes.
5241            if (edit.mType != TYPE_DELETE) {
5242                return false;
5243            }
5244            // Only merge deletions that are contiguous.
5245            if (mOldTextStart != edit.getOldTextEnd()) {
5246                return false;
5247            }
5248            mOldTextStart = edit.mOldTextStart;
5249            mOldText = edit.mOldText + mOldText;
5250            mNewCursorPos = edit.mNewCursorPos;
5251            return true;
5252        }
5253
5254        private boolean mergeReplaceWith(EditOperation edit) {
5255            // Replacements can merge only with adjacent inserts.
5256            if (edit.mType != TYPE_INSERT || getNewTextEnd() != edit.mNewTextStart) {
5257                return false;
5258            }
5259            mOldText += edit.mOldText;
5260            mNewText += edit.mNewText;
5261            mNewCursorPos = edit.mNewCursorPos;
5262            return true;
5263        }
5264
5265        /**
5266         * Forcibly creates a single merged edit operation by simulating the entire text
5267         * contents being replaced.
5268         */
5269        public void forceMergeWith(EditOperation edit) {
5270            if (DEBUG_UNDO) Log.d(TAG, "forceMerge");
5271            Editor editor = getOwnerData();
5272
5273            // Copy the text of the current field.
5274            // NOTE: Using StringBuilder instead of SpannableStringBuilder would be somewhat faster,
5275            // but would require two parallel implementations of modifyText() because Editable and
5276            // StringBuilder do not share an interface for replace/delete/insert.
5277            Editable editable = (Editable) editor.mTextView.getText();
5278            Editable originalText = new SpannableStringBuilder(editable.toString());
5279
5280            // Roll back the last operation.
5281            modifyText(originalText, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
5282                    mOldCursorPos);
5283
5284            // Clone the text again and apply the new operation.
5285            Editable finalText = new SpannableStringBuilder(editable.toString());
5286            modifyText(finalText, edit.mOldTextStart, edit.getOldTextEnd(), edit.mNewText,
5287                    edit.mNewTextStart, edit.mNewCursorPos);
5288
5289            // Convert this operation into a non-mergeable replacement of the entire string.
5290            mType = TYPE_REPLACE;
5291            mNewText = finalText.toString();
5292            mNewTextStart = 0;
5293            mOldText = originalText.toString();
5294            mOldTextStart = 0;
5295            mNewCursorPos = edit.mNewCursorPos;
5296            // mOldCursorPos is unchanged.
5297        }
5298
5299        private static void modifyText(Editable text, int deleteFrom, int deleteTo,
5300                CharSequence newText, int newTextInsertAt, int newCursorPos) {
5301            // Apply the edit if it is still valid.
5302            if (isValidRange(text, deleteFrom, deleteTo) &&
5303                    newTextInsertAt <= text.length() - (deleteTo - deleteFrom)) {
5304                if (deleteFrom != deleteTo) {
5305                    text.delete(deleteFrom, deleteTo);
5306                }
5307                if (newText.length() != 0) {
5308                    text.insert(newTextInsertAt, newText);
5309                }
5310            }
5311            // Restore the cursor position. If there wasn't an old cursor (newCursorPos == -1) then
5312            // don't explicitly set it and rely on SpannableStringBuilder to position it.
5313            // TODO: Select all the text that was undone.
5314            if (0 <= newCursorPos && newCursorPos <= text.length()) {
5315                Selection.setSelection(text, newCursorPos);
5316            }
5317        }
5318
5319        private String getTypeString() {
5320            switch (mType) {
5321                case TYPE_INSERT:
5322                    return "insert";
5323                case TYPE_DELETE:
5324                    return "delete";
5325                case TYPE_REPLACE:
5326                    return "replace";
5327                default:
5328                    return "";
5329            }
5330        }
5331
5332        @Override
5333        public String toString() {
5334            return "[mType=" + getTypeString() + ", " +
5335                    "mOldText=" + mOldText + ", " +
5336                    "mOldTextStart=" + mOldTextStart + ", " +
5337                    "mNewText=" + mNewText + ", " +
5338                    "mNewTextStart=" + mNewTextStart + ", " +
5339                    "mOldCursorPos=" + mOldCursorPos + ", " +
5340                    "mNewCursorPos=" + mNewCursorPos + "]";
5341        }
5342
5343        public static final Parcelable.ClassLoaderCreator<EditOperation> CREATOR
5344                = new Parcelable.ClassLoaderCreator<EditOperation>() {
5345            @Override
5346            public EditOperation createFromParcel(Parcel in) {
5347                return new EditOperation(in, null);
5348            }
5349
5350            @Override
5351            public EditOperation createFromParcel(Parcel in, ClassLoader loader) {
5352                return new EditOperation(in, loader);
5353            }
5354
5355            @Override
5356            public EditOperation[] newArray(int size) {
5357                return new EditOperation[size];
5358            }
5359        };
5360    }
5361}
5362