Editor.java revision ebc86af1dc186c77f723c8970951e8ff00b4866b
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        final int height = mTextView.getHeight();
1229
1230        final long lineRange = layout.getLineRangeForDraw(canvas);
1231        int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
1232        int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
1233        if (lastLine < 0) return;
1234
1235        layout.drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
1236                firstLine, lastLine);
1237
1238        if (layout instanceof DynamicLayout) {
1239            if (mTextDisplayLists == null) {
1240                mTextDisplayLists = new DisplayList[ArrayUtils.idealObjectArraySize(0)];
1241            }
1242
1243            DynamicLayout dynamicLayout = (DynamicLayout) layout;
1244            int[] blockEndLines = dynamicLayout.getBlockEndLines();
1245            int[] blockIndices = dynamicLayout.getBlockIndices();
1246            final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
1247
1248            int endOfPreviousBlock = -1;
1249            int searchStartIndex = 0;
1250            for (int i = 0; i < numberOfBlocks; i++) {
1251                int blockEndLine = blockEndLines[i];
1252                int blockIndex = blockIndices[i];
1253
1254                final boolean blockIsInvalid = blockIndex == DynamicLayout.INVALID_BLOCK_INDEX;
1255                if (blockIsInvalid) {
1256                    blockIndex = getAvailableDisplayListIndex(blockIndices, numberOfBlocks,
1257                            searchStartIndex);
1258                    // Note how dynamic layout's internal block indices get updated from Editor
1259                    blockIndices[i] = blockIndex;
1260                    searchStartIndex = blockIndex + 1;
1261                }
1262
1263                DisplayList blockDisplayList = mTextDisplayLists[blockIndex];
1264                if (blockDisplayList == null) {
1265                    blockDisplayList = mTextDisplayLists[blockIndex] =
1266                            mTextView.getHardwareRenderer().createDisplayList("Text " + blockIndex);
1267                } else {
1268                    if (blockIsInvalid) blockDisplayList.invalidate();
1269                }
1270
1271                if (!blockDisplayList.isValid()) {
1272                    final int blockBeginLine = endOfPreviousBlock + 1;
1273                    final int top = layout.getLineTop(blockBeginLine);
1274                    final int bottom = layout.getLineBottom(blockEndLine);
1275
1276                    final HardwareCanvas hardwareCanvas = blockDisplayList.start();
1277                    try {
1278                        hardwareCanvas.setViewport(width, bottom - top);
1279                        // The dirty rect should always be null for a display list
1280                        hardwareCanvas.onPreDraw(null);
1281                        // drawText is always relative to TextView's origin, this translation brings
1282                        // this range of text back to the top of the viewport
1283                        hardwareCanvas.translate(0, -top);
1284                        layout.drawText(hardwareCanvas, blockBeginLine, blockEndLine);
1285                        hardwareCanvas.translate(0, top);
1286                    } finally {
1287                        hardwareCanvas.onPostDraw();
1288                        blockDisplayList.end();
1289                        if (View.USE_DISPLAY_LIST_PROPERTIES) {
1290                            blockDisplayList.setLeftTopRightBottom(0, top, width, bottom);
1291                            // Same as drawDisplayList below, handled by our TextView's parent
1292                            blockDisplayList.setClipChildren(false);
1293                        }
1294                    }
1295                }
1296
1297                // TODO When View.USE_DISPLAY_LIST_PROPERTIES is the only code path, the
1298                // width and height parameters should be removed and the bounds set above in
1299                // setLeftTopRightBottom should be used instead for quick rejection.
1300                ((HardwareCanvas) canvas).drawDisplayList(blockDisplayList, width, height, null,
1301                        0 /* no child clipping, our TextView parent enforces it */);
1302                endOfPreviousBlock = blockEndLine;
1303            }
1304        } else {
1305            // Boring layout is used for empty and hint text
1306            layout.drawText(canvas, firstLine, lastLine);
1307        }
1308    }
1309
1310    private int getAvailableDisplayListIndex(int[] blockIndices, int numberOfBlocks,
1311            int searchStartIndex) {
1312        int length = mTextDisplayLists.length;
1313        for (int i = searchStartIndex; i < length; i++) {
1314            boolean blockIndexFound = false;
1315            for (int j = 0; j < numberOfBlocks; j++) {
1316                if (blockIndices[j] == i) {
1317                    blockIndexFound = true;
1318                    break;
1319                }
1320            }
1321            if (blockIndexFound) continue;
1322            return i;
1323        }
1324
1325        // No available index found, the pool has to grow
1326        int newSize = ArrayUtils.idealIntArraySize(length + 1);
1327        DisplayList[] displayLists = new DisplayList[newSize];
1328        System.arraycopy(mTextDisplayLists, 0, displayLists, 0, length);
1329        mTextDisplayLists = displayLists;
1330        return length;
1331    }
1332
1333    private void drawCursor(Canvas canvas, int cursorOffsetVertical) {
1334        final boolean translate = cursorOffsetVertical != 0;
1335        if (translate) canvas.translate(0, cursorOffsetVertical);
1336        for (int i = 0; i < mCursorCount; i++) {
1337            mCursorDrawable[i].draw(canvas);
1338        }
1339        if (translate) canvas.translate(0, -cursorOffsetVertical);
1340    }
1341
1342    /**
1343     * Invalidates all the sub-display lists that overlap the specified character range
1344     */
1345    void invalidateTextDisplayList(Layout layout, int start, int end) {
1346        if (mTextDisplayLists != null && layout instanceof DynamicLayout) {
1347            final int firstLine = layout.getLineForOffset(start);
1348            final int lastLine = layout.getLineForOffset(end);
1349
1350            DynamicLayout dynamicLayout = (DynamicLayout) layout;
1351            int[] blockEndLines = dynamicLayout.getBlockEndLines();
1352            int[] blockIndices = dynamicLayout.getBlockIndices();
1353            final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
1354
1355            int i = 0;
1356            // Skip the blocks before firstLine
1357            while (i < numberOfBlocks) {
1358                if (blockEndLines[i] >= firstLine) break;
1359                i++;
1360            }
1361
1362            // Invalidate all subsequent blocks until lastLine is passed
1363            while (i < numberOfBlocks) {
1364                final int blockIndex = blockIndices[i];
1365                if (blockIndex != DynamicLayout.INVALID_BLOCK_INDEX) {
1366                    mTextDisplayLists[blockIndex].invalidate();
1367                }
1368                if (blockEndLines[i] >= lastLine) break;
1369                i++;
1370            }
1371        }
1372    }
1373
1374    void invalidateTextDisplayList() {
1375        if (mTextDisplayLists != null) {
1376            for (int i = 0; i < mTextDisplayLists.length; i++) {
1377                if (mTextDisplayLists[i] != null) mTextDisplayLists[i].invalidate();
1378            }
1379        }
1380    }
1381
1382    void updateCursorsPositions() {
1383        if (mTextView.mCursorDrawableRes == 0) {
1384            mCursorCount = 0;
1385            return;
1386        }
1387
1388        Layout layout = mTextView.getLayout();
1389        final int offset = mTextView.getSelectionStart();
1390        final int line = layout.getLineForOffset(offset);
1391        final int top = layout.getLineTop(line);
1392        final int bottom = layout.getLineTop(line + 1);
1393
1394        mCursorCount = layout.isLevelBoundary(offset) ? 2 : 1;
1395
1396        int middle = bottom;
1397        if (mCursorCount == 2) {
1398            // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)}
1399            middle = (top + bottom) >> 1;
1400        }
1401
1402        updateCursorPosition(0, top, middle, layout.getPrimaryHorizontal(offset));
1403
1404        if (mCursorCount == 2) {
1405            updateCursorPosition(1, middle, bottom, layout.getSecondaryHorizontal(offset));
1406        }
1407    }
1408
1409    /**
1410     * @return true if the selection mode was actually started.
1411     */
1412    boolean startSelectionActionMode() {
1413        if (mSelectionActionMode != null) {
1414            // Selection action mode is already started
1415            return false;
1416        }
1417
1418        if (!canSelectText() || !mTextView.requestFocus()) {
1419            Log.w(TextView.LOG_TAG,
1420                    "TextView does not support text selection. Action mode cancelled.");
1421            return false;
1422        }
1423
1424        if (!mTextView.hasSelection()) {
1425            // There may already be a selection on device rotation
1426            if (!selectCurrentWord()) {
1427                // No word found under cursor or text selection not permitted.
1428                return false;
1429            }
1430        }
1431
1432        boolean willExtract = extractedTextModeWillBeStarted();
1433
1434        // Do not start the action mode when extracted text will show up full screen, which would
1435        // immediately hide the newly created action bar and would be visually distracting.
1436        if (!willExtract) {
1437            ActionMode.Callback actionModeCallback = new SelectionActionModeCallback();
1438            mSelectionActionMode = mTextView.startActionMode(actionModeCallback);
1439        }
1440
1441        final boolean selectionStarted = mSelectionActionMode != null || willExtract;
1442        if (selectionStarted && !mTextView.isTextSelectable()) {
1443            // Show the IME to be able to replace text, except when selecting non editable text.
1444            final InputMethodManager imm = InputMethodManager.peekInstance();
1445            if (imm != null) {
1446                imm.showSoftInput(mTextView, 0, null);
1447            }
1448        }
1449
1450        return selectionStarted;
1451    }
1452
1453    private boolean extractedTextModeWillBeStarted() {
1454        if (!(mTextView instanceof ExtractEditText)) {
1455            final InputMethodManager imm = InputMethodManager.peekInstance();
1456            return  imm != null && imm.isFullscreenMode();
1457        }
1458        return false;
1459    }
1460
1461    /**
1462     * @return <code>true</code> if the cursor/current selection overlaps a {@link SuggestionSpan}.
1463     */
1464    private boolean isCursorInsideSuggestionSpan() {
1465        CharSequence text = mTextView.getText();
1466        if (!(text instanceof Spannable)) return false;
1467
1468        SuggestionSpan[] suggestionSpans = ((Spannable) text).getSpans(
1469                mTextView.getSelectionStart(), mTextView.getSelectionEnd(), SuggestionSpan.class);
1470        return (suggestionSpans.length > 0);
1471    }
1472
1473    /**
1474     * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with
1475     * {@link SuggestionSpan#FLAG_EASY_CORRECT} set.
1476     */
1477    private boolean isCursorInsideEasyCorrectionSpan() {
1478        Spannable spannable = (Spannable) mTextView.getText();
1479        SuggestionSpan[] suggestionSpans = spannable.getSpans(mTextView.getSelectionStart(),
1480                mTextView.getSelectionEnd(), SuggestionSpan.class);
1481        for (int i = 0; i < suggestionSpans.length; i++) {
1482            if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) {
1483                return true;
1484            }
1485        }
1486        return false;
1487    }
1488
1489    void onTouchUpEvent(MotionEvent event) {
1490        boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect();
1491        hideControllers();
1492        CharSequence text = mTextView.getText();
1493        if (!selectAllGotFocus && text.length() > 0) {
1494            // Move cursor
1495            final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
1496            Selection.setSelection((Spannable) text, offset);
1497            if (mSpellChecker != null) {
1498                // When the cursor moves, the word that was typed may need spell check
1499                mSpellChecker.onSelectionChanged();
1500            }
1501            if (!extractedTextModeWillBeStarted()) {
1502                if (isCursorInsideEasyCorrectionSpan()) {
1503                    mShowSuggestionRunnable = new Runnable() {
1504                        public void run() {
1505                            showSuggestions();
1506                        }
1507                    };
1508                    // removeCallbacks is performed on every touch
1509                    mTextView.postDelayed(mShowSuggestionRunnable,
1510                            ViewConfiguration.getDoubleTapTimeout());
1511                } else if (hasInsertionController()) {
1512                    getInsertionController().show();
1513                }
1514            }
1515        }
1516    }
1517
1518    protected void stopSelectionActionMode() {
1519        if (mSelectionActionMode != null) {
1520            // This will hide the mSelectionModifierCursorController
1521            mSelectionActionMode.finish();
1522        }
1523    }
1524
1525    /**
1526     * @return True if this view supports insertion handles.
1527     */
1528    boolean hasInsertionController() {
1529        return mInsertionControllerEnabled;
1530    }
1531
1532    /**
1533     * @return True if this view supports selection handles.
1534     */
1535    boolean hasSelectionController() {
1536        return mSelectionControllerEnabled;
1537    }
1538
1539    InsertionPointCursorController getInsertionController() {
1540        if (!mInsertionControllerEnabled) {
1541            return null;
1542        }
1543
1544        if (mInsertionPointCursorController == null) {
1545            mInsertionPointCursorController = new InsertionPointCursorController();
1546
1547            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
1548            observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
1549        }
1550
1551        return mInsertionPointCursorController;
1552    }
1553
1554    SelectionModifierCursorController getSelectionController() {
1555        if (!mSelectionControllerEnabled) {
1556            return null;
1557        }
1558
1559        if (mSelectionModifierCursorController == null) {
1560            mSelectionModifierCursorController = new SelectionModifierCursorController();
1561
1562            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
1563            observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
1564        }
1565
1566        return mSelectionModifierCursorController;
1567    }
1568
1569    private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) {
1570        if (mCursorDrawable[cursorIndex] == null)
1571            mCursorDrawable[cursorIndex] = mTextView.getResources().getDrawable(
1572                    mTextView.mCursorDrawableRes);
1573
1574        if (mTempRect == null) mTempRect = new Rect();
1575        mCursorDrawable[cursorIndex].getPadding(mTempRect);
1576        final int width = mCursorDrawable[cursorIndex].getIntrinsicWidth();
1577        horizontal = Math.max(0.5f, horizontal - 0.5f);
1578        final int left = (int) (horizontal) - mTempRect.left;
1579        mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width,
1580                bottom + mTempRect.bottom);
1581    }
1582
1583    /**
1584     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
1585     * a dictionnary) from the current input method, provided by it calling
1586     * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
1587     * implementation flashes the background of the corrected word to provide feedback to the user.
1588     *
1589     * @param info The auto correct info about the text that was corrected.
1590     */
1591    public void onCommitCorrection(CorrectionInfo info) {
1592        if (mCorrectionHighlighter == null) {
1593            mCorrectionHighlighter = new CorrectionHighlighter();
1594        } else {
1595            mCorrectionHighlighter.invalidate(false);
1596        }
1597
1598        mCorrectionHighlighter.highlight(info);
1599    }
1600
1601    void showSuggestions() {
1602        if (mSuggestionsPopupWindow == null) {
1603            mSuggestionsPopupWindow = new SuggestionsPopupWindow();
1604        }
1605        hideControllers();
1606        mSuggestionsPopupWindow.show();
1607    }
1608
1609    boolean areSuggestionsShown() {
1610        return mSuggestionsPopupWindow != null && mSuggestionsPopupWindow.isShowing();
1611    }
1612
1613    void onScrollChanged() {
1614        if (mPositionListener != null) {
1615            mPositionListener.onScrollChanged();
1616        }
1617    }
1618
1619    /**
1620     * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
1621     */
1622    private boolean shouldBlink() {
1623        if (!isCursorVisible() || !mTextView.isFocused()) return false;
1624
1625        final int start = mTextView.getSelectionStart();
1626        if (start < 0) return false;
1627
1628        final int end = mTextView.getSelectionEnd();
1629        if (end < 0) return false;
1630
1631        return start == end;
1632    }
1633
1634    void makeBlink() {
1635        if (shouldBlink()) {
1636            mShowCursor = SystemClock.uptimeMillis();
1637            if (mBlink == null) mBlink = new Blink();
1638            mBlink.removeCallbacks(mBlink);
1639            mBlink.postAtTime(mBlink, mShowCursor + BLINK);
1640        } else {
1641            if (mBlink != null) mBlink.removeCallbacks(mBlink);
1642        }
1643    }
1644
1645    private class Blink extends Handler implements Runnable {
1646        private boolean mCancelled;
1647
1648        public void run() {
1649            if (mCancelled) {
1650                return;
1651            }
1652
1653            removeCallbacks(Blink.this);
1654
1655            if (shouldBlink()) {
1656                if (mTextView.getLayout() != null) {
1657                    mTextView.invalidateCursorPath();
1658                }
1659
1660                postAtTime(this, SystemClock.uptimeMillis() + BLINK);
1661            }
1662        }
1663
1664        void cancel() {
1665            if (!mCancelled) {
1666                removeCallbacks(Blink.this);
1667                mCancelled = true;
1668            }
1669        }
1670
1671        void uncancel() {
1672            mCancelled = false;
1673        }
1674    }
1675
1676    private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) {
1677        TextView shadowView = (TextView) View.inflate(mTextView.getContext(),
1678                com.android.internal.R.layout.text_drag_thumbnail, null);
1679
1680        if (shadowView == null) {
1681            throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
1682        }
1683
1684        if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) {
1685            text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH);
1686        }
1687        shadowView.setText(text);
1688        shadowView.setTextColor(mTextView.getTextColors());
1689
1690        shadowView.setTextAppearance(mTextView.getContext(), R.styleable.Theme_textAppearanceLarge);
1691        shadowView.setGravity(Gravity.CENTER);
1692
1693        shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
1694                ViewGroup.LayoutParams.WRAP_CONTENT));
1695
1696        final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
1697        shadowView.measure(size, size);
1698
1699        shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
1700        shadowView.invalidate();
1701        return new DragShadowBuilder(shadowView);
1702    }
1703
1704    private static class DragLocalState {
1705        public TextView sourceTextView;
1706        public int start, end;
1707
1708        public DragLocalState(TextView sourceTextView, int start, int end) {
1709            this.sourceTextView = sourceTextView;
1710            this.start = start;
1711            this.end = end;
1712        }
1713    }
1714
1715    void onDrop(DragEvent event) {
1716        StringBuilder content = new StringBuilder("");
1717        ClipData clipData = event.getClipData();
1718        final int itemCount = clipData.getItemCount();
1719        for (int i=0; i < itemCount; i++) {
1720            Item item = clipData.getItemAt(i);
1721            content.append(item.coerceToStyledText(mTextView.getContext()));
1722        }
1723
1724        final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
1725
1726        Object localState = event.getLocalState();
1727        DragLocalState dragLocalState = null;
1728        if (localState instanceof DragLocalState) {
1729            dragLocalState = (DragLocalState) localState;
1730        }
1731        boolean dragDropIntoItself = dragLocalState != null &&
1732                dragLocalState.sourceTextView == mTextView;
1733
1734        if (dragDropIntoItself) {
1735            if (offset >= dragLocalState.start && offset < dragLocalState.end) {
1736                // A drop inside the original selection discards the drop.
1737                return;
1738            }
1739        }
1740
1741        final int originalLength = mTextView.getText().length();
1742        long minMax = mTextView.prepareSpacesAroundPaste(offset, offset, content);
1743        int min = TextUtils.unpackRangeStartFromLong(minMax);
1744        int max = TextUtils.unpackRangeEndFromLong(minMax);
1745
1746        Selection.setSelection((Spannable) mTextView.getText(), max);
1747        mTextView.replaceText_internal(min, max, content);
1748
1749        if (dragDropIntoItself) {
1750            int dragSourceStart = dragLocalState.start;
1751            int dragSourceEnd = dragLocalState.end;
1752            if (max <= dragSourceStart) {
1753                // Inserting text before selection has shifted positions
1754                final int shift = mTextView.getText().length() - originalLength;
1755                dragSourceStart += shift;
1756                dragSourceEnd += shift;
1757            }
1758
1759            // Delete original selection
1760            mTextView.deleteText_internal(dragSourceStart, dragSourceEnd);
1761
1762            // Make sure we do not leave two adjacent spaces.
1763            CharSequence t = mTextView.getTransformedText(dragSourceStart - 1, dragSourceStart + 1);
1764            if ( (dragSourceStart == 0 || Character.isSpaceChar(t.charAt(0))) &&
1765                    (dragSourceStart == mTextView.getText().length() ||
1766                    Character.isSpaceChar(t.charAt(1))) ) {
1767                final int pos = dragSourceStart == mTextView.getText().length() ?
1768                        dragSourceStart - 1 : dragSourceStart;
1769                mTextView.deleteText_internal(pos, pos + 1);
1770            }
1771        }
1772    }
1773
1774    /**
1775     * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related
1776     * pop-up should be displayed.
1777     */
1778    class EasyEditSpanController implements TextWatcher {
1779
1780        private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs
1781
1782        private EasyEditPopupWindow mPopupWindow;
1783
1784        private EasyEditSpan mEasyEditSpan;
1785
1786        private Runnable mHidePopup;
1787
1788        public void hide() {
1789            if (mPopupWindow != null) {
1790                mPopupWindow.hide();
1791                mTextView.removeCallbacks(mHidePopup);
1792            }
1793            removeSpans(mTextView.getText());
1794            mEasyEditSpan = null;
1795        }
1796
1797        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1798            // Intentionally empty
1799        }
1800
1801        public void afterTextChanged(Editable s) {
1802            // Intentionally empty
1803        }
1804
1805        /**
1806         * Monitors the changes in the text.
1807         *
1808         * <p>{@link SpanWatcher#onSpanAdded(Spannable, Object, int, int)} cannot be used,
1809         * as the notifications are not sent when a spannable (with spans) is inserted.
1810         */
1811        public void onTextChanged(CharSequence buffer, int start, int before, int after) {
1812            adjustSpans(buffer, start, after);
1813
1814            if (mTextView.getWindowVisibility() != View.VISIBLE) {
1815                // The window is not visible yet, ignore the text change.
1816                return;
1817            }
1818
1819            if (mTextView.getLayout() == null) {
1820                // The view has not been layout yet, ignore the text change
1821                return;
1822            }
1823
1824            InputMethodManager imm = InputMethodManager.peekInstance();
1825            if (!(mTextView instanceof ExtractEditText) && imm != null && imm.isFullscreenMode()) {
1826                // The input is in extract mode. We do not have to handle the easy edit in the
1827                // original TextView, as the ExtractEditText will do
1828                return;
1829            }
1830
1831            // Remove the current easy edit span, as the text changed, and remove the pop-up
1832            // (if any)
1833            if (mEasyEditSpan != null) {
1834                if (buffer instanceof Spannable) {
1835                    ((Spannable) buffer).removeSpan(mEasyEditSpan);
1836                }
1837                mEasyEditSpan = null;
1838            }
1839            if (mPopupWindow != null && mPopupWindow.isShowing()) {
1840                mPopupWindow.hide();
1841            }
1842
1843            // Display the new easy edit span (if any).
1844            if (buffer instanceof Spanned) {
1845                mEasyEditSpan = getSpan((Spanned) buffer);
1846                if (mEasyEditSpan != null) {
1847                    if (mPopupWindow == null) {
1848                        mPopupWindow = new EasyEditPopupWindow();
1849                        mHidePopup = new Runnable() {
1850                            @Override
1851                            public void run() {
1852                                hide();
1853                            }
1854                        };
1855                    }
1856                    mPopupWindow.show(mEasyEditSpan);
1857                    mTextView.removeCallbacks(mHidePopup);
1858                    mTextView.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS);
1859                }
1860            }
1861        }
1862
1863        /**
1864         * Adjusts the spans by removing all of them except the last one.
1865         */
1866        private void adjustSpans(CharSequence buffer, int start, int after) {
1867            // This method enforces that only one easy edit span is attached to the text.
1868            // A better way to enforce this would be to listen for onSpanAdded, but this method
1869            // cannot be used in this scenario as no notification is triggered when a text with
1870            // spans is inserted into a text.
1871            if (buffer instanceof Spannable) {
1872                Spannable spannable = (Spannable) buffer;
1873                EasyEditSpan[] spans = spannable.getSpans(start, start + after, EasyEditSpan.class);
1874                if (spans.length > 0) {
1875                    // Assuming there was only one EasyEditSpan before, we only need check to
1876                    // check for a duplicate if a new one is found in the modified interval
1877                    spans = spannable.getSpans(0, spannable.length(),  EasyEditSpan.class);
1878                    for (int i = 1; i < spans.length; i++) {
1879                        spannable.removeSpan(spans[i]);
1880                    }
1881                }
1882            }
1883        }
1884
1885        /**
1886         * Removes all the {@link EasyEditSpan} currently attached.
1887         */
1888        private void removeSpans(CharSequence buffer) {
1889            if (buffer instanceof Spannable) {
1890                Spannable spannable = (Spannable) buffer;
1891                EasyEditSpan[] spans = spannable.getSpans(0, spannable.length(),
1892                        EasyEditSpan.class);
1893                for (int i = 0; i < spans.length; i++) {
1894                    spannable.removeSpan(spans[i]);
1895                }
1896            }
1897        }
1898
1899        private EasyEditSpan getSpan(Spanned spanned) {
1900            EasyEditSpan[] easyEditSpans = spanned.getSpans(0, spanned.length(),
1901                    EasyEditSpan.class);
1902            if (easyEditSpans.length == 0) {
1903                return null;
1904            } else {
1905                return easyEditSpans[0];
1906            }
1907        }
1908    }
1909
1910    /**
1911     * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled
1912     * by {@link EasyEditSpanController}.
1913     */
1914    private class EasyEditPopupWindow extends PinnedPopupWindow
1915            implements OnClickListener {
1916        private static final int POPUP_TEXT_LAYOUT =
1917                com.android.internal.R.layout.text_edit_action_popup_text;
1918        private TextView mDeleteTextView;
1919        private EasyEditSpan mEasyEditSpan;
1920
1921        @Override
1922        protected void createPopupWindow() {
1923            mPopupWindow = new PopupWindow(mTextView.getContext(), null,
1924                    com.android.internal.R.attr.textSelectHandleWindowStyle);
1925            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
1926            mPopupWindow.setClippingEnabled(true);
1927        }
1928
1929        @Override
1930        protected void initContentView() {
1931            LinearLayout linearLayout = new LinearLayout(mTextView.getContext());
1932            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
1933            mContentView = linearLayout;
1934            mContentView.setBackgroundResource(
1935                    com.android.internal.R.drawable.text_edit_side_paste_window);
1936
1937            LayoutInflater inflater = (LayoutInflater)mTextView.getContext().
1938                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
1939
1940            LayoutParams wrapContent = new LayoutParams(
1941                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
1942
1943            mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
1944            mDeleteTextView.setLayoutParams(wrapContent);
1945            mDeleteTextView.setText(com.android.internal.R.string.delete);
1946            mDeleteTextView.setOnClickListener(this);
1947            mContentView.addView(mDeleteTextView);
1948        }
1949
1950        public void show(EasyEditSpan easyEditSpan) {
1951            mEasyEditSpan = easyEditSpan;
1952            super.show();
1953        }
1954
1955        @Override
1956        public void onClick(View view) {
1957            if (view == mDeleteTextView) {
1958                Editable editable = (Editable) mTextView.getText();
1959                int start = editable.getSpanStart(mEasyEditSpan);
1960                int end = editable.getSpanEnd(mEasyEditSpan);
1961                if (start >= 0 && end >= 0) {
1962                    mTextView.deleteText_internal(start, end);
1963                }
1964            }
1965        }
1966
1967        @Override
1968        protected int getTextOffset() {
1969            // Place the pop-up at the end of the span
1970            Editable editable = (Editable) mTextView.getText();
1971            return editable.getSpanEnd(mEasyEditSpan);
1972        }
1973
1974        @Override
1975        protected int getVerticalLocalPosition(int line) {
1976            return mTextView.getLayout().getLineBottom(line);
1977        }
1978
1979        @Override
1980        protected int clipVertically(int positionY) {
1981            // As we display the pop-up below the span, no vertical clipping is required.
1982            return positionY;
1983        }
1984    }
1985
1986    private class PositionListener implements ViewTreeObserver.OnPreDrawListener {
1987        // 3 handles
1988        // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others)
1989        private final int MAXIMUM_NUMBER_OF_LISTENERS = 6;
1990        private TextViewPositionListener[] mPositionListeners =
1991                new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS];
1992        private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS];
1993        private boolean mPositionHasChanged = true;
1994        // Absolute position of the TextView with respect to its parent window
1995        private int mPositionX, mPositionY;
1996        private int mNumberOfListeners;
1997        private boolean mScrollHasChanged;
1998        final int[] mTempCoords = new int[2];
1999
2000        public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) {
2001            if (mNumberOfListeners == 0) {
2002                updatePosition();
2003                ViewTreeObserver vto = mTextView.getViewTreeObserver();
2004                vto.addOnPreDrawListener(this);
2005            }
2006
2007            int emptySlotIndex = -1;
2008            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2009                TextViewPositionListener listener = mPositionListeners[i];
2010                if (listener == positionListener) {
2011                    return;
2012                } else if (emptySlotIndex < 0 && listener == null) {
2013                    emptySlotIndex = i;
2014                }
2015            }
2016
2017            mPositionListeners[emptySlotIndex] = positionListener;
2018            mCanMove[emptySlotIndex] = canMove;
2019            mNumberOfListeners++;
2020        }
2021
2022        public void removeSubscriber(TextViewPositionListener positionListener) {
2023            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2024                if (mPositionListeners[i] == positionListener) {
2025                    mPositionListeners[i] = null;
2026                    mNumberOfListeners--;
2027                    break;
2028                }
2029            }
2030
2031            if (mNumberOfListeners == 0) {
2032                ViewTreeObserver vto = mTextView.getViewTreeObserver();
2033                vto.removeOnPreDrawListener(this);
2034            }
2035        }
2036
2037        public int getPositionX() {
2038            return mPositionX;
2039        }
2040
2041        public int getPositionY() {
2042            return mPositionY;
2043        }
2044
2045        @Override
2046        public boolean onPreDraw() {
2047            updatePosition();
2048
2049            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2050                if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) {
2051                    TextViewPositionListener positionListener = mPositionListeners[i];
2052                    if (positionListener != null) {
2053                        positionListener.updatePosition(mPositionX, mPositionY,
2054                                mPositionHasChanged, mScrollHasChanged);
2055                    }
2056                }
2057            }
2058
2059            mScrollHasChanged = false;
2060            return true;
2061        }
2062
2063        private void updatePosition() {
2064            mTextView.getLocationInWindow(mTempCoords);
2065
2066            mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY;
2067
2068            mPositionX = mTempCoords[0];
2069            mPositionY = mTempCoords[1];
2070        }
2071
2072        public void onScrollChanged() {
2073            mScrollHasChanged = true;
2074        }
2075    }
2076
2077    private abstract class PinnedPopupWindow implements TextViewPositionListener {
2078        protected PopupWindow mPopupWindow;
2079        protected ViewGroup mContentView;
2080        int mPositionX, mPositionY;
2081
2082        protected abstract void createPopupWindow();
2083        protected abstract void initContentView();
2084        protected abstract int getTextOffset();
2085        protected abstract int getVerticalLocalPosition(int line);
2086        protected abstract int clipVertically(int positionY);
2087
2088        public PinnedPopupWindow() {
2089            createPopupWindow();
2090
2091            mPopupWindow.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
2092            mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
2093            mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
2094
2095            initContentView();
2096
2097            LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2098                    ViewGroup.LayoutParams.WRAP_CONTENT);
2099            mContentView.setLayoutParams(wrapContent);
2100
2101            mPopupWindow.setContentView(mContentView);
2102        }
2103
2104        public void show() {
2105            getPositionListener().addSubscriber(this, false /* offset is fixed */);
2106
2107            computeLocalPosition();
2108
2109            final PositionListener positionListener = getPositionListener();
2110            updatePosition(positionListener.getPositionX(), positionListener.getPositionY());
2111        }
2112
2113        protected void measureContent() {
2114            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2115            mContentView.measure(
2116                    View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels,
2117                            View.MeasureSpec.AT_MOST),
2118                    View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels,
2119                            View.MeasureSpec.AT_MOST));
2120        }
2121
2122        /* The popup window will be horizontally centered on the getTextOffset() and vertically
2123         * positioned according to viewportToContentHorizontalOffset.
2124         *
2125         * This method assumes that mContentView has properly been measured from its content. */
2126        private void computeLocalPosition() {
2127            measureContent();
2128            final int width = mContentView.getMeasuredWidth();
2129            final int offset = getTextOffset();
2130            mPositionX = (int) (mTextView.getLayout().getPrimaryHorizontal(offset) - width / 2.0f);
2131            mPositionX += mTextView.viewportToContentHorizontalOffset();
2132
2133            final int line = mTextView.getLayout().getLineForOffset(offset);
2134            mPositionY = getVerticalLocalPosition(line);
2135            mPositionY += mTextView.viewportToContentVerticalOffset();
2136        }
2137
2138        private void updatePosition(int parentPositionX, int parentPositionY) {
2139            int positionX = parentPositionX + mPositionX;
2140            int positionY = parentPositionY + mPositionY;
2141
2142            positionY = clipVertically(positionY);
2143
2144            // Horizontal clipping
2145            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2146            final int width = mContentView.getMeasuredWidth();
2147            positionX = Math.min(displayMetrics.widthPixels - width, positionX);
2148            positionX = Math.max(0, positionX);
2149
2150            if (isShowing()) {
2151                mPopupWindow.update(positionX, positionY, -1, -1);
2152            } else {
2153                mPopupWindow.showAtLocation(mTextView, Gravity.NO_GRAVITY,
2154                        positionX, positionY);
2155            }
2156        }
2157
2158        public void hide() {
2159            mPopupWindow.dismiss();
2160            getPositionListener().removeSubscriber(this);
2161        }
2162
2163        @Override
2164        public void updatePosition(int parentPositionX, int parentPositionY,
2165                boolean parentPositionChanged, boolean parentScrolled) {
2166            // Either parentPositionChanged or parentScrolled is true, check if still visible
2167            if (isShowing() && isOffsetVisible(getTextOffset())) {
2168                if (parentScrolled) computeLocalPosition();
2169                updatePosition(parentPositionX, parentPositionY);
2170            } else {
2171                hide();
2172            }
2173        }
2174
2175        public boolean isShowing() {
2176            return mPopupWindow.isShowing();
2177        }
2178    }
2179
2180    private class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener {
2181        private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE;
2182        private static final int ADD_TO_DICTIONARY = -1;
2183        private static final int DELETE_TEXT = -2;
2184        private SuggestionInfo[] mSuggestionInfos;
2185        private int mNumberOfSuggestions;
2186        private boolean mCursorWasVisibleBeforeSuggestions;
2187        private boolean mIsShowingUp = false;
2188        private SuggestionAdapter mSuggestionsAdapter;
2189        private final Comparator<SuggestionSpan> mSuggestionSpanComparator;
2190        private final HashMap<SuggestionSpan, Integer> mSpansLengths;
2191
2192        private class CustomPopupWindow extends PopupWindow {
2193            public CustomPopupWindow(Context context, int defStyle) {
2194                super(context, null, defStyle);
2195            }
2196
2197            @Override
2198            public void dismiss() {
2199                super.dismiss();
2200
2201                getPositionListener().removeSubscriber(SuggestionsPopupWindow.this);
2202
2203                // Safe cast since show() checks that mTextView.getText() is an Editable
2204                ((Spannable) mTextView.getText()).removeSpan(mSuggestionRangeSpan);
2205
2206                mTextView.setCursorVisible(mCursorWasVisibleBeforeSuggestions);
2207                if (hasInsertionController()) {
2208                    getInsertionController().show();
2209                }
2210            }
2211        }
2212
2213        public SuggestionsPopupWindow() {
2214            mCursorWasVisibleBeforeSuggestions = mCursorVisible;
2215            mSuggestionSpanComparator = new SuggestionSpanComparator();
2216            mSpansLengths = new HashMap<SuggestionSpan, Integer>();
2217        }
2218
2219        @Override
2220        protected void createPopupWindow() {
2221            mPopupWindow = new CustomPopupWindow(mTextView.getContext(),
2222                com.android.internal.R.attr.textSuggestionsWindowStyle);
2223            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
2224            mPopupWindow.setFocusable(true);
2225            mPopupWindow.setClippingEnabled(false);
2226        }
2227
2228        @Override
2229        protected void initContentView() {
2230            ListView listView = new ListView(mTextView.getContext());
2231            mSuggestionsAdapter = new SuggestionAdapter();
2232            listView.setAdapter(mSuggestionsAdapter);
2233            listView.setOnItemClickListener(this);
2234            mContentView = listView;
2235
2236            // Inflate the suggestion items once and for all. + 2 for add to dictionary and delete
2237            mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS + 2];
2238            for (int i = 0; i < mSuggestionInfos.length; i++) {
2239                mSuggestionInfos[i] = new SuggestionInfo();
2240            }
2241        }
2242
2243        public boolean isShowingUp() {
2244            return mIsShowingUp;
2245        }
2246
2247        public void onParentLostFocus() {
2248            mIsShowingUp = false;
2249        }
2250
2251        private class SuggestionInfo {
2252            int suggestionStart, suggestionEnd; // range of actual suggestion within text
2253            SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents
2254            int suggestionIndex; // the index of this suggestion inside suggestionSpan
2255            SpannableStringBuilder text = new SpannableStringBuilder();
2256            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mTextView.getContext(),
2257                    android.R.style.TextAppearance_SuggestionHighlight);
2258        }
2259
2260        private class SuggestionAdapter extends BaseAdapter {
2261            private LayoutInflater mInflater = (LayoutInflater) mTextView.getContext().
2262                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2263
2264            @Override
2265            public int getCount() {
2266                return mNumberOfSuggestions;
2267            }
2268
2269            @Override
2270            public Object getItem(int position) {
2271                return mSuggestionInfos[position];
2272            }
2273
2274            @Override
2275            public long getItemId(int position) {
2276                return position;
2277            }
2278
2279            @Override
2280            public View getView(int position, View convertView, ViewGroup parent) {
2281                TextView textView = (TextView) convertView;
2282
2283                if (textView == null) {
2284                    textView = (TextView) mInflater.inflate(mTextView.mTextEditSuggestionItemLayout,
2285                            parent, false);
2286                }
2287
2288                final SuggestionInfo suggestionInfo = mSuggestionInfos[position];
2289                textView.setText(suggestionInfo.text);
2290
2291                if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) {
2292                    textView.setCompoundDrawablesWithIntrinsicBounds(
2293                            com.android.internal.R.drawable.ic_suggestions_add, 0, 0, 0);
2294                } else if (suggestionInfo.suggestionIndex == DELETE_TEXT) {
2295                    textView.setCompoundDrawablesWithIntrinsicBounds(
2296                            com.android.internal.R.drawable.ic_suggestions_delete, 0, 0, 0);
2297                } else {
2298                    textView.setCompoundDrawables(null, null, null, null);
2299                }
2300
2301                return textView;
2302            }
2303        }
2304
2305        private class SuggestionSpanComparator implements Comparator<SuggestionSpan> {
2306            public int compare(SuggestionSpan span1, SuggestionSpan span2) {
2307                final int flag1 = span1.getFlags();
2308                final int flag2 = span2.getFlags();
2309                if (flag1 != flag2) {
2310                    // The order here should match what is used in updateDrawState
2311                    final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
2312                    final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
2313                    final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0;
2314                    final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0;
2315                    if (easy1 && !misspelled1) return -1;
2316                    if (easy2 && !misspelled2) return 1;
2317                    if (misspelled1) return -1;
2318                    if (misspelled2) return 1;
2319                }
2320
2321                return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue();
2322            }
2323        }
2324
2325        /**
2326         * Returns the suggestion spans that cover the current cursor position. The suggestion
2327         * spans are sorted according to the length of text that they are attached to.
2328         */
2329        private SuggestionSpan[] getSuggestionSpans() {
2330            int pos = mTextView.getSelectionStart();
2331            Spannable spannable = (Spannable) mTextView.getText();
2332            SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class);
2333
2334            mSpansLengths.clear();
2335            for (SuggestionSpan suggestionSpan : suggestionSpans) {
2336                int start = spannable.getSpanStart(suggestionSpan);
2337                int end = spannable.getSpanEnd(suggestionSpan);
2338                mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start));
2339            }
2340
2341            // The suggestions are sorted according to their types (easy correction first, then
2342            // misspelled) and to the length of the text that they cover (shorter first).
2343            Arrays.sort(suggestionSpans, mSuggestionSpanComparator);
2344            return suggestionSpans;
2345        }
2346
2347        @Override
2348        public void show() {
2349            if (!(mTextView.getText() instanceof Editable)) return;
2350
2351            if (updateSuggestions()) {
2352                mCursorWasVisibleBeforeSuggestions = mCursorVisible;
2353                mTextView.setCursorVisible(false);
2354                mIsShowingUp = true;
2355                super.show();
2356            }
2357        }
2358
2359        @Override
2360        protected void measureContent() {
2361            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2362            final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec(
2363                    displayMetrics.widthPixels, View.MeasureSpec.AT_MOST);
2364            final int verticalMeasure = View.MeasureSpec.makeMeasureSpec(
2365                    displayMetrics.heightPixels, View.MeasureSpec.AT_MOST);
2366
2367            int width = 0;
2368            View view = null;
2369            for (int i = 0; i < mNumberOfSuggestions; i++) {
2370                view = mSuggestionsAdapter.getView(i, view, mContentView);
2371                view.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
2372                view.measure(horizontalMeasure, verticalMeasure);
2373                width = Math.max(width, view.getMeasuredWidth());
2374            }
2375
2376            // Enforce the width based on actual text widths
2377            mContentView.measure(
2378                    View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
2379                    verticalMeasure);
2380
2381            Drawable popupBackground = mPopupWindow.getBackground();
2382            if (popupBackground != null) {
2383                if (mTempRect == null) mTempRect = new Rect();
2384                popupBackground.getPadding(mTempRect);
2385                width += mTempRect.left + mTempRect.right;
2386            }
2387            mPopupWindow.setWidth(width);
2388        }
2389
2390        @Override
2391        protected int getTextOffset() {
2392            return mTextView.getSelectionStart();
2393        }
2394
2395        @Override
2396        protected int getVerticalLocalPosition(int line) {
2397            return mTextView.getLayout().getLineBottom(line);
2398        }
2399
2400        @Override
2401        protected int clipVertically(int positionY) {
2402            final int height = mContentView.getMeasuredHeight();
2403            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2404            return Math.min(positionY, displayMetrics.heightPixels - height);
2405        }
2406
2407        @Override
2408        public void hide() {
2409            super.hide();
2410        }
2411
2412        private boolean updateSuggestions() {
2413            Spannable spannable = (Spannable) mTextView.getText();
2414            SuggestionSpan[] suggestionSpans = getSuggestionSpans();
2415
2416            final int nbSpans = suggestionSpans.length;
2417            // Suggestions are shown after a delay: the underlying spans may have been removed
2418            if (nbSpans == 0) return false;
2419
2420            mNumberOfSuggestions = 0;
2421            int spanUnionStart = mTextView.getText().length();
2422            int spanUnionEnd = 0;
2423
2424            SuggestionSpan misspelledSpan = null;
2425            int underlineColor = 0;
2426
2427            for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) {
2428                SuggestionSpan suggestionSpan = suggestionSpans[spanIndex];
2429                final int spanStart = spannable.getSpanStart(suggestionSpan);
2430                final int spanEnd = spannable.getSpanEnd(suggestionSpan);
2431                spanUnionStart = Math.min(spanStart, spanUnionStart);
2432                spanUnionEnd = Math.max(spanEnd, spanUnionEnd);
2433
2434                if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) {
2435                    misspelledSpan = suggestionSpan;
2436                }
2437
2438                // The first span dictates the background color of the highlighted text
2439                if (spanIndex == 0) underlineColor = suggestionSpan.getUnderlineColor();
2440
2441                String[] suggestions = suggestionSpan.getSuggestions();
2442                int nbSuggestions = suggestions.length;
2443                for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) {
2444                    String suggestion = suggestions[suggestionIndex];
2445
2446                    boolean suggestionIsDuplicate = false;
2447                    for (int i = 0; i < mNumberOfSuggestions; i++) {
2448                        if (mSuggestionInfos[i].text.toString().equals(suggestion)) {
2449                            SuggestionSpan otherSuggestionSpan = mSuggestionInfos[i].suggestionSpan;
2450                            final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan);
2451                            final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan);
2452                            if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) {
2453                                suggestionIsDuplicate = true;
2454                                break;
2455                            }
2456                        }
2457                    }
2458
2459                    if (!suggestionIsDuplicate) {
2460                        SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2461                        suggestionInfo.suggestionSpan = suggestionSpan;
2462                        suggestionInfo.suggestionIndex = suggestionIndex;
2463                        suggestionInfo.text.replace(0, suggestionInfo.text.length(), suggestion);
2464
2465                        mNumberOfSuggestions++;
2466
2467                        if (mNumberOfSuggestions == MAX_NUMBER_SUGGESTIONS) {
2468                            // Also end outer for loop
2469                            spanIndex = nbSpans;
2470                            break;
2471                        }
2472                    }
2473                }
2474            }
2475
2476            for (int i = 0; i < mNumberOfSuggestions; i++) {
2477                highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd);
2478            }
2479
2480            // Add "Add to dictionary" item if there is a span with the misspelled flag
2481            if (misspelledSpan != null) {
2482                final int misspelledStart = spannable.getSpanStart(misspelledSpan);
2483                final int misspelledEnd = spannable.getSpanEnd(misspelledSpan);
2484                if (misspelledStart >= 0 && misspelledEnd > misspelledStart) {
2485                    SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2486                    suggestionInfo.suggestionSpan = misspelledSpan;
2487                    suggestionInfo.suggestionIndex = ADD_TO_DICTIONARY;
2488                    suggestionInfo.text.replace(0, suggestionInfo.text.length(), mTextView.
2489                            getContext().getString(com.android.internal.R.string.addToDictionary));
2490                    suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
2491                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2492
2493                    mNumberOfSuggestions++;
2494                }
2495            }
2496
2497            // Delete item
2498            SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2499            suggestionInfo.suggestionSpan = null;
2500            suggestionInfo.suggestionIndex = DELETE_TEXT;
2501            suggestionInfo.text.replace(0, suggestionInfo.text.length(),
2502                    mTextView.getContext().getString(com.android.internal.R.string.deleteText));
2503            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
2504                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2505            mNumberOfSuggestions++;
2506
2507            if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan();
2508            if (underlineColor == 0) {
2509                // Fallback on the default highlight color when the first span does not provide one
2510                mSuggestionRangeSpan.setBackgroundColor(mTextView.mHighlightColor);
2511            } else {
2512                final float BACKGROUND_TRANSPARENCY = 0.4f;
2513                final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY);
2514                mSuggestionRangeSpan.setBackgroundColor(
2515                        (underlineColor & 0x00FFFFFF) + (newAlpha << 24));
2516            }
2517            spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd,
2518                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2519
2520            mSuggestionsAdapter.notifyDataSetChanged();
2521            return true;
2522        }
2523
2524        private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart,
2525                int unionEnd) {
2526            final Spannable text = (Spannable) mTextView.getText();
2527            final int spanStart = text.getSpanStart(suggestionInfo.suggestionSpan);
2528            final int spanEnd = text.getSpanEnd(suggestionInfo.suggestionSpan);
2529
2530            // Adjust the start/end of the suggestion span
2531            suggestionInfo.suggestionStart = spanStart - unionStart;
2532            suggestionInfo.suggestionEnd = suggestionInfo.suggestionStart
2533                    + suggestionInfo.text.length();
2534
2535            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0,
2536                    suggestionInfo.text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2537
2538            // Add the text before and after the span.
2539            final String textAsString = text.toString();
2540            suggestionInfo.text.insert(0, textAsString.substring(unionStart, spanStart));
2541            suggestionInfo.text.append(textAsString.substring(spanEnd, unionEnd));
2542        }
2543
2544        @Override
2545        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2546            Editable editable = (Editable) mTextView.getText();
2547            SuggestionInfo suggestionInfo = mSuggestionInfos[position];
2548
2549            if (suggestionInfo.suggestionIndex == DELETE_TEXT) {
2550                final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan);
2551                int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan);
2552                if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) {
2553                    // Do not leave two adjacent spaces after deletion, or one at beginning of text
2554                    if (spanUnionEnd < editable.length() &&
2555                            Character.isSpaceChar(editable.charAt(spanUnionEnd)) &&
2556                            (spanUnionStart == 0 ||
2557                            Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) {
2558                        spanUnionEnd = spanUnionEnd + 1;
2559                    }
2560                    mTextView.deleteText_internal(spanUnionStart, spanUnionEnd);
2561                }
2562                hide();
2563                return;
2564            }
2565
2566            final int spanStart = editable.getSpanStart(suggestionInfo.suggestionSpan);
2567            final int spanEnd = editable.getSpanEnd(suggestionInfo.suggestionSpan);
2568            if (spanStart < 0 || spanEnd <= spanStart) {
2569                // Span has been removed
2570                hide();
2571                return;
2572            }
2573
2574            final String originalText = editable.toString().substring(spanStart, spanEnd);
2575
2576            if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) {
2577                Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT);
2578                intent.putExtra("word", originalText);
2579                intent.putExtra("locale", mTextView.getTextServicesLocale().toString());
2580                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
2581                mTextView.getContext().startActivity(intent);
2582                // There is no way to know if the word was indeed added. Re-check.
2583                // TODO The ExtractEditText should remove the span in the original text instead
2584                editable.removeSpan(suggestionInfo.suggestionSpan);
2585                updateSpellCheckSpans(spanStart, spanEnd, false);
2586            } else {
2587                // SuggestionSpans are removed by replace: save them before
2588                SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd,
2589                        SuggestionSpan.class);
2590                final int length = suggestionSpans.length;
2591                int[] suggestionSpansStarts = new int[length];
2592                int[] suggestionSpansEnds = new int[length];
2593                int[] suggestionSpansFlags = new int[length];
2594                for (int i = 0; i < length; i++) {
2595                    final SuggestionSpan suggestionSpan = suggestionSpans[i];
2596                    suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan);
2597                    suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan);
2598                    suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan);
2599
2600                    // Remove potential misspelled flags
2601                    int suggestionSpanFlags = suggestionSpan.getFlags();
2602                    if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) > 0) {
2603                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED;
2604                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
2605                        suggestionSpan.setFlags(suggestionSpanFlags);
2606                    }
2607                }
2608
2609                final int suggestionStart = suggestionInfo.suggestionStart;
2610                final int suggestionEnd = suggestionInfo.suggestionEnd;
2611                final String suggestion = suggestionInfo.text.subSequence(
2612                        suggestionStart, suggestionEnd).toString();
2613                mTextView.replaceText_internal(spanStart, spanEnd, suggestion);
2614
2615                // Notify source IME of the suggestion pick. Do this before swaping texts.
2616                if (!TextUtils.isEmpty(
2617                        suggestionInfo.suggestionSpan.getNotificationTargetClassName())) {
2618                    InputMethodManager imm = InputMethodManager.peekInstance();
2619                    if (imm != null) {
2620                        imm.notifySuggestionPicked(suggestionInfo.suggestionSpan, originalText,
2621                                suggestionInfo.suggestionIndex);
2622                    }
2623                }
2624
2625                // Swap text content between actual text and Suggestion span
2626                String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions();
2627                suggestions[suggestionInfo.suggestionIndex] = originalText;
2628
2629                // Restore previous SuggestionSpans
2630                final int lengthDifference = suggestion.length() - (spanEnd - spanStart);
2631                for (int i = 0; i < length; i++) {
2632                    // Only spans that include the modified region make sense after replacement
2633                    // Spans partially included in the replaced region are removed, there is no
2634                    // way to assign them a valid range after replacement
2635                    if (suggestionSpansStarts[i] <= spanStart &&
2636                            suggestionSpansEnds[i] >= spanEnd) {
2637                        mTextView.setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i],
2638                                suggestionSpansEnds[i] + lengthDifference, suggestionSpansFlags[i]);
2639                    }
2640                }
2641
2642                // Move cursor at the end of the replaced word
2643                final int newCursorPosition = spanEnd + lengthDifference;
2644                mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition);
2645            }
2646
2647            hide();
2648        }
2649    }
2650
2651    /**
2652     * An ActionMode Callback class that is used to provide actions while in text selection mode.
2653     *
2654     * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending
2655     * on which of these this TextView supports.
2656     */
2657    private class SelectionActionModeCallback implements ActionMode.Callback {
2658
2659        @Override
2660        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2661            TypedArray styledAttributes = mTextView.getContext().obtainStyledAttributes(
2662                    com.android.internal.R.styleable.SelectionModeDrawables);
2663
2664            boolean allowText = mTextView.getContext().getResources().getBoolean(
2665                    com.android.internal.R.bool.config_allowActionMenuItemTextWithIcon);
2666
2667            mode.setTitle(mTextView.getContext().getString(
2668                    com.android.internal.R.string.textSelectionCABTitle));
2669            mode.setSubtitle(null);
2670            mode.setTitleOptionalHint(true);
2671
2672            int selectAllIconId = 0; // No icon by default
2673            if (!allowText) {
2674                // Provide an icon, text will not be displayed on smaller screens.
2675                selectAllIconId = styledAttributes.getResourceId(
2676                        R.styleable.SelectionModeDrawables_actionModeSelectAllDrawable, 0);
2677            }
2678
2679            menu.add(0, TextView.ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll).
2680                    setIcon(selectAllIconId).
2681                    setAlphabeticShortcut('a').
2682                    setShowAsAction(
2683                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
2684
2685            if (mTextView.canCut()) {
2686                menu.add(0, TextView.ID_CUT, 0, com.android.internal.R.string.cut).
2687                    setIcon(styledAttributes.getResourceId(
2688                            R.styleable.SelectionModeDrawables_actionModeCutDrawable, 0)).
2689                    setAlphabeticShortcut('x').
2690                    setShowAsAction(
2691                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
2692            }
2693
2694            if (mTextView.canCopy()) {
2695                menu.add(0, TextView.ID_COPY, 0, com.android.internal.R.string.copy).
2696                    setIcon(styledAttributes.getResourceId(
2697                            R.styleable.SelectionModeDrawables_actionModeCopyDrawable, 0)).
2698                    setAlphabeticShortcut('c').
2699                    setShowAsAction(
2700                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
2701            }
2702
2703            if (mTextView.canPaste()) {
2704                menu.add(0, TextView.ID_PASTE, 0, com.android.internal.R.string.paste).
2705                        setIcon(styledAttributes.getResourceId(
2706                                R.styleable.SelectionModeDrawables_actionModePasteDrawable, 0)).
2707                        setAlphabeticShortcut('v').
2708                        setShowAsAction(
2709                                MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
2710            }
2711
2712            styledAttributes.recycle();
2713
2714            if (mCustomSelectionActionModeCallback != null) {
2715                if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) {
2716                    // The custom mode can choose to cancel the action mode
2717                    return false;
2718                }
2719            }
2720
2721            if (menu.hasVisibleItems() || mode.getCustomView() != null) {
2722                getSelectionController().show();
2723                return true;
2724            } else {
2725                return false;
2726            }
2727        }
2728
2729        @Override
2730        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
2731            if (mCustomSelectionActionModeCallback != null) {
2732                return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu);
2733            }
2734            return true;
2735        }
2736
2737        @Override
2738        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
2739            if (mCustomSelectionActionModeCallback != null &&
2740                 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) {
2741                return true;
2742            }
2743            return mTextView.onTextContextMenuItem(item.getItemId());
2744        }
2745
2746        @Override
2747        public void onDestroyActionMode(ActionMode mode) {
2748            if (mCustomSelectionActionModeCallback != null) {
2749                mCustomSelectionActionModeCallback.onDestroyActionMode(mode);
2750            }
2751            Selection.setSelection((Spannable) mTextView.getText(), mTextView.getSelectionEnd());
2752
2753            if (mSelectionModifierCursorController != null) {
2754                mSelectionModifierCursorController.hide();
2755            }
2756
2757            mSelectionActionMode = null;
2758        }
2759    }
2760
2761    private class ActionPopupWindow extends PinnedPopupWindow implements OnClickListener {
2762        private static final int POPUP_TEXT_LAYOUT =
2763                com.android.internal.R.layout.text_edit_action_popup_text;
2764        private TextView mPasteTextView;
2765        private TextView mReplaceTextView;
2766
2767        @Override
2768        protected void createPopupWindow() {
2769            mPopupWindow = new PopupWindow(mTextView.getContext(), null,
2770                    com.android.internal.R.attr.textSelectHandleWindowStyle);
2771            mPopupWindow.setClippingEnabled(true);
2772        }
2773
2774        @Override
2775        protected void initContentView() {
2776            LinearLayout linearLayout = new LinearLayout(mTextView.getContext());
2777            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
2778            mContentView = linearLayout;
2779            mContentView.setBackgroundResource(
2780                    com.android.internal.R.drawable.text_edit_paste_window);
2781
2782            LayoutInflater inflater = (LayoutInflater) mTextView.getContext().
2783                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2784
2785            LayoutParams wrapContent = new LayoutParams(
2786                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
2787
2788            mPasteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
2789            mPasteTextView.setLayoutParams(wrapContent);
2790            mContentView.addView(mPasteTextView);
2791            mPasteTextView.setText(com.android.internal.R.string.paste);
2792            mPasteTextView.setOnClickListener(this);
2793
2794            mReplaceTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
2795            mReplaceTextView.setLayoutParams(wrapContent);
2796            mContentView.addView(mReplaceTextView);
2797            mReplaceTextView.setText(com.android.internal.R.string.replace);
2798            mReplaceTextView.setOnClickListener(this);
2799        }
2800
2801        @Override
2802        public void show() {
2803            boolean canPaste = mTextView.canPaste();
2804            boolean canSuggest = mTextView.isSuggestionsEnabled() && isCursorInsideSuggestionSpan();
2805            mPasteTextView.setVisibility(canPaste ? View.VISIBLE : View.GONE);
2806            mReplaceTextView.setVisibility(canSuggest ? View.VISIBLE : View.GONE);
2807
2808            if (!canPaste && !canSuggest) return;
2809
2810            super.show();
2811        }
2812
2813        @Override
2814        public void onClick(View view) {
2815            if (view == mPasteTextView && mTextView.canPaste()) {
2816                mTextView.onTextContextMenuItem(TextView.ID_PASTE);
2817                hide();
2818            } else if (view == mReplaceTextView) {
2819                int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2;
2820                stopSelectionActionMode();
2821                Selection.setSelection((Spannable) mTextView.getText(), middle);
2822                showSuggestions();
2823            }
2824        }
2825
2826        @Override
2827        protected int getTextOffset() {
2828            return (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2;
2829        }
2830
2831        @Override
2832        protected int getVerticalLocalPosition(int line) {
2833            return mTextView.getLayout().getLineTop(line) - mContentView.getMeasuredHeight();
2834        }
2835
2836        @Override
2837        protected int clipVertically(int positionY) {
2838            if (positionY < 0) {
2839                final int offset = getTextOffset();
2840                final Layout layout = mTextView.getLayout();
2841                final int line = layout.getLineForOffset(offset);
2842                positionY += layout.getLineBottom(line) - layout.getLineTop(line);
2843                positionY += mContentView.getMeasuredHeight();
2844
2845                // Assumes insertion and selection handles share the same height
2846                final Drawable handle = mTextView.getResources().getDrawable(
2847                        mTextView.mTextSelectHandleRes);
2848                positionY += handle.getIntrinsicHeight();
2849            }
2850
2851            return positionY;
2852        }
2853    }
2854
2855    private abstract class HandleView extends View implements TextViewPositionListener {
2856        protected Drawable mDrawable;
2857        protected Drawable mDrawableLtr;
2858        protected Drawable mDrawableRtl;
2859        private final PopupWindow mContainer;
2860        // Position with respect to the parent TextView
2861        private int mPositionX, mPositionY;
2862        private boolean mIsDragging;
2863        // Offset from touch position to mPosition
2864        private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
2865        protected int mHotspotX;
2866        // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
2867        private float mTouchOffsetY;
2868        // Where the touch position should be on the handle to ensure a maximum cursor visibility
2869        private float mIdealVerticalOffset;
2870        // Parent's (TextView) previous position in window
2871        private int mLastParentX, mLastParentY;
2872        // Transient action popup window for Paste and Replace actions
2873        protected ActionPopupWindow mActionPopupWindow;
2874        // Previous text character offset
2875        private int mPreviousOffset = -1;
2876        // Previous text character offset
2877        private boolean mPositionHasChanged = true;
2878        // Used to delay the appearance of the action popup window
2879        private Runnable mActionPopupShower;
2880
2881        public HandleView(Drawable drawableLtr, Drawable drawableRtl) {
2882            super(mTextView.getContext());
2883            mContainer = new PopupWindow(mTextView.getContext(), null,
2884                    com.android.internal.R.attr.textSelectHandleWindowStyle);
2885            mContainer.setSplitTouchEnabled(true);
2886            mContainer.setClippingEnabled(false);
2887            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
2888            mContainer.setContentView(this);
2889
2890            mDrawableLtr = drawableLtr;
2891            mDrawableRtl = drawableRtl;
2892
2893            updateDrawable();
2894
2895            final int handleHeight = mDrawable.getIntrinsicHeight();
2896            mTouchOffsetY = -0.3f * handleHeight;
2897            mIdealVerticalOffset = 0.7f * handleHeight;
2898        }
2899
2900        protected void updateDrawable() {
2901            final int offset = getCurrentCursorOffset();
2902            final boolean isRtlCharAtOffset = mTextView.getLayout().isRtlCharAt(offset);
2903            mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
2904            mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
2905        }
2906
2907        protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
2908
2909        // Touch-up filter: number of previous positions remembered
2910        private static final int HISTORY_SIZE = 5;
2911        private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
2912        private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
2913        private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
2914        private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
2915        private int mPreviousOffsetIndex = 0;
2916        private int mNumberPreviousOffsets = 0;
2917
2918        private void startTouchUpFilter(int offset) {
2919            mNumberPreviousOffsets = 0;
2920            addPositionToTouchUpFilter(offset);
2921        }
2922
2923        private void addPositionToTouchUpFilter(int offset) {
2924            mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
2925            mPreviousOffsets[mPreviousOffsetIndex] = offset;
2926            mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
2927            mNumberPreviousOffsets++;
2928        }
2929
2930        private void filterOnTouchUp() {
2931            final long now = SystemClock.uptimeMillis();
2932            int i = 0;
2933            int index = mPreviousOffsetIndex;
2934            final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
2935            while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
2936                i++;
2937                index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
2938            }
2939
2940            if (i > 0 && i < iMax &&
2941                    (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
2942                positionAtCursorOffset(mPreviousOffsets[index], false);
2943            }
2944        }
2945
2946        public boolean offsetHasBeenChanged() {
2947            return mNumberPreviousOffsets > 1;
2948        }
2949
2950        @Override
2951        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
2952            setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
2953        }
2954
2955        public void show() {
2956            if (isShowing()) return;
2957
2958            getPositionListener().addSubscriber(this, true /* local position may change */);
2959
2960            // Make sure the offset is always considered new, even when focusing at same position
2961            mPreviousOffset = -1;
2962            positionAtCursorOffset(getCurrentCursorOffset(), false);
2963
2964            hideActionPopupWindow();
2965        }
2966
2967        protected void dismiss() {
2968            mIsDragging = false;
2969            mContainer.dismiss();
2970            onDetached();
2971        }
2972
2973        public void hide() {
2974            dismiss();
2975
2976            getPositionListener().removeSubscriber(this);
2977        }
2978
2979        void showActionPopupWindow(int delay) {
2980            if (mActionPopupWindow == null) {
2981                mActionPopupWindow = new ActionPopupWindow();
2982            }
2983            if (mActionPopupShower == null) {
2984                mActionPopupShower = new Runnable() {
2985                    public void run() {
2986                        mActionPopupWindow.show();
2987                    }
2988                };
2989            } else {
2990                mTextView.removeCallbacks(mActionPopupShower);
2991            }
2992            mTextView.postDelayed(mActionPopupShower, delay);
2993        }
2994
2995        protected void hideActionPopupWindow() {
2996            if (mActionPopupShower != null) {
2997                mTextView.removeCallbacks(mActionPopupShower);
2998            }
2999            if (mActionPopupWindow != null) {
3000                mActionPopupWindow.hide();
3001            }
3002        }
3003
3004        public boolean isShowing() {
3005            return mContainer.isShowing();
3006        }
3007
3008        private boolean isVisible() {
3009            // Always show a dragging handle.
3010            if (mIsDragging) {
3011                return true;
3012            }
3013
3014            if (mTextView.isInBatchEditMode()) {
3015                return false;
3016            }
3017
3018            return isPositionVisible(mPositionX + mHotspotX, mPositionY);
3019        }
3020
3021        public abstract int getCurrentCursorOffset();
3022
3023        protected abstract void updateSelection(int offset);
3024
3025        public abstract void updatePosition(float x, float y);
3026
3027        protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
3028            // A HandleView relies on the layout, which may be nulled by external methods
3029            Layout layout = mTextView.getLayout();
3030            if (layout == null) {
3031                // Will update controllers' state, hiding them and stopping selection mode if needed
3032                prepareCursorControllers();
3033                return;
3034            }
3035
3036            boolean offsetChanged = offset != mPreviousOffset;
3037            if (offsetChanged || parentScrolled) {
3038                if (offsetChanged) {
3039                    updateSelection(offset);
3040                    addPositionToTouchUpFilter(offset);
3041                }
3042                final int line = layout.getLineForOffset(offset);
3043
3044                mPositionX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX);
3045                mPositionY = layout.getLineBottom(line);
3046
3047                // Take TextView's padding and scroll into account.
3048                mPositionX += mTextView.viewportToContentHorizontalOffset();
3049                mPositionY += mTextView.viewportToContentVerticalOffset();
3050
3051                mPreviousOffset = offset;
3052                mPositionHasChanged = true;
3053            }
3054        }
3055
3056        public void updatePosition(int parentPositionX, int parentPositionY,
3057                boolean parentPositionChanged, boolean parentScrolled) {
3058            positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled);
3059            if (parentPositionChanged || mPositionHasChanged) {
3060                if (mIsDragging) {
3061                    // Update touchToWindow offset in case of parent scrolling while dragging
3062                    if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
3063                        mTouchToWindowOffsetX += parentPositionX - mLastParentX;
3064                        mTouchToWindowOffsetY += parentPositionY - mLastParentY;
3065                        mLastParentX = parentPositionX;
3066                        mLastParentY = parentPositionY;
3067                    }
3068
3069                    onHandleMoved();
3070                }
3071
3072                if (isVisible()) {
3073                    final int positionX = parentPositionX + mPositionX;
3074                    final int positionY = parentPositionY + mPositionY;
3075                    if (isShowing()) {
3076                        mContainer.update(positionX, positionY, -1, -1);
3077                    } else {
3078                        mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY,
3079                                positionX, positionY);
3080                    }
3081                } else {
3082                    if (isShowing()) {
3083                        dismiss();
3084                    }
3085                }
3086
3087                mPositionHasChanged = false;
3088            }
3089        }
3090
3091        @Override
3092        protected void onDraw(Canvas c) {
3093            mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
3094            mDrawable.draw(c);
3095        }
3096
3097        @Override
3098        public boolean onTouchEvent(MotionEvent ev) {
3099            switch (ev.getActionMasked()) {
3100                case MotionEvent.ACTION_DOWN: {
3101                    startTouchUpFilter(getCurrentCursorOffset());
3102                    mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
3103                    mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
3104
3105                    final PositionListener positionListener = getPositionListener();
3106                    mLastParentX = positionListener.getPositionX();
3107                    mLastParentY = positionListener.getPositionY();
3108                    mIsDragging = true;
3109                    break;
3110                }
3111
3112                case MotionEvent.ACTION_MOVE: {
3113                    final float rawX = ev.getRawX();
3114                    final float rawY = ev.getRawY();
3115
3116                    // Vertical hysteresis: vertical down movement tends to snap to ideal offset
3117                    final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
3118                    final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
3119                    float newVerticalOffset;
3120                    if (previousVerticalOffset < mIdealVerticalOffset) {
3121                        newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
3122                        newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
3123                    } else {
3124                        newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
3125                        newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
3126                    }
3127                    mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
3128
3129                    final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX;
3130                    final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
3131
3132                    updatePosition(newPosX, newPosY);
3133                    break;
3134                }
3135
3136                case MotionEvent.ACTION_UP:
3137                    filterOnTouchUp();
3138                    mIsDragging = false;
3139                    break;
3140
3141                case MotionEvent.ACTION_CANCEL:
3142                    mIsDragging = false;
3143                    break;
3144            }
3145            return true;
3146        }
3147
3148        public boolean isDragging() {
3149            return mIsDragging;
3150        }
3151
3152        void onHandleMoved() {
3153            hideActionPopupWindow();
3154        }
3155
3156        public void onDetached() {
3157            hideActionPopupWindow();
3158        }
3159    }
3160
3161    private class InsertionHandleView extends HandleView {
3162        private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
3163        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
3164
3165        // Used to detect taps on the insertion handle, which will affect the ActionPopupWindow
3166        private float mDownPositionX, mDownPositionY;
3167        private Runnable mHider;
3168
3169        public InsertionHandleView(Drawable drawable) {
3170            super(drawable, drawable);
3171        }
3172
3173        @Override
3174        public void show() {
3175            super.show();
3176
3177            final long durationSinceCutOrCopy =
3178                    SystemClock.uptimeMillis() - TextView.LAST_CUT_OR_COPY_TIME;
3179            if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) {
3180                showActionPopupWindow(0);
3181            }
3182
3183            hideAfterDelay();
3184        }
3185
3186        public void showWithActionPopup() {
3187            show();
3188            showActionPopupWindow(0);
3189        }
3190
3191        private void hideAfterDelay() {
3192            if (mHider == null) {
3193                mHider = new Runnable() {
3194                    public void run() {
3195                        hide();
3196                    }
3197                };
3198            } else {
3199                removeHiderCallback();
3200            }
3201            mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
3202        }
3203
3204        private void removeHiderCallback() {
3205            if (mHider != null) {
3206                mTextView.removeCallbacks(mHider);
3207            }
3208        }
3209
3210        @Override
3211        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
3212            return drawable.getIntrinsicWidth() / 2;
3213        }
3214
3215        @Override
3216        public boolean onTouchEvent(MotionEvent ev) {
3217            final boolean result = super.onTouchEvent(ev);
3218
3219            switch (ev.getActionMasked()) {
3220                case MotionEvent.ACTION_DOWN:
3221                    mDownPositionX = ev.getRawX();
3222                    mDownPositionY = ev.getRawY();
3223                    break;
3224
3225                case MotionEvent.ACTION_UP:
3226                    if (!offsetHasBeenChanged()) {
3227                        final float deltaX = mDownPositionX - ev.getRawX();
3228                        final float deltaY = mDownPositionY - ev.getRawY();
3229                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
3230
3231                        final ViewConfiguration viewConfiguration = ViewConfiguration.get(
3232                                mTextView.getContext());
3233                        final int touchSlop = viewConfiguration.getScaledTouchSlop();
3234
3235                        if (distanceSquared < touchSlop * touchSlop) {
3236                            if (mActionPopupWindow != null && mActionPopupWindow.isShowing()) {
3237                                // Tapping on the handle dismisses the displayed action popup
3238                                mActionPopupWindow.hide();
3239                            } else {
3240                                showWithActionPopup();
3241                            }
3242                        }
3243                    }
3244                    hideAfterDelay();
3245                    break;
3246
3247                case MotionEvent.ACTION_CANCEL:
3248                    hideAfterDelay();
3249                    break;
3250
3251                default:
3252                    break;
3253            }
3254
3255            return result;
3256        }
3257
3258        @Override
3259        public int getCurrentCursorOffset() {
3260            return mTextView.getSelectionStart();
3261        }
3262
3263        @Override
3264        public void updateSelection(int offset) {
3265            Selection.setSelection((Spannable) mTextView.getText(), offset);
3266        }
3267
3268        @Override
3269        public void updatePosition(float x, float y) {
3270            positionAtCursorOffset(mTextView.getOffsetForPosition(x, y), false);
3271        }
3272
3273        @Override
3274        void onHandleMoved() {
3275            super.onHandleMoved();
3276            removeHiderCallback();
3277        }
3278
3279        @Override
3280        public void onDetached() {
3281            super.onDetached();
3282            removeHiderCallback();
3283        }
3284    }
3285
3286    private class SelectionStartHandleView extends HandleView {
3287
3288        public SelectionStartHandleView(Drawable drawableLtr, Drawable drawableRtl) {
3289            super(drawableLtr, drawableRtl);
3290        }
3291
3292        @Override
3293        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
3294            if (isRtlRun) {
3295                return drawable.getIntrinsicWidth() / 4;
3296            } else {
3297                return (drawable.getIntrinsicWidth() * 3) / 4;
3298            }
3299        }
3300
3301        @Override
3302        public int getCurrentCursorOffset() {
3303            return mTextView.getSelectionStart();
3304        }
3305
3306        @Override
3307        public void updateSelection(int offset) {
3308            Selection.setSelection((Spannable) mTextView.getText(), offset,
3309                    mTextView.getSelectionEnd());
3310            updateDrawable();
3311        }
3312
3313        @Override
3314        public void updatePosition(float x, float y) {
3315            int offset = mTextView.getOffsetForPosition(x, y);
3316
3317            // Handles can not cross and selection is at least one character
3318            final int selectionEnd = mTextView.getSelectionEnd();
3319            if (offset >= selectionEnd) offset = Math.max(0, selectionEnd - 1);
3320
3321            positionAtCursorOffset(offset, false);
3322        }
3323
3324        public ActionPopupWindow getActionPopupWindow() {
3325            return mActionPopupWindow;
3326        }
3327    }
3328
3329    private class SelectionEndHandleView extends HandleView {
3330
3331        public SelectionEndHandleView(Drawable drawableLtr, Drawable drawableRtl) {
3332            super(drawableLtr, drawableRtl);
3333        }
3334
3335        @Override
3336        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
3337            if (isRtlRun) {
3338                return (drawable.getIntrinsicWidth() * 3) / 4;
3339            } else {
3340                return drawable.getIntrinsicWidth() / 4;
3341            }
3342        }
3343
3344        @Override
3345        public int getCurrentCursorOffset() {
3346            return mTextView.getSelectionEnd();
3347        }
3348
3349        @Override
3350        public void updateSelection(int offset) {
3351            Selection.setSelection((Spannable) mTextView.getText(),
3352                    mTextView.getSelectionStart(), offset);
3353            updateDrawable();
3354        }
3355
3356        @Override
3357        public void updatePosition(float x, float y) {
3358            int offset = mTextView.getOffsetForPosition(x, y);
3359
3360            // Handles can not cross and selection is at least one character
3361            final int selectionStart = mTextView.getSelectionStart();
3362            if (offset <= selectionStart) {
3363                offset = Math.min(selectionStart + 1, mTextView.getText().length());
3364            }
3365
3366            positionAtCursorOffset(offset, false);
3367        }
3368
3369        public void setActionPopupWindow(ActionPopupWindow actionPopupWindow) {
3370            mActionPopupWindow = actionPopupWindow;
3371        }
3372    }
3373
3374    /**
3375     * A CursorController instance can be used to control a cursor in the text.
3376     */
3377    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
3378        /**
3379         * Makes the cursor controller visible on screen.
3380         * See also {@link #hide()}.
3381         */
3382        public void show();
3383
3384        /**
3385         * Hide the cursor controller from screen.
3386         * See also {@link #show()}.
3387         */
3388        public void hide();
3389
3390        /**
3391         * Called when the view is detached from window. Perform house keeping task, such as
3392         * stopping Runnable thread that would otherwise keep a reference on the context, thus
3393         * preventing the activity from being recycled.
3394         */
3395        public void onDetached();
3396    }
3397
3398    private class InsertionPointCursorController implements CursorController {
3399        private InsertionHandleView mHandle;
3400
3401        public void show() {
3402            getHandle().show();
3403        }
3404
3405        public void showWithActionPopup() {
3406            getHandle().showWithActionPopup();
3407        }
3408
3409        public void hide() {
3410            if (mHandle != null) {
3411                mHandle.hide();
3412            }
3413        }
3414
3415        public void onTouchModeChanged(boolean isInTouchMode) {
3416            if (!isInTouchMode) {
3417                hide();
3418            }
3419        }
3420
3421        private InsertionHandleView getHandle() {
3422            if (mSelectHandleCenter == null) {
3423                mSelectHandleCenter = mTextView.getResources().getDrawable(
3424                        mTextView.mTextSelectHandleRes);
3425            }
3426            if (mHandle == null) {
3427                mHandle = new InsertionHandleView(mSelectHandleCenter);
3428            }
3429            return mHandle;
3430        }
3431
3432        @Override
3433        public void onDetached() {
3434            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
3435            observer.removeOnTouchModeChangeListener(this);
3436
3437            if (mHandle != null) mHandle.onDetached();
3438        }
3439    }
3440
3441    class SelectionModifierCursorController implements CursorController {
3442        private static final int DELAY_BEFORE_REPLACE_ACTION = 200; // milliseconds
3443        // The cursor controller handles, lazily created when shown.
3444        private SelectionStartHandleView mStartHandle;
3445        private SelectionEndHandleView mEndHandle;
3446        // The offsets of that last touch down event. Remembered to start selection there.
3447        private int mMinTouchOffset, mMaxTouchOffset;
3448
3449        // Double tap detection
3450        private long mPreviousTapUpTime = 0;
3451        private float mDownPositionX, mDownPositionY;
3452        private boolean mGestureStayedInTapRegion;
3453
3454        SelectionModifierCursorController() {
3455            resetTouchOffsets();
3456        }
3457
3458        public void show() {
3459            if (mTextView.isInBatchEditMode()) {
3460                return;
3461            }
3462            initDrawables();
3463            initHandles();
3464            hideInsertionPointCursorController();
3465        }
3466
3467        private void initDrawables() {
3468            if (mSelectHandleLeft == null) {
3469                mSelectHandleLeft = mTextView.getContext().getResources().getDrawable(
3470                        mTextView.mTextSelectHandleLeftRes);
3471            }
3472            if (mSelectHandleRight == null) {
3473                mSelectHandleRight = mTextView.getContext().getResources().getDrawable(
3474                        mTextView.mTextSelectHandleRightRes);
3475            }
3476        }
3477
3478        private void initHandles() {
3479            // Lazy object creation has to be done before updatePosition() is called.
3480            if (mStartHandle == null) {
3481                mStartHandle = new SelectionStartHandleView(mSelectHandleLeft, mSelectHandleRight);
3482            }
3483            if (mEndHandle == null) {
3484                mEndHandle = new SelectionEndHandleView(mSelectHandleRight, mSelectHandleLeft);
3485            }
3486
3487            mStartHandle.show();
3488            mEndHandle.show();
3489
3490            // Make sure both left and right handles share the same ActionPopupWindow (so that
3491            // moving any of the handles hides the action popup).
3492            mStartHandle.showActionPopupWindow(DELAY_BEFORE_REPLACE_ACTION);
3493            mEndHandle.setActionPopupWindow(mStartHandle.getActionPopupWindow());
3494
3495            hideInsertionPointCursorController();
3496        }
3497
3498        public void hide() {
3499            if (mStartHandle != null) mStartHandle.hide();
3500            if (mEndHandle != null) mEndHandle.hide();
3501        }
3502
3503        public void onTouchEvent(MotionEvent event) {
3504            // This is done even when the View does not have focus, so that long presses can start
3505            // selection and tap can move cursor from this tap position.
3506            switch (event.getActionMasked()) {
3507                case MotionEvent.ACTION_DOWN:
3508                    final float x = event.getX();
3509                    final float y = event.getY();
3510
3511                    // Remember finger down position, to be able to start selection from there
3512                    mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(x, y);
3513
3514                    // Double tap detection
3515                    if (mGestureStayedInTapRegion) {
3516                        long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime;
3517                        if (duration <= ViewConfiguration.getDoubleTapTimeout()) {
3518                            final float deltaX = x - mDownPositionX;
3519                            final float deltaY = y - mDownPositionY;
3520                            final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
3521
3522                            ViewConfiguration viewConfiguration = ViewConfiguration.get(
3523                                    mTextView.getContext());
3524                            int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop();
3525                            boolean stayedInArea = distanceSquared < doubleTapSlop * doubleTapSlop;
3526
3527                            if (stayedInArea && isPositionOnText(x, y)) {
3528                                startSelectionActionMode();
3529                                mDiscardNextActionUp = true;
3530                            }
3531                        }
3532                    }
3533
3534                    mDownPositionX = x;
3535                    mDownPositionY = y;
3536                    mGestureStayedInTapRegion = true;
3537                    break;
3538
3539                case MotionEvent.ACTION_POINTER_DOWN:
3540                case MotionEvent.ACTION_POINTER_UP:
3541                    // Handle multi-point gestures. Keep min and max offset positions.
3542                    // Only activated for devices that correctly handle multi-touch.
3543                    if (mTextView.getContext().getPackageManager().hasSystemFeature(
3544                            PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
3545                        updateMinAndMaxOffsets(event);
3546                    }
3547                    break;
3548
3549                case MotionEvent.ACTION_MOVE:
3550                    if (mGestureStayedInTapRegion) {
3551                        final float deltaX = event.getX() - mDownPositionX;
3552                        final float deltaY = event.getY() - mDownPositionY;
3553                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
3554
3555                        final ViewConfiguration viewConfiguration = ViewConfiguration.get(
3556                                mTextView.getContext());
3557                        int doubleTapTouchSlop = viewConfiguration.getScaledDoubleTapTouchSlop();
3558
3559                        if (distanceSquared > doubleTapTouchSlop * doubleTapTouchSlop) {
3560                            mGestureStayedInTapRegion = false;
3561                        }
3562                    }
3563                    break;
3564
3565                case MotionEvent.ACTION_UP:
3566                    mPreviousTapUpTime = SystemClock.uptimeMillis();
3567                    break;
3568            }
3569        }
3570
3571        /**
3572         * @param event
3573         */
3574        private void updateMinAndMaxOffsets(MotionEvent event) {
3575            int pointerCount = event.getPointerCount();
3576            for (int index = 0; index < pointerCount; index++) {
3577                int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index));
3578                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
3579                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
3580            }
3581        }
3582
3583        public int getMinTouchOffset() {
3584            return mMinTouchOffset;
3585        }
3586
3587        public int getMaxTouchOffset() {
3588            return mMaxTouchOffset;
3589        }
3590
3591        public void resetTouchOffsets() {
3592            mMinTouchOffset = mMaxTouchOffset = -1;
3593        }
3594
3595        /**
3596         * @return true iff this controller is currently used to move the selection start.
3597         */
3598        public boolean isSelectionStartDragged() {
3599            return mStartHandle != null && mStartHandle.isDragging();
3600        }
3601
3602        public void onTouchModeChanged(boolean isInTouchMode) {
3603            if (!isInTouchMode) {
3604                hide();
3605            }
3606        }
3607
3608        @Override
3609        public void onDetached() {
3610            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
3611            observer.removeOnTouchModeChangeListener(this);
3612
3613            if (mStartHandle != null) mStartHandle.onDetached();
3614            if (mEndHandle != null) mEndHandle.onDetached();
3615        }
3616    }
3617
3618    private class CorrectionHighlighter {
3619        private final Path mPath = new Path();
3620        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
3621        private int mStart, mEnd;
3622        private long mFadingStartTime;
3623        private RectF mTempRectF;
3624        private final static int FADE_OUT_DURATION = 400;
3625
3626        public CorrectionHighlighter() {
3627            mPaint.setCompatibilityScaling(mTextView.getResources().getCompatibilityInfo().
3628                    applicationScale);
3629            mPaint.setStyle(Paint.Style.FILL);
3630        }
3631
3632        public void highlight(CorrectionInfo info) {
3633            mStart = info.getOffset();
3634            mEnd = mStart + info.getNewText().length();
3635            mFadingStartTime = SystemClock.uptimeMillis();
3636
3637            if (mStart < 0 || mEnd < 0) {
3638                stopAnimation();
3639            }
3640        }
3641
3642        public void draw(Canvas canvas, int cursorOffsetVertical) {
3643            if (updatePath() && updatePaint()) {
3644                if (cursorOffsetVertical != 0) {
3645                    canvas.translate(0, cursorOffsetVertical);
3646                }
3647
3648                canvas.drawPath(mPath, mPaint);
3649
3650                if (cursorOffsetVertical != 0) {
3651                    canvas.translate(0, -cursorOffsetVertical);
3652                }
3653                invalidate(true); // TODO invalidate cursor region only
3654            } else {
3655                stopAnimation();
3656                invalidate(false); // TODO invalidate cursor region only
3657            }
3658        }
3659
3660        private boolean updatePaint() {
3661            final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
3662            if (duration > FADE_OUT_DURATION) return false;
3663
3664            final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
3665            final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor);
3666            final int color = (mTextView.mHighlightColor & 0x00FFFFFF) +
3667                    ((int) (highlightColorAlpha * coef) << 24);
3668            mPaint.setColor(color);
3669            return true;
3670        }
3671
3672        private boolean updatePath() {
3673            final Layout layout = mTextView.getLayout();
3674            if (layout == null) return false;
3675
3676            // Update in case text is edited while the animation is run
3677            final int length = mTextView.getText().length();
3678            int start = Math.min(length, mStart);
3679            int end = Math.min(length, mEnd);
3680
3681            mPath.reset();
3682            layout.getSelectionPath(start, end, mPath);
3683            return true;
3684        }
3685
3686        private void invalidate(boolean delayed) {
3687            if (mTextView.getLayout() == null) return;
3688
3689            if (mTempRectF == null) mTempRectF = new RectF();
3690            mPath.computeBounds(mTempRectF, false);
3691
3692            int left = mTextView.getCompoundPaddingLeft();
3693            int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true);
3694
3695            if (delayed) {
3696                mTextView.postInvalidateOnAnimation(
3697                        left + (int) mTempRectF.left, top + (int) mTempRectF.top,
3698                        left + (int) mTempRectF.right, top + (int) mTempRectF.bottom);
3699            } else {
3700                mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top,
3701                        (int) mTempRectF.right, (int) mTempRectF.bottom);
3702            }
3703        }
3704
3705        private void stopAnimation() {
3706            Editor.this.mCorrectionHighlighter = null;
3707        }
3708    }
3709
3710    private static class ErrorPopup extends PopupWindow {
3711        private boolean mAbove = false;
3712        private final TextView mView;
3713        private int mPopupInlineErrorBackgroundId = 0;
3714        private int mPopupInlineErrorAboveBackgroundId = 0;
3715
3716        ErrorPopup(TextView v, int width, int height) {
3717            super(v, width, height);
3718            mView = v;
3719            // Make sure the TextView has a background set as it will be used the first time it is
3720            // shown and positionned. Initialized with below background, which should have
3721            // dimensions identical to the above version for this to work (and is more likely).
3722            mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
3723                    com.android.internal.R.styleable.Theme_errorMessageBackground);
3724            mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
3725        }
3726
3727        void fixDirection(boolean above) {
3728            mAbove = above;
3729
3730            if (above) {
3731                mPopupInlineErrorAboveBackgroundId =
3732                    getResourceId(mPopupInlineErrorAboveBackgroundId,
3733                            com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
3734            } else {
3735                mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
3736                        com.android.internal.R.styleable.Theme_errorMessageBackground);
3737            }
3738
3739            mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId :
3740                mPopupInlineErrorBackgroundId);
3741        }
3742
3743        private int getResourceId(int currentId, int index) {
3744            if (currentId == 0) {
3745                TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
3746                        R.styleable.Theme);
3747                currentId = styledAttributes.getResourceId(index, 0);
3748                styledAttributes.recycle();
3749            }
3750            return currentId;
3751        }
3752
3753        @Override
3754        public void update(int x, int y, int w, int h, boolean force) {
3755            super.update(x, y, w, h, force);
3756
3757            boolean above = isAboveAnchor();
3758            if (above != mAbove) {
3759                fixDirection(above);
3760            }
3761        }
3762    }
3763
3764    static class InputContentType {
3765        int imeOptions = EditorInfo.IME_NULL;
3766        String privateImeOptions;
3767        CharSequence imeActionLabel;
3768        int imeActionId;
3769        Bundle extras;
3770        OnEditorActionListener onEditorActionListener;
3771        boolean enterDown;
3772    }
3773
3774    static class InputMethodState {
3775        Rect mCursorRectInWindow = new Rect();
3776        RectF mTmpRectF = new RectF();
3777        float[] mTmpOffset = new float[2];
3778        ExtractedTextRequest mExtracting;
3779        final ExtractedText mTmpExtracted = new ExtractedText();
3780        int mBatchEditNesting;
3781        boolean mCursorChanged;
3782        boolean mSelectionModeChanged;
3783        boolean mContentChanged;
3784        int mChangedStart, mChangedEnd, mChangedDelta;
3785    }
3786}
3787