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