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