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