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