Editor.java revision fb9f5be318e4f530eff9964702cfb655a6433f00
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.content.ClipData;
21import android.content.ClipData.Item;
22import android.content.Context;
23import android.content.Intent;
24import android.content.pm.PackageManager;
25import android.content.res.TypedArray;
26import android.graphics.Canvas;
27import android.graphics.Color;
28import android.graphics.Paint;
29import android.graphics.Path;
30import android.graphics.Rect;
31import android.graphics.RectF;
32import android.graphics.drawable.Drawable;
33import android.inputmethodservice.ExtractEditText;
34import android.os.Bundle;
35import android.os.Handler;
36import android.os.SystemClock;
37import android.provider.Settings;
38import android.text.DynamicLayout;
39import android.text.Editable;
40import android.text.InputType;
41import android.text.Layout;
42import android.text.ParcelableSpan;
43import android.text.Selection;
44import android.text.SpanWatcher;
45import android.text.Spannable;
46import android.text.SpannableStringBuilder;
47import android.text.Spanned;
48import android.text.StaticLayout;
49import android.text.TextUtils;
50import android.text.TextWatcher;
51import android.text.method.KeyListener;
52import android.text.method.MetaKeyKeyListener;
53import android.text.method.MovementMethod;
54import android.text.method.PasswordTransformationMethod;
55import android.text.method.WordIterator;
56import android.text.style.EasyEditSpan;
57import android.text.style.SuggestionRangeSpan;
58import android.text.style.SuggestionSpan;
59import android.text.style.TextAppearanceSpan;
60import android.text.style.URLSpan;
61import android.util.DisplayMetrics;
62import android.util.Log;
63import android.view.ActionMode;
64import android.view.ActionMode.Callback;
65import android.view.DisplayList;
66import android.view.DragEvent;
67import android.view.Gravity;
68import android.view.HardwareCanvas;
69import android.view.LayoutInflater;
70import android.view.Menu;
71import android.view.MenuItem;
72import android.view.MotionEvent;
73import android.view.View;
74import android.view.ViewConfiguration;
75import android.view.ViewGroup;
76import android.view.View.DragShadowBuilder;
77import android.view.View.OnClickListener;
78import android.view.ViewGroup.LayoutParams;
79import android.view.ViewParent;
80import android.view.ViewTreeObserver;
81import android.view.WindowManager;
82import android.view.inputmethod.CorrectionInfo;
83import android.view.inputmethod.EditorInfo;
84import android.view.inputmethod.ExtractedText;
85import android.view.inputmethod.ExtractedTextRequest;
86import android.view.inputmethod.InputConnection;
87import android.view.inputmethod.InputMethodManager;
88import android.widget.AdapterView.OnItemClickListener;
89import android.widget.TextView.Drawables;
90import android.widget.TextView.OnEditorActionListener;
91
92import com.android.internal.util.ArrayUtils;
93import com.android.internal.widget.EditableInputConnection;
94
95import java.text.BreakIterator;
96import java.util.Arrays;
97import java.util.Comparator;
98import java.util.HashMap;
99
100/**
101 * Helper class used by TextView to handle editable text views.
102 *
103 * @hide
104 */
105public class Editor {
106    static final int BLINK = 500;
107    private static final float[] TEMP_POSITION = new float[2];
108    private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
109
110    // Cursor Controllers.
111    InsertionPointCursorController mInsertionPointCursorController;
112    SelectionModifierCursorController mSelectionModifierCursorController;
113    ActionMode mSelectionActionMode;
114    boolean mInsertionControllerEnabled;
115    boolean mSelectionControllerEnabled;
116
117    // Used to highlight a word when it is corrected by the IME
118    CorrectionHighlighter mCorrectionHighlighter;
119
120    InputContentType mInputContentType;
121    InputMethodState mInputMethodState;
122
123    DisplayList[] mTextDisplayLists;
124
125    boolean mFrozenWithFocus;
126    boolean mSelectionMoved;
127    boolean mTouchFocusSelected;
128
129    KeyListener mKeyListener;
130    int mInputType = EditorInfo.TYPE_NULL;
131
132    boolean mDiscardNextActionUp;
133    boolean mIgnoreActionUpEvent;
134
135    long mShowCursor;
136    Blink mBlink;
137
138    boolean mCursorVisible = true;
139    boolean mSelectAllOnFocus;
140    boolean mTextIsSelectable;
141
142    CharSequence mError;
143    boolean mErrorWasChanged;
144    ErrorPopup mErrorPopup;
145    /**
146     * This flag is set if the TextView tries to display an error before it
147     * is attached to the window (so its position is still unknown).
148     * It causes the error to be shown later, when onAttachedToWindow()
149     * is called.
150     */
151    boolean mShowErrorAfterAttach;
152
153    boolean mInBatchEditControllers;
154
155    SuggestionsPopupWindow mSuggestionsPopupWindow;
156    SuggestionRangeSpan mSuggestionRangeSpan;
157    Runnable mShowSuggestionRunnable;
158
159    final Drawable[] mCursorDrawable = new Drawable[2];
160    int mCursorCount; // Current number of used mCursorDrawable: 0 (resource=0), 1 or 2 (split)
161
162    private Drawable mSelectHandleLeft;
163    private Drawable mSelectHandleRight;
164    private Drawable mSelectHandleCenter;
165
166    // Global listener that detects changes in the global position of the TextView
167    private PositionListener mPositionListener;
168
169    float mLastDownPositionX, mLastDownPositionY;
170    Callback mCustomSelectionActionModeCallback;
171
172    // Set when this TextView gained focus with some text selected. Will start selection mode.
173    boolean mCreatedWithASelection;
174
175    private EasyEditSpanController mEasyEditSpanController;
176
177    WordIterator mWordIterator;
178    SpellChecker mSpellChecker;
179
180    private Rect mTempRect;
181
182    private TextView mTextView;
183
184    Editor(TextView textView) {
185        mTextView = textView;
186        mEasyEditSpanController = new EasyEditSpanController();
187        mTextView.addTextChangedListener(mEasyEditSpanController);
188    }
189
190    void onAttachedToWindow() {
191        if (mShowErrorAfterAttach) {
192            showError();
193            mShowErrorAfterAttach = false;
194        }
195
196        final ViewTreeObserver observer = mTextView.getViewTreeObserver();
197        // No need to create the controller.
198        // The get method will add the listener on controller creation.
199        if (mInsertionPointCursorController != null) {
200            observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
201        }
202        if (mSelectionModifierCursorController != null) {
203            observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
204        }
205        updateSpellCheckSpans(0, mTextView.getText().length(),
206                true /* create the spell checker if needed */);
207    }
208
209    void onDetachedFromWindow() {
210        if (mError != null) {
211            hideError();
212        }
213
214        if (mBlink != null) {
215            mBlink.removeCallbacks(mBlink);
216        }
217
218        if (mInsertionPointCursorController != null) {
219            mInsertionPointCursorController.onDetached();
220        }
221
222        if (mSelectionModifierCursorController != null) {
223            mSelectionModifierCursorController.onDetached();
224        }
225
226        if (mShowSuggestionRunnable != null) {
227            mTextView.removeCallbacks(mShowSuggestionRunnable);
228        }
229
230        invalidateTextDisplayList();
231
232        if (mSpellChecker != null) {
233            mSpellChecker.closeSession();
234            // Forces the creation of a new SpellChecker next time this window is created.
235            // Will handle the cases where the settings has been changed in the meantime.
236            mSpellChecker = null;
237        }
238
239        hideControllers();
240    }
241
242    private void showError() {
243        if (mTextView.getWindowToken() == null) {
244            mShowErrorAfterAttach = true;
245            return;
246        }
247
248        if (mErrorPopup == null) {
249            LayoutInflater inflater = LayoutInflater.from(mTextView.getContext());
250            final TextView err = (TextView) inflater.inflate(
251                    com.android.internal.R.layout.textview_hint, null);
252
253            final float scale = mTextView.getResources().getDisplayMetrics().density;
254            mErrorPopup = new ErrorPopup(err, (int)(200 * scale + 0.5f), (int)(50 * scale + 0.5f));
255            mErrorPopup.setFocusable(false);
256            // The user is entering text, so the input method is needed.  We
257            // don't want the popup to be displayed on top of it.
258            mErrorPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
259        }
260
261        TextView tv = (TextView) mErrorPopup.getContentView();
262        chooseSize(mErrorPopup, mError, tv);
263        tv.setText(mError);
264
265        mErrorPopup.showAsDropDown(mTextView, getErrorX(), getErrorY());
266        mErrorPopup.fixDirection(mErrorPopup.isAboveAnchor());
267    }
268
269    public void setError(CharSequence error, Drawable icon) {
270        mError = TextUtils.stringOrSpannedString(error);
271        mErrorWasChanged = true;
272        final Drawables dr = mTextView.mDrawables;
273        if (dr != null) {
274            switch (mTextView.getResolvedLayoutDirection()) {
275                default:
276                case View.LAYOUT_DIRECTION_LTR:
277                    mTextView.setCompoundDrawables(dr.mDrawableLeft, dr.mDrawableTop, icon,
278                            dr.mDrawableBottom);
279                    break;
280                case View.LAYOUT_DIRECTION_RTL:
281                    mTextView.setCompoundDrawables(icon, dr.mDrawableTop, dr.mDrawableRight,
282                            dr.mDrawableBottom);
283                    break;
284            }
285        } else {
286            mTextView.setCompoundDrawables(null, null, icon, null);
287        }
288
289        if (mError == null) {
290            if (mErrorPopup != null) {
291                if (mErrorPopup.isShowing()) {
292                    mErrorPopup.dismiss();
293                }
294
295                mErrorPopup = null;
296            }
297        } else {
298            if (mTextView.isFocused()) {
299                showError();
300            }
301        }
302    }
303
304    private void hideError() {
305        if (mErrorPopup != null) {
306            if (mErrorPopup.isShowing()) {
307                mErrorPopup.dismiss();
308            }
309        }
310
311        mShowErrorAfterAttach = false;
312    }
313
314    /**
315     * Returns the Y offset to make the pointy top of the error point
316     * at the middle of the error icon.
317     */
318    private int getErrorX() {
319        /*
320         * The "25" is the distance between the point and the right edge
321         * of the background
322         */
323        final float scale = mTextView.getResources().getDisplayMetrics().density;
324
325        final Drawables dr = mTextView.mDrawables;
326        return mTextView.getWidth() - mErrorPopup.getWidth() - mTextView.getPaddingRight() -
327                (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f);
328    }
329
330    /**
331     * Returns the Y offset to make the pointy top of the error point
332     * at the bottom of the error icon.
333     */
334    private int getErrorY() {
335        /*
336         * Compound, not extended, because the icon is not clipped
337         * if the text height is smaller.
338         */
339        final int compoundPaddingTop = mTextView.getCompoundPaddingTop();
340        int vspace = mTextView.getBottom() - mTextView.getTop() -
341                mTextView.getCompoundPaddingBottom() - compoundPaddingTop;
342
343        final Drawables dr = mTextView.mDrawables;
344        int icontop = compoundPaddingTop +
345                (vspace - (dr != null ? dr.mDrawableHeightRight : 0)) / 2;
346
347        /*
348         * The "2" is the distance between the point and the top edge
349         * of the background.
350         */
351        final float scale = mTextView.getResources().getDisplayMetrics().density;
352        return icontop + (dr != null ? dr.mDrawableHeightRight : 0) - mTextView.getHeight() -
353                (int) (2 * scale + 0.5f);
354    }
355
356    void createInputContentTypeIfNeeded() {
357        if (mInputContentType == null) {
358            mInputContentType = new InputContentType();
359        }
360    }
361
362    void createInputMethodStateIfNeeded() {
363        if (mInputMethodState == null) {
364            mInputMethodState = new InputMethodState();
365        }
366    }
367
368    boolean isCursorVisible() {
369        // The default value is true, even when there is no associated Editor
370        return mCursorVisible && mTextView.isTextEditable();
371    }
372
373    void prepareCursorControllers() {
374        boolean windowSupportsHandles = false;
375
376        ViewGroup.LayoutParams params = mTextView.getRootView().getLayoutParams();
377        if (params instanceof WindowManager.LayoutParams) {
378            WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params;
379            windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW
380                    || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW;
381        }
382
383        boolean enabled = windowSupportsHandles && mTextView.getLayout() != null;
384        mInsertionControllerEnabled = enabled && isCursorVisible();
385        mSelectionControllerEnabled = enabled && mTextView.textCanBeSelected();
386
387        if (!mInsertionControllerEnabled) {
388            hideInsertionPointCursorController();
389            if (mInsertionPointCursorController != null) {
390                mInsertionPointCursorController.onDetached();
391                mInsertionPointCursorController = null;
392            }
393        }
394
395        if (!mSelectionControllerEnabled) {
396            stopSelectionActionMode();
397            if (mSelectionModifierCursorController != null) {
398                mSelectionModifierCursorController.onDetached();
399                mSelectionModifierCursorController = null;
400            }
401        }
402    }
403
404    private void hideInsertionPointCursorController() {
405        if (mInsertionPointCursorController != null) {
406            mInsertionPointCursorController.hide();
407        }
408    }
409
410    /**
411     * Hides the insertion controller and stops text selection mode, hiding the selection controller
412     */
413    void hideControllers() {
414        hideCursorControllers();
415        hideSpanControllers();
416    }
417
418    private void hideSpanControllers() {
419        if (mEasyEditSpanController != null) {
420            mEasyEditSpanController.hide();
421        }
422    }
423
424    private void hideCursorControllers() {
425        if (mSuggestionsPopupWindow != null && !mSuggestionsPopupWindow.isShowingUp()) {
426            // Should be done before hide insertion point controller since it triggers a show of it
427            mSuggestionsPopupWindow.hide();
428        }
429        hideInsertionPointCursorController();
430        stopSelectionActionMode();
431    }
432
433    /**
434     * Create new SpellCheckSpans on the modified region.
435     */
436    private void updateSpellCheckSpans(int start, int end, boolean createSpellChecker) {
437        if (mTextView.isTextEditable() && mTextView.isSuggestionsEnabled() &&
438                !(mTextView instanceof ExtractEditText)) {
439            if (mSpellChecker == null && createSpellChecker) {
440                mSpellChecker = new SpellChecker(mTextView);
441            }
442            if (mSpellChecker != null) {
443                mSpellChecker.spellCheck(start, end);
444            }
445        }
446    }
447
448    void onScreenStateChanged(int screenState) {
449        switch (screenState) {
450            case View.SCREEN_STATE_ON:
451                resumeBlink();
452                break;
453            case View.SCREEN_STATE_OFF:
454                suspendBlink();
455                break;
456        }
457    }
458
459    private void suspendBlink() {
460        if (mBlink != null) {
461            mBlink.cancel();
462        }
463    }
464
465    private void resumeBlink() {
466        if (mBlink != null) {
467            mBlink.uncancel();
468            makeBlink();
469        }
470    }
471
472    void adjustInputType(boolean password, boolean passwordInputType,
473            boolean webPasswordInputType, boolean numberPasswordInputType) {
474        // mInputType has been set from inputType, possibly modified by mInputMethod.
475        // Specialize mInputType to [web]password if we have a text class and the original input
476        // type was a password.
477        if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
478            if (password || passwordInputType) {
479                mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
480                        | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD;
481            }
482            if (webPasswordInputType) {
483                mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
484                        | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD;
485            }
486        } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) {
487            if (numberPasswordInputType) {
488                mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
489                        | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD;
490            }
491        }
492    }
493
494    private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) {
495        int wid = tv.getPaddingLeft() + tv.getPaddingRight();
496        int ht = tv.getPaddingTop() + tv.getPaddingBottom();
497
498        int defaultWidthInPixels = mTextView.getResources().getDimensionPixelSize(
499                com.android.internal.R.dimen.textview_error_popup_default_width);
500        Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels,
501                                    Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
502        float max = 0;
503        for (int i = 0; i < l.getLineCount(); i++) {
504            max = Math.max(max, l.getLineWidth(i));
505        }
506
507        /*
508         * Now set the popup size to be big enough for the text plus the border capped
509         * to DEFAULT_MAX_POPUP_WIDTH
510         */
511        pop.setWidth(wid + (int) Math.ceil(max));
512        pop.setHeight(ht + l.getHeight());
513    }
514
515    void setFrame() {
516        if (mErrorPopup != null) {
517            TextView tv = (TextView) mErrorPopup.getContentView();
518            chooseSize(mErrorPopup, mError, tv);
519            mErrorPopup.update(mTextView, getErrorX(), getErrorY(),
520                    mErrorPopup.getWidth(), mErrorPopup.getHeight());
521        }
522    }
523
524    /**
525     * Unlike {@link TextView#textCanBeSelected()}, this method is based on the <i>current</i> state
526     * of the TextView. textCanBeSelected() has to be true (this is one of the conditions to have
527     * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient.
528     */
529    private boolean canSelectText() {
530        return hasSelectionController() && mTextView.getText().length() != 0;
531    }
532
533    /**
534     * It would be better to rely on the input type for everything. A password inputType should have
535     * a password transformation. We should hence use isPasswordInputType instead of this method.
536     *
537     * We should:
538     * - Call setInputType in setKeyListener instead of changing the input type directly (which
539     * would install the correct transformation).
540     * - Refuse the installation of a non-password transformation in setTransformation if the input
541     * type is password.
542     *
543     * However, this is like this for legacy reasons and we cannot break existing apps. This method
544     * is useful since it matches what the user can see (obfuscated text or not).
545     *
546     * @return true if the current transformation method is of the password type.
547     */
548    private boolean hasPasswordTransformationMethod() {
549        return mTextView.getTransformationMethod() instanceof PasswordTransformationMethod;
550    }
551
552    /**
553     * Adjusts selection to the word under last touch offset.
554     * Return true if the operation was successfully performed.
555     */
556    private boolean selectCurrentWord() {
557        if (!canSelectText()) {
558            return false;
559        }
560
561        if (hasPasswordTransformationMethod()) {
562            // Always select all on a password field.
563            // Cut/copy menu entries are not available for passwords, but being able to select all
564            // is however useful to delete or paste to replace the entire content.
565            return mTextView.selectAllText();
566        }
567
568        int inputType = mTextView.getInputType();
569        int klass = inputType & InputType.TYPE_MASK_CLASS;
570        int variation = inputType & InputType.TYPE_MASK_VARIATION;
571
572        // Specific text field types: select the entire text for these
573        if (klass == InputType.TYPE_CLASS_NUMBER ||
574                klass == InputType.TYPE_CLASS_PHONE ||
575                klass == InputType.TYPE_CLASS_DATETIME ||
576                variation == InputType.TYPE_TEXT_VARIATION_URI ||
577                variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
578                variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ||
579                variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
580            return mTextView.selectAllText();
581        }
582
583        long lastTouchOffsets = getLastTouchOffsets();
584        final int minOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets);
585        final int maxOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets);
586
587        // Safety check in case standard touch event handling has been bypassed
588        if (minOffset < 0 || minOffset >= mTextView.getText().length()) return false;
589        if (maxOffset < 0 || maxOffset >= mTextView.getText().length()) return false;
590
591        int selectionStart, selectionEnd;
592
593        // If a URLSpan (web address, email, phone...) is found at that position, select it.
594        URLSpan[] urlSpans = ((Spanned) mTextView.getText()).
595                getSpans(minOffset, maxOffset, URLSpan.class);
596        if (urlSpans.length >= 1) {
597            URLSpan urlSpan = urlSpans[0];
598            selectionStart = ((Spanned) mTextView.getText()).getSpanStart(urlSpan);
599            selectionEnd = ((Spanned) mTextView.getText()).getSpanEnd(urlSpan);
600        } else {
601            final WordIterator wordIterator = getWordIterator();
602            wordIterator.setCharSequence(mTextView.getText(), minOffset, maxOffset);
603
604            selectionStart = wordIterator.getBeginning(minOffset);
605            selectionEnd = wordIterator.getEnd(maxOffset);
606
607            if (selectionStart == BreakIterator.DONE || selectionEnd == BreakIterator.DONE ||
608                    selectionStart == selectionEnd) {
609                // Possible when the word iterator does not properly handle the text's language
610                long range = getCharRange(minOffset);
611                selectionStart = TextUtils.unpackRangeStartFromLong(range);
612                selectionEnd = TextUtils.unpackRangeEndFromLong(range);
613            }
614        }
615
616        Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
617        return selectionEnd > selectionStart;
618    }
619
620    void onLocaleChanged() {
621        // Will be re-created on demand in getWordIterator with the proper new locale
622        mWordIterator = null;
623    }
624
625    /**
626     * @hide
627     */
628    public WordIterator getWordIterator() {
629        if (mWordIterator == null) {
630            mWordIterator = new WordIterator(mTextView.getTextServicesLocale());
631        }
632        return mWordIterator;
633    }
634
635    private long getCharRange(int offset) {
636        final int textLength = mTextView.getText().length();
637        if (offset + 1 < textLength) {
638            final char currentChar = mTextView.getText().charAt(offset);
639            final char nextChar = mTextView.getText().charAt(offset + 1);
640            if (Character.isSurrogatePair(currentChar, nextChar)) {
641                return TextUtils.packRangeInLong(offset,  offset + 2);
642            }
643        }
644        if (offset < textLength) {
645            return TextUtils.packRangeInLong(offset,  offset + 1);
646        }
647        if (offset - 2 >= 0) {
648            final char previousChar = mTextView.getText().charAt(offset - 1);
649            final char previousPreviousChar = mTextView.getText().charAt(offset - 2);
650            if (Character.isSurrogatePair(previousPreviousChar, previousChar)) {
651                return TextUtils.packRangeInLong(offset - 2,  offset);
652            }
653        }
654        if (offset - 1 >= 0) {
655            return TextUtils.packRangeInLong(offset - 1,  offset);
656        }
657        return TextUtils.packRangeInLong(offset,  offset);
658    }
659
660    private boolean touchPositionIsInSelection() {
661        int selectionStart = mTextView.getSelectionStart();
662        int selectionEnd = mTextView.getSelectionEnd();
663
664        if (selectionStart == selectionEnd) {
665            return false;
666        }
667
668        if (selectionStart > selectionEnd) {
669            int tmp = selectionStart;
670            selectionStart = selectionEnd;
671            selectionEnd = tmp;
672            Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
673        }
674
675        SelectionModifierCursorController selectionController = getSelectionController();
676        int minOffset = selectionController.getMinTouchOffset();
677        int maxOffset = selectionController.getMaxTouchOffset();
678
679        return ((minOffset >= selectionStart) && (maxOffset < selectionEnd));
680    }
681
682    private PositionListener getPositionListener() {
683        if (mPositionListener == null) {
684            mPositionListener = new PositionListener();
685        }
686        return mPositionListener;
687    }
688
689    private interface TextViewPositionListener {
690        public void updatePosition(int parentPositionX, int parentPositionY,
691                boolean parentPositionChanged, boolean parentScrolled);
692    }
693
694    private boolean isPositionVisible(int positionX, int positionY) {
695        synchronized (TEMP_POSITION) {
696            final float[] position = TEMP_POSITION;
697            position[0] = positionX;
698            position[1] = positionY;
699            View view = mTextView;
700
701            while (view != null) {
702                if (view != mTextView) {
703                    // Local scroll is already taken into account in positionX/Y
704                    position[0] -= view.getScrollX();
705                    position[1] -= view.getScrollY();
706                }
707
708                if (position[0] < 0 || position[1] < 0 ||
709                        position[0] > view.getWidth() || position[1] > view.getHeight()) {
710                    return false;
711                }
712
713                if (!view.getMatrix().isIdentity()) {
714                    view.getMatrix().mapPoints(position);
715                }
716
717                position[0] += view.getLeft();
718                position[1] += view.getTop();
719
720                final ViewParent parent = view.getParent();
721                if (parent instanceof View) {
722                    view = (View) parent;
723                } else {
724                    // We've reached the ViewRoot, stop iterating
725                    view = null;
726                }
727            }
728        }
729
730        // We've been able to walk up the view hierarchy and the position was never clipped
731        return true;
732    }
733
734    private boolean isOffsetVisible(int offset) {
735        Layout layout = mTextView.getLayout();
736        final int line = layout.getLineForOffset(offset);
737        final int lineBottom = layout.getLineBottom(line);
738        final int primaryHorizontal = (int) layout.getPrimaryHorizontal(offset);
739        return isPositionVisible(primaryHorizontal + mTextView.viewportToContentHorizontalOffset(),
740                lineBottom + mTextView.viewportToContentVerticalOffset());
741    }
742
743    /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed
744     * in the view. Returns false when the position is in the empty space of left/right of text.
745     */
746    private boolean isPositionOnText(float x, float y) {
747        Layout layout = mTextView.getLayout();
748        if (layout == null) return false;
749
750        final int line = mTextView.getLineAtCoordinate(y);
751        x = mTextView.convertToLocalHorizontalCoordinate(x);
752
753        if (x < layout.getLineLeft(line)) return false;
754        if (x > layout.getLineRight(line)) return false;
755        return true;
756    }
757
758    public boolean performLongClick(boolean handled) {
759        // Long press in empty space moves cursor and shows the Paste affordance if available.
760        if (!handled && !isPositionOnText(mLastDownPositionX, mLastDownPositionY) &&
761                mInsertionControllerEnabled) {
762            final int offset = mTextView.getOffsetForPosition(mLastDownPositionX,
763                    mLastDownPositionY);
764            stopSelectionActionMode();
765            Selection.setSelection((Spannable) mTextView.getText(), offset);
766            getInsertionController().showWithActionPopup();
767            handled = true;
768        }
769
770        if (!handled && mSelectionActionMode != null) {
771            if (touchPositionIsInSelection()) {
772                // Start a drag
773                final int start = mTextView.getSelectionStart();
774                final int end = mTextView.getSelectionEnd();
775                CharSequence selectedText = mTextView.getTransformedText(start, end);
776                ClipData data = ClipData.newPlainText(null, selectedText);
777                DragLocalState localState = new DragLocalState(mTextView, start, end);
778                mTextView.startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0);
779                stopSelectionActionMode();
780            } else {
781                getSelectionController().hide();
782                selectCurrentWord();
783                getSelectionController().show();
784            }
785            handled = true;
786        }
787
788        // Start a new selection
789        if (!handled) {
790            handled = startSelectionActionMode();
791        }
792
793        return handled;
794    }
795
796    private long getLastTouchOffsets() {
797        SelectionModifierCursorController selectionController = getSelectionController();
798        final int minOffset = selectionController.getMinTouchOffset();
799        final int maxOffset = selectionController.getMaxTouchOffset();
800        return TextUtils.packRangeInLong(minOffset, maxOffset);
801    }
802
803    void onFocusChanged(boolean focused, int direction) {
804        mShowCursor = SystemClock.uptimeMillis();
805        ensureEndedBatchEdit();
806
807        if (focused) {
808            int selStart = mTextView.getSelectionStart();
809            int selEnd = mTextView.getSelectionEnd();
810
811            // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection
812            // mode for these, unless there was a specific selection already started.
813            final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 &&
814                    selEnd == mTextView.getText().length();
815
816            mCreatedWithASelection = mFrozenWithFocus && mTextView.hasSelection() &&
817                    !isFocusHighlighted;
818
819            if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
820                // If a tap was used to give focus to that view, move cursor at tap position.
821                // Has to be done before onTakeFocus, which can be overloaded.
822                final int lastTapPosition = getLastTapPosition();
823                if (lastTapPosition >= 0) {
824                    Selection.setSelection((Spannable) mTextView.getText(), lastTapPosition);
825                }
826
827                // Note this may have to be moved out of the Editor class
828                MovementMethod mMovement = mTextView.getMovementMethod();
829                if (mMovement != null) {
830                    mMovement.onTakeFocus(mTextView, (Spannable) mTextView.getText(), direction);
831                }
832
833                // The DecorView does not have focus when the 'Done' ExtractEditText button is
834                // pressed. Since it is the ViewAncestor's mView, it requests focus before
835                // ExtractEditText clears focus, which gives focus to the ExtractEditText.
836                // This special case ensure that we keep current selection in that case.
837                // It would be better to know why the DecorView does not have focus at that time.
838                if (((mTextView instanceof ExtractEditText) || mSelectionMoved) &&
839                        selStart >= 0 && selEnd >= 0) {
840                    /*
841                     * Someone intentionally set the selection, so let them
842                     * do whatever it is that they wanted to do instead of
843                     * the default on-focus behavior.  We reset the selection
844                     * here instead of just skipping the onTakeFocus() call
845                     * because some movement methods do something other than
846                     * just setting the selection in theirs and we still
847                     * need to go through that path.
848                     */
849                    Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd);
850                }
851
852                if (mSelectAllOnFocus) {
853                    mTextView.selectAllText();
854                }
855
856                mTouchFocusSelected = true;
857            }
858
859            mFrozenWithFocus = false;
860            mSelectionMoved = false;
861
862            if (mError != null) {
863                showError();
864            }
865
866            makeBlink();
867        } else {
868            if (mError != null) {
869                hideError();
870            }
871            // Don't leave us in the middle of a batch edit.
872            mTextView.onEndBatchEdit();
873
874            if (mTextView instanceof ExtractEditText) {
875                // terminateTextSelectionMode removes selection, which we want to keep when
876                // ExtractEditText goes out of focus.
877                final int selStart = mTextView.getSelectionStart();
878                final int selEnd = mTextView.getSelectionEnd();
879                hideControllers();
880                Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd);
881            } else {
882                hideControllers();
883                downgradeEasyCorrectionSpans();
884            }
885
886            // No need to create the controller
887            if (mSelectionModifierCursorController != null) {
888                mSelectionModifierCursorController.resetTouchOffsets();
889            }
890        }
891    }
892
893    /**
894     * Downgrades to simple suggestions all the easy correction spans that are not a spell check
895     * span.
896     */
897    private void downgradeEasyCorrectionSpans() {
898        CharSequence text = mTextView.getText();
899        if (text instanceof Spannable) {
900            Spannable spannable = (Spannable) text;
901            SuggestionSpan[] suggestionSpans = spannable.getSpans(0,
902                    spannable.length(), SuggestionSpan.class);
903            for (int i = 0; i < suggestionSpans.length; i++) {
904                int flags = suggestionSpans[i].getFlags();
905                if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0
906                        && (flags & SuggestionSpan.FLAG_MISSPELLED) == 0) {
907                    flags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
908                    suggestionSpans[i].setFlags(flags);
909                }
910            }
911        }
912    }
913
914    void sendOnTextChanged(int start, int after) {
915        updateSpellCheckSpans(start, start + after, false);
916
917        // Hide the controllers as soon as text is modified (typing, procedural...)
918        // We do not hide the span controllers, since they can be added when a new text is
919        // inserted into the text view (voice IME).
920        hideCursorControllers();
921    }
922
923    private int getLastTapPosition() {
924        // No need to create the controller at that point, no last tap position saved
925        if (mSelectionModifierCursorController != null) {
926            int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset();
927            if (lastTapPosition >= 0) {
928                // Safety check, should not be possible.
929                if (lastTapPosition > mTextView.getText().length()) {
930                    lastTapPosition = mTextView.getText().length();
931                }
932                return lastTapPosition;
933            }
934        }
935
936        return -1;
937    }
938
939    void onWindowFocusChanged(boolean hasWindowFocus) {
940        if (hasWindowFocus) {
941            if (mBlink != null) {
942                mBlink.uncancel();
943                makeBlink();
944            }
945        } else {
946            if (mBlink != null) {
947                mBlink.cancel();
948            }
949            if (mInputContentType != null) {
950                mInputContentType.enterDown = false;
951            }
952            // Order matters! Must be done before onParentLostFocus to rely on isShowingUp
953            hideControllers();
954            if (mSuggestionsPopupWindow != null) {
955                mSuggestionsPopupWindow.onParentLostFocus();
956            }
957
958            // Don't leave us in the middle of a batch edit.
959            mTextView.onEndBatchEdit();
960        }
961    }
962
963    void onTouchEvent(MotionEvent event) {
964        if (hasSelectionController()) {
965            getSelectionController().onTouchEvent(event);
966        }
967
968        if (mShowSuggestionRunnable != null) {
969            mTextView.removeCallbacks(mShowSuggestionRunnable);
970            mShowSuggestionRunnable = null;
971        }
972
973        if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
974            mLastDownPositionX = event.getX();
975            mLastDownPositionY = event.getY();
976
977            // Reset this state; it will be re-set if super.onTouchEvent
978            // causes focus to move to the view.
979            mTouchFocusSelected = false;
980            mIgnoreActionUpEvent = false;
981        }
982    }
983
984    public void beginBatchEdit() {
985        mInBatchEditControllers = true;
986        final InputMethodState ims = mInputMethodState;
987        if (ims != null) {
988            int nesting = ++ims.mBatchEditNesting;
989            if (nesting == 1) {
990                ims.mCursorChanged = false;
991                ims.mChangedDelta = 0;
992                if (ims.mContentChanged) {
993                    // We already have a pending change from somewhere else,
994                    // so turn this into a full update.
995                    ims.mChangedStart = 0;
996                    ims.mChangedEnd = mTextView.getText().length();
997                } else {
998                    ims.mChangedStart = EXTRACT_UNKNOWN;
999                    ims.mChangedEnd = EXTRACT_UNKNOWN;
1000                    ims.mContentChanged = false;
1001                }
1002                mTextView.onBeginBatchEdit();
1003            }
1004        }
1005    }
1006
1007    public void endBatchEdit() {
1008        mInBatchEditControllers = false;
1009        final InputMethodState ims = mInputMethodState;
1010        if (ims != null) {
1011            int nesting = --ims.mBatchEditNesting;
1012            if (nesting == 0) {
1013                finishBatchEdit(ims);
1014            }
1015        }
1016    }
1017
1018    void ensureEndedBatchEdit() {
1019        final InputMethodState ims = mInputMethodState;
1020        if (ims != null && ims.mBatchEditNesting != 0) {
1021            ims.mBatchEditNesting = 0;
1022            finishBatchEdit(ims);
1023        }
1024    }
1025
1026    void finishBatchEdit(final InputMethodState ims) {
1027        mTextView.onEndBatchEdit();
1028
1029        if (ims.mContentChanged || ims.mSelectionModeChanged) {
1030            mTextView.updateAfterEdit();
1031            reportExtractedText();
1032        } else if (ims.mCursorChanged) {
1033            // Cheezy way to get us to report the current cursor location.
1034            mTextView.invalidateCursor();
1035        }
1036    }
1037
1038    static final int EXTRACT_NOTHING = -2;
1039    static final int EXTRACT_UNKNOWN = -1;
1040
1041    boolean extractText(ExtractedTextRequest request, ExtractedText outText) {
1042        return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN,
1043                EXTRACT_UNKNOWN, outText);
1044    }
1045
1046    private boolean extractTextInternal(ExtractedTextRequest request,
1047            int partialStartOffset, int partialEndOffset, int delta,
1048            ExtractedText outText) {
1049        final CharSequence content = mTextView.getText();
1050        if (content != null) {
1051            if (partialStartOffset != EXTRACT_NOTHING) {
1052                final int N = content.length();
1053                if (partialStartOffset < 0) {
1054                    outText.partialStartOffset = outText.partialEndOffset = -1;
1055                    partialStartOffset = 0;
1056                    partialEndOffset = N;
1057                } else {
1058                    // Now use the delta to determine the actual amount of text
1059                    // we need.
1060                    partialEndOffset += delta;
1061                    // Adjust offsets to ensure we contain full spans.
1062                    if (content instanceof Spanned) {
1063                        Spanned spanned = (Spanned)content;
1064                        Object[] spans = spanned.getSpans(partialStartOffset,
1065                                partialEndOffset, ParcelableSpan.class);
1066                        int i = spans.length;
1067                        while (i > 0) {
1068                            i--;
1069                            int j = spanned.getSpanStart(spans[i]);
1070                            if (j < partialStartOffset) partialStartOffset = j;
1071                            j = spanned.getSpanEnd(spans[i]);
1072                            if (j > partialEndOffset) partialEndOffset = j;
1073                        }
1074                    }
1075                    outText.partialStartOffset = partialStartOffset;
1076                    outText.partialEndOffset = partialEndOffset - delta;
1077
1078                    if (partialStartOffset > N) {
1079                        partialStartOffset = N;
1080                    } else if (partialStartOffset < 0) {
1081                        partialStartOffset = 0;
1082                    }
1083                    if (partialEndOffset > N) {
1084                        partialEndOffset = N;
1085                    } else if (partialEndOffset < 0) {
1086                        partialEndOffset = 0;
1087                    }
1088                }
1089                if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) {
1090                    outText.text = content.subSequence(partialStartOffset,
1091                            partialEndOffset);
1092                } else {
1093                    outText.text = TextUtils.substring(content, partialStartOffset,
1094                            partialEndOffset);
1095                }
1096            } else {
1097                outText.partialStartOffset = 0;
1098                outText.partialEndOffset = 0;
1099                outText.text = "";
1100            }
1101            outText.flags = 0;
1102            if (MetaKeyKeyListener.getMetaState(content, MetaKeyKeyListener.META_SELECTING) != 0) {
1103                outText.flags |= ExtractedText.FLAG_SELECTING;
1104            }
1105            if (mTextView.isSingleLine()) {
1106                outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
1107            }
1108            outText.startOffset = 0;
1109            outText.selectionStart = mTextView.getSelectionStart();
1110            outText.selectionEnd = mTextView.getSelectionEnd();
1111            return true;
1112        }
1113        return false;
1114    }
1115
1116    boolean reportExtractedText() {
1117        final Editor.InputMethodState ims = mInputMethodState;
1118        if (ims != null) {
1119            final boolean contentChanged = ims.mContentChanged;
1120            if (contentChanged || ims.mSelectionModeChanged) {
1121                ims.mContentChanged = false;
1122                ims.mSelectionModeChanged = false;
1123                final ExtractedTextRequest req = ims.mExtracting;
1124                if (req != null) {
1125                    InputMethodManager imm = InputMethodManager.peekInstance();
1126                    if (imm != null) {
1127                        if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG,
1128                                "Retrieving extracted start=" + ims.mChangedStart +
1129                                " end=" + ims.mChangedEnd +
1130                                " delta=" + ims.mChangedDelta);
1131                        if (ims.mChangedStart < 0 && !contentChanged) {
1132                            ims.mChangedStart = EXTRACT_NOTHING;
1133                        }
1134                        if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd,
1135                                ims.mChangedDelta, ims.mTmpExtracted)) {
1136                            if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG,
1137                                    "Reporting extracted start=" +
1138                                    ims.mTmpExtracted.partialStartOffset +
1139                                    " end=" + ims.mTmpExtracted.partialEndOffset +
1140                                    ": " + ims.mTmpExtracted.text);
1141                            imm.updateExtractedText(mTextView, req.token, ims.mTmpExtracted);
1142                            ims.mChangedStart = EXTRACT_UNKNOWN;
1143                            ims.mChangedEnd = EXTRACT_UNKNOWN;
1144                            ims.mChangedDelta = 0;
1145                            ims.mContentChanged = false;
1146                            return true;
1147                        }
1148                    }
1149                }
1150            }
1151        }
1152        return false;
1153    }
1154
1155    void onDraw(Canvas canvas, Layout layout, Path highlight, Paint highlightPaint,
1156            int cursorOffsetVertical) {
1157        final int selectionStart = mTextView.getSelectionStart();
1158        final int selectionEnd = mTextView.getSelectionEnd();
1159
1160        final InputMethodState ims = mInputMethodState;
1161        if (ims != null && ims.mBatchEditNesting == 0) {
1162            InputMethodManager imm = InputMethodManager.peekInstance();
1163            if (imm != null) {
1164                if (imm.isActive(mTextView)) {
1165                    boolean reported = false;
1166                    if (ims.mContentChanged || ims.mSelectionModeChanged) {
1167                        // We are in extract mode and the content has changed
1168                        // in some way... just report complete new text to the
1169                        // input method.
1170                        reported = reportExtractedText();
1171                    }
1172                    if (!reported && highlight != null) {
1173                        int candStart = -1;
1174                        int candEnd = -1;
1175                        if (mTextView.getText() instanceof Spannable) {
1176                            Spannable sp = (Spannable) mTextView.getText();
1177                            candStart = EditableInputConnection.getComposingSpanStart(sp);
1178                            candEnd = EditableInputConnection.getComposingSpanEnd(sp);
1179                        }
1180                        imm.updateSelection(mTextView,
1181                                selectionStart, selectionEnd, candStart, candEnd);
1182                    }
1183                }
1184
1185                if (imm.isWatchingCursor(mTextView) && highlight != null) {
1186                    highlight.computeBounds(ims.mTmpRectF, true);
1187                    ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0;
1188
1189                    canvas.getMatrix().mapPoints(ims.mTmpOffset);
1190                    ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]);
1191
1192                    ims.mTmpRectF.offset(0, cursorOffsetVertical);
1193
1194                    ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5),
1195                            (int)(ims.mTmpRectF.top + 0.5),
1196                            (int)(ims.mTmpRectF.right + 0.5),
1197                            (int)(ims.mTmpRectF.bottom + 0.5));
1198
1199                    imm.updateCursor(mTextView,
1200                            ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top,
1201                            ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom);
1202                }
1203            }
1204        }
1205
1206        if (mCorrectionHighlighter != null) {
1207            mCorrectionHighlighter.draw(canvas, cursorOffsetVertical);
1208        }
1209
1210        if (highlight != null && selectionStart == selectionEnd && mCursorCount > 0) {
1211            drawCursor(canvas, cursorOffsetVertical);
1212            // Rely on the drawable entirely, do not draw the cursor line.
1213            // Has to be done after the IMM related code above which relies on the highlight.
1214            highlight = null;
1215        }
1216
1217        if (mTextView.canHaveDisplayList() && canvas.isHardwareAccelerated()) {
1218            drawHardwareAccelerated(canvas, layout, highlight, highlightPaint,
1219                    cursorOffsetVertical);
1220        } else {
1221            layout.draw(canvas, highlight, highlightPaint, cursorOffsetVertical);
1222        }
1223    }
1224
1225    private void drawHardwareAccelerated(Canvas canvas, Layout layout, Path highlight,
1226            Paint highlightPaint, int cursorOffsetVertical) {
1227        final int width = mTextView.getWidth();
1228
1229        final long lineRange = layout.getLineRangeForDraw(canvas);
1230        int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
1231        int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
1232        if (lastLine < 0) return;
1233
1234        layout.drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
1235                firstLine, lastLine);
1236
1237        if (layout instanceof DynamicLayout) {
1238            if (mTextDisplayLists == null) {
1239                mTextDisplayLists = new DisplayList[ArrayUtils.idealObjectArraySize(0)];
1240            }
1241
1242            DynamicLayout dynamicLayout = (DynamicLayout) layout;
1243            int[] blockEndLines = dynamicLayout.getBlockEndLines();
1244            int[] blockIndices = dynamicLayout.getBlockIndices();
1245            final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
1246
1247            final int scrollX = mTextView.getScrollX();
1248            final int scrollY = mTextView.getScrollY();
1249            canvas.translate(scrollX, scrollY);
1250
1251            int endOfPreviousBlock = -1;
1252            int searchStartIndex = 0;
1253            for (int i = 0; i < numberOfBlocks; i++) {
1254                int blockEndLine = blockEndLines[i];
1255                int blockIndex = blockIndices[i];
1256
1257                final boolean blockIsInvalid = blockIndex == DynamicLayout.INVALID_BLOCK_INDEX;
1258                if (blockIsInvalid) {
1259                    blockIndex = getAvailableDisplayListIndex(blockIndices, numberOfBlocks,
1260                            searchStartIndex);
1261                    // Note how dynamic layout's internal block indices get updated from Editor
1262                    blockIndices[i] = blockIndex;
1263                    searchStartIndex = blockIndex + 1;
1264                }
1265
1266                DisplayList blockDisplayList = mTextDisplayLists[blockIndex];
1267                if (blockDisplayList == null) {
1268                    blockDisplayList = mTextDisplayLists[blockIndex] =
1269                            mTextView.getHardwareRenderer().createDisplayList("Text " + blockIndex);
1270                } else {
1271                    if (blockIsInvalid) blockDisplayList.invalidate();
1272                }
1273
1274                if (!blockDisplayList.isValid()) {
1275                    final int blockBeginLine = endOfPreviousBlock + 1;
1276                    final int top = layout.getLineTop(blockBeginLine);
1277                    final int bottom = layout.getLineBottom(blockEndLine);
1278
1279                    final HardwareCanvas hardwareCanvas = blockDisplayList.start();
1280                    try {
1281                        hardwareCanvas.setViewport(width, bottom - top);
1282                        // The dirty rect should always be null for a display list
1283                        hardwareCanvas.onPreDraw(null);
1284                        // drawText is always relative to TextView's origin, this translation brings
1285                        // this range of text back to the top of the viewport
1286                        hardwareCanvas.translate(-scrollX, -top);
1287                        layout.drawText(hardwareCanvas, blockBeginLine, blockEndLine);
1288                        hardwareCanvas.translate(scrollX, top);
1289                    } finally {
1290                        hardwareCanvas.onPostDraw();
1291                        blockDisplayList.end();
1292                        blockDisplayList.setLeftTopRightBottom(0, top, width, bottom);
1293                        // Same as drawDisplayList below, handled by our TextView's parent
1294                        blockDisplayList.setClipChildren(false);
1295                    }
1296                }
1297
1298                // TODO When View.USE_DISPLAY_LIST_PROPERTIES is the only code path, the
1299                // width and height parameters should be removed and the bounds set above in
1300                // setLeftTopRightBottom should be used instead for quick rejection.
1301                ((HardwareCanvas) canvas).drawDisplayList(blockDisplayList, null,
1302                        0 /* no child clipping, our TextView parent enforces it */);
1303                endOfPreviousBlock = blockEndLine;
1304
1305                canvas.translate(-scrollX, -scrollY);
1306            }
1307        } else {
1308            // Boring layout is used for empty and hint text
1309            layout.drawText(canvas, firstLine, lastLine);
1310        }
1311    }
1312
1313    private int getAvailableDisplayListIndex(int[] blockIndices, int numberOfBlocks,
1314            int searchStartIndex) {
1315        int length = mTextDisplayLists.length;
1316        for (int i = searchStartIndex; i < length; i++) {
1317            boolean blockIndexFound = false;
1318            for (int j = 0; j < numberOfBlocks; j++) {
1319                if (blockIndices[j] == i) {
1320                    blockIndexFound = true;
1321                    break;
1322                }
1323            }
1324            if (blockIndexFound) continue;
1325            return i;
1326        }
1327
1328        // No available index found, the pool has to grow
1329        int newSize = ArrayUtils.idealIntArraySize(length + 1);
1330        DisplayList[] displayLists = new DisplayList[newSize];
1331        System.arraycopy(mTextDisplayLists, 0, displayLists, 0, length);
1332        mTextDisplayLists = displayLists;
1333        return length;
1334    }
1335
1336    private void drawCursor(Canvas canvas, int cursorOffsetVertical) {
1337        final boolean translate = cursorOffsetVertical != 0;
1338        if (translate) canvas.translate(0, cursorOffsetVertical);
1339        for (int i = 0; i < mCursorCount; i++) {
1340            mCursorDrawable[i].draw(canvas);
1341        }
1342        if (translate) canvas.translate(0, -cursorOffsetVertical);
1343    }
1344
1345    /**
1346     * Invalidates all the sub-display lists that overlap the specified character range
1347     */
1348    void invalidateTextDisplayList(Layout layout, int start, int end) {
1349        if (mTextDisplayLists != null && layout instanceof DynamicLayout) {
1350            final int firstLine = layout.getLineForOffset(start);
1351            final int lastLine = layout.getLineForOffset(end);
1352
1353            DynamicLayout dynamicLayout = (DynamicLayout) layout;
1354            int[] blockEndLines = dynamicLayout.getBlockEndLines();
1355            int[] blockIndices = dynamicLayout.getBlockIndices();
1356            final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
1357
1358            int i = 0;
1359            // Skip the blocks before firstLine
1360            while (i < numberOfBlocks) {
1361                if (blockEndLines[i] >= firstLine) break;
1362                i++;
1363            }
1364
1365            // Invalidate all subsequent blocks until lastLine is passed
1366            while (i < numberOfBlocks) {
1367                final int blockIndex = blockIndices[i];
1368                if (blockIndex != DynamicLayout.INVALID_BLOCK_INDEX) {
1369                    mTextDisplayLists[blockIndex].invalidate();
1370                }
1371                if (blockEndLines[i] >= lastLine) break;
1372                i++;
1373            }
1374        }
1375    }
1376
1377    void invalidateTextDisplayList() {
1378        if (mTextDisplayLists != null) {
1379            for (int i = 0; i < mTextDisplayLists.length; i++) {
1380                if (mTextDisplayLists[i] != null) mTextDisplayLists[i].invalidate();
1381            }
1382        }
1383    }
1384
1385    void updateCursorsPositions() {
1386        if (mTextView.mCursorDrawableRes == 0) {
1387            mCursorCount = 0;
1388            return;
1389        }
1390
1391        Layout layout = mTextView.getLayout();
1392        final int offset = mTextView.getSelectionStart();
1393        final int line = layout.getLineForOffset(offset);
1394        final int top = layout.getLineTop(line);
1395        final int bottom = layout.getLineTop(line + 1);
1396
1397        mCursorCount = layout.isLevelBoundary(offset) ? 2 : 1;
1398
1399        int middle = bottom;
1400        if (mCursorCount == 2) {
1401            // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)}
1402            middle = (top + bottom) >> 1;
1403        }
1404
1405        updateCursorPosition(0, top, middle, layout.getPrimaryHorizontal(offset));
1406
1407        if (mCursorCount == 2) {
1408            updateCursorPosition(1, middle, bottom, layout.getSecondaryHorizontal(offset));
1409        }
1410    }
1411
1412    /**
1413     * @return true if the selection mode was actually started.
1414     */
1415    boolean startSelectionActionMode() {
1416        if (mSelectionActionMode != null) {
1417            // Selection action mode is already started
1418            return false;
1419        }
1420
1421        if (!canSelectText() || !mTextView.requestFocus()) {
1422            Log.w(TextView.LOG_TAG,
1423                    "TextView does not support text selection. Action mode cancelled.");
1424            return false;
1425        }
1426
1427        if (!mTextView.hasSelection()) {
1428            // There may already be a selection on device rotation
1429            if (!selectCurrentWord()) {
1430                // No word found under cursor or text selection not permitted.
1431                return false;
1432            }
1433        }
1434
1435        boolean willExtract = extractedTextModeWillBeStarted();
1436
1437        // Do not start the action mode when extracted text will show up full screen, which would
1438        // immediately hide the newly created action bar and would be visually distracting.
1439        if (!willExtract) {
1440            ActionMode.Callback actionModeCallback = new SelectionActionModeCallback();
1441            mSelectionActionMode = mTextView.startActionMode(actionModeCallback);
1442        }
1443
1444        final boolean selectionStarted = mSelectionActionMode != null || willExtract;
1445        if (selectionStarted && !mTextView.isTextSelectable()) {
1446            // Show the IME to be able to replace text, except when selecting non editable text.
1447            final InputMethodManager imm = InputMethodManager.peekInstance();
1448            if (imm != null) {
1449                imm.showSoftInput(mTextView, 0, null);
1450            }
1451        }
1452
1453        return selectionStarted;
1454    }
1455
1456    private boolean extractedTextModeWillBeStarted() {
1457        if (!(mTextView instanceof ExtractEditText)) {
1458            final InputMethodManager imm = InputMethodManager.peekInstance();
1459            return  imm != null && imm.isFullscreenMode();
1460        }
1461        return false;
1462    }
1463
1464    /**
1465     * @return <code>true</code> if the cursor/current selection overlaps a {@link SuggestionSpan}.
1466     */
1467    private boolean isCursorInsideSuggestionSpan() {
1468        CharSequence text = mTextView.getText();
1469        if (!(text instanceof Spannable)) return false;
1470
1471        SuggestionSpan[] suggestionSpans = ((Spannable) text).getSpans(
1472                mTextView.getSelectionStart(), mTextView.getSelectionEnd(), SuggestionSpan.class);
1473        return (suggestionSpans.length > 0);
1474    }
1475
1476    /**
1477     * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with
1478     * {@link SuggestionSpan#FLAG_EASY_CORRECT} set.
1479     */
1480    private boolean isCursorInsideEasyCorrectionSpan() {
1481        Spannable spannable = (Spannable) mTextView.getText();
1482        SuggestionSpan[] suggestionSpans = spannable.getSpans(mTextView.getSelectionStart(),
1483                mTextView.getSelectionEnd(), SuggestionSpan.class);
1484        for (int i = 0; i < suggestionSpans.length; i++) {
1485            if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) {
1486                return true;
1487            }
1488        }
1489        return false;
1490    }
1491
1492    void onTouchUpEvent(MotionEvent event) {
1493        boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect();
1494        hideControllers();
1495        CharSequence text = mTextView.getText();
1496        if (!selectAllGotFocus && text.length() > 0) {
1497            // Move cursor
1498            final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
1499            Selection.setSelection((Spannable) text, offset);
1500            if (mSpellChecker != null) {
1501                // When the cursor moves, the word that was typed may need spell check
1502                mSpellChecker.onSelectionChanged();
1503            }
1504            if (!extractedTextModeWillBeStarted()) {
1505                if (isCursorInsideEasyCorrectionSpan()) {
1506                    mShowSuggestionRunnable = new Runnable() {
1507                        public void run() {
1508                            showSuggestions();
1509                        }
1510                    };
1511                    // removeCallbacks is performed on every touch
1512                    mTextView.postDelayed(mShowSuggestionRunnable,
1513                            ViewConfiguration.getDoubleTapTimeout());
1514                } else if (hasInsertionController()) {
1515                    getInsertionController().show();
1516                }
1517            }
1518        }
1519    }
1520
1521    protected void stopSelectionActionMode() {
1522        if (mSelectionActionMode != null) {
1523            // This will hide the mSelectionModifierCursorController
1524            mSelectionActionMode.finish();
1525        }
1526    }
1527
1528    /**
1529     * @return True if this view supports insertion handles.
1530     */
1531    boolean hasInsertionController() {
1532        return mInsertionControllerEnabled;
1533    }
1534
1535    /**
1536     * @return True if this view supports selection handles.
1537     */
1538    boolean hasSelectionController() {
1539        return mSelectionControllerEnabled;
1540    }
1541
1542    InsertionPointCursorController getInsertionController() {
1543        if (!mInsertionControllerEnabled) {
1544            return null;
1545        }
1546
1547        if (mInsertionPointCursorController == null) {
1548            mInsertionPointCursorController = new InsertionPointCursorController();
1549
1550            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
1551            observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
1552        }
1553
1554        return mInsertionPointCursorController;
1555    }
1556
1557    SelectionModifierCursorController getSelectionController() {
1558        if (!mSelectionControllerEnabled) {
1559            return null;
1560        }
1561
1562        if (mSelectionModifierCursorController == null) {
1563            mSelectionModifierCursorController = new SelectionModifierCursorController();
1564
1565            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
1566            observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
1567        }
1568
1569        return mSelectionModifierCursorController;
1570    }
1571
1572    private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) {
1573        if (mCursorDrawable[cursorIndex] == null)
1574            mCursorDrawable[cursorIndex] = mTextView.getResources().getDrawable(
1575                    mTextView.mCursorDrawableRes);
1576
1577        if (mTempRect == null) mTempRect = new Rect();
1578        mCursorDrawable[cursorIndex].getPadding(mTempRect);
1579        final int width = mCursorDrawable[cursorIndex].getIntrinsicWidth();
1580        horizontal = Math.max(0.5f, horizontal - 0.5f);
1581        final int left = (int) (horizontal) - mTempRect.left;
1582        mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width,
1583                bottom + mTempRect.bottom);
1584    }
1585
1586    /**
1587     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
1588     * a dictionnary) from the current input method, provided by it calling
1589     * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
1590     * implementation flashes the background of the corrected word to provide feedback to the user.
1591     *
1592     * @param info The auto correct info about the text that was corrected.
1593     */
1594    public void onCommitCorrection(CorrectionInfo info) {
1595        if (mCorrectionHighlighter == null) {
1596            mCorrectionHighlighter = new CorrectionHighlighter();
1597        } else {
1598            mCorrectionHighlighter.invalidate(false);
1599        }
1600
1601        mCorrectionHighlighter.highlight(info);
1602    }
1603
1604    void showSuggestions() {
1605        if (mSuggestionsPopupWindow == null) {
1606            mSuggestionsPopupWindow = new SuggestionsPopupWindow();
1607        }
1608        hideControllers();
1609        mSuggestionsPopupWindow.show();
1610    }
1611
1612    boolean areSuggestionsShown() {
1613        return mSuggestionsPopupWindow != null && mSuggestionsPopupWindow.isShowing();
1614    }
1615
1616    void onScrollChanged() {
1617        if (mPositionListener != null) {
1618            mPositionListener.onScrollChanged();
1619        }
1620    }
1621
1622    /**
1623     * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
1624     */
1625    private boolean shouldBlink() {
1626        if (!isCursorVisible() || !mTextView.isFocused()) return false;
1627
1628        final int start = mTextView.getSelectionStart();
1629        if (start < 0) return false;
1630
1631        final int end = mTextView.getSelectionEnd();
1632        if (end < 0) return false;
1633
1634        return start == end;
1635    }
1636
1637    void makeBlink() {
1638        if (shouldBlink()) {
1639            mShowCursor = SystemClock.uptimeMillis();
1640            if (mBlink == null) mBlink = new Blink();
1641            mBlink.removeCallbacks(mBlink);
1642            mBlink.postAtTime(mBlink, mShowCursor + BLINK);
1643        } else {
1644            if (mBlink != null) mBlink.removeCallbacks(mBlink);
1645        }
1646    }
1647
1648    private class Blink extends Handler implements Runnable {
1649        private boolean mCancelled;
1650
1651        public void run() {
1652            if (mCancelled) {
1653                return;
1654            }
1655
1656            removeCallbacks(Blink.this);
1657
1658            if (shouldBlink()) {
1659                if (mTextView.getLayout() != null) {
1660                    mTextView.invalidateCursorPath();
1661                }
1662
1663                postAtTime(this, SystemClock.uptimeMillis() + BLINK);
1664            }
1665        }
1666
1667        void cancel() {
1668            if (!mCancelled) {
1669                removeCallbacks(Blink.this);
1670                mCancelled = true;
1671            }
1672        }
1673
1674        void uncancel() {
1675            mCancelled = false;
1676        }
1677    }
1678
1679    private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) {
1680        TextView shadowView = (TextView) View.inflate(mTextView.getContext(),
1681                com.android.internal.R.layout.text_drag_thumbnail, null);
1682
1683        if (shadowView == null) {
1684            throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
1685        }
1686
1687        if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) {
1688            text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH);
1689        }
1690        shadowView.setText(text);
1691        shadowView.setTextColor(mTextView.getTextColors());
1692
1693        shadowView.setTextAppearance(mTextView.getContext(), R.styleable.Theme_textAppearanceLarge);
1694        shadowView.setGravity(Gravity.CENTER);
1695
1696        shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
1697                ViewGroup.LayoutParams.WRAP_CONTENT));
1698
1699        final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
1700        shadowView.measure(size, size);
1701
1702        shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
1703        shadowView.invalidate();
1704        return new DragShadowBuilder(shadowView);
1705    }
1706
1707    private static class DragLocalState {
1708        public TextView sourceTextView;
1709        public int start, end;
1710
1711        public DragLocalState(TextView sourceTextView, int start, int end) {
1712            this.sourceTextView = sourceTextView;
1713            this.start = start;
1714            this.end = end;
1715        }
1716    }
1717
1718    void onDrop(DragEvent event) {
1719        StringBuilder content = new StringBuilder("");
1720        ClipData clipData = event.getClipData();
1721        final int itemCount = clipData.getItemCount();
1722        for (int i=0; i < itemCount; i++) {
1723            Item item = clipData.getItemAt(i);
1724            content.append(item.coerceToStyledText(mTextView.getContext()));
1725        }
1726
1727        final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
1728
1729        Object localState = event.getLocalState();
1730        DragLocalState dragLocalState = null;
1731        if (localState instanceof DragLocalState) {
1732            dragLocalState = (DragLocalState) localState;
1733        }
1734        boolean dragDropIntoItself = dragLocalState != null &&
1735                dragLocalState.sourceTextView == mTextView;
1736
1737        if (dragDropIntoItself) {
1738            if (offset >= dragLocalState.start && offset < dragLocalState.end) {
1739                // A drop inside the original selection discards the drop.
1740                return;
1741            }
1742        }
1743
1744        final int originalLength = mTextView.getText().length();
1745        long minMax = mTextView.prepareSpacesAroundPaste(offset, offset, content);
1746        int min = TextUtils.unpackRangeStartFromLong(minMax);
1747        int max = TextUtils.unpackRangeEndFromLong(minMax);
1748
1749        Selection.setSelection((Spannable) mTextView.getText(), max);
1750        mTextView.replaceText_internal(min, max, content);
1751
1752        if (dragDropIntoItself) {
1753            int dragSourceStart = dragLocalState.start;
1754            int dragSourceEnd = dragLocalState.end;
1755            if (max <= dragSourceStart) {
1756                // Inserting text before selection has shifted positions
1757                final int shift = mTextView.getText().length() - originalLength;
1758                dragSourceStart += shift;
1759                dragSourceEnd += shift;
1760            }
1761
1762            // Delete original selection
1763            mTextView.deleteText_internal(dragSourceStart, dragSourceEnd);
1764
1765            // Make sure we do not leave two adjacent spaces.
1766            CharSequence t = mTextView.getTransformedText(dragSourceStart - 1, dragSourceStart + 1);
1767            if ( (dragSourceStart == 0 || Character.isSpaceChar(t.charAt(0))) &&
1768                    (dragSourceStart == mTextView.getText().length() ||
1769                    Character.isSpaceChar(t.charAt(1))) ) {
1770                final int pos = dragSourceStart == mTextView.getText().length() ?
1771                        dragSourceStart - 1 : dragSourceStart;
1772                mTextView.deleteText_internal(pos, pos + 1);
1773            }
1774        }
1775    }
1776
1777    /**
1778     * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related
1779     * pop-up should be displayed.
1780     */
1781    class EasyEditSpanController implements TextWatcher {
1782
1783        private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs
1784
1785        private EasyEditPopupWindow mPopupWindow;
1786
1787        private EasyEditSpan mEasyEditSpan;
1788
1789        private Runnable mHidePopup;
1790
1791        public void hide() {
1792            if (mPopupWindow != null) {
1793                mPopupWindow.hide();
1794                mTextView.removeCallbacks(mHidePopup);
1795            }
1796            removeSpans(mTextView.getText());
1797            mEasyEditSpan = null;
1798        }
1799
1800        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1801            // Intentionally empty
1802        }
1803
1804        public void afterTextChanged(Editable s) {
1805            // Intentionally empty
1806        }
1807
1808        /**
1809         * Monitors the changes in the text.
1810         *
1811         * <p>{@link SpanWatcher#onSpanAdded(Spannable, Object, int, int)} cannot be used,
1812         * as the notifications are not sent when a spannable (with spans) is inserted.
1813         */
1814        public void onTextChanged(CharSequence buffer, int start, int before, int after) {
1815            adjustSpans(buffer, start, after);
1816
1817            if (mTextView.getWindowVisibility() != View.VISIBLE) {
1818                // The window is not visible yet, ignore the text change.
1819                return;
1820            }
1821
1822            if (mTextView.getLayout() == null) {
1823                // The view has not been layout yet, ignore the text change
1824                return;
1825            }
1826
1827            InputMethodManager imm = InputMethodManager.peekInstance();
1828            if (!(mTextView instanceof ExtractEditText) && imm != null && imm.isFullscreenMode()) {
1829                // The input is in extract mode. We do not have to handle the easy edit in the
1830                // original TextView, as the ExtractEditText will do
1831                return;
1832            }
1833
1834            // Remove the current easy edit span, as the text changed, and remove the pop-up
1835            // (if any)
1836            if (mEasyEditSpan != null) {
1837                if (buffer instanceof Spannable) {
1838                    ((Spannable) buffer).removeSpan(mEasyEditSpan);
1839                }
1840                mEasyEditSpan = null;
1841            }
1842            if (mPopupWindow != null && mPopupWindow.isShowing()) {
1843                mPopupWindow.hide();
1844            }
1845
1846            // Display the new easy edit span (if any).
1847            if (buffer instanceof Spanned) {
1848                mEasyEditSpan = getSpan((Spanned) buffer);
1849                if (mEasyEditSpan != null) {
1850                    if (mPopupWindow == null) {
1851                        mPopupWindow = new EasyEditPopupWindow();
1852                        mHidePopup = new Runnable() {
1853                            @Override
1854                            public void run() {
1855                                hide();
1856                            }
1857                        };
1858                    }
1859                    mPopupWindow.show(mEasyEditSpan);
1860                    mTextView.removeCallbacks(mHidePopup);
1861                    mTextView.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS);
1862                }
1863            }
1864        }
1865
1866        /**
1867         * Adjusts the spans by removing all of them except the last one.
1868         */
1869        private void adjustSpans(CharSequence buffer, int start, int after) {
1870            // This method enforces that only one easy edit span is attached to the text.
1871            // A better way to enforce this would be to listen for onSpanAdded, but this method
1872            // cannot be used in this scenario as no notification is triggered when a text with
1873            // spans is inserted into a text.
1874            if (buffer instanceof Spannable) {
1875                Spannable spannable = (Spannable) buffer;
1876                EasyEditSpan[] spans = spannable.getSpans(start, start + after, EasyEditSpan.class);
1877                if (spans.length > 0) {
1878                    // Assuming there was only one EasyEditSpan before, we only need check to
1879                    // check for a duplicate if a new one is found in the modified interval
1880                    spans = spannable.getSpans(0, spannable.length(),  EasyEditSpan.class);
1881                    for (int i = 1; i < spans.length; i++) {
1882                        spannable.removeSpan(spans[i]);
1883                    }
1884                }
1885            }
1886        }
1887
1888        /**
1889         * Removes all the {@link EasyEditSpan} currently attached.
1890         */
1891        private void removeSpans(CharSequence buffer) {
1892            if (buffer instanceof Spannable) {
1893                Spannable spannable = (Spannable) buffer;
1894                EasyEditSpan[] spans = spannable.getSpans(0, spannable.length(),
1895                        EasyEditSpan.class);
1896                for (int i = 0; i < spans.length; i++) {
1897                    spannable.removeSpan(spans[i]);
1898                }
1899            }
1900        }
1901
1902        private EasyEditSpan getSpan(Spanned spanned) {
1903            EasyEditSpan[] easyEditSpans = spanned.getSpans(0, spanned.length(),
1904                    EasyEditSpan.class);
1905            if (easyEditSpans.length == 0) {
1906                return null;
1907            } else {
1908                return easyEditSpans[0];
1909            }
1910        }
1911    }
1912
1913    /**
1914     * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled
1915     * by {@link EasyEditSpanController}.
1916     */
1917    private class EasyEditPopupWindow extends PinnedPopupWindow
1918            implements OnClickListener {
1919        private static final int POPUP_TEXT_LAYOUT =
1920                com.android.internal.R.layout.text_edit_action_popup_text;
1921        private TextView mDeleteTextView;
1922        private EasyEditSpan mEasyEditSpan;
1923
1924        @Override
1925        protected void createPopupWindow() {
1926            mPopupWindow = new PopupWindow(mTextView.getContext(), null,
1927                    com.android.internal.R.attr.textSelectHandleWindowStyle);
1928            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
1929            mPopupWindow.setClippingEnabled(true);
1930        }
1931
1932        @Override
1933        protected void initContentView() {
1934            LinearLayout linearLayout = new LinearLayout(mTextView.getContext());
1935            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
1936            mContentView = linearLayout;
1937            mContentView.setBackgroundResource(
1938                    com.android.internal.R.drawable.text_edit_side_paste_window);
1939
1940            LayoutInflater inflater = (LayoutInflater)mTextView.getContext().
1941                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
1942
1943            LayoutParams wrapContent = new LayoutParams(
1944                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
1945
1946            mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
1947            mDeleteTextView.setLayoutParams(wrapContent);
1948            mDeleteTextView.setText(com.android.internal.R.string.delete);
1949            mDeleteTextView.setOnClickListener(this);
1950            mContentView.addView(mDeleteTextView);
1951        }
1952
1953        public void show(EasyEditSpan easyEditSpan) {
1954            mEasyEditSpan = easyEditSpan;
1955            super.show();
1956        }
1957
1958        @Override
1959        public void onClick(View view) {
1960            if (view == mDeleteTextView) {
1961                Editable editable = (Editable) mTextView.getText();
1962                int start = editable.getSpanStart(mEasyEditSpan);
1963                int end = editable.getSpanEnd(mEasyEditSpan);
1964                if (start >= 0 && end >= 0) {
1965                    mTextView.deleteText_internal(start, end);
1966                }
1967            }
1968        }
1969
1970        @Override
1971        protected int getTextOffset() {
1972            // Place the pop-up at the end of the span
1973            Editable editable = (Editable) mTextView.getText();
1974            return editable.getSpanEnd(mEasyEditSpan);
1975        }
1976
1977        @Override
1978        protected int getVerticalLocalPosition(int line) {
1979            return mTextView.getLayout().getLineBottom(line);
1980        }
1981
1982        @Override
1983        protected int clipVertically(int positionY) {
1984            // As we display the pop-up below the span, no vertical clipping is required.
1985            return positionY;
1986        }
1987    }
1988
1989    private class PositionListener implements ViewTreeObserver.OnPreDrawListener {
1990        // 3 handles
1991        // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others)
1992        private final int MAXIMUM_NUMBER_OF_LISTENERS = 6;
1993        private TextViewPositionListener[] mPositionListeners =
1994                new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS];
1995        private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS];
1996        private boolean mPositionHasChanged = true;
1997        // Absolute position of the TextView with respect to its parent window
1998        private int mPositionX, mPositionY;
1999        private int mNumberOfListeners;
2000        private boolean mScrollHasChanged;
2001        final int[] mTempCoords = new int[2];
2002
2003        public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) {
2004            if (mNumberOfListeners == 0) {
2005                updatePosition();
2006                ViewTreeObserver vto = mTextView.getViewTreeObserver();
2007                vto.addOnPreDrawListener(this);
2008            }
2009
2010            int emptySlotIndex = -1;
2011            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2012                TextViewPositionListener listener = mPositionListeners[i];
2013                if (listener == positionListener) {
2014                    return;
2015                } else if (emptySlotIndex < 0 && listener == null) {
2016                    emptySlotIndex = i;
2017                }
2018            }
2019
2020            mPositionListeners[emptySlotIndex] = positionListener;
2021            mCanMove[emptySlotIndex] = canMove;
2022            mNumberOfListeners++;
2023        }
2024
2025        public void removeSubscriber(TextViewPositionListener positionListener) {
2026            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2027                if (mPositionListeners[i] == positionListener) {
2028                    mPositionListeners[i] = null;
2029                    mNumberOfListeners--;
2030                    break;
2031                }
2032            }
2033
2034            if (mNumberOfListeners == 0) {
2035                ViewTreeObserver vto = mTextView.getViewTreeObserver();
2036                vto.removeOnPreDrawListener(this);
2037            }
2038        }
2039
2040        public int getPositionX() {
2041            return mPositionX;
2042        }
2043
2044        public int getPositionY() {
2045            return mPositionY;
2046        }
2047
2048        @Override
2049        public boolean onPreDraw() {
2050            updatePosition();
2051
2052            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2053                if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) {
2054                    TextViewPositionListener positionListener = mPositionListeners[i];
2055                    if (positionListener != null) {
2056                        positionListener.updatePosition(mPositionX, mPositionY,
2057                                mPositionHasChanged, mScrollHasChanged);
2058                    }
2059                }
2060            }
2061
2062            mScrollHasChanged = false;
2063            return true;
2064        }
2065
2066        private void updatePosition() {
2067            mTextView.getLocationInWindow(mTempCoords);
2068
2069            mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY;
2070
2071            mPositionX = mTempCoords[0];
2072            mPositionY = mTempCoords[1];
2073        }
2074
2075        public void onScrollChanged() {
2076            mScrollHasChanged = true;
2077        }
2078    }
2079
2080    private abstract class PinnedPopupWindow implements TextViewPositionListener {
2081        protected PopupWindow mPopupWindow;
2082        protected ViewGroup mContentView;
2083        int mPositionX, mPositionY;
2084
2085        protected abstract void createPopupWindow();
2086        protected abstract void initContentView();
2087        protected abstract int getTextOffset();
2088        protected abstract int getVerticalLocalPosition(int line);
2089        protected abstract int clipVertically(int positionY);
2090
2091        public PinnedPopupWindow() {
2092            createPopupWindow();
2093
2094            mPopupWindow.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
2095            mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
2096            mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
2097
2098            initContentView();
2099
2100            LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2101                    ViewGroup.LayoutParams.WRAP_CONTENT);
2102            mContentView.setLayoutParams(wrapContent);
2103
2104            mPopupWindow.setContentView(mContentView);
2105        }
2106
2107        public void show() {
2108            getPositionListener().addSubscriber(this, false /* offset is fixed */);
2109
2110            computeLocalPosition();
2111
2112            final PositionListener positionListener = getPositionListener();
2113            updatePosition(positionListener.getPositionX(), positionListener.getPositionY());
2114        }
2115
2116        protected void measureContent() {
2117            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2118            mContentView.measure(
2119                    View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels,
2120                            View.MeasureSpec.AT_MOST),
2121                    View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels,
2122                            View.MeasureSpec.AT_MOST));
2123        }
2124
2125        /* The popup window will be horizontally centered on the getTextOffset() and vertically
2126         * positioned according to viewportToContentHorizontalOffset.
2127         *
2128         * This method assumes that mContentView has properly been measured from its content. */
2129        private void computeLocalPosition() {
2130            measureContent();
2131            final int width = mContentView.getMeasuredWidth();
2132            final int offset = getTextOffset();
2133            mPositionX = (int) (mTextView.getLayout().getPrimaryHorizontal(offset) - width / 2.0f);
2134            mPositionX += mTextView.viewportToContentHorizontalOffset();
2135
2136            final int line = mTextView.getLayout().getLineForOffset(offset);
2137            mPositionY = getVerticalLocalPosition(line);
2138            mPositionY += mTextView.viewportToContentVerticalOffset();
2139        }
2140
2141        private void updatePosition(int parentPositionX, int parentPositionY) {
2142            int positionX = parentPositionX + mPositionX;
2143            int positionY = parentPositionY + mPositionY;
2144
2145            positionY = clipVertically(positionY);
2146
2147            // Horizontal clipping
2148            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2149            final int width = mContentView.getMeasuredWidth();
2150            positionX = Math.min(displayMetrics.widthPixels - width, positionX);
2151            positionX = Math.max(0, positionX);
2152
2153            if (isShowing()) {
2154                mPopupWindow.update(positionX, positionY, -1, -1);
2155            } else {
2156                mPopupWindow.showAtLocation(mTextView, Gravity.NO_GRAVITY,
2157                        positionX, positionY);
2158            }
2159        }
2160
2161        public void hide() {
2162            mPopupWindow.dismiss();
2163            getPositionListener().removeSubscriber(this);
2164        }
2165
2166        @Override
2167        public void updatePosition(int parentPositionX, int parentPositionY,
2168                boolean parentPositionChanged, boolean parentScrolled) {
2169            // Either parentPositionChanged or parentScrolled is true, check if still visible
2170            if (isShowing() && isOffsetVisible(getTextOffset())) {
2171                if (parentScrolled) computeLocalPosition();
2172                updatePosition(parentPositionX, parentPositionY);
2173            } else {
2174                hide();
2175            }
2176        }
2177
2178        public boolean isShowing() {
2179            return mPopupWindow.isShowing();
2180        }
2181    }
2182
2183    private class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener {
2184        private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE;
2185        private static final int ADD_TO_DICTIONARY = -1;
2186        private static final int DELETE_TEXT = -2;
2187        private SuggestionInfo[] mSuggestionInfos;
2188        private int mNumberOfSuggestions;
2189        private boolean mCursorWasVisibleBeforeSuggestions;
2190        private boolean mIsShowingUp = false;
2191        private SuggestionAdapter mSuggestionsAdapter;
2192        private final Comparator<SuggestionSpan> mSuggestionSpanComparator;
2193        private final HashMap<SuggestionSpan, Integer> mSpansLengths;
2194
2195        private class CustomPopupWindow extends PopupWindow {
2196            public CustomPopupWindow(Context context, int defStyle) {
2197                super(context, null, defStyle);
2198            }
2199
2200            @Override
2201            public void dismiss() {
2202                super.dismiss();
2203
2204                getPositionListener().removeSubscriber(SuggestionsPopupWindow.this);
2205
2206                // Safe cast since show() checks that mTextView.getText() is an Editable
2207                ((Spannable) mTextView.getText()).removeSpan(mSuggestionRangeSpan);
2208
2209                mTextView.setCursorVisible(mCursorWasVisibleBeforeSuggestions);
2210                if (hasInsertionController()) {
2211                    getInsertionController().show();
2212                }
2213            }
2214        }
2215
2216        public SuggestionsPopupWindow() {
2217            mCursorWasVisibleBeforeSuggestions = mCursorVisible;
2218            mSuggestionSpanComparator = new SuggestionSpanComparator();
2219            mSpansLengths = new HashMap<SuggestionSpan, Integer>();
2220        }
2221
2222        @Override
2223        protected void createPopupWindow() {
2224            mPopupWindow = new CustomPopupWindow(mTextView.getContext(),
2225                com.android.internal.R.attr.textSuggestionsWindowStyle);
2226            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
2227            mPopupWindow.setFocusable(true);
2228            mPopupWindow.setClippingEnabled(false);
2229        }
2230
2231        @Override
2232        protected void initContentView() {
2233            ListView listView = new ListView(mTextView.getContext());
2234            mSuggestionsAdapter = new SuggestionAdapter();
2235            listView.setAdapter(mSuggestionsAdapter);
2236            listView.setOnItemClickListener(this);
2237            mContentView = listView;
2238
2239            // Inflate the suggestion items once and for all. + 2 for add to dictionary and delete
2240            mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS + 2];
2241            for (int i = 0; i < mSuggestionInfos.length; i++) {
2242                mSuggestionInfos[i] = new SuggestionInfo();
2243            }
2244        }
2245
2246        public boolean isShowingUp() {
2247            return mIsShowingUp;
2248        }
2249
2250        public void onParentLostFocus() {
2251            mIsShowingUp = false;
2252        }
2253
2254        private class SuggestionInfo {
2255            int suggestionStart, suggestionEnd; // range of actual suggestion within text
2256            SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents
2257            int suggestionIndex; // the index of this suggestion inside suggestionSpan
2258            SpannableStringBuilder text = new SpannableStringBuilder();
2259            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mTextView.getContext(),
2260                    android.R.style.TextAppearance_SuggestionHighlight);
2261        }
2262
2263        private class SuggestionAdapter extends BaseAdapter {
2264            private LayoutInflater mInflater = (LayoutInflater) mTextView.getContext().
2265                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2266
2267            @Override
2268            public int getCount() {
2269                return mNumberOfSuggestions;
2270            }
2271
2272            @Override
2273            public Object getItem(int position) {
2274                return mSuggestionInfos[position];
2275            }
2276
2277            @Override
2278            public long getItemId(int position) {
2279                return position;
2280            }
2281
2282            @Override
2283            public View getView(int position, View convertView, ViewGroup parent) {
2284                TextView textView = (TextView) convertView;
2285
2286                if (textView == null) {
2287                    textView = (TextView) mInflater.inflate(mTextView.mTextEditSuggestionItemLayout,
2288                            parent, false);
2289                }
2290
2291                final SuggestionInfo suggestionInfo = mSuggestionInfos[position];
2292                textView.setText(suggestionInfo.text);
2293
2294                if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) {
2295                    textView.setCompoundDrawablesWithIntrinsicBounds(
2296                            com.android.internal.R.drawable.ic_suggestions_add, 0, 0, 0);
2297                } else if (suggestionInfo.suggestionIndex == DELETE_TEXT) {
2298                    textView.setCompoundDrawablesWithIntrinsicBounds(
2299                            com.android.internal.R.drawable.ic_suggestions_delete, 0, 0, 0);
2300                } else {
2301                    textView.setCompoundDrawables(null, null, null, null);
2302                }
2303
2304                return textView;
2305            }
2306        }
2307
2308        private class SuggestionSpanComparator implements Comparator<SuggestionSpan> {
2309            public int compare(SuggestionSpan span1, SuggestionSpan span2) {
2310                final int flag1 = span1.getFlags();
2311                final int flag2 = span2.getFlags();
2312                if (flag1 != flag2) {
2313                    // The order here should match what is used in updateDrawState
2314                    final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
2315                    final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
2316                    final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0;
2317                    final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0;
2318                    if (easy1 && !misspelled1) return -1;
2319                    if (easy2 && !misspelled2) return 1;
2320                    if (misspelled1) return -1;
2321                    if (misspelled2) return 1;
2322                }
2323
2324                return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue();
2325            }
2326        }
2327
2328        /**
2329         * Returns the suggestion spans that cover the current cursor position. The suggestion
2330         * spans are sorted according to the length of text that they are attached to.
2331         */
2332        private SuggestionSpan[] getSuggestionSpans() {
2333            int pos = mTextView.getSelectionStart();
2334            Spannable spannable = (Spannable) mTextView.getText();
2335            SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class);
2336
2337            mSpansLengths.clear();
2338            for (SuggestionSpan suggestionSpan : suggestionSpans) {
2339                int start = spannable.getSpanStart(suggestionSpan);
2340                int end = spannable.getSpanEnd(suggestionSpan);
2341                mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start));
2342            }
2343
2344            // The suggestions are sorted according to their types (easy correction first, then
2345            // misspelled) and to the length of the text that they cover (shorter first).
2346            Arrays.sort(suggestionSpans, mSuggestionSpanComparator);
2347            return suggestionSpans;
2348        }
2349
2350        @Override
2351        public void show() {
2352            if (!(mTextView.getText() instanceof Editable)) return;
2353
2354            if (updateSuggestions()) {
2355                mCursorWasVisibleBeforeSuggestions = mCursorVisible;
2356                mTextView.setCursorVisible(false);
2357                mIsShowingUp = true;
2358                super.show();
2359            }
2360        }
2361
2362        @Override
2363        protected void measureContent() {
2364            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2365            final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec(
2366                    displayMetrics.widthPixels, View.MeasureSpec.AT_MOST);
2367            final int verticalMeasure = View.MeasureSpec.makeMeasureSpec(
2368                    displayMetrics.heightPixels, View.MeasureSpec.AT_MOST);
2369
2370            int width = 0;
2371            View view = null;
2372            for (int i = 0; i < mNumberOfSuggestions; i++) {
2373                view = mSuggestionsAdapter.getView(i, view, mContentView);
2374                view.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
2375                view.measure(horizontalMeasure, verticalMeasure);
2376                width = Math.max(width, view.getMeasuredWidth());
2377            }
2378
2379            // Enforce the width based on actual text widths
2380            mContentView.measure(
2381                    View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
2382                    verticalMeasure);
2383
2384            Drawable popupBackground = mPopupWindow.getBackground();
2385            if (popupBackground != null) {
2386                if (mTempRect == null) mTempRect = new Rect();
2387                popupBackground.getPadding(mTempRect);
2388                width += mTempRect.left + mTempRect.right;
2389            }
2390            mPopupWindow.setWidth(width);
2391        }
2392
2393        @Override
2394        protected int getTextOffset() {
2395            return mTextView.getSelectionStart();
2396        }
2397
2398        @Override
2399        protected int getVerticalLocalPosition(int line) {
2400            return mTextView.getLayout().getLineBottom(line);
2401        }
2402
2403        @Override
2404        protected int clipVertically(int positionY) {
2405            final int height = mContentView.getMeasuredHeight();
2406            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2407            return Math.min(positionY, displayMetrics.heightPixels - height);
2408        }
2409
2410        @Override
2411        public void hide() {
2412            super.hide();
2413        }
2414
2415        private boolean updateSuggestions() {
2416            Spannable spannable = (Spannable) mTextView.getText();
2417            SuggestionSpan[] suggestionSpans = getSuggestionSpans();
2418
2419            final int nbSpans = suggestionSpans.length;
2420            // Suggestions are shown after a delay: the underlying spans may have been removed
2421            if (nbSpans == 0) return false;
2422
2423            mNumberOfSuggestions = 0;
2424            int spanUnionStart = mTextView.getText().length();
2425            int spanUnionEnd = 0;
2426
2427            SuggestionSpan misspelledSpan = null;
2428            int underlineColor = 0;
2429
2430            for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) {
2431                SuggestionSpan suggestionSpan = suggestionSpans[spanIndex];
2432                final int spanStart = spannable.getSpanStart(suggestionSpan);
2433                final int spanEnd = spannable.getSpanEnd(suggestionSpan);
2434                spanUnionStart = Math.min(spanStart, spanUnionStart);
2435                spanUnionEnd = Math.max(spanEnd, spanUnionEnd);
2436
2437                if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) {
2438                    misspelledSpan = suggestionSpan;
2439                }
2440
2441                // The first span dictates the background color of the highlighted text
2442                if (spanIndex == 0) underlineColor = suggestionSpan.getUnderlineColor();
2443
2444                String[] suggestions = suggestionSpan.getSuggestions();
2445                int nbSuggestions = suggestions.length;
2446                for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) {
2447                    String suggestion = suggestions[suggestionIndex];
2448
2449                    boolean suggestionIsDuplicate = false;
2450                    for (int i = 0; i < mNumberOfSuggestions; i++) {
2451                        if (mSuggestionInfos[i].text.toString().equals(suggestion)) {
2452                            SuggestionSpan otherSuggestionSpan = mSuggestionInfos[i].suggestionSpan;
2453                            final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan);
2454                            final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan);
2455                            if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) {
2456                                suggestionIsDuplicate = true;
2457                                break;
2458                            }
2459                        }
2460                    }
2461
2462                    if (!suggestionIsDuplicate) {
2463                        SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2464                        suggestionInfo.suggestionSpan = suggestionSpan;
2465                        suggestionInfo.suggestionIndex = suggestionIndex;
2466                        suggestionInfo.text.replace(0, suggestionInfo.text.length(), suggestion);
2467
2468                        mNumberOfSuggestions++;
2469
2470                        if (mNumberOfSuggestions == MAX_NUMBER_SUGGESTIONS) {
2471                            // Also end outer for loop
2472                            spanIndex = nbSpans;
2473                            break;
2474                        }
2475                    }
2476                }
2477            }
2478
2479            for (int i = 0; i < mNumberOfSuggestions; i++) {
2480                highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd);
2481            }
2482
2483            // Add "Add to dictionary" item if there is a span with the misspelled flag
2484            if (misspelledSpan != null) {
2485                final int misspelledStart = spannable.getSpanStart(misspelledSpan);
2486                final int misspelledEnd = spannable.getSpanEnd(misspelledSpan);
2487                if (misspelledStart >= 0 && misspelledEnd > misspelledStart) {
2488                    SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2489                    suggestionInfo.suggestionSpan = misspelledSpan;
2490                    suggestionInfo.suggestionIndex = ADD_TO_DICTIONARY;
2491                    suggestionInfo.text.replace(0, suggestionInfo.text.length(), mTextView.
2492                            getContext().getString(com.android.internal.R.string.addToDictionary));
2493                    suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
2494                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2495
2496                    mNumberOfSuggestions++;
2497                }
2498            }
2499
2500            // Delete item
2501            SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2502            suggestionInfo.suggestionSpan = null;
2503            suggestionInfo.suggestionIndex = DELETE_TEXT;
2504            suggestionInfo.text.replace(0, suggestionInfo.text.length(),
2505                    mTextView.getContext().getString(com.android.internal.R.string.deleteText));
2506            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
2507                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2508            mNumberOfSuggestions++;
2509
2510            if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan();
2511            if (underlineColor == 0) {
2512                // Fallback on the default highlight color when the first span does not provide one
2513                mSuggestionRangeSpan.setBackgroundColor(mTextView.mHighlightColor);
2514            } else {
2515                final float BACKGROUND_TRANSPARENCY = 0.4f;
2516                final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY);
2517                mSuggestionRangeSpan.setBackgroundColor(
2518                        (underlineColor & 0x00FFFFFF) + (newAlpha << 24));
2519            }
2520            spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd,
2521                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2522
2523            mSuggestionsAdapter.notifyDataSetChanged();
2524            return true;
2525        }
2526
2527        private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart,
2528                int unionEnd) {
2529            final Spannable text = (Spannable) mTextView.getText();
2530            final int spanStart = text.getSpanStart(suggestionInfo.suggestionSpan);
2531            final int spanEnd = text.getSpanEnd(suggestionInfo.suggestionSpan);
2532
2533            // Adjust the start/end of the suggestion span
2534            suggestionInfo.suggestionStart = spanStart - unionStart;
2535            suggestionInfo.suggestionEnd = suggestionInfo.suggestionStart
2536                    + suggestionInfo.text.length();
2537
2538            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0,
2539                    suggestionInfo.text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2540
2541            // Add the text before and after the span.
2542            final String textAsString = text.toString();
2543            suggestionInfo.text.insert(0, textAsString.substring(unionStart, spanStart));
2544            suggestionInfo.text.append(textAsString.substring(spanEnd, unionEnd));
2545        }
2546
2547        @Override
2548        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2549            Editable editable = (Editable) mTextView.getText();
2550            SuggestionInfo suggestionInfo = mSuggestionInfos[position];
2551
2552            if (suggestionInfo.suggestionIndex == DELETE_TEXT) {
2553                final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan);
2554                int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan);
2555                if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) {
2556                    // Do not leave two adjacent spaces after deletion, or one at beginning of text
2557                    if (spanUnionEnd < editable.length() &&
2558                            Character.isSpaceChar(editable.charAt(spanUnionEnd)) &&
2559                            (spanUnionStart == 0 ||
2560                            Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) {
2561                        spanUnionEnd = spanUnionEnd + 1;
2562                    }
2563                    mTextView.deleteText_internal(spanUnionStart, spanUnionEnd);
2564                }
2565                hide();
2566                return;
2567            }
2568
2569            final int spanStart = editable.getSpanStart(suggestionInfo.suggestionSpan);
2570            final int spanEnd = editable.getSpanEnd(suggestionInfo.suggestionSpan);
2571            if (spanStart < 0 || spanEnd <= spanStart) {
2572                // Span has been removed
2573                hide();
2574                return;
2575            }
2576
2577            final String originalText = editable.toString().substring(spanStart, spanEnd);
2578
2579            if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) {
2580                Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT);
2581                intent.putExtra("word", originalText);
2582                intent.putExtra("locale", mTextView.getTextServicesLocale().toString());
2583                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
2584                mTextView.getContext().startActivity(intent);
2585                // There is no way to know if the word was indeed added. Re-check.
2586                // TODO The ExtractEditText should remove the span in the original text instead
2587                editable.removeSpan(suggestionInfo.suggestionSpan);
2588                Selection.setSelection(editable, spanEnd);
2589                updateSpellCheckSpans(spanStart, spanEnd, false);
2590            } else {
2591                // SuggestionSpans are removed by replace: save them before
2592                SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd,
2593                        SuggestionSpan.class);
2594                final int length = suggestionSpans.length;
2595                int[] suggestionSpansStarts = new int[length];
2596                int[] suggestionSpansEnds = new int[length];
2597                int[] suggestionSpansFlags = new int[length];
2598                for (int i = 0; i < length; i++) {
2599                    final SuggestionSpan suggestionSpan = suggestionSpans[i];
2600                    suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan);
2601                    suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan);
2602                    suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan);
2603
2604                    // Remove potential misspelled flags
2605                    int suggestionSpanFlags = suggestionSpan.getFlags();
2606                    if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) > 0) {
2607                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED;
2608                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
2609                        suggestionSpan.setFlags(suggestionSpanFlags);
2610                    }
2611                }
2612
2613                final int suggestionStart = suggestionInfo.suggestionStart;
2614                final int suggestionEnd = suggestionInfo.suggestionEnd;
2615                final String suggestion = suggestionInfo.text.subSequence(
2616                        suggestionStart, suggestionEnd).toString();
2617                mTextView.replaceText_internal(spanStart, spanEnd, suggestion);
2618
2619                // Notify source IME of the suggestion pick. Do this before swaping texts.
2620                if (!TextUtils.isEmpty(
2621                        suggestionInfo.suggestionSpan.getNotificationTargetClassName())) {
2622                    InputMethodManager imm = InputMethodManager.peekInstance();
2623                    if (imm != null) {
2624                        imm.notifySuggestionPicked(suggestionInfo.suggestionSpan, originalText,
2625                                suggestionInfo.suggestionIndex);
2626                    }
2627                }
2628
2629                // Swap text content between actual text and Suggestion span
2630                String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions();
2631                suggestions[suggestionInfo.suggestionIndex] = originalText;
2632
2633                // Restore previous SuggestionSpans
2634                final int lengthDifference = suggestion.length() - (spanEnd - spanStart);
2635                for (int i = 0; i < length; i++) {
2636                    // Only spans that include the modified region make sense after replacement
2637                    // Spans partially included in the replaced region are removed, there is no
2638                    // way to assign them a valid range after replacement
2639                    if (suggestionSpansStarts[i] <= spanStart &&
2640                            suggestionSpansEnds[i] >= spanEnd) {
2641                        mTextView.setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i],
2642                                suggestionSpansEnds[i] + lengthDifference, suggestionSpansFlags[i]);
2643                    }
2644                }
2645
2646                // Move cursor at the end of the replaced word
2647                final int newCursorPosition = spanEnd + lengthDifference;
2648                mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition);
2649            }
2650
2651            hide();
2652        }
2653    }
2654
2655    /**
2656     * An ActionMode Callback class that is used to provide actions while in text selection mode.
2657     *
2658     * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending
2659     * on which of these this TextView supports.
2660     */
2661    private class SelectionActionModeCallback implements ActionMode.Callback {
2662
2663        @Override
2664        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2665            TypedArray styledAttributes = mTextView.getContext().obtainStyledAttributes(
2666                    com.android.internal.R.styleable.SelectionModeDrawables);
2667
2668            boolean allowText = mTextView.getContext().getResources().getBoolean(
2669                    com.android.internal.R.bool.config_allowActionMenuItemTextWithIcon);
2670
2671            mode.setTitle(mTextView.getContext().getString(
2672                    com.android.internal.R.string.textSelectionCABTitle));
2673            mode.setSubtitle(null);
2674            mode.setTitleOptionalHint(true);
2675
2676            int selectAllIconId = 0; // No icon by default
2677            if (!allowText) {
2678                // Provide an icon, text will not be displayed on smaller screens.
2679                selectAllIconId = styledAttributes.getResourceId(
2680                        R.styleable.SelectionModeDrawables_actionModeSelectAllDrawable, 0);
2681            }
2682
2683            menu.add(0, TextView.ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll).
2684                    setIcon(selectAllIconId).
2685                    setAlphabeticShortcut('a').
2686                    setShowAsAction(
2687                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
2688
2689            if (mTextView.canCut()) {
2690                menu.add(0, TextView.ID_CUT, 0, com.android.internal.R.string.cut).
2691                    setIcon(styledAttributes.getResourceId(
2692                            R.styleable.SelectionModeDrawables_actionModeCutDrawable, 0)).
2693                    setAlphabeticShortcut('x').
2694                    setShowAsAction(
2695                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
2696            }
2697
2698            if (mTextView.canCopy()) {
2699                menu.add(0, TextView.ID_COPY, 0, com.android.internal.R.string.copy).
2700                    setIcon(styledAttributes.getResourceId(
2701                            R.styleable.SelectionModeDrawables_actionModeCopyDrawable, 0)).
2702                    setAlphabeticShortcut('c').
2703                    setShowAsAction(
2704                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
2705            }
2706
2707            if (mTextView.canPaste()) {
2708                menu.add(0, TextView.ID_PASTE, 0, com.android.internal.R.string.paste).
2709                        setIcon(styledAttributes.getResourceId(
2710                                R.styleable.SelectionModeDrawables_actionModePasteDrawable, 0)).
2711                        setAlphabeticShortcut('v').
2712                        setShowAsAction(
2713                                MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
2714            }
2715
2716            styledAttributes.recycle();
2717
2718            if (mCustomSelectionActionModeCallback != null) {
2719                if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) {
2720                    // The custom mode can choose to cancel the action mode
2721                    return false;
2722                }
2723            }
2724
2725            if (menu.hasVisibleItems() || mode.getCustomView() != null) {
2726                getSelectionController().show();
2727                return true;
2728            } else {
2729                return false;
2730            }
2731        }
2732
2733        @Override
2734        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
2735            if (mCustomSelectionActionModeCallback != null) {
2736                return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu);
2737            }
2738            return true;
2739        }
2740
2741        @Override
2742        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
2743            if (mCustomSelectionActionModeCallback != null &&
2744                 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) {
2745                return true;
2746            }
2747            return mTextView.onTextContextMenuItem(item.getItemId());
2748        }
2749
2750        @Override
2751        public void onDestroyActionMode(ActionMode mode) {
2752            if (mCustomSelectionActionModeCallback != null) {
2753                mCustomSelectionActionModeCallback.onDestroyActionMode(mode);
2754            }
2755            Selection.setSelection((Spannable) mTextView.getText(), mTextView.getSelectionEnd());
2756
2757            if (mSelectionModifierCursorController != null) {
2758                mSelectionModifierCursorController.hide();
2759            }
2760
2761            mSelectionActionMode = null;
2762        }
2763    }
2764
2765    private class ActionPopupWindow extends PinnedPopupWindow implements OnClickListener {
2766        private static final int POPUP_TEXT_LAYOUT =
2767                com.android.internal.R.layout.text_edit_action_popup_text;
2768        private TextView mPasteTextView;
2769        private TextView mReplaceTextView;
2770
2771        @Override
2772        protected void createPopupWindow() {
2773            mPopupWindow = new PopupWindow(mTextView.getContext(), null,
2774                    com.android.internal.R.attr.textSelectHandleWindowStyle);
2775            mPopupWindow.setClippingEnabled(true);
2776        }
2777
2778        @Override
2779        protected void initContentView() {
2780            LinearLayout linearLayout = new LinearLayout(mTextView.getContext());
2781            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
2782            mContentView = linearLayout;
2783            mContentView.setBackgroundResource(
2784                    com.android.internal.R.drawable.text_edit_paste_window);
2785
2786            LayoutInflater inflater = (LayoutInflater) mTextView.getContext().
2787                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2788
2789            LayoutParams wrapContent = new LayoutParams(
2790                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
2791
2792            mPasteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
2793            mPasteTextView.setLayoutParams(wrapContent);
2794            mContentView.addView(mPasteTextView);
2795            mPasteTextView.setText(com.android.internal.R.string.paste);
2796            mPasteTextView.setOnClickListener(this);
2797
2798            mReplaceTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
2799            mReplaceTextView.setLayoutParams(wrapContent);
2800            mContentView.addView(mReplaceTextView);
2801            mReplaceTextView.setText(com.android.internal.R.string.replace);
2802            mReplaceTextView.setOnClickListener(this);
2803        }
2804
2805        @Override
2806        public void show() {
2807            boolean canPaste = mTextView.canPaste();
2808            boolean canSuggest = mTextView.isSuggestionsEnabled() && isCursorInsideSuggestionSpan();
2809            mPasteTextView.setVisibility(canPaste ? View.VISIBLE : View.GONE);
2810            mReplaceTextView.setVisibility(canSuggest ? View.VISIBLE : View.GONE);
2811
2812            if (!canPaste && !canSuggest) return;
2813
2814            super.show();
2815        }
2816
2817        @Override
2818        public void onClick(View view) {
2819            if (view == mPasteTextView && mTextView.canPaste()) {
2820                mTextView.onTextContextMenuItem(TextView.ID_PASTE);
2821                hide();
2822            } else if (view == mReplaceTextView) {
2823                int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2;
2824                stopSelectionActionMode();
2825                Selection.setSelection((Spannable) mTextView.getText(), middle);
2826                showSuggestions();
2827            }
2828        }
2829
2830        @Override
2831        protected int getTextOffset() {
2832            return (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2;
2833        }
2834
2835        @Override
2836        protected int getVerticalLocalPosition(int line) {
2837            return mTextView.getLayout().getLineTop(line) - mContentView.getMeasuredHeight();
2838        }
2839
2840        @Override
2841        protected int clipVertically(int positionY) {
2842            if (positionY < 0) {
2843                final int offset = getTextOffset();
2844                final Layout layout = mTextView.getLayout();
2845                final int line = layout.getLineForOffset(offset);
2846                positionY += layout.getLineBottom(line) - layout.getLineTop(line);
2847                positionY += mContentView.getMeasuredHeight();
2848
2849                // Assumes insertion and selection handles share the same height
2850                final Drawable handle = mTextView.getResources().getDrawable(
2851                        mTextView.mTextSelectHandleRes);
2852                positionY += handle.getIntrinsicHeight();
2853            }
2854
2855            return positionY;
2856        }
2857    }
2858
2859    private abstract class HandleView extends View implements TextViewPositionListener {
2860        protected Drawable mDrawable;
2861        protected Drawable mDrawableLtr;
2862        protected Drawable mDrawableRtl;
2863        private final PopupWindow mContainer;
2864        // Position with respect to the parent TextView
2865        private int mPositionX, mPositionY;
2866        private boolean mIsDragging;
2867        // Offset from touch position to mPosition
2868        private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
2869        protected int mHotspotX;
2870        // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
2871        private float mTouchOffsetY;
2872        // Where the touch position should be on the handle to ensure a maximum cursor visibility
2873        private float mIdealVerticalOffset;
2874        // Parent's (TextView) previous position in window
2875        private int mLastParentX, mLastParentY;
2876        // Transient action popup window for Paste and Replace actions
2877        protected ActionPopupWindow mActionPopupWindow;
2878        // Previous text character offset
2879        private int mPreviousOffset = -1;
2880        // Previous text character offset
2881        private boolean mPositionHasChanged = true;
2882        // Used to delay the appearance of the action popup window
2883        private Runnable mActionPopupShower;
2884
2885        public HandleView(Drawable drawableLtr, Drawable drawableRtl) {
2886            super(mTextView.getContext());
2887            mContainer = new PopupWindow(mTextView.getContext(), null,
2888                    com.android.internal.R.attr.textSelectHandleWindowStyle);
2889            mContainer.setSplitTouchEnabled(true);
2890            mContainer.setClippingEnabled(false);
2891            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
2892            mContainer.setContentView(this);
2893
2894            mDrawableLtr = drawableLtr;
2895            mDrawableRtl = drawableRtl;
2896
2897            updateDrawable();
2898
2899            final int handleHeight = mDrawable.getIntrinsicHeight();
2900            mTouchOffsetY = -0.3f * handleHeight;
2901            mIdealVerticalOffset = 0.7f * handleHeight;
2902        }
2903
2904        protected void updateDrawable() {
2905            final int offset = getCurrentCursorOffset();
2906            final boolean isRtlCharAtOffset = mTextView.getLayout().isRtlCharAt(offset);
2907            mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
2908            mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
2909        }
2910
2911        protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
2912
2913        // Touch-up filter: number of previous positions remembered
2914        private static final int HISTORY_SIZE = 5;
2915        private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
2916        private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
2917        private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
2918        private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
2919        private int mPreviousOffsetIndex = 0;
2920        private int mNumberPreviousOffsets = 0;
2921
2922        private void startTouchUpFilter(int offset) {
2923            mNumberPreviousOffsets = 0;
2924            addPositionToTouchUpFilter(offset);
2925        }
2926
2927        private void addPositionToTouchUpFilter(int offset) {
2928            mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
2929            mPreviousOffsets[mPreviousOffsetIndex] = offset;
2930            mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
2931            mNumberPreviousOffsets++;
2932        }
2933
2934        private void filterOnTouchUp() {
2935            final long now = SystemClock.uptimeMillis();
2936            int i = 0;
2937            int index = mPreviousOffsetIndex;
2938            final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
2939            while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
2940                i++;
2941                index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
2942            }
2943
2944            if (i > 0 && i < iMax &&
2945                    (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
2946                positionAtCursorOffset(mPreviousOffsets[index], false);
2947            }
2948        }
2949
2950        public boolean offsetHasBeenChanged() {
2951            return mNumberPreviousOffsets > 1;
2952        }
2953
2954        @Override
2955        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
2956            setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
2957        }
2958
2959        public void show() {
2960            if (isShowing()) return;
2961
2962            getPositionListener().addSubscriber(this, true /* local position may change */);
2963
2964            // Make sure the offset is always considered new, even when focusing at same position
2965            mPreviousOffset = -1;
2966            positionAtCursorOffset(getCurrentCursorOffset(), false);
2967
2968            hideActionPopupWindow();
2969        }
2970
2971        protected void dismiss() {
2972            mIsDragging = false;
2973            mContainer.dismiss();
2974            onDetached();
2975        }
2976
2977        public void hide() {
2978            dismiss();
2979
2980            getPositionListener().removeSubscriber(this);
2981        }
2982
2983        void showActionPopupWindow(int delay) {
2984            if (mActionPopupWindow == null) {
2985                mActionPopupWindow = new ActionPopupWindow();
2986            }
2987            if (mActionPopupShower == null) {
2988                mActionPopupShower = new Runnable() {
2989                    public void run() {
2990                        mActionPopupWindow.show();
2991                    }
2992                };
2993            } else {
2994                mTextView.removeCallbacks(mActionPopupShower);
2995            }
2996            mTextView.postDelayed(mActionPopupShower, delay);
2997        }
2998
2999        protected void hideActionPopupWindow() {
3000            if (mActionPopupShower != null) {
3001                mTextView.removeCallbacks(mActionPopupShower);
3002            }
3003            if (mActionPopupWindow != null) {
3004                mActionPopupWindow.hide();
3005            }
3006        }
3007
3008        public boolean isShowing() {
3009            return mContainer.isShowing();
3010        }
3011
3012        private boolean isVisible() {
3013            // Always show a dragging handle.
3014            if (mIsDragging) {
3015                return true;
3016            }
3017
3018            if (mTextView.isInBatchEditMode()) {
3019                return false;
3020            }
3021
3022            return isPositionVisible(mPositionX + mHotspotX, mPositionY);
3023        }
3024
3025        public abstract int getCurrentCursorOffset();
3026
3027        protected abstract void updateSelection(int offset);
3028
3029        public abstract void updatePosition(float x, float y);
3030
3031        protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
3032            // A HandleView relies on the layout, which may be nulled by external methods
3033            Layout layout = mTextView.getLayout();
3034            if (layout == null) {
3035                // Will update controllers' state, hiding them and stopping selection mode if needed
3036                prepareCursorControllers();
3037                return;
3038            }
3039
3040            boolean offsetChanged = offset != mPreviousOffset;
3041            if (offsetChanged || parentScrolled) {
3042                if (offsetChanged) {
3043                    updateSelection(offset);
3044                    addPositionToTouchUpFilter(offset);
3045                }
3046                final int line = layout.getLineForOffset(offset);
3047
3048                mPositionX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX);
3049                mPositionY = layout.getLineBottom(line);
3050
3051                // Take TextView's padding and scroll into account.
3052                mPositionX += mTextView.viewportToContentHorizontalOffset();
3053                mPositionY += mTextView.viewportToContentVerticalOffset();
3054
3055                mPreviousOffset = offset;
3056                mPositionHasChanged = true;
3057            }
3058        }
3059
3060        public void updatePosition(int parentPositionX, int parentPositionY,
3061                boolean parentPositionChanged, boolean parentScrolled) {
3062            positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled);
3063            if (parentPositionChanged || mPositionHasChanged) {
3064                if (mIsDragging) {
3065                    // Update touchToWindow offset in case of parent scrolling while dragging
3066                    if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
3067                        mTouchToWindowOffsetX += parentPositionX - mLastParentX;
3068                        mTouchToWindowOffsetY += parentPositionY - mLastParentY;
3069                        mLastParentX = parentPositionX;
3070                        mLastParentY = parentPositionY;
3071                    }
3072
3073                    onHandleMoved();
3074                }
3075
3076                if (isVisible()) {
3077                    final int positionX = parentPositionX + mPositionX;
3078                    final int positionY = parentPositionY + mPositionY;
3079                    if (isShowing()) {
3080                        mContainer.update(positionX, positionY, -1, -1);
3081                    } else {
3082                        mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY,
3083                                positionX, positionY);
3084                    }
3085                } else {
3086                    if (isShowing()) {
3087                        dismiss();
3088                    }
3089                }
3090
3091                mPositionHasChanged = false;
3092            }
3093        }
3094
3095        @Override
3096        protected void onDraw(Canvas c) {
3097            mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
3098            mDrawable.draw(c);
3099        }
3100
3101        @Override
3102        public boolean onTouchEvent(MotionEvent ev) {
3103            switch (ev.getActionMasked()) {
3104                case MotionEvent.ACTION_DOWN: {
3105                    startTouchUpFilter(getCurrentCursorOffset());
3106                    mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
3107                    mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
3108
3109                    final PositionListener positionListener = getPositionListener();
3110                    mLastParentX = positionListener.getPositionX();
3111                    mLastParentY = positionListener.getPositionY();
3112                    mIsDragging = true;
3113                    break;
3114                }
3115
3116                case MotionEvent.ACTION_MOVE: {
3117                    final float rawX = ev.getRawX();
3118                    final float rawY = ev.getRawY();
3119
3120                    // Vertical hysteresis: vertical down movement tends to snap to ideal offset
3121                    final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
3122                    final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
3123                    float newVerticalOffset;
3124                    if (previousVerticalOffset < mIdealVerticalOffset) {
3125                        newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
3126                        newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
3127                    } else {
3128                        newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
3129                        newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
3130                    }
3131                    mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
3132
3133                    final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX;
3134                    final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
3135
3136                    updatePosition(newPosX, newPosY);
3137                    break;
3138                }
3139
3140                case MotionEvent.ACTION_UP:
3141                    filterOnTouchUp();
3142                    mIsDragging = false;
3143                    break;
3144
3145                case MotionEvent.ACTION_CANCEL:
3146                    mIsDragging = false;
3147                    break;
3148            }
3149            return true;
3150        }
3151
3152        public boolean isDragging() {
3153            return mIsDragging;
3154        }
3155
3156        void onHandleMoved() {
3157            hideActionPopupWindow();
3158        }
3159
3160        public void onDetached() {
3161            hideActionPopupWindow();
3162        }
3163    }
3164
3165    private class InsertionHandleView extends HandleView {
3166        private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
3167        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
3168
3169        // Used to detect taps on the insertion handle, which will affect the ActionPopupWindow
3170        private float mDownPositionX, mDownPositionY;
3171        private Runnable mHider;
3172
3173        public InsertionHandleView(Drawable drawable) {
3174            super(drawable, drawable);
3175        }
3176
3177        @Override
3178        public void show() {
3179            super.show();
3180
3181            final long durationSinceCutOrCopy =
3182                    SystemClock.uptimeMillis() - TextView.LAST_CUT_OR_COPY_TIME;
3183            if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) {
3184                showActionPopupWindow(0);
3185            }
3186
3187            hideAfterDelay();
3188        }
3189
3190        public void showWithActionPopup() {
3191            show();
3192            showActionPopupWindow(0);
3193        }
3194
3195        private void hideAfterDelay() {
3196            if (mHider == null) {
3197                mHider = new Runnable() {
3198                    public void run() {
3199                        hide();
3200                    }
3201                };
3202            } else {
3203                removeHiderCallback();
3204            }
3205            mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
3206        }
3207
3208        private void removeHiderCallback() {
3209            if (mHider != null) {
3210                mTextView.removeCallbacks(mHider);
3211            }
3212        }
3213
3214        @Override
3215        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
3216            return drawable.getIntrinsicWidth() / 2;
3217        }
3218
3219        @Override
3220        public boolean onTouchEvent(MotionEvent ev) {
3221            final boolean result = super.onTouchEvent(ev);
3222
3223            switch (ev.getActionMasked()) {
3224                case MotionEvent.ACTION_DOWN:
3225                    mDownPositionX = ev.getRawX();
3226                    mDownPositionY = ev.getRawY();
3227                    break;
3228
3229                case MotionEvent.ACTION_UP:
3230                    if (!offsetHasBeenChanged()) {
3231                        final float deltaX = mDownPositionX - ev.getRawX();
3232                        final float deltaY = mDownPositionY - ev.getRawY();
3233                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
3234
3235                        final ViewConfiguration viewConfiguration = ViewConfiguration.get(
3236                                mTextView.getContext());
3237                        final int touchSlop = viewConfiguration.getScaledTouchSlop();
3238
3239                        if (distanceSquared < touchSlop * touchSlop) {
3240                            if (mActionPopupWindow != null && mActionPopupWindow.isShowing()) {
3241                                // Tapping on the handle dismisses the displayed action popup
3242                                mActionPopupWindow.hide();
3243                            } else {
3244                                showWithActionPopup();
3245                            }
3246                        }
3247                    }
3248                    hideAfterDelay();
3249                    break;
3250
3251                case MotionEvent.ACTION_CANCEL:
3252                    hideAfterDelay();
3253                    break;
3254
3255                default:
3256                    break;
3257            }
3258
3259            return result;
3260        }
3261
3262        @Override
3263        public int getCurrentCursorOffset() {
3264            return mTextView.getSelectionStart();
3265        }
3266
3267        @Override
3268        public void updateSelection(int offset) {
3269            Selection.setSelection((Spannable) mTextView.getText(), offset);
3270        }
3271
3272        @Override
3273        public void updatePosition(float x, float y) {
3274            positionAtCursorOffset(mTextView.getOffsetForPosition(x, y), false);
3275        }
3276
3277        @Override
3278        void onHandleMoved() {
3279            super.onHandleMoved();
3280            removeHiderCallback();
3281        }
3282
3283        @Override
3284        public void onDetached() {
3285            super.onDetached();
3286            removeHiderCallback();
3287        }
3288    }
3289
3290    private class SelectionStartHandleView extends HandleView {
3291
3292        public SelectionStartHandleView(Drawable drawableLtr, Drawable drawableRtl) {
3293            super(drawableLtr, drawableRtl);
3294        }
3295
3296        @Override
3297        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
3298            if (isRtlRun) {
3299                return drawable.getIntrinsicWidth() / 4;
3300            } else {
3301                return (drawable.getIntrinsicWidth() * 3) / 4;
3302            }
3303        }
3304
3305        @Override
3306        public int getCurrentCursorOffset() {
3307            return mTextView.getSelectionStart();
3308        }
3309
3310        @Override
3311        public void updateSelection(int offset) {
3312            Selection.setSelection((Spannable) mTextView.getText(), offset,
3313                    mTextView.getSelectionEnd());
3314            updateDrawable();
3315        }
3316
3317        @Override
3318        public void updatePosition(float x, float y) {
3319            int offset = mTextView.getOffsetForPosition(x, y);
3320
3321            // Handles can not cross and selection is at least one character
3322            final int selectionEnd = mTextView.getSelectionEnd();
3323            if (offset >= selectionEnd) offset = Math.max(0, selectionEnd - 1);
3324
3325            positionAtCursorOffset(offset, false);
3326        }
3327
3328        public ActionPopupWindow getActionPopupWindow() {
3329            return mActionPopupWindow;
3330        }
3331    }
3332
3333    private class SelectionEndHandleView extends HandleView {
3334
3335        public SelectionEndHandleView(Drawable drawableLtr, Drawable drawableRtl) {
3336            super(drawableLtr, drawableRtl);
3337        }
3338
3339        @Override
3340        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
3341            if (isRtlRun) {
3342                return (drawable.getIntrinsicWidth() * 3) / 4;
3343            } else {
3344                return drawable.getIntrinsicWidth() / 4;
3345            }
3346        }
3347
3348        @Override
3349        public int getCurrentCursorOffset() {
3350            return mTextView.getSelectionEnd();
3351        }
3352
3353        @Override
3354        public void updateSelection(int offset) {
3355            Selection.setSelection((Spannable) mTextView.getText(),
3356                    mTextView.getSelectionStart(), offset);
3357            updateDrawable();
3358        }
3359
3360        @Override
3361        public void updatePosition(float x, float y) {
3362            int offset = mTextView.getOffsetForPosition(x, y);
3363
3364            // Handles can not cross and selection is at least one character
3365            final int selectionStart = mTextView.getSelectionStart();
3366            if (offset <= selectionStart) {
3367                offset = Math.min(selectionStart + 1, mTextView.getText().length());
3368            }
3369
3370            positionAtCursorOffset(offset, false);
3371        }
3372
3373        public void setActionPopupWindow(ActionPopupWindow actionPopupWindow) {
3374            mActionPopupWindow = actionPopupWindow;
3375        }
3376    }
3377
3378    /**
3379     * A CursorController instance can be used to control a cursor in the text.
3380     */
3381    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
3382        /**
3383         * Makes the cursor controller visible on screen.
3384         * See also {@link #hide()}.
3385         */
3386        public void show();
3387
3388        /**
3389         * Hide the cursor controller from screen.
3390         * See also {@link #show()}.
3391         */
3392        public void hide();
3393
3394        /**
3395         * Called when the view is detached from window. Perform house keeping task, such as
3396         * stopping Runnable thread that would otherwise keep a reference on the context, thus
3397         * preventing the activity from being recycled.
3398         */
3399        public void onDetached();
3400    }
3401
3402    private class InsertionPointCursorController implements CursorController {
3403        private InsertionHandleView mHandle;
3404
3405        public void show() {
3406            getHandle().show();
3407        }
3408
3409        public void showWithActionPopup() {
3410            getHandle().showWithActionPopup();
3411        }
3412
3413        public void hide() {
3414            if (mHandle != null) {
3415                mHandle.hide();
3416            }
3417        }
3418
3419        public void onTouchModeChanged(boolean isInTouchMode) {
3420            if (!isInTouchMode) {
3421                hide();
3422            }
3423        }
3424
3425        private InsertionHandleView getHandle() {
3426            if (mSelectHandleCenter == null) {
3427                mSelectHandleCenter = mTextView.getResources().getDrawable(
3428                        mTextView.mTextSelectHandleRes);
3429            }
3430            if (mHandle == null) {
3431                mHandle = new InsertionHandleView(mSelectHandleCenter);
3432            }
3433            return mHandle;
3434        }
3435
3436        @Override
3437        public void onDetached() {
3438            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
3439            observer.removeOnTouchModeChangeListener(this);
3440
3441            if (mHandle != null) mHandle.onDetached();
3442        }
3443    }
3444
3445    class SelectionModifierCursorController implements CursorController {
3446        private static final int DELAY_BEFORE_REPLACE_ACTION = 200; // milliseconds
3447        // The cursor controller handles, lazily created when shown.
3448        private SelectionStartHandleView mStartHandle;
3449        private SelectionEndHandleView mEndHandle;
3450        // The offsets of that last touch down event. Remembered to start selection there.
3451        private int mMinTouchOffset, mMaxTouchOffset;
3452
3453        // Double tap detection
3454        private long mPreviousTapUpTime = 0;
3455        private float mDownPositionX, mDownPositionY;
3456        private boolean mGestureStayedInTapRegion;
3457
3458        SelectionModifierCursorController() {
3459            resetTouchOffsets();
3460        }
3461
3462        public void show() {
3463            if (mTextView.isInBatchEditMode()) {
3464                return;
3465            }
3466            initDrawables();
3467            initHandles();
3468            hideInsertionPointCursorController();
3469        }
3470
3471        private void initDrawables() {
3472            if (mSelectHandleLeft == null) {
3473                mSelectHandleLeft = mTextView.getContext().getResources().getDrawable(
3474                        mTextView.mTextSelectHandleLeftRes);
3475            }
3476            if (mSelectHandleRight == null) {
3477                mSelectHandleRight = mTextView.getContext().getResources().getDrawable(
3478                        mTextView.mTextSelectHandleRightRes);
3479            }
3480        }
3481
3482        private void initHandles() {
3483            // Lazy object creation has to be done before updatePosition() is called.
3484            if (mStartHandle == null) {
3485                mStartHandle = new SelectionStartHandleView(mSelectHandleLeft, mSelectHandleRight);
3486            }
3487            if (mEndHandle == null) {
3488                mEndHandle = new SelectionEndHandleView(mSelectHandleRight, mSelectHandleLeft);
3489            }
3490
3491            mStartHandle.show();
3492            mEndHandle.show();
3493
3494            // Make sure both left and right handles share the same ActionPopupWindow (so that
3495            // moving any of the handles hides the action popup).
3496            mStartHandle.showActionPopupWindow(DELAY_BEFORE_REPLACE_ACTION);
3497            mEndHandle.setActionPopupWindow(mStartHandle.getActionPopupWindow());
3498
3499            hideInsertionPointCursorController();
3500        }
3501
3502        public void hide() {
3503            if (mStartHandle != null) mStartHandle.hide();
3504            if (mEndHandle != null) mEndHandle.hide();
3505        }
3506
3507        public void onTouchEvent(MotionEvent event) {
3508            // This is done even when the View does not have focus, so that long presses can start
3509            // selection and tap can move cursor from this tap position.
3510            switch (event.getActionMasked()) {
3511                case MotionEvent.ACTION_DOWN:
3512                    final float x = event.getX();
3513                    final float y = event.getY();
3514
3515                    // Remember finger down position, to be able to start selection from there
3516                    mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(x, y);
3517
3518                    // Double tap detection
3519                    if (mGestureStayedInTapRegion) {
3520                        long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime;
3521                        if (duration <= ViewConfiguration.getDoubleTapTimeout()) {
3522                            final float deltaX = x - mDownPositionX;
3523                            final float deltaY = y - mDownPositionY;
3524                            final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
3525
3526                            ViewConfiguration viewConfiguration = ViewConfiguration.get(
3527                                    mTextView.getContext());
3528                            int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop();
3529                            boolean stayedInArea = distanceSquared < doubleTapSlop * doubleTapSlop;
3530
3531                            if (stayedInArea && isPositionOnText(x, y)) {
3532                                startSelectionActionMode();
3533                                mDiscardNextActionUp = true;
3534                            }
3535                        }
3536                    }
3537
3538                    mDownPositionX = x;
3539                    mDownPositionY = y;
3540                    mGestureStayedInTapRegion = true;
3541                    break;
3542
3543                case MotionEvent.ACTION_POINTER_DOWN:
3544                case MotionEvent.ACTION_POINTER_UP:
3545                    // Handle multi-point gestures. Keep min and max offset positions.
3546                    // Only activated for devices that correctly handle multi-touch.
3547                    if (mTextView.getContext().getPackageManager().hasSystemFeature(
3548                            PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
3549                        updateMinAndMaxOffsets(event);
3550                    }
3551                    break;
3552
3553                case MotionEvent.ACTION_MOVE:
3554                    if (mGestureStayedInTapRegion) {
3555                        final float deltaX = event.getX() - mDownPositionX;
3556                        final float deltaY = event.getY() - mDownPositionY;
3557                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
3558
3559                        final ViewConfiguration viewConfiguration = ViewConfiguration.get(
3560                                mTextView.getContext());
3561                        int doubleTapTouchSlop = viewConfiguration.getScaledDoubleTapTouchSlop();
3562
3563                        if (distanceSquared > doubleTapTouchSlop * doubleTapTouchSlop) {
3564                            mGestureStayedInTapRegion = false;
3565                        }
3566                    }
3567                    break;
3568
3569                case MotionEvent.ACTION_UP:
3570                    mPreviousTapUpTime = SystemClock.uptimeMillis();
3571                    break;
3572            }
3573        }
3574
3575        /**
3576         * @param event
3577         */
3578        private void updateMinAndMaxOffsets(MotionEvent event) {
3579            int pointerCount = event.getPointerCount();
3580            for (int index = 0; index < pointerCount; index++) {
3581                int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index));
3582                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
3583                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
3584            }
3585        }
3586
3587        public int getMinTouchOffset() {
3588            return mMinTouchOffset;
3589        }
3590
3591        public int getMaxTouchOffset() {
3592            return mMaxTouchOffset;
3593        }
3594
3595        public void resetTouchOffsets() {
3596            mMinTouchOffset = mMaxTouchOffset = -1;
3597        }
3598
3599        /**
3600         * @return true iff this controller is currently used to move the selection start.
3601         */
3602        public boolean isSelectionStartDragged() {
3603            return mStartHandle != null && mStartHandle.isDragging();
3604        }
3605
3606        public void onTouchModeChanged(boolean isInTouchMode) {
3607            if (!isInTouchMode) {
3608                hide();
3609            }
3610        }
3611
3612        @Override
3613        public void onDetached() {
3614            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
3615            observer.removeOnTouchModeChangeListener(this);
3616
3617            if (mStartHandle != null) mStartHandle.onDetached();
3618            if (mEndHandle != null) mEndHandle.onDetached();
3619        }
3620    }
3621
3622    private class CorrectionHighlighter {
3623        private final Path mPath = new Path();
3624        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
3625        private int mStart, mEnd;
3626        private long mFadingStartTime;
3627        private RectF mTempRectF;
3628        private final static int FADE_OUT_DURATION = 400;
3629
3630        public CorrectionHighlighter() {
3631            mPaint.setCompatibilityScaling(mTextView.getResources().getCompatibilityInfo().
3632                    applicationScale);
3633            mPaint.setStyle(Paint.Style.FILL);
3634        }
3635
3636        public void highlight(CorrectionInfo info) {
3637            mStart = info.getOffset();
3638            mEnd = mStart + info.getNewText().length();
3639            mFadingStartTime = SystemClock.uptimeMillis();
3640
3641            if (mStart < 0 || mEnd < 0) {
3642                stopAnimation();
3643            }
3644        }
3645
3646        public void draw(Canvas canvas, int cursorOffsetVertical) {
3647            if (updatePath() && updatePaint()) {
3648                if (cursorOffsetVertical != 0) {
3649                    canvas.translate(0, cursorOffsetVertical);
3650                }
3651
3652                canvas.drawPath(mPath, mPaint);
3653
3654                if (cursorOffsetVertical != 0) {
3655                    canvas.translate(0, -cursorOffsetVertical);
3656                }
3657                invalidate(true); // TODO invalidate cursor region only
3658            } else {
3659                stopAnimation();
3660                invalidate(false); // TODO invalidate cursor region only
3661            }
3662        }
3663
3664        private boolean updatePaint() {
3665            final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
3666            if (duration > FADE_OUT_DURATION) return false;
3667
3668            final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
3669            final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor);
3670            final int color = (mTextView.mHighlightColor & 0x00FFFFFF) +
3671                    ((int) (highlightColorAlpha * coef) << 24);
3672            mPaint.setColor(color);
3673            return true;
3674        }
3675
3676        private boolean updatePath() {
3677            final Layout layout = mTextView.getLayout();
3678            if (layout == null) return false;
3679
3680            // Update in case text is edited while the animation is run
3681            final int length = mTextView.getText().length();
3682            int start = Math.min(length, mStart);
3683            int end = Math.min(length, mEnd);
3684
3685            mPath.reset();
3686            layout.getSelectionPath(start, end, mPath);
3687            return true;
3688        }
3689
3690        private void invalidate(boolean delayed) {
3691            if (mTextView.getLayout() == null) return;
3692
3693            if (mTempRectF == null) mTempRectF = new RectF();
3694            mPath.computeBounds(mTempRectF, false);
3695
3696            int left = mTextView.getCompoundPaddingLeft();
3697            int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true);
3698
3699            if (delayed) {
3700                mTextView.postInvalidateOnAnimation(
3701                        left + (int) mTempRectF.left, top + (int) mTempRectF.top,
3702                        left + (int) mTempRectF.right, top + (int) mTempRectF.bottom);
3703            } else {
3704                mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top,
3705                        (int) mTempRectF.right, (int) mTempRectF.bottom);
3706            }
3707        }
3708
3709        private void stopAnimation() {
3710            Editor.this.mCorrectionHighlighter = null;
3711        }
3712    }
3713
3714    private static class ErrorPopup extends PopupWindow {
3715        private boolean mAbove = false;
3716        private final TextView mView;
3717        private int mPopupInlineErrorBackgroundId = 0;
3718        private int mPopupInlineErrorAboveBackgroundId = 0;
3719
3720        ErrorPopup(TextView v, int width, int height) {
3721            super(v, width, height);
3722            mView = v;
3723            // Make sure the TextView has a background set as it will be used the first time it is
3724            // shown and positionned. Initialized with below background, which should have
3725            // dimensions identical to the above version for this to work (and is more likely).
3726            mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
3727                    com.android.internal.R.styleable.Theme_errorMessageBackground);
3728            mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
3729        }
3730
3731        void fixDirection(boolean above) {
3732            mAbove = above;
3733
3734            if (above) {
3735                mPopupInlineErrorAboveBackgroundId =
3736                    getResourceId(mPopupInlineErrorAboveBackgroundId,
3737                            com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
3738            } else {
3739                mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
3740                        com.android.internal.R.styleable.Theme_errorMessageBackground);
3741            }
3742
3743            mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId :
3744                mPopupInlineErrorBackgroundId);
3745        }
3746
3747        private int getResourceId(int currentId, int index) {
3748            if (currentId == 0) {
3749                TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
3750                        R.styleable.Theme);
3751                currentId = styledAttributes.getResourceId(index, 0);
3752                styledAttributes.recycle();
3753            }
3754            return currentId;
3755        }
3756
3757        @Override
3758        public void update(int x, int y, int w, int h, boolean force) {
3759            super.update(x, y, w, h, force);
3760
3761            boolean above = isAboveAnchor();
3762            if (above != mAbove) {
3763                fixDirection(above);
3764            }
3765        }
3766    }
3767
3768    static class InputContentType {
3769        int imeOptions = EditorInfo.IME_NULL;
3770        String privateImeOptions;
3771        CharSequence imeActionLabel;
3772        int imeActionId;
3773        Bundle extras;
3774        OnEditorActionListener onEditorActionListener;
3775        boolean enterDown;
3776    }
3777
3778    static class InputMethodState {
3779        Rect mCursorRectInWindow = new Rect();
3780        RectF mTmpRectF = new RectF();
3781        float[] mTmpOffset = new float[2];
3782        ExtractedTextRequest mExtracting;
3783        final ExtractedText mTmpExtracted = new ExtractedText();
3784        int mBatchEditNesting;
3785        boolean mCursorChanged;
3786        boolean mSelectionModeChanged;
3787        boolean mContentChanged;
3788        int mChangedStart, mChangedEnd, mChangedDelta;
3789    }
3790}
3791