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