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