Editor.java revision 7e4fbe03899a2c278ffdf1e36fb4a16dc8cc204c
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            for (int i = 0; i < suggestionSpans.length; i++) {
1810                if (suggestionSpans[i].getSuggestions().length > 0) {
1811                    return true;
1812                }
1813            }
1814            return false;
1815        }
1816        int minSpanStart = mTextView.getText().length();
1817        int maxSpanEnd = 0;
1818        int unionOfSpansCoveringSelectionStartStart = mTextView.getText().length();
1819        int unionOfSpansCoveringSelectionStartEnd = 0;
1820        boolean hasValidSuggestions = false;
1821        for (int i = 0; i < suggestionSpans.length; i++) {
1822            final int spanStart = spannable.getSpanStart(suggestionSpans[i]);
1823            final int spanEnd = spannable.getSpanEnd(suggestionSpans[i]);
1824            minSpanStart = Math.min(minSpanStart, spanStart);
1825            maxSpanEnd = Math.max(maxSpanEnd, spanEnd);
1826            if (selectionStart < spanStart || selectionStart > spanEnd) {
1827                // The span doesn't cover the current selection start point.
1828                continue;
1829            }
1830            hasValidSuggestions =
1831                    hasValidSuggestions || suggestionSpans[i].getSuggestions().length > 0;
1832            unionOfSpansCoveringSelectionStartStart =
1833                    Math.min(unionOfSpansCoveringSelectionStartStart, spanStart);
1834            unionOfSpansCoveringSelectionStartEnd =
1835                    Math.max(unionOfSpansCoveringSelectionStartEnd, spanEnd);
1836        }
1837        if (!hasValidSuggestions) {
1838            return false;
1839        }
1840        if (unionOfSpansCoveringSelectionStartStart >= unionOfSpansCoveringSelectionStartEnd) {
1841            // No spans cover the selection start point.
1842            return false;
1843        }
1844        if (minSpanStart < unionOfSpansCoveringSelectionStartStart
1845                || maxSpanEnd > unionOfSpansCoveringSelectionStartEnd) {
1846            // There is a span that is not covered by the union. In this case, we soouldn't offer
1847            // to show suggestions as it's confusing.
1848            return false;
1849        }
1850        return true;
1851    }
1852
1853    /**
1854     * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with
1855     * {@link SuggestionSpan#FLAG_EASY_CORRECT} set.
1856     */
1857    private boolean isCursorInsideEasyCorrectionSpan() {
1858        Spannable spannable = (Spannable) mTextView.getText();
1859        SuggestionSpan[] suggestionSpans = spannable.getSpans(mTextView.getSelectionStart(),
1860                mTextView.getSelectionEnd(), SuggestionSpan.class);
1861        for (int i = 0; i < suggestionSpans.length; i++) {
1862            if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) {
1863                return true;
1864            }
1865        }
1866        return false;
1867    }
1868
1869    void onTouchUpEvent(MotionEvent event) {
1870        boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect();
1871        hideControllers();
1872        CharSequence text = mTextView.getText();
1873        if (!selectAllGotFocus && text.length() > 0) {
1874            // Move cursor
1875            final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
1876            Selection.setSelection((Spannable) text, offset);
1877            if (mSpellChecker != null) {
1878                // When the cursor moves, the word that was typed may need spell check
1879                mSpellChecker.onSelectionChanged();
1880            }
1881            if (!extractedTextModeWillBeStarted()) {
1882                if (isCursorInsideEasyCorrectionSpan()) {
1883                    mShowSuggestionRunnable = new Runnable() {
1884                        public void run() {
1885                            showSuggestions();
1886                        }
1887                    };
1888                    // removeCallbacks is performed on every touch
1889                    mTextView.postDelayed(mShowSuggestionRunnable,
1890                            ViewConfiguration.getDoubleTapTimeout());
1891                } else if (hasInsertionController()) {
1892                    getInsertionController().show();
1893                }
1894            }
1895        }
1896    }
1897
1898    protected void stopSelectionActionMode() {
1899        if (mSelectionActionMode != null) {
1900            // This will hide the mSelectionModifierCursorController
1901            mSelectionActionMode.finish();
1902        }
1903    }
1904
1905    /**
1906     * @return True if this view supports insertion handles.
1907     */
1908    boolean hasInsertionController() {
1909        return mInsertionControllerEnabled;
1910    }
1911
1912    /**
1913     * @return True if this view supports selection handles.
1914     */
1915    boolean hasSelectionController() {
1916        return mSelectionControllerEnabled;
1917    }
1918
1919    InsertionPointCursorController getInsertionController() {
1920        if (!mInsertionControllerEnabled) {
1921            return null;
1922        }
1923
1924        if (mInsertionPointCursorController == null) {
1925            mInsertionPointCursorController = new InsertionPointCursorController();
1926
1927            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
1928            observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
1929        }
1930
1931        return mInsertionPointCursorController;
1932    }
1933
1934    SelectionModifierCursorController getSelectionController() {
1935        if (!mSelectionControllerEnabled) {
1936            return null;
1937        }
1938
1939        if (mSelectionModifierCursorController == null) {
1940            mSelectionModifierCursorController = new SelectionModifierCursorController();
1941
1942            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
1943            observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
1944        }
1945
1946        return mSelectionModifierCursorController;
1947    }
1948
1949    private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) {
1950        if (mCursorDrawable[cursorIndex] == null)
1951            mCursorDrawable[cursorIndex] = mTextView.getContext().getDrawable(
1952                    mTextView.mCursorDrawableRes);
1953
1954        if (mTempRect == null) mTempRect = new Rect();
1955        mCursorDrawable[cursorIndex].getPadding(mTempRect);
1956        final int width = mCursorDrawable[cursorIndex].getIntrinsicWidth();
1957        horizontal = Math.max(0.5f, horizontal - 0.5f);
1958        final int left = (int) (horizontal) - mTempRect.left;
1959        mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width,
1960                bottom + mTempRect.bottom);
1961    }
1962
1963    /**
1964     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
1965     * a dictionary) from the current input method, provided by it calling
1966     * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
1967     * implementation flashes the background of the corrected word to provide feedback to the user.
1968     *
1969     * @param info The auto correct info about the text that was corrected.
1970     */
1971    public void onCommitCorrection(CorrectionInfo info) {
1972        if (mCorrectionHighlighter == null) {
1973            mCorrectionHighlighter = new CorrectionHighlighter();
1974        } else {
1975            mCorrectionHighlighter.invalidate(false);
1976        }
1977
1978        mCorrectionHighlighter.highlight(info);
1979    }
1980
1981    void showSuggestions() {
1982        if (mSuggestionsPopupWindow == null) {
1983            mSuggestionsPopupWindow = new SuggestionsPopupWindow();
1984        }
1985        hideControllers();
1986        mSuggestionsPopupWindow.show();
1987    }
1988
1989    void onScrollChanged() {
1990        if (mPositionListener != null) {
1991            mPositionListener.onScrollChanged();
1992        }
1993        if (mSelectionActionMode != null) {
1994            mSelectionActionMode.invalidateContentRect();
1995        }
1996    }
1997
1998    /**
1999     * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
2000     */
2001    private boolean shouldBlink() {
2002        if (!isCursorVisible() || !mTextView.isFocused()) return false;
2003
2004        final int start = mTextView.getSelectionStart();
2005        if (start < 0) return false;
2006
2007        final int end = mTextView.getSelectionEnd();
2008        if (end < 0) return false;
2009
2010        return start == end;
2011    }
2012
2013    void makeBlink() {
2014        if (shouldBlink()) {
2015            mShowCursor = SystemClock.uptimeMillis();
2016            if (mBlink == null) mBlink = new Blink();
2017            mBlink.removeCallbacks(mBlink);
2018            mBlink.postAtTime(mBlink, mShowCursor + BLINK);
2019        } else {
2020            if (mBlink != null) mBlink.removeCallbacks(mBlink);
2021        }
2022    }
2023
2024    private class Blink extends Handler implements Runnable {
2025        private boolean mCancelled;
2026
2027        public void run() {
2028            if (mCancelled) {
2029                return;
2030            }
2031
2032            removeCallbacks(Blink.this);
2033
2034            if (shouldBlink()) {
2035                if (mTextView.getLayout() != null) {
2036                    mTextView.invalidateCursorPath();
2037                }
2038
2039                postAtTime(this, SystemClock.uptimeMillis() + BLINK);
2040            }
2041        }
2042
2043        void cancel() {
2044            if (!mCancelled) {
2045                removeCallbacks(Blink.this);
2046                mCancelled = true;
2047            }
2048        }
2049
2050        void uncancel() {
2051            mCancelled = false;
2052        }
2053    }
2054
2055    private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) {
2056        TextView shadowView = (TextView) View.inflate(mTextView.getContext(),
2057                com.android.internal.R.layout.text_drag_thumbnail, null);
2058
2059        if (shadowView == null) {
2060            throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
2061        }
2062
2063        if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) {
2064            text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH);
2065        }
2066        shadowView.setText(text);
2067        shadowView.setTextColor(mTextView.getTextColors());
2068
2069        shadowView.setTextAppearance(R.styleable.Theme_textAppearanceLarge);
2070        shadowView.setGravity(Gravity.CENTER);
2071
2072        shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2073                ViewGroup.LayoutParams.WRAP_CONTENT));
2074
2075        final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
2076        shadowView.measure(size, size);
2077
2078        shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
2079        shadowView.invalidate();
2080        return new DragShadowBuilder(shadowView);
2081    }
2082
2083    private static class DragLocalState {
2084        public TextView sourceTextView;
2085        public int start, end;
2086
2087        public DragLocalState(TextView sourceTextView, int start, int end) {
2088            this.sourceTextView = sourceTextView;
2089            this.start = start;
2090            this.end = end;
2091        }
2092    }
2093
2094    void onDrop(DragEvent event) {
2095        StringBuilder content = new StringBuilder("");
2096        ClipData clipData = event.getClipData();
2097        final int itemCount = clipData.getItemCount();
2098        for (int i=0; i < itemCount; i++) {
2099            Item item = clipData.getItemAt(i);
2100            content.append(item.coerceToStyledText(mTextView.getContext()));
2101        }
2102
2103        final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
2104
2105        Object localState = event.getLocalState();
2106        DragLocalState dragLocalState = null;
2107        if (localState instanceof DragLocalState) {
2108            dragLocalState = (DragLocalState) localState;
2109        }
2110        boolean dragDropIntoItself = dragLocalState != null &&
2111                dragLocalState.sourceTextView == mTextView;
2112
2113        if (dragDropIntoItself) {
2114            if (offset >= dragLocalState.start && offset < dragLocalState.end) {
2115                // A drop inside the original selection discards the drop.
2116                return;
2117            }
2118        }
2119
2120        final int originalLength = mTextView.getText().length();
2121        int min = offset;
2122        int max = offset;
2123
2124        Selection.setSelection((Spannable) mTextView.getText(), max);
2125        mTextView.replaceText_internal(min, max, content);
2126
2127        if (dragDropIntoItself) {
2128            int dragSourceStart = dragLocalState.start;
2129            int dragSourceEnd = dragLocalState.end;
2130            if (max <= dragSourceStart) {
2131                // Inserting text before selection has shifted positions
2132                final int shift = mTextView.getText().length() - originalLength;
2133                dragSourceStart += shift;
2134                dragSourceEnd += shift;
2135            }
2136
2137            // Delete original selection
2138            mTextView.deleteText_internal(dragSourceStart, dragSourceEnd);
2139
2140            // Make sure we do not leave two adjacent spaces.
2141            final int prevCharIdx = Math.max(0,  dragSourceStart - 1);
2142            final int nextCharIdx = Math.min(mTextView.getText().length(), dragSourceStart + 1);
2143            if (nextCharIdx > prevCharIdx + 1) {
2144                CharSequence t = mTextView.getTransformedText(prevCharIdx, nextCharIdx);
2145                if (Character.isSpaceChar(t.charAt(0)) && Character.isSpaceChar(t.charAt(1))) {
2146                    mTextView.deleteText_internal(prevCharIdx, prevCharIdx + 1);
2147                }
2148            }
2149        }
2150    }
2151
2152    public void addSpanWatchers(Spannable text) {
2153        final int textLength = text.length();
2154
2155        if (mKeyListener != null) {
2156            text.setSpan(mKeyListener, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2157        }
2158
2159        if (mSpanController == null) {
2160            mSpanController = new SpanController();
2161        }
2162        text.setSpan(mSpanController, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2163    }
2164
2165    /**
2166     * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related
2167     * pop-up should be displayed.
2168     * Also monitors {@link Selection} to call back to the attached input method.
2169     */
2170    class SpanController implements SpanWatcher {
2171
2172        private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs
2173
2174        private EasyEditPopupWindow mPopupWindow;
2175
2176        private Runnable mHidePopup;
2177
2178        // This function is pure but inner classes can't have static functions
2179        private boolean isNonIntermediateSelectionSpan(final Spannable text,
2180                final Object span) {
2181            return (Selection.SELECTION_START == span || Selection.SELECTION_END == span)
2182                    && (text.getSpanFlags(span) & Spanned.SPAN_INTERMEDIATE) == 0;
2183        }
2184
2185        @Override
2186        public void onSpanAdded(Spannable text, Object span, int start, int end) {
2187            if (isNonIntermediateSelectionSpan(text, span)) {
2188                sendUpdateSelection();
2189            } else if (span instanceof EasyEditSpan) {
2190                if (mPopupWindow == null) {
2191                    mPopupWindow = new EasyEditPopupWindow();
2192                    mHidePopup = new Runnable() {
2193                        @Override
2194                        public void run() {
2195                            hide();
2196                        }
2197                    };
2198                }
2199
2200                // Make sure there is only at most one EasyEditSpan in the text
2201                if (mPopupWindow.mEasyEditSpan != null) {
2202                    mPopupWindow.mEasyEditSpan.setDeleteEnabled(false);
2203                }
2204
2205                mPopupWindow.setEasyEditSpan((EasyEditSpan) span);
2206                mPopupWindow.setOnDeleteListener(new EasyEditDeleteListener() {
2207                    @Override
2208                    public void onDeleteClick(EasyEditSpan span) {
2209                        Editable editable = (Editable) mTextView.getText();
2210                        int start = editable.getSpanStart(span);
2211                        int end = editable.getSpanEnd(span);
2212                        if (start >= 0 && end >= 0) {
2213                            sendEasySpanNotification(EasyEditSpan.TEXT_DELETED, span);
2214                            mTextView.deleteText_internal(start, end);
2215                        }
2216                        editable.removeSpan(span);
2217                    }
2218                });
2219
2220                if (mTextView.getWindowVisibility() != View.VISIBLE) {
2221                    // The window is not visible yet, ignore the text change.
2222                    return;
2223                }
2224
2225                if (mTextView.getLayout() == null) {
2226                    // The view has not been laid out yet, ignore the text change
2227                    return;
2228                }
2229
2230                if (extractedTextModeWillBeStarted()) {
2231                    // The input is in extract mode. Do not handle the easy edit in
2232                    // the original TextView, as the ExtractEditText will do
2233                    return;
2234                }
2235
2236                mPopupWindow.show();
2237                mTextView.removeCallbacks(mHidePopup);
2238                mTextView.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS);
2239            }
2240        }
2241
2242        @Override
2243        public void onSpanRemoved(Spannable text, Object span, int start, int end) {
2244            if (isNonIntermediateSelectionSpan(text, span)) {
2245                sendUpdateSelection();
2246            } else if (mPopupWindow != null && span == mPopupWindow.mEasyEditSpan) {
2247                hide();
2248            }
2249        }
2250
2251        @Override
2252        public void onSpanChanged(Spannable text, Object span, int previousStart, int previousEnd,
2253                int newStart, int newEnd) {
2254            if (isNonIntermediateSelectionSpan(text, span)) {
2255                sendUpdateSelection();
2256            } else if (mPopupWindow != null && span instanceof EasyEditSpan) {
2257                EasyEditSpan easyEditSpan = (EasyEditSpan) span;
2258                sendEasySpanNotification(EasyEditSpan.TEXT_MODIFIED, easyEditSpan);
2259                text.removeSpan(easyEditSpan);
2260            }
2261        }
2262
2263        public void hide() {
2264            if (mPopupWindow != null) {
2265                mPopupWindow.hide();
2266                mTextView.removeCallbacks(mHidePopup);
2267            }
2268        }
2269
2270        private void sendEasySpanNotification(int textChangedType, EasyEditSpan span) {
2271            try {
2272                PendingIntent pendingIntent = span.getPendingIntent();
2273                if (pendingIntent != null) {
2274                    Intent intent = new Intent();
2275                    intent.putExtra(EasyEditSpan.EXTRA_TEXT_CHANGED_TYPE, textChangedType);
2276                    pendingIntent.send(mTextView.getContext(), 0, intent);
2277                }
2278            } catch (CanceledException e) {
2279                // This should not happen, as we should try to send the intent only once.
2280                Log.w(TAG, "PendingIntent for notification cannot be sent", e);
2281            }
2282        }
2283    }
2284
2285    /**
2286     * Listens for the delete event triggered by {@link EasyEditPopupWindow}.
2287     */
2288    private interface EasyEditDeleteListener {
2289
2290        /**
2291         * Clicks the delete pop-up.
2292         */
2293        void onDeleteClick(EasyEditSpan span);
2294    }
2295
2296    /**
2297     * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled
2298     * by {@link SpanController}.
2299     */
2300    private class EasyEditPopupWindow extends PinnedPopupWindow
2301            implements OnClickListener {
2302        private static final int POPUP_TEXT_LAYOUT =
2303                com.android.internal.R.layout.text_edit_action_popup_text;
2304        private TextView mDeleteTextView;
2305        private EasyEditSpan mEasyEditSpan;
2306        private EasyEditDeleteListener mOnDeleteListener;
2307
2308        @Override
2309        protected void createPopupWindow() {
2310            mPopupWindow = new PopupWindow(mTextView.getContext(), null,
2311                    com.android.internal.R.attr.textSelectHandleWindowStyle);
2312            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
2313            mPopupWindow.setClippingEnabled(true);
2314        }
2315
2316        @Override
2317        protected void initContentView() {
2318            LinearLayout linearLayout = new LinearLayout(mTextView.getContext());
2319            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
2320            mContentView = linearLayout;
2321            mContentView.setBackgroundResource(
2322                    com.android.internal.R.drawable.text_edit_side_paste_window);
2323
2324            LayoutInflater inflater = (LayoutInflater)mTextView.getContext().
2325                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2326
2327            LayoutParams wrapContent = new LayoutParams(
2328                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
2329
2330            mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
2331            mDeleteTextView.setLayoutParams(wrapContent);
2332            mDeleteTextView.setText(com.android.internal.R.string.delete);
2333            mDeleteTextView.setOnClickListener(this);
2334            mContentView.addView(mDeleteTextView);
2335        }
2336
2337        public void setEasyEditSpan(EasyEditSpan easyEditSpan) {
2338            mEasyEditSpan = easyEditSpan;
2339        }
2340
2341        private void setOnDeleteListener(EasyEditDeleteListener listener) {
2342            mOnDeleteListener = listener;
2343        }
2344
2345        @Override
2346        public void onClick(View view) {
2347            if (view == mDeleteTextView
2348                    && mEasyEditSpan != null && mEasyEditSpan.isDeleteEnabled()
2349                    && mOnDeleteListener != null) {
2350                mOnDeleteListener.onDeleteClick(mEasyEditSpan);
2351            }
2352        }
2353
2354        @Override
2355        public void hide() {
2356            if (mEasyEditSpan != null) {
2357                mEasyEditSpan.setDeleteEnabled(false);
2358            }
2359            mOnDeleteListener = null;
2360            super.hide();
2361        }
2362
2363        @Override
2364        protected int getTextOffset() {
2365            // Place the pop-up at the end of the span
2366            Editable editable = (Editable) mTextView.getText();
2367            return editable.getSpanEnd(mEasyEditSpan);
2368        }
2369
2370        @Override
2371        protected int getVerticalLocalPosition(int line) {
2372            return mTextView.getLayout().getLineBottom(line);
2373        }
2374
2375        @Override
2376        protected int clipVertically(int positionY) {
2377            // As we display the pop-up below the span, no vertical clipping is required.
2378            return positionY;
2379        }
2380    }
2381
2382    private class PositionListener implements ViewTreeObserver.OnPreDrawListener {
2383        // 3 handles
2384        // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others)
2385        // 1 CursorAnchorInfoNotifier
2386        private final int MAXIMUM_NUMBER_OF_LISTENERS = 7;
2387        private TextViewPositionListener[] mPositionListeners =
2388                new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS];
2389        private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS];
2390        private boolean mPositionHasChanged = true;
2391        // Absolute position of the TextView with respect to its parent window
2392        private int mPositionX, mPositionY;
2393        private int mNumberOfListeners;
2394        private boolean mScrollHasChanged;
2395        final int[] mTempCoords = new int[2];
2396
2397        public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) {
2398            if (mNumberOfListeners == 0) {
2399                updatePosition();
2400                ViewTreeObserver vto = mTextView.getViewTreeObserver();
2401                vto.addOnPreDrawListener(this);
2402            }
2403
2404            int emptySlotIndex = -1;
2405            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2406                TextViewPositionListener listener = mPositionListeners[i];
2407                if (listener == positionListener) {
2408                    return;
2409                } else if (emptySlotIndex < 0 && listener == null) {
2410                    emptySlotIndex = i;
2411                }
2412            }
2413
2414            mPositionListeners[emptySlotIndex] = positionListener;
2415            mCanMove[emptySlotIndex] = canMove;
2416            mNumberOfListeners++;
2417        }
2418
2419        public void removeSubscriber(TextViewPositionListener positionListener) {
2420            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2421                if (mPositionListeners[i] == positionListener) {
2422                    mPositionListeners[i] = null;
2423                    mNumberOfListeners--;
2424                    break;
2425                }
2426            }
2427
2428            if (mNumberOfListeners == 0) {
2429                ViewTreeObserver vto = mTextView.getViewTreeObserver();
2430                vto.removeOnPreDrawListener(this);
2431            }
2432        }
2433
2434        public int getPositionX() {
2435            return mPositionX;
2436        }
2437
2438        public int getPositionY() {
2439            return mPositionY;
2440        }
2441
2442        @Override
2443        public boolean onPreDraw() {
2444            updatePosition();
2445
2446            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2447                if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) {
2448                    TextViewPositionListener positionListener = mPositionListeners[i];
2449                    if (positionListener != null) {
2450                        positionListener.updatePosition(mPositionX, mPositionY,
2451                                mPositionHasChanged, mScrollHasChanged);
2452                    }
2453                }
2454            }
2455
2456            mScrollHasChanged = false;
2457            return true;
2458        }
2459
2460        private void updatePosition() {
2461            mTextView.getLocationInWindow(mTempCoords);
2462
2463            mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY;
2464
2465            mPositionX = mTempCoords[0];
2466            mPositionY = mTempCoords[1];
2467        }
2468
2469        public void onScrollChanged() {
2470            mScrollHasChanged = true;
2471        }
2472    }
2473
2474    private abstract class PinnedPopupWindow implements TextViewPositionListener {
2475        protected PopupWindow mPopupWindow;
2476        protected ViewGroup mContentView;
2477        int mPositionX, mPositionY;
2478
2479        protected abstract void createPopupWindow();
2480        protected abstract void initContentView();
2481        protected abstract int getTextOffset();
2482        protected abstract int getVerticalLocalPosition(int line);
2483        protected abstract int clipVertically(int positionY);
2484
2485        public PinnedPopupWindow() {
2486            createPopupWindow();
2487
2488            mPopupWindow.setWindowLayoutType(
2489                    WindowManager.LayoutParams.TYPE_APPLICATION_ABOVE_SUB_PANEL);
2490            mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
2491            mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
2492
2493            initContentView();
2494
2495            LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2496                    ViewGroup.LayoutParams.WRAP_CONTENT);
2497            mContentView.setLayoutParams(wrapContent);
2498
2499            mPopupWindow.setContentView(mContentView);
2500        }
2501
2502        public void show() {
2503            getPositionListener().addSubscriber(this, false /* offset is fixed */);
2504
2505            computeLocalPosition();
2506
2507            final PositionListener positionListener = getPositionListener();
2508            updatePosition(positionListener.getPositionX(), positionListener.getPositionY());
2509        }
2510
2511        protected void measureContent() {
2512            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2513            mContentView.measure(
2514                    View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels,
2515                            View.MeasureSpec.AT_MOST),
2516                    View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels,
2517                            View.MeasureSpec.AT_MOST));
2518        }
2519
2520        /* The popup window will be horizontally centered on the getTextOffset() and vertically
2521         * positioned according to viewportToContentHorizontalOffset.
2522         *
2523         * This method assumes that mContentView has properly been measured from its content. */
2524        private void computeLocalPosition() {
2525            measureContent();
2526            final int width = mContentView.getMeasuredWidth();
2527            final int offset = getTextOffset();
2528            mPositionX = (int) (mTextView.getLayout().getPrimaryHorizontal(offset) - width / 2.0f);
2529            mPositionX += mTextView.viewportToContentHorizontalOffset();
2530
2531            final int line = mTextView.getLayout().getLineForOffset(offset);
2532            mPositionY = getVerticalLocalPosition(line);
2533            mPositionY += mTextView.viewportToContentVerticalOffset();
2534        }
2535
2536        private void updatePosition(int parentPositionX, int parentPositionY) {
2537            int positionX = parentPositionX + mPositionX;
2538            int positionY = parentPositionY + mPositionY;
2539
2540            positionY = clipVertically(positionY);
2541
2542            // Horizontal clipping
2543            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2544            final int width = mContentView.getMeasuredWidth();
2545            positionX = Math.min(displayMetrics.widthPixels - width, positionX);
2546            positionX = Math.max(0, positionX);
2547
2548            if (isShowing()) {
2549                mPopupWindow.update(positionX, positionY, -1, -1);
2550            } else {
2551                mPopupWindow.showAtLocation(mTextView, Gravity.NO_GRAVITY,
2552                        positionX, positionY);
2553            }
2554        }
2555
2556        public void hide() {
2557            mPopupWindow.dismiss();
2558            getPositionListener().removeSubscriber(this);
2559        }
2560
2561        @Override
2562        public void updatePosition(int parentPositionX, int parentPositionY,
2563                boolean parentPositionChanged, boolean parentScrolled) {
2564            // Either parentPositionChanged or parentScrolled is true, check if still visible
2565            if (isShowing() && isOffsetVisible(getTextOffset())) {
2566                if (parentScrolled) computeLocalPosition();
2567                updatePosition(parentPositionX, parentPositionY);
2568            } else {
2569                hide();
2570            }
2571        }
2572
2573        public boolean isShowing() {
2574            return mPopupWindow.isShowing();
2575        }
2576    }
2577
2578    private class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener {
2579        private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE;
2580        private static final int ADD_TO_DICTIONARY = -1;
2581        private static final int DELETE_TEXT = -2;
2582        private SuggestionInfo[] mSuggestionInfos;
2583        private int mNumberOfSuggestions;
2584        private boolean mCursorWasVisibleBeforeSuggestions;
2585        private boolean mIsShowingUp = false;
2586        private SuggestionAdapter mSuggestionsAdapter;
2587        private final Comparator<SuggestionSpan> mSuggestionSpanComparator;
2588        private final HashMap<SuggestionSpan, Integer> mSpansLengths;
2589
2590        private class CustomPopupWindow extends PopupWindow {
2591            public CustomPopupWindow(Context context, int defStyleAttr) {
2592                super(context, null, defStyleAttr);
2593            }
2594
2595            @Override
2596            public void dismiss() {
2597                super.dismiss();
2598
2599                getPositionListener().removeSubscriber(SuggestionsPopupWindow.this);
2600
2601                // Safe cast since show() checks that mTextView.getText() is an Editable
2602                ((Spannable) mTextView.getText()).removeSpan(mSuggestionRangeSpan);
2603
2604                mTextView.setCursorVisible(mCursorWasVisibleBeforeSuggestions);
2605                if (hasInsertionController()) {
2606                    getInsertionController().show();
2607                }
2608            }
2609        }
2610
2611        public SuggestionsPopupWindow() {
2612            mCursorWasVisibleBeforeSuggestions = mCursorVisible;
2613            mSuggestionSpanComparator = new SuggestionSpanComparator();
2614            mSpansLengths = new HashMap<SuggestionSpan, Integer>();
2615        }
2616
2617        @Override
2618        protected void createPopupWindow() {
2619            mPopupWindow = new CustomPopupWindow(mTextView.getContext(),
2620                com.android.internal.R.attr.textSuggestionsWindowStyle);
2621            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
2622            mPopupWindow.setFocusable(true);
2623            mPopupWindow.setClippingEnabled(false);
2624        }
2625
2626        @Override
2627        protected void initContentView() {
2628            ListView listView = new ListView(mTextView.getContext());
2629            mSuggestionsAdapter = new SuggestionAdapter();
2630            listView.setAdapter(mSuggestionsAdapter);
2631            listView.setOnItemClickListener(this);
2632            mContentView = listView;
2633
2634            // Inflate the suggestion items once and for all. + 2 for add to dictionary and delete
2635            mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS + 2];
2636            for (int i = 0; i < mSuggestionInfos.length; i++) {
2637                mSuggestionInfos[i] = new SuggestionInfo();
2638            }
2639        }
2640
2641        public boolean isShowingUp() {
2642            return mIsShowingUp;
2643        }
2644
2645        public void onParentLostFocus() {
2646            mIsShowingUp = false;
2647        }
2648
2649        private class SuggestionInfo {
2650            int suggestionStart, suggestionEnd; // range of actual suggestion within text
2651            SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents
2652            int suggestionIndex; // the index of this suggestion inside suggestionSpan
2653            SpannableStringBuilder text = new SpannableStringBuilder();
2654            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mTextView.getContext(),
2655                    android.R.style.TextAppearance_SuggestionHighlight);
2656        }
2657
2658        private class SuggestionAdapter extends BaseAdapter {
2659            private LayoutInflater mInflater = (LayoutInflater) mTextView.getContext().
2660                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2661
2662            @Override
2663            public int getCount() {
2664                return mNumberOfSuggestions;
2665            }
2666
2667            @Override
2668            public Object getItem(int position) {
2669                return mSuggestionInfos[position];
2670            }
2671
2672            @Override
2673            public long getItemId(int position) {
2674                return position;
2675            }
2676
2677            @Override
2678            public View getView(int position, View convertView, ViewGroup parent) {
2679                TextView textView = (TextView) convertView;
2680
2681                if (textView == null) {
2682                    textView = (TextView) mInflater.inflate(mTextView.mTextEditSuggestionItemLayout,
2683                            parent, false);
2684                }
2685
2686                final SuggestionInfo suggestionInfo = mSuggestionInfos[position];
2687                textView.setText(suggestionInfo.text);
2688
2689                if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY ||
2690                suggestionInfo.suggestionIndex == DELETE_TEXT) {
2691                    textView.setBackgroundColor(Color.TRANSPARENT);
2692                } else {
2693                    textView.setBackgroundColor(Color.WHITE);
2694                }
2695
2696                return textView;
2697            }
2698        }
2699
2700        private class SuggestionSpanComparator implements Comparator<SuggestionSpan> {
2701            public int compare(SuggestionSpan span1, SuggestionSpan span2) {
2702                final int flag1 = span1.getFlags();
2703                final int flag2 = span2.getFlags();
2704                if (flag1 != flag2) {
2705                    // The order here should match what is used in updateDrawState
2706                    final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
2707                    final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
2708                    final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0;
2709                    final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0;
2710                    if (easy1 && !misspelled1) return -1;
2711                    if (easy2 && !misspelled2) return 1;
2712                    if (misspelled1) return -1;
2713                    if (misspelled2) return 1;
2714                }
2715
2716                return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue();
2717            }
2718        }
2719
2720        /**
2721         * Returns the suggestion spans that cover the current cursor position. The suggestion
2722         * spans are sorted according to the length of text that they are attached to.
2723         */
2724        private SuggestionSpan[] getSuggestionSpans() {
2725            int pos = mTextView.getSelectionStart();
2726            Spannable spannable = (Spannable) mTextView.getText();
2727            SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class);
2728
2729            mSpansLengths.clear();
2730            for (SuggestionSpan suggestionSpan : suggestionSpans) {
2731                int start = spannable.getSpanStart(suggestionSpan);
2732                int end = spannable.getSpanEnd(suggestionSpan);
2733                mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start));
2734            }
2735
2736            // The suggestions are sorted according to their types (easy correction first, then
2737            // misspelled) and to the length of the text that they cover (shorter first).
2738            Arrays.sort(suggestionSpans, mSuggestionSpanComparator);
2739            return suggestionSpans;
2740        }
2741
2742        @Override
2743        public void show() {
2744            if (!(mTextView.getText() instanceof Editable)) return;
2745
2746            if (updateSuggestions()) {
2747                mCursorWasVisibleBeforeSuggestions = mCursorVisible;
2748                mTextView.setCursorVisible(false);
2749                mIsShowingUp = true;
2750                super.show();
2751            }
2752        }
2753
2754        @Override
2755        protected void measureContent() {
2756            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2757            final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec(
2758                    displayMetrics.widthPixels, View.MeasureSpec.AT_MOST);
2759            final int verticalMeasure = View.MeasureSpec.makeMeasureSpec(
2760                    displayMetrics.heightPixels, View.MeasureSpec.AT_MOST);
2761
2762            int width = 0;
2763            View view = null;
2764            for (int i = 0; i < mNumberOfSuggestions; i++) {
2765                view = mSuggestionsAdapter.getView(i, view, mContentView);
2766                view.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
2767                view.measure(horizontalMeasure, verticalMeasure);
2768                width = Math.max(width, view.getMeasuredWidth());
2769            }
2770
2771            // Enforce the width based on actual text widths
2772            mContentView.measure(
2773                    View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
2774                    verticalMeasure);
2775
2776            Drawable popupBackground = mPopupWindow.getBackground();
2777            if (popupBackground != null) {
2778                if (mTempRect == null) mTempRect = new Rect();
2779                popupBackground.getPadding(mTempRect);
2780                width += mTempRect.left + mTempRect.right;
2781            }
2782            mPopupWindow.setWidth(width);
2783        }
2784
2785        @Override
2786        protected int getTextOffset() {
2787            return mTextView.getSelectionStart();
2788        }
2789
2790        @Override
2791        protected int getVerticalLocalPosition(int line) {
2792            return mTextView.getLayout().getLineBottom(line);
2793        }
2794
2795        @Override
2796        protected int clipVertically(int positionY) {
2797            final int height = mContentView.getMeasuredHeight();
2798            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2799            return Math.min(positionY, displayMetrics.heightPixels - height);
2800        }
2801
2802        @Override
2803        public void hide() {
2804            super.hide();
2805        }
2806
2807        private boolean updateSuggestions() {
2808            Spannable spannable = (Spannable) mTextView.getText();
2809            SuggestionSpan[] suggestionSpans = getSuggestionSpans();
2810
2811            final int nbSpans = suggestionSpans.length;
2812            // Suggestions are shown after a delay: the underlying spans may have been removed
2813            if (nbSpans == 0) return false;
2814
2815            mNumberOfSuggestions = 0;
2816            int spanUnionStart = mTextView.getText().length();
2817            int spanUnionEnd = 0;
2818
2819            SuggestionSpan misspelledSpan = null;
2820            int underlineColor = 0;
2821
2822            for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) {
2823                SuggestionSpan suggestionSpan = suggestionSpans[spanIndex];
2824                final int spanStart = spannable.getSpanStart(suggestionSpan);
2825                final int spanEnd = spannable.getSpanEnd(suggestionSpan);
2826                spanUnionStart = Math.min(spanStart, spanUnionStart);
2827                spanUnionEnd = Math.max(spanEnd, spanUnionEnd);
2828
2829                if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) {
2830                    misspelledSpan = suggestionSpan;
2831                }
2832
2833                // The first span dictates the background color of the highlighted text
2834                if (spanIndex == 0) underlineColor = suggestionSpan.getUnderlineColor();
2835
2836                String[] suggestions = suggestionSpan.getSuggestions();
2837                int nbSuggestions = suggestions.length;
2838                for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) {
2839                    String suggestion = suggestions[suggestionIndex];
2840
2841                    boolean suggestionIsDuplicate = false;
2842                    for (int i = 0; i < mNumberOfSuggestions; i++) {
2843                        if (mSuggestionInfos[i].text.toString().equals(suggestion)) {
2844                            SuggestionSpan otherSuggestionSpan = mSuggestionInfos[i].suggestionSpan;
2845                            final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan);
2846                            final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan);
2847                            if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) {
2848                                suggestionIsDuplicate = true;
2849                                break;
2850                            }
2851                        }
2852                    }
2853
2854                    if (!suggestionIsDuplicate) {
2855                        SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2856                        suggestionInfo.suggestionSpan = suggestionSpan;
2857                        suggestionInfo.suggestionIndex = suggestionIndex;
2858                        suggestionInfo.text.replace(0, suggestionInfo.text.length(), suggestion);
2859
2860                        mNumberOfSuggestions++;
2861
2862                        if (mNumberOfSuggestions == MAX_NUMBER_SUGGESTIONS) {
2863                            // Also end outer for loop
2864                            spanIndex = nbSpans;
2865                            break;
2866                        }
2867                    }
2868                }
2869            }
2870
2871            for (int i = 0; i < mNumberOfSuggestions; i++) {
2872                highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd);
2873            }
2874
2875            // Add "Add to dictionary" item if there is a span with the misspelled flag
2876            if (misspelledSpan != null) {
2877                final int misspelledStart = spannable.getSpanStart(misspelledSpan);
2878                final int misspelledEnd = spannable.getSpanEnd(misspelledSpan);
2879                if (misspelledStart >= 0 && misspelledEnd > misspelledStart) {
2880                    SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2881                    suggestionInfo.suggestionSpan = misspelledSpan;
2882                    suggestionInfo.suggestionIndex = ADD_TO_DICTIONARY;
2883                    suggestionInfo.text.replace(0, suggestionInfo.text.length(), mTextView.
2884                            getContext().getString(com.android.internal.R.string.addToDictionary));
2885                    suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
2886                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2887
2888                    mNumberOfSuggestions++;
2889                }
2890            }
2891
2892            // Delete item
2893            SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2894            suggestionInfo.suggestionSpan = null;
2895            suggestionInfo.suggestionIndex = DELETE_TEXT;
2896            suggestionInfo.text.replace(0, suggestionInfo.text.length(),
2897                    mTextView.getContext().getString(com.android.internal.R.string.deleteText));
2898            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
2899                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2900            mNumberOfSuggestions++;
2901
2902            if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan();
2903            if (underlineColor == 0) {
2904                // Fallback on the default highlight color when the first span does not provide one
2905                mSuggestionRangeSpan.setBackgroundColor(mTextView.mHighlightColor);
2906            } else {
2907                final float BACKGROUND_TRANSPARENCY = 0.4f;
2908                final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY);
2909                mSuggestionRangeSpan.setBackgroundColor(
2910                        (underlineColor & 0x00FFFFFF) + (newAlpha << 24));
2911            }
2912            spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd,
2913                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2914
2915            mSuggestionsAdapter.notifyDataSetChanged();
2916            return true;
2917        }
2918
2919        private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart,
2920                int unionEnd) {
2921            final Spannable text = (Spannable) mTextView.getText();
2922            final int spanStart = text.getSpanStart(suggestionInfo.suggestionSpan);
2923            final int spanEnd = text.getSpanEnd(suggestionInfo.suggestionSpan);
2924
2925            // Adjust the start/end of the suggestion span
2926            suggestionInfo.suggestionStart = spanStart - unionStart;
2927            suggestionInfo.suggestionEnd = suggestionInfo.suggestionStart
2928                    + suggestionInfo.text.length();
2929
2930            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0,
2931                    suggestionInfo.text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2932
2933            // Add the text before and after the span.
2934            final String textAsString = text.toString();
2935            suggestionInfo.text.insert(0, textAsString.substring(unionStart, spanStart));
2936            suggestionInfo.text.append(textAsString.substring(spanEnd, unionEnd));
2937        }
2938
2939        @Override
2940        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2941            Editable editable = (Editable) mTextView.getText();
2942            SuggestionInfo suggestionInfo = mSuggestionInfos[position];
2943
2944            if (suggestionInfo.suggestionIndex == DELETE_TEXT) {
2945                final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan);
2946                int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan);
2947                if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) {
2948                    // Do not leave two adjacent spaces after deletion, or one at beginning of text
2949                    if (spanUnionEnd < editable.length() &&
2950                            Character.isSpaceChar(editable.charAt(spanUnionEnd)) &&
2951                            (spanUnionStart == 0 ||
2952                            Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) {
2953                        spanUnionEnd = spanUnionEnd + 1;
2954                    }
2955                    mTextView.deleteText_internal(spanUnionStart, spanUnionEnd);
2956                }
2957                hide();
2958                return;
2959            }
2960
2961            final int spanStart = editable.getSpanStart(suggestionInfo.suggestionSpan);
2962            final int spanEnd = editable.getSpanEnd(suggestionInfo.suggestionSpan);
2963            if (spanStart < 0 || spanEnd <= spanStart) {
2964                // Span has been removed
2965                hide();
2966                return;
2967            }
2968
2969            final String originalText = editable.toString().substring(spanStart, spanEnd);
2970
2971            if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) {
2972                Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT);
2973                intent.putExtra("word", originalText);
2974                intent.putExtra("locale", mTextView.getTextServicesLocale().toString());
2975                // Put a listener to replace the original text with a word which the user
2976                // modified in a user dictionary dialog.
2977                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
2978                mTextView.getContext().startActivity(intent);
2979                // There is no way to know if the word was indeed added. Re-check.
2980                // TODO The ExtractEditText should remove the span in the original text instead
2981                editable.removeSpan(suggestionInfo.suggestionSpan);
2982                Selection.setSelection(editable, spanEnd);
2983                updateSpellCheckSpans(spanStart, spanEnd, false);
2984            } else {
2985                // SuggestionSpans are removed by replace: save them before
2986                SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd,
2987                        SuggestionSpan.class);
2988                final int length = suggestionSpans.length;
2989                int[] suggestionSpansStarts = new int[length];
2990                int[] suggestionSpansEnds = new int[length];
2991                int[] suggestionSpansFlags = new int[length];
2992                for (int i = 0; i < length; i++) {
2993                    final SuggestionSpan suggestionSpan = suggestionSpans[i];
2994                    suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan);
2995                    suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan);
2996                    suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan);
2997
2998                    // Remove potential misspelled flags
2999                    int suggestionSpanFlags = suggestionSpan.getFlags();
3000                    if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) > 0) {
3001                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED;
3002                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
3003                        suggestionSpan.setFlags(suggestionSpanFlags);
3004                    }
3005                }
3006
3007                final int suggestionStart = suggestionInfo.suggestionStart;
3008                final int suggestionEnd = suggestionInfo.suggestionEnd;
3009                final String suggestion = suggestionInfo.text.subSequence(
3010                        suggestionStart, suggestionEnd).toString();
3011                mTextView.replaceText_internal(spanStart, spanEnd, suggestion);
3012
3013                // Notify source IME of the suggestion pick. Do this before
3014                // swaping texts.
3015                suggestionInfo.suggestionSpan.notifySelection(
3016                        mTextView.getContext(), originalText, suggestionInfo.suggestionIndex);
3017
3018                // Swap text content between actual text and Suggestion span
3019                String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions();
3020                suggestions[suggestionInfo.suggestionIndex] = originalText;
3021
3022                // Restore previous SuggestionSpans
3023                final int lengthDifference = suggestion.length() - (spanEnd - spanStart);
3024                for (int i = 0; i < length; i++) {
3025                    // Only spans that include the modified region make sense after replacement
3026                    // Spans partially included in the replaced region are removed, there is no
3027                    // way to assign them a valid range after replacement
3028                    if (suggestionSpansStarts[i] <= spanStart &&
3029                            suggestionSpansEnds[i] >= spanEnd) {
3030                        mTextView.setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i],
3031                                suggestionSpansEnds[i] + lengthDifference, suggestionSpansFlags[i]);
3032                    }
3033                }
3034
3035                // Move cursor at the end of the replaced word
3036                final int newCursorPosition = spanEnd + lengthDifference;
3037                mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition);
3038            }
3039
3040            hide();
3041        }
3042    }
3043
3044    /**
3045     * An ActionMode Callback class that is used to provide actions while in text selection mode.
3046     *
3047     * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending
3048     * on which of these this TextView supports.
3049     */
3050    private class SelectionActionModeCallback extends ActionMode.Callback2 {
3051        private final Path mSelectionPath = new Path();
3052        private final RectF mSelectionBounds = new RectF();
3053
3054        private int mSelectionHandleHeight;
3055        private int mInsertionHandleHeight;
3056
3057        public SelectionActionModeCallback() {
3058            SelectionModifierCursorController selectionController = getSelectionController();
3059            if (selectionController.mStartHandle == null) {
3060                // As these are for initializing selectionController, hide() must be called.
3061                selectionController.initDrawables();
3062                selectionController.initHandles();
3063                selectionController.hide();
3064            }
3065            mSelectionHandleHeight = Math.max(
3066                    mSelectHandleLeft.getMinimumHeight(), mSelectHandleRight.getMinimumHeight());
3067            InsertionPointCursorController insertionController = getInsertionController();
3068            if (insertionController != null) {
3069                insertionController.getHandle();
3070                mInsertionHandleHeight = mSelectHandleCenter.getMinimumHeight();
3071            }
3072        }
3073
3074        @Override
3075        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
3076            mode.setTitle(mTextView.getContext().getString(
3077                    com.android.internal.R.string.textSelectionCABTitle));
3078            mode.setSubtitle(null);
3079            mode.setTitleOptionalHint(true);
3080            populateMenuWithItems(menu);
3081
3082            if (mCustomSelectionActionModeCallback != null) {
3083                if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) {
3084                    // The custom mode can choose to cancel the action mode
3085                    return false;
3086                }
3087            }
3088
3089            addIntentMenuItemsForTextProcessing(menu);
3090
3091            if (menu.hasVisibleItems() || mode.getCustomView() != null) {
3092                mTextView.setHasTransientState(true);
3093                return true;
3094            } else {
3095                return false;
3096            }
3097        }
3098
3099        private void populateMenuWithItems(Menu menu) {
3100            if (mTextView.canCut()) {
3101                menu.add(0, TextView.ID_CUT, 0, com.android.internal.R.string.cut).
3102                    setAlphabeticShortcut('x').
3103                    setShowAsAction(
3104                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
3105            }
3106
3107            if (mTextView.canCopy()) {
3108                menu.add(0, TextView.ID_COPY, 0, com.android.internal.R.string.copy).
3109                    setAlphabeticShortcut('c').
3110                    setShowAsAction(
3111                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
3112            }
3113
3114            if (mTextView.canPaste()) {
3115                menu.add(0, TextView.ID_PASTE, 0, com.android.internal.R.string.paste).
3116                        setAlphabeticShortcut('v').
3117                        setShowAsAction(
3118                                MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
3119            }
3120
3121            if (mTextView.canShare()) {
3122                menu.add(0, TextView.ID_SHARE, 0, com.android.internal.R.string.share).
3123                        setShowAsAction(
3124                                MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
3125            }
3126
3127            if (mTextView.canSelectAllText()) {
3128                menu.add(0, TextView.ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll).
3129                        setAlphabeticShortcut('a').
3130                        setShowAsAction(
3131                                MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
3132            }
3133
3134            updateReplaceItem(menu);
3135        }
3136
3137        private void addIntentMenuItemsForTextProcessing(Menu menu) {
3138            if (mTextView.canProcessText()) {
3139                PackageManager packageManager = mTextView.getContext().getPackageManager();
3140                List<ResolveInfo> supportedActivities =
3141                        packageManager.queryIntentActivities(createProcessTextIntent(), 0);
3142                for (ResolveInfo info : supportedActivities) {
3143                    menu.add(info.loadLabel(packageManager))
3144                        .setIntent(createProcessTextIntentForResolveInfo(info))
3145                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
3146                                | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
3147                }
3148            }
3149        }
3150
3151        private Intent createProcessTextIntent() {
3152            return new Intent()
3153                .setAction(Intent.ACTION_PROCESS_TEXT)
3154                .setType("text/plain");
3155        }
3156
3157        private Intent createProcessTextIntentForResolveInfo(ResolveInfo info) {
3158            return createProcessTextIntent()
3159                    .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, !mTextView.isTextEditable())
3160                    .setClassName(info.activityInfo.packageName, info.activityInfo.name);
3161        }
3162
3163        @Override
3164        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
3165            updateReplaceItem(menu);
3166
3167            if (mCustomSelectionActionModeCallback != null) {
3168                return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu);
3169            }
3170            return true;
3171        }
3172
3173        private void updateReplaceItem(Menu menu) {
3174            boolean canReplace = mTextView.isSuggestionsEnabled() && shouldOfferToShowSuggestions();
3175            boolean replaceItemExists = menu.findItem(TextView.ID_REPLACE) != null;
3176            if (canReplace && !replaceItemExists) {
3177                menu.add(0, TextView.ID_REPLACE, 0, com.android.internal.R.string.replace).
3178                setShowAsAction(
3179                        MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
3180            } else if (!canReplace && replaceItemExists) {
3181                menu.removeItem(TextView.ID_REPLACE);
3182            }
3183        }
3184
3185        @Override
3186        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
3187            if (item.getIntent() != null
3188                    && item.getIntent().getAction().equals(Intent.ACTION_PROCESS_TEXT)) {
3189                item.getIntent().putExtra(Intent.EXTRA_PROCESS_TEXT, mTextView.getSelectedText());
3190                mPreserveDetachedSelection = true;
3191                mTextView.startActivityForResult(
3192                        item.getIntent(), TextView.PROCESS_TEXT_REQUEST_CODE);
3193                return true;
3194            }
3195            if (mCustomSelectionActionModeCallback != null &&
3196                 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) {
3197                return true;
3198            }
3199            if (item.getItemId() == TextView.ID_REPLACE) {
3200                onReplace();
3201                return true;
3202            }
3203            return mTextView.onTextContextMenuItem(item.getItemId());
3204        }
3205
3206        @Override
3207        public void onDestroyActionMode(ActionMode mode) {
3208            if (mCustomSelectionActionModeCallback != null) {
3209                mCustomSelectionActionModeCallback.onDestroyActionMode(mode);
3210            }
3211
3212            /*
3213             * If we're ending this mode because we're detaching from a window,
3214             * we still have selection state to preserve. Don't clear it, we'll
3215             * bring back the selection mode when (if) we get reattached.
3216             */
3217            if (!mPreserveDetachedSelection) {
3218                Selection.setSelection((Spannable) mTextView.getText(),
3219                        mTextView.getSelectionEnd());
3220                mTextView.setHasTransientState(false);
3221            }
3222
3223            if (mSelectionModifierCursorController != null) {
3224                mSelectionModifierCursorController.hide();
3225            }
3226
3227            mSelectionActionMode = null;
3228        }
3229
3230        @Override
3231        public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
3232            if (!view.equals(mTextView) || mTextView.getLayout() == null) {
3233                super.onGetContentRect(mode, view, outRect);
3234                return;
3235            }
3236            if (mTextView.getSelectionStart() != mTextView.getSelectionEnd()) {
3237                // We have a selection.
3238                mSelectionPath.reset();
3239                mTextView.getLayout().getSelectionPath(
3240                        mTextView.getSelectionStart(), mTextView.getSelectionEnd(), mSelectionPath);
3241                mSelectionPath.computeBounds(mSelectionBounds, true);
3242                mSelectionBounds.bottom += mSelectionHandleHeight;
3243            } else if (mCursorCount == 2) {
3244                // We have a split cursor. In this case, we take the rectangle that includes both
3245                // parts of the cursor to ensure we don't obscure either of them.
3246                Rect firstCursorBounds = mCursorDrawable[0].getBounds();
3247                Rect secondCursorBounds = mCursorDrawable[1].getBounds();
3248                mSelectionBounds.set(
3249                        Math.min(firstCursorBounds.left, secondCursorBounds.left),
3250                        Math.min(firstCursorBounds.top, secondCursorBounds.top),
3251                        Math.max(firstCursorBounds.right, secondCursorBounds.right),
3252                        Math.max(firstCursorBounds.bottom, secondCursorBounds.bottom)
3253                            + mInsertionHandleHeight);
3254            } else {
3255                // We have a single cursor.
3256                int line = mTextView.getLayout().getLineForOffset(mTextView.getSelectionStart());
3257                float primaryHorizontal =
3258                        mTextView.getLayout().getPrimaryHorizontal(mTextView.getSelectionStart());
3259                mSelectionBounds.set(
3260                        primaryHorizontal,
3261                        mTextView.getLayout().getLineTop(line),
3262                        primaryHorizontal + 1,
3263                        mTextView.getLayout().getLineTop(line + 1) + mInsertionHandleHeight);
3264            }
3265            // Take TextView's padding and scroll into account.
3266            int textHorizontalOffset = mTextView.viewportToContentHorizontalOffset();
3267            int textVerticalOffset = mTextView.viewportToContentVerticalOffset();
3268            outRect.set(
3269                    (int) Math.floor(mSelectionBounds.left + textHorizontalOffset),
3270                    (int) Math.floor(mSelectionBounds.top + textVerticalOffset),
3271                    (int) Math.ceil(mSelectionBounds.right + textHorizontalOffset),
3272                    (int) Math.ceil(mSelectionBounds.bottom + textVerticalOffset));
3273        }
3274    }
3275
3276    private void onReplace() {
3277        int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2;
3278        stopSelectionActionMode();
3279        Selection.setSelection((Spannable) mTextView.getText(), middle);
3280        showSuggestions();
3281    }
3282
3283    /**
3284     * A listener to call {@link InputMethodManager#updateCursorAnchorInfo(View, CursorAnchorInfo)}
3285     * while the input method is requesting the cursor/anchor position. Does nothing as long as
3286     * {@link InputMethodManager#isWatchingCursor(View)} returns false.
3287     */
3288    private final class CursorAnchorInfoNotifier implements TextViewPositionListener {
3289        final CursorAnchorInfo.Builder mSelectionInfoBuilder = new CursorAnchorInfo.Builder();
3290        final int[] mTmpIntOffset = new int[2];
3291        final Matrix mViewToScreenMatrix = new Matrix();
3292
3293        @Override
3294        public void updatePosition(int parentPositionX, int parentPositionY,
3295                boolean parentPositionChanged, boolean parentScrolled) {
3296            final InputMethodState ims = mInputMethodState;
3297            if (ims == null || ims.mBatchEditNesting > 0) {
3298                return;
3299            }
3300            final InputMethodManager imm = InputMethodManager.peekInstance();
3301            if (null == imm) {
3302                return;
3303            }
3304            if (!imm.isActive(mTextView)) {
3305                return;
3306            }
3307            // Skip if the IME has not requested the cursor/anchor position.
3308            if (!imm.isCursorAnchorInfoEnabled()) {
3309                return;
3310            }
3311            Layout layout = mTextView.getLayout();
3312            if (layout == null) {
3313                return;
3314            }
3315
3316            final CursorAnchorInfo.Builder builder = mSelectionInfoBuilder;
3317            builder.reset();
3318
3319            final int selectionStart = mTextView.getSelectionStart();
3320            builder.setSelectionRange(selectionStart, mTextView.getSelectionEnd());
3321
3322            // Construct transformation matrix from view local coordinates to screen coordinates.
3323            mViewToScreenMatrix.set(mTextView.getMatrix());
3324            mTextView.getLocationOnScreen(mTmpIntOffset);
3325            mViewToScreenMatrix.postTranslate(mTmpIntOffset[0], mTmpIntOffset[1]);
3326            builder.setMatrix(mViewToScreenMatrix);
3327
3328            final float viewportToContentHorizontalOffset =
3329                    mTextView.viewportToContentHorizontalOffset();
3330            final float viewportToContentVerticalOffset =
3331                    mTextView.viewportToContentVerticalOffset();
3332
3333            final CharSequence text = mTextView.getText();
3334            if (text instanceof Spannable) {
3335                final Spannable sp = (Spannable) text;
3336                int composingTextStart = EditableInputConnection.getComposingSpanStart(sp);
3337                int composingTextEnd = EditableInputConnection.getComposingSpanEnd(sp);
3338                if (composingTextEnd < composingTextStart) {
3339                    final int temp = composingTextEnd;
3340                    composingTextEnd = composingTextStart;
3341                    composingTextStart = temp;
3342                }
3343                final boolean hasComposingText =
3344                        (0 <= composingTextStart) && (composingTextStart < composingTextEnd);
3345                if (hasComposingText) {
3346                    final CharSequence composingText = text.subSequence(composingTextStart,
3347                            composingTextEnd);
3348                    builder.setComposingText(composingTextStart, composingText);
3349
3350                    final int minLine = layout.getLineForOffset(composingTextStart);
3351                    final int maxLine = layout.getLineForOffset(composingTextEnd - 1);
3352                    for (int line = minLine; line <= maxLine; ++line) {
3353                        final int lineStart = layout.getLineStart(line);
3354                        final int lineEnd = layout.getLineEnd(line);
3355                        final int offsetStart = Math.max(lineStart, composingTextStart);
3356                        final int offsetEnd = Math.min(lineEnd, composingTextEnd);
3357                        final boolean ltrLine =
3358                                layout.getParagraphDirection(line) == Layout.DIR_LEFT_TO_RIGHT;
3359                        final float[] widths = new float[offsetEnd - offsetStart];
3360                        layout.getPaint().getTextWidths(text, offsetStart, offsetEnd, widths);
3361                        final float top = layout.getLineTop(line);
3362                        final float bottom = layout.getLineBottom(line);
3363                        for (int offset = offsetStart; offset < offsetEnd; ++offset) {
3364                            final float charWidth = widths[offset - offsetStart];
3365                            final boolean isRtl = layout.isRtlCharAt(offset);
3366                            final float primary = layout.getPrimaryHorizontal(offset);
3367                            final float secondary = layout.getSecondaryHorizontal(offset);
3368                            // TODO: This doesn't work perfectly for text with custom styles and
3369                            // TAB chars.
3370                            final float left;
3371                            final float right;
3372                            if (ltrLine) {
3373                                if (isRtl) {
3374                                    left = secondary - charWidth;
3375                                    right = secondary;
3376                                } else {
3377                                    left = primary;
3378                                    right = primary + charWidth;
3379                                }
3380                            } else {
3381                                if (!isRtl) {
3382                                    left = secondary;
3383                                    right = secondary + charWidth;
3384                                } else {
3385                                    left = primary - charWidth;
3386                                    right = primary;
3387                                }
3388                            }
3389                            // TODO: Check top-right and bottom-left as well.
3390                            final float localLeft = left + viewportToContentHorizontalOffset;
3391                            final float localRight = right + viewportToContentHorizontalOffset;
3392                            final float localTop = top + viewportToContentVerticalOffset;
3393                            final float localBottom = bottom + viewportToContentVerticalOffset;
3394                            final boolean isTopLeftVisible = isPositionVisible(localLeft, localTop);
3395                            final boolean isBottomRightVisible =
3396                                    isPositionVisible(localRight, localBottom);
3397                            int characterBoundsFlags = 0;
3398                            if (isTopLeftVisible || isBottomRightVisible) {
3399                                characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
3400                            }
3401                            if (!isTopLeftVisible || !isBottomRightVisible) {
3402                                characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
3403                            }
3404                            if (isRtl) {
3405                                characterBoundsFlags |= CursorAnchorInfo.FLAG_IS_RTL;
3406                            }
3407                            // Here offset is the index in Java chars.
3408                            builder.addCharacterBounds(offset, localLeft, localTop, localRight,
3409                                    localBottom, characterBoundsFlags);
3410                        }
3411                    }
3412                }
3413            }
3414
3415            // Treat selectionStart as the insertion point.
3416            if (0 <= selectionStart) {
3417                final int offset = selectionStart;
3418                final int line = layout.getLineForOffset(offset);
3419                final float insertionMarkerX = layout.getPrimaryHorizontal(offset)
3420                        + viewportToContentHorizontalOffset;
3421                final float insertionMarkerTop = layout.getLineTop(line)
3422                        + viewportToContentVerticalOffset;
3423                final float insertionMarkerBaseline = layout.getLineBaseline(line)
3424                        + viewportToContentVerticalOffset;
3425                final float insertionMarkerBottom = layout.getLineBottom(line)
3426                        + viewportToContentVerticalOffset;
3427                final boolean isTopVisible =
3428                        isPositionVisible(insertionMarkerX, insertionMarkerTop);
3429                final boolean isBottomVisible =
3430                        isPositionVisible(insertionMarkerX, insertionMarkerBottom);
3431                int insertionMarkerFlags = 0;
3432                if (isTopVisible || isBottomVisible) {
3433                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
3434                }
3435                if (!isTopVisible || !isBottomVisible) {
3436                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
3437                }
3438                if (layout.isRtlCharAt(offset)) {
3439                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_IS_RTL;
3440                }
3441                builder.setInsertionMarkerLocation(insertionMarkerX, insertionMarkerTop,
3442                        insertionMarkerBaseline, insertionMarkerBottom, insertionMarkerFlags);
3443            }
3444
3445            imm.updateCursorAnchorInfo(mTextView, builder.build());
3446        }
3447    }
3448
3449    private abstract class HandleView extends View implements TextViewPositionListener {
3450        protected Drawable mDrawable;
3451        protected Drawable mDrawableLtr;
3452        protected Drawable mDrawableRtl;
3453        private final PopupWindow mContainer;
3454        // Position with respect to the parent TextView
3455        private int mPositionX, mPositionY;
3456        private boolean mIsDragging;
3457        // Offset from touch position to mPosition
3458        private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
3459        protected int mHotspotX;
3460        protected int mHorizontalGravity;
3461        // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
3462        private float mTouchOffsetY;
3463        // Where the touch position should be on the handle to ensure a maximum cursor visibility
3464        private float mIdealVerticalOffset;
3465        // Parent's (TextView) previous position in window
3466        private int mLastParentX, mLastParentY;
3467        // Previous text character offset
3468        protected int mPreviousOffset = -1;
3469        // Previous text character offset
3470        private boolean mPositionHasChanged = true;
3471        // Minimum touch target size for handles
3472        private int mMinSize;
3473        // Indicates the line of text that the handle is on.
3474        protected int mPrevLine = -1;
3475
3476        public HandleView(Drawable drawableLtr, Drawable drawableRtl) {
3477            super(mTextView.getContext());
3478            mContainer = new PopupWindow(mTextView.getContext(), null,
3479                    com.android.internal.R.attr.textSelectHandleWindowStyle);
3480            mContainer.setSplitTouchEnabled(true);
3481            mContainer.setClippingEnabled(false);
3482            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
3483            mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
3484            mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
3485            mContainer.setContentView(this);
3486
3487            mDrawableLtr = drawableLtr;
3488            mDrawableRtl = drawableRtl;
3489            mMinSize = mTextView.getContext().getResources().getDimensionPixelSize(
3490                    com.android.internal.R.dimen.text_handle_min_size);
3491
3492            updateDrawable();
3493
3494            final int handleHeight = getPreferredHeight();
3495            mTouchOffsetY = -0.3f * handleHeight;
3496            mIdealVerticalOffset = 0.7f * handleHeight;
3497        }
3498
3499        protected void updateDrawable() {
3500            final int offset = getCurrentCursorOffset();
3501            final boolean isRtlCharAtOffset = mTextView.getLayout().isRtlCharAt(offset);
3502            mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
3503            mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
3504            mHorizontalGravity = getHorizontalGravity(isRtlCharAtOffset);
3505        }
3506
3507        protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
3508        protected abstract int getHorizontalGravity(boolean isRtlRun);
3509
3510        // Touch-up filter: number of previous positions remembered
3511        private static final int HISTORY_SIZE = 5;
3512        private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
3513        private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
3514        private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
3515        private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
3516        private int mPreviousOffsetIndex = 0;
3517        private int mNumberPreviousOffsets = 0;
3518
3519        private void startTouchUpFilter(int offset) {
3520            mNumberPreviousOffsets = 0;
3521            addPositionToTouchUpFilter(offset);
3522        }
3523
3524        private void addPositionToTouchUpFilter(int offset) {
3525            mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
3526            mPreviousOffsets[mPreviousOffsetIndex] = offset;
3527            mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
3528            mNumberPreviousOffsets++;
3529        }
3530
3531        private void filterOnTouchUp() {
3532            final long now = SystemClock.uptimeMillis();
3533            int i = 0;
3534            int index = mPreviousOffsetIndex;
3535            final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
3536            while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
3537                i++;
3538                index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
3539            }
3540
3541            if (i > 0 && i < iMax &&
3542                    (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
3543                positionAtCursorOffset(mPreviousOffsets[index], false);
3544            }
3545        }
3546
3547        public boolean offsetHasBeenChanged() {
3548            return mNumberPreviousOffsets > 1;
3549        }
3550
3551        @Override
3552        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
3553            setMeasuredDimension(getPreferredWidth(), getPreferredHeight());
3554        }
3555
3556        private int getPreferredWidth() {
3557            return Math.max(mDrawable.getIntrinsicWidth(), mMinSize);
3558        }
3559
3560        private int getPreferredHeight() {
3561            return Math.max(mDrawable.getIntrinsicHeight(), mMinSize);
3562        }
3563
3564        public void show() {
3565            if (isShowing()) return;
3566
3567            getPositionListener().addSubscriber(this, true /* local position may change */);
3568
3569            // Make sure the offset is always considered new, even when focusing at same position
3570            mPreviousOffset = -1;
3571            positionAtCursorOffset(getCurrentCursorOffset(), false);
3572        }
3573
3574        protected void dismiss() {
3575            mIsDragging = false;
3576            mContainer.dismiss();
3577            onDetached();
3578        }
3579
3580        public void hide() {
3581            dismiss();
3582
3583            getPositionListener().removeSubscriber(this);
3584        }
3585
3586        public boolean isShowing() {
3587            return mContainer.isShowing();
3588        }
3589
3590        private boolean isVisible() {
3591            // Always show a dragging handle.
3592            if (mIsDragging) {
3593                return true;
3594            }
3595
3596            if (mTextView.isInBatchEditMode()) {
3597                return false;
3598            }
3599
3600            return isPositionVisible(mPositionX + mHotspotX + getHorizontalOffset(), mPositionY);
3601        }
3602
3603        public abstract int getCurrentCursorOffset();
3604
3605        protected abstract void updateSelection(int offset);
3606
3607        public abstract void updatePosition(float x, float y);
3608
3609        protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
3610            // A HandleView relies on the layout, which may be nulled by external methods
3611            Layout layout = mTextView.getLayout();
3612            if (layout == null) {
3613                // Will update controllers' state, hiding them and stopping selection mode if needed
3614                prepareCursorControllers();
3615                return;
3616            }
3617
3618            boolean offsetChanged = offset != mPreviousOffset;
3619            if (offsetChanged || parentScrolled) {
3620                if (offsetChanged) {
3621                    updateSelection(offset);
3622                    addPositionToTouchUpFilter(offset);
3623                }
3624                final int line = layout.getLineForOffset(offset);
3625                mPrevLine = line;
3626
3627                mPositionX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX -
3628                        getHorizontalOffset() + getCursorOffset());
3629                mPositionY = layout.getLineBottom(line);
3630
3631                // Take TextView's padding and scroll into account.
3632                mPositionX += mTextView.viewportToContentHorizontalOffset();
3633                mPositionY += mTextView.viewportToContentVerticalOffset();
3634
3635                mPreviousOffset = offset;
3636                mPositionHasChanged = true;
3637            }
3638        }
3639
3640        public void updatePosition(int parentPositionX, int parentPositionY,
3641                boolean parentPositionChanged, boolean parentScrolled) {
3642            positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled);
3643            if (parentPositionChanged || mPositionHasChanged) {
3644                if (mIsDragging) {
3645                    // Update touchToWindow offset in case of parent scrolling while dragging
3646                    if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
3647                        mTouchToWindowOffsetX += parentPositionX - mLastParentX;
3648                        mTouchToWindowOffsetY += parentPositionY - mLastParentY;
3649                        mLastParentX = parentPositionX;
3650                        mLastParentY = parentPositionY;
3651                    }
3652
3653                    onHandleMoved();
3654                }
3655
3656                if (isVisible()) {
3657                    final int positionX = parentPositionX + mPositionX;
3658                    final int positionY = parentPositionY + mPositionY;
3659                    if (isShowing()) {
3660                        mContainer.update(positionX, positionY, -1, -1);
3661                    } else {
3662                        mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY,
3663                                positionX, positionY);
3664                    }
3665                } else {
3666                    if (isShowing()) {
3667                        dismiss();
3668                    }
3669                }
3670
3671                mPositionHasChanged = false;
3672            }
3673        }
3674
3675        public void showAtLocation(int offset) {
3676            // TODO - investigate if there's a better way to show the handles
3677            // after the drag accelerator has occured.
3678            int[] tmpCords = new int[2];
3679            mTextView.getLocationInWindow(tmpCords);
3680
3681            Layout layout = mTextView.getLayout();
3682            int posX = tmpCords[0];
3683            int posY = tmpCords[1];
3684
3685            final int line = layout.getLineForOffset(offset);
3686
3687            int startX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f
3688                    - mHotspotX - getHorizontalOffset() + getCursorOffset());
3689            int startY = layout.getLineBottom(line);
3690
3691            // Take TextView's padding and scroll into account.
3692            startX += mTextView.viewportToContentHorizontalOffset();
3693            startY += mTextView.viewportToContentVerticalOffset();
3694
3695            mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY,
3696                    startX + posX, startY + posY);
3697        }
3698
3699        @Override
3700        protected void onDraw(Canvas c) {
3701            final int drawWidth = mDrawable.getIntrinsicWidth();
3702            final int left = getHorizontalOffset();
3703
3704            mDrawable.setBounds(left, 0, left + drawWidth, mDrawable.getIntrinsicHeight());
3705            mDrawable.draw(c);
3706        }
3707
3708        private int getHorizontalOffset() {
3709            final int width = getPreferredWidth();
3710            final int drawWidth = mDrawable.getIntrinsicWidth();
3711            final int left;
3712            switch (mHorizontalGravity) {
3713                case Gravity.LEFT:
3714                    left = 0;
3715                    break;
3716                default:
3717                case Gravity.CENTER:
3718                    left = (width - drawWidth) / 2;
3719                    break;
3720                case Gravity.RIGHT:
3721                    left = width - drawWidth;
3722                    break;
3723            }
3724            return left;
3725        }
3726
3727        protected int getCursorOffset() {
3728            return 0;
3729        }
3730
3731        @Override
3732        public boolean onTouchEvent(MotionEvent ev) {
3733            switch (ev.getActionMasked()) {
3734                case MotionEvent.ACTION_DOWN: {
3735                    startTouchUpFilter(getCurrentCursorOffset());
3736                    mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
3737                    mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
3738
3739                    final PositionListener positionListener = getPositionListener();
3740                    mLastParentX = positionListener.getPositionX();
3741                    mLastParentY = positionListener.getPositionY();
3742                    mIsDragging = true;
3743                    break;
3744                }
3745
3746                case MotionEvent.ACTION_MOVE: {
3747                    final float rawX = ev.getRawX();
3748                    final float rawY = ev.getRawY();
3749
3750                    // Vertical hysteresis: vertical down movement tends to snap to ideal offset
3751                    final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
3752                    final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
3753                    float newVerticalOffset;
3754                    if (previousVerticalOffset < mIdealVerticalOffset) {
3755                        newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
3756                        newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
3757                    } else {
3758                        newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
3759                        newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
3760                    }
3761                    mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
3762
3763                    final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX;
3764                    final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
3765
3766                    updatePosition(newPosX, newPosY);
3767                    break;
3768                }
3769
3770                case MotionEvent.ACTION_UP:
3771                    filterOnTouchUp();
3772                    mIsDragging = false;
3773                    break;
3774
3775                case MotionEvent.ACTION_CANCEL:
3776                    mIsDragging = false;
3777                    break;
3778            }
3779            return true;
3780        }
3781
3782        public boolean isDragging() {
3783            return mIsDragging;
3784        }
3785
3786        void onHandleMoved() {}
3787
3788        public void onDetached() {}
3789    }
3790
3791    private class InsertionHandleView extends HandleView {
3792        private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
3793        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
3794
3795        // Used to detect taps on the insertion handle, which will affect the selection action mode
3796        private float mDownPositionX, mDownPositionY;
3797        private Runnable mHider;
3798
3799        public InsertionHandleView(Drawable drawable) {
3800            super(drawable, drawable);
3801        }
3802
3803        @Override
3804        public void show() {
3805            super.show();
3806
3807            final long durationSinceCutOrCopy =
3808                    SystemClock.uptimeMillis() - TextView.LAST_CUT_OR_COPY_TIME;
3809            if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) {
3810                startSelectionActionModeWithoutSelection();
3811            }
3812
3813            hideAfterDelay();
3814        }
3815
3816        private void hideAfterDelay() {
3817            if (mHider == null) {
3818                mHider = new Runnable() {
3819                    public void run() {
3820                        hide();
3821                    }
3822                };
3823            } else {
3824                removeHiderCallback();
3825            }
3826            mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
3827        }
3828
3829        private void removeHiderCallback() {
3830            if (mHider != null) {
3831                mTextView.removeCallbacks(mHider);
3832            }
3833        }
3834
3835        @Override
3836        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
3837            return drawable.getIntrinsicWidth() / 2;
3838        }
3839
3840        @Override
3841        protected int getHorizontalGravity(boolean isRtlRun) {
3842            return Gravity.CENTER_HORIZONTAL;
3843        }
3844
3845        @Override
3846        protected int getCursorOffset() {
3847            int offset = super.getCursorOffset();
3848            final Drawable cursor = mCursorCount > 0 ? mCursorDrawable[0] : null;
3849            if (cursor != null) {
3850                cursor.getPadding(mTempRect);
3851                offset += (cursor.getIntrinsicWidth() - mTempRect.left - mTempRect.right) / 2;
3852            }
3853            return offset;
3854        }
3855
3856        @Override
3857        public boolean onTouchEvent(MotionEvent ev) {
3858            final boolean result = super.onTouchEvent(ev);
3859
3860            switch (ev.getActionMasked()) {
3861                case MotionEvent.ACTION_DOWN:
3862                    mDownPositionX = ev.getRawX();
3863                    mDownPositionY = ev.getRawY();
3864                    break;
3865
3866                case MotionEvent.ACTION_UP:
3867                    if (!offsetHasBeenChanged()) {
3868                        final float deltaX = mDownPositionX - ev.getRawX();
3869                        final float deltaY = mDownPositionY - ev.getRawY();
3870                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
3871
3872                        final ViewConfiguration viewConfiguration = ViewConfiguration.get(
3873                                mTextView.getContext());
3874                        final int touchSlop = viewConfiguration.getScaledTouchSlop();
3875
3876                        if (distanceSquared < touchSlop * touchSlop) {
3877                            // Tapping on the handle toggles the selection action mode.
3878                            if (mSelectionActionMode != null) {
3879                                mSelectionActionMode.finish();
3880                            } else {
3881                                startSelectionActionModeWithoutSelection();
3882                            }
3883                        }
3884                    } else {
3885                        if (mSelectionActionMode != null) {
3886                            mSelectionActionMode.invalidateContentRect();
3887                        }
3888                    }
3889                    hideAfterDelay();
3890                    break;
3891
3892                case MotionEvent.ACTION_CANCEL:
3893                    hideAfterDelay();
3894                    break;
3895
3896                default:
3897                    break;
3898            }
3899
3900            return result;
3901        }
3902
3903        @Override
3904        public int getCurrentCursorOffset() {
3905            return mTextView.getSelectionStart();
3906        }
3907
3908        @Override
3909        public void updateSelection(int offset) {
3910            Selection.setSelection((Spannable) mTextView.getText(), offset);
3911        }
3912
3913        @Override
3914        public void updatePosition(float x, float y) {
3915            positionAtCursorOffset(mTextView.getOffsetForPosition(x, y), false);
3916        }
3917
3918        @Override
3919        void onHandleMoved() {
3920            super.onHandleMoved();
3921            removeHiderCallback();
3922        }
3923
3924        @Override
3925        public void onDetached() {
3926            super.onDetached();
3927            removeHiderCallback();
3928        }
3929    }
3930
3931    private class SelectionStartHandleView extends HandleView {
3932        // Indicates whether the cursor is making adjustments within a word.
3933        private boolean mInWord = false;
3934        // Offset to track difference between touch and word boundary.
3935        protected int mTouchWordOffset;
3936
3937        public SelectionStartHandleView(Drawable drawableLtr, Drawable drawableRtl) {
3938            super(drawableLtr, drawableRtl);
3939        }
3940
3941        @Override
3942        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
3943            return isRtlRun ? 0 : drawable.getIntrinsicWidth();
3944        }
3945
3946        @Override
3947        protected int getHorizontalGravity(boolean isRtlRun) {
3948            return isRtlRun ? Gravity.RIGHT : Gravity.LEFT;
3949        }
3950
3951        @Override
3952        public int getCurrentCursorOffset() {
3953            return mTextView.getSelectionStart();
3954        }
3955
3956        @Override
3957        public void updateSelection(int offset) {
3958            Selection.setSelection((Spannable) mTextView.getText(), offset,
3959                    mTextView.getSelectionEnd());
3960            updateDrawable();
3961            if (mSelectionActionMode != null) {
3962                mSelectionActionMode.invalidate();
3963            }
3964        }
3965
3966        @Override
3967        public void updatePosition(float x, float y) {
3968            final int trueOffset = mTextView.getOffsetForPosition(x, y);
3969            final int currLine = mTextView.getLineAtCoordinate(y);
3970            boolean positionCursor = false;
3971            int offset = trueOffset;
3972            int end = getWordEnd(offset);
3973            int start = getWordStart(offset);
3974
3975            if (offset < mPreviousOffset) {
3976                // User is increasing the selection.
3977                if (!mInWord || currLine < mPrevLine) {
3978                    // We're not in a word, or we're on a different line so we'll expand by
3979                    // word. First ensure the user has at least entered the next word.
3980                    int offsetToWord = Math.min((end - start) / 2, 2);
3981                    if (offset <= end - offsetToWord || currLine < mPrevLine) {
3982                        offset = start;
3983                    } else {
3984                        offset = mPreviousOffset;
3985                    }
3986                }
3987                mTouchWordOffset = Math.max(trueOffset - offset, 0);
3988                positionCursor = true;
3989            } else if (offset - mTouchWordOffset > mPreviousOffset || currLine > mPrevLine) {
3990                // User is shrinking the selection.
3991                if (currLine > mPrevLine) {
3992                    // We're on a different line, so we'll snap to word boundaries.
3993                    offset = start;
3994                    mTouchWordOffset = Math.max(trueOffset - offset, 0);
3995                } else {
3996                    offset -= mTouchWordOffset;
3997                }
3998                positionCursor = true;
3999            }
4000
4001            // Handles can not cross and selection is at least one character.
4002            if (positionCursor) {
4003                final int selectionEnd = mTextView.getSelectionEnd();
4004                if (offset >= selectionEnd) {
4005                    // We can't cross the handles so let's just constrain the Y value.
4006                    int alteredOffset = mTextView.getOffsetAtCoordinate(mPrevLine, x);
4007                    if (alteredOffset >= selectionEnd) {
4008                        // Can't pass the other drag handle.
4009                        offset = getNextCursorOffset(selectionEnd, false);
4010                    } else {
4011                        offset = alteredOffset;
4012                    }
4013                    mTouchWordOffset = 0;
4014                }
4015                mInWord = !getWordIteratorWithText().isBoundary(offset);
4016                positionAtCursorOffset(offset, false);
4017            }
4018        }
4019
4020        @Override
4021        public boolean onTouchEvent(MotionEvent event) {
4022            boolean superResult = super.onTouchEvent(event);
4023            if (event.getActionMasked() == MotionEvent.ACTION_UP) {
4024                // Reset the touch word offset when the user has lifted their finger.
4025                mTouchWordOffset = 0;
4026            }
4027            return superResult;
4028        }
4029    }
4030
4031    private class SelectionEndHandleView extends HandleView {
4032        // Indicates whether the cursor is making adjustments within a word.
4033        private boolean mInWord = false;
4034        // Offset to track difference between touch and word boundary.
4035        protected int mTouchWordOffset;
4036
4037        public SelectionEndHandleView(Drawable drawableLtr, Drawable drawableRtl) {
4038            super(drawableLtr, drawableRtl);
4039        }
4040
4041        @Override
4042        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4043            return isRtlRun ? drawable.getIntrinsicWidth() : 0;
4044        }
4045
4046        @Override
4047        protected int getHorizontalGravity(boolean isRtlRun) {
4048            return isRtlRun ? Gravity.LEFT : Gravity.RIGHT;
4049        }
4050
4051        @Override
4052        public int getCurrentCursorOffset() {
4053            return mTextView.getSelectionEnd();
4054        }
4055
4056        @Override
4057        public void updateSelection(int offset) {
4058            Selection.setSelection((Spannable) mTextView.getText(),
4059                    mTextView.getSelectionStart(), offset);
4060            if (mSelectionActionMode != null) {
4061                mSelectionActionMode.invalidate();
4062            }
4063            updateDrawable();
4064        }
4065
4066        @Override
4067        public void updatePosition(float x, float y) {
4068            final int trueOffset = mTextView.getOffsetForPosition(x, y);
4069            final int currLine = mTextView.getLineAtCoordinate(y);
4070            int offset = trueOffset;
4071            boolean positionCursor = false;
4072            int end = getWordEnd(offset);
4073            int start = getWordStart(offset);
4074
4075            if (offset > mPreviousOffset) {
4076                // User is increasing the selection.
4077                if (!mInWord || currLine > mPrevLine) {
4078                    // We're not in a word, or we're on a different line so we'll expand by
4079                    // word. First ensure the user has at least entered the next word.
4080                    int midPoint = Math.min((end - start) / 2, 2);
4081                    if (offset >= start + midPoint || currLine > mPrevLine) {
4082                        offset = end;
4083                    } else {
4084                        offset = mPreviousOffset;
4085                    }
4086                }
4087                mTouchWordOffset = Math.max(offset - trueOffset, 0);
4088                positionCursor = true;
4089            } else if (offset + mTouchWordOffset < mPreviousOffset || currLine < mPrevLine) {
4090                // User is shrinking the selection.
4091                if (currLine < mPrevLine) {
4092                    // We're on a different line, so we'll snap to word boundaries.
4093                    offset = end;
4094                    mTouchWordOffset = Math.max(offset - trueOffset, 0);
4095                } else {
4096                    offset += mTouchWordOffset;
4097                }
4098                positionCursor = true;
4099            }
4100
4101            if (positionCursor) {
4102                final int selectionStart = mTextView.getSelectionStart();
4103                if (offset <= selectionStart) {
4104                    // We can't cross the handles so let's just constrain the Y value.
4105                    int alteredOffset = mTextView.getOffsetAtCoordinate(mPrevLine, x);
4106                    int length = mTextView.getText().length();
4107                    if (alteredOffset <= selectionStart) {
4108                        // Can't pass the other drag handle.
4109                        offset = getNextCursorOffset(selectionStart, true);
4110                    } else {
4111                        offset = Math.min(alteredOffset, length);
4112                    }
4113                    mTouchWordOffset = 0;
4114                }
4115                mInWord = !getWordIteratorWithText().isBoundary(offset);
4116                positionAtCursorOffset(offset, false);
4117            }
4118        }
4119
4120        @Override
4121        public boolean onTouchEvent(MotionEvent event) {
4122            boolean superResult = super.onTouchEvent(event);
4123            if (event.getActionMasked() == MotionEvent.ACTION_UP) {
4124                // Reset the touch word offset when the user has lifted their finger.
4125                mTouchWordOffset = 0;
4126            }
4127            return superResult;
4128        }
4129    }
4130
4131    /**
4132     * A CursorController instance can be used to control a cursor in the text.
4133     */
4134    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
4135        /**
4136         * Makes the cursor controller visible on screen.
4137         * See also {@link #hide()}.
4138         */
4139        public void show();
4140
4141        /**
4142         * Hide the cursor controller from screen.
4143         * See also {@link #show()}.
4144         */
4145        public void hide();
4146
4147        /**
4148         * Called when the view is detached from window. Perform house keeping task, such as
4149         * stopping Runnable thread that would otherwise keep a reference on the context, thus
4150         * preventing the activity from being recycled.
4151         */
4152        public void onDetached();
4153    }
4154
4155    private class InsertionPointCursorController implements CursorController {
4156        private InsertionHandleView mHandle;
4157
4158        public void show() {
4159            getHandle().show();
4160        }
4161
4162        public void hide() {
4163            if (mHandle != null) {
4164                mHandle.hide();
4165            }
4166        }
4167
4168        public void onTouchModeChanged(boolean isInTouchMode) {
4169            if (!isInTouchMode) {
4170                hide();
4171            }
4172        }
4173
4174        private InsertionHandleView getHandle() {
4175            if (mSelectHandleCenter == null) {
4176                mSelectHandleCenter = mTextView.getContext().getDrawable(
4177                        mTextView.mTextSelectHandleRes);
4178            }
4179            if (mHandle == null) {
4180                mHandle = new InsertionHandleView(mSelectHandleCenter);
4181            }
4182            return mHandle;
4183        }
4184
4185        @Override
4186        public void onDetached() {
4187            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
4188            observer.removeOnTouchModeChangeListener(this);
4189
4190            if (mHandle != null) mHandle.onDetached();
4191        }
4192    }
4193
4194    class SelectionModifierCursorController implements CursorController {
4195        // The cursor controller handles, lazily created when shown.
4196        private SelectionStartHandleView mStartHandle;
4197        private SelectionEndHandleView mEndHandle;
4198        // The offsets of that last touch down event. Remembered to start selection there.
4199        private int mMinTouchOffset, mMaxTouchOffset;
4200
4201        // Double tap detection
4202        private long mPreviousTapUpTime = 0;
4203        private float mDownPositionX, mDownPositionY;
4204        private boolean mGestureStayedInTapRegion;
4205
4206        // Where the user first starts the drag motion.
4207        private int mStartOffset = -1;
4208        // Indicates whether the user is selecting text and using the drag accelerator.
4209        private boolean mDragAcceleratorActive;
4210
4211        SelectionModifierCursorController() {
4212            resetTouchOffsets();
4213        }
4214
4215        public void show() {
4216            if (mTextView.isInBatchEditMode()) {
4217                return;
4218            }
4219            initDrawables();
4220            initHandles();
4221            hideInsertionPointCursorController();
4222        }
4223
4224        private void initDrawables() {
4225            if (mSelectHandleLeft == null) {
4226                mSelectHandleLeft = mTextView.getContext().getDrawable(
4227                        mTextView.mTextSelectHandleLeftRes);
4228            }
4229            if (mSelectHandleRight == null) {
4230                mSelectHandleRight = mTextView.getContext().getDrawable(
4231                        mTextView.mTextSelectHandleRightRes);
4232            }
4233        }
4234
4235        private void initHandles() {
4236            // Lazy object creation has to be done before updatePosition() is called.
4237            if (mStartHandle == null) {
4238                mStartHandle = new SelectionStartHandleView(mSelectHandleLeft, mSelectHandleRight);
4239            }
4240            if (mEndHandle == null) {
4241                mEndHandle = new SelectionEndHandleView(mSelectHandleRight, mSelectHandleLeft);
4242            }
4243
4244            mStartHandle.show();
4245            mEndHandle.show();
4246
4247            hideInsertionPointCursorController();
4248        }
4249
4250        public void hide() {
4251            if (mStartHandle != null) mStartHandle.hide();
4252            if (mEndHandle != null) mEndHandle.hide();
4253        }
4254
4255        public void enterDrag() {
4256            // Just need to init the handles / hide insertion cursor.
4257            show();
4258            mDragAcceleratorActive = true;
4259            // Start location of selection.
4260            mStartOffset = mTextView.getOffsetForPosition(mLastDownPositionX,
4261                    mLastDownPositionY);
4262            // Don't show the handles until user has lifted finger.
4263            hide();
4264
4265            // This stops scrolling parents from intercepting the touch event, allowing
4266            // the user to continue dragging across the screen to select text; TextView will
4267            // scroll as necessary.
4268            mTextView.getParent().requestDisallowInterceptTouchEvent(true);
4269        }
4270
4271        public void onTouchEvent(MotionEvent event) {
4272            // This is done even when the View does not have focus, so that long presses can start
4273            // selection and tap can move cursor from this tap position.
4274            switch (event.getActionMasked()) {
4275                case MotionEvent.ACTION_DOWN:
4276                    final float x = event.getX();
4277                    final float y = event.getY();
4278
4279                    // Remember finger down position, to be able to start selection from there.
4280                    mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(x, y);
4281
4282                    // Double tap detection
4283                    if (mGestureStayedInTapRegion) {
4284                        long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime;
4285                        if (duration <= ViewConfiguration.getDoubleTapTimeout()) {
4286                            final float deltaX = x - mDownPositionX;
4287                            final float deltaY = y - mDownPositionY;
4288                            final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
4289
4290                            ViewConfiguration viewConfiguration = ViewConfiguration.get(
4291                                    mTextView.getContext());
4292                            int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop();
4293                            boolean stayedInArea = distanceSquared < doubleTapSlop * doubleTapSlop;
4294
4295                            if (stayedInArea && isPositionOnText(x, y)) {
4296                                startSelectionActionModeWithSelectionAndStartDrag();
4297                                mDiscardNextActionUp = true;
4298                            }
4299                        }
4300                    }
4301
4302                    mDownPositionX = x;
4303                    mDownPositionY = y;
4304                    mGestureStayedInTapRegion = true;
4305                    break;
4306
4307                case MotionEvent.ACTION_POINTER_DOWN:
4308                case MotionEvent.ACTION_POINTER_UP:
4309                    // Handle multi-point gestures. Keep min and max offset positions.
4310                    // Only activated for devices that correctly handle multi-touch.
4311                    if (mTextView.getContext().getPackageManager().hasSystemFeature(
4312                            PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
4313                        updateMinAndMaxOffsets(event);
4314                    }
4315                    break;
4316
4317                case MotionEvent.ACTION_MOVE:
4318                    final ViewConfiguration viewConfiguration = ViewConfiguration.get(
4319                            mTextView.getContext());
4320
4321                    if (mGestureStayedInTapRegion) {
4322                        final float deltaX = event.getX() - mDownPositionX;
4323                        final float deltaY = event.getY() - mDownPositionY;
4324                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
4325
4326                        int doubleTapTouchSlop = viewConfiguration.getScaledDoubleTapTouchSlop();
4327
4328                        if (distanceSquared > doubleTapTouchSlop * doubleTapTouchSlop) {
4329                            mGestureStayedInTapRegion = false;
4330                        }
4331                    }
4332
4333                    if (mStartHandle != null && mStartHandle.isShowing()) {
4334                        // Don't do the drag if the handles are showing already.
4335                        break;
4336                    }
4337
4338                    if (mStartOffset != -1) {
4339                        final int rawOffset = mTextView.getOffsetForPosition(event.getX(),
4340                                event.getY());
4341                        int offset = rawOffset;
4342
4343                        // We don't start "dragging" until the user is past the initial word that
4344                        // gets selected on long press.
4345                        int firstWordStart = getWordStart(mStartOffset);
4346                        int firstWordEnd = getWordEnd(mStartOffset);
4347                        if (offset > firstWordEnd || offset < firstWordStart) {
4348
4349                            // Basically the goal in the below code is to have the highlight be
4350                            // offset so that your finger isn't covering the end point.
4351                            int fingerOffset = viewConfiguration.getScaledTouchSlop();
4352                            float mx = event.getX();
4353                            float my = event.getY();
4354                            if (mx > fingerOffset) mx -= fingerOffset;
4355                            if (my > fingerOffset) my -= fingerOffset;
4356                            offset = mTextView.getOffsetForPosition(mx, my);
4357
4358                            // Perform the check for closeness at edge of view, if we're very close
4359                            // don't adjust the offset to be in front of the finger - otherwise the
4360                            // user can't select words at the edge.
4361                            if (mTextView.getWidth() - fingerOffset > mx) {
4362                                // We're going by word, so we need to make sure that the offset
4363                                // that we get is within this, so we'll get the previous boundary.
4364                                final WordIterator wordIterator = getWordIteratorWithText();
4365
4366                                final int precedingOffset = wordIterator.preceding(offset);
4367                                if (mStartOffset < offset) {
4368                                    // Expanding with bottom handle, in this case the selection end
4369                                    // is before the finger.
4370                                    offset = Math.max(precedingOffset - 1, 0);
4371                                } else {
4372                                    // Expand with the start handle, in this case the selection
4373                                    // start is before the finger.
4374                                    if (precedingOffset == WordIterator.DONE) {
4375                                        offset = 0;
4376                                    } else {
4377                                        offset = wordIterator.preceding(precedingOffset);
4378                                    }
4379                                }
4380                            }
4381                            if (offset == WordIterator.DONE)
4382                                offset = rawOffset;
4383
4384                            // Need to adjust start offset based on direction of movement.
4385                            int newStart = mStartOffset < offset ? getWordStart(mStartOffset)
4386                                    : getWordEnd(mStartOffset);
4387                            Selection.setSelection((Spannable) mTextView.getText(), newStart,
4388                                    offset);
4389                        }
4390                    }
4391                    break;
4392
4393                case MotionEvent.ACTION_UP:
4394                    mPreviousTapUpTime = SystemClock.uptimeMillis();
4395                    if (mDragAcceleratorActive) {
4396                        // No longer dragging to select text, let the parent intercept events.
4397                        mTextView.getParent().requestDisallowInterceptTouchEvent(false);
4398
4399                        show();
4400                        int startOffset = mTextView.getSelectionStart();
4401                        int endOffset = mTextView.getSelectionEnd();
4402
4403                        // Since we don't let drag handles pass once they're visible, we need to
4404                        // make sure the start / end locations are correct because the user *can*
4405                        // switch directions during the initial drag.
4406                        if (endOffset < startOffset) {
4407                            int tmp = endOffset;
4408                            endOffset = startOffset;
4409                            startOffset = tmp;
4410
4411                            // Also update the selection with the right offsets in this case.
4412                            Selection.setSelection((Spannable) mTextView.getText(),
4413                                    startOffset, endOffset);
4414                        }
4415
4416                        // Need to do this to display the handles.
4417                        mStartHandle.showAtLocation(startOffset);
4418                        mEndHandle.showAtLocation(endOffset);
4419
4420                        // No longer the first dragging motion, reset.
4421                        mDragAcceleratorActive = false;
4422                        mStartOffset = -1;
4423                    }
4424                    break;
4425            }
4426        }
4427
4428        /**
4429         * @param event
4430         */
4431        private void updateMinAndMaxOffsets(MotionEvent event) {
4432            int pointerCount = event.getPointerCount();
4433            for (int index = 0; index < pointerCount; index++) {
4434                int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index));
4435                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
4436                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
4437            }
4438        }
4439
4440        public int getMinTouchOffset() {
4441            return mMinTouchOffset;
4442        }
4443
4444        public int getMaxTouchOffset() {
4445            return mMaxTouchOffset;
4446        }
4447
4448        public void resetTouchOffsets() {
4449            mMinTouchOffset = mMaxTouchOffset = -1;
4450            mStartOffset = -1;
4451            mDragAcceleratorActive = false;
4452        }
4453
4454        /**
4455         * @return true iff this controller is currently used to move the selection start.
4456         */
4457        public boolean isSelectionStartDragged() {
4458            return mStartHandle != null && mStartHandle.isDragging();
4459        }
4460
4461        /**
4462         * @return true if the user is selecting text using the drag accelerator.
4463         */
4464        public boolean isDragAcceleratorActive() {
4465            return mDragAcceleratorActive;
4466        }
4467
4468        public void onTouchModeChanged(boolean isInTouchMode) {
4469            if (!isInTouchMode) {
4470                hide();
4471            }
4472        }
4473
4474        @Override
4475        public void onDetached() {
4476            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
4477            observer.removeOnTouchModeChangeListener(this);
4478
4479            if (mStartHandle != null) mStartHandle.onDetached();
4480            if (mEndHandle != null) mEndHandle.onDetached();
4481        }
4482    }
4483
4484    private class CorrectionHighlighter {
4485        private final Path mPath = new Path();
4486        private final Paint mPaint = new Paint();
4487        private int mStart, mEnd;
4488        private long mFadingStartTime;
4489        private RectF mTempRectF;
4490        private final static int FADE_OUT_DURATION = 400;
4491
4492        public CorrectionHighlighter() {
4493            mPaint.setCompatibilityScaling(mTextView.getResources().getCompatibilityInfo().
4494                    applicationScale);
4495            mPaint.setStyle(Paint.Style.FILL);
4496        }
4497
4498        public void highlight(CorrectionInfo info) {
4499            mStart = info.getOffset();
4500            mEnd = mStart + info.getNewText().length();
4501            mFadingStartTime = SystemClock.uptimeMillis();
4502
4503            if (mStart < 0 || mEnd < 0) {
4504                stopAnimation();
4505            }
4506        }
4507
4508        public void draw(Canvas canvas, int cursorOffsetVertical) {
4509            if (updatePath() && updatePaint()) {
4510                if (cursorOffsetVertical != 0) {
4511                    canvas.translate(0, cursorOffsetVertical);
4512                }
4513
4514                canvas.drawPath(mPath, mPaint);
4515
4516                if (cursorOffsetVertical != 0) {
4517                    canvas.translate(0, -cursorOffsetVertical);
4518                }
4519                invalidate(true); // TODO invalidate cursor region only
4520            } else {
4521                stopAnimation();
4522                invalidate(false); // TODO invalidate cursor region only
4523            }
4524        }
4525
4526        private boolean updatePaint() {
4527            final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
4528            if (duration > FADE_OUT_DURATION) return false;
4529
4530            final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
4531            final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor);
4532            final int color = (mTextView.mHighlightColor & 0x00FFFFFF) +
4533                    ((int) (highlightColorAlpha * coef) << 24);
4534            mPaint.setColor(color);
4535            return true;
4536        }
4537
4538        private boolean updatePath() {
4539            final Layout layout = mTextView.getLayout();
4540            if (layout == null) return false;
4541
4542            // Update in case text is edited while the animation is run
4543            final int length = mTextView.getText().length();
4544            int start = Math.min(length, mStart);
4545            int end = Math.min(length, mEnd);
4546
4547            mPath.reset();
4548            layout.getSelectionPath(start, end, mPath);
4549            return true;
4550        }
4551
4552        private void invalidate(boolean delayed) {
4553            if (mTextView.getLayout() == null) return;
4554
4555            if (mTempRectF == null) mTempRectF = new RectF();
4556            mPath.computeBounds(mTempRectF, false);
4557
4558            int left = mTextView.getCompoundPaddingLeft();
4559            int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true);
4560
4561            if (delayed) {
4562                mTextView.postInvalidateOnAnimation(
4563                        left + (int) mTempRectF.left, top + (int) mTempRectF.top,
4564                        left + (int) mTempRectF.right, top + (int) mTempRectF.bottom);
4565            } else {
4566                mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top,
4567                        (int) mTempRectF.right, (int) mTempRectF.bottom);
4568            }
4569        }
4570
4571        private void stopAnimation() {
4572            Editor.this.mCorrectionHighlighter = null;
4573        }
4574    }
4575
4576    private static class ErrorPopup extends PopupWindow {
4577        private boolean mAbove = false;
4578        private final TextView mView;
4579        private int mPopupInlineErrorBackgroundId = 0;
4580        private int mPopupInlineErrorAboveBackgroundId = 0;
4581
4582        ErrorPopup(TextView v, int width, int height) {
4583            super(v, width, height);
4584            mView = v;
4585            // Make sure the TextView has a background set as it will be used the first time it is
4586            // shown and positioned. Initialized with below background, which should have
4587            // dimensions identical to the above version for this to work (and is more likely).
4588            mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
4589                    com.android.internal.R.styleable.Theme_errorMessageBackground);
4590            mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
4591        }
4592
4593        void fixDirection(boolean above) {
4594            mAbove = above;
4595
4596            if (above) {
4597                mPopupInlineErrorAboveBackgroundId =
4598                    getResourceId(mPopupInlineErrorAboveBackgroundId,
4599                            com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
4600            } else {
4601                mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
4602                        com.android.internal.R.styleable.Theme_errorMessageBackground);
4603            }
4604
4605            mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId :
4606                mPopupInlineErrorBackgroundId);
4607        }
4608
4609        private int getResourceId(int currentId, int index) {
4610            if (currentId == 0) {
4611                TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
4612                        R.styleable.Theme);
4613                currentId = styledAttributes.getResourceId(index, 0);
4614                styledAttributes.recycle();
4615            }
4616            return currentId;
4617        }
4618
4619        @Override
4620        public void update(int x, int y, int w, int h, boolean force) {
4621            super.update(x, y, w, h, force);
4622
4623            boolean above = isAboveAnchor();
4624            if (above != mAbove) {
4625                fixDirection(above);
4626            }
4627        }
4628    }
4629
4630    static class InputContentType {
4631        int imeOptions = EditorInfo.IME_NULL;
4632        String privateImeOptions;
4633        CharSequence imeActionLabel;
4634        int imeActionId;
4635        Bundle extras;
4636        OnEditorActionListener onEditorActionListener;
4637        boolean enterDown;
4638    }
4639
4640    static class InputMethodState {
4641        ExtractedTextRequest mExtractedTextRequest;
4642        final ExtractedText mExtractedText = new ExtractedText();
4643        int mBatchEditNesting;
4644        boolean mCursorChanged;
4645        boolean mSelectionModeChanged;
4646        boolean mContentChanged;
4647        int mChangedStart, mChangedEnd, mChangedDelta;
4648    }
4649
4650    /**
4651     * @return True iff (start, end) is a valid range within the text.
4652     */
4653    private static boolean isValidRange(CharSequence text, int start, int end) {
4654        return 0 <= start && start <= end && end <= text.length();
4655    }
4656
4657    /**
4658     * An InputFilter that monitors text input to maintain undo history. It does not modify the
4659     * text being typed (and hence always returns null from the filter() method).
4660     */
4661    public static class UndoInputFilter implements InputFilter {
4662        private final Editor mEditor;
4663
4664        // Whether the current filter pass is directly caused by an end-user text edit.
4665        private boolean mIsUserEdit;
4666
4667        // Whether the text field is handling an IME composition. Must be parceled in case the user
4668        // rotates the screen during composition.
4669        private boolean mHasComposition;
4670
4671        public UndoInputFilter(Editor editor) {
4672            mEditor = editor;
4673        }
4674
4675        public void saveInstanceState(Parcel parcel) {
4676            parcel.writeInt(mIsUserEdit ? 1 : 0);
4677            parcel.writeInt(mHasComposition ? 1 : 0);
4678        }
4679
4680        public void restoreInstanceState(Parcel parcel) {
4681            mIsUserEdit = parcel.readInt() != 0;
4682            mHasComposition = parcel.readInt() != 0;
4683        }
4684
4685        /**
4686         * Signals that a user-triggered edit is starting.
4687         */
4688        public void beginBatchEdit() {
4689            if (DEBUG_UNDO) Log.d(TAG, "beginBatchEdit");
4690            mIsUserEdit = true;
4691        }
4692
4693        public void endBatchEdit() {
4694            if (DEBUG_UNDO) Log.d(TAG, "endBatchEdit");
4695            mIsUserEdit = false;
4696        }
4697
4698        @Override
4699        public CharSequence filter(CharSequence source, int start, int end,
4700                Spanned dest, int dstart, int dend) {
4701            if (DEBUG_UNDO) {
4702                Log.d(TAG, "filter: source=" + source + " (" + start + "-" + end + ") " +
4703                        "dest=" + dest + " (" + dstart + "-" + dend + ")");
4704            }
4705
4706            // Check to see if this edit should be tracked for undo.
4707            if (!canUndoEdit(source, start, end, dest, dstart, dend)) {
4708                return null;
4709            }
4710
4711            // Check for and handle IME composition edits.
4712            if (handleCompositionEdit(source, start, end, dstart)) {
4713                return null;
4714            }
4715
4716            // Handle keyboard edits.
4717            handleKeyboardEdit(source, start, end, dest, dstart, dend);
4718            return null;
4719        }
4720
4721        /**
4722         * Returns true iff the edit was handled, either because it should be ignored or because
4723         * this function created an undo operation for it.
4724         */
4725        private boolean handleCompositionEdit(CharSequence source, int start, int end, int dstart) {
4726            // Ignore edits while the user is composing.
4727            if (isComposition(source)) {
4728                mHasComposition = true;
4729                return true;
4730            }
4731            final boolean hadComposition = mHasComposition;
4732            mHasComposition = false;
4733
4734            // Check for the transition out of the composing state.
4735            if (hadComposition) {
4736                // If there was no text the user canceled composition. Ignore the edit.
4737                if (start == end) {
4738                    return true;
4739                }
4740
4741                // Otherwise the user inserted the composition.
4742                String newText = TextUtils.substring(source, start, end);
4743                EditOperation edit = new EditOperation(mEditor, "", dstart, newText);
4744                recordEdit(edit, false /* forceMerge */);
4745                return true;
4746            }
4747
4748            // This was neither a composition event nor a transition out of composing.
4749            return false;
4750        }
4751
4752        private void handleKeyboardEdit(CharSequence source, int start, int end,
4753                Spanned dest, int dstart, int dend) {
4754            // An application may install a TextWatcher to provide additional modifications after
4755            // the initial input filters run (e.g. a credit card formatter that adds spaces to a
4756            // string). This results in multiple filter() calls for what the user considers to be
4757            // a single operation. Always undo the whole set of changes in one step.
4758            final boolean forceMerge = isInTextWatcher();
4759
4760            // Build a new operation with all the information from this edit.
4761            String newText = TextUtils.substring(source, start, end);
4762            String oldText = TextUtils.substring(dest, dstart, dend);
4763            EditOperation edit = new EditOperation(mEditor, oldText, dstart, newText);
4764            recordEdit(edit, forceMerge);
4765        }
4766
4767        /**
4768         * Fetches the last undo operation and checks to see if a new edit should be merged into it.
4769         * If forceMerge is true then the new edit is always merged.
4770         */
4771        private void recordEdit(EditOperation edit, boolean forceMerge) {
4772            // Fetch the last edit operation and attempt to merge in the new edit.
4773            final UndoManager um = mEditor.mUndoManager;
4774            um.beginUpdate("Edit text");
4775            EditOperation lastEdit = um.getLastOperation(
4776                  EditOperation.class, mEditor.mUndoOwner, UndoManager.MERGE_MODE_UNIQUE);
4777            if (lastEdit == null) {
4778                // Add this as the first edit.
4779                if (DEBUG_UNDO) Log.d(TAG, "filter: adding first op " + edit);
4780                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
4781            } else if (forceMerge) {
4782                // Forced merges take priority because they could be the result of a non-user-edit
4783                // change and this case should not create a new undo operation.
4784                if (DEBUG_UNDO) Log.d(TAG, "filter: force merge " + edit);
4785                lastEdit.forceMergeWith(edit);
4786            } else if (!mIsUserEdit) {
4787                // An application directly modified the Editable outside of a text edit. Treat this
4788                // as a new change and don't attempt to merge.
4789                if (DEBUG_UNDO) Log.d(TAG, "non-user edit, new op " + edit);
4790                um.commitState(mEditor.mUndoOwner);
4791                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
4792            } else if (lastEdit.mergeWith(edit)) {
4793                // Merge succeeded, nothing else to do.
4794                if (DEBUG_UNDO) Log.d(TAG, "filter: merge succeeded, created " + lastEdit);
4795            } else {
4796                // Could not merge with the last edit, so commit the last edit and add this edit.
4797                if (DEBUG_UNDO) Log.d(TAG, "filter: merge failed, adding " + edit);
4798                um.commitState(mEditor.mUndoOwner);
4799                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
4800            }
4801            um.endUpdate();
4802        }
4803
4804        private boolean canUndoEdit(CharSequence source, int start, int end,
4805                Spanned dest, int dstart, int dend) {
4806            if (!mEditor.mAllowUndo) {
4807                if (DEBUG_UNDO) Log.d(TAG, "filter: undo is disabled");
4808                return false;
4809            }
4810
4811            if (mEditor.mUndoManager.isInUndo()) {
4812                if (DEBUG_UNDO) Log.d(TAG, "filter: skipping, currently performing undo/redo");
4813                return false;
4814            }
4815
4816            // Text filters run before input operations are applied. However, some input operations
4817            // are invalid and will throw exceptions when applied. This is common in tests. Don't
4818            // attempt to undo invalid operations.
4819            if (!isValidRange(source, start, end) || !isValidRange(dest, dstart, dend)) {
4820                if (DEBUG_UNDO) Log.d(TAG, "filter: invalid op");
4821                return false;
4822            }
4823
4824            // Earlier filters can rewrite input to be a no-op, for example due to a length limit
4825            // on an input field. Skip no-op changes.
4826            if (start == end && dstart == dend) {
4827                if (DEBUG_UNDO) Log.d(TAG, "filter: skipping no-op");
4828                return false;
4829            }
4830
4831            return true;
4832        }
4833
4834        private boolean isComposition(CharSequence source) {
4835            if (!(source instanceof Spannable)) {
4836                return false;
4837            }
4838            // This is a composition edit if the source has a non-zero-length composing span.
4839            Spannable text = (Spannable) source;
4840            int composeBegin = EditableInputConnection.getComposingSpanStart(text);
4841            int composeEnd = EditableInputConnection.getComposingSpanEnd(text);
4842            return composeBegin < composeEnd;
4843        }
4844
4845        private boolean isInTextWatcher() {
4846            CharSequence text = mEditor.mTextView.getText();
4847            return (text instanceof SpannableStringBuilder)
4848                    && ((SpannableStringBuilder) text).getTextWatcherDepth() > 0;
4849        }
4850    }
4851
4852    /**
4853     * An operation to undo a single "edit" to a text view.
4854     */
4855    public static class EditOperation extends UndoOperation<Editor> {
4856        private static final int TYPE_INSERT = 0;
4857        private static final int TYPE_DELETE = 1;
4858        private static final int TYPE_REPLACE = 2;
4859
4860        private int mType;
4861        private String mOldText;
4862        private int mOldTextStart;
4863        private String mNewText;
4864        private int mNewTextStart;
4865
4866        private int mOldCursorPos;
4867        private int mNewCursorPos;
4868
4869        /**
4870         * Constructs an edit operation from a text input operation on editor that replaces the
4871         * oldText starting at dstart with newText.
4872         */
4873        public EditOperation(Editor editor, String oldText, int dstart, String newText) {
4874            super(editor.mUndoOwner);
4875            mOldText = oldText;
4876            mNewText = newText;
4877
4878            // Determine the type of the edit and store where it occurred. Avoid storing
4879            // irrevelant data (e.g. mNewTextStart for a delete) because that makes the
4880            // merging logic more complex (e.g. merging deletes could lead to mNewTextStart being
4881            // outside the bounds of the final text).
4882            if (mNewText.length() > 0 && mOldText.length() == 0) {
4883                mType = TYPE_INSERT;
4884                mNewTextStart = dstart;
4885            } else if (mNewText.length() == 0 && mOldText.length() > 0) {
4886                mType = TYPE_DELETE;
4887                mOldTextStart = dstart;
4888            } else {
4889                mType = TYPE_REPLACE;
4890                mOldTextStart = mNewTextStart = dstart;
4891            }
4892
4893            // Store cursor data.
4894            mOldCursorPos = editor.mTextView.getSelectionStart();
4895            mNewCursorPos = dstart + mNewText.length();
4896        }
4897
4898        public EditOperation(Parcel src, ClassLoader loader) {
4899            super(src, loader);
4900            mType = src.readInt();
4901            mOldText = src.readString();
4902            mOldTextStart = src.readInt();
4903            mNewText = src.readString();
4904            mNewTextStart = src.readInt();
4905            mOldCursorPos = src.readInt();
4906            mNewCursorPos = src.readInt();
4907        }
4908
4909        @Override
4910        public void writeToParcel(Parcel dest, int flags) {
4911            dest.writeInt(mType);
4912            dest.writeString(mOldText);
4913            dest.writeInt(mOldTextStart);
4914            dest.writeString(mNewText);
4915            dest.writeInt(mNewTextStart);
4916            dest.writeInt(mOldCursorPos);
4917            dest.writeInt(mNewCursorPos);
4918        }
4919
4920        private int getNewTextEnd() {
4921            return mNewTextStart + mNewText.length();
4922        }
4923
4924        private int getOldTextEnd() {
4925            return mOldTextStart + mOldText.length();
4926        }
4927
4928        @Override
4929        public void commit() {
4930        }
4931
4932        @Override
4933        public void undo() {
4934            if (DEBUG_UNDO) Log.d(TAG, "undo");
4935            // Remove the new text and insert the old.
4936            Editor editor = getOwnerData();
4937            Editable text = (Editable) editor.mTextView.getText();
4938            modifyText(text, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
4939                    mOldCursorPos);
4940        }
4941
4942        @Override
4943        public void redo() {
4944            if (DEBUG_UNDO) Log.d(TAG, "redo");
4945            // Remove the old text and insert the new.
4946            Editor editor = getOwnerData();
4947            Editable text = (Editable) editor.mTextView.getText();
4948            modifyText(text, mOldTextStart, getOldTextEnd(), mNewText, mNewTextStart,
4949                    mNewCursorPos);
4950        }
4951
4952        /**
4953         * Attempts to merge this existing operation with a new edit.
4954         * @param edit The new edit operation.
4955         * @return If the merge succeeded, returns true. Otherwise returns false and leaves this
4956         * object unchanged.
4957         */
4958        private boolean mergeWith(EditOperation edit) {
4959            if (DEBUG_UNDO) {
4960                Log.d(TAG, "mergeWith old " + this);
4961                Log.d(TAG, "mergeWith new " + edit);
4962            }
4963            switch (mType) {
4964                case TYPE_INSERT:
4965                    return mergeInsertWith(edit);
4966                case TYPE_DELETE:
4967                    return mergeDeleteWith(edit);
4968                case TYPE_REPLACE:
4969                    return mergeReplaceWith(edit);
4970                default:
4971                    return false;
4972            }
4973        }
4974
4975        private boolean mergeInsertWith(EditOperation edit) {
4976            // Only merge continuous insertions.
4977            if (edit.mType != TYPE_INSERT) {
4978                return false;
4979            }
4980            // Only merge insertions that are contiguous.
4981            if (getNewTextEnd() != edit.mNewTextStart) {
4982                return false;
4983            }
4984            mNewText += edit.mNewText;
4985            mNewCursorPos = edit.mNewCursorPos;
4986            return true;
4987        }
4988
4989        // TODO: Support forward delete.
4990        private boolean mergeDeleteWith(EditOperation edit) {
4991            // Only merge continuous deletes.
4992            if (edit.mType != TYPE_DELETE) {
4993                return false;
4994            }
4995            // Only merge deletions that are contiguous.
4996            if (mOldTextStart != edit.getOldTextEnd()) {
4997                return false;
4998            }
4999            mOldTextStart = edit.mOldTextStart;
5000            mOldText = edit.mOldText + mOldText;
5001            mNewCursorPos = edit.mNewCursorPos;
5002            return true;
5003        }
5004
5005        private boolean mergeReplaceWith(EditOperation edit) {
5006            // Replacements can merge only with adjacent inserts.
5007            if (edit.mType != TYPE_INSERT || getNewTextEnd() != edit.mNewTextStart) {
5008                return false;
5009            }
5010            mOldText += edit.mOldText;
5011            mNewText += edit.mNewText;
5012            mNewCursorPos = edit.mNewCursorPos;
5013            return true;
5014        }
5015
5016        /**
5017         * Forcibly creates a single merged edit operation by simulating the entire text
5018         * contents being replaced.
5019         */
5020        public void forceMergeWith(EditOperation edit) {
5021            if (DEBUG_UNDO) Log.d(TAG, "forceMerge");
5022            Editor editor = getOwnerData();
5023
5024            // Copy the text of the current field.
5025            // NOTE: Using StringBuilder instead of SpannableStringBuilder would be somewhat faster,
5026            // but would require two parallel implementations of modifyText() because Editable and
5027            // StringBuilder do not share an interface for replace/delete/insert.
5028            Editable editable = (Editable) editor.mTextView.getText();
5029            Editable originalText = new SpannableStringBuilder(editable.toString());
5030
5031            // Roll back the last operation.
5032            modifyText(originalText, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
5033                    mOldCursorPos);
5034
5035            // Clone the text again and apply the new operation.
5036            Editable finalText = new SpannableStringBuilder(editable.toString());
5037            modifyText(finalText, edit.mOldTextStart, edit.getOldTextEnd(), edit.mNewText,
5038                    edit.mNewTextStart, edit.mNewCursorPos);
5039
5040            // Convert this operation into a non-mergeable replacement of the entire string.
5041            mType = TYPE_REPLACE;
5042            mNewText = finalText.toString();
5043            mNewTextStart = 0;
5044            mOldText = originalText.toString();
5045            mOldTextStart = 0;
5046            mNewCursorPos = edit.mNewCursorPos;
5047            // mOldCursorPos is unchanged.
5048        }
5049
5050        private static void modifyText(Editable text, int deleteFrom, int deleteTo,
5051                CharSequence newText, int newTextInsertAt, int newCursorPos) {
5052            // Apply the edit if it is still valid.
5053            if (isValidRange(text, deleteFrom, deleteTo) &&
5054                    newTextInsertAt <= text.length() - (deleteTo - deleteFrom)) {
5055                if (deleteFrom != deleteTo) {
5056                    text.delete(deleteFrom, deleteTo);
5057                }
5058                if (newText.length() != 0) {
5059                    text.insert(newTextInsertAt, newText);
5060                }
5061            }
5062            // Restore the cursor position. If there wasn't an old cursor (newCursorPos == -1) then
5063            // don't explicitly set it and rely on SpannableStringBuilder to position it.
5064            // TODO: Select all the text that was undone.
5065            if (0 <= newCursorPos && newCursorPos <= text.length()) {
5066                Selection.setSelection(text, newCursorPos);
5067            }
5068        }
5069
5070        private String getTypeString() {
5071            switch (mType) {
5072                case TYPE_INSERT:
5073                    return "insert";
5074                case TYPE_DELETE:
5075                    return "delete";
5076                case TYPE_REPLACE:
5077                    return "replace";
5078                default:
5079                    return "";
5080            }
5081        }
5082
5083        @Override
5084        public String toString() {
5085            return "[mType=" + getTypeString() + ", " +
5086                    "mOldText=" + mOldText + ", " +
5087                    "mOldTextStart=" + mOldTextStart + ", " +
5088                    "mNewText=" + mNewText + ", " +
5089                    "mNewTextStart=" + mNewTextStart + ", " +
5090                    "mOldCursorPos=" + mOldCursorPos + ", " +
5091                    "mNewCursorPos=" + mNewCursorPos + "]";
5092        }
5093
5094        public static final Parcelable.ClassLoaderCreator<EditOperation> CREATOR
5095                = new Parcelable.ClassLoaderCreator<EditOperation>() {
5096            @Override
5097            public EditOperation createFromParcel(Parcel in) {
5098                return new EditOperation(in, null);
5099            }
5100
5101            @Override
5102            public EditOperation createFromParcel(Parcel in, ClassLoader loader) {
5103                return new EditOperation(in, loader);
5104            }
5105
5106            @Override
5107            public EditOperation[] newArray(int size) {
5108                return new EditOperation[size];
5109            }
5110        };
5111    }
5112}
5113