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