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