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