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