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