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