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