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