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