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