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