TextView.java revision 9511b41e05312f1f5ed88d22040876218d7bfdd4
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.widget;
18
19import android.R;
20import android.content.ClipData;
21import android.content.ClipData.Item;
22import android.content.ClipboardManager;
23import android.content.Context;
24import android.content.pm.PackageManager;
25import android.content.res.ColorStateList;
26import android.content.res.Resources;
27import android.content.res.TypedArray;
28import android.content.res.XmlResourceParser;
29import android.graphics.Canvas;
30import android.graphics.Color;
31import android.graphics.Paint;
32import android.graphics.Path;
33import android.graphics.Rect;
34import android.graphics.RectF;
35import android.graphics.Typeface;
36import android.graphics.drawable.Drawable;
37import android.inputmethodservice.ExtractEditText;
38import android.net.Uri;
39import android.os.Bundle;
40import android.os.Handler;
41import android.os.Message;
42import android.os.Parcel;
43import android.os.Parcelable;
44import android.os.SystemClock;
45import android.text.BoringLayout;
46import android.text.DynamicLayout;
47import android.text.Editable;
48import android.text.GetChars;
49import android.text.GraphicsOperations;
50import android.text.InputFilter;
51import android.text.InputType;
52import android.text.Layout;
53import android.text.ParcelableSpan;
54import android.text.Selection;
55import android.text.SpanWatcher;
56import android.text.Spannable;
57import android.text.SpannableString;
58import android.text.SpannableStringBuilder;
59import android.text.Spanned;
60import android.text.SpannedString;
61import android.text.StaticLayout;
62import android.text.TextPaint;
63import android.text.TextUtils;
64import android.text.TextWatcher;
65import android.text.method.ArrowKeyMovementMethod;
66import android.text.method.DateKeyListener;
67import android.text.method.DateTimeKeyListener;
68import android.text.method.DialerKeyListener;
69import android.text.method.DigitsKeyListener;
70import android.text.method.KeyListener;
71import android.text.method.LinkMovementMethod;
72import android.text.method.MetaKeyKeyListener;
73import android.text.method.MovementMethod;
74import android.text.method.PasswordTransformationMethod;
75import android.text.method.SingleLineTransformationMethod;
76import android.text.method.TextKeyListener;
77import android.text.method.TimeKeyListener;
78import android.text.method.TransformationMethod;
79import android.text.method.WordIterator;
80import android.text.style.ClickableSpan;
81import android.text.style.ParagraphStyle;
82import android.text.style.SuggestionSpan;
83import android.text.style.TextAppearanceSpan;
84import android.text.style.URLSpan;
85import android.text.style.UnderlineSpan;
86import android.text.style.UpdateAppearance;
87import android.text.util.Linkify;
88import android.util.AttributeSet;
89import android.util.DisplayMetrics;
90import android.util.FloatMath;
91import android.util.Log;
92import android.util.TypedValue;
93import android.view.ActionMode;
94import android.view.ActionMode.Callback;
95import android.view.ContextMenu;
96import android.view.DragEvent;
97import android.view.Gravity;
98import android.view.HapticFeedbackConstants;
99import android.view.KeyCharacterMap;
100import android.view.KeyEvent;
101import android.view.LayoutInflater;
102import android.view.Menu;
103import android.view.MenuItem;
104import android.view.MotionEvent;
105import android.view.View;
106import android.view.ViewAncestor;
107import android.view.ViewConfiguration;
108import android.view.ViewDebug;
109import android.view.ViewGroup;
110import android.view.ViewGroup.LayoutParams;
111import android.view.ViewParent;
112import android.view.ViewTreeObserver;
113import android.view.WindowManager;
114import android.view.accessibility.AccessibilityEvent;
115import android.view.accessibility.AccessibilityManager;
116import android.view.animation.AnimationUtils;
117import android.view.inputmethod.BaseInputConnection;
118import android.view.inputmethod.CompletionInfo;
119import android.view.inputmethod.CorrectionInfo;
120import android.view.inputmethod.EditorInfo;
121import android.view.inputmethod.ExtractedText;
122import android.view.inputmethod.ExtractedTextRequest;
123import android.view.inputmethod.InputConnection;
124import android.view.inputmethod.InputMethodManager;
125import android.widget.RemoteViews.RemoteView;
126
127import com.android.internal.util.FastMath;
128import com.android.internal.widget.EditableInputConnection;
129
130import org.xmlpull.v1.XmlPullParserException;
131
132import java.io.IOException;
133import java.lang.ref.WeakReference;
134import java.text.BreakIterator;
135import java.util.ArrayList;
136
137/**
138 * Displays text to the user and optionally allows them to edit it.  A TextView
139 * is a complete text editor, however the basic class is configured to not
140 * allow editing; see {@link EditText} for a subclass that configures the text
141 * view for editing.
142 *
143 * <p>
144 * <b>XML attributes</b>
145 * <p>
146 * See {@link android.R.styleable#TextView TextView Attributes},
147 * {@link android.R.styleable#View View Attributes}
148 *
149 * @attr ref android.R.styleable#TextView_text
150 * @attr ref android.R.styleable#TextView_bufferType
151 * @attr ref android.R.styleable#TextView_hint
152 * @attr ref android.R.styleable#TextView_textColor
153 * @attr ref android.R.styleable#TextView_textColorHighlight
154 * @attr ref android.R.styleable#TextView_textColorHint
155 * @attr ref android.R.styleable#TextView_textAppearance
156 * @attr ref android.R.styleable#TextView_textColorLink
157 * @attr ref android.R.styleable#TextView_textSize
158 * @attr ref android.R.styleable#TextView_textScaleX
159 * @attr ref android.R.styleable#TextView_typeface
160 * @attr ref android.R.styleable#TextView_textStyle
161 * @attr ref android.R.styleable#TextView_cursorVisible
162 * @attr ref android.R.styleable#TextView_maxLines
163 * @attr ref android.R.styleable#TextView_maxHeight
164 * @attr ref android.R.styleable#TextView_lines
165 * @attr ref android.R.styleable#TextView_height
166 * @attr ref android.R.styleable#TextView_minLines
167 * @attr ref android.R.styleable#TextView_minHeight
168 * @attr ref android.R.styleable#TextView_maxEms
169 * @attr ref android.R.styleable#TextView_maxWidth
170 * @attr ref android.R.styleable#TextView_ems
171 * @attr ref android.R.styleable#TextView_width
172 * @attr ref android.R.styleable#TextView_minEms
173 * @attr ref android.R.styleable#TextView_minWidth
174 * @attr ref android.R.styleable#TextView_gravity
175 * @attr ref android.R.styleable#TextView_scrollHorizontally
176 * @attr ref android.R.styleable#TextView_password
177 * @attr ref android.R.styleable#TextView_singleLine
178 * @attr ref android.R.styleable#TextView_selectAllOnFocus
179 * @attr ref android.R.styleable#TextView_includeFontPadding
180 * @attr ref android.R.styleable#TextView_maxLength
181 * @attr ref android.R.styleable#TextView_shadowColor
182 * @attr ref android.R.styleable#TextView_shadowDx
183 * @attr ref android.R.styleable#TextView_shadowDy
184 * @attr ref android.R.styleable#TextView_shadowRadius
185 * @attr ref android.R.styleable#TextView_autoLink
186 * @attr ref android.R.styleable#TextView_linksClickable
187 * @attr ref android.R.styleable#TextView_numeric
188 * @attr ref android.R.styleable#TextView_digits
189 * @attr ref android.R.styleable#TextView_phoneNumber
190 * @attr ref android.R.styleable#TextView_inputMethod
191 * @attr ref android.R.styleable#TextView_capitalize
192 * @attr ref android.R.styleable#TextView_autoText
193 * @attr ref android.R.styleable#TextView_editable
194 * @attr ref android.R.styleable#TextView_freezesText
195 * @attr ref android.R.styleable#TextView_ellipsize
196 * @attr ref android.R.styleable#TextView_drawableTop
197 * @attr ref android.R.styleable#TextView_drawableBottom
198 * @attr ref android.R.styleable#TextView_drawableRight
199 * @attr ref android.R.styleable#TextView_drawableLeft
200 * @attr ref android.R.styleable#TextView_drawablePadding
201 * @attr ref android.R.styleable#TextView_lineSpacingExtra
202 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier
203 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
204 * @attr ref android.R.styleable#TextView_inputType
205 * @attr ref android.R.styleable#TextView_imeOptions
206 * @attr ref android.R.styleable#TextView_privateImeOptions
207 * @attr ref android.R.styleable#TextView_imeActionLabel
208 * @attr ref android.R.styleable#TextView_imeActionId
209 * @attr ref android.R.styleable#TextView_editorExtras
210 */
211@RemoteView
212public class TextView extends View implements ViewTreeObserver.OnPreDrawListener {
213    static final String LOG_TAG = "TextView";
214    static final boolean DEBUG_EXTRACT = false;
215
216    private static final int PRIORITY = 100;
217    private int mCurrentAlpha = 255;
218
219    final int[] mTempCoords = new int[2];
220    Rect mTempRect;
221
222    private ColorStateList mTextColor;
223    private int mCurTextColor;
224    private ColorStateList mHintTextColor;
225    private ColorStateList mLinkTextColor;
226    private int mCurHintTextColor;
227    private boolean mFreezesText;
228    private boolean mFrozenWithFocus;
229    private boolean mTemporaryDetach;
230    private boolean mDispatchTemporaryDetach;
231
232    private boolean mDiscardNextActionUp = false;
233    private boolean mIgnoreActionUpEvent = false;
234
235    private Editable.Factory mEditableFactory = Editable.Factory.getInstance();
236    private Spannable.Factory mSpannableFactory = Spannable.Factory.getInstance();
237
238    private float mShadowRadius, mShadowDx, mShadowDy;
239
240    private static final int PREDRAW_NOT_REGISTERED = 0;
241    private static final int PREDRAW_PENDING = 1;
242    private static final int PREDRAW_DONE = 2;
243    private int mPreDrawState = PREDRAW_NOT_REGISTERED;
244
245    private TextUtils.TruncateAt mEllipsize = null;
246
247    // Enum for the "typeface" XML parameter.
248    // TODO: How can we get this from the XML instead of hardcoding it here?
249    private static final int SANS = 1;
250    private static final int SERIF = 2;
251    private static final int MONOSPACE = 3;
252
253    // Bitfield for the "numeric" XML parameter.
254    // TODO: How can we get this from the XML instead of hardcoding it here?
255    private static final int SIGNED = 2;
256    private static final int DECIMAL = 4;
257
258    class Drawables {
259        final Rect mCompoundRect = new Rect();
260        Drawable mDrawableTop, mDrawableBottom, mDrawableLeft, mDrawableRight;
261        int mDrawableSizeTop, mDrawableSizeBottom, mDrawableSizeLeft, mDrawableSizeRight;
262        int mDrawableWidthTop, mDrawableWidthBottom, mDrawableHeightLeft, mDrawableHeightRight;
263        int mDrawablePadding;
264    }
265    private Drawables mDrawables;
266
267    private CharSequence mError;
268    private boolean mErrorWasChanged;
269    private ErrorPopup mPopup;
270    /**
271     * This flag is set if the TextView tries to display an error before it
272     * is attached to the window (so its position is still unknown).
273     * It causes the error to be shown later, when onAttachedToWindow()
274     * is called.
275     */
276    private boolean mShowErrorAfterAttach;
277
278    private CharWrapper mCharWrapper = null;
279
280    private boolean mSelectionMoved = false;
281    private boolean mTouchFocusSelected = false;
282
283    private Marquee mMarquee;
284    private boolean mRestartMarquee;
285
286    private int mMarqueeRepeatLimit = 3;
287
288    class InputContentType {
289        int imeOptions = EditorInfo.IME_NULL;
290        String privateImeOptions;
291        CharSequence imeActionLabel;
292        int imeActionId;
293        Bundle extras;
294        OnEditorActionListener onEditorActionListener;
295        boolean enterDown;
296    }
297    InputContentType mInputContentType;
298
299    class InputMethodState {
300        Rect mCursorRectInWindow = new Rect();
301        RectF mTmpRectF = new RectF();
302        float[] mTmpOffset = new float[2];
303        ExtractedTextRequest mExtracting;
304        final ExtractedText mTmpExtracted = new ExtractedText();
305        int mBatchEditNesting;
306        boolean mCursorChanged;
307        boolean mSelectionModeChanged;
308        boolean mContentChanged;
309        int mChangedStart, mChangedEnd, mChangedDelta;
310    }
311    InputMethodState mInputMethodState;
312
313    private int mTextSelectHandleLeftRes;
314    private int mTextSelectHandleRightRes;
315    private int mTextSelectHandleRes;
316    private int mTextEditPasteWindowLayout, mTextEditSidePasteWindowLayout;
317    private int mTextEditNoPasteWindowLayout, mTextEditSideNoPasteWindowLayout;
318
319    private int mTextEditSuggestionsBottomWindowLayout, mTextEditSuggestionsTopWindowLayout;
320    private int mTextEditSuggestionItemLayout;
321    private SuggestionsPopupWindow mSuggestionsPopupWindow;
322    private SuggestionRangeSpan mSuggestionRangeSpan;
323
324    private int mCursorDrawableRes;
325    private final Drawable[] mCursorDrawable = new Drawable[2];
326    private int mCursorCount; // Actual current number of used mCursorDrawable: 0, 1 or 2
327
328    private Drawable mSelectHandleLeft;
329    private Drawable mSelectHandleRight;
330    private Drawable mSelectHandleCenter;
331
332    private float mLastDownPositionX, mLastDownPositionY;
333    private Callback mCustomSelectionActionModeCallback;
334
335    private final int mSquaredTouchSlopDistance;
336    // Set when this TextView gained focus with some text selected. Will start selection mode.
337    private boolean mCreatedWithASelection = false;
338
339    private WordIterator mWordIterator;
340
341    /*
342     * Kick-start the font cache for the zygote process (to pay the cost of
343     * initializing freetype for our default font only once).
344     */
345    static {
346        Paint p = new Paint();
347        p.setAntiAlias(true);
348        // We don't care about the result, just the side-effect of measuring.
349        p.measureText("H");
350    }
351
352    /**
353     * Interface definition for a callback to be invoked when an action is
354     * performed on the editor.
355     */
356    public interface OnEditorActionListener {
357        /**
358         * Called when an action is being performed.
359         *
360         * @param v The view that was clicked.
361         * @param actionId Identifier of the action.  This will be either the
362         * identifier you supplied, or {@link EditorInfo#IME_NULL
363         * EditorInfo.IME_NULL} if being called due to the enter key
364         * being pressed.
365         * @param event If triggered by an enter key, this is the event;
366         * otherwise, this is null.
367         * @return Return true if you have consumed the action, else false.
368         */
369        boolean onEditorAction(TextView v, int actionId, KeyEvent event);
370    }
371
372    public TextView(Context context) {
373        this(context, null);
374    }
375
376    public TextView(Context context,
377                    AttributeSet attrs) {
378        this(context, attrs, com.android.internal.R.attr.textViewStyle);
379    }
380
381    @SuppressWarnings("deprecation")
382    public TextView(Context context,
383                    AttributeSet attrs,
384                    int defStyle) {
385        super(context, attrs, defStyle);
386        mText = "";
387
388        mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
389        mTextPaint.density = getResources().getDisplayMetrics().density;
390        mTextPaint.setCompatibilityScaling(
391                getResources().getCompatibilityInfo().applicationScale);
392
393        // If we get the paint from the skin, we should set it to left, since
394        // the layout always wants it to be left.
395        // mTextPaint.setTextAlign(Paint.Align.LEFT);
396
397        mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
398        mHighlightPaint.setCompatibilityScaling(
399                getResources().getCompatibilityInfo().applicationScale);
400
401        mMovement = getDefaultMovementMethod();
402        mTransformation = null;
403
404        TypedArray a =
405            context.obtainStyledAttributes(
406                attrs, com.android.internal.R.styleable.TextView, defStyle, 0);
407
408        int textColorHighlight = 0;
409        ColorStateList textColor = null;
410        ColorStateList textColorHint = null;
411        ColorStateList textColorLink = null;
412        int textSize = 15;
413        int typefaceIndex = -1;
414        int styleIndex = -1;
415
416        /*
417         * Look the appearance up without checking first if it exists because
418         * almost every TextView has one and it greatly simplifies the logic
419         * to be able to parse the appearance first and then let specific tags
420         * for this View override it.
421         */
422        TypedArray appearance = null;
423        int ap = a.getResourceId(com.android.internal.R.styleable.TextView_textAppearance, -1);
424        if (ap != -1) {
425            appearance = context.obtainStyledAttributes(ap,
426                                com.android.internal.R.styleable.
427                                TextAppearance);
428        }
429        if (appearance != null) {
430            int n = appearance.getIndexCount();
431            for (int i = 0; i < n; i++) {
432                int attr = appearance.getIndex(i);
433
434                switch (attr) {
435                case com.android.internal.R.styleable.TextAppearance_textColorHighlight:
436                    textColorHighlight = appearance.getColor(attr, textColorHighlight);
437                    break;
438
439                case com.android.internal.R.styleable.TextAppearance_textColor:
440                    textColor = appearance.getColorStateList(attr);
441                    break;
442
443                case com.android.internal.R.styleable.TextAppearance_textColorHint:
444                    textColorHint = appearance.getColorStateList(attr);
445                    break;
446
447                case com.android.internal.R.styleable.TextAppearance_textColorLink:
448                    textColorLink = appearance.getColorStateList(attr);
449                    break;
450
451                case com.android.internal.R.styleable.TextAppearance_textSize:
452                    textSize = appearance.getDimensionPixelSize(attr, textSize);
453                    break;
454
455                case com.android.internal.R.styleable.TextAppearance_typeface:
456                    typefaceIndex = appearance.getInt(attr, -1);
457                    break;
458
459                case com.android.internal.R.styleable.TextAppearance_textStyle:
460                    styleIndex = appearance.getInt(attr, -1);
461                    break;
462                }
463            }
464
465            appearance.recycle();
466        }
467
468        boolean editable = getDefaultEditable();
469        CharSequence inputMethod = null;
470        int numeric = 0;
471        CharSequence digits = null;
472        boolean phone = false;
473        boolean autotext = false;
474        int autocap = -1;
475        int buffertype = 0;
476        boolean selectallonfocus = false;
477        Drawable drawableLeft = null, drawableTop = null, drawableRight = null,
478            drawableBottom = null;
479        int drawablePadding = 0;
480        int ellipsize = -1;
481        boolean singleLine = false;
482        int maxlength = -1;
483        CharSequence text = "";
484        CharSequence hint = null;
485        int shadowcolor = 0;
486        float dx = 0, dy = 0, r = 0;
487        boolean password = false;
488        int inputType = EditorInfo.TYPE_NULL;
489
490        int n = a.getIndexCount();
491        for (int i = 0; i < n; i++) {
492            int attr = a.getIndex(i);
493
494            switch (attr) {
495            case com.android.internal.R.styleable.TextView_editable:
496                editable = a.getBoolean(attr, editable);
497                break;
498
499            case com.android.internal.R.styleable.TextView_inputMethod:
500                inputMethod = a.getText(attr);
501                break;
502
503            case com.android.internal.R.styleable.TextView_numeric:
504                numeric = a.getInt(attr, numeric);
505                break;
506
507            case com.android.internal.R.styleable.TextView_digits:
508                digits = a.getText(attr);
509                break;
510
511            case com.android.internal.R.styleable.TextView_phoneNumber:
512                phone = a.getBoolean(attr, phone);
513                break;
514
515            case com.android.internal.R.styleable.TextView_autoText:
516                autotext = a.getBoolean(attr, autotext);
517                break;
518
519            case com.android.internal.R.styleable.TextView_capitalize:
520                autocap = a.getInt(attr, autocap);
521                break;
522
523            case com.android.internal.R.styleable.TextView_bufferType:
524                buffertype = a.getInt(attr, buffertype);
525                break;
526
527            case com.android.internal.R.styleable.TextView_selectAllOnFocus:
528                selectallonfocus = a.getBoolean(attr, selectallonfocus);
529                break;
530
531            case com.android.internal.R.styleable.TextView_autoLink:
532                mAutoLinkMask = a.getInt(attr, 0);
533                break;
534
535            case com.android.internal.R.styleable.TextView_linksClickable:
536                mLinksClickable = a.getBoolean(attr, true);
537                break;
538
539            case com.android.internal.R.styleable.TextView_drawableLeft:
540                drawableLeft = a.getDrawable(attr);
541                break;
542
543            case com.android.internal.R.styleable.TextView_drawableTop:
544                drawableTop = a.getDrawable(attr);
545                break;
546
547            case com.android.internal.R.styleable.TextView_drawableRight:
548                drawableRight = a.getDrawable(attr);
549                break;
550
551            case com.android.internal.R.styleable.TextView_drawableBottom:
552                drawableBottom = a.getDrawable(attr);
553                break;
554
555            case com.android.internal.R.styleable.TextView_drawablePadding:
556                drawablePadding = a.getDimensionPixelSize(attr, drawablePadding);
557                break;
558
559            case com.android.internal.R.styleable.TextView_maxLines:
560                setMaxLines(a.getInt(attr, -1));
561                break;
562
563            case com.android.internal.R.styleable.TextView_maxHeight:
564                setMaxHeight(a.getDimensionPixelSize(attr, -1));
565                break;
566
567            case com.android.internal.R.styleable.TextView_lines:
568                setLines(a.getInt(attr, -1));
569                break;
570
571            case com.android.internal.R.styleable.TextView_height:
572                setHeight(a.getDimensionPixelSize(attr, -1));
573                break;
574
575            case com.android.internal.R.styleable.TextView_minLines:
576                setMinLines(a.getInt(attr, -1));
577                break;
578
579            case com.android.internal.R.styleable.TextView_minHeight:
580                setMinHeight(a.getDimensionPixelSize(attr, -1));
581                break;
582
583            case com.android.internal.R.styleable.TextView_maxEms:
584                setMaxEms(a.getInt(attr, -1));
585                break;
586
587            case com.android.internal.R.styleable.TextView_maxWidth:
588                setMaxWidth(a.getDimensionPixelSize(attr, -1));
589                break;
590
591            case com.android.internal.R.styleable.TextView_ems:
592                setEms(a.getInt(attr, -1));
593                break;
594
595            case com.android.internal.R.styleable.TextView_width:
596                setWidth(a.getDimensionPixelSize(attr, -1));
597                break;
598
599            case com.android.internal.R.styleable.TextView_minEms:
600                setMinEms(a.getInt(attr, -1));
601                break;
602
603            case com.android.internal.R.styleable.TextView_minWidth:
604                setMinWidth(a.getDimensionPixelSize(attr, -1));
605                break;
606
607            case com.android.internal.R.styleable.TextView_gravity:
608                setGravity(a.getInt(attr, -1));
609                break;
610
611            case com.android.internal.R.styleable.TextView_hint:
612                hint = a.getText(attr);
613                break;
614
615            case com.android.internal.R.styleable.TextView_text:
616                text = a.getText(attr);
617                break;
618
619            case com.android.internal.R.styleable.TextView_scrollHorizontally:
620                if (a.getBoolean(attr, false)) {
621                    setHorizontallyScrolling(true);
622                }
623                break;
624
625            case com.android.internal.R.styleable.TextView_singleLine:
626                singleLine = a.getBoolean(attr, singleLine);
627                break;
628
629            case com.android.internal.R.styleable.TextView_ellipsize:
630                ellipsize = a.getInt(attr, ellipsize);
631                break;
632
633            case com.android.internal.R.styleable.TextView_marqueeRepeatLimit:
634                setMarqueeRepeatLimit(a.getInt(attr, mMarqueeRepeatLimit));
635                break;
636
637            case com.android.internal.R.styleable.TextView_includeFontPadding:
638                if (!a.getBoolean(attr, true)) {
639                    setIncludeFontPadding(false);
640                }
641                break;
642
643            case com.android.internal.R.styleable.TextView_cursorVisible:
644                if (!a.getBoolean(attr, true)) {
645                    setCursorVisible(false);
646                }
647                break;
648
649            case com.android.internal.R.styleable.TextView_maxLength:
650                maxlength = a.getInt(attr, -1);
651                break;
652
653            case com.android.internal.R.styleable.TextView_textScaleX:
654                setTextScaleX(a.getFloat(attr, 1.0f));
655                break;
656
657            case com.android.internal.R.styleable.TextView_freezesText:
658                mFreezesText = a.getBoolean(attr, false);
659                break;
660
661            case com.android.internal.R.styleable.TextView_shadowColor:
662                shadowcolor = a.getInt(attr, 0);
663                break;
664
665            case com.android.internal.R.styleable.TextView_shadowDx:
666                dx = a.getFloat(attr, 0);
667                break;
668
669            case com.android.internal.R.styleable.TextView_shadowDy:
670                dy = a.getFloat(attr, 0);
671                break;
672
673            case com.android.internal.R.styleable.TextView_shadowRadius:
674                r = a.getFloat(attr, 0);
675                break;
676
677            case com.android.internal.R.styleable.TextView_enabled:
678                setEnabled(a.getBoolean(attr, isEnabled()));
679                break;
680
681            case com.android.internal.R.styleable.TextView_textColorHighlight:
682                textColorHighlight = a.getColor(attr, textColorHighlight);
683                break;
684
685            case com.android.internal.R.styleable.TextView_textColor:
686                textColor = a.getColorStateList(attr);
687                break;
688
689            case com.android.internal.R.styleable.TextView_textColorHint:
690                textColorHint = a.getColorStateList(attr);
691                break;
692
693            case com.android.internal.R.styleable.TextView_textColorLink:
694                textColorLink = a.getColorStateList(attr);
695                break;
696
697            case com.android.internal.R.styleable.TextView_textSize:
698                textSize = a.getDimensionPixelSize(attr, textSize);
699                break;
700
701            case com.android.internal.R.styleable.TextView_typeface:
702                typefaceIndex = a.getInt(attr, typefaceIndex);
703                break;
704
705            case com.android.internal.R.styleable.TextView_textStyle:
706                styleIndex = a.getInt(attr, styleIndex);
707                break;
708
709            case com.android.internal.R.styleable.TextView_password:
710                password = a.getBoolean(attr, password);
711                break;
712
713            case com.android.internal.R.styleable.TextView_lineSpacingExtra:
714                mSpacingAdd = a.getDimensionPixelSize(attr, (int) mSpacingAdd);
715                break;
716
717            case com.android.internal.R.styleable.TextView_lineSpacingMultiplier:
718                mSpacingMult = a.getFloat(attr, mSpacingMult);
719                break;
720
721            case com.android.internal.R.styleable.TextView_inputType:
722                inputType = a.getInt(attr, mInputType);
723                break;
724
725            case com.android.internal.R.styleable.TextView_imeOptions:
726                if (mInputContentType == null) {
727                    mInputContentType = new InputContentType();
728                }
729                mInputContentType.imeOptions = a.getInt(attr,
730                        mInputContentType.imeOptions);
731                break;
732
733            case com.android.internal.R.styleable.TextView_imeActionLabel:
734                if (mInputContentType == null) {
735                    mInputContentType = new InputContentType();
736                }
737                mInputContentType.imeActionLabel = a.getText(attr);
738                break;
739
740            case com.android.internal.R.styleable.TextView_imeActionId:
741                if (mInputContentType == null) {
742                    mInputContentType = new InputContentType();
743                }
744                mInputContentType.imeActionId = a.getInt(attr,
745                        mInputContentType.imeActionId);
746                break;
747
748            case com.android.internal.R.styleable.TextView_privateImeOptions:
749                setPrivateImeOptions(a.getString(attr));
750                break;
751
752            case com.android.internal.R.styleable.TextView_editorExtras:
753                try {
754                    setInputExtras(a.getResourceId(attr, 0));
755                } catch (XmlPullParserException e) {
756                    Log.w(LOG_TAG, "Failure reading input extras", e);
757                } catch (IOException e) {
758                    Log.w(LOG_TAG, "Failure reading input extras", e);
759                }
760                break;
761
762            case com.android.internal.R.styleable.TextView_textCursorDrawable:
763                mCursorDrawableRes = a.getResourceId(attr, 0);
764                break;
765
766            case com.android.internal.R.styleable.TextView_textSelectHandleLeft:
767                mTextSelectHandleLeftRes = a.getResourceId(attr, 0);
768                break;
769
770            case com.android.internal.R.styleable.TextView_textSelectHandleRight:
771                mTextSelectHandleRightRes = a.getResourceId(attr, 0);
772                break;
773
774            case com.android.internal.R.styleable.TextView_textSelectHandle:
775                mTextSelectHandleRes = a.getResourceId(attr, 0);
776                break;
777
778            case com.android.internal.R.styleable.TextView_textEditPasteWindowLayout:
779                mTextEditPasteWindowLayout = a.getResourceId(attr, 0);
780                break;
781
782            case com.android.internal.R.styleable.TextView_textEditNoPasteWindowLayout:
783                mTextEditNoPasteWindowLayout = a.getResourceId(attr, 0);
784                break;
785
786            case com.android.internal.R.styleable.TextView_textEditSidePasteWindowLayout:
787                mTextEditSidePasteWindowLayout = a.getResourceId(attr, 0);
788                break;
789
790            case com.android.internal.R.styleable.TextView_textEditSideNoPasteWindowLayout:
791                mTextEditSideNoPasteWindowLayout = a.getResourceId(attr, 0);
792                break;
793
794            case com.android.internal.R.styleable.TextView_textEditSuggestionsBottomWindowLayout:
795                mTextEditSuggestionsBottomWindowLayout = a.getResourceId(attr, 0);
796                break;
797
798            case com.android.internal.R.styleable.TextView_textEditSuggestionsTopWindowLayout:
799                mTextEditSuggestionsTopWindowLayout = a.getResourceId(attr, 0);
800                break;
801
802            case com.android.internal.R.styleable.TextView_textEditSuggestionItemLayout:
803                mTextEditSuggestionItemLayout = a.getResourceId(attr, 0);
804                break;
805
806            case com.android.internal.R.styleable.TextView_textIsSelectable:
807                mTextIsSelectable = a.getBoolean(attr, false);
808                break;
809            }
810        }
811        a.recycle();
812
813        BufferType bufferType = BufferType.EDITABLE;
814
815        final int variation =
816                inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION);
817        final boolean passwordInputType = variation
818                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
819        final boolean webPasswordInputType = variation
820                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD);
821        final boolean numberPasswordInputType = variation
822                == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD);
823
824        if (inputMethod != null) {
825            Class<?> c;
826
827            try {
828                c = Class.forName(inputMethod.toString());
829            } catch (ClassNotFoundException ex) {
830                throw new RuntimeException(ex);
831            }
832
833            try {
834                mInput = (KeyListener) c.newInstance();
835            } catch (InstantiationException ex) {
836                throw new RuntimeException(ex);
837            } catch (IllegalAccessException ex) {
838                throw new RuntimeException(ex);
839            }
840            try {
841                mInputType = inputType != EditorInfo.TYPE_NULL
842                        ? inputType
843                        : mInput.getInputType();
844            } catch (IncompatibleClassChangeError e) {
845                mInputType = EditorInfo.TYPE_CLASS_TEXT;
846            }
847        } else if (digits != null) {
848            mInput = DigitsKeyListener.getInstance(digits.toString());
849            // If no input type was specified, we will default to generic
850            // text, since we can't tell the IME about the set of digits
851            // that was selected.
852            mInputType = inputType != EditorInfo.TYPE_NULL
853                    ? inputType : EditorInfo.TYPE_CLASS_TEXT;
854        } else if (inputType != EditorInfo.TYPE_NULL) {
855            setInputType(inputType, true);
856            // If set, the input type overrides what was set using the deprecated singleLine flag.
857            singleLine = !isMultilineInputType(inputType);
858        } else if (phone) {
859            mInput = DialerKeyListener.getInstance();
860            mInputType = inputType = EditorInfo.TYPE_CLASS_PHONE;
861        } else if (numeric != 0) {
862            mInput = DigitsKeyListener.getInstance((numeric & SIGNED) != 0,
863                                                   (numeric & DECIMAL) != 0);
864            inputType = EditorInfo.TYPE_CLASS_NUMBER;
865            if ((numeric & SIGNED) != 0) {
866                inputType |= EditorInfo.TYPE_NUMBER_FLAG_SIGNED;
867            }
868            if ((numeric & DECIMAL) != 0) {
869                inputType |= EditorInfo.TYPE_NUMBER_FLAG_DECIMAL;
870            }
871            mInputType = inputType;
872        } else if (autotext || autocap != -1) {
873            TextKeyListener.Capitalize cap;
874
875            inputType = EditorInfo.TYPE_CLASS_TEXT;
876
877            switch (autocap) {
878            case 1:
879                cap = TextKeyListener.Capitalize.SENTENCES;
880                inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES;
881                break;
882
883            case 2:
884                cap = TextKeyListener.Capitalize.WORDS;
885                inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS;
886                break;
887
888            case 3:
889                cap = TextKeyListener.Capitalize.CHARACTERS;
890                inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS;
891                break;
892
893            default:
894                cap = TextKeyListener.Capitalize.NONE;
895                break;
896            }
897
898            mInput = TextKeyListener.getInstance(autotext, cap);
899            mInputType = inputType;
900        } else if (mTextIsSelectable) {
901            // Prevent text changes from keyboard.
902            mInputType = EditorInfo.TYPE_NULL;
903            mInput = null;
904            bufferType = BufferType.SPANNABLE;
905            // Required to request focus while in touch mode.
906            setFocusableInTouchMode(true);
907            // So that selection can be changed using arrow keys and touch is handled.
908            setMovementMethod(ArrowKeyMovementMethod.getInstance());
909        } else if (editable) {
910            mInput = TextKeyListener.getInstance();
911            mInputType = EditorInfo.TYPE_CLASS_TEXT;
912        } else {
913            mInput = null;
914
915            switch (buffertype) {
916                case 0:
917                    bufferType = BufferType.NORMAL;
918                    break;
919                case 1:
920                    bufferType = BufferType.SPANNABLE;
921                    break;
922                case 2:
923                    bufferType = BufferType.EDITABLE;
924                    break;
925            }
926        }
927
928        // mInputType has been set from inputType, possibly modified by mInputMethod.
929        // Specialize mInputType to [web]password if we have a text class and the original input
930        // type was a password.
931        if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
932            if (password || passwordInputType) {
933                mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
934                        | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD;
935            }
936            if (webPasswordInputType) {
937                mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
938                        | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD;
939            }
940        } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) {
941            if (numberPasswordInputType) {
942                mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
943                        | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD;
944            }
945        }
946
947        if (selectallonfocus) {
948            mSelectAllOnFocus = true;
949
950            if (bufferType == BufferType.NORMAL)
951                bufferType = BufferType.SPANNABLE;
952        }
953
954        setCompoundDrawablesWithIntrinsicBounds(
955            drawableLeft, drawableTop, drawableRight, drawableBottom);
956        setCompoundDrawablePadding(drawablePadding);
957
958        // Same as setSingleLine(), but make sure the transformation method and the maximum number
959        // of lines of height are unchanged for multi-line TextViews.
960        setInputTypeSingleLine(singleLine);
961        applySingleLine(singleLine, singleLine, singleLine);
962
963        if (singleLine && mInput == null && ellipsize < 0) {
964                ellipsize = 3; // END
965        }
966
967        switch (ellipsize) {
968            case 1:
969                setEllipsize(TextUtils.TruncateAt.START);
970                break;
971            case 2:
972                setEllipsize(TextUtils.TruncateAt.MIDDLE);
973                break;
974            case 3:
975                setEllipsize(TextUtils.TruncateAt.END);
976                break;
977            case 4:
978                setHorizontalFadingEdgeEnabled(true);
979                setEllipsize(TextUtils.TruncateAt.MARQUEE);
980                break;
981        }
982
983        setTextColor(textColor != null ? textColor : ColorStateList.valueOf(0xFF000000));
984        setHintTextColor(textColorHint);
985        setLinkTextColor(textColorLink);
986        if (textColorHighlight != 0) {
987            setHighlightColor(textColorHighlight);
988        }
989        setRawTextSize(textSize);
990
991        if (password || passwordInputType || webPasswordInputType || numberPasswordInputType) {
992            setTransformationMethod(PasswordTransformationMethod.getInstance());
993            typefaceIndex = MONOSPACE;
994        } else if ((mInputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION))
995                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) {
996            typefaceIndex = MONOSPACE;
997        }
998
999        setTypefaceByIndex(typefaceIndex, styleIndex);
1000
1001        if (shadowcolor != 0) {
1002            setShadowLayer(r, dx, dy, shadowcolor);
1003        }
1004
1005        if (maxlength >= 0) {
1006            setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) });
1007        } else {
1008            setFilters(NO_FILTERS);
1009        }
1010
1011        setText(text, bufferType);
1012        if (hint != null) setHint(hint);
1013
1014        /*
1015         * Views are not normally focusable unless specified to be.
1016         * However, TextViews that have input or movement methods *are*
1017         * focusable by default.
1018         */
1019        a = context.obtainStyledAttributes(attrs,
1020                                           com.android.internal.R.styleable.View,
1021                                           defStyle, 0);
1022
1023        boolean focusable = mMovement != null || mInput != null;
1024        boolean clickable = focusable;
1025        boolean longClickable = focusable;
1026
1027        n = a.getIndexCount();
1028        for (int i = 0; i < n; i++) {
1029            int attr = a.getIndex(i);
1030
1031            switch (attr) {
1032            case com.android.internal.R.styleable.View_focusable:
1033                focusable = a.getBoolean(attr, focusable);
1034                break;
1035
1036            case com.android.internal.R.styleable.View_clickable:
1037                clickable = a.getBoolean(attr, clickable);
1038                break;
1039
1040            case com.android.internal.R.styleable.View_longClickable:
1041                longClickable = a.getBoolean(attr, longClickable);
1042                break;
1043            }
1044        }
1045        a.recycle();
1046
1047        setFocusable(focusable);
1048        setClickable(clickable);
1049        setLongClickable(longClickable);
1050
1051        prepareCursorControllers();
1052
1053        final ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
1054        final int touchSlop = viewConfiguration.getScaledTouchSlop();
1055        mSquaredTouchSlopDistance = touchSlop * touchSlop;
1056    }
1057
1058    private void setTypefaceByIndex(int typefaceIndex, int styleIndex) {
1059        Typeface tf = null;
1060        switch (typefaceIndex) {
1061            case SANS:
1062                tf = Typeface.SANS_SERIF;
1063                break;
1064
1065            case SERIF:
1066                tf = Typeface.SERIF;
1067                break;
1068
1069            case MONOSPACE:
1070                tf = Typeface.MONOSPACE;
1071                break;
1072        }
1073
1074        setTypeface(tf, styleIndex);
1075    }
1076
1077    @Override
1078    public void setEnabled(boolean enabled) {
1079        if (enabled == isEnabled()) {
1080            return;
1081        }
1082
1083        if (!enabled) {
1084            // Hide the soft input if the currently active TextView is disabled
1085            InputMethodManager imm = InputMethodManager.peekInstance();
1086            if (imm != null && imm.isActive(this)) {
1087                imm.hideSoftInputFromWindow(getWindowToken(), 0);
1088            }
1089        }
1090        super.setEnabled(enabled);
1091    }
1092
1093    /**
1094     * Sets the typeface and style in which the text should be displayed,
1095     * and turns on the fake bold and italic bits in the Paint if the
1096     * Typeface that you provided does not have all the bits in the
1097     * style that you specified.
1098     *
1099     * @attr ref android.R.styleable#TextView_typeface
1100     * @attr ref android.R.styleable#TextView_textStyle
1101     */
1102    public void setTypeface(Typeface tf, int style) {
1103        if (style > 0) {
1104            if (tf == null) {
1105                tf = Typeface.defaultFromStyle(style);
1106            } else {
1107                tf = Typeface.create(tf, style);
1108            }
1109
1110            setTypeface(tf);
1111            // now compute what (if any) algorithmic styling is needed
1112            int typefaceStyle = tf != null ? tf.getStyle() : 0;
1113            int need = style & ~typefaceStyle;
1114            mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
1115            mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
1116        } else {
1117            mTextPaint.setFakeBoldText(false);
1118            mTextPaint.setTextSkewX(0);
1119            setTypeface(tf);
1120        }
1121    }
1122
1123    /**
1124     * Subclasses override this to specify that they have a KeyListener
1125     * by default even if not specifically called for in the XML options.
1126     */
1127    protected boolean getDefaultEditable() {
1128        return false;
1129    }
1130
1131    /**
1132     * Subclasses override this to specify a default movement method.
1133     */
1134    protected MovementMethod getDefaultMovementMethod() {
1135        return null;
1136    }
1137
1138    /**
1139     * Return the text the TextView is displaying. If setText() was called with
1140     * an argument of BufferType.SPANNABLE or BufferType.EDITABLE, you can cast
1141     * the return value from this method to Spannable or Editable, respectively.
1142     *
1143     * Note: The content of the return value should not be modified. If you want
1144     * a modifiable one, you should make your own copy first.
1145     */
1146    @ViewDebug.CapturedViewProperty
1147    public CharSequence getText() {
1148        return mText;
1149    }
1150
1151    /**
1152     * Returns the length, in characters, of the text managed by this TextView
1153     */
1154    public int length() {
1155        return mText.length();
1156    }
1157
1158    /**
1159     * Return the text the TextView is displaying as an Editable object.  If
1160     * the text is not editable, null is returned.
1161     *
1162     * @see #getText
1163     */
1164    public Editable getEditableText() {
1165        return (mText instanceof Editable) ? (Editable)mText : null;
1166    }
1167
1168    /**
1169     * @return the height of one standard line in pixels.  Note that markup
1170     * within the text can cause individual lines to be taller or shorter
1171     * than this height, and the layout may contain additional first-
1172     * or last-line padding.
1173     */
1174    public int getLineHeight() {
1175        return FastMath.round(mTextPaint.getFontMetricsInt(null) * mSpacingMult + mSpacingAdd);
1176    }
1177
1178    /**
1179     * @return the Layout that is currently being used to display the text.
1180     * This can be null if the text or width has recently changes.
1181     */
1182    public final Layout getLayout() {
1183        return mLayout;
1184    }
1185
1186    /**
1187     * @return the current key listener for this TextView.
1188     * This will frequently be null for non-EditText TextViews.
1189     */
1190    public final KeyListener getKeyListener() {
1191        return mInput;
1192    }
1193
1194    /**
1195     * Sets the key listener to be used with this TextView.  This can be null
1196     * to disallow user input.  Note that this method has significant and
1197     * subtle interactions with soft keyboards and other input method:
1198     * see {@link KeyListener#getInputType() KeyListener.getContentType()}
1199     * for important details.  Calling this method will replace the current
1200     * content type of the text view with the content type returned by the
1201     * key listener.
1202     * <p>
1203     * Be warned that if you want a TextView with a key listener or movement
1204     * method not to be focusable, or if you want a TextView without a
1205     * key listener or movement method to be focusable, you must call
1206     * {@link #setFocusable} again after calling this to get the focusability
1207     * back the way you want it.
1208     *
1209     * @attr ref android.R.styleable#TextView_numeric
1210     * @attr ref android.R.styleable#TextView_digits
1211     * @attr ref android.R.styleable#TextView_phoneNumber
1212     * @attr ref android.R.styleable#TextView_inputMethod
1213     * @attr ref android.R.styleable#TextView_capitalize
1214     * @attr ref android.R.styleable#TextView_autoText
1215     */
1216    public void setKeyListener(KeyListener input) {
1217        setKeyListenerOnly(input);
1218        fixFocusableAndClickableSettings();
1219
1220        if (input != null) {
1221            try {
1222                mInputType = mInput.getInputType();
1223            } catch (IncompatibleClassChangeError e) {
1224                mInputType = EditorInfo.TYPE_CLASS_TEXT;
1225            }
1226            // Change inputType, without affecting transformation.
1227            // No need to applySingleLine since mSingleLine is unchanged.
1228            setInputTypeSingleLine(mSingleLine);
1229        } else {
1230            mInputType = EditorInfo.TYPE_NULL;
1231        }
1232
1233        InputMethodManager imm = InputMethodManager.peekInstance();
1234        if (imm != null) imm.restartInput(this);
1235    }
1236
1237    private void setKeyListenerOnly(KeyListener input) {
1238        mInput = input;
1239        if (mInput != null && !(mText instanceof Editable))
1240            setText(mText);
1241
1242        setFilters((Editable) mText, mFilters);
1243    }
1244
1245    /**
1246     * @return the movement method being used for this TextView.
1247     * This will frequently be null for non-EditText TextViews.
1248     */
1249    public final MovementMethod getMovementMethod() {
1250        return mMovement;
1251    }
1252
1253    /**
1254     * Sets the movement method (arrow key handler) to be used for
1255     * this TextView.  This can be null to disallow using the arrow keys
1256     * to move the cursor or scroll the view.
1257     * <p>
1258     * Be warned that if you want a TextView with a key listener or movement
1259     * method not to be focusable, or if you want a TextView without a
1260     * key listener or movement method to be focusable, you must call
1261     * {@link #setFocusable} again after calling this to get the focusability
1262     * back the way you want it.
1263     */
1264    public final void setMovementMethod(MovementMethod movement) {
1265        mMovement = movement;
1266
1267        if (mMovement != null && !(mText instanceof Spannable))
1268            setText(mText);
1269
1270        fixFocusableAndClickableSettings();
1271
1272        // SelectionModifierCursorController depends on textCanBeSelected, which depends on mMovement
1273        prepareCursorControllers();
1274    }
1275
1276    private void fixFocusableAndClickableSettings() {
1277        if ((mMovement != null) || mInput != null) {
1278            setFocusable(true);
1279            setClickable(true);
1280            setLongClickable(true);
1281        } else {
1282            setFocusable(false);
1283            setClickable(false);
1284            setLongClickable(false);
1285        }
1286    }
1287
1288    /**
1289     * @return the current transformation method for this TextView.
1290     * This will frequently be null except for single-line and password
1291     * fields.
1292     */
1293    public final TransformationMethod getTransformationMethod() {
1294        return mTransformation;
1295    }
1296
1297    /**
1298     * Sets the transformation that is applied to the text that this
1299     * TextView is displaying.
1300     *
1301     * @attr ref android.R.styleable#TextView_password
1302     * @attr ref android.R.styleable#TextView_singleLine
1303     */
1304    public final void setTransformationMethod(TransformationMethod method) {
1305        if (method == mTransformation) {
1306            // Avoid the setText() below if the transformation is
1307            // the same.
1308            return;
1309        }
1310        if (mTransformation != null) {
1311            if (mText instanceof Spannable) {
1312                ((Spannable) mText).removeSpan(mTransformation);
1313            }
1314        }
1315
1316        mTransformation = method;
1317
1318        setText(mText);
1319    }
1320
1321    /**
1322     * Returns the top padding of the view, plus space for the top
1323     * Drawable if any.
1324     */
1325    public int getCompoundPaddingTop() {
1326        final Drawables dr = mDrawables;
1327        if (dr == null || dr.mDrawableTop == null) {
1328            return mPaddingTop;
1329        } else {
1330            return mPaddingTop + dr.mDrawablePadding + dr.mDrawableSizeTop;
1331        }
1332    }
1333
1334    /**
1335     * Returns the bottom padding of the view, plus space for the bottom
1336     * Drawable if any.
1337     */
1338    public int getCompoundPaddingBottom() {
1339        final Drawables dr = mDrawables;
1340        if (dr == null || dr.mDrawableBottom == null) {
1341            return mPaddingBottom;
1342        } else {
1343            return mPaddingBottom + dr.mDrawablePadding + dr.mDrawableSizeBottom;
1344        }
1345    }
1346
1347    /**
1348     * Returns the left padding of the view, plus space for the left
1349     * Drawable if any.
1350     */
1351    public int getCompoundPaddingLeft() {
1352        final Drawables dr = mDrawables;
1353        if (dr == null || dr.mDrawableLeft == null) {
1354            return mPaddingLeft;
1355        } else {
1356            return mPaddingLeft + dr.mDrawablePadding + dr.mDrawableSizeLeft;
1357        }
1358    }
1359
1360    /**
1361     * Returns the right padding of the view, plus space for the right
1362     * Drawable if any.
1363     */
1364    public int getCompoundPaddingRight() {
1365        final Drawables dr = mDrawables;
1366        if (dr == null || dr.mDrawableRight == null) {
1367            return mPaddingRight;
1368        } else {
1369            return mPaddingRight + dr.mDrawablePadding + dr.mDrawableSizeRight;
1370        }
1371    }
1372
1373    /**
1374     * Returns the extended top padding of the view, including both the
1375     * top Drawable if any and any extra space to keep more than maxLines
1376     * of text from showing.  It is only valid to call this after measuring.
1377     */
1378    public int getExtendedPaddingTop() {
1379        if (mMaxMode != LINES) {
1380            return getCompoundPaddingTop();
1381        }
1382
1383        if (mLayout.getLineCount() <= mMaximum) {
1384            return getCompoundPaddingTop();
1385        }
1386
1387        int top = getCompoundPaddingTop();
1388        int bottom = getCompoundPaddingBottom();
1389        int viewht = getHeight() - top - bottom;
1390        int layoutht = mLayout.getLineTop(mMaximum);
1391
1392        if (layoutht >= viewht) {
1393            return top;
1394        }
1395
1396        final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
1397        if (gravity == Gravity.TOP) {
1398            return top;
1399        } else if (gravity == Gravity.BOTTOM) {
1400            return top + viewht - layoutht;
1401        } else { // (gravity == Gravity.CENTER_VERTICAL)
1402            return top + (viewht - layoutht) / 2;
1403        }
1404    }
1405
1406    /**
1407     * Returns the extended bottom padding of the view, including both the
1408     * bottom Drawable if any and any extra space to keep more than maxLines
1409     * of text from showing.  It is only valid to call this after measuring.
1410     */
1411    public int getExtendedPaddingBottom() {
1412        if (mMaxMode != LINES) {
1413            return getCompoundPaddingBottom();
1414        }
1415
1416        if (mLayout.getLineCount() <= mMaximum) {
1417            return getCompoundPaddingBottom();
1418        }
1419
1420        int top = getCompoundPaddingTop();
1421        int bottom = getCompoundPaddingBottom();
1422        int viewht = getHeight() - top - bottom;
1423        int layoutht = mLayout.getLineTop(mMaximum);
1424
1425        if (layoutht >= viewht) {
1426            return bottom;
1427        }
1428
1429        final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
1430        if (gravity == Gravity.TOP) {
1431            return bottom + viewht - layoutht;
1432        } else if (gravity == Gravity.BOTTOM) {
1433            return bottom;
1434        } else { // (gravity == Gravity.CENTER_VERTICAL)
1435            return bottom + (viewht - layoutht) / 2;
1436        }
1437    }
1438
1439    /**
1440     * Returns the total left padding of the view, including the left
1441     * Drawable if any.
1442     */
1443    public int getTotalPaddingLeft() {
1444        return getCompoundPaddingLeft();
1445    }
1446
1447    /**
1448     * Returns the total right padding of the view, including the right
1449     * Drawable if any.
1450     */
1451    public int getTotalPaddingRight() {
1452        return getCompoundPaddingRight();
1453    }
1454
1455    /**
1456     * Returns the total top padding of the view, including the top
1457     * Drawable if any, the extra space to keep more than maxLines
1458     * from showing, and the vertical offset for gravity, if any.
1459     */
1460    public int getTotalPaddingTop() {
1461        return getExtendedPaddingTop() + getVerticalOffset(true);
1462    }
1463
1464    /**
1465     * Returns the total bottom padding of the view, including the bottom
1466     * Drawable if any, the extra space to keep more than maxLines
1467     * from showing, and the vertical offset for gravity, if any.
1468     */
1469    public int getTotalPaddingBottom() {
1470        return getExtendedPaddingBottom() + getBottomVerticalOffset(true);
1471    }
1472
1473    /**
1474     * Sets the Drawables (if any) to appear to the left of, above,
1475     * to the right of, and below the text.  Use null if you do not
1476     * want a Drawable there.  The Drawables must already have had
1477     * {@link Drawable#setBounds} called.
1478     *
1479     * @attr ref android.R.styleable#TextView_drawableLeft
1480     * @attr ref android.R.styleable#TextView_drawableTop
1481     * @attr ref android.R.styleable#TextView_drawableRight
1482     * @attr ref android.R.styleable#TextView_drawableBottom
1483     */
1484    public void setCompoundDrawables(Drawable left, Drawable top,
1485                                     Drawable right, Drawable bottom) {
1486        Drawables dr = mDrawables;
1487
1488        final boolean drawables = left != null || top != null
1489                || right != null || bottom != null;
1490
1491        if (!drawables) {
1492            // Clearing drawables...  can we free the data structure?
1493            if (dr != null) {
1494                if (dr.mDrawablePadding == 0) {
1495                    mDrawables = null;
1496                } else {
1497                    // We need to retain the last set padding, so just clear
1498                    // out all of the fields in the existing structure.
1499                    if (dr.mDrawableLeft != null) dr.mDrawableLeft.setCallback(null);
1500                    dr.mDrawableLeft = null;
1501                    if (dr.mDrawableTop != null) dr.mDrawableTop.setCallback(null);
1502                    dr.mDrawableTop = null;
1503                    if (dr.mDrawableRight != null) dr.mDrawableRight.setCallback(null);
1504                    dr.mDrawableRight = null;
1505                    if (dr.mDrawableBottom != null) dr.mDrawableBottom.setCallback(null);
1506                    dr.mDrawableBottom = null;
1507                    dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0;
1508                    dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0;
1509                    dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0;
1510                    dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0;
1511                }
1512            }
1513        } else {
1514            if (dr == null) {
1515                mDrawables = dr = new Drawables();
1516            }
1517
1518            if (dr.mDrawableLeft != left && dr.mDrawableLeft != null) {
1519                dr.mDrawableLeft.setCallback(null);
1520            }
1521            dr.mDrawableLeft = left;
1522
1523            if (dr.mDrawableTop != top && dr.mDrawableTop != null) {
1524                dr.mDrawableTop.setCallback(null);
1525            }
1526            dr.mDrawableTop = top;
1527
1528            if (dr.mDrawableRight != right && dr.mDrawableRight != null) {
1529                dr.mDrawableRight.setCallback(null);
1530            }
1531            dr.mDrawableRight = right;
1532
1533            if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) {
1534                dr.mDrawableBottom.setCallback(null);
1535            }
1536            dr.mDrawableBottom = bottom;
1537
1538            final Rect compoundRect = dr.mCompoundRect;
1539            int[] state;
1540
1541            state = getDrawableState();
1542
1543            if (left != null) {
1544                left.setState(state);
1545                left.copyBounds(compoundRect);
1546                left.setCallback(this);
1547                dr.mDrawableSizeLeft = compoundRect.width();
1548                dr.mDrawableHeightLeft = compoundRect.height();
1549            } else {
1550                dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0;
1551            }
1552
1553            if (right != null) {
1554                right.setState(state);
1555                right.copyBounds(compoundRect);
1556                right.setCallback(this);
1557                dr.mDrawableSizeRight = compoundRect.width();
1558                dr.mDrawableHeightRight = compoundRect.height();
1559            } else {
1560                dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0;
1561            }
1562
1563            if (top != null) {
1564                top.setState(state);
1565                top.copyBounds(compoundRect);
1566                top.setCallback(this);
1567                dr.mDrawableSizeTop = compoundRect.height();
1568                dr.mDrawableWidthTop = compoundRect.width();
1569            } else {
1570                dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0;
1571            }
1572
1573            if (bottom != null) {
1574                bottom.setState(state);
1575                bottom.copyBounds(compoundRect);
1576                bottom.setCallback(this);
1577                dr.mDrawableSizeBottom = compoundRect.height();
1578                dr.mDrawableWidthBottom = compoundRect.width();
1579            } else {
1580                dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0;
1581            }
1582        }
1583
1584        invalidate();
1585        requestLayout();
1586    }
1587
1588    /**
1589     * Sets the Drawables (if any) to appear to the left of, above,
1590     * to the right of, and below the text.  Use 0 if you do not
1591     * want a Drawable there. The Drawables' bounds will be set to
1592     * their intrinsic bounds.
1593     *
1594     * @param left Resource identifier of the left Drawable.
1595     * @param top Resource identifier of the top Drawable.
1596     * @param right Resource identifier of the right Drawable.
1597     * @param bottom Resource identifier of the bottom Drawable.
1598     *
1599     * @attr ref android.R.styleable#TextView_drawableLeft
1600     * @attr ref android.R.styleable#TextView_drawableTop
1601     * @attr ref android.R.styleable#TextView_drawableRight
1602     * @attr ref android.R.styleable#TextView_drawableBottom
1603     */
1604    public void setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) {
1605        final Resources resources = getContext().getResources();
1606        setCompoundDrawablesWithIntrinsicBounds(left != 0 ? resources.getDrawable(left) : null,
1607                top != 0 ? resources.getDrawable(top) : null,
1608                right != 0 ? resources.getDrawable(right) : null,
1609                bottom != 0 ? resources.getDrawable(bottom) : null);
1610    }
1611
1612    /**
1613     * Sets the Drawables (if any) to appear to the left of, above,
1614     * to the right of, and below the text.  Use null if you do not
1615     * want a Drawable there. The Drawables' bounds will be set to
1616     * their intrinsic bounds.
1617     *
1618     * @attr ref android.R.styleable#TextView_drawableLeft
1619     * @attr ref android.R.styleable#TextView_drawableTop
1620     * @attr ref android.R.styleable#TextView_drawableRight
1621     * @attr ref android.R.styleable#TextView_drawableBottom
1622     */
1623    public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top,
1624            Drawable right, Drawable bottom) {
1625
1626        if (left != null) {
1627            left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight());
1628        }
1629        if (right != null) {
1630            right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight());
1631        }
1632        if (top != null) {
1633            top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight());
1634        }
1635        if (bottom != null) {
1636            bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight());
1637        }
1638        setCompoundDrawables(left, top, right, bottom);
1639    }
1640
1641    /**
1642     * Returns drawables for the left, top, right, and bottom borders.
1643     */
1644    public Drawable[] getCompoundDrawables() {
1645        final Drawables dr = mDrawables;
1646        if (dr != null) {
1647            return new Drawable[] {
1648                dr.mDrawableLeft, dr.mDrawableTop, dr.mDrawableRight, dr.mDrawableBottom
1649            };
1650        } else {
1651            return new Drawable[] { null, null, null, null };
1652        }
1653    }
1654
1655    /**
1656     * Sets the size of the padding between the compound drawables and
1657     * the text.
1658     *
1659     * @attr ref android.R.styleable#TextView_drawablePadding
1660     */
1661    public void setCompoundDrawablePadding(int pad) {
1662        Drawables dr = mDrawables;
1663        if (pad == 0) {
1664            if (dr != null) {
1665                dr.mDrawablePadding = pad;
1666            }
1667        } else {
1668            if (dr == null) {
1669                mDrawables = dr = new Drawables();
1670            }
1671            dr.mDrawablePadding = pad;
1672        }
1673
1674        invalidate();
1675        requestLayout();
1676    }
1677
1678    /**
1679     * Returns the padding between the compound drawables and the text.
1680     */
1681    public int getCompoundDrawablePadding() {
1682        final Drawables dr = mDrawables;
1683        return dr != null ? dr.mDrawablePadding : 0;
1684    }
1685
1686    @Override
1687    public void setPadding(int left, int top, int right, int bottom) {
1688        if (left != mPaddingLeft ||
1689            right != mPaddingRight ||
1690            top != mPaddingTop ||
1691            bottom != mPaddingBottom) {
1692            nullLayouts();
1693        }
1694
1695        // the super call will requestLayout()
1696        super.setPadding(left, top, right, bottom);
1697        invalidate();
1698    }
1699
1700    /**
1701     * Gets the autolink mask of the text.  See {@link
1702     * android.text.util.Linkify#ALL Linkify.ALL} and peers for
1703     * possible values.
1704     *
1705     * @attr ref android.R.styleable#TextView_autoLink
1706     */
1707    public final int getAutoLinkMask() {
1708        return mAutoLinkMask;
1709    }
1710
1711    /**
1712     * Sets the text color, size, style, hint color, and highlight color
1713     * from the specified TextAppearance resource.
1714     */
1715    public void setTextAppearance(Context context, int resid) {
1716        TypedArray appearance =
1717            context.obtainStyledAttributes(resid,
1718                                           com.android.internal.R.styleable.TextAppearance);
1719
1720        int color;
1721        ColorStateList colors;
1722        int ts;
1723
1724        color = appearance.getColor(com.android.internal.R.styleable.TextAppearance_textColorHighlight, 0);
1725        if (color != 0) {
1726            setHighlightColor(color);
1727        }
1728
1729        colors = appearance.getColorStateList(com.android.internal.R.styleable.
1730                                              TextAppearance_textColor);
1731        if (colors != null) {
1732            setTextColor(colors);
1733        }
1734
1735        ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable.
1736                                              TextAppearance_textSize, 0);
1737        if (ts != 0) {
1738            setRawTextSize(ts);
1739        }
1740
1741        colors = appearance.getColorStateList(com.android.internal.R.styleable.
1742                                              TextAppearance_textColorHint);
1743        if (colors != null) {
1744            setHintTextColor(colors);
1745        }
1746
1747        colors = appearance.getColorStateList(com.android.internal.R.styleable.
1748                                              TextAppearance_textColorLink);
1749        if (colors != null) {
1750            setLinkTextColor(colors);
1751        }
1752
1753        int typefaceIndex, styleIndex;
1754
1755        typefaceIndex = appearance.getInt(com.android.internal.R.styleable.
1756                                          TextAppearance_typeface, -1);
1757        styleIndex = appearance.getInt(com.android.internal.R.styleable.
1758                                       TextAppearance_textStyle, -1);
1759
1760        setTypefaceByIndex(typefaceIndex, styleIndex);
1761
1762        appearance.recycle();
1763    }
1764
1765    /**
1766     * @return the size (in pixels) of the default text size in this TextView.
1767     */
1768    public float getTextSize() {
1769        return mTextPaint.getTextSize();
1770    }
1771
1772    /**
1773     * Set the default text size to the given value, interpreted as "scaled
1774     * pixel" units.  This size is adjusted based on the current density and
1775     * user font size preference.
1776     *
1777     * @param size The scaled pixel size.
1778     *
1779     * @attr ref android.R.styleable#TextView_textSize
1780     */
1781    @android.view.RemotableViewMethod
1782    public void setTextSize(float size) {
1783        setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
1784    }
1785
1786    /**
1787     * Set the default text size to a given unit and value.  See {@link
1788     * TypedValue} for the possible dimension units.
1789     *
1790     * @param unit The desired dimension unit.
1791     * @param size The desired size in the given units.
1792     *
1793     * @attr ref android.R.styleable#TextView_textSize
1794     */
1795    public void setTextSize(int unit, float size) {
1796        Context c = getContext();
1797        Resources r;
1798
1799        if (c == null)
1800            r = Resources.getSystem();
1801        else
1802            r = c.getResources();
1803
1804        setRawTextSize(TypedValue.applyDimension(
1805            unit, size, r.getDisplayMetrics()));
1806    }
1807
1808    private void setRawTextSize(float size) {
1809        if (size != mTextPaint.getTextSize()) {
1810            mTextPaint.setTextSize(size);
1811
1812            if (mLayout != null) {
1813                nullLayouts();
1814                requestLayout();
1815                invalidate();
1816            }
1817        }
1818    }
1819
1820    /**
1821     * @return the extent by which text is currently being stretched
1822     * horizontally.  This will usually be 1.
1823     */
1824    public float getTextScaleX() {
1825        return mTextPaint.getTextScaleX();
1826    }
1827
1828    /**
1829     * Sets the extent by which text should be stretched horizontally.
1830     *
1831     * @attr ref android.R.styleable#TextView_textScaleX
1832     */
1833    @android.view.RemotableViewMethod
1834    public void setTextScaleX(float size) {
1835        if (size != mTextPaint.getTextScaleX()) {
1836            mUserSetTextScaleX = true;
1837            mTextPaint.setTextScaleX(size);
1838
1839            if (mLayout != null) {
1840                nullLayouts();
1841                requestLayout();
1842                invalidate();
1843            }
1844        }
1845    }
1846
1847    /**
1848     * Sets the typeface and style in which the text should be displayed.
1849     * Note that not all Typeface families actually have bold and italic
1850     * variants, so you may need to use
1851     * {@link #setTypeface(Typeface, int)} to get the appearance
1852     * that you actually want.
1853     *
1854     * @attr ref android.R.styleable#TextView_typeface
1855     * @attr ref android.R.styleable#TextView_textStyle
1856     */
1857    public void setTypeface(Typeface tf) {
1858        if (mTextPaint.getTypeface() != tf) {
1859            mTextPaint.setTypeface(tf);
1860
1861            if (mLayout != null) {
1862                nullLayouts();
1863                requestLayout();
1864                invalidate();
1865            }
1866        }
1867    }
1868
1869    /**
1870     * @return the current typeface and style in which the text is being
1871     * displayed.
1872     */
1873    public Typeface getTypeface() {
1874        return mTextPaint.getTypeface();
1875    }
1876
1877    /**
1878     * Sets the text color for all the states (normal, selected,
1879     * focused) to be this color.
1880     *
1881     * @attr ref android.R.styleable#TextView_textColor
1882     */
1883    @android.view.RemotableViewMethod
1884    public void setTextColor(int color) {
1885        mTextColor = ColorStateList.valueOf(color);
1886        updateTextColors();
1887    }
1888
1889    /**
1890     * Sets the text color.
1891     *
1892     * @attr ref android.R.styleable#TextView_textColor
1893     */
1894    public void setTextColor(ColorStateList colors) {
1895        if (colors == null) {
1896            throw new NullPointerException();
1897        }
1898
1899        mTextColor = colors;
1900        updateTextColors();
1901    }
1902
1903    /**
1904     * Return the set of text colors.
1905     *
1906     * @return Returns the set of text colors.
1907     */
1908    public final ColorStateList getTextColors() {
1909        return mTextColor;
1910    }
1911
1912    /**
1913     * <p>Return the current color selected for normal text.</p>
1914     *
1915     * @return Returns the current text color.
1916     */
1917    public final int getCurrentTextColor() {
1918        return mCurTextColor;
1919    }
1920
1921    /**
1922     * Sets the color used to display the selection highlight.
1923     *
1924     * @attr ref android.R.styleable#TextView_textColorHighlight
1925     */
1926    @android.view.RemotableViewMethod
1927    public void setHighlightColor(int color) {
1928        if (mHighlightColor != color) {
1929            mHighlightColor = color;
1930            invalidate();
1931        }
1932    }
1933
1934    /**
1935     * Gives the text a shadow of the specified radius and color, the specified
1936     * distance from its normal position.
1937     *
1938     * @attr ref android.R.styleable#TextView_shadowColor
1939     * @attr ref android.R.styleable#TextView_shadowDx
1940     * @attr ref android.R.styleable#TextView_shadowDy
1941     * @attr ref android.R.styleable#TextView_shadowRadius
1942     */
1943    public void setShadowLayer(float radius, float dx, float dy, int color) {
1944        mTextPaint.setShadowLayer(radius, dx, dy, color);
1945
1946        mShadowRadius = radius;
1947        mShadowDx = dx;
1948        mShadowDy = dy;
1949
1950        invalidate();
1951    }
1952
1953    /**
1954     * @return the base paint used for the text.  Please use this only to
1955     * consult the Paint's properties and not to change them.
1956     */
1957    public TextPaint getPaint() {
1958        return mTextPaint;
1959    }
1960
1961    /**
1962     * Sets the autolink mask of the text.  See {@link
1963     * android.text.util.Linkify#ALL Linkify.ALL} and peers for
1964     * possible values.
1965     *
1966     * @attr ref android.R.styleable#TextView_autoLink
1967     */
1968    @android.view.RemotableViewMethod
1969    public final void setAutoLinkMask(int mask) {
1970        mAutoLinkMask = mask;
1971    }
1972
1973    /**
1974     * Sets whether the movement method will automatically be set to
1975     * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been
1976     * set to nonzero and links are detected in {@link #setText}.
1977     * The default is true.
1978     *
1979     * @attr ref android.R.styleable#TextView_linksClickable
1980     */
1981    @android.view.RemotableViewMethod
1982    public final void setLinksClickable(boolean whether) {
1983        mLinksClickable = whether;
1984    }
1985
1986    /**
1987     * Returns whether the movement method will automatically be set to
1988     * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been
1989     * set to nonzero and links are detected in {@link #setText}.
1990     * The default is true.
1991     *
1992     * @attr ref android.R.styleable#TextView_linksClickable
1993     */
1994    public final boolean getLinksClickable() {
1995        return mLinksClickable;
1996    }
1997
1998    /**
1999     * Returns the list of URLSpans attached to the text
2000     * (by {@link Linkify} or otherwise) if any.  You can call
2001     * {@link URLSpan#getURL} on them to find where they link to
2002     * or use {@link Spanned#getSpanStart} and {@link Spanned#getSpanEnd}
2003     * to find the region of the text they are attached to.
2004     */
2005    public URLSpan[] getUrls() {
2006        if (mText instanceof Spanned) {
2007            return ((Spanned) mText).getSpans(0, mText.length(), URLSpan.class);
2008        } else {
2009            return new URLSpan[0];
2010        }
2011    }
2012
2013    /**
2014     * Sets the color of the hint text.
2015     *
2016     * @attr ref android.R.styleable#TextView_textColorHint
2017     */
2018    @android.view.RemotableViewMethod
2019    public final void setHintTextColor(int color) {
2020        mHintTextColor = ColorStateList.valueOf(color);
2021        updateTextColors();
2022    }
2023
2024    /**
2025     * Sets the color of the hint text.
2026     *
2027     * @attr ref android.R.styleable#TextView_textColorHint
2028     */
2029    public final void setHintTextColor(ColorStateList colors) {
2030        mHintTextColor = colors;
2031        updateTextColors();
2032    }
2033
2034    /**
2035     * <p>Return the color used to paint the hint text.</p>
2036     *
2037     * @return Returns the list of hint text colors.
2038     */
2039    public final ColorStateList getHintTextColors() {
2040        return mHintTextColor;
2041    }
2042
2043    /**
2044     * <p>Return the current color selected to paint the hint text.</p>
2045     *
2046     * @return Returns the current hint text color.
2047     */
2048    public final int getCurrentHintTextColor() {
2049        return mHintTextColor != null ? mCurHintTextColor : mCurTextColor;
2050    }
2051
2052    /**
2053     * Sets the color of links in the text.
2054     *
2055     * @attr ref android.R.styleable#TextView_textColorLink
2056     */
2057    @android.view.RemotableViewMethod
2058    public final void setLinkTextColor(int color) {
2059        mLinkTextColor = ColorStateList.valueOf(color);
2060        updateTextColors();
2061    }
2062
2063    /**
2064     * Sets the color of links in the text.
2065     *
2066     * @attr ref android.R.styleable#TextView_textColorLink
2067     */
2068    public final void setLinkTextColor(ColorStateList colors) {
2069        mLinkTextColor = colors;
2070        updateTextColors();
2071    }
2072
2073    /**
2074     * <p>Returns the color used to paint links in the text.</p>
2075     *
2076     * @return Returns the list of link text colors.
2077     */
2078    public final ColorStateList getLinkTextColors() {
2079        return mLinkTextColor;
2080    }
2081
2082    /**
2083     * Sets the horizontal alignment of the text and the
2084     * vertical gravity that will be used when there is extra space
2085     * in the TextView beyond what is required for the text itself.
2086     *
2087     * @see android.view.Gravity
2088     * @attr ref android.R.styleable#TextView_gravity
2089     */
2090    public void setGravity(int gravity) {
2091        if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) {
2092            gravity |= Gravity.LEFT;
2093        }
2094        if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
2095            gravity |= Gravity.TOP;
2096        }
2097
2098        boolean newLayout = false;
2099
2100        if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) !=
2101            (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK)) {
2102            newLayout = true;
2103        }
2104
2105        if (gravity != mGravity) {
2106            invalidate();
2107        }
2108
2109        mGravity = gravity;
2110
2111        if (mLayout != null && newLayout) {
2112            // XXX this is heavy-handed because no actual content changes.
2113            int want = mLayout.getWidth();
2114            int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();
2115
2116            makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
2117                          mRight - mLeft - getCompoundPaddingLeft() -
2118                          getCompoundPaddingRight(), true);
2119        }
2120    }
2121
2122    /**
2123     * Returns the horizontal and vertical alignment of this TextView.
2124     *
2125     * @see android.view.Gravity
2126     * @attr ref android.R.styleable#TextView_gravity
2127     */
2128    public int getGravity() {
2129        return mGravity;
2130    }
2131
2132    /**
2133     * @return the flags on the Paint being used to display the text.
2134     * @see Paint#getFlags
2135     */
2136    public int getPaintFlags() {
2137        return mTextPaint.getFlags();
2138    }
2139
2140    /**
2141     * Sets flags on the Paint being used to display the text and
2142     * reflows the text if they are different from the old flags.
2143     * @see Paint#setFlags
2144     */
2145    @android.view.RemotableViewMethod
2146    public void setPaintFlags(int flags) {
2147        if (mTextPaint.getFlags() != flags) {
2148            mTextPaint.setFlags(flags);
2149
2150            if (mLayout != null) {
2151                nullLayouts();
2152                requestLayout();
2153                invalidate();
2154            }
2155        }
2156    }
2157
2158    /**
2159     * Sets whether the text should be allowed to be wider than the
2160     * View is.  If false, it will be wrapped to the width of the View.
2161     *
2162     * @attr ref android.R.styleable#TextView_scrollHorizontally
2163     */
2164    public void setHorizontallyScrolling(boolean whether) {
2165        mHorizontallyScrolling = whether;
2166
2167        if (mLayout != null) {
2168            nullLayouts();
2169            requestLayout();
2170            invalidate();
2171        }
2172    }
2173
2174    /**
2175     * Makes the TextView at least this many lines tall.
2176     *
2177     * Setting this value overrides any other (minimum) height setting. A single line TextView will
2178     * set this value to 1.
2179     *
2180     * @attr ref android.R.styleable#TextView_minLines
2181     */
2182    @android.view.RemotableViewMethod
2183    public void setMinLines(int minlines) {
2184        mMinimum = minlines;
2185        mMinMode = LINES;
2186
2187        requestLayout();
2188        invalidate();
2189    }
2190
2191    /**
2192     * Makes the TextView at least this many pixels tall.
2193     *
2194     * Setting this value overrides any other (minimum) number of lines setting.
2195     *
2196     * @attr ref android.R.styleable#TextView_minHeight
2197     */
2198    @android.view.RemotableViewMethod
2199    public void setMinHeight(int minHeight) {
2200        mMinimum = minHeight;
2201        mMinMode = PIXELS;
2202
2203        requestLayout();
2204        invalidate();
2205    }
2206
2207    /**
2208     * Makes the TextView at most this many lines tall.
2209     *
2210     * Setting this value overrides any other (maximum) height setting.
2211     *
2212     * @attr ref android.R.styleable#TextView_maxLines
2213     */
2214    @android.view.RemotableViewMethod
2215    public void setMaxLines(int maxlines) {
2216        mMaximum = maxlines;
2217        mMaxMode = LINES;
2218
2219        requestLayout();
2220        invalidate();
2221    }
2222
2223    /**
2224     * Makes the TextView at most this many pixels tall.  This option is mutually exclusive with the
2225     * {@link #setMaxLines(int)} method.
2226     *
2227     * Setting this value overrides any other (maximum) number of lines setting.
2228     *
2229     * @attr ref android.R.styleable#TextView_maxHeight
2230     */
2231    @android.view.RemotableViewMethod
2232    public void setMaxHeight(int maxHeight) {
2233        mMaximum = maxHeight;
2234        mMaxMode = PIXELS;
2235
2236        requestLayout();
2237        invalidate();
2238    }
2239
2240    /**
2241     * Makes the TextView exactly this many lines tall.
2242     *
2243     * Note that setting this value overrides any other (minimum / maximum) number of lines or
2244     * height setting. A single line TextView will set this value to 1.
2245     *
2246     * @attr ref android.R.styleable#TextView_lines
2247     */
2248    @android.view.RemotableViewMethod
2249    public void setLines(int lines) {
2250        mMaximum = mMinimum = lines;
2251        mMaxMode = mMinMode = LINES;
2252
2253        requestLayout();
2254        invalidate();
2255    }
2256
2257    /**
2258     * Makes the TextView exactly this many pixels tall.
2259     * You could do the same thing by specifying this number in the
2260     * LayoutParams.
2261     *
2262     * Note that setting this value overrides any other (minimum / maximum) number of lines or
2263     * height setting.
2264     *
2265     * @attr ref android.R.styleable#TextView_height
2266     */
2267    @android.view.RemotableViewMethod
2268    public void setHeight(int pixels) {
2269        mMaximum = mMinimum = pixels;
2270        mMaxMode = mMinMode = PIXELS;
2271
2272        requestLayout();
2273        invalidate();
2274    }
2275
2276    /**
2277     * Makes the TextView at least this many ems wide
2278     *
2279     * @attr ref android.R.styleable#TextView_minEms
2280     */
2281    @android.view.RemotableViewMethod
2282    public void setMinEms(int minems) {
2283        mMinWidth = minems;
2284        mMinWidthMode = EMS;
2285
2286        requestLayout();
2287        invalidate();
2288    }
2289
2290    /**
2291     * Makes the TextView at least this many pixels wide
2292     *
2293     * @attr ref android.R.styleable#TextView_minWidth
2294     */
2295    @android.view.RemotableViewMethod
2296    public void setMinWidth(int minpixels) {
2297        mMinWidth = minpixels;
2298        mMinWidthMode = PIXELS;
2299
2300        requestLayout();
2301        invalidate();
2302    }
2303
2304    /**
2305     * Makes the TextView at most this many ems wide
2306     *
2307     * @attr ref android.R.styleable#TextView_maxEms
2308     */
2309    @android.view.RemotableViewMethod
2310    public void setMaxEms(int maxems) {
2311        mMaxWidth = maxems;
2312        mMaxWidthMode = EMS;
2313
2314        requestLayout();
2315        invalidate();
2316    }
2317
2318    /**
2319     * Makes the TextView at most this many pixels wide
2320     *
2321     * @attr ref android.R.styleable#TextView_maxWidth
2322     */
2323    @android.view.RemotableViewMethod
2324    public void setMaxWidth(int maxpixels) {
2325        mMaxWidth = maxpixels;
2326        mMaxWidthMode = PIXELS;
2327
2328        requestLayout();
2329        invalidate();
2330    }
2331
2332    /**
2333     * Makes the TextView exactly this many ems wide
2334     *
2335     * @attr ref android.R.styleable#TextView_ems
2336     */
2337    @android.view.RemotableViewMethod
2338    public void setEms(int ems) {
2339        mMaxWidth = mMinWidth = ems;
2340        mMaxWidthMode = mMinWidthMode = EMS;
2341
2342        requestLayout();
2343        invalidate();
2344    }
2345
2346    /**
2347     * Makes the TextView exactly this many pixels wide.
2348     * You could do the same thing by specifying this number in the
2349     * LayoutParams.
2350     *
2351     * @attr ref android.R.styleable#TextView_width
2352     */
2353    @android.view.RemotableViewMethod
2354    public void setWidth(int pixels) {
2355        mMaxWidth = mMinWidth = pixels;
2356        mMaxWidthMode = mMinWidthMode = PIXELS;
2357
2358        requestLayout();
2359        invalidate();
2360    }
2361
2362
2363    /**
2364     * Sets line spacing for this TextView.  Each line will have its height
2365     * multiplied by <code>mult</code> and have <code>add</code> added to it.
2366     *
2367     * @attr ref android.R.styleable#TextView_lineSpacingExtra
2368     * @attr ref android.R.styleable#TextView_lineSpacingMultiplier
2369     */
2370    public void setLineSpacing(float add, float mult) {
2371        mSpacingMult = mult;
2372        mSpacingAdd = add;
2373
2374        if (mLayout != null) {
2375            nullLayouts();
2376            requestLayout();
2377            invalidate();
2378        }
2379    }
2380
2381    /**
2382     * Convenience method: Append the specified text to the TextView's
2383     * display buffer, upgrading it to BufferType.EDITABLE if it was
2384     * not already editable.
2385     */
2386    public final void append(CharSequence text) {
2387        append(text, 0, text.length());
2388    }
2389
2390    /**
2391     * Convenience method: Append the specified text slice to the TextView's
2392     * display buffer, upgrading it to BufferType.EDITABLE if it was
2393     * not already editable.
2394     */
2395    public void append(CharSequence text, int start, int end) {
2396        if (!(mText instanceof Editable)) {
2397            setText(mText, BufferType.EDITABLE);
2398        }
2399
2400        ((Editable) mText).append(text, start, end);
2401    }
2402
2403    private void updateTextColors() {
2404        boolean inval = false;
2405        int color = mTextColor.getColorForState(getDrawableState(), 0);
2406        if (color != mCurTextColor) {
2407            mCurTextColor = color;
2408            inval = true;
2409        }
2410        if (mLinkTextColor != null) {
2411            color = mLinkTextColor.getColorForState(getDrawableState(), 0);
2412            if (color != mTextPaint.linkColor) {
2413                mTextPaint.linkColor = color;
2414                inval = true;
2415            }
2416        }
2417        if (mHintTextColor != null) {
2418            color = mHintTextColor.getColorForState(getDrawableState(), 0);
2419            if (color != mCurHintTextColor && mText.length() == 0) {
2420                mCurHintTextColor = color;
2421                inval = true;
2422            }
2423        }
2424        if (inval) {
2425            invalidate();
2426        }
2427    }
2428
2429    @Override
2430    protected void drawableStateChanged() {
2431        super.drawableStateChanged();
2432        if (mTextColor != null && mTextColor.isStateful()
2433                || (mHintTextColor != null && mHintTextColor.isStateful())
2434                || (mLinkTextColor != null && mLinkTextColor.isStateful())) {
2435            updateTextColors();
2436        }
2437
2438        final Drawables dr = mDrawables;
2439        if (dr != null) {
2440            int[] state = getDrawableState();
2441            if (dr.mDrawableTop != null && dr.mDrawableTop.isStateful()) {
2442                dr.mDrawableTop.setState(state);
2443            }
2444            if (dr.mDrawableBottom != null && dr.mDrawableBottom.isStateful()) {
2445                dr.mDrawableBottom.setState(state);
2446            }
2447            if (dr.mDrawableLeft != null && dr.mDrawableLeft.isStateful()) {
2448                dr.mDrawableLeft.setState(state);
2449            }
2450            if (dr.mDrawableRight != null && dr.mDrawableRight.isStateful()) {
2451                dr.mDrawableRight.setState(state);
2452            }
2453        }
2454    }
2455
2456    /**
2457     * User interface state that is stored by TextView for implementing
2458     * {@link View#onSaveInstanceState}.
2459     */
2460    public static class SavedState extends BaseSavedState {
2461        int selStart;
2462        int selEnd;
2463        CharSequence text;
2464        boolean frozenWithFocus;
2465        CharSequence error;
2466
2467        SavedState(Parcelable superState) {
2468            super(superState);
2469        }
2470
2471        @Override
2472        public void writeToParcel(Parcel out, int flags) {
2473            super.writeToParcel(out, flags);
2474            out.writeInt(selStart);
2475            out.writeInt(selEnd);
2476            out.writeInt(frozenWithFocus ? 1 : 0);
2477            TextUtils.writeToParcel(text, out, flags);
2478
2479            if (error == null) {
2480                out.writeInt(0);
2481            } else {
2482                out.writeInt(1);
2483                TextUtils.writeToParcel(error, out, flags);
2484            }
2485        }
2486
2487        @Override
2488        public String toString() {
2489            String str = "TextView.SavedState{"
2490                    + Integer.toHexString(System.identityHashCode(this))
2491                    + " start=" + selStart + " end=" + selEnd;
2492            if (text != null) {
2493                str += " text=" + text;
2494            }
2495            return str + "}";
2496        }
2497
2498        @SuppressWarnings("hiding")
2499        public static final Parcelable.Creator<SavedState> CREATOR
2500                = new Parcelable.Creator<SavedState>() {
2501            public SavedState createFromParcel(Parcel in) {
2502                return new SavedState(in);
2503            }
2504
2505            public SavedState[] newArray(int size) {
2506                return new SavedState[size];
2507            }
2508        };
2509
2510        private SavedState(Parcel in) {
2511            super(in);
2512            selStart = in.readInt();
2513            selEnd = in.readInt();
2514            frozenWithFocus = (in.readInt() != 0);
2515            text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
2516
2517            if (in.readInt() != 0) {
2518                error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
2519            }
2520        }
2521    }
2522
2523    @Override
2524    public Parcelable onSaveInstanceState() {
2525        Parcelable superState = super.onSaveInstanceState();
2526
2527        // Save state if we are forced to
2528        boolean save = mFreezesText;
2529        int start = 0;
2530        int end = 0;
2531
2532        if (mText != null) {
2533            start = getSelectionStart();
2534            end = getSelectionEnd();
2535            if (start >= 0 || end >= 0) {
2536                // Or save state if there is a selection
2537                save = true;
2538            }
2539        }
2540
2541        if (save) {
2542            SavedState ss = new SavedState(superState);
2543            // XXX Should also save the current scroll position!
2544            ss.selStart = start;
2545            ss.selEnd = end;
2546
2547            if (mText instanceof Spanned) {
2548                /*
2549                 * Calling setText() strips off any ChangeWatchers;
2550                 * strip them now to avoid leaking references.
2551                 * But do it to a copy so that if there are any
2552                 * further changes to the text of this view, it
2553                 * won't get into an inconsistent state.
2554                 */
2555
2556                Spannable sp = new SpannableString(mText);
2557
2558                for (ChangeWatcher cw :
2559                     sp.getSpans(0, sp.length(), ChangeWatcher.class)) {
2560                    sp.removeSpan(cw);
2561                }
2562
2563                ss.text = sp;
2564            } else {
2565                ss.text = mText.toString();
2566            }
2567
2568            if (isFocused() && start >= 0 && end >= 0) {
2569                ss.frozenWithFocus = true;
2570            }
2571
2572            ss.error = mError;
2573
2574            return ss;
2575        }
2576
2577        return superState;
2578    }
2579
2580    @Override
2581    public void onRestoreInstanceState(Parcelable state) {
2582        if (!(state instanceof SavedState)) {
2583            super.onRestoreInstanceState(state);
2584            return;
2585        }
2586
2587        SavedState ss = (SavedState)state;
2588        super.onRestoreInstanceState(ss.getSuperState());
2589
2590        // XXX restore buffer type too, as well as lots of other stuff
2591        if (ss.text != null) {
2592            setText(ss.text);
2593        }
2594
2595        if (ss.selStart >= 0 && ss.selEnd >= 0) {
2596            if (mText instanceof Spannable) {
2597                int len = mText.length();
2598
2599                if (ss.selStart > len || ss.selEnd > len) {
2600                    String restored = "";
2601
2602                    if (ss.text != null) {
2603                        restored = "(restored) ";
2604                    }
2605
2606                    Log.e(LOG_TAG, "Saved cursor position " + ss.selStart +
2607                          "/" + ss.selEnd + " out of range for " + restored +
2608                          "text " + mText);
2609                } else {
2610                    Selection.setSelection((Spannable) mText, ss.selStart,
2611                                           ss.selEnd);
2612
2613                    if (ss.frozenWithFocus) {
2614                        mFrozenWithFocus = true;
2615                    }
2616                }
2617            }
2618        }
2619
2620        if (ss.error != null) {
2621            final CharSequence error = ss.error;
2622            // Display the error later, after the first layout pass
2623            post(new Runnable() {
2624                public void run() {
2625                    setError(error);
2626                }
2627            });
2628        }
2629    }
2630
2631    /**
2632     * Control whether this text view saves its entire text contents when
2633     * freezing to an icicle, in addition to dynamic state such as cursor
2634     * position.  By default this is false, not saving the text.  Set to true
2635     * if the text in the text view is not being saved somewhere else in
2636     * persistent storage (such as in a content provider) so that if the
2637     * view is later thawed the user will not lose their data.
2638     *
2639     * @param freezesText Controls whether a frozen icicle should include the
2640     * entire text data: true to include it, false to not.
2641     *
2642     * @attr ref android.R.styleable#TextView_freezesText
2643     */
2644    @android.view.RemotableViewMethod
2645    public void setFreezesText(boolean freezesText) {
2646        mFreezesText = freezesText;
2647    }
2648
2649    /**
2650     * Return whether this text view is including its entire text contents
2651     * in frozen icicles.
2652     *
2653     * @return Returns true if text is included, false if it isn't.
2654     *
2655     * @see #setFreezesText
2656     */
2657    public boolean getFreezesText() {
2658        return mFreezesText;
2659    }
2660
2661    ///////////////////////////////////////////////////////////////////////////
2662
2663    /**
2664     * Sets the Factory used to create new Editables.
2665     */
2666    public final void setEditableFactory(Editable.Factory factory) {
2667        mEditableFactory = factory;
2668        setText(mText);
2669    }
2670
2671    /**
2672     * Sets the Factory used to create new Spannables.
2673     */
2674    public final void setSpannableFactory(Spannable.Factory factory) {
2675        mSpannableFactory = factory;
2676        setText(mText);
2677    }
2678
2679    /**
2680     * Sets the string value of the TextView. TextView <em>does not</em> accept
2681     * HTML-like formatting, which you can do with text strings in XML resource files.
2682     * To style your strings, attach android.text.style.* objects to a
2683     * {@link android.text.SpannableString SpannableString}, or see the
2684     * <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources">
2685     * Available Resource Types</a> documentation for an example of setting
2686     * formatted text in the XML resource file.
2687     *
2688     * @attr ref android.R.styleable#TextView_text
2689     */
2690    @android.view.RemotableViewMethod
2691    public final void setText(CharSequence text) {
2692        setText(text, mBufferType);
2693    }
2694
2695    /**
2696     * Like {@link #setText(CharSequence)},
2697     * except that the cursor position (if any) is retained in the new text.
2698     *
2699     * @param text The new text to place in the text view.
2700     *
2701     * @see #setText(CharSequence)
2702     */
2703    @android.view.RemotableViewMethod
2704    public final void setTextKeepState(CharSequence text) {
2705        setTextKeepState(text, mBufferType);
2706    }
2707
2708    /**
2709     * Sets the text that this TextView is to display (see
2710     * {@link #setText(CharSequence)}) and also sets whether it is stored
2711     * in a styleable/spannable buffer and whether it is editable.
2712     *
2713     * @attr ref android.R.styleable#TextView_text
2714     * @attr ref android.R.styleable#TextView_bufferType
2715     */
2716    public void setText(CharSequence text, BufferType type) {
2717        setText(text, type, true, 0);
2718
2719        if (mCharWrapper != null) {
2720            mCharWrapper.mChars = null;
2721        }
2722    }
2723
2724    private void setText(CharSequence text, BufferType type,
2725                         boolean notifyBefore, int oldlen) {
2726        if (text == null) {
2727            text = "";
2728        }
2729
2730        if (!mUserSetTextScaleX) mTextPaint.setTextScaleX(1.0f);
2731
2732        if (text instanceof Spanned &&
2733            ((Spanned) text).getSpanStart(TextUtils.TruncateAt.MARQUEE) >= 0) {
2734            setHorizontalFadingEdgeEnabled(true);
2735            setEllipsize(TextUtils.TruncateAt.MARQUEE);
2736        }
2737
2738        int n = mFilters.length;
2739        for (int i = 0; i < n; i++) {
2740            CharSequence out = mFilters[i].filter(text, 0, text.length(),
2741                                                  EMPTY_SPANNED, 0, 0);
2742            if (out != null) {
2743                text = out;
2744            }
2745        }
2746
2747        if (notifyBefore) {
2748            if (mText != null) {
2749                oldlen = mText.length();
2750                sendBeforeTextChanged(mText, 0, oldlen, text.length());
2751            } else {
2752                sendBeforeTextChanged("", 0, 0, text.length());
2753            }
2754        }
2755
2756        boolean needEditableForNotification = false;
2757
2758        if (mListeners != null && mListeners.size() != 0) {
2759            needEditableForNotification = true;
2760        }
2761
2762        if (type == BufferType.EDITABLE || mInput != null ||
2763            needEditableForNotification) {
2764            Editable t = mEditableFactory.newEditable(text);
2765            text = t;
2766            setFilters(t, mFilters);
2767            InputMethodManager imm = InputMethodManager.peekInstance();
2768            if (imm != null) imm.restartInput(this);
2769        } else if (type == BufferType.SPANNABLE || mMovement != null) {
2770            text = mSpannableFactory.newSpannable(text);
2771        } else if (!(text instanceof CharWrapper)) {
2772            text = TextUtils.stringOrSpannedString(text);
2773        }
2774
2775        if (mAutoLinkMask != 0) {
2776            Spannable s2;
2777
2778            if (type == BufferType.EDITABLE || text instanceof Spannable) {
2779                s2 = (Spannable) text;
2780            } else {
2781                s2 = mSpannableFactory.newSpannable(text);
2782            }
2783
2784            if (Linkify.addLinks(s2, mAutoLinkMask)) {
2785                text = s2;
2786                type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE;
2787
2788                /*
2789                 * We must go ahead and set the text before changing the
2790                 * movement method, because setMovementMethod() may call
2791                 * setText() again to try to upgrade the buffer type.
2792                 */
2793                mText = text;
2794
2795                // Do not change the movement method for text that support text selection as it
2796                // would prevent an arbitrary cursor displacement.
2797                final boolean hasTextSelection = this instanceof EditText || mTextIsSelectable;
2798                if (mLinksClickable && !hasTextSelection) {
2799                    setMovementMethod(LinkMovementMethod.getInstance());
2800                }
2801            }
2802        }
2803
2804        mBufferType = type;
2805        mText = text;
2806
2807        if (mTransformation == null)
2808            mTransformed = text;
2809        else
2810            mTransformed = mTransformation.getTransformation(text, this);
2811
2812        final int textLength = text.length();
2813
2814        if (text instanceof Spannable) {
2815            Spannable sp = (Spannable) text;
2816
2817            // Remove any ChangeWatchers that might have come
2818            // from other TextViews.
2819            final ChangeWatcher[] watchers = sp.getSpans(0, sp.length(), ChangeWatcher.class);
2820            final int count = watchers.length;
2821            for (int i = 0; i < count; i++)
2822                sp.removeSpan(watchers[i]);
2823
2824            if (mChangeWatcher == null)
2825                mChangeWatcher = new ChangeWatcher();
2826
2827            sp.setSpan(mChangeWatcher, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE |
2828                       (PRIORITY << Spanned.SPAN_PRIORITY_SHIFT));
2829
2830            if (mInput != null) {
2831                sp.setSpan(mInput, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2832            }
2833
2834            if (mTransformation != null) {
2835                sp.setSpan(mTransformation, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2836
2837            }
2838
2839            if (mMovement != null) {
2840                mMovement.initialize(this, (Spannable) text);
2841
2842                /*
2843                 * Initializing the movement method will have set the
2844                 * selection, so reset mSelectionMoved to keep that from
2845                 * interfering with the normal on-focus selection-setting.
2846                 */
2847                mSelectionMoved = false;
2848            }
2849        }
2850
2851        if (mLayout != null) {
2852            checkForRelayout();
2853        }
2854
2855        sendOnTextChanged(text, 0, oldlen, textLength);
2856        onTextChanged(text, 0, oldlen, textLength);
2857
2858        if (needEditableForNotification) {
2859            sendAfterTextChanged((Editable) text);
2860        }
2861
2862        // SelectionModifierCursorController depends on textCanBeSelected, which depends on text
2863        prepareCursorControllers();
2864    }
2865
2866    /**
2867     * Sets the TextView to display the specified slice of the specified
2868     * char array.  You must promise that you will not change the contents
2869     * of the array except for right before another call to setText(),
2870     * since the TextView has no way to know that the text
2871     * has changed and that it needs to invalidate and re-layout.
2872     */
2873    public final void setText(char[] text, int start, int len) {
2874        int oldlen = 0;
2875
2876        if (start < 0 || len < 0 || start + len > text.length) {
2877            throw new IndexOutOfBoundsException(start + ", " + len);
2878        }
2879
2880        /*
2881         * We must do the before-notification here ourselves because if
2882         * the old text is a CharWrapper we destroy it before calling
2883         * into the normal path.
2884         */
2885        if (mText != null) {
2886            oldlen = mText.length();
2887            sendBeforeTextChanged(mText, 0, oldlen, len);
2888        } else {
2889            sendBeforeTextChanged("", 0, 0, len);
2890        }
2891
2892        if (mCharWrapper == null) {
2893            mCharWrapper = new CharWrapper(text, start, len);
2894        } else {
2895            mCharWrapper.set(text, start, len);
2896        }
2897
2898        setText(mCharWrapper, mBufferType, false, oldlen);
2899    }
2900
2901    private static class CharWrapper implements CharSequence, GetChars, GraphicsOperations {
2902        private char[] mChars;
2903        private int mStart, mLength;
2904
2905        public CharWrapper(char[] chars, int start, int len) {
2906            mChars = chars;
2907            mStart = start;
2908            mLength = len;
2909        }
2910
2911        /* package */ void set(char[] chars, int start, int len) {
2912            mChars = chars;
2913            mStart = start;
2914            mLength = len;
2915        }
2916
2917        public int length() {
2918            return mLength;
2919        }
2920
2921        public char charAt(int off) {
2922            return mChars[off + mStart];
2923        }
2924
2925        @Override
2926        public String toString() {
2927            return new String(mChars, mStart, mLength);
2928        }
2929
2930        public CharSequence subSequence(int start, int end) {
2931            if (start < 0 || end < 0 || start > mLength || end > mLength) {
2932                throw new IndexOutOfBoundsException(start + ", " + end);
2933            }
2934
2935            return new String(mChars, start + mStart, end - start);
2936        }
2937
2938        public void getChars(int start, int end, char[] buf, int off) {
2939            if (start < 0 || end < 0 || start > mLength || end > mLength) {
2940                throw new IndexOutOfBoundsException(start + ", " + end);
2941            }
2942
2943            System.arraycopy(mChars, start + mStart, buf, off, end - start);
2944        }
2945
2946        public void drawText(Canvas c, int start, int end,
2947                             float x, float y, Paint p) {
2948            c.drawText(mChars, start + mStart, end - start, x, y, p);
2949        }
2950
2951        public void drawTextRun(Canvas c, int start, int end,
2952                int contextStart, int contextEnd, float x, float y, int flags, Paint p) {
2953            int count = end - start;
2954            int contextCount = contextEnd - contextStart;
2955            c.drawTextRun(mChars, start + mStart, count, contextStart + mStart,
2956                    contextCount, x, y, flags, p);
2957        }
2958
2959        public float measureText(int start, int end, Paint p) {
2960            return p.measureText(mChars, start + mStart, end - start);
2961        }
2962
2963        public int getTextWidths(int start, int end, float[] widths, Paint p) {
2964            return p.getTextWidths(mChars, start + mStart, end - start, widths);
2965        }
2966
2967        public float getTextRunAdvances(int start, int end, int contextStart,
2968                int contextEnd, int flags, float[] advances, int advancesIndex,
2969                Paint p) {
2970            int count = end - start;
2971            int contextCount = contextEnd - contextStart;
2972            return p.getTextRunAdvances(mChars, start + mStart, count,
2973                    contextStart + mStart, contextCount, flags, advances,
2974                    advancesIndex);
2975        }
2976
2977        public float getTextRunAdvances(int start, int end, int contextStart,
2978                int contextEnd, int flags, float[] advances, int advancesIndex,
2979                Paint p, int reserved) {
2980            int count = end - start;
2981            int contextCount = contextEnd - contextStart;
2982            return p.getTextRunAdvances(mChars, start + mStart, count,
2983                    contextStart + mStart, contextCount, flags, advances,
2984                    advancesIndex, reserved);
2985        }
2986
2987        public int getTextRunCursor(int contextStart, int contextEnd, int flags,
2988                int offset, int cursorOpt, Paint p) {
2989            int contextCount = contextEnd - contextStart;
2990            return p.getTextRunCursor(mChars, contextStart + mStart,
2991                    contextCount, flags, offset + mStart, cursorOpt);
2992        }
2993    }
2994
2995    /**
2996     * Like {@link #setText(CharSequence, android.widget.TextView.BufferType)},
2997     * except that the cursor position (if any) is retained in the new text.
2998     *
2999     * @see #setText(CharSequence, android.widget.TextView.BufferType)
3000     */
3001    public final void setTextKeepState(CharSequence text, BufferType type) {
3002        int start = getSelectionStart();
3003        int end = getSelectionEnd();
3004        int len = text.length();
3005
3006        setText(text, type);
3007
3008        if (start >= 0 || end >= 0) {
3009            if (mText instanceof Spannable) {
3010                Selection.setSelection((Spannable) mText,
3011                                       Math.max(0, Math.min(start, len)),
3012                                       Math.max(0, Math.min(end, len)));
3013            }
3014        }
3015    }
3016
3017    @android.view.RemotableViewMethod
3018    public final void setText(int resid) {
3019        setText(getContext().getResources().getText(resid));
3020    }
3021
3022    public final void setText(int resid, BufferType type) {
3023        setText(getContext().getResources().getText(resid), type);
3024    }
3025
3026    /**
3027     * Sets the text to be displayed when the text of the TextView is empty.
3028     * Null means to use the normal empty text. The hint does not currently
3029     * participate in determining the size of the view.
3030     *
3031     * @attr ref android.R.styleable#TextView_hint
3032     */
3033    @android.view.RemotableViewMethod
3034    public final void setHint(CharSequence hint) {
3035        mHint = TextUtils.stringOrSpannedString(hint);
3036
3037        if (mLayout != null) {
3038            checkForRelayout();
3039        }
3040
3041        if (mText.length() == 0) {
3042            invalidate();
3043        }
3044    }
3045
3046    /**
3047     * Sets the text to be displayed when the text of the TextView is empty,
3048     * from a resource.
3049     *
3050     * @attr ref android.R.styleable#TextView_hint
3051     */
3052    @android.view.RemotableViewMethod
3053    public final void setHint(int resid) {
3054        setHint(getContext().getResources().getText(resid));
3055    }
3056
3057    /**
3058     * Returns the hint that is displayed when the text of the TextView
3059     * is empty.
3060     *
3061     * @attr ref android.R.styleable#TextView_hint
3062     */
3063    @ViewDebug.CapturedViewProperty
3064    public CharSequence getHint() {
3065        return mHint;
3066    }
3067
3068    private boolean isMultilineInputType(int type) {
3069        return (type & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) ==
3070            (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
3071    }
3072
3073    /**
3074     * Set the type of the content with a constant as defined for {@link EditorInfo#inputType}. This
3075     * will take care of changing the key listener, by calling {@link #setKeyListener(KeyListener)},
3076     * to match the given content type.  If the given content type is {@link EditorInfo#TYPE_NULL}
3077     * then a soft keyboard will not be displayed for this text view.
3078     *
3079     * Note that the maximum number of displayed lines (see {@link #setMaxLines(int)}) will be
3080     * modified if you change the {@link EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE} flag of the input
3081     * type.
3082     *
3083     * @see #getInputType()
3084     * @see #setRawInputType(int)
3085     * @see android.text.InputType
3086     * @attr ref android.R.styleable#TextView_inputType
3087     */
3088    public void setInputType(int type) {
3089        final boolean wasPassword = isPasswordInputType(mInputType);
3090        final boolean wasVisiblePassword = isVisiblePasswordInputType(mInputType);
3091        setInputType(type, false);
3092        final boolean isPassword = isPasswordInputType(type);
3093        final boolean isVisiblePassword = isVisiblePasswordInputType(type);
3094        boolean forceUpdate = false;
3095        if (isPassword) {
3096            setTransformationMethod(PasswordTransformationMethod.getInstance());
3097            setTypefaceByIndex(MONOSPACE, 0);
3098        } else if (isVisiblePassword) {
3099            if (mTransformation == PasswordTransformationMethod.getInstance()) {
3100                forceUpdate = true;
3101            }
3102            setTypefaceByIndex(MONOSPACE, 0);
3103        } else if (wasPassword || wasVisiblePassword) {
3104            // not in password mode, clean up typeface and transformation
3105            setTypefaceByIndex(-1, -1);
3106            if (mTransformation == PasswordTransformationMethod.getInstance()) {
3107                forceUpdate = true;
3108            }
3109        }
3110
3111        boolean singleLine = !isMultilineInputType(type);
3112
3113        // We need to update the single line mode if it has changed or we
3114        // were previously in password mode.
3115        if (mSingleLine != singleLine || forceUpdate) {
3116            // Change single line mode, but only change the transformation if
3117            // we are not in password mode.
3118            applySingleLine(singleLine, !isPassword, true);
3119        }
3120
3121        InputMethodManager imm = InputMethodManager.peekInstance();
3122        if (imm != null) imm.restartInput(this);
3123    }
3124
3125    /**
3126     * It would be better to rely on the input type for everything. A password inputType should have
3127     * a password transformation. We should hence use isPasswordInputType instead of this method.
3128     *
3129     * We should:
3130     * - Call setInputType in setKeyListener instead of changing the input type directly (which
3131     * would install the correct transformation).
3132     * - Refuse the installation of a non-password transformation in setTransformation if the input
3133     * type is password.
3134     *
3135     * However, this is like this for legacy reasons and we cannot break existing apps. This method
3136     * is useful since it matches what the user can see (obfuscated text or not).
3137     *
3138     * @return true if the current transformation method is of the password type.
3139     */
3140    private boolean hasPasswordTransformationMethod() {
3141        return mTransformation instanceof PasswordTransformationMethod;
3142    }
3143
3144    private boolean isPasswordInputType(int inputType) {
3145        final int variation =
3146                inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION);
3147        return variation
3148                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)
3149                || variation
3150                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD)
3151                || variation
3152                == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD);
3153    }
3154
3155    private boolean isVisiblePasswordInputType(int inputType) {
3156        final int variation =
3157                inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION);
3158        return variation
3159                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
3160    }
3161
3162    /**
3163     * Directly change the content type integer of the text view, without
3164     * modifying any other state.
3165     * @see #setInputType(int)
3166     * @see android.text.InputType
3167     * @attr ref android.R.styleable#TextView_inputType
3168     */
3169    public void setRawInputType(int type) {
3170        mInputType = type;
3171    }
3172
3173    private void setInputType(int type, boolean direct) {
3174        final int cls = type & EditorInfo.TYPE_MASK_CLASS;
3175        KeyListener input;
3176        if (cls == EditorInfo.TYPE_CLASS_TEXT) {
3177            boolean autotext = (type & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) != 0;
3178            TextKeyListener.Capitalize cap;
3179            if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) {
3180                cap = TextKeyListener.Capitalize.CHARACTERS;
3181            } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS) != 0) {
3182                cap = TextKeyListener.Capitalize.WORDS;
3183            } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) {
3184                cap = TextKeyListener.Capitalize.SENTENCES;
3185            } else {
3186                cap = TextKeyListener.Capitalize.NONE;
3187            }
3188            input = TextKeyListener.getInstance(autotext, cap);
3189        } else if (cls == EditorInfo.TYPE_CLASS_NUMBER) {
3190            input = DigitsKeyListener.getInstance(
3191                    (type & EditorInfo.TYPE_NUMBER_FLAG_SIGNED) != 0,
3192                    (type & EditorInfo.TYPE_NUMBER_FLAG_DECIMAL) != 0);
3193        } else if (cls == EditorInfo.TYPE_CLASS_DATETIME) {
3194            switch (type & EditorInfo.TYPE_MASK_VARIATION) {
3195                case EditorInfo.TYPE_DATETIME_VARIATION_DATE:
3196                    input = DateKeyListener.getInstance();
3197                    break;
3198                case EditorInfo.TYPE_DATETIME_VARIATION_TIME:
3199                    input = TimeKeyListener.getInstance();
3200                    break;
3201                default:
3202                    input = DateTimeKeyListener.getInstance();
3203                    break;
3204            }
3205        } else if (cls == EditorInfo.TYPE_CLASS_PHONE) {
3206            input = DialerKeyListener.getInstance();
3207        } else {
3208            input = TextKeyListener.getInstance();
3209        }
3210        setRawInputType(type);
3211        if (direct) mInput = input;
3212        else {
3213            setKeyListenerOnly(input);
3214        }
3215    }
3216
3217    /**
3218     * Get the type of the content.
3219     *
3220     * @see #setInputType(int)
3221     * @see android.text.InputType
3222     */
3223    public int getInputType() {
3224        return mInputType;
3225    }
3226
3227    /**
3228     * Change the editor type integer associated with the text view, which
3229     * will be reported to an IME with {@link EditorInfo#imeOptions} when it
3230     * has focus.
3231     * @see #getImeOptions
3232     * @see android.view.inputmethod.EditorInfo
3233     * @attr ref android.R.styleable#TextView_imeOptions
3234     */
3235    public void setImeOptions(int imeOptions) {
3236        if (mInputContentType == null) {
3237            mInputContentType = new InputContentType();
3238        }
3239        mInputContentType.imeOptions = imeOptions;
3240    }
3241
3242    /**
3243     * Get the type of the IME editor.
3244     *
3245     * @see #setImeOptions(int)
3246     * @see android.view.inputmethod.EditorInfo
3247     */
3248    public int getImeOptions() {
3249        return mInputContentType != null
3250                ? mInputContentType.imeOptions : EditorInfo.IME_NULL;
3251    }
3252
3253    /**
3254     * Change the custom IME action associated with the text view, which
3255     * will be reported to an IME with {@link EditorInfo#actionLabel}
3256     * and {@link EditorInfo#actionId} when it has focus.
3257     * @see #getImeActionLabel
3258     * @see #getImeActionId
3259     * @see android.view.inputmethod.EditorInfo
3260     * @attr ref android.R.styleable#TextView_imeActionLabel
3261     * @attr ref android.R.styleable#TextView_imeActionId
3262     */
3263    public void setImeActionLabel(CharSequence label, int actionId) {
3264        if (mInputContentType == null) {
3265            mInputContentType = new InputContentType();
3266        }
3267        mInputContentType.imeActionLabel = label;
3268        mInputContentType.imeActionId = actionId;
3269    }
3270
3271    /**
3272     * Get the IME action label previous set with {@link #setImeActionLabel}.
3273     *
3274     * @see #setImeActionLabel
3275     * @see android.view.inputmethod.EditorInfo
3276     */
3277    public CharSequence getImeActionLabel() {
3278        return mInputContentType != null
3279                ? mInputContentType.imeActionLabel : null;
3280    }
3281
3282    /**
3283     * Get the IME action ID previous set with {@link #setImeActionLabel}.
3284     *
3285     * @see #setImeActionLabel
3286     * @see android.view.inputmethod.EditorInfo
3287     */
3288    public int getImeActionId() {
3289        return mInputContentType != null
3290                ? mInputContentType.imeActionId : 0;
3291    }
3292
3293    /**
3294     * Set a special listener to be called when an action is performed
3295     * on the text view.  This will be called when the enter key is pressed,
3296     * or when an action supplied to the IME is selected by the user.  Setting
3297     * this means that the normal hard key event will not insert a newline
3298     * into the text view, even if it is multi-line; holding down the ALT
3299     * modifier will, however, allow the user to insert a newline character.
3300     */
3301    public void setOnEditorActionListener(OnEditorActionListener l) {
3302        if (mInputContentType == null) {
3303            mInputContentType = new InputContentType();
3304        }
3305        mInputContentType.onEditorActionListener = l;
3306    }
3307
3308    /**
3309     * Called when an attached input method calls
3310     * {@link InputConnection#performEditorAction(int)
3311     * InputConnection.performEditorAction()}
3312     * for this text view.  The default implementation will call your action
3313     * listener supplied to {@link #setOnEditorActionListener}, or perform
3314     * a standard operation for {@link EditorInfo#IME_ACTION_NEXT
3315     * EditorInfo.IME_ACTION_NEXT}, {@link EditorInfo#IME_ACTION_PREVIOUS
3316     * EditorInfo.IME_ACTION_PREVIOUS}, or {@link EditorInfo#IME_ACTION_DONE
3317     * EditorInfo.IME_ACTION_DONE}.
3318     *
3319     * <p>For backwards compatibility, if no IME options have been set and the
3320     * text view would not normally advance focus on enter, then
3321     * the NEXT and DONE actions received here will be turned into an enter
3322     * key down/up pair to go through the normal key handling.
3323     *
3324     * @param actionCode The code of the action being performed.
3325     *
3326     * @see #setOnEditorActionListener
3327     */
3328    public void onEditorAction(int actionCode) {
3329        final InputContentType ict = mInputContentType;
3330        if (ict != null) {
3331            if (ict.onEditorActionListener != null) {
3332                if (ict.onEditorActionListener.onEditorAction(this,
3333                        actionCode, null)) {
3334                    return;
3335                }
3336            }
3337
3338            // This is the handling for some default action.
3339            // Note that for backwards compatibility we don't do this
3340            // default handling if explicit ime options have not been given,
3341            // instead turning this into the normal enter key codes that an
3342            // app may be expecting.
3343            if (actionCode == EditorInfo.IME_ACTION_NEXT) {
3344                View v = focusSearch(FOCUS_DOWN);
3345                if (v != null) {
3346                    if (!v.requestFocus(FOCUS_DOWN)) {
3347                        throw new IllegalStateException("focus search returned a view " +
3348                                "that wasn't able to take focus!");
3349                    }
3350                }
3351                return;
3352
3353            } else if (actionCode == EditorInfo.IME_ACTION_PREVIOUS) {
3354                View v = focusSearch(FOCUS_UP);
3355                if (v != null) {
3356                    if (!v.requestFocus(FOCUS_UP)) {
3357                        throw new IllegalStateException("focus search returned a view " +
3358                                "that wasn't able to take focus!");
3359                    }
3360                }
3361                return;
3362
3363            } else if (actionCode == EditorInfo.IME_ACTION_DONE) {
3364                InputMethodManager imm = InputMethodManager.peekInstance();
3365                if (imm != null && imm.isActive(this)) {
3366                    imm.hideSoftInputFromWindow(getWindowToken(), 0);
3367                }
3368                return;
3369            }
3370        }
3371
3372        Handler h = getHandler();
3373        if (h != null) {
3374            long eventTime = SystemClock.uptimeMillis();
3375            h.sendMessage(h.obtainMessage(ViewAncestor.DISPATCH_KEY_FROM_IME,
3376                    new KeyEvent(eventTime, eventTime,
3377                    KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0,
3378                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
3379                    KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE
3380                    | KeyEvent.FLAG_EDITOR_ACTION)));
3381            h.sendMessage(h.obtainMessage(ViewAncestor.DISPATCH_KEY_FROM_IME,
3382                    new KeyEvent(SystemClock.uptimeMillis(), eventTime,
3383                    KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0,
3384                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
3385                    KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE
3386                    | KeyEvent.FLAG_EDITOR_ACTION)));
3387        }
3388    }
3389
3390    /**
3391     * Set the private content type of the text, which is the
3392     * {@link EditorInfo#privateImeOptions EditorInfo.privateImeOptions}
3393     * field that will be filled in when creating an input connection.
3394     *
3395     * @see #getPrivateImeOptions()
3396     * @see EditorInfo#privateImeOptions
3397     * @attr ref android.R.styleable#TextView_privateImeOptions
3398     */
3399    public void setPrivateImeOptions(String type) {
3400        if (mInputContentType == null) mInputContentType = new InputContentType();
3401        mInputContentType.privateImeOptions = type;
3402    }
3403
3404    /**
3405     * Get the private type of the content.
3406     *
3407     * @see #setPrivateImeOptions(String)
3408     * @see EditorInfo#privateImeOptions
3409     */
3410    public String getPrivateImeOptions() {
3411        return mInputContentType != null
3412                ? mInputContentType.privateImeOptions : null;
3413    }
3414
3415    /**
3416     * Set the extra input data of the text, which is the
3417     * {@link EditorInfo#extras TextBoxAttribute.extras}
3418     * Bundle that will be filled in when creating an input connection.  The
3419     * given integer is the resource ID of an XML resource holding an
3420     * {@link android.R.styleable#InputExtras &lt;input-extras&gt;} XML tree.
3421     *
3422     * @see #getInputExtras(boolean)
3423     * @see EditorInfo#extras
3424     * @attr ref android.R.styleable#TextView_editorExtras
3425     */
3426    public void setInputExtras(int xmlResId)
3427            throws XmlPullParserException, IOException {
3428        XmlResourceParser parser = getResources().getXml(xmlResId);
3429        if (mInputContentType == null) mInputContentType = new InputContentType();
3430        mInputContentType.extras = new Bundle();
3431        getResources().parseBundleExtras(parser, mInputContentType.extras);
3432    }
3433
3434    /**
3435     * Retrieve the input extras currently associated with the text view, which
3436     * can be viewed as well as modified.
3437     *
3438     * @param create If true, the extras will be created if they don't already
3439     * exist.  Otherwise, null will be returned if none have been created.
3440     * @see #setInputExtras(int)
3441     * @see EditorInfo#extras
3442     * @attr ref android.R.styleable#TextView_editorExtras
3443     */
3444    public Bundle getInputExtras(boolean create) {
3445        if (mInputContentType == null) {
3446            if (!create) return null;
3447            mInputContentType = new InputContentType();
3448        }
3449        if (mInputContentType.extras == null) {
3450            if (!create) return null;
3451            mInputContentType.extras = new Bundle();
3452        }
3453        return mInputContentType.extras;
3454    }
3455
3456    /**
3457     * Returns the error message that was set to be displayed with
3458     * {@link #setError}, or <code>null</code> if no error was set
3459     * or if it the error was cleared by the widget after user input.
3460     */
3461    public CharSequence getError() {
3462        return mError;
3463    }
3464
3465    /**
3466     * Sets the right-hand compound drawable of the TextView to the "error"
3467     * icon and sets an error message that will be displayed in a popup when
3468     * the TextView has focus.  The icon and error message will be reset to
3469     * null when any key events cause changes to the TextView's text.  If the
3470     * <code>error</code> is <code>null</code>, the error message and icon
3471     * will be cleared.
3472     */
3473    @android.view.RemotableViewMethod
3474    public void setError(CharSequence error) {
3475        if (error == null) {
3476            setError(null, null);
3477        } else {
3478            Drawable dr = getContext().getResources().
3479                getDrawable(com.android.internal.R.drawable.indicator_input_error);
3480
3481            dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());
3482            setError(error, dr);
3483        }
3484    }
3485
3486    /**
3487     * Sets the right-hand compound drawable of the TextView to the specified
3488     * icon and sets an error message that will be displayed in a popup when
3489     * the TextView has focus.  The icon and error message will be reset to
3490     * null when any key events cause changes to the TextView's text.  The
3491     * drawable must already have had {@link Drawable#setBounds} set on it.
3492     * If the <code>error</code> is <code>null</code>, the error message will
3493     * be cleared (and you should provide a <code>null</code> icon as well).
3494     */
3495    public void setError(CharSequence error, Drawable icon) {
3496        error = TextUtils.stringOrSpannedString(error);
3497
3498        mError = error;
3499        mErrorWasChanged = true;
3500        final Drawables dr = mDrawables;
3501        if (dr != null) {
3502            setCompoundDrawables(dr.mDrawableLeft, dr.mDrawableTop, icon, dr.mDrawableBottom);
3503        } else {
3504            setCompoundDrawables(null, null, icon, null);
3505        }
3506
3507        if (error == null) {
3508            if (mPopup != null) {
3509                if (mPopup.isShowing()) {
3510                    mPopup.dismiss();
3511                }
3512
3513                mPopup = null;
3514            }
3515        } else {
3516            if (isFocused()) {
3517                showError();
3518            }
3519        }
3520    }
3521
3522    private void showError() {
3523        if (getWindowToken() == null) {
3524            mShowErrorAfterAttach = true;
3525            return;
3526        }
3527
3528        if (mPopup == null) {
3529            LayoutInflater inflater = LayoutInflater.from(getContext());
3530            final TextView err = (TextView) inflater.inflate(
3531                    com.android.internal.R.layout.textview_hint, null);
3532
3533            final float scale = getResources().getDisplayMetrics().density;
3534            mPopup = new ErrorPopup(err, (int) (200 * scale + 0.5f), (int) (50 * scale + 0.5f));
3535            mPopup.setFocusable(false);
3536            // The user is entering text, so the input method is needed.  We
3537            // don't want the popup to be displayed on top of it.
3538            mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
3539        }
3540
3541        TextView tv = (TextView) mPopup.getContentView();
3542        chooseSize(mPopup, mError, tv);
3543        tv.setText(mError);
3544
3545        mPopup.showAsDropDown(this, getErrorX(), getErrorY());
3546        mPopup.fixDirection(mPopup.isAboveAnchor());
3547    }
3548
3549    private static class ErrorPopup extends PopupWindow {
3550        private boolean mAbove = false;
3551        private final TextView mView;
3552        private int mPopupInlineErrorBackgroundId = 0;
3553        private int mPopupInlineErrorAboveBackgroundId = 0;
3554
3555        ErrorPopup(TextView v, int width, int height) {
3556            super(v, width, height);
3557            mView = v;
3558            // Make sure the TextView has a background set as it will be used the first time it is
3559            // shown and positionned. Initialized with below background, which should have
3560            // dimensions identical to the above version for this to work (and is more likely).
3561            mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
3562                    com.android.internal.R.styleable.Theme_errorMessageBackground);
3563            mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
3564        }
3565
3566        void fixDirection(boolean above) {
3567            mAbove = above;
3568
3569            if (above) {
3570                mPopupInlineErrorAboveBackgroundId =
3571                    getResourceId(mPopupInlineErrorAboveBackgroundId,
3572                            com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
3573            } else {
3574                mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
3575                        com.android.internal.R.styleable.Theme_errorMessageBackground);
3576            }
3577
3578            mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId :
3579                mPopupInlineErrorBackgroundId);
3580        }
3581
3582        private int getResourceId(int currentId, int index) {
3583            if (currentId == 0) {
3584                TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
3585                        R.styleable.Theme);
3586                currentId = styledAttributes.getResourceId(index, 0);
3587                styledAttributes.recycle();
3588            }
3589            return currentId;
3590        }
3591
3592        @Override
3593        public void update(int x, int y, int w, int h, boolean force) {
3594            super.update(x, y, w, h, force);
3595
3596            boolean above = isAboveAnchor();
3597            if (above != mAbove) {
3598                fixDirection(above);
3599            }
3600        }
3601    }
3602
3603    /**
3604     * Returns the Y offset to make the pointy top of the error point
3605     * at the middle of the error icon.
3606     */
3607    private int getErrorX() {
3608        /*
3609         * The "25" is the distance between the point and the right edge
3610         * of the background
3611         */
3612        final float scale = getResources().getDisplayMetrics().density;
3613
3614        final Drawables dr = mDrawables;
3615        return getWidth() - mPopup.getWidth() - getPaddingRight() -
3616                (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f);
3617    }
3618
3619    /**
3620     * Returns the Y offset to make the pointy top of the error point
3621     * at the bottom of the error icon.
3622     */
3623    private int getErrorY() {
3624        /*
3625         * Compound, not extended, because the icon is not clipped
3626         * if the text height is smaller.
3627         */
3628        final int compoundPaddingTop = getCompoundPaddingTop();
3629        int vspace = mBottom - mTop - getCompoundPaddingBottom() - compoundPaddingTop;
3630
3631        final Drawables dr = mDrawables;
3632        int icontop = compoundPaddingTop +
3633                (vspace - (dr != null ? dr.mDrawableHeightRight : 0)) / 2;
3634
3635        /*
3636         * The "2" is the distance between the point and the top edge
3637         * of the background.
3638         */
3639        final float scale = getResources().getDisplayMetrics().density;
3640        return icontop + (dr != null ? dr.mDrawableHeightRight : 0) - getHeight() -
3641                (int) (2 * scale + 0.5f);
3642    }
3643
3644    private void hideError() {
3645        if (mPopup != null) {
3646            if (mPopup.isShowing()) {
3647                mPopup.dismiss();
3648            }
3649        }
3650
3651        mShowErrorAfterAttach = false;
3652    }
3653
3654    private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) {
3655        int wid = tv.getPaddingLeft() + tv.getPaddingRight();
3656        int ht = tv.getPaddingTop() + tv.getPaddingBottom();
3657
3658        /*
3659         * Figure out how big the text would be if we laid it out to the
3660         * full width of this view minus the border.
3661         */
3662        int cap = getWidth() - wid;
3663        if (cap < 0) {
3664            cap = 200; // We must not be measured yet -- setFrame() will fix it.
3665        }
3666
3667        Layout l = new StaticLayout(text, tv.getPaint(), cap,
3668                                    Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
3669        float max = 0;
3670        for (int i = 0; i < l.getLineCount(); i++) {
3671            max = Math.max(max, l.getLineWidth(i));
3672        }
3673
3674        /*
3675         * Now set the popup size to be big enough for the text plus the border.
3676         */
3677        pop.setWidth(wid + (int) Math.ceil(max));
3678        pop.setHeight(ht + l.getHeight());
3679    }
3680
3681
3682    @Override
3683    protected boolean setFrame(int l, int t, int r, int b) {
3684        boolean result = super.setFrame(l, t, r, b);
3685
3686        if (mPopup != null) {
3687            TextView tv = (TextView) mPopup.getContentView();
3688            chooseSize(mPopup, mError, tv);
3689            mPopup.update(this, getErrorX(), getErrorY(),
3690                          mPopup.getWidth(), mPopup.getHeight());
3691        }
3692
3693        restartMarqueeIfNeeded();
3694
3695        return result;
3696    }
3697
3698    private void restartMarqueeIfNeeded() {
3699        if (mRestartMarquee && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
3700            mRestartMarquee = false;
3701            startMarquee();
3702        }
3703    }
3704
3705    /**
3706     * Sets the list of input filters that will be used if the buffer is
3707     * Editable.  Has no effect otherwise.
3708     *
3709     * @attr ref android.R.styleable#TextView_maxLength
3710     */
3711    public void setFilters(InputFilter[] filters) {
3712        if (filters == null) {
3713            throw new IllegalArgumentException();
3714        }
3715
3716        mFilters = filters;
3717
3718        if (mText instanceof Editable) {
3719            setFilters((Editable) mText, filters);
3720        }
3721    }
3722
3723    /**
3724     * Sets the list of input filters on the specified Editable,
3725     * and includes mInput in the list if it is an InputFilter.
3726     */
3727    private void setFilters(Editable e, InputFilter[] filters) {
3728        if (mInput instanceof InputFilter) {
3729            InputFilter[] nf = new InputFilter[filters.length + 1];
3730
3731            System.arraycopy(filters, 0, nf, 0, filters.length);
3732            nf[filters.length] = (InputFilter) mInput;
3733
3734            e.setFilters(nf);
3735        } else {
3736            e.setFilters(filters);
3737        }
3738    }
3739
3740    /**
3741     * Returns the current list of input filters.
3742     */
3743    public InputFilter[] getFilters() {
3744        return mFilters;
3745    }
3746
3747    /////////////////////////////////////////////////////////////////////////
3748
3749    private int getVerticalOffset(boolean forceNormal) {
3750        int voffset = 0;
3751        final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
3752
3753        Layout l = mLayout;
3754        if (!forceNormal && mText.length() == 0 && mHintLayout != null) {
3755            l = mHintLayout;
3756        }
3757
3758        if (gravity != Gravity.TOP) {
3759            int boxht;
3760
3761            if (l == mHintLayout) {
3762                boxht = getMeasuredHeight() - getCompoundPaddingTop() -
3763                        getCompoundPaddingBottom();
3764            } else {
3765                boxht = getMeasuredHeight() - getExtendedPaddingTop() -
3766                        getExtendedPaddingBottom();
3767            }
3768            int textht = l.getHeight();
3769
3770            if (textht < boxht) {
3771                if (gravity == Gravity.BOTTOM)
3772                    voffset = boxht - textht;
3773                else // (gravity == Gravity.CENTER_VERTICAL)
3774                    voffset = (boxht - textht) >> 1;
3775            }
3776        }
3777        return voffset;
3778    }
3779
3780    private int getBottomVerticalOffset(boolean forceNormal) {
3781        int voffset = 0;
3782        final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
3783
3784        Layout l = mLayout;
3785        if (!forceNormal && mText.length() == 0 && mHintLayout != null) {
3786            l = mHintLayout;
3787        }
3788
3789        if (gravity != Gravity.BOTTOM) {
3790            int boxht;
3791
3792            if (l == mHintLayout) {
3793                boxht = getMeasuredHeight() - getCompoundPaddingTop() -
3794                        getCompoundPaddingBottom();
3795            } else {
3796                boxht = getMeasuredHeight() - getExtendedPaddingTop() -
3797                        getExtendedPaddingBottom();
3798            }
3799            int textht = l.getHeight();
3800
3801            if (textht < boxht) {
3802                if (gravity == Gravity.TOP)
3803                    voffset = boxht - textht;
3804                else // (gravity == Gravity.CENTER_VERTICAL)
3805                    voffset = (boxht - textht) >> 1;
3806            }
3807        }
3808        return voffset;
3809    }
3810
3811    private void invalidateCursorPath() {
3812        if (mHighlightPathBogus) {
3813            invalidateCursor();
3814        } else {
3815            final int horizontalPadding = getCompoundPaddingLeft();
3816            final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true);
3817
3818            if (mCursorCount == 0) {
3819                synchronized (sTempRect) {
3820                    /*
3821                     * The reason for this concern about the thickness of the
3822                     * cursor and doing the floor/ceil on the coordinates is that
3823                     * some EditTexts (notably textfields in the Browser) have
3824                     * anti-aliased text where not all the characters are
3825                     * necessarily at integer-multiple locations.  This should
3826                     * make sure the entire cursor gets invalidated instead of
3827                     * sometimes missing half a pixel.
3828                     */
3829                    float thick = FloatMath.ceil(mTextPaint.getStrokeWidth());
3830                    if (thick < 1.0f) {
3831                        thick = 1.0f;
3832                    }
3833
3834                    thick /= 2.0f;
3835
3836                    mHighlightPath.computeBounds(sTempRect, false);
3837
3838                    invalidate((int) FloatMath.floor(horizontalPadding + sTempRect.left - thick),
3839                            (int) FloatMath.floor(verticalPadding + sTempRect.top - thick),
3840                            (int) FloatMath.ceil(horizontalPadding + sTempRect.right + thick),
3841                            (int) FloatMath.ceil(verticalPadding + sTempRect.bottom + thick));
3842                }
3843            } else {
3844                for (int i = 0; i < mCursorCount; i++) {
3845                    Rect bounds = mCursorDrawable[i].getBounds();
3846                    invalidate(bounds.left + horizontalPadding, bounds.top + verticalPadding,
3847                            bounds.right + horizontalPadding, bounds.bottom + verticalPadding);
3848                }
3849            }
3850        }
3851    }
3852
3853    private void invalidateCursor() {
3854        int where = getSelectionEnd();
3855
3856        invalidateCursor(where, where, where);
3857    }
3858
3859    private void invalidateCursor(int a, int b, int c) {
3860        if (mLayout == null) {
3861            invalidate();
3862        } else {
3863            if (a >= 0 || b >= 0 || c >= 0) {
3864                int first = Math.min(Math.min(a, b), c);
3865                int last = Math.max(Math.max(a, b), c);
3866
3867                int line = mLayout.getLineForOffset(first);
3868                int top = mLayout.getLineTop(line);
3869
3870                // This is ridiculous, but the descent from the line above
3871                // can hang down into the line we really want to redraw,
3872                // so we have to invalidate part of the line above to make
3873                // sure everything that needs to be redrawn really is.
3874                // (But not the whole line above, because that would cause
3875                // the same problem with the descenders on the line above it!)
3876                if (line > 0) {
3877                    top -= mLayout.getLineDescent(line - 1);
3878                }
3879
3880                int line2;
3881
3882                if (first == last)
3883                    line2 = line;
3884                else
3885                    line2 = mLayout.getLineForOffset(last);
3886
3887                int bottom = mLayout.getLineTop(line2 + 1);
3888
3889                final int horizontalPadding = getCompoundPaddingLeft();
3890                final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true);
3891
3892                // If used, the cursor drawables can have an arbitrary dimension that can go beyond
3893                // the invalidated lines specified above.
3894                for (int i = 0; i < mCursorCount; i++) {
3895                    Rect bounds = mCursorDrawable[i].getBounds();
3896                    top = Math.min(top, bounds.top);
3897                    bottom = Math.max(bottom, bounds.bottom);
3898                    // Horizontal bounds are already full width, no need to update
3899                }
3900
3901                invalidate(horizontalPadding + mScrollX, top + verticalPadding,
3902                        horizontalPadding + mScrollX + getWidth() -
3903                        getCompoundPaddingLeft() - getCompoundPaddingRight(),
3904                        bottom + verticalPadding);
3905            }
3906        }
3907    }
3908
3909    private void registerForPreDraw() {
3910        final ViewTreeObserver observer = getViewTreeObserver();
3911
3912        if (mPreDrawState == PREDRAW_NOT_REGISTERED) {
3913            observer.addOnPreDrawListener(this);
3914            mPreDrawState = PREDRAW_PENDING;
3915        } else if (mPreDrawState == PREDRAW_DONE) {
3916            mPreDrawState = PREDRAW_PENDING;
3917        }
3918
3919        // else state is PREDRAW_PENDING, so keep waiting.
3920    }
3921
3922    /**
3923     * {@inheritDoc}
3924     */
3925    public boolean onPreDraw() {
3926        if (mPreDrawState != PREDRAW_PENDING) {
3927            return true;
3928        }
3929
3930        if (mLayout == null) {
3931            assumeLayout();
3932        }
3933
3934        boolean changed = false;
3935
3936        if (mMovement != null) {
3937            /* This code also provides auto-scrolling when a cursor is moved using a
3938             * CursorController (insertion point or selection limits).
3939             * For selection, ensure start or end is visible depending on controller's state.
3940             */
3941            int curs = getSelectionEnd();
3942            // Do not create the controller if it is not already created.
3943            if (mSelectionModifierCursorController != null &&
3944                    mSelectionModifierCursorController.isSelectionStartDragged()) {
3945                curs = getSelectionStart();
3946            }
3947
3948            /*
3949             * TODO: This should really only keep the end in view if
3950             * it already was before the text changed.  I'm not sure
3951             * of a good way to tell from here if it was.
3952             */
3953            if (curs < 0 &&
3954                  (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
3955                curs = mText.length();
3956            }
3957
3958            if (curs >= 0) {
3959                changed = bringPointIntoView(curs);
3960            }
3961        } else {
3962            changed = bringTextIntoView();
3963        }
3964
3965        // This has to be checked here since:
3966        // - onFocusChanged cannot start it when focus is given to a view with selected text (after
3967        //   a screen rotation) since layout is not yet initialized at that point.
3968        if (mCreatedWithASelection) {
3969            startSelectionActionMode();
3970            mCreatedWithASelection = false;
3971        }
3972
3973        // Phone specific code (there is no ExtractEditText on tablets).
3974        // ExtractEditText does not call onFocus when it is displayed, and mHasSelectionOnFocus can
3975        // not be set. Do the test here instead.
3976        if (this instanceof ExtractEditText && hasSelection()) {
3977            startSelectionActionMode();
3978        }
3979
3980        mPreDrawState = PREDRAW_DONE;
3981        return !changed;
3982    }
3983
3984    @Override
3985    protected void onAttachedToWindow() {
3986        super.onAttachedToWindow();
3987
3988        mTemporaryDetach = false;
3989
3990        if (mShowErrorAfterAttach) {
3991            showError();
3992            mShowErrorAfterAttach = false;
3993        }
3994
3995        final ViewTreeObserver observer = getViewTreeObserver();
3996        // No need to create the controller.
3997        // The get method will add the listener on controller creation.
3998        if (mInsertionPointCursorController != null) {
3999            observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
4000        }
4001        if (mSelectionModifierCursorController != null) {
4002            observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
4003        }
4004    }
4005
4006    @Override
4007    protected void onDetachedFromWindow() {
4008        super.onDetachedFromWindow();
4009
4010        final ViewTreeObserver observer = getViewTreeObserver();
4011        if (mPreDrawState != PREDRAW_NOT_REGISTERED) {
4012            observer.removeOnPreDrawListener(this);
4013            mPreDrawState = PREDRAW_NOT_REGISTERED;
4014        }
4015
4016        if (mError != null) {
4017            hideError();
4018        }
4019
4020        if (mBlink != null) {
4021            mBlink.removeCallbacks(mBlink);
4022        }
4023
4024        if (mInsertionPointCursorController != null) {
4025            mInsertionPointCursorController.onDetached();
4026        }
4027
4028        if (mSelectionModifierCursorController != null) {
4029            mSelectionModifierCursorController.onDetached();
4030        }
4031
4032        hideControllers();
4033    }
4034
4035    @Override
4036    protected boolean isPaddingOffsetRequired() {
4037        return mShadowRadius != 0 || mDrawables != null;
4038    }
4039
4040    @Override
4041    protected int getLeftPaddingOffset() {
4042        return getCompoundPaddingLeft() - mPaddingLeft +
4043                (int) Math.min(0, mShadowDx - mShadowRadius);
4044    }
4045
4046    @Override
4047    protected int getTopPaddingOffset() {
4048        return (int) Math.min(0, mShadowDy - mShadowRadius);
4049    }
4050
4051    @Override
4052    protected int getBottomPaddingOffset() {
4053        return (int) Math.max(0, mShadowDy + mShadowRadius);
4054    }
4055
4056    @Override
4057    protected int getRightPaddingOffset() {
4058        return -(getCompoundPaddingRight() - mPaddingRight) +
4059                (int) Math.max(0, mShadowDx + mShadowRadius);
4060    }
4061
4062    @Override
4063    protected boolean verifyDrawable(Drawable who) {
4064        final boolean verified = super.verifyDrawable(who);
4065        if (!verified && mDrawables != null) {
4066            return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop ||
4067                    who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom;
4068        }
4069        return verified;
4070    }
4071
4072    @Override
4073    public void jumpDrawablesToCurrentState() {
4074        super.jumpDrawablesToCurrentState();
4075        if (mDrawables != null) {
4076            if (mDrawables.mDrawableLeft != null) {
4077                mDrawables.mDrawableLeft.jumpToCurrentState();
4078            }
4079            if (mDrawables.mDrawableTop != null) {
4080                mDrawables.mDrawableTop.jumpToCurrentState();
4081            }
4082            if (mDrawables.mDrawableRight != null) {
4083                mDrawables.mDrawableRight.jumpToCurrentState();
4084            }
4085            if (mDrawables.mDrawableBottom != null) {
4086                mDrawables.mDrawableBottom.jumpToCurrentState();
4087            }
4088        }
4089    }
4090
4091    @Override
4092    public void invalidateDrawable(Drawable drawable) {
4093        if (verifyDrawable(drawable)) {
4094            final Rect dirty = drawable.getBounds();
4095            int scrollX = mScrollX;
4096            int scrollY = mScrollY;
4097
4098            // IMPORTANT: The coordinates below are based on the coordinates computed
4099            // for each compound drawable in onDraw(). Make sure to update each section
4100            // accordingly.
4101            final TextView.Drawables drawables = mDrawables;
4102            if (drawables != null) {
4103                if (drawable == drawables.mDrawableLeft) {
4104                    final int compoundPaddingTop = getCompoundPaddingTop();
4105                    final int compoundPaddingBottom = getCompoundPaddingBottom();
4106                    final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
4107
4108                    scrollX += mPaddingLeft;
4109                    scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2;
4110                } else if (drawable == drawables.mDrawableRight) {
4111                    final int compoundPaddingTop = getCompoundPaddingTop();
4112                    final int compoundPaddingBottom = getCompoundPaddingBottom();
4113                    final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
4114
4115                    scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight);
4116                    scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2;
4117                } else if (drawable == drawables.mDrawableTop) {
4118                    final int compoundPaddingLeft = getCompoundPaddingLeft();
4119                    final int compoundPaddingRight = getCompoundPaddingRight();
4120                    final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft;
4121
4122                    scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2;
4123                    scrollY += mPaddingTop;
4124                } else if (drawable == drawables.mDrawableBottom) {
4125                    final int compoundPaddingLeft = getCompoundPaddingLeft();
4126                    final int compoundPaddingRight = getCompoundPaddingRight();
4127                    final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft;
4128
4129                    scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2;
4130                    scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom);
4131                }
4132            }
4133
4134            invalidate(dirty.left + scrollX, dirty.top + scrollY,
4135                    dirty.right + scrollX, dirty.bottom + scrollY);
4136        }
4137    }
4138
4139    @Override
4140    protected boolean onSetAlpha(int alpha) {
4141        // Alpha is supported if and only if the drawing can be done in one pass.
4142        // TODO text with spans with a background color currently do not respect this alpha.
4143        if (getBackground() == null) {
4144            mCurrentAlpha = alpha;
4145            final Drawables dr = mDrawables;
4146            if (dr != null) {
4147                if (dr.mDrawableLeft != null) dr.mDrawableLeft.mutate().setAlpha(alpha);
4148                if (dr.mDrawableTop != null) dr.mDrawableTop.mutate().setAlpha(alpha);
4149                if (dr.mDrawableRight != null) dr.mDrawableRight.mutate().setAlpha(alpha);
4150                if (dr.mDrawableBottom != null) dr.mDrawableBottom.mutate().setAlpha(alpha);
4151            }
4152            return true;
4153        }
4154
4155        mCurrentAlpha = 255;
4156        return false;
4157    }
4158
4159    /**
4160     * When a TextView is used to display a useful piece of information to the user (such as a
4161     * contact's address), it should be made selectable, so that the user can select and copy this
4162     * content.
4163     *
4164     * Use {@link #setTextIsSelectable(boolean)} or the
4165     * {@link android.R.styleable#TextView_textIsSelectable} XML attribute to make this TextView
4166     * selectable (text is not selectable by default).
4167     *
4168     * Note that the content of an EditText is always selectable.
4169     *
4170     * @return True if the text displayed in this TextView can be selected by the user.
4171     *
4172     * @attr ref android.R.styleable#TextView_textIsSelectable
4173     */
4174    public boolean isTextSelectable() {
4175        return mTextIsSelectable;
4176    }
4177
4178    /**
4179     * Sets whether or not (default) the content of this view is selectable by the user.
4180     *
4181     * Note that this methods affect the {@link #setFocusable(boolean)},
4182     * {@link #setFocusableInTouchMode(boolean)} {@link #setClickable(boolean)} and
4183     * {@link #setLongClickable(boolean)} states and you may want to restore these if they were
4184     * customized.
4185     *
4186     * See {@link #isTextSelectable} for details.
4187     *
4188     * @param selectable Whether or not the content of this TextView should be selectable.
4189     */
4190    public void setTextIsSelectable(boolean selectable) {
4191        if (mTextIsSelectable == selectable) return;
4192
4193        mTextIsSelectable = selectable;
4194
4195        setFocusableInTouchMode(selectable);
4196        setFocusable(selectable);
4197        setClickable(selectable);
4198        setLongClickable(selectable);
4199
4200        // mInputType is already EditorInfo.TYPE_NULL and mInput is null;
4201
4202        setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null);
4203        setText(getText(), selectable ? BufferType.SPANNABLE : BufferType.NORMAL);
4204
4205        // Called by setText above, but safer in case of future code changes
4206        prepareCursorControllers();
4207    }
4208
4209    @Override
4210    protected int[] onCreateDrawableState(int extraSpace) {
4211        final int[] drawableState;
4212
4213        if (mSingleLine) {
4214            drawableState = super.onCreateDrawableState(extraSpace);
4215        } else {
4216            drawableState = super.onCreateDrawableState(extraSpace + 1);
4217            mergeDrawableStates(drawableState, MULTILINE_STATE_SET);
4218        }
4219
4220        if (mTextIsSelectable) {
4221            // Disable pressed state, which was introduced when TextView was made clickable.
4222            // Prevents text color change.
4223            // setClickable(false) would have a similar effect, but it also disables focus changes
4224            // and long press actions, which are both needed by text selection.
4225            final int length = drawableState.length;
4226            for (int i = 0; i < length; i++) {
4227                if (drawableState[i] == R.attr.state_pressed) {
4228                    final int[] nonPressedState = new int[length - 1];
4229                    System.arraycopy(drawableState, 0, nonPressedState, 0, i);
4230                    System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1);
4231                    return nonPressedState;
4232                }
4233            }
4234        }
4235
4236        return drawableState;
4237    }
4238
4239    @Override
4240    protected void onDraw(Canvas canvas) {
4241        if (mPreDrawState == PREDRAW_DONE) {
4242            final ViewTreeObserver observer = getViewTreeObserver();
4243            observer.removeOnPreDrawListener(this);
4244            mPreDrawState = PREDRAW_NOT_REGISTERED;
4245        }
4246
4247        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return;
4248
4249        restartMarqueeIfNeeded();
4250
4251        // Draw the background for this view
4252        super.onDraw(canvas);
4253
4254        final int compoundPaddingLeft = getCompoundPaddingLeft();
4255        final int compoundPaddingTop = getCompoundPaddingTop();
4256        final int compoundPaddingRight = getCompoundPaddingRight();
4257        final int compoundPaddingBottom = getCompoundPaddingBottom();
4258        final int scrollX = mScrollX;
4259        final int scrollY = mScrollY;
4260        final int right = mRight;
4261        final int left = mLeft;
4262        final int bottom = mBottom;
4263        final int top = mTop;
4264
4265        final Drawables dr = mDrawables;
4266        if (dr != null) {
4267            /*
4268             * Compound, not extended, because the icon is not clipped
4269             * if the text height is smaller.
4270             */
4271
4272            int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop;
4273            int hspace = right - left - compoundPaddingRight - compoundPaddingLeft;
4274
4275            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4276            // Make sure to update invalidateDrawable() when changing this code.
4277            if (dr.mDrawableLeft != null) {
4278                canvas.save();
4279                canvas.translate(scrollX + mPaddingLeft,
4280                                 scrollY + compoundPaddingTop +
4281                                 (vspace - dr.mDrawableHeightLeft) / 2);
4282                dr.mDrawableLeft.draw(canvas);
4283                canvas.restore();
4284            }
4285
4286            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4287            // Make sure to update invalidateDrawable() when changing this code.
4288            if (dr.mDrawableRight != null) {
4289                canvas.save();
4290                canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight,
4291                         scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2);
4292                dr.mDrawableRight.draw(canvas);
4293                canvas.restore();
4294            }
4295
4296            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4297            // Make sure to update invalidateDrawable() when changing this code.
4298            if (dr.mDrawableTop != null) {
4299                canvas.save();
4300                canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2,
4301                        scrollY + mPaddingTop);
4302                dr.mDrawableTop.draw(canvas);
4303                canvas.restore();
4304            }
4305
4306            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4307            // Make sure to update invalidateDrawable() when changing this code.
4308            if (dr.mDrawableBottom != null) {
4309                canvas.save();
4310                canvas.translate(scrollX + compoundPaddingLeft +
4311                        (hspace - dr.mDrawableWidthBottom) / 2,
4312                         scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom);
4313                dr.mDrawableBottom.draw(canvas);
4314                canvas.restore();
4315            }
4316        }
4317
4318        int color = mCurTextColor;
4319
4320        if (mLayout == null) {
4321            assumeLayout();
4322        }
4323
4324        Layout layout = mLayout;
4325        int cursorcolor = color;
4326
4327        if (mHint != null && mText.length() == 0) {
4328            if (mHintTextColor != null) {
4329                color = mCurHintTextColor;
4330            }
4331
4332            layout = mHintLayout;
4333        }
4334
4335        mTextPaint.setColor(color);
4336        if (mCurrentAlpha != 255) {
4337            // If set, the alpha will override the color's alpha. Multiply the alphas.
4338            mTextPaint.setAlpha((mCurrentAlpha * Color.alpha(color)) / 255);
4339        }
4340        mTextPaint.drawableState = getDrawableState();
4341
4342        canvas.save();
4343        /*  Would be faster if we didn't have to do this. Can we chop the
4344            (displayable) text so that we don't need to do this ever?
4345        */
4346
4347        int extendedPaddingTop = getExtendedPaddingTop();
4348        int extendedPaddingBottom = getExtendedPaddingBottom();
4349
4350        float clipLeft = compoundPaddingLeft + scrollX;
4351        float clipTop = extendedPaddingTop + scrollY;
4352        float clipRight = right - left - compoundPaddingRight + scrollX;
4353        float clipBottom = bottom - top - extendedPaddingBottom + scrollY;
4354
4355        if (mShadowRadius != 0) {
4356            clipLeft += Math.min(0, mShadowDx - mShadowRadius);
4357            clipRight += Math.max(0, mShadowDx + mShadowRadius);
4358
4359            clipTop += Math.min(0, mShadowDy - mShadowRadius);
4360            clipBottom += Math.max(0, mShadowDy + mShadowRadius);
4361        }
4362
4363        canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom);
4364
4365        int voffsetText = 0;
4366        int voffsetCursor = 0;
4367
4368        // translate in by our padding
4369        {
4370            /* shortcircuit calling getVerticaOffset() */
4371            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4372                voffsetText = getVerticalOffset(false);
4373                voffsetCursor = getVerticalOffset(true);
4374            }
4375            canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText);
4376        }
4377
4378        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
4379            if (!mSingleLine && getLineCount() == 1 && canMarquee() &&
4380                    (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) {
4381                canvas.translate(mLayout.getLineRight(0) - (mRight - mLeft -
4382                        getCompoundPaddingLeft() - getCompoundPaddingRight()), 0.0f);
4383            }
4384
4385            if (mMarquee != null && mMarquee.isRunning()) {
4386                canvas.translate(-mMarquee.mScroll, 0.0f);
4387            }
4388        }
4389
4390        Path highlight = null;
4391        int selStart = -1, selEnd = -1;
4392        boolean drawCursor = false;
4393
4394        //  If there is no movement method, then there can be no selection.
4395        //  Check that first and attempt to skip everything having to do with
4396        //  the cursor.
4397        //  XXX This is not strictly true -- a program could set the
4398        //  selection manually if it really wanted to.
4399        if (mMovement != null && (isFocused() || isPressed())) {
4400            selStart = getSelectionStart();
4401            selEnd = getSelectionEnd();
4402
4403            if ((isCursorVisible() || mTextIsSelectable) && selStart >= 0 && isEnabled()) {
4404                if (mHighlightPath == null)
4405                    mHighlightPath = new Path();
4406
4407                if (selStart == selEnd) {
4408                    if (!mTextIsSelectable &&
4409                            (SystemClock.uptimeMillis() - mShowCursor) % (2 * BLINK) < BLINK) {
4410                        if (mHighlightPathBogus) {
4411                            mHighlightPath.reset();
4412                            mLayout.getCursorPath(selStart, mHighlightPath, mText);
4413                            updateCursorsPositions();
4414                            mHighlightPathBogus = false;
4415                        }
4416
4417                        // XXX should pass to skin instead of drawing directly
4418                        mHighlightPaint.setColor(cursorcolor);
4419                        if (mCurrentAlpha != 255) {
4420                            mHighlightPaint.setAlpha(
4421                                    (mCurrentAlpha * Color.alpha(cursorcolor)) / 255);
4422                        }
4423                        mHighlightPaint.setStyle(Paint.Style.STROKE);
4424                        highlight = mHighlightPath;
4425                        drawCursor = mCursorCount > 0;
4426                    }
4427                } else {
4428                    if (mHighlightPathBogus) {
4429                        mHighlightPath.reset();
4430                        mLayout.getSelectionPath(selStart, selEnd, mHighlightPath);
4431                        mHighlightPathBogus = false;
4432                    }
4433
4434                    // XXX should pass to skin instead of drawing directly
4435                    mHighlightPaint.setColor(mHighlightColor);
4436                    if (mCurrentAlpha != 255) {
4437                        mHighlightPaint.setAlpha(
4438                                (mCurrentAlpha * Color.alpha(mHighlightColor)) / 255);
4439                    }
4440                    mHighlightPaint.setStyle(Paint.Style.FILL);
4441
4442                    highlight = mHighlightPath;
4443                }
4444            }
4445        }
4446
4447        /*  Comment out until we decide what to do about animations
4448        boolean isLinearTextOn = false;
4449        if (currentTransformation != null) {
4450            isLinearTextOn = mTextPaint.isLinearTextOn();
4451            Matrix m = currentTransformation.getMatrix();
4452            if (!m.isIdentity()) {
4453                // mTextPaint.setLinearTextOn(true);
4454            }
4455        }
4456        */
4457
4458        final InputMethodState ims = mInputMethodState;
4459        final int cursorOffsetVertical = voffsetCursor - voffsetText;
4460        if (ims != null && ims.mBatchEditNesting == 0) {
4461            InputMethodManager imm = InputMethodManager.peekInstance();
4462            if (imm != null) {
4463                if (imm.isActive(this)) {
4464                    boolean reported = false;
4465                    if (ims.mContentChanged || ims.mSelectionModeChanged) {
4466                        // We are in extract mode and the content has changed
4467                        // in some way... just report complete new text to the
4468                        // input method.
4469                        reported = reportExtractedText();
4470                    }
4471                    if (!reported && highlight != null) {
4472                        int candStart = -1;
4473                        int candEnd = -1;
4474                        if (mText instanceof Spannable) {
4475                            Spannable sp = (Spannable)mText;
4476                            candStart = EditableInputConnection.getComposingSpanStart(sp);
4477                            candEnd = EditableInputConnection.getComposingSpanEnd(sp);
4478                        }
4479                        imm.updateSelection(this, selStart, selEnd, candStart, candEnd);
4480                    }
4481                }
4482
4483                if (imm.isWatchingCursor(this) && highlight != null) {
4484                    highlight.computeBounds(ims.mTmpRectF, true);
4485                    ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0;
4486
4487                    canvas.getMatrix().mapPoints(ims.mTmpOffset);
4488                    ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]);
4489
4490                    ims.mTmpRectF.offset(0, cursorOffsetVertical);
4491
4492                    ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5),
4493                            (int)(ims.mTmpRectF.top + 0.5),
4494                            (int)(ims.mTmpRectF.right + 0.5),
4495                            (int)(ims.mTmpRectF.bottom + 0.5));
4496
4497                    imm.updateCursor(this,
4498                            ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top,
4499                            ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom);
4500                }
4501            }
4502        }
4503
4504        if (mCorrectionHighlighter != null) {
4505            mCorrectionHighlighter.draw(canvas, cursorOffsetVertical);
4506        }
4507
4508        if (drawCursor) {
4509            drawCursor(canvas, cursorOffsetVertical);
4510            // Rely on the drawable entirely, do not draw the cursor line.
4511            // Has to be done after the IMM related code above which relies on the highlight.
4512            highlight = null;
4513        }
4514
4515        layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
4516
4517        if (mMarquee != null && mMarquee.shouldDrawGhost()) {
4518            canvas.translate((int) mMarquee.getGhostOffset(), 0.0f);
4519            layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
4520        }
4521
4522        /*  Comment out until we decide what to do about animations
4523        if (currentTransformation != null) {
4524            mTextPaint.setLinearTextOn(isLinearTextOn);
4525        }
4526        */
4527
4528        canvas.restore();
4529    }
4530
4531    private void updateCursorsPositions() {
4532        if (mCursorDrawableRes == 0) {
4533            mCursorCount = 0;
4534            return;
4535        }
4536
4537        final int offset = getSelectionStart();
4538        final int line = mLayout.getLineForOffset(offset);
4539        final int top = mLayout.getLineTop(line);
4540        final int bottom = mLayout.getLineTop(line + 1);
4541
4542        mCursorCount = mLayout.isLevelBoundary(offset) ? 2 : 1;
4543
4544        int middle = bottom;
4545        if (mCursorCount == 2) {
4546            // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)}
4547            middle = (top + bottom) >> 1;
4548        }
4549
4550        updateCursorPosition(0, top, middle, mLayout.getPrimaryHorizontal(offset));
4551
4552        if (mCursorCount == 2) {
4553            updateCursorPosition(1, middle, bottom, mLayout.getSecondaryHorizontal(offset));
4554        }
4555    }
4556
4557    private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) {
4558        if (mCursorDrawable[cursorIndex] == null)
4559            mCursorDrawable[cursorIndex] = mContext.getResources().getDrawable(mCursorDrawableRes);
4560
4561        if (mTempRect == null) mTempRect = new Rect();
4562
4563        mCursorDrawable[cursorIndex].getPadding(mTempRect);
4564        final int width = mCursorDrawable[cursorIndex].getIntrinsicWidth();
4565        horizontal = Math.max(0.5f, horizontal - 0.5f);
4566        final int left = (int) (horizontal) - mTempRect.left;
4567        mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width,
4568                bottom + mTempRect.bottom);
4569    }
4570
4571    private void drawCursor(Canvas canvas, int cursorOffsetVertical) {
4572        final boolean translate = cursorOffsetVertical != 0;
4573        if (translate) canvas.translate(0, cursorOffsetVertical);
4574        for (int i = 0; i < mCursorCount; i++) {
4575            mCursorDrawable[i].draw(canvas);
4576        }
4577        if (translate) canvas.translate(0, -cursorOffsetVertical);
4578    }
4579
4580    @Override
4581    public void getFocusedRect(Rect r) {
4582        if (mLayout == null) {
4583            super.getFocusedRect(r);
4584            return;
4585        }
4586
4587        int sel = getSelectionEnd();
4588        if (sel < 0) {
4589            super.getFocusedRect(r);
4590            return;
4591        }
4592
4593        int line = mLayout.getLineForOffset(sel);
4594        r.top = mLayout.getLineTop(line);
4595        r.bottom = mLayout.getLineBottom(line);
4596
4597        r.left = (int) mLayout.getPrimaryHorizontal(sel);
4598        r.right = r.left + 1;
4599
4600        // Adjust for padding and gravity.
4601        int paddingLeft = getCompoundPaddingLeft();
4602        int paddingTop = getExtendedPaddingTop();
4603        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4604            paddingTop += getVerticalOffset(false);
4605        }
4606        r.offset(paddingLeft, paddingTop);
4607    }
4608
4609    /**
4610     * Return the number of lines of text, or 0 if the internal Layout has not
4611     * been built.
4612     */
4613    public int getLineCount() {
4614        return mLayout != null ? mLayout.getLineCount() : 0;
4615    }
4616
4617    /**
4618     * Return the baseline for the specified line (0...getLineCount() - 1)
4619     * If bounds is not null, return the top, left, right, bottom extents
4620     * of the specified line in it. If the internal Layout has not been built,
4621     * return 0 and set bounds to (0, 0, 0, 0)
4622     * @param line which line to examine (0..getLineCount() - 1)
4623     * @param bounds Optional. If not null, it returns the extent of the line
4624     * @return the Y-coordinate of the baseline
4625     */
4626    public int getLineBounds(int line, Rect bounds) {
4627        if (mLayout == null) {
4628            if (bounds != null) {
4629                bounds.set(0, 0, 0, 0);
4630            }
4631            return 0;
4632        }
4633        else {
4634            int baseline = mLayout.getLineBounds(line, bounds);
4635
4636            int voffset = getExtendedPaddingTop();
4637            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4638                voffset += getVerticalOffset(true);
4639            }
4640            if (bounds != null) {
4641                bounds.offset(getCompoundPaddingLeft(), voffset);
4642            }
4643            return baseline + voffset;
4644        }
4645    }
4646
4647    @Override
4648    public int getBaseline() {
4649        if (mLayout == null) {
4650            return super.getBaseline();
4651        }
4652
4653        int voffset = 0;
4654        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4655            voffset = getVerticalOffset(true);
4656        }
4657
4658        return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0);
4659    }
4660
4661    @Override
4662    public boolean onKeyDown(int keyCode, KeyEvent event) {
4663        int which = doKeyDown(keyCode, event, null);
4664        if (which == 0) {
4665            // Go through default dispatching.
4666            return super.onKeyDown(keyCode, event);
4667        }
4668
4669        return true;
4670    }
4671
4672    @Override
4673    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4674        KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN);
4675
4676        int which = doKeyDown(keyCode, down, event);
4677        if (which == 0) {
4678            // Go through default dispatching.
4679            return super.onKeyMultiple(keyCode, repeatCount, event);
4680        }
4681        if (which == -1) {
4682            // Consumed the whole thing.
4683            return true;
4684        }
4685
4686        repeatCount--;
4687
4688        // We are going to dispatch the remaining events to either the input
4689        // or movement method.  To do this, we will just send a repeated stream
4690        // of down and up events until we have done the complete repeatCount.
4691        // It would be nice if those interfaces had an onKeyMultiple() method,
4692        // but adding that is a more complicated change.
4693        KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP);
4694        if (which == 1) {
4695            mInput.onKeyUp(this, (Editable)mText, keyCode, up);
4696            while (--repeatCount > 0) {
4697                mInput.onKeyDown(this, (Editable)mText, keyCode, down);
4698                mInput.onKeyUp(this, (Editable)mText, keyCode, up);
4699            }
4700            hideErrorIfUnchanged();
4701
4702        } else if (which == 2) {
4703            mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
4704            while (--repeatCount > 0) {
4705                mMovement.onKeyDown(this, (Spannable)mText, keyCode, down);
4706                mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
4707            }
4708        }
4709
4710        return true;
4711    }
4712
4713    /**
4714     * Returns true if pressing ENTER in this field advances focus instead
4715     * of inserting the character.  This is true mostly in single-line fields,
4716     * but also in mail addresses and subjects which will display on multiple
4717     * lines but where it doesn't make sense to insert newlines.
4718     */
4719    private boolean shouldAdvanceFocusOnEnter() {
4720        if (mInput == null) {
4721            return false;
4722        }
4723
4724        if (mSingleLine) {
4725            return true;
4726        }
4727
4728        if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
4729            int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION;
4730            if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
4731                    || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) {
4732                return true;
4733            }
4734        }
4735
4736        return false;
4737    }
4738
4739    /**
4740     * Returns true if pressing TAB in this field advances focus instead
4741     * of inserting the character.  Insert tabs only in multi-line editors.
4742     */
4743    private boolean shouldAdvanceFocusOnTab() {
4744        if (mInput != null && !mSingleLine) {
4745            if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
4746                int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION;
4747                if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE
4748                        || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) {
4749                    return false;
4750                }
4751            }
4752        }
4753        return true;
4754    }
4755
4756    private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) {
4757        if (!isEnabled()) {
4758            return 0;
4759        }
4760
4761        switch (keyCode) {
4762            case KeyEvent.KEYCODE_ENTER:
4763                mEnterKeyIsDown = true;
4764                if (event.hasNoModifiers()) {
4765                    // When mInputContentType is set, we know that we are
4766                    // running in a "modern" cupcake environment, so don't need
4767                    // to worry about the application trying to capture
4768                    // enter key events.
4769                    if (mInputContentType != null) {
4770                        // If there is an action listener, given them a
4771                        // chance to consume the event.
4772                        if (mInputContentType.onEditorActionListener != null &&
4773                                mInputContentType.onEditorActionListener.onEditorAction(
4774                                this, EditorInfo.IME_NULL, event)) {
4775                            mInputContentType.enterDown = true;
4776                            // We are consuming the enter key for them.
4777                            return -1;
4778                        }
4779                    }
4780
4781                    // If our editor should move focus when enter is pressed, or
4782                    // this is a generated event from an IME action button, then
4783                    // don't let it be inserted into the text.
4784                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
4785                            || shouldAdvanceFocusOnEnter()) {
4786                        if (mOnClickListener != null) {
4787                            return 0;
4788                        }
4789                        return -1;
4790                    }
4791                }
4792                break;
4793
4794            case KeyEvent.KEYCODE_DPAD_CENTER:
4795                mDPadCenterIsDown = true;
4796                if (event.hasNoModifiers()) {
4797                    if (shouldAdvanceFocusOnEnter()) {
4798                        return 0;
4799                    }
4800                }
4801                break;
4802
4803            case KeyEvent.KEYCODE_TAB:
4804                if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
4805                    if (shouldAdvanceFocusOnTab()) {
4806                        return 0;
4807                    }
4808                }
4809                break;
4810
4811                // Has to be done on key down (and not on key up) to correctly be intercepted.
4812            case KeyEvent.KEYCODE_BACK:
4813                if (mSelectionActionMode != null) {
4814                    stopSelectionActionMode();
4815                    return -1;
4816                }
4817                break;
4818        }
4819
4820        if (mInput != null) {
4821            resetErrorChangedFlag();
4822
4823            boolean doDown = true;
4824            if (otherEvent != null) {
4825                try {
4826                    beginBatchEdit();
4827                    final boolean handled = mInput.onKeyOther(this, (Editable) mText, otherEvent);
4828                    hideErrorIfUnchanged();
4829                    doDown = false;
4830                    if (handled) {
4831                        return -1;
4832                    }
4833                } catch (AbstractMethodError e) {
4834                    // onKeyOther was added after 1.0, so if it isn't
4835                    // implemented we need to try to dispatch as a regular down.
4836                } finally {
4837                    endBatchEdit();
4838                }
4839            }
4840
4841            if (doDown) {
4842                beginBatchEdit();
4843                final boolean handled = mInput.onKeyDown(this, (Editable) mText, keyCode, event);
4844                endBatchEdit();
4845                hideErrorIfUnchanged();
4846                if (handled) return 1;
4847            }
4848        }
4849
4850        // bug 650865: sometimes we get a key event before a layout.
4851        // don't try to move around if we don't know the layout.
4852
4853        if (mMovement != null && mLayout != null) {
4854            boolean doDown = true;
4855            if (otherEvent != null) {
4856                try {
4857                    boolean handled = mMovement.onKeyOther(this, (Spannable) mText,
4858                            otherEvent);
4859                    doDown = false;
4860                    if (handled) {
4861                        return -1;
4862                    }
4863                } catch (AbstractMethodError e) {
4864                    // onKeyOther was added after 1.0, so if it isn't
4865                    // implemented we need to try to dispatch as a regular down.
4866                }
4867            }
4868            if (doDown) {
4869                if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event))
4870                    return 2;
4871            }
4872        }
4873
4874        return 0;
4875    }
4876
4877    /**
4878     * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)}
4879     * can be recorded.
4880     * @hide
4881     */
4882    public void resetErrorChangedFlag() {
4883        /*
4884         * Keep track of what the error was before doing the input
4885         * so that if an input filter changed the error, we leave
4886         * that error showing.  Otherwise, we take down whatever
4887         * error was showing when the user types something.
4888         */
4889        mErrorWasChanged = false;
4890    }
4891
4892    /**
4893     * @hide
4894     */
4895    public void hideErrorIfUnchanged() {
4896        if (mError != null && !mErrorWasChanged) {
4897            setError(null, null);
4898        }
4899    }
4900
4901    @Override
4902    public boolean onKeyUp(int keyCode, KeyEvent event) {
4903        if (!isEnabled()) {
4904            return super.onKeyUp(keyCode, event);
4905        }
4906
4907        switch (keyCode) {
4908            case KeyEvent.KEYCODE_DPAD_CENTER:
4909                mDPadCenterIsDown = false;
4910                if (event.hasNoModifiers()) {
4911                    /*
4912                     * If there is a click listener, just call through to
4913                     * super, which will invoke it.
4914                     *
4915                     * If there isn't a click listener, try to show the soft
4916                     * input method.  (It will also
4917                     * call performClick(), but that won't do anything in
4918                     * this case.)
4919                     */
4920                    if (mOnClickListener == null) {
4921                        if (mMovement != null && mText instanceof Editable
4922                                && mLayout != null && onCheckIsTextEditor()) {
4923                            InputMethodManager imm = InputMethodManager.peekInstance();
4924                            if (imm != null) imm.showSoftInput(this, 0);
4925                        }
4926                    }
4927                }
4928                return super.onKeyUp(keyCode, event);
4929
4930            case KeyEvent.KEYCODE_ENTER:
4931                mEnterKeyIsDown = false;
4932                if (event.hasNoModifiers()) {
4933                    if (mInputContentType != null
4934                            && mInputContentType.onEditorActionListener != null
4935                            && mInputContentType.enterDown) {
4936                        mInputContentType.enterDown = false;
4937                        if (mInputContentType.onEditorActionListener.onEditorAction(
4938                                this, EditorInfo.IME_NULL, event)) {
4939                            return true;
4940                        }
4941                    }
4942
4943                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
4944                            || shouldAdvanceFocusOnEnter()) {
4945                        /*
4946                         * If there is a click listener, just call through to
4947                         * super, which will invoke it.
4948                         *
4949                         * If there isn't a click listener, try to advance focus,
4950                         * but still call through to super, which will reset the
4951                         * pressed state and longpress state.  (It will also
4952                         * call performClick(), but that won't do anything in
4953                         * this case.)
4954                         */
4955                        if (mOnClickListener == null) {
4956                            View v = focusSearch(FOCUS_DOWN);
4957
4958                            if (v != null) {
4959                                if (!v.requestFocus(FOCUS_DOWN)) {
4960                                    throw new IllegalStateException(
4961                                            "focus search returned a view " +
4962                                            "that wasn't able to take focus!");
4963                                }
4964
4965                                /*
4966                                 * Return true because we handled the key; super
4967                                 * will return false because there was no click
4968                                 * listener.
4969                                 */
4970                                super.onKeyUp(keyCode, event);
4971                                return true;
4972                            } else if ((event.getFlags()
4973                                    & KeyEvent.FLAG_EDITOR_ACTION) != 0) {
4974                                // No target for next focus, but make sure the IME
4975                                // if this came from it.
4976                                InputMethodManager imm = InputMethodManager.peekInstance();
4977                                if (imm != null && imm.isActive(this)) {
4978                                    imm.hideSoftInputFromWindow(getWindowToken(), 0);
4979                                }
4980                            }
4981                        }
4982                    }
4983                    return super.onKeyUp(keyCode, event);
4984                }
4985                break;
4986        }
4987
4988        if (mInput != null)
4989            if (mInput.onKeyUp(this, (Editable) mText, keyCode, event))
4990                return true;
4991
4992        if (mMovement != null && mLayout != null)
4993            if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event))
4994                return true;
4995
4996        return super.onKeyUp(keyCode, event);
4997    }
4998
4999    @Override public boolean onCheckIsTextEditor() {
5000        return mInputType != EditorInfo.TYPE_NULL;
5001    }
5002
5003    @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
5004        if (onCheckIsTextEditor() && isEnabled()) {
5005            if (mInputMethodState == null) {
5006                mInputMethodState = new InputMethodState();
5007            }
5008            outAttrs.inputType = mInputType;
5009            if (mInputContentType != null) {
5010                outAttrs.imeOptions = mInputContentType.imeOptions;
5011                outAttrs.privateImeOptions = mInputContentType.privateImeOptions;
5012                outAttrs.actionLabel = mInputContentType.imeActionLabel;
5013                outAttrs.actionId = mInputContentType.imeActionId;
5014                outAttrs.extras = mInputContentType.extras;
5015            } else {
5016                outAttrs.imeOptions = EditorInfo.IME_NULL;
5017            }
5018            if (focusSearch(FOCUS_DOWN) != null) {
5019                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT;
5020            }
5021            if (focusSearch(FOCUS_UP) != null) {
5022                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS;
5023            }
5024            if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION)
5025                    == EditorInfo.IME_ACTION_UNSPECIFIED) {
5026                if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) {
5027                    // An action has not been set, but the enter key will move to
5028                    // the next focus, so set the action to that.
5029                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT;
5030                } else {
5031                    // An action has not been set, and there is no focus to move
5032                    // to, so let's just supply a "done" action.
5033                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
5034                }
5035                if (!shouldAdvanceFocusOnEnter()) {
5036                    outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
5037                }
5038            }
5039            if (isMultilineInputType(outAttrs.inputType)) {
5040                // Multi-line text editors should always show an enter key.
5041                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
5042            }
5043            outAttrs.hintText = mHint;
5044            if (mText instanceof Editable) {
5045                InputConnection ic = new EditableInputConnection(this);
5046                outAttrs.initialSelStart = getSelectionStart();
5047                outAttrs.initialSelEnd = getSelectionEnd();
5048                outAttrs.initialCapsMode = ic.getCursorCapsMode(mInputType);
5049                return ic;
5050            }
5051        }
5052        return null;
5053    }
5054
5055    /**
5056     * If this TextView contains editable content, extract a portion of it
5057     * based on the information in <var>request</var> in to <var>outText</var>.
5058     * @return Returns true if the text was successfully extracted, else false.
5059     */
5060    public boolean extractText(ExtractedTextRequest request,
5061            ExtractedText outText) {
5062        return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN,
5063                EXTRACT_UNKNOWN, outText);
5064    }
5065
5066    static final int EXTRACT_NOTHING = -2;
5067    static final int EXTRACT_UNKNOWN = -1;
5068
5069    boolean extractTextInternal(ExtractedTextRequest request,
5070            int partialStartOffset, int partialEndOffset, int delta,
5071            ExtractedText outText) {
5072        final CharSequence content = mText;
5073        if (content != null) {
5074            if (partialStartOffset != EXTRACT_NOTHING) {
5075                final int N = content.length();
5076                if (partialStartOffset < 0) {
5077                    outText.partialStartOffset = outText.partialEndOffset = -1;
5078                    partialStartOffset = 0;
5079                    partialEndOffset = N;
5080                } else {
5081                    // Now use the delta to determine the actual amount of text
5082                    // we need.
5083                    partialEndOffset += delta;
5084                    // Adjust offsets to ensure we contain full spans.
5085                    if (content instanceof Spanned) {
5086                        Spanned spanned = (Spanned)content;
5087                        Object[] spans = spanned.getSpans(partialStartOffset,
5088                                partialEndOffset, ParcelableSpan.class);
5089                        int i = spans.length;
5090                        while (i > 0) {
5091                            i--;
5092                            int j = spanned.getSpanStart(spans[i]);
5093                            if (j < partialStartOffset) partialStartOffset = j;
5094                            j = spanned.getSpanEnd(spans[i]);
5095                            if (j > partialEndOffset) partialEndOffset = j;
5096                        }
5097                    }
5098                    outText.partialStartOffset = partialStartOffset;
5099                    outText.partialEndOffset = partialEndOffset - delta;
5100
5101                    if (partialStartOffset > N) {
5102                        partialStartOffset = N;
5103                    } else if (partialStartOffset < 0) {
5104                        partialStartOffset = 0;
5105                    }
5106                    if (partialEndOffset > N) {
5107                        partialEndOffset = N;
5108                    } else if (partialEndOffset < 0) {
5109                        partialEndOffset = 0;
5110                    }
5111                }
5112                if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) {
5113                    outText.text = content.subSequence(partialStartOffset,
5114                            partialEndOffset);
5115                } else {
5116                    outText.text = TextUtils.substring(content, partialStartOffset,
5117                            partialEndOffset);
5118                }
5119            } else {
5120                outText.partialStartOffset = 0;
5121                outText.partialEndOffset = 0;
5122                outText.text = "";
5123            }
5124            outText.flags = 0;
5125            if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) {
5126                outText.flags |= ExtractedText.FLAG_SELECTING;
5127            }
5128            if (mSingleLine) {
5129                outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
5130            }
5131            outText.startOffset = 0;
5132            outText.selectionStart = getSelectionStart();
5133            outText.selectionEnd = getSelectionEnd();
5134            return true;
5135        }
5136        return false;
5137    }
5138
5139    boolean reportExtractedText() {
5140        final InputMethodState ims = mInputMethodState;
5141        if (ims != null) {
5142            final boolean contentChanged = ims.mContentChanged;
5143            if (contentChanged || ims.mSelectionModeChanged) {
5144                ims.mContentChanged = false;
5145                ims.mSelectionModeChanged = false;
5146                final ExtractedTextRequest req = mInputMethodState.mExtracting;
5147                if (req != null) {
5148                    InputMethodManager imm = InputMethodManager.peekInstance();
5149                    if (imm != null) {
5150                        if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start="
5151                                + ims.mChangedStart + " end=" + ims.mChangedEnd
5152                                + " delta=" + ims.mChangedDelta);
5153                        if (ims.mChangedStart < 0 && !contentChanged) {
5154                            ims.mChangedStart = EXTRACT_NOTHING;
5155                        }
5156                        if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd,
5157                                ims.mChangedDelta, ims.mTmpExtracted)) {
5158                            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start="
5159                                    + ims.mTmpExtracted.partialStartOffset
5160                                    + " end=" + ims.mTmpExtracted.partialEndOffset
5161                                    + ": " + ims.mTmpExtracted.text);
5162                            imm.updateExtractedText(this, req.token,
5163                                    mInputMethodState.mTmpExtracted);
5164                            ims.mChangedStart = EXTRACT_UNKNOWN;
5165                            ims.mChangedEnd = EXTRACT_UNKNOWN;
5166                            ims.mChangedDelta = 0;
5167                            ims.mContentChanged = false;
5168                            return true;
5169                        }
5170                    }
5171                }
5172            }
5173        }
5174        return false;
5175    }
5176
5177    /**
5178     * This is used to remove all style-impacting spans from text before new
5179     * extracted text is being replaced into it, so that we don't have any
5180     * lingering spans applied during the replace.
5181     */
5182    static void removeParcelableSpans(Spannable spannable, int start, int end) {
5183        Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class);
5184        int i = spans.length;
5185        while (i > 0) {
5186            i--;
5187            spannable.removeSpan(spans[i]);
5188        }
5189    }
5190
5191    /**
5192     * Apply to this text view the given extracted text, as previously
5193     * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}.
5194     */
5195    public void setExtractedText(ExtractedText text) {
5196        Editable content = getEditableText();
5197        if (text.text != null) {
5198            if (content == null) {
5199                setText(text.text, TextView.BufferType.EDITABLE);
5200            } else if (text.partialStartOffset < 0) {
5201                removeParcelableSpans(content, 0, content.length());
5202                content.replace(0, content.length(), text.text);
5203            } else {
5204                final int N = content.length();
5205                int start = text.partialStartOffset;
5206                if (start > N) start = N;
5207                int end = text.partialEndOffset;
5208                if (end > N) end = N;
5209                removeParcelableSpans(content, start, end);
5210                content.replace(start, end, text.text);
5211            }
5212        }
5213
5214        // Now set the selection position...  make sure it is in range, to
5215        // avoid crashes.  If this is a partial update, it is possible that
5216        // the underlying text may have changed, causing us problems here.
5217        // Also we just don't want to trust clients to do the right thing.
5218        Spannable sp = (Spannable)getText();
5219        final int N = sp.length();
5220        int start = text.selectionStart;
5221        if (start < 0) start = 0;
5222        else if (start > N) start = N;
5223        int end = text.selectionEnd;
5224        if (end < 0) end = 0;
5225        else if (end > N) end = N;
5226        Selection.setSelection(sp, start, end);
5227
5228        // Finally, update the selection mode.
5229        if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) {
5230            MetaKeyKeyListener.startSelecting(this, sp);
5231        } else {
5232            MetaKeyKeyListener.stopSelecting(this, sp);
5233        }
5234    }
5235
5236    /**
5237     * @hide
5238     */
5239    public void setExtracting(ExtractedTextRequest req) {
5240        if (mInputMethodState != null) {
5241            mInputMethodState.mExtracting = req;
5242        }
5243        // This stops a possible text selection mode. Maybe not intended.
5244        hideControllers();
5245    }
5246
5247    /**
5248     * Called by the framework in response to a text completion from
5249     * the current input method, provided by it calling
5250     * {@link InputConnection#commitCompletion
5251     * InputConnection.commitCompletion()}.  The default implementation does
5252     * nothing; text views that are supporting auto-completion should override
5253     * this to do their desired behavior.
5254     *
5255     * @param text The auto complete text the user has selected.
5256     */
5257    public void onCommitCompletion(CompletionInfo text) {
5258        // intentionally empty
5259    }
5260
5261    /**
5262     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
5263     * a dictionnary) from the current input method, provided by it calling
5264     * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
5265     * implementation flashes the background of the corrected word to provide feedback to the user.
5266     *
5267     * @param info The auto correct info about the text that was corrected.
5268     */
5269    public void onCommitCorrection(CorrectionInfo info) {
5270        if (mCorrectionHighlighter == null) {
5271            mCorrectionHighlighter = new CorrectionHighlighter();
5272        } else {
5273            mCorrectionHighlighter.invalidate(false);
5274        }
5275
5276        mCorrectionHighlighter.highlight(info);
5277    }
5278
5279    private class CorrectionHighlighter {
5280        private final Path mPath = new Path();
5281        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
5282        private int mStart, mEnd;
5283        private long mFadingStartTime;
5284        private final static int FADE_OUT_DURATION = 400;
5285
5286        public CorrectionHighlighter() {
5287            mPaint.setCompatibilityScaling(getResources().getCompatibilityInfo().applicationScale);
5288            mPaint.setStyle(Paint.Style.FILL);
5289        }
5290
5291        public void highlight(CorrectionInfo info) {
5292            mStart = info.getOffset();
5293            mEnd = mStart + info.getNewText().length();
5294            mFadingStartTime = SystemClock.uptimeMillis();
5295
5296            if (mStart < 0 || mEnd < 0) {
5297                stopAnimation();
5298            }
5299        }
5300
5301        public void draw(Canvas canvas, int cursorOffsetVertical) {
5302            if (updatePath() && updatePaint()) {
5303                if (cursorOffsetVertical != 0) {
5304                    canvas.translate(0, cursorOffsetVertical);
5305                }
5306
5307                canvas.drawPath(mPath, mPaint);
5308
5309                if (cursorOffsetVertical != 0) {
5310                    canvas.translate(0, -cursorOffsetVertical);
5311                }
5312                invalidate(true);
5313            } else {
5314                stopAnimation();
5315                invalidate(false);
5316            }
5317        }
5318
5319        private boolean updatePaint() {
5320            final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
5321            if (duration > FADE_OUT_DURATION) return false;
5322
5323            final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
5324            final int highlightColorAlpha = Color.alpha(mHighlightColor);
5325            final int color = (mHighlightColor & 0x00FFFFFF) +
5326                    ((int) (highlightColorAlpha * coef) << 24);
5327            mPaint.setColor(color);
5328            return true;
5329        }
5330
5331        private boolean updatePath() {
5332            final Layout layout = TextView.this.mLayout;
5333            if (layout == null) return false;
5334
5335            // Update in case text is edited while the animation is run
5336            final int length = mText.length();
5337            int start = Math.min(length, mStart);
5338            int end = Math.min(length, mEnd);
5339
5340            mPath.reset();
5341            TextView.this.mLayout.getSelectionPath(start, end, mPath);
5342            return true;
5343        }
5344
5345        private void invalidate(boolean delayed) {
5346            if (TextView.this.mLayout == null) return;
5347
5348            synchronized (sTempRect) {
5349                mPath.computeBounds(sTempRect, false);
5350
5351                int left = getCompoundPaddingLeft();
5352                int top = getExtendedPaddingTop() + getVerticalOffset(true);
5353
5354                if (delayed) {
5355                    TextView.this.postInvalidateDelayed(16, // 60 Hz update
5356                            left + (int) sTempRect.left, top + (int) sTempRect.top,
5357                            left + (int) sTempRect.right, top + (int) sTempRect.bottom);
5358                } else {
5359                    TextView.this.postInvalidate((int) sTempRect.left, (int) sTempRect.top,
5360                            (int) sTempRect.right, (int) sTempRect.bottom);
5361                }
5362            }
5363        }
5364
5365        private void stopAnimation() {
5366            TextView.this.mCorrectionHighlighter = null;
5367        }
5368    }
5369
5370    public void beginBatchEdit() {
5371        mInBatchEditControllers = true;
5372        final InputMethodState ims = mInputMethodState;
5373        if (ims != null) {
5374            int nesting = ++ims.mBatchEditNesting;
5375            if (nesting == 1) {
5376                ims.mCursorChanged = false;
5377                ims.mChangedDelta = 0;
5378                if (ims.mContentChanged) {
5379                    // We already have a pending change from somewhere else,
5380                    // so turn this into a full update.
5381                    ims.mChangedStart = 0;
5382                    ims.mChangedEnd = mText.length();
5383                } else {
5384                    ims.mChangedStart = EXTRACT_UNKNOWN;
5385                    ims.mChangedEnd = EXTRACT_UNKNOWN;
5386                    ims.mContentChanged = false;
5387                }
5388                onBeginBatchEdit();
5389            }
5390        }
5391    }
5392
5393    public void endBatchEdit() {
5394        mInBatchEditControllers = false;
5395        final InputMethodState ims = mInputMethodState;
5396        if (ims != null) {
5397            int nesting = --ims.mBatchEditNesting;
5398            if (nesting == 0) {
5399                finishBatchEdit(ims);
5400            }
5401        }
5402    }
5403
5404    void ensureEndedBatchEdit() {
5405        final InputMethodState ims = mInputMethodState;
5406        if (ims != null && ims.mBatchEditNesting != 0) {
5407            ims.mBatchEditNesting = 0;
5408            finishBatchEdit(ims);
5409        }
5410    }
5411
5412    void finishBatchEdit(final InputMethodState ims) {
5413        onEndBatchEdit();
5414
5415        if (ims.mContentChanged || ims.mSelectionModeChanged) {
5416            updateAfterEdit();
5417            reportExtractedText();
5418        } else if (ims.mCursorChanged) {
5419            // Cheezy way to get us to report the current cursor location.
5420            invalidateCursor();
5421        }
5422    }
5423
5424    void updateAfterEdit() {
5425        invalidate();
5426        int curs = getSelectionStart();
5427
5428        if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
5429            registerForPreDraw();
5430        }
5431
5432        if (curs >= 0) {
5433            mHighlightPathBogus = true;
5434            makeBlink();
5435        }
5436
5437        checkForResize();
5438    }
5439
5440    /**
5441     * Called by the framework in response to a request to begin a batch
5442     * of edit operations through a call to link {@link #beginBatchEdit()}.
5443     */
5444    public void onBeginBatchEdit() {
5445        // intentionally empty
5446    }
5447
5448    /**
5449     * Called by the framework in response to a request to end a batch
5450     * of edit operations through a call to link {@link #endBatchEdit}.
5451     */
5452    public void onEndBatchEdit() {
5453        // intentionally empty
5454    }
5455
5456    /**
5457     * Called by the framework in response to a private command from the
5458     * current method, provided by it calling
5459     * {@link InputConnection#performPrivateCommand
5460     * InputConnection.performPrivateCommand()}.
5461     *
5462     * @param action The action name of the command.
5463     * @param data Any additional data for the command.  This may be null.
5464     * @return Return true if you handled the command, else false.
5465     */
5466    public boolean onPrivateIMECommand(String action, Bundle data) {
5467        return false;
5468    }
5469
5470    private void nullLayouts() {
5471        if (mLayout instanceof BoringLayout && mSavedLayout == null) {
5472            mSavedLayout = (BoringLayout) mLayout;
5473        }
5474        if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) {
5475            mSavedHintLayout = (BoringLayout) mHintLayout;
5476        }
5477
5478        mLayout = mHintLayout = null;
5479
5480        // Since it depends on the value of mLayout
5481        prepareCursorControllers();
5482    }
5483
5484    /**
5485     * Make a new Layout based on the already-measured size of the view,
5486     * on the assumption that it was measured correctly at some point.
5487     */
5488    private void assumeLayout() {
5489        int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5490
5491        if (width < 1) {
5492            width = 0;
5493        }
5494
5495        int physicalWidth = width;
5496
5497        if (mHorizontallyScrolling) {
5498            width = VERY_WIDE;
5499        }
5500
5501        makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING,
5502                      physicalWidth, false);
5503    }
5504
5505    /**
5506     * The width passed in is now the desired layout width,
5507     * not the full view width with padding.
5508     * {@hide}
5509     */
5510    protected void makeNewLayout(int w, int hintWidth,
5511                                 BoringLayout.Metrics boring,
5512                                 BoringLayout.Metrics hintBoring,
5513                                 int ellipsisWidth, boolean bringIntoView) {
5514        stopMarquee();
5515
5516        mHighlightPathBogus = true;
5517
5518        if (w < 0) {
5519            w = 0;
5520        }
5521        if (hintWidth < 0) {
5522            hintWidth = 0;
5523        }
5524
5525        Layout.Alignment alignment;
5526        switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
5527            case Gravity.CENTER_HORIZONTAL:
5528                alignment = Layout.Alignment.ALIGN_CENTER;
5529                break;
5530
5531            case Gravity.RIGHT:
5532                // Note, Layout resolves ALIGN_OPPOSITE to left or
5533                // right based on the paragraph direction.
5534                alignment = Layout.Alignment.ALIGN_OPPOSITE;
5535                break;
5536
5537            default:
5538                alignment = Layout.Alignment.ALIGN_NORMAL;
5539        }
5540
5541        boolean shouldEllipsize = mEllipsize != null && mInput == null;
5542
5543        if (mText instanceof Spannable) {
5544            mLayout = new DynamicLayout(mText, mTransformed, mTextPaint, w,
5545                    alignment, mSpacingMult,
5546                    mSpacingAdd, mIncludePad, mInput == null ? mEllipsize : null,
5547                    ellipsisWidth);
5548        } else {
5549            if (boring == UNKNOWN_BORING) {
5550                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mBoring);
5551                if (boring != null) {
5552                    mBoring = boring;
5553                }
5554            }
5555
5556            if (boring != null) {
5557                if (boring.width <= w &&
5558                    (mEllipsize == null || boring.width <= ellipsisWidth)) {
5559                    if (mSavedLayout != null) {
5560                        mLayout = mSavedLayout.
5561                                replaceOrMake(mTransformed, mTextPaint,
5562                                w, alignment, mSpacingMult, mSpacingAdd,
5563                                boring, mIncludePad);
5564                    } else {
5565                        mLayout = BoringLayout.make(mTransformed, mTextPaint,
5566                                w, alignment, mSpacingMult, mSpacingAdd,
5567                                boring, mIncludePad);
5568                    }
5569
5570                    mSavedLayout = (BoringLayout) mLayout;
5571                } else if (shouldEllipsize && boring.width <= w) {
5572                    if (mSavedLayout != null) {
5573                        mLayout = mSavedLayout.
5574                                replaceOrMake(mTransformed, mTextPaint,
5575                                w, alignment, mSpacingMult, mSpacingAdd,
5576                                boring, mIncludePad, mEllipsize,
5577                                ellipsisWidth);
5578                    } else {
5579                        mLayout = BoringLayout.make(mTransformed, mTextPaint,
5580                                w, alignment, mSpacingMult, mSpacingAdd,
5581                                boring, mIncludePad, mEllipsize,
5582                                ellipsisWidth);
5583                    }
5584                } else if (shouldEllipsize) {
5585                    mLayout = new StaticLayout(mTransformed,
5586                                0, mTransformed.length(),
5587                                mTextPaint, w, alignment, mSpacingMult,
5588                                mSpacingAdd, mIncludePad, mEllipsize,
5589                                ellipsisWidth);
5590                } else {
5591                    mLayout = new StaticLayout(mTransformed, mTextPaint,
5592                            w, alignment, mSpacingMult, mSpacingAdd,
5593                            mIncludePad);
5594                }
5595            } else if (shouldEllipsize) {
5596                mLayout = new StaticLayout(mTransformed,
5597                            0, mTransformed.length(),
5598                            mTextPaint, w, alignment, mSpacingMult,
5599                            mSpacingAdd, mIncludePad, mEllipsize,
5600                            ellipsisWidth);
5601            } else {
5602                mLayout = new StaticLayout(mTransformed, mTextPaint,
5603                        w, alignment, mSpacingMult, mSpacingAdd,
5604                        mIncludePad);
5605            }
5606        }
5607
5608        shouldEllipsize = mEllipsize != null;
5609        mHintLayout = null;
5610
5611        if (mHint != null) {
5612            if (shouldEllipsize) hintWidth = w;
5613
5614            if (hintBoring == UNKNOWN_BORING) {
5615                hintBoring = BoringLayout.isBoring(mHint, mTextPaint,
5616                                                   mHintBoring);
5617                if (hintBoring != null) {
5618                    mHintBoring = hintBoring;
5619                }
5620            }
5621
5622            if (hintBoring != null) {
5623                if (hintBoring.width <= hintWidth &&
5624                    (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) {
5625                    if (mSavedHintLayout != null) {
5626                        mHintLayout = mSavedHintLayout.
5627                                replaceOrMake(mHint, mTextPaint,
5628                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5629                                hintBoring, mIncludePad);
5630                    } else {
5631                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5632                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5633                                hintBoring, mIncludePad);
5634                    }
5635
5636                    mSavedHintLayout = (BoringLayout) mHintLayout;
5637                } else if (shouldEllipsize && hintBoring.width <= hintWidth) {
5638                    if (mSavedHintLayout != null) {
5639                        mHintLayout = mSavedHintLayout.
5640                                replaceOrMake(mHint, mTextPaint,
5641                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5642                                hintBoring, mIncludePad, mEllipsize,
5643                                ellipsisWidth);
5644                    } else {
5645                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5646                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5647                                hintBoring, mIncludePad, mEllipsize,
5648                                ellipsisWidth);
5649                    }
5650                } else if (shouldEllipsize) {
5651                    mHintLayout = new StaticLayout(mHint,
5652                                0, mHint.length(),
5653                                mTextPaint, hintWidth, alignment, mSpacingMult,
5654                                mSpacingAdd, mIncludePad, mEllipsize,
5655                                ellipsisWidth);
5656                } else {
5657                    mHintLayout = new StaticLayout(mHint, mTextPaint,
5658                            hintWidth, alignment, mSpacingMult, mSpacingAdd,
5659                            mIncludePad);
5660                }
5661            } else if (shouldEllipsize) {
5662                mHintLayout = new StaticLayout(mHint,
5663                            0, mHint.length(),
5664                            mTextPaint, hintWidth, alignment, mSpacingMult,
5665                            mSpacingAdd, mIncludePad, mEllipsize,
5666                            ellipsisWidth);
5667            } else {
5668                mHintLayout = new StaticLayout(mHint, mTextPaint,
5669                        hintWidth, alignment, mSpacingMult, mSpacingAdd,
5670                        mIncludePad);
5671            }
5672        }
5673
5674        if (bringIntoView) {
5675            registerForPreDraw();
5676        }
5677
5678        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
5679            if (!compressText(ellipsisWidth)) {
5680                final int height = mLayoutParams.height;
5681                // If the size of the view does not depend on the size of the text, try to
5682                // start the marquee immediately
5683                if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) {
5684                    startMarquee();
5685                } else {
5686                    // Defer the start of the marquee until we know our width (see setFrame())
5687                    mRestartMarquee = true;
5688                }
5689            }
5690        }
5691
5692        // CursorControllers need a non-null mLayout
5693        prepareCursorControllers();
5694    }
5695
5696    private boolean compressText(float width) {
5697        if (isHardwareAccelerated()) return false;
5698
5699        // Only compress the text if it hasn't been compressed by the previous pass
5700        if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX &&
5701                mTextPaint.getTextScaleX() == 1.0f) {
5702            final float textWidth = mLayout.getLineWidth(0);
5703            final float overflow = (textWidth + 1.0f - width) / width;
5704            if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) {
5705                mTextPaint.setTextScaleX(1.0f - overflow - 0.005f);
5706                post(new Runnable() {
5707                    public void run() {
5708                        requestLayout();
5709                    }
5710                });
5711                return true;
5712            }
5713        }
5714
5715        return false;
5716    }
5717
5718    private static int desired(Layout layout) {
5719        int n = layout.getLineCount();
5720        CharSequence text = layout.getText();
5721        float max = 0;
5722
5723        // if any line was wrapped, we can't use it.
5724        // but it's ok for the last line not to have a newline
5725
5726        for (int i = 0; i < n - 1; i++) {
5727            if (text.charAt(layout.getLineEnd(i) - 1) != '\n')
5728                return -1;
5729        }
5730
5731        for (int i = 0; i < n; i++) {
5732            max = Math.max(max, layout.getLineWidth(i));
5733        }
5734
5735        return (int) FloatMath.ceil(max);
5736    }
5737
5738    /**
5739     * Set whether the TextView includes extra top and bottom padding to make
5740     * room for accents that go above the normal ascent and descent.
5741     * The default is true.
5742     *
5743     * @attr ref android.R.styleable#TextView_includeFontPadding
5744     */
5745    public void setIncludeFontPadding(boolean includepad) {
5746        mIncludePad = includepad;
5747
5748        if (mLayout != null) {
5749            nullLayouts();
5750            requestLayout();
5751            invalidate();
5752        }
5753    }
5754
5755    private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics();
5756
5757    @Override
5758    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
5759        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
5760        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
5761        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
5762        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
5763
5764        int width;
5765        int height;
5766
5767        BoringLayout.Metrics boring = UNKNOWN_BORING;
5768        BoringLayout.Metrics hintBoring = UNKNOWN_BORING;
5769
5770        int des = -1;
5771        boolean fromexisting = false;
5772
5773        if (widthMode == MeasureSpec.EXACTLY) {
5774            // Parent has told us how big to be. So be it.
5775            width = widthSize;
5776        } else {
5777            if (mLayout != null && mEllipsize == null) {
5778                des = desired(mLayout);
5779            }
5780
5781            if (des < 0) {
5782                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mBoring);
5783                if (boring != null) {
5784                    mBoring = boring;
5785                }
5786            } else {
5787                fromexisting = true;
5788            }
5789
5790            if (boring == null || boring == UNKNOWN_BORING) {
5791                if (des < 0) {
5792                    des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint));
5793                }
5794
5795                width = des;
5796            } else {
5797                width = boring.width;
5798            }
5799
5800            final Drawables dr = mDrawables;
5801            if (dr != null) {
5802                width = Math.max(width, dr.mDrawableWidthTop);
5803                width = Math.max(width, dr.mDrawableWidthBottom);
5804            }
5805
5806            if (mHint != null) {
5807                int hintDes = -1;
5808                int hintWidth;
5809
5810                if (mHintLayout != null && mEllipsize == null) {
5811                    hintDes = desired(mHintLayout);
5812                }
5813
5814                if (hintDes < 0) {
5815                    hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring);
5816                    if (hintBoring != null) {
5817                        mHintBoring = hintBoring;
5818                    }
5819                }
5820
5821                if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
5822                    if (hintDes < 0) {
5823                        hintDes = (int) FloatMath.ceil(
5824                                Layout.getDesiredWidth(mHint, mTextPaint));
5825                    }
5826
5827                    hintWidth = hintDes;
5828                } else {
5829                    hintWidth = hintBoring.width;
5830                }
5831
5832                if (hintWidth > width) {
5833                    width = hintWidth;
5834                }
5835            }
5836
5837            width += getCompoundPaddingLeft() + getCompoundPaddingRight();
5838
5839            if (mMaxWidthMode == EMS) {
5840                width = Math.min(width, mMaxWidth * getLineHeight());
5841            } else {
5842                width = Math.min(width, mMaxWidth);
5843            }
5844
5845            if (mMinWidthMode == EMS) {
5846                width = Math.max(width, mMinWidth * getLineHeight());
5847            } else {
5848                width = Math.max(width, mMinWidth);
5849            }
5850
5851            // Check against our minimum width
5852            width = Math.max(width, getSuggestedMinimumWidth());
5853
5854            if (widthMode == MeasureSpec.AT_MOST) {
5855                width = Math.min(widthSize, width);
5856            }
5857        }
5858
5859        int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight();
5860        int unpaddedWidth = want;
5861
5862        if (mHorizontallyScrolling) want = VERY_WIDE;
5863
5864        int hintWant = want;
5865        int hintWidth = mHintLayout == null ? hintWant : mHintLayout.getWidth();
5866
5867        if (mLayout == null) {
5868            makeNewLayout(want, hintWant, boring, hintBoring,
5869                          width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
5870        } else if ((mLayout.getWidth() != want) || (hintWidth != hintWant) ||
5871                   (mLayout.getEllipsizedWidth() !=
5872                        width - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
5873            if (mHint == null && mEllipsize == null &&
5874                    want > mLayout.getWidth() &&
5875                    (mLayout instanceof BoringLayout ||
5876                            (fromexisting && des >= 0 && des <= want))) {
5877                mLayout.increaseWidthTo(want);
5878            } else {
5879                makeNewLayout(want, hintWant, boring, hintBoring,
5880                              width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
5881            }
5882        } else {
5883            // Width has not changed.
5884        }
5885
5886        if (heightMode == MeasureSpec.EXACTLY) {
5887            // Parent has told us how big to be. So be it.
5888            height = heightSize;
5889            mDesiredHeightAtMeasure = -1;
5890        } else {
5891            int desired = getDesiredHeight();
5892
5893            height = desired;
5894            mDesiredHeightAtMeasure = desired;
5895
5896            if (heightMode == MeasureSpec.AT_MOST) {
5897                height = Math.min(desired, heightSize);
5898            }
5899        }
5900
5901        int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
5902        if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) {
5903            unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum));
5904        }
5905
5906        /*
5907         * We didn't let makeNewLayout() register to bring the cursor into view,
5908         * so do it here if there is any possibility that it is needed.
5909         */
5910        if (mMovement != null ||
5911            mLayout.getWidth() > unpaddedWidth ||
5912            mLayout.getHeight() > unpaddedHeight) {
5913            registerForPreDraw();
5914        } else {
5915            scrollTo(0, 0);
5916        }
5917
5918        setMeasuredDimension(width, height);
5919    }
5920
5921    private int getDesiredHeight() {
5922        return Math.max(
5923                getDesiredHeight(mLayout, true),
5924                getDesiredHeight(mHintLayout, mEllipsize != null));
5925    }
5926
5927    private int getDesiredHeight(Layout layout, boolean cap) {
5928        if (layout == null) {
5929            return 0;
5930        }
5931
5932        int linecount = layout.getLineCount();
5933        int pad = getCompoundPaddingTop() + getCompoundPaddingBottom();
5934        int desired = layout.getLineTop(linecount);
5935
5936        final Drawables dr = mDrawables;
5937        if (dr != null) {
5938            desired = Math.max(desired, dr.mDrawableHeightLeft);
5939            desired = Math.max(desired, dr.mDrawableHeightRight);
5940        }
5941
5942        desired += pad;
5943        layout.setMaximumVisibleLineCount(0);
5944
5945        if (mMaxMode == LINES) {
5946            /*
5947             * Don't cap the hint to a certain number of lines.
5948             * (Do cap it, though, if we have a maximum pixel height.)
5949             */
5950            if (cap) {
5951                if (linecount > mMaximum) {
5952                    layout.setMaximumVisibleLineCount(mMaximum);
5953                    desired = layout.getLineTop(mMaximum);
5954
5955                    if (dr != null) {
5956                        desired = Math.max(desired, dr.mDrawableHeightLeft);
5957                        desired = Math.max(desired, dr.mDrawableHeightRight);
5958                    }
5959
5960                    desired += pad;
5961                    linecount = mMaximum;
5962                }
5963            }
5964        } else {
5965            desired = Math.min(desired, mMaximum);
5966        }
5967
5968        if (mMinMode == LINES) {
5969            if (linecount < mMinimum) {
5970                desired += getLineHeight() * (mMinimum - linecount);
5971            }
5972        } else {
5973            desired = Math.max(desired, mMinimum);
5974        }
5975
5976        // Check against our minimum height
5977        desired = Math.max(desired, getSuggestedMinimumHeight());
5978
5979        return desired;
5980    }
5981
5982    /**
5983     * Check whether a change to the existing text layout requires a
5984     * new view layout.
5985     */
5986    private void checkForResize() {
5987        boolean sizeChanged = false;
5988
5989        if (mLayout != null) {
5990            // Check if our width changed
5991            if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) {
5992                sizeChanged = true;
5993                invalidate();
5994            }
5995
5996            // Check if our height changed
5997            if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) {
5998                int desiredHeight = getDesiredHeight();
5999
6000                if (desiredHeight != this.getHeight()) {
6001                    sizeChanged = true;
6002                }
6003            } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) {
6004                if (mDesiredHeightAtMeasure >= 0) {
6005                    int desiredHeight = getDesiredHeight();
6006
6007                    if (desiredHeight != mDesiredHeightAtMeasure) {
6008                        sizeChanged = true;
6009                    }
6010                }
6011            }
6012        }
6013
6014        if (sizeChanged) {
6015            requestLayout();
6016            // caller will have already invalidated
6017        }
6018    }
6019
6020    /**
6021     * Check whether entirely new text requires a new view layout
6022     * or merely a new text layout.
6023     */
6024    private void checkForRelayout() {
6025        // If we have a fixed width, we can just swap in a new text layout
6026        // if the text height stays the same or if the view height is fixed.
6027
6028        if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT ||
6029                (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) &&
6030                (mHint == null || mHintLayout != null) &&
6031                (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) {
6032            // Static width, so try making a new text layout.
6033
6034            int oldht = mLayout.getHeight();
6035            int want = mLayout.getWidth();
6036            int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();
6037
6038            /*
6039             * No need to bring the text into view, since the size is not
6040             * changing (unless we do the requestLayout(), in which case it
6041             * will happen at measure).
6042             */
6043            makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
6044                          mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(),
6045                          false);
6046
6047            if (mEllipsize != TextUtils.TruncateAt.MARQUEE) {
6048                // In a fixed-height view, so use our new text layout.
6049                if (mLayoutParams.height != LayoutParams.WRAP_CONTENT &&
6050                    mLayoutParams.height != LayoutParams.MATCH_PARENT) {
6051                    invalidate();
6052                    return;
6053                }
6054
6055                // Dynamic height, but height has stayed the same,
6056                // so use our new text layout.
6057                if (mLayout.getHeight() == oldht &&
6058                    (mHintLayout == null || mHintLayout.getHeight() == oldht)) {
6059                    invalidate();
6060                    return;
6061                }
6062            }
6063
6064            // We lose: the height has changed and we have a dynamic height.
6065            // Request a new view layout using our new text layout.
6066            requestLayout();
6067            invalidate();
6068        } else {
6069            // Dynamic width, so we have no choice but to request a new
6070            // view layout with a new text layout.
6071
6072            nullLayouts();
6073            requestLayout();
6074            invalidate();
6075        }
6076    }
6077
6078    /**
6079     * Returns true if anything changed.
6080     */
6081    private boolean bringTextIntoView() {
6082        int line = 0;
6083        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
6084            line = mLayout.getLineCount() - 1;
6085        }
6086
6087        Layout.Alignment a = mLayout.getParagraphAlignment(line);
6088        int dir = mLayout.getParagraphDirection(line);
6089        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6090        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6091        int ht = mLayout.getHeight();
6092
6093        int scrollx, scrolly;
6094
6095        if (a == Layout.Alignment.ALIGN_CENTER) {
6096            /*
6097             * Keep centered if possible, or, if it is too wide to fit,
6098             * keep leading edge in view.
6099             */
6100
6101            int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
6102            int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6103
6104            if (right - left < hspace) {
6105                scrollx = (right + left) / 2 - hspace / 2;
6106            } else {
6107                if (dir < 0) {
6108                    scrollx = right - hspace;
6109                } else {
6110                    scrollx = left;
6111                }
6112            }
6113        } else if (a == Layout.Alignment.ALIGN_NORMAL) {
6114            /*
6115             * Keep leading edge in view.
6116             */
6117
6118            if (dir < 0) {
6119                int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6120                scrollx = right - hspace;
6121            } else {
6122                scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line));
6123            }
6124        } else /* a == Layout.Alignment.ALIGN_OPPOSITE */ {
6125            /*
6126             * Keep trailing edge in view.
6127             */
6128
6129            if (dir < 0) {
6130                scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line));
6131            } else {
6132                int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6133                scrollx = right - hspace;
6134            }
6135        }
6136
6137        if (ht < vspace) {
6138            scrolly = 0;
6139        } else {
6140            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
6141                scrolly = ht - vspace;
6142            } else {
6143                scrolly = 0;
6144            }
6145        }
6146
6147        if (scrollx != mScrollX || scrolly != mScrollY) {
6148            scrollTo(scrollx, scrolly);
6149            return true;
6150        } else {
6151            return false;
6152        }
6153    }
6154
6155    /**
6156     * Move the point, specified by the offset, into the view if it is needed.
6157     * This has to be called after layout. Returns true if anything changed.
6158     */
6159    public boolean bringPointIntoView(int offset) {
6160        boolean changed = false;
6161
6162        int line = mLayout.getLineForOffset(offset);
6163
6164        // FIXME: Is it okay to truncate this, or should we round?
6165        final int x = (int)mLayout.getPrimaryHorizontal(offset);
6166        final int top = mLayout.getLineTop(line);
6167        final int bottom = mLayout.getLineTop(line + 1);
6168
6169        int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
6170        int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6171        int ht = mLayout.getHeight();
6172
6173        int grav;
6174
6175        switch (mLayout.getParagraphAlignment(line)) {
6176            case ALIGN_NORMAL:
6177                grav = 1;
6178                break;
6179
6180            case ALIGN_OPPOSITE:
6181                grav = -1;
6182                break;
6183
6184            default:
6185                grav = 0;
6186        }
6187
6188        grav *= mLayout.getParagraphDirection(line);
6189
6190        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6191        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6192
6193        int hslack = (bottom - top) / 2;
6194        int vslack = hslack;
6195
6196        if (vslack > vspace / 4)
6197            vslack = vspace / 4;
6198        if (hslack > hspace / 4)
6199            hslack = hspace / 4;
6200
6201        int hs = mScrollX;
6202        int vs = mScrollY;
6203
6204        if (top - vs < vslack)
6205            vs = top - vslack;
6206        if (bottom - vs > vspace - vslack)
6207            vs = bottom - (vspace - vslack);
6208        if (ht - vs < vspace)
6209            vs = ht - vspace;
6210        if (0 - vs > 0)
6211            vs = 0;
6212
6213        if (grav != 0) {
6214            if (x - hs < hslack) {
6215                hs = x - hslack;
6216            }
6217            if (x - hs > hspace - hslack) {
6218                hs = x - (hspace - hslack);
6219            }
6220        }
6221
6222        if (grav < 0) {
6223            if (left - hs > 0)
6224                hs = left;
6225            if (right - hs < hspace)
6226                hs = right - hspace;
6227        } else if (grav > 0) {
6228            if (right - hs < hspace)
6229                hs = right - hspace;
6230            if (left - hs > 0)
6231                hs = left;
6232        } else /* grav == 0 */ {
6233            if (right - left <= hspace) {
6234                /*
6235                 * If the entire text fits, center it exactly.
6236                 */
6237                hs = left - (hspace - (right - left)) / 2;
6238            } else if (x > right - hslack) {
6239                /*
6240                 * If we are near the right edge, keep the right edge
6241                 * at the edge of the view.
6242                 */
6243                hs = right - hspace;
6244            } else if (x < left + hslack) {
6245                /*
6246                 * If we are near the left edge, keep the left edge
6247                 * at the edge of the view.
6248                 */
6249                hs = left;
6250            } else if (left > hs) {
6251                /*
6252                 * Is there whitespace visible at the left?  Fix it if so.
6253                 */
6254                hs = left;
6255            } else if (right < hs + hspace) {
6256                /*
6257                 * Is there whitespace visible at the right?  Fix it if so.
6258                 */
6259                hs = right - hspace;
6260            } else {
6261                /*
6262                 * Otherwise, float as needed.
6263                 */
6264                if (x - hs < hslack) {
6265                    hs = x - hslack;
6266                }
6267                if (x - hs > hspace - hslack) {
6268                    hs = x - (hspace - hslack);
6269                }
6270            }
6271        }
6272
6273        if (hs != mScrollX || vs != mScrollY) {
6274            if (mScroller == null) {
6275                scrollTo(hs, vs);
6276            } else {
6277                long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
6278                int dx = hs - mScrollX;
6279                int dy = vs - mScrollY;
6280
6281                if (duration > ANIMATED_SCROLL_GAP) {
6282                    mScroller.startScroll(mScrollX, mScrollY, dx, dy);
6283                    awakenScrollBars(mScroller.getDuration());
6284                    invalidate();
6285                } else {
6286                    if (!mScroller.isFinished()) {
6287                        mScroller.abortAnimation();
6288                    }
6289
6290                    scrollBy(dx, dy);
6291                }
6292
6293                mLastScroll = AnimationUtils.currentAnimationTimeMillis();
6294            }
6295
6296            changed = true;
6297        }
6298
6299        if (isFocused()) {
6300            // This offsets because getInterestingRect() is in terms of viewport coordinates, but
6301            // requestRectangleOnScreen() is in terms of content coordinates.
6302
6303            if (mTempRect == null) mTempRect = new Rect();
6304            mTempRect.set(x, top, x + 1, bottom);
6305            getInterestingRect(mTempRect, line);
6306            mTempRect.offset(mScrollX, mScrollY);
6307
6308            if (requestRectangleOnScreen(mTempRect)) {
6309                changed = true;
6310            }
6311        }
6312
6313        return changed;
6314    }
6315
6316    /**
6317     * Move the cursor, if needed, so that it is at an offset that is visible
6318     * to the user.  This will not move the cursor if it represents more than
6319     * one character (a selection range).  This will only work if the
6320     * TextView contains spannable text; otherwise it will do nothing.
6321     *
6322     * @return True if the cursor was actually moved, false otherwise.
6323     */
6324    public boolean moveCursorToVisibleOffset() {
6325        if (!(mText instanceof Spannable)) {
6326            return false;
6327        }
6328        int start = getSelectionStart();
6329        int end = getSelectionEnd();
6330        if (start != end) {
6331            return false;
6332        }
6333
6334        // First: make sure the line is visible on screen:
6335
6336        int line = mLayout.getLineForOffset(start);
6337
6338        final int top = mLayout.getLineTop(line);
6339        final int bottom = mLayout.getLineTop(line + 1);
6340        final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6341        int vslack = (bottom - top) / 2;
6342        if (vslack > vspace / 4)
6343            vslack = vspace / 4;
6344        final int vs = mScrollY;
6345
6346        if (top < (vs+vslack)) {
6347            line = mLayout.getLineForVertical(vs+vslack+(bottom-top));
6348        } else if (bottom > (vspace+vs-vslack)) {
6349            line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top));
6350        }
6351
6352        // Next: make sure the character is visible on screen:
6353
6354        final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6355        final int hs = mScrollX;
6356        final int leftChar = mLayout.getOffsetForHorizontal(line, hs);
6357        final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs);
6358
6359        // line might contain bidirectional text
6360        final int lowChar = leftChar < rightChar ? leftChar : rightChar;
6361        final int highChar = leftChar > rightChar ? leftChar : rightChar;
6362
6363        int newStart = start;
6364        if (newStart < lowChar) {
6365            newStart = lowChar;
6366        } else if (newStart > highChar) {
6367            newStart = highChar;
6368        }
6369
6370        if (newStart != start) {
6371            Selection.setSelection((Spannable)mText, newStart);
6372            return true;
6373        }
6374
6375        return false;
6376    }
6377
6378    @Override
6379    public void computeScroll() {
6380        if (mScroller != null) {
6381            if (mScroller.computeScrollOffset()) {
6382                mScrollX = mScroller.getCurrX();
6383                mScrollY = mScroller.getCurrY();
6384                invalidateParentCaches();
6385                postInvalidate();  // So we draw again
6386            }
6387        }
6388    }
6389
6390    private void getInterestingRect(Rect r, int line) {
6391        convertFromViewportToContentCoordinates(r);
6392
6393        // Rectangle can can be expanded on first and last line to take
6394        // padding into account.
6395        // TODO Take left/right padding into account too?
6396        if (line == 0) r.top -= getExtendedPaddingTop();
6397        if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom();
6398    }
6399
6400    private void convertFromViewportToContentCoordinates(Rect r) {
6401        final int horizontalOffset = viewportToContentHorizontalOffset();
6402        r.left += horizontalOffset;
6403        r.right += horizontalOffset;
6404
6405        final int verticalOffset = viewportToContentVerticalOffset();
6406        r.top += verticalOffset;
6407        r.bottom += verticalOffset;
6408    }
6409
6410    private int viewportToContentHorizontalOffset() {
6411        return getCompoundPaddingLeft() - mScrollX;
6412    }
6413
6414    private int viewportToContentVerticalOffset() {
6415        int offset = getExtendedPaddingTop() - mScrollY;
6416        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
6417            offset += getVerticalOffset(false);
6418        }
6419        return offset;
6420    }
6421
6422    @Override
6423    public void debug(int depth) {
6424        super.debug(depth);
6425
6426        String output = debugIndent(depth);
6427        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
6428                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
6429                + "} ";
6430
6431        if (mText != null) {
6432
6433            output += "mText=\"" + mText + "\" ";
6434            if (mLayout != null) {
6435                output += "mLayout width=" + mLayout.getWidth()
6436                        + " height=" + mLayout.getHeight();
6437            }
6438        } else {
6439            output += "mText=NULL";
6440        }
6441        Log.d(VIEW_LOG_TAG, output);
6442    }
6443
6444    /**
6445     * Convenience for {@link Selection#getSelectionStart}.
6446     */
6447    @ViewDebug.ExportedProperty(category = "text")
6448    public int getSelectionStart() {
6449        return Selection.getSelectionStart(getText());
6450    }
6451
6452    /**
6453     * Convenience for {@link Selection#getSelectionEnd}.
6454     */
6455    @ViewDebug.ExportedProperty(category = "text")
6456    public int getSelectionEnd() {
6457        return Selection.getSelectionEnd(getText());
6458    }
6459
6460    /**
6461     * Return true iff there is a selection inside this text view.
6462     */
6463    public boolean hasSelection() {
6464        final int selectionStart = getSelectionStart();
6465        final int selectionEnd = getSelectionEnd();
6466
6467        return selectionStart >= 0 && selectionStart != selectionEnd;
6468    }
6469
6470    /**
6471     * Sets the properties of this field (lines, horizontally scrolling,
6472     * transformation method) to be for a single-line input.
6473     *
6474     * @attr ref android.R.styleable#TextView_singleLine
6475     */
6476    public void setSingleLine() {
6477        setSingleLine(true);
6478    }
6479
6480    /**
6481     * If true, sets the properties of this field (number of lines, horizontally scrolling,
6482     * transformation method) to be for a single-line input; if false, restores these to the default
6483     * conditions.
6484     *
6485     * Note that the default conditions are not necessarily those that were in effect prior this
6486     * method, and you may want to reset these properties to your custom values.
6487     *
6488     * @attr ref android.R.styleable#TextView_singleLine
6489     */
6490    @android.view.RemotableViewMethod
6491    public void setSingleLine(boolean singleLine) {
6492        // Could be used, but may break backward compatibility.
6493        // if (mSingleLine == singleLine) return;
6494        setInputTypeSingleLine(singleLine);
6495        applySingleLine(singleLine, true, true);
6496    }
6497
6498    /**
6499     * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType.
6500     * @param singleLine
6501     */
6502    private void setInputTypeSingleLine(boolean singleLine) {
6503        if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
6504            if (singleLine) {
6505                mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
6506            } else {
6507                mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
6508            }
6509        }
6510    }
6511
6512    private void applySingleLine(boolean singleLine, boolean applyTransformation,
6513            boolean changeMaxLines) {
6514        mSingleLine = singleLine;
6515        if (singleLine) {
6516            setLines(1);
6517            setHorizontallyScrolling(true);
6518            if (applyTransformation) {
6519                setTransformationMethod(SingleLineTransformationMethod.getInstance());
6520            }
6521        } else {
6522            if (changeMaxLines) {
6523                setMaxLines(Integer.MAX_VALUE);
6524            }
6525            setHorizontallyScrolling(false);
6526            if (applyTransformation) {
6527                setTransformationMethod(null);
6528            }
6529        }
6530    }
6531
6532    /**
6533     * Causes words in the text that are longer than the view is wide
6534     * to be ellipsized instead of broken in the middle.  You may also
6535     * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling}
6536     * to constrain the text to a single line.  Use <code>null</code>
6537     * to turn off ellipsizing.
6538     *
6539     * @attr ref android.R.styleable#TextView_ellipsize
6540     */
6541    public void setEllipsize(TextUtils.TruncateAt where) {
6542        mEllipsize = where;
6543
6544        if (mLayout != null) {
6545            nullLayouts();
6546            requestLayout();
6547            invalidate();
6548        }
6549    }
6550
6551    /**
6552     * Sets how many times to repeat the marquee animation. Only applied if the
6553     * TextView has marquee enabled. Set to -1 to repeat indefinitely.
6554     *
6555     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
6556     */
6557    public void setMarqueeRepeatLimit(int marqueeLimit) {
6558        mMarqueeRepeatLimit = marqueeLimit;
6559    }
6560
6561    /**
6562     * Returns where, if anywhere, words that are longer than the view
6563     * is wide should be ellipsized.
6564     */
6565    @ViewDebug.ExportedProperty
6566    public TextUtils.TruncateAt getEllipsize() {
6567        return mEllipsize;
6568    }
6569
6570    /**
6571     * Set the TextView so that when it takes focus, all the text is
6572     * selected.
6573     *
6574     * @attr ref android.R.styleable#TextView_selectAllOnFocus
6575     */
6576    @android.view.RemotableViewMethod
6577    public void setSelectAllOnFocus(boolean selectAllOnFocus) {
6578        mSelectAllOnFocus = selectAllOnFocus;
6579
6580        if (selectAllOnFocus && !(mText instanceof Spannable)) {
6581            setText(mText, BufferType.SPANNABLE);
6582        }
6583    }
6584
6585    /**
6586     * Set whether the cursor is visible.  The default is true.
6587     *
6588     * @attr ref android.R.styleable#TextView_cursorVisible
6589     */
6590    @android.view.RemotableViewMethod
6591    public void setCursorVisible(boolean visible) {
6592        if (mCursorVisible != visible) {
6593            mCursorVisible = visible;
6594            invalidate();
6595
6596            makeBlink();
6597
6598            // InsertionPointCursorController depends on mCursorVisible
6599            prepareCursorControllers();
6600        }
6601    }
6602
6603    private boolean isCursorVisible() {
6604        return mCursorVisible && isTextEditable();
6605    }
6606
6607    private boolean canMarquee() {
6608        int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight());
6609        return width > 0 && mLayout.getLineWidth(0) > width;
6610    }
6611
6612    private void startMarquee() {
6613        // Do not ellipsize EditText
6614        if (mInput != null) return;
6615
6616        if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
6617            return;
6618        }
6619
6620        if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) &&
6621                getLineCount() == 1 && canMarquee()) {
6622
6623            if (mMarquee == null) mMarquee = new Marquee(this);
6624            mMarquee.start(mMarqueeRepeatLimit);
6625        }
6626    }
6627
6628    private void stopMarquee() {
6629        if (mMarquee != null && !mMarquee.isStopped()) {
6630            mMarquee.stop();
6631        }
6632    }
6633
6634    private void startStopMarquee(boolean start) {
6635        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6636            if (start) {
6637                startMarquee();
6638            } else {
6639                stopMarquee();
6640            }
6641        }
6642    }
6643
6644    private static final class Marquee extends Handler {
6645        // TODO: Add an option to configure this
6646        private static final float MARQUEE_DELTA_MAX = 0.07f;
6647        private static final int MARQUEE_DELAY = 1200;
6648        private static final int MARQUEE_RESTART_DELAY = 1200;
6649        private static final int MARQUEE_RESOLUTION = 1000 / 30;
6650        private static final int MARQUEE_PIXELS_PER_SECOND = 30;
6651
6652        private static final byte MARQUEE_STOPPED = 0x0;
6653        private static final byte MARQUEE_STARTING = 0x1;
6654        private static final byte MARQUEE_RUNNING = 0x2;
6655
6656        private static final int MESSAGE_START = 0x1;
6657        private static final int MESSAGE_TICK = 0x2;
6658        private static final int MESSAGE_RESTART = 0x3;
6659
6660        private final WeakReference<TextView> mView;
6661
6662        private byte mStatus = MARQUEE_STOPPED;
6663        private final float mScrollUnit;
6664        private float mMaxScroll;
6665        float mMaxFadeScroll;
6666        private float mGhostStart;
6667        private float mGhostOffset;
6668        private float mFadeStop;
6669        private int mRepeatLimit;
6670
6671        float mScroll;
6672
6673        Marquee(TextView v) {
6674            final float density = v.getContext().getResources().getDisplayMetrics().density;
6675            mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION;
6676            mView = new WeakReference<TextView>(v);
6677        }
6678
6679        @Override
6680        public void handleMessage(Message msg) {
6681            switch (msg.what) {
6682                case MESSAGE_START:
6683                    mStatus = MARQUEE_RUNNING;
6684                    tick();
6685                    break;
6686                case MESSAGE_TICK:
6687                    tick();
6688                    break;
6689                case MESSAGE_RESTART:
6690                    if (mStatus == MARQUEE_RUNNING) {
6691                        if (mRepeatLimit >= 0) {
6692                            mRepeatLimit--;
6693                        }
6694                        start(mRepeatLimit);
6695                    }
6696                    break;
6697            }
6698        }
6699
6700        void tick() {
6701            if (mStatus != MARQUEE_RUNNING) {
6702                return;
6703            }
6704
6705            removeMessages(MESSAGE_TICK);
6706
6707            final TextView textView = mView.get();
6708            if (textView != null && (textView.isFocused() || textView.isSelected())) {
6709                mScroll += mScrollUnit;
6710                if (mScroll > mMaxScroll) {
6711                    mScroll = mMaxScroll;
6712                    sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY);
6713                } else {
6714                    sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION);
6715                }
6716                textView.invalidate();
6717            }
6718        }
6719
6720        void stop() {
6721            mStatus = MARQUEE_STOPPED;
6722            removeMessages(MESSAGE_START);
6723            removeMessages(MESSAGE_RESTART);
6724            removeMessages(MESSAGE_TICK);
6725            resetScroll();
6726        }
6727
6728        private void resetScroll() {
6729            mScroll = 0.0f;
6730            final TextView textView = mView.get();
6731            if (textView != null) textView.invalidate();
6732        }
6733
6734        void start(int repeatLimit) {
6735            if (repeatLimit == 0) {
6736                stop();
6737                return;
6738            }
6739            mRepeatLimit = repeatLimit;
6740            final TextView textView = mView.get();
6741            if (textView != null && textView.mLayout != null) {
6742                mStatus = MARQUEE_STARTING;
6743                mScroll = 0.0f;
6744                final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() -
6745                        textView.getCompoundPaddingRight();
6746                final float lineWidth = textView.mLayout.getLineWidth(0);
6747                final float gap = textWidth / 3.0f;
6748                mGhostStart = lineWidth - textWidth + gap;
6749                mMaxScroll = mGhostStart + textWidth;
6750                mGhostOffset = lineWidth + gap;
6751                mFadeStop = lineWidth + textWidth / 6.0f;
6752                mMaxFadeScroll = mGhostStart + lineWidth + lineWidth;
6753
6754                textView.invalidate();
6755                sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY);
6756            }
6757        }
6758
6759        float getGhostOffset() {
6760            return mGhostOffset;
6761        }
6762
6763        boolean shouldDrawLeftFade() {
6764            return mScroll <= mFadeStop;
6765        }
6766
6767        boolean shouldDrawGhost() {
6768            return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart;
6769        }
6770
6771        boolean isRunning() {
6772            return mStatus == MARQUEE_RUNNING;
6773        }
6774
6775        boolean isStopped() {
6776            return mStatus == MARQUEE_STOPPED;
6777        }
6778    }
6779
6780    /**
6781     * This method is called when the text is changed, in case any subclasses
6782     * would like to know.
6783     *
6784     * Within <code>text</code>, the <code>lengthAfter</code> characters
6785     * beginning at <code>start</code> have just replaced old text that had
6786     * length <code>lengthBefore</code>. It is an error to attempt to make
6787     * changes to <code>text</code> from this callback.
6788     *
6789     * @param text The text the TextView is displaying
6790     * @param start The offset of the start of the range of the text that was
6791     * modified
6792     * @param lengthBefore The length of the former text that has been replaced
6793     * @param lengthAfter The length of the replacement modified text
6794     */
6795    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
6796        // intentionally empty
6797    }
6798
6799    /**
6800     * This method is called when the selection has changed, in case any
6801     * subclasses would like to know.
6802     *
6803     * @param selStart The new selection start location.
6804     * @param selEnd The new selection end location.
6805     */
6806    protected void onSelectionChanged(int selStart, int selEnd) {
6807        // intentionally empty
6808    }
6809
6810    /**
6811     * Adds a TextWatcher to the list of those whose methods are called
6812     * whenever this TextView's text changes.
6813     * <p>
6814     * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
6815     * not called after {@link #setText} calls.  Now, doing {@link #setText}
6816     * if there are any text changed listeners forces the buffer type to
6817     * Editable if it would not otherwise be and does call this method.
6818     */
6819    public void addTextChangedListener(TextWatcher watcher) {
6820        if (mListeners == null) {
6821            mListeners = new ArrayList<TextWatcher>();
6822        }
6823
6824        mListeners.add(watcher);
6825    }
6826
6827    /**
6828     * Removes the specified TextWatcher from the list of those whose
6829     * methods are called
6830     * whenever this TextView's text changes.
6831     */
6832    public void removeTextChangedListener(TextWatcher watcher) {
6833        if (mListeners != null) {
6834            int i = mListeners.indexOf(watcher);
6835
6836            if (i >= 0) {
6837                mListeners.remove(i);
6838            }
6839        }
6840    }
6841
6842    private void sendBeforeTextChanged(CharSequence text, int start, int before,
6843                                   int after) {
6844        if (mListeners != null) {
6845            final ArrayList<TextWatcher> list = mListeners;
6846            final int count = list.size();
6847            for (int i = 0; i < count; i++) {
6848                list.get(i).beforeTextChanged(text, start, before, after);
6849            }
6850        }
6851    }
6852
6853    /**
6854     * Not private so it can be called from an inner class without going
6855     * through a thunk.
6856     */
6857    void sendOnTextChanged(CharSequence text, int start, int before,
6858                                   int after) {
6859        if (mListeners != null) {
6860            final ArrayList<TextWatcher> list = mListeners;
6861            final int count = list.size();
6862            for (int i = 0; i < count; i++) {
6863                list.get(i).onTextChanged(text, start, before, after);
6864            }
6865        }
6866    }
6867
6868    /**
6869     * Not private so it can be called from an inner class without going
6870     * through a thunk.
6871     */
6872    void sendAfterTextChanged(Editable text) {
6873        if (mListeners != null) {
6874            final ArrayList<TextWatcher> list = mListeners;
6875            final int count = list.size();
6876            for (int i = 0; i < count; i++) {
6877                list.get(i).afterTextChanged(text);
6878            }
6879        }
6880    }
6881
6882    /**
6883     * Not private so it can be called from an inner class without going
6884     * through a thunk.
6885     */
6886    void handleTextChanged(CharSequence buffer, int start, int before, int after) {
6887        final InputMethodState ims = mInputMethodState;
6888        if (ims == null || ims.mBatchEditNesting == 0) {
6889            updateAfterEdit();
6890        }
6891        if (ims != null) {
6892            ims.mContentChanged = true;
6893            if (ims.mChangedStart < 0) {
6894                ims.mChangedStart = start;
6895                ims.mChangedEnd = start+before;
6896            } else {
6897                ims.mChangedStart = Math.min(ims.mChangedStart, start);
6898                ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta);
6899            }
6900            ims.mChangedDelta += after-before;
6901        }
6902
6903        sendOnTextChanged(buffer, start, before, after);
6904        onTextChanged(buffer, start, before, after);
6905
6906        // Hide the controllers if the amount of content changed
6907        if (before != after) {
6908            hideControllers();
6909        }
6910    }
6911
6912    /**
6913     * Not private so it can be called from an inner class without going
6914     * through a thunk.
6915     */
6916    void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) {
6917        // XXX Make the start and end move together if this ends up
6918        // spending too much time invalidating.
6919
6920        boolean selChanged = false;
6921        int newSelStart=-1, newSelEnd=-1;
6922
6923        final InputMethodState ims = mInputMethodState;
6924
6925        if (what == Selection.SELECTION_END) {
6926            mHighlightPathBogus = true;
6927            selChanged = true;
6928            newSelEnd = newStart;
6929
6930            if (!isFocused()) {
6931                mSelectionMoved = true;
6932            }
6933
6934            if (oldStart >= 0 || newStart >= 0) {
6935                invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart);
6936                registerForPreDraw();
6937                makeBlink();
6938            }
6939        }
6940
6941        if (what == Selection.SELECTION_START) {
6942            mHighlightPathBogus = true;
6943            selChanged = true;
6944            newSelStart = newStart;
6945
6946            if (!isFocused()) {
6947                mSelectionMoved = true;
6948            }
6949
6950            if (oldStart >= 0 || newStart >= 0) {
6951                int end = Selection.getSelectionEnd(buf);
6952                invalidateCursor(end, oldStart, newStart);
6953            }
6954        }
6955
6956        if (selChanged) {
6957            if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) {
6958                if (newSelStart < 0) {
6959                    newSelStart = Selection.getSelectionStart(buf);
6960                }
6961                if (newSelEnd < 0) {
6962                    newSelEnd = Selection.getSelectionEnd(buf);
6963                }
6964                onSelectionChanged(newSelStart, newSelEnd);
6965            }
6966        }
6967
6968        if (what instanceof UpdateAppearance ||
6969            what instanceof ParagraphStyle) {
6970            if (ims == null || ims.mBatchEditNesting == 0) {
6971                invalidate();
6972                mHighlightPathBogus = true;
6973                checkForResize();
6974            } else {
6975                ims.mContentChanged = true;
6976            }
6977        }
6978
6979        if (MetaKeyKeyListener.isMetaTracker(buf, what)) {
6980            mHighlightPathBogus = true;
6981            if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) {
6982                ims.mSelectionModeChanged = true;
6983            }
6984
6985            if (Selection.getSelectionStart(buf) >= 0) {
6986                if (ims == null || ims.mBatchEditNesting == 0) {
6987                    invalidateCursor();
6988                } else {
6989                    ims.mCursorChanged = true;
6990                }
6991            }
6992        }
6993
6994        if (what instanceof ParcelableSpan) {
6995            // If this is a span that can be sent to a remote process,
6996            // the current extract editor would be interested in it.
6997            if (ims != null && ims.mExtracting != null) {
6998                if (ims.mBatchEditNesting != 0) {
6999                    if (oldStart >= 0) {
7000                        if (ims.mChangedStart > oldStart) {
7001                            ims.mChangedStart = oldStart;
7002                        }
7003                        if (ims.mChangedStart > oldEnd) {
7004                            ims.mChangedStart = oldEnd;
7005                        }
7006                    }
7007                    if (newStart >= 0) {
7008                        if (ims.mChangedStart > newStart) {
7009                            ims.mChangedStart = newStart;
7010                        }
7011                        if (ims.mChangedStart > newEnd) {
7012                            ims.mChangedStart = newEnd;
7013                        }
7014                    }
7015                } else {
7016                    if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: "
7017                            + oldStart + "-" + oldEnd + ","
7018                            + newStart + "-" + newEnd + what);
7019                    ims.mContentChanged = true;
7020                }
7021            }
7022        }
7023    }
7024
7025    private class ChangeWatcher
7026    implements TextWatcher, SpanWatcher {
7027
7028        private CharSequence mBeforeText;
7029
7030        public void beforeTextChanged(CharSequence buffer, int start,
7031                                      int before, int after) {
7032            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start
7033                    + " before=" + before + " after=" + after + ": " + buffer);
7034
7035            if (AccessibilityManager.getInstance(mContext).isEnabled()
7036                    && !isPasswordInputType(mInputType)
7037                    && !hasPasswordTransformationMethod()) {
7038                mBeforeText = buffer.toString();
7039            }
7040
7041            TextView.this.sendBeforeTextChanged(buffer, start, before, after);
7042        }
7043
7044        public void onTextChanged(CharSequence buffer, int start,
7045                                  int before, int after) {
7046            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start
7047                    + " before=" + before + " after=" + after + ": " + buffer);
7048            TextView.this.handleTextChanged(buffer, start, before, after);
7049
7050            if (AccessibilityManager.getInstance(mContext).isEnabled() &&
7051                    (isFocused() || isSelected() &&
7052                    isShown())) {
7053                sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after);
7054                mBeforeText = null;
7055            }
7056        }
7057
7058        public void afterTextChanged(Editable buffer) {
7059            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer);
7060            TextView.this.sendAfterTextChanged(buffer);
7061
7062            if (MetaKeyKeyListener.getMetaState(buffer,
7063                                 MetaKeyKeyListener.META_SELECTING) != 0) {
7064                MetaKeyKeyListener.stopSelecting(TextView.this, buffer);
7065            }
7066        }
7067
7068        public void onSpanChanged(Spannable buf,
7069                                  Object what, int s, int e, int st, int en) {
7070            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e
7071                    + " st=" + st + " en=" + en + " what=" + what + ": " + buf);
7072            TextView.this.spanChange(buf, what, s, st, e, en);
7073        }
7074
7075        public void onSpanAdded(Spannable buf, Object what, int s, int e) {
7076            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e
7077                    + " what=" + what + ": " + buf);
7078            TextView.this.spanChange(buf, what, -1, s, -1, e);
7079        }
7080
7081        public void onSpanRemoved(Spannable buf, Object what, int s, int e) {
7082            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e
7083                    + " what=" + what + ": " + buf);
7084            TextView.this.spanChange(buf, what, s, -1, e, -1);
7085        }
7086    }
7087
7088    /**
7089     * @hide
7090     */
7091    @Override
7092    public void dispatchFinishTemporaryDetach() {
7093        mDispatchTemporaryDetach = true;
7094        super.dispatchFinishTemporaryDetach();
7095        mDispatchTemporaryDetach = false;
7096    }
7097
7098    @Override
7099    public void onStartTemporaryDetach() {
7100        super.onStartTemporaryDetach();
7101        // Only track when onStartTemporaryDetach() is called directly,
7102        // usually because this instance is an editable field in a list
7103        if (!mDispatchTemporaryDetach) mTemporaryDetach = true;
7104
7105        // Because of View recycling in ListView, there is no easy way to know when a TextView with
7106        // selection becomes visible again. Until a better solution is found, stop text selection
7107        // mode (if any) as soon as this TextView is recycled.
7108        stopSelectionActionMode();
7109    }
7110
7111    @Override
7112    public void onFinishTemporaryDetach() {
7113        super.onFinishTemporaryDetach();
7114        // Only track when onStartTemporaryDetach() is called directly,
7115        // usually because this instance is an editable field in a list
7116        if (!mDispatchTemporaryDetach) mTemporaryDetach = false;
7117    }
7118
7119    @Override
7120    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
7121        if (mTemporaryDetach) {
7122            // If we are temporarily in the detach state, then do nothing.
7123            super.onFocusChanged(focused, direction, previouslyFocusedRect);
7124            return;
7125        }
7126
7127        mShowCursor = SystemClock.uptimeMillis();
7128
7129        ensureEndedBatchEdit();
7130
7131        if (focused) {
7132            int selStart = getSelectionStart();
7133            int selEnd = getSelectionEnd();
7134
7135            // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection
7136            // mode for these, unless there was a specific selection already started.
7137            final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 &&
7138                    selEnd == mText.length();
7139            mCreatedWithASelection = mFrozenWithFocus && hasSelection() && !isFocusHighlighted;
7140
7141            if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
7142                // If a tap was used to give focus to that view, move cursor at tap position.
7143                // Has to be done before onTakeFocus, which can be overloaded.
7144                final int lastTapPosition = getLastTapPosition();
7145                if (lastTapPosition >= 0) {
7146                    Selection.setSelection((Spannable) mText, lastTapPosition);
7147                }
7148
7149                if (mMovement != null) {
7150                    mMovement.onTakeFocus(this, (Spannable) mText, direction);
7151                }
7152
7153                // The DecorView does not have focus when the 'Done' ExtractEditText button is
7154                // pressed. Since it is the ViewAncestor's mView, it requests focus before
7155                // ExtractEditText clears focus, which gives focus to the ExtractEditText.
7156                // This special case ensure that we keep current selection in that case.
7157                // It would be better to know why the DecorView does not have focus at that time.
7158                if (((this instanceof ExtractEditText) || mSelectionMoved) &&
7159                        selStart >= 0 && selEnd >= 0) {
7160                    /*
7161                     * Someone intentionally set the selection, so let them
7162                     * do whatever it is that they wanted to do instead of
7163                     * the default on-focus behavior.  We reset the selection
7164                     * here instead of just skipping the onTakeFocus() call
7165                     * because some movement methods do something other than
7166                     * just setting the selection in theirs and we still
7167                     * need to go through that path.
7168                     */
7169                    Selection.setSelection((Spannable) mText, selStart, selEnd);
7170                }
7171
7172                if (mSelectAllOnFocus) {
7173                    selectAll();
7174                }
7175
7176                mTouchFocusSelected = true;
7177            }
7178
7179            mFrozenWithFocus = false;
7180            mSelectionMoved = false;
7181
7182            if (mText instanceof Spannable) {
7183                Spannable sp = (Spannable) mText;
7184                MetaKeyKeyListener.resetMetaState(sp);
7185            }
7186
7187            makeBlink();
7188
7189            if (mError != null) {
7190                showError();
7191            }
7192        } else {
7193            if (mError != null) {
7194                hideError();
7195            }
7196            // Don't leave us in the middle of a batch edit.
7197            onEndBatchEdit();
7198
7199            if (this instanceof ExtractEditText) {
7200                // terminateTextSelectionMode removes selection, which we want to keep when
7201                // ExtractEditText goes out of focus.
7202                final int selStart = getSelectionStart();
7203                final int selEnd = getSelectionEnd();
7204                hideControllers();
7205                Selection.setSelection((Spannable) mText, selStart, selEnd);
7206            } else {
7207                hideControllers();
7208            }
7209
7210            // No need to create the controller
7211            if (mSelectionModifierCursorController != null) {
7212                mSelectionModifierCursorController.resetTouchOffsets();
7213            }
7214        }
7215
7216        startStopMarquee(focused);
7217
7218        if (mTransformation != null) {
7219            mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect);
7220        }
7221
7222        super.onFocusChanged(focused, direction, previouslyFocusedRect);
7223    }
7224
7225    private int getLastTapPosition() {
7226        // No need to create the controller at that point, no last tap position saved
7227        if (mSelectionModifierCursorController != null) {
7228            int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset();
7229            if (lastTapPosition >= 0) {
7230                // Safety check, should not be possible.
7231                if (lastTapPosition > mText.length()) {
7232                    Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs "
7233                            + mText.length() + ")");
7234                    lastTapPosition = mText.length();
7235                }
7236                return lastTapPosition;
7237            }
7238        }
7239
7240        return -1;
7241    }
7242
7243    @Override
7244    public void onWindowFocusChanged(boolean hasWindowFocus) {
7245        super.onWindowFocusChanged(hasWindowFocus);
7246
7247        if (hasWindowFocus) {
7248            if (mBlink != null) {
7249                mBlink.uncancel();
7250                makeBlink();
7251            }
7252        } else {
7253            if (mBlink != null) {
7254                mBlink.cancel();
7255            }
7256            // Don't leave us in the middle of a batch edit.
7257            onEndBatchEdit();
7258            if (mInputContentType != null) {
7259                mInputContentType.enterDown = false;
7260            }
7261            hideControllers();
7262            removeAllSuggestionSpans();
7263        }
7264
7265        startStopMarquee(hasWindowFocus);
7266    }
7267
7268    private void removeAllSuggestionSpans() {
7269        if (mText instanceof Editable) {
7270            Editable editable = ((Editable) mText);
7271            SuggestionSpan[] spans = editable.getSpans(0, mText.length(), SuggestionSpan.class);
7272            final int length = spans.length;
7273            for (int i = 0; i < length; i++) {
7274                editable.removeSpan(spans[i]);
7275            }
7276        }
7277    }
7278
7279    @Override
7280    protected void onVisibilityChanged(View changedView, int visibility) {
7281        super.onVisibilityChanged(changedView, visibility);
7282        if (visibility != VISIBLE) {
7283            hideControllers();
7284        }
7285    }
7286
7287    /**
7288     * Use {@link BaseInputConnection#removeComposingSpans
7289     * BaseInputConnection.removeComposingSpans()} to remove any IME composing
7290     * state from this text view.
7291     */
7292    public void clearComposingText() {
7293        if (mText instanceof Spannable) {
7294            BaseInputConnection.removeComposingSpans((Spannable)mText);
7295        }
7296    }
7297
7298    @Override
7299    public void setSelected(boolean selected) {
7300        boolean wasSelected = isSelected();
7301
7302        super.setSelected(selected);
7303
7304        if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
7305            if (selected) {
7306                startMarquee();
7307            } else {
7308                stopMarquee();
7309            }
7310        }
7311    }
7312
7313    @Override
7314    public boolean onTouchEvent(MotionEvent event) {
7315        final int action = event.getActionMasked();
7316
7317        if (hasInsertionController()) {
7318            getInsertionController().onTouchEvent(event);
7319        }
7320        if (hasSelectionController()) {
7321            getSelectionController().onTouchEvent(event);
7322        }
7323
7324        if (action == MotionEvent.ACTION_DOWN) {
7325            mLastDownPositionX = event.getX();
7326            mLastDownPositionY = event.getY();
7327
7328            // Reset this state; it will be re-set if super.onTouchEvent
7329            // causes focus to move to the view.
7330            mTouchFocusSelected = false;
7331            mIgnoreActionUpEvent = false;
7332        }
7333
7334        final boolean superResult = super.onTouchEvent(event);
7335
7336        /*
7337         * Don't handle the release after a long press, because it will
7338         * move the selection away from whatever the menu action was
7339         * trying to affect.
7340         */
7341        if (mDiscardNextActionUp && action == MotionEvent.ACTION_UP) {
7342            mDiscardNextActionUp = false;
7343            return superResult;
7344        }
7345
7346        final boolean touchIsFinished = action == MotionEvent.ACTION_UP && !mIgnoreActionUpEvent &&
7347                isFocused();
7348
7349        if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()
7350                && mText instanceof Spannable && mLayout != null) {
7351            boolean handled = false;
7352
7353            if (mMovement != null) {
7354                handled |= mMovement.onTouchEvent(this, (Spannable) mText, event);
7355            }
7356
7357            if (mLinksClickable && mAutoLinkMask != 0 && mTextIsSelectable && touchIsFinished) {
7358                // The LinkMovementMethod which should handle taps on links has not been installed
7359                // to support text selection. We reproduce its behavior here to open links.
7360                ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(),
7361                        getSelectionEnd(), ClickableSpan.class);
7362
7363                if (links.length != 0) {
7364                    links[0].onClick(this);
7365                    handled = true;
7366                }
7367            }
7368
7369            if ((isTextEditable() || mTextIsSelectable) && touchIsFinished) {
7370                // Show the IME, except when selecting in read-only text.
7371                if (!mTextIsSelectable) {
7372                    final InputMethodManager imm = InputMethodManager.peekInstance();
7373                    handled |= imm != null && imm.showSoftInput(this, 0);
7374                }
7375
7376                boolean selectAllGotFocus = mSelectAllOnFocus && didTouchFocusSelect();
7377                if (!selectAllGotFocus && hasSelection()) {
7378                    startSelectionActionMode();
7379                } else {
7380                    stopSelectionActionMode();
7381                    hideSuggestions();
7382                    if (hasInsertionController() && !selectAllGotFocus && mText.length() > 0) {
7383                        getInsertionController().show();
7384                    }
7385                }
7386            }
7387
7388            if (handled) {
7389                return true;
7390            }
7391        }
7392
7393        return superResult;
7394    }
7395
7396    @Override
7397    public boolean onGenericMotionEvent(MotionEvent event) {
7398        if (mMovement != null && mText instanceof Spannable && mLayout != null) {
7399            try {
7400                if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) {
7401                    return true;
7402                }
7403            } catch (AbstractMethodError ex) {
7404                // onGenericMotionEvent was added to the MovementMethod interface in API 12.
7405                // Ignore its absence in case third party applications implemented the
7406                // interface directly.
7407            }
7408        }
7409        return super.onGenericMotionEvent(event);
7410    }
7411
7412    private void prepareCursorControllers() {
7413        boolean windowSupportsHandles = false;
7414
7415        ViewGroup.LayoutParams params = getRootView().getLayoutParams();
7416        if (params instanceof WindowManager.LayoutParams) {
7417            WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params;
7418            windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW
7419                    || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW;
7420        }
7421
7422        mInsertionControllerEnabled = windowSupportsHandles && isCursorVisible() && mLayout != null;
7423        mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() &&
7424                mLayout != null;
7425
7426        if (!mInsertionControllerEnabled) {
7427            hideInsertionPointCursorController();
7428            if (mInsertionPointCursorController != null) {
7429                mInsertionPointCursorController.onDetached();
7430                mInsertionPointCursorController = null;
7431            }
7432        }
7433
7434        if (!mSelectionControllerEnabled) {
7435            stopSelectionActionMode();
7436            if (mSelectionModifierCursorController != null) {
7437                mSelectionModifierCursorController.onDetached();
7438                mSelectionModifierCursorController = null;
7439            }
7440        }
7441    }
7442
7443    /**
7444     * @return True iff this TextView contains a text that can be edited, or if this is
7445     * a selectable TextView.
7446     */
7447    private boolean isTextEditable() {
7448        return mText instanceof Editable && onCheckIsTextEditor() && isEnabled();
7449    }
7450
7451    /**
7452     * Returns true, only while processing a touch gesture, if the initial
7453     * touch down event caused focus to move to the text view and as a result
7454     * its selection changed.  Only valid while processing the touch gesture
7455     * of interest.
7456     */
7457    public boolean didTouchFocusSelect() {
7458        return mTouchFocusSelected;
7459    }
7460
7461    @Override
7462    public void cancelLongPress() {
7463        super.cancelLongPress();
7464        mIgnoreActionUpEvent = true;
7465    }
7466
7467    @Override
7468    public boolean onTrackballEvent(MotionEvent event) {
7469        if (mMovement != null && mText instanceof Spannable &&
7470            mLayout != null) {
7471            if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) {
7472                return true;
7473            }
7474        }
7475
7476        return super.onTrackballEvent(event);
7477    }
7478
7479    public void setScroller(Scroller s) {
7480        mScroller = s;
7481    }
7482
7483    private static class Blink extends Handler implements Runnable {
7484        private final WeakReference<TextView> mView;
7485        private boolean mCancelled;
7486
7487        public Blink(TextView v) {
7488            mView = new WeakReference<TextView>(v);
7489        }
7490
7491        public void run() {
7492            if (mCancelled) {
7493                return;
7494            }
7495
7496            removeCallbacks(Blink.this);
7497
7498            TextView tv = mView.get();
7499
7500            if (tv != null && tv.shouldBlink()) {
7501                if (tv.mLayout != null) {
7502                    tv.invalidateCursorPath();
7503                }
7504
7505                postAtTime(this, SystemClock.uptimeMillis() + BLINK);
7506            }
7507        }
7508
7509        void cancel() {
7510            if (!mCancelled) {
7511                removeCallbacks(Blink.this);
7512                mCancelled = true;
7513            }
7514        }
7515
7516        void uncancel() {
7517            mCancelled = false;
7518        }
7519    }
7520
7521    /**
7522     * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
7523     */
7524    private boolean shouldBlink() {
7525        if (!isFocused()) return false;
7526
7527        final int start = getSelectionStart();
7528        if (start < 0) return false;
7529
7530        final int end = getSelectionEnd();
7531        if (end < 0) return false;
7532
7533        return start == end;
7534    }
7535
7536    private void makeBlink() {
7537        if (isCursorVisible()) {
7538            if (shouldBlink()) {
7539                mShowCursor = SystemClock.uptimeMillis();
7540                if (mBlink == null) mBlink = new Blink(this);
7541                mBlink.removeCallbacks(mBlink);
7542                mBlink.postAtTime(mBlink, mShowCursor + BLINK);
7543            }
7544        } else {
7545            if (mBlink != null) mBlink.removeCallbacks(mBlink);
7546        }
7547    }
7548
7549    @Override
7550    protected float getLeftFadingEdgeStrength() {
7551        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f;
7552        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
7553            if (mMarquee != null && !mMarquee.isStopped()) {
7554                final Marquee marquee = mMarquee;
7555                if (marquee.shouldDrawLeftFade()) {
7556                    return marquee.mScroll / getHorizontalFadingEdgeLength();
7557                } else {
7558                    return 0.0f;
7559                }
7560            } else if (getLineCount() == 1) {
7561                switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
7562                    case Gravity.LEFT:
7563                        return 0.0f;
7564                    case Gravity.RIGHT:
7565                        return (mLayout.getLineRight(0) - (mRight - mLeft) -
7566                                getCompoundPaddingLeft() - getCompoundPaddingRight() -
7567                                mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength();
7568                    case Gravity.CENTER_HORIZONTAL:
7569                        return 0.0f;
7570                }
7571            }
7572        }
7573        return super.getLeftFadingEdgeStrength();
7574    }
7575
7576    @Override
7577    protected float getRightFadingEdgeStrength() {
7578        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f;
7579        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
7580            if (mMarquee != null && !mMarquee.isStopped()) {
7581                final Marquee marquee = mMarquee;
7582                return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength();
7583            } else if (getLineCount() == 1) {
7584                switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
7585                    case Gravity.LEFT:
7586                        final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() -
7587                                getCompoundPaddingRight();
7588                        final float lineWidth = mLayout.getLineWidth(0);
7589                        return (lineWidth - textWidth) / getHorizontalFadingEdgeLength();
7590                    case Gravity.RIGHT:
7591                        return 0.0f;
7592                    case Gravity.CENTER_HORIZONTAL:
7593                    case Gravity.FILL_HORIZONTAL:
7594                        return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
7595                                getCompoundPaddingLeft() - getCompoundPaddingRight())) /
7596                                getHorizontalFadingEdgeLength();
7597                }
7598            }
7599        }
7600        return super.getRightFadingEdgeStrength();
7601    }
7602
7603    @Override
7604    protected int computeHorizontalScrollRange() {
7605        if (mLayout != null) {
7606            return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ?
7607                    (int) mLayout.getLineWidth(0) : mLayout.getWidth();
7608        }
7609
7610        return super.computeHorizontalScrollRange();
7611    }
7612
7613    @Override
7614    protected int computeVerticalScrollRange() {
7615        if (mLayout != null)
7616            return mLayout.getHeight();
7617
7618        return super.computeVerticalScrollRange();
7619    }
7620
7621    @Override
7622    protected int computeVerticalScrollExtent() {
7623        return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
7624    }
7625
7626    public enum BufferType {
7627        NORMAL, SPANNABLE, EDITABLE,
7628    }
7629
7630    /**
7631     * Returns the TextView_textColor attribute from the
7632     * Resources.StyledAttributes, if set, or the TextAppearance_textColor
7633     * from the TextView_textAppearance attribute, if TextView_textColor
7634     * was not set directly.
7635     */
7636    public static ColorStateList getTextColors(Context context, TypedArray attrs) {
7637        ColorStateList colors;
7638        colors = attrs.getColorStateList(com.android.internal.R.styleable.
7639                                         TextView_textColor);
7640
7641        if (colors == null) {
7642            int ap = attrs.getResourceId(com.android.internal.R.styleable.
7643                                         TextView_textAppearance, -1);
7644            if (ap != -1) {
7645                TypedArray appearance;
7646                appearance = context.obtainStyledAttributes(ap,
7647                                            com.android.internal.R.styleable.TextAppearance);
7648                colors = appearance.getColorStateList(com.android.internal.R.styleable.
7649                                                  TextAppearance_textColor);
7650                appearance.recycle();
7651            }
7652        }
7653
7654        return colors;
7655    }
7656
7657    /**
7658     * Returns the default color from the TextView_textColor attribute
7659     * from the AttributeSet, if set, or the default color from the
7660     * TextAppearance_textColor from the TextView_textAppearance attribute,
7661     * if TextView_textColor was not set directly.
7662     */
7663    public static int getTextColor(Context context,
7664                                   TypedArray attrs,
7665                                   int def) {
7666        ColorStateList colors = getTextColors(context, attrs);
7667
7668        if (colors == null) {
7669            return def;
7670        } else {
7671            return colors.getDefaultColor();
7672        }
7673    }
7674
7675    @Override
7676    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7677        final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK;
7678        if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) {
7679            switch (keyCode) {
7680            case KeyEvent.KEYCODE_A:
7681                if (canSelectText()) {
7682                    return onTextContextMenuItem(ID_SELECT_ALL);
7683                }
7684                break;
7685            case KeyEvent.KEYCODE_X:
7686                if (canCut()) {
7687                    return onTextContextMenuItem(ID_CUT);
7688                }
7689                break;
7690            case KeyEvent.KEYCODE_C:
7691                if (canCopy()) {
7692                    return onTextContextMenuItem(ID_COPY);
7693                }
7694                break;
7695            case KeyEvent.KEYCODE_V:
7696                if (canPaste()) {
7697                    return onTextContextMenuItem(ID_PASTE);
7698                }
7699                break;
7700            }
7701        }
7702        return super.onKeyShortcut(keyCode, event);
7703    }
7704
7705    /**
7706     * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the
7707     * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have
7708     * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient.
7709     */
7710    private boolean canSelectText() {
7711        return hasSelectionController() && mText.length() != 0;
7712    }
7713
7714    /**
7715     * Test based on the <i>intrinsic</i> charateristics of the TextView.
7716     * The text must be spannable and the movement method must allow for arbitary selection.
7717     *
7718     * See also {@link #canSelectText()}.
7719     */
7720    private boolean textCanBeSelected() {
7721        // prepareCursorController() relies on this method.
7722        // If you change this condition, make sure prepareCursorController is called anywhere
7723        // the value of this condition might be changed.
7724        return mText instanceof Spannable && mMovement != null && mMovement.canSelectArbitrarily();
7725    }
7726
7727    private boolean canCut() {
7728        if (hasPasswordTransformationMethod()) {
7729            return false;
7730        }
7731
7732        if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mInput != null) {
7733            return true;
7734        }
7735
7736        return false;
7737    }
7738
7739    private boolean canCopy() {
7740        if (hasPasswordTransformationMethod()) {
7741            return false;
7742        }
7743
7744        if (mText.length() > 0 && hasSelection()) {
7745            return true;
7746        }
7747
7748        return false;
7749    }
7750
7751    private boolean canPaste() {
7752        return (mText instanceof Editable &&
7753                mInput != null &&
7754                getSelectionStart() >= 0 &&
7755                getSelectionEnd() >= 0 &&
7756                ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)).
7757                hasPrimaryClip());
7758    }
7759
7760    private static long packRangeInLong(int start, int end) {
7761        return (((long) start) << 32) | end;
7762    }
7763
7764    private static int extractRangeStartFromLong(long range) {
7765        return (int) (range >>> 32);
7766    }
7767
7768    private static int extractRangeEndFromLong(long range) {
7769        return (int) (range & 0x00000000FFFFFFFFL);
7770    }
7771
7772    private boolean selectAll() {
7773        final int length = mText.length();
7774        Selection.setSelection((Spannable) mText, 0, length);
7775        return length > 0;
7776    }
7777
7778    /**
7779     * Adjusts selection to the word under last touch offset.
7780     * Return true if the operation was successfully performed.
7781     */
7782    private boolean selectCurrentWord() {
7783        if (!canSelectText()) {
7784            return false;
7785        }
7786
7787        if (hasPasswordTransformationMethod()) {
7788            // Always select all on a password field.
7789            // Cut/copy menu entries are not available for passwords, but being able to select all
7790            // is however useful to delete or paste to replace the entire content.
7791            return selectAll();
7792        }
7793
7794        int klass = mInputType & InputType.TYPE_MASK_CLASS;
7795        int variation = mInputType & InputType.TYPE_MASK_VARIATION;
7796
7797        // Specific text field types: select the entire text for these
7798        if (klass == InputType.TYPE_CLASS_NUMBER ||
7799                klass == InputType.TYPE_CLASS_PHONE ||
7800                klass == InputType.TYPE_CLASS_DATETIME ||
7801                variation == InputType.TYPE_TEXT_VARIATION_URI ||
7802                variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
7803                variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ||
7804                variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
7805            return selectAll();
7806        }
7807
7808        long lastTouchOffsets = getLastTouchOffsets();
7809        final int minOffset = extractRangeStartFromLong(lastTouchOffsets);
7810        final int maxOffset = extractRangeEndFromLong(lastTouchOffsets);
7811
7812        int selectionStart, selectionEnd;
7813
7814        // If a URLSpan (web address, email, phone...) is found at that position, select it.
7815        URLSpan[] urlSpans = ((Spanned) mText).getSpans(minOffset, maxOffset, URLSpan.class);
7816        if (urlSpans.length == 1) {
7817            URLSpan url = urlSpans[0];
7818            selectionStart = ((Spanned) mText).getSpanStart(url);
7819            selectionEnd = ((Spanned) mText).getSpanEnd(url);
7820        } else {
7821            if (mWordIterator == null) {
7822                mWordIterator = new WordIterator();
7823            }
7824            // WordIerator handles text changes, this is a no-op if text in unchanged.
7825            mWordIterator.setCharSequence(mText);
7826
7827            selectionStart = mWordIterator.getBeginning(minOffset);
7828            if (selectionStart == BreakIterator.DONE) return false;
7829
7830            selectionEnd = mWordIterator.getEnd(maxOffset);
7831            if (selectionEnd == BreakIterator.DONE) return false;
7832        }
7833
7834        Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
7835        return true;
7836    }
7837
7838    private long getLastTouchOffsets() {
7839        int minOffset, maxOffset;
7840
7841        if (mContextMenuTriggeredByKey) {
7842            minOffset = getSelectionStart();
7843            maxOffset = getSelectionEnd();
7844        } else {
7845            SelectionModifierCursorController selectionController = getSelectionController();
7846            minOffset = selectionController.getMinTouchOffset();
7847            maxOffset = selectionController.getMaxTouchOffset();
7848        }
7849
7850        return packRangeInLong(minOffset, maxOffset);
7851    }
7852
7853    @Override
7854    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7855        super.onPopulateAccessibilityEvent(event);
7856
7857        final boolean isPassword = hasPasswordTransformationMethod();
7858        if (!isPassword) {
7859            CharSequence text = getText();
7860            if (TextUtils.isEmpty(text)) {
7861                text = getHint();
7862            }
7863            if (!TextUtils.isEmpty(text)) {
7864                event.getText().add(text);
7865            }
7866        }
7867    }
7868
7869    @Override
7870    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7871        super.onInitializeAccessibilityEvent(event);
7872
7873        final boolean isPassword = hasPasswordTransformationMethod();
7874        event.setPassword(isPassword);
7875    }
7876
7877    void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText,
7878            int fromIndex, int removedCount, int addedCount) {
7879        AccessibilityEvent event =
7880            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
7881        event.setFromIndex(fromIndex);
7882        event.setRemovedCount(removedCount);
7883        event.setAddedCount(addedCount);
7884        event.setBeforeText(beforeText);
7885        sendAccessibilityEventUnchecked(event);
7886    }
7887
7888    @Override
7889    protected void onCreateContextMenu(ContextMenu menu) {
7890        super.onCreateContextMenu(menu);
7891        boolean added = false;
7892        mContextMenuTriggeredByKey = mDPadCenterIsDown || mEnterKeyIsDown;
7893        // Problem with context menu on long press: the menu appears while the key in down and when
7894        // the key is released, the view does not receive the key_up event.
7895        // We need two layers of flags: mDPadCenterIsDown and mEnterKeyIsDown are set in key down/up
7896        // events. We cannot simply clear these flags in onTextContextMenuItem since
7897        // it may not be called (if the user/ discards the context menu with the back key).
7898        // We clear these flags here and mContextMenuTriggeredByKey saves that state so that it is
7899        // available in onTextContextMenuItem.
7900        mDPadCenterIsDown = mEnterKeyIsDown = false;
7901
7902        MenuHandler handler = new MenuHandler();
7903
7904        if (mText instanceof Spanned && hasSelectionController()) {
7905            long lastTouchOffset = getLastTouchOffsets();
7906            final int selStart = extractRangeStartFromLong(lastTouchOffset);
7907            final int selEnd = extractRangeEndFromLong(lastTouchOffset);
7908
7909            URLSpan[] urls = ((Spanned) mText).getSpans(selStart, selEnd, URLSpan.class);
7910            if (urls.length > 0) {
7911                menu.add(0, ID_COPY_URL, 0, com.android.internal.R.string.copyUrl).
7912                        setOnMenuItemClickListener(handler);
7913
7914                added = true;
7915            }
7916        }
7917
7918        // The context menu is not empty, which will prevent the selection mode from starting.
7919        // Add a entry to start it in the context menu.
7920        // TODO Does not handle the case where a subclass does not call super.thisMethod or
7921        // populates the menu AFTER this call.
7922        if (menu.size() > 0) {
7923            menu.add(0, ID_SELECTION_MODE, 0, com.android.internal.R.string.selectTextMode).
7924                    setOnMenuItemClickListener(handler);
7925            added = true;
7926        }
7927
7928        if (added) {
7929            menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle);
7930        }
7931    }
7932
7933    /**
7934     * Returns whether this text view is a current input method target.  The
7935     * default implementation just checks with {@link InputMethodManager}.
7936     */
7937    public boolean isInputMethodTarget() {
7938        InputMethodManager imm = InputMethodManager.peekInstance();
7939        return imm != null && imm.isActive(this);
7940    }
7941
7942    // Selection context mode
7943    private static final int ID_SELECT_ALL = android.R.id.selectAll;
7944    private static final int ID_CUT = android.R.id.cut;
7945    private static final int ID_COPY = android.R.id.copy;
7946    private static final int ID_PASTE = android.R.id.paste;
7947    // Context menu entries
7948    private static final int ID_COPY_URL = android.R.id.copyUrl;
7949    private static final int ID_SELECTION_MODE = android.R.id.selectTextMode;
7950
7951    private class MenuHandler implements MenuItem.OnMenuItemClickListener {
7952        public boolean onMenuItemClick(MenuItem item) {
7953            return onTextContextMenuItem(item.getItemId());
7954        }
7955    }
7956
7957    /**
7958     * Called when a context menu option for the text view is selected.  Currently
7959     * this will be {@link android.R.id#copyUrl}, {@link android.R.id#selectTextMode},
7960     * {@link android.R.id#selectAll}, {@link android.R.id#paste}, {@link android.R.id#cut}
7961     * or {@link android.R.id#copy}.
7962     *
7963     * @return true if the context menu item action was performed.
7964     */
7965    public boolean onTextContextMenuItem(int id) {
7966        int min = 0;
7967        int max = mText.length();
7968
7969        if (isFocused()) {
7970            final int selStart = getSelectionStart();
7971            final int selEnd = getSelectionEnd();
7972
7973            min = Math.max(0, Math.min(selStart, selEnd));
7974            max = Math.max(0, Math.max(selStart, selEnd));
7975        }
7976
7977        switch (id) {
7978            case ID_COPY_URL:
7979                URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class);
7980                if (urls.length >= 1) {
7981                    ClipData clip = null;
7982                    for (int i=0; i<urls.length; i++) {
7983                        Uri uri = Uri.parse(urls[0].getURL());
7984                        if (clip == null) {
7985                            clip = ClipData.newRawUri(null, uri);
7986                        } else {
7987                            clip.addItem(new ClipData.Item(uri));
7988                        }
7989                    }
7990                    if (clip != null) {
7991                        setPrimaryClip(clip);
7992                    }
7993                }
7994                stopSelectionActionMode();
7995                return true;
7996
7997            case ID_SELECTION_MODE:
7998                if (mSelectionActionMode != null) {
7999                    // Selection mode is already started, simply change selected part.
8000                    selectCurrentWord();
8001                } else {
8002                    startSelectionActionMode();
8003                }
8004                return true;
8005
8006            case ID_SELECT_ALL:
8007                // This does not enter text selection mode. Text is highlighted, so that it can be
8008                // bulk edited, like selectAllOnFocus does. Returns true even if text is empty.
8009                selectAll();
8010                return true;
8011
8012            case ID_PASTE:
8013                paste(min, max);
8014                return true;
8015
8016            case ID_CUT:
8017                setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max)));
8018                ((Editable) mText).delete(min, max);
8019                stopSelectionActionMode();
8020                return true;
8021
8022            case ID_COPY:
8023                setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max)));
8024                stopSelectionActionMode();
8025                return true;
8026        }
8027        return false;
8028    }
8029
8030    /**
8031     * Prepare text so that there are not zero or two spaces at beginning and end of region defined
8032     * by [min, max] when replacing this region by paste.
8033     * Note that if there were two spaces (or more) at that position before, they are kept. We just
8034     * make sure we do not add an extra one from the paste content.
8035     */
8036    private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) {
8037        if (paste.length() > 0) {
8038            if (min > 0) {
8039                final char charBefore = mTransformed.charAt(min - 1);
8040                final char charAfter = paste.charAt(0);
8041
8042                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
8043                    // Two spaces at beginning of paste: remove one
8044                    final int originalLength = mText.length();
8045                    ((Editable) mText).delete(min - 1, min);
8046                    // Due to filters, there is no guarantee that exactly one character was
8047                    // removed: count instead.
8048                    final int delta = mText.length() - originalLength;
8049                    min += delta;
8050                    max += delta;
8051                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
8052                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
8053                    // No space at beginning of paste: add one
8054                    final int originalLength = mText.length();
8055                    ((Editable) mText).replace(min, min, " ");
8056                    // Taking possible filters into account as above.
8057                    final int delta = mText.length() - originalLength;
8058                    min += delta;
8059                    max += delta;
8060                }
8061            }
8062
8063            if (max < mText.length()) {
8064                final char charBefore = paste.charAt(paste.length() - 1);
8065                final char charAfter = mTransformed.charAt(max);
8066
8067                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
8068                    // Two spaces at end of paste: remove one
8069                    ((Editable) mText).delete(max, max + 1);
8070                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
8071                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
8072                    // No space at end of paste: add one
8073                    ((Editable) mText).replace(max, max, " ");
8074                }
8075            }
8076        }
8077
8078        return packRangeInLong(min, max);
8079    }
8080
8081    private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) {
8082        TextView shadowView = (TextView) inflate(mContext,
8083                com.android.internal.R.layout.text_drag_thumbnail, null);
8084
8085        if (shadowView == null) {
8086            throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
8087        }
8088
8089        if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) {
8090            text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH);
8091        }
8092        shadowView.setText(text);
8093        shadowView.setTextColor(getTextColors());
8094
8095        shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge);
8096        shadowView.setGravity(Gravity.CENTER);
8097
8098        shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
8099                ViewGroup.LayoutParams.WRAP_CONTENT));
8100
8101        final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
8102        shadowView.measure(size, size);
8103
8104        shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
8105        shadowView.invalidate();
8106        return new DragShadowBuilder(shadowView);
8107    }
8108
8109    private static class DragLocalState {
8110        public TextView sourceTextView;
8111        public int start, end;
8112
8113        public DragLocalState(TextView sourceTextView, int start, int end) {
8114            this.sourceTextView = sourceTextView;
8115            this.start = start;
8116            this.end = end;
8117        }
8118    }
8119
8120    @Override
8121    public boolean performLongClick() {
8122        if (super.performLongClick()) {
8123            mDiscardNextActionUp = true;
8124            return true;
8125        }
8126
8127        boolean handled = false;
8128
8129        // Long press in empty space moves cursor and shows the Paste affordance if available.
8130        if (!isPositionOnText(mLastDownPositionX, mLastDownPositionY) &&
8131                mInsertionControllerEnabled) {
8132            final int offset = getOffsetForPosition(mLastDownPositionX, mLastDownPositionY);
8133            stopSelectionActionMode();
8134            Selection.setSelection((Spannable) mText, offset);
8135            getInsertionController().showWithPaste();
8136            handled = true;
8137        }
8138
8139        if (!handled && mSelectionActionMode != null) {
8140            if (touchPositionIsInSelection()) {
8141                // Start a drag
8142                final int start = getSelectionStart();
8143                final int end = getSelectionEnd();
8144                CharSequence selectedText = mTransformed.subSequence(start, end);
8145                ClipData data = ClipData.newPlainText(null, selectedText);
8146                DragLocalState localState = new DragLocalState(this, start, end);
8147                startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0);
8148                stopSelectionActionMode();
8149            } else {
8150                selectCurrentWord();
8151            }
8152            handled = true;
8153        }
8154
8155        // Start a new selection
8156        handled |= !handled && startSelectionActionMode();
8157
8158        if (handled) {
8159            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
8160            mDiscardNextActionUp = true;
8161        }
8162
8163        return handled;
8164    }
8165
8166    private boolean touchPositionIsInSelection() {
8167        int selectionStart = getSelectionStart();
8168        int selectionEnd = getSelectionEnd();
8169
8170        if (selectionStart == selectionEnd) {
8171            return false;
8172        }
8173
8174        if (selectionStart > selectionEnd) {
8175            int tmp = selectionStart;
8176            selectionStart = selectionEnd;
8177            selectionEnd = tmp;
8178            Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
8179        }
8180
8181        SelectionModifierCursorController selectionController = getSelectionController();
8182        int minOffset = selectionController.getMinTouchOffset();
8183        int maxOffset = selectionController.getMaxTouchOffset();
8184
8185        return ((minOffset >= selectionStart) && (maxOffset < selectionEnd));
8186    }
8187
8188    private static class SuggestionRangeSpan extends UnderlineSpan {
8189        // TODO themable, would be nice to make it a child class of TextAppearanceSpan, but
8190        // there is no way to have underline and TextAppearanceSpan.
8191    }
8192
8193    private class SuggestionsPopupWindow implements OnClickListener {
8194        private static final int MAX_NUMBER_SUGGESTIONS = 5;
8195        private static final int NO_SUGGESTIONS = -1;
8196        private final PopupWindow mContainer;
8197        private final ViewGroup[] mSuggestionViews = new ViewGroup[2];
8198        private final int[] mSuggestionViewLayouts = new int[] {
8199                mTextEditSuggestionsBottomWindowLayout, mTextEditSuggestionsTopWindowLayout};
8200        private WordIterator mSuggestionWordIterator;
8201        private TextAppearanceSpan[] mHighlightSpans = new TextAppearanceSpan[0];
8202
8203        public SuggestionsPopupWindow() {
8204            mContainer = new PopupWindow(TextView.this.mContext, null,
8205                    com.android.internal.R.attr.textSuggestionsWindowStyle);
8206            mContainer.setSplitTouchEnabled(true);
8207            mContainer.setClippingEnabled(false);
8208            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
8209
8210            mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
8211            mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
8212        }
8213
8214        private class SuggestionInfo {
8215            int suggestionStart, suggestionEnd; // range of suggestion item with replacement text
8216            int spanStart, spanEnd; // range in TextView where text should be inserted
8217            SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents
8218            int suggestionIndex; // the index of the suggestion inside suggestionSpan
8219        }
8220
8221        private ViewGroup getViewGroup(boolean under) {
8222            final int viewIndex = under ? 0 : 1;
8223            ViewGroup viewGroup = mSuggestionViews[viewIndex];
8224
8225            if (viewGroup == null) {
8226                final int layout = mSuggestionViewLayouts[viewIndex];
8227                LayoutInflater inflater = (LayoutInflater) TextView.this.mContext.
8228                        getSystemService(Context.LAYOUT_INFLATER_SERVICE);
8229
8230                if (inflater == null) {
8231                    throw new IllegalArgumentException(
8232                            "Unable to create TextEdit suggestion window inflater");
8233                }
8234
8235                View view = inflater.inflate(layout, null);
8236
8237                if (! (view instanceof ViewGroup)) {
8238                    throw new IllegalArgumentException(
8239                            "Inflated TextEdit suggestion window is not a ViewGroup: " + view);
8240                }
8241
8242                viewGroup = (ViewGroup) view;
8243
8244                // Inflate the suggestion items once and for all.
8245                for (int i = 0; i < MAX_NUMBER_SUGGESTIONS; i++) {
8246                    View childView = inflater.inflate(mTextEditSuggestionItemLayout, viewGroup,
8247                            false);
8248
8249                    if (! (childView instanceof TextView)) {
8250                        throw new IllegalArgumentException(
8251                               "Inflated TextEdit suggestion item is not a TextView: " + childView);
8252                    }
8253
8254                    childView.setTag(new SuggestionInfo());
8255                    viewGroup.addView(childView);
8256                    childView.setOnClickListener(this);
8257                }
8258
8259                mSuggestionViews[viewIndex] = viewGroup;
8260            }
8261
8262            return viewGroup;
8263        }
8264
8265        public void show() {
8266            if (!(mText instanceof Editable)) return;
8267
8268            final int pos = TextView.this.getSelectionStart();
8269            Spannable spannable = (Spannable)TextView.this.mText;
8270            SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class);
8271            final int nbSpans = suggestionSpans.length;
8272
8273            ViewGroup viewGroup = getViewGroup(true);
8274            mContainer.setContentView(viewGroup);
8275
8276            int totalNbSuggestions = 0;
8277            int spanUnionStart = mText.length();
8278            int spanUnionEnd = 0;
8279
8280            for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) {
8281                SuggestionSpan suggestionSpan = suggestionSpans[spanIndex];
8282                final int spanStart = spannable.getSpanStart(suggestionSpan);
8283                final int spanEnd = spannable.getSpanEnd(suggestionSpan);
8284                spanUnionStart = Math.min(spanStart, spanUnionStart);
8285                spanUnionEnd = Math.max(spanEnd, spanUnionEnd);
8286
8287                String[] suggestions = suggestionSpan.getSuggestions();
8288                int nbSuggestions = suggestions.length;
8289                for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) {
8290                    TextView textView = (TextView) viewGroup.getChildAt(totalNbSuggestions);
8291                    textView.setText(suggestions[suggestionIndex]);
8292                    SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag();
8293                    suggestionInfo.spanStart = spanStart;
8294                    suggestionInfo.spanEnd = spanEnd;
8295                    suggestionInfo.suggestionSpan = suggestionSpan;
8296                    suggestionInfo.suggestionIndex = suggestionIndex;
8297
8298                    totalNbSuggestions++;
8299                    if (totalNbSuggestions == MAX_NUMBER_SUGGESTIONS) {
8300                        // Also end outer for loop
8301                        spanIndex = nbSpans;
8302                        break;
8303                    }
8304                }
8305            }
8306
8307            if (totalNbSuggestions == 0) {
8308                // TODO Replace by final text, use a dedicated layout, add a fade out timer...
8309                TextView textView = (TextView) viewGroup.getChildAt(0);
8310                textView.setText("No suggestions available");
8311                SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag();
8312                suggestionInfo.spanStart = NO_SUGGESTIONS;
8313                totalNbSuggestions++;
8314            } else {
8315                if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan();
8316                ((Editable) mText).setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd,
8317                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
8318
8319                for (int i = 0; i < totalNbSuggestions; i++) {
8320                    final TextView textView = (TextView) viewGroup.getChildAt(i);
8321                    highlightTextDifferences(textView, spanUnionStart, spanUnionEnd);
8322                }
8323            }
8324
8325            for (int i = 0; i < MAX_NUMBER_SUGGESTIONS; i++) {
8326                viewGroup.getChildAt(i).setVisibility(i < totalNbSuggestions ? VISIBLE : GONE);
8327            }
8328
8329            final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
8330            viewGroup.measure(size, size);
8331
8332            positionAtCursor();
8333        }
8334
8335        private long[] getWordLimits(CharSequence text) {
8336            // TODO locale for mSuggestionWordIterator
8337            if (mSuggestionWordIterator == null) mSuggestionWordIterator = new WordIterator();
8338            mSuggestionWordIterator.setCharSequence(text);
8339
8340            // First pass will simply count the number of words to be able to create an array
8341            // Not too expensive since previous break positions are cached by the BreakIterator
8342            int nbWords = 0;
8343            int position = mSuggestionWordIterator.following(0);
8344            while (position != BreakIterator.DONE) {
8345                nbWords++;
8346                position = mSuggestionWordIterator.following(position);
8347            }
8348
8349            int index = 0;
8350            long[] result = new long[nbWords];
8351
8352            position = mSuggestionWordIterator.following(0);
8353            while (position != BreakIterator.DONE) {
8354                int wordStart = mSuggestionWordIterator.getBeginning(position);
8355                result[index++] = packRangeInLong(wordStart, position);
8356                position = mSuggestionWordIterator.following(position);
8357            }
8358
8359            return result;
8360        }
8361
8362        private TextAppearanceSpan highlightSpan(int index) {
8363            final int length = mHighlightSpans.length;
8364            if (index < length) {
8365                return mHighlightSpans[index];
8366            }
8367
8368            // Assumes indexes are requested in sequence: simply append one more item
8369            TextAppearanceSpan[] newArray = new TextAppearanceSpan[length + 1];
8370            System.arraycopy(mHighlightSpans, 0, newArray, 0, length);
8371            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mContext,
8372                    android.R.style.TextAppearance_SuggestionHighlight);
8373            newArray[length] = highlightSpan;
8374            mHighlightSpans = newArray;
8375            return highlightSpan;
8376        }
8377
8378        private void highlightTextDifferences(TextView textView, int unionStart, int unionEnd) {
8379            SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag();
8380            final int spanStart = suggestionInfo.spanStart;
8381            final int spanEnd = suggestionInfo.spanEnd;
8382
8383            // Remove all text formating by converting to Strings
8384            final String text = textView.getText().toString();
8385            final String sourceText = mText.subSequence(spanStart, spanEnd).toString();
8386
8387            long[] sourceWordLimits = getWordLimits(sourceText);
8388            long[] wordLimits = getWordLimits(text);
8389
8390            SpannableStringBuilder ssb = new SpannableStringBuilder();
8391            // span [spanStart, spanEnd] is included in union [spanUnionStart, int spanUnionEnd]
8392            // The final result is made of 3 parts: the text before, between and after the span
8393            // This is the text before, provided for context
8394            ssb.append(mText.subSequence(unionStart, spanStart).toString());
8395
8396            // shift is used to offset spans positions wrt span's beginning
8397            final int shift = spanStart - unionStart;
8398            suggestionInfo.suggestionStart = shift;
8399            suggestionInfo.suggestionEnd = shift + text.length();
8400
8401            // This is the actual suggestion text, which will be highlighted by the following code
8402            ssb.append(text);
8403
8404            String[] words = new String[wordLimits.length];
8405            for (int i = 0; i < wordLimits.length; i++) {
8406                int wordStart = extractRangeStartFromLong(wordLimits[i]);
8407                int wordEnd = extractRangeEndFromLong(wordLimits[i]);
8408                words[i] = text.substring(wordStart, wordEnd);
8409            }
8410
8411            // Highlighted word algorithm is based on word matching between source and text
8412            // Matching words are found from left to right. TODO: change for RTL languages
8413            // Characters between matching words are highlighted
8414            int previousCommonWordIndex = -1;
8415            int nbHighlightSpans = 0;
8416            for (int i = 0; i < sourceWordLimits.length; i++) {
8417                int wordStart = extractRangeStartFromLong(sourceWordLimits[i]);
8418                int wordEnd = extractRangeEndFromLong(sourceWordLimits[i]);
8419                String sourceWord = sourceText.substring(wordStart, wordEnd);
8420
8421                for (int j = previousCommonWordIndex + 1; j < words.length; j++) {
8422                    if (sourceWord.equals(words[j])) {
8423                        if (j != previousCommonWordIndex + 1) {
8424                            int firstDifferentPosition = previousCommonWordIndex < 0 ? 0 :
8425                                extractRangeEndFromLong(wordLimits[previousCommonWordIndex]);
8426                            int lastDifferentPosition = extractRangeStartFromLong(wordLimits[j]);
8427                            ssb.setSpan(highlightSpan(nbHighlightSpans++),
8428                                    shift + firstDifferentPosition, shift + lastDifferentPosition,
8429                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
8430                        } else {
8431                            // Compare characters between words
8432                            int previousSourceWordEnd = i == 0 ? 0 :
8433                                extractRangeEndFromLong(sourceWordLimits[i - 1]);
8434                            int sourceWordStart = extractRangeStartFromLong(sourceWordLimits[i]);
8435                            String sourceSpaces = sourceText.substring(previousSourceWordEnd,
8436                                    sourceWordStart);
8437
8438                            int previousWordEnd = j == 0 ? 0 :
8439                                extractRangeEndFromLong(wordLimits[j - 1]);
8440                            int currentWordStart = extractRangeStartFromLong(wordLimits[j]);
8441                            String textSpaces = text.substring(previousWordEnd, currentWordStart);
8442
8443                            if (!sourceSpaces.equals(textSpaces)) {
8444                                ssb.setSpan(highlightSpan(nbHighlightSpans++),
8445                                        shift + previousWordEnd, shift + currentWordStart,
8446                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
8447                            }
8448                        }
8449                        previousCommonWordIndex = j;
8450                        break;
8451                    }
8452                }
8453            }
8454
8455            // Finally, compare ends of Strings
8456            if (previousCommonWordIndex < words.length - 1) {
8457                int firstDifferentPosition = previousCommonWordIndex < 0 ? 0 :
8458                    extractRangeEndFromLong(wordLimits[previousCommonWordIndex]);
8459                int lastDifferentPosition = textView.length();
8460                ssb.setSpan(highlightSpan(nbHighlightSpans++),
8461                        shift + firstDifferentPosition, shift + lastDifferentPosition,
8462                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
8463            } else {
8464                int lastSourceWordEnd = sourceWordLimits.length == 0 ? 0 :
8465                    extractRangeEndFromLong(sourceWordLimits[sourceWordLimits.length - 1]);
8466                String sourceSpaces = sourceText.substring(lastSourceWordEnd, sourceText.length());
8467
8468                int lastCommonTextWordEnd = previousCommonWordIndex < 0 ? 0 :
8469                    extractRangeEndFromLong(wordLimits[previousCommonWordIndex]);
8470                String textSpaces = text.substring(lastCommonTextWordEnd, textView.length());
8471
8472                if (!sourceSpaces.equals(textSpaces) && textSpaces.length() > 0) {
8473                    ssb.setSpan(highlightSpan(nbHighlightSpans++),
8474                            shift + lastCommonTextWordEnd, shift + textView.length(),
8475                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
8476                }
8477            }
8478
8479            // Final part, text after the current suggestion range.
8480            ssb.append(mText.subSequence(spanEnd, unionEnd).toString());
8481            textView.setText(ssb);
8482        }
8483
8484        public void hide() {
8485            if ((mText instanceof Editable) && mSuggestionRangeSpan != null) {
8486                ((Editable) mText).removeSpan(mSuggestionRangeSpan);
8487            }
8488            mContainer.dismiss();
8489        }
8490
8491        @Override
8492        public void onClick(View view) {
8493            if (view instanceof TextView) {
8494                TextView textView = (TextView) view;
8495                SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag();
8496                final int spanStart = suggestionInfo.spanStart;
8497                final int spanEnd = suggestionInfo.spanEnd;
8498                if (spanStart != NO_SUGGESTIONS) {
8499                    // SuggestionSpans are removed by replace: save them before
8500                    Editable editable = ((Editable) mText);
8501                    SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd,
8502                            SuggestionSpan.class);
8503                    final int length = suggestionSpans.length;
8504                    int[] suggestionSpansStarts = new int[length];
8505                    int[] suggestionSpansEnds = new int[length];
8506                    int[] suggestionSpansFlags = new int[length];
8507                    for (int i = 0; i < length; i++) {
8508                        final SuggestionSpan suggestionSpan = suggestionSpans[i];
8509                        suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan);
8510                        suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan);
8511                        suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan);
8512                    }
8513
8514                    final int suggestionStart = suggestionInfo.suggestionStart;
8515                    final int suggestionEnd = suggestionInfo.suggestionEnd;
8516                    final String suggestion = textView.getText().subSequence(
8517                            suggestionStart, suggestionEnd).toString();
8518                    final String originalText = mText.subSequence(spanStart, spanEnd).toString();
8519                    ((Editable) mText).replace(spanStart, spanEnd, suggestion);
8520
8521                    // Swap text content between actual text and Suggestion span
8522                    String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions();
8523                    suggestions[suggestionInfo.suggestionIndex] = originalText;
8524
8525                    // Restore previous SuggestionSpans
8526                    final int lengthDifference = suggestion.length() - (spanEnd - spanStart);
8527                    for (int i = 0; i < length; i++) {
8528                        // Only spans that include the modified region make sense after replacement
8529                        // Spans partially included in the replaced region are removed, there is no
8530                        // way to assign them a valid range after replacement
8531                        if (suggestionSpansStarts[i] <= spanStart &&
8532                                suggestionSpansEnds[i] >= spanEnd) {
8533                            editable.setSpan(suggestionSpans[i], suggestionSpansStarts[i],
8534                                    suggestionSpansEnds[i] + lengthDifference,
8535                                    suggestionSpansFlags[i]);
8536                        }
8537                    }
8538                }
8539            }
8540            hide();
8541        }
8542
8543        void positionAtCursor() {
8544            View contentView = mContainer.getContentView();
8545            int width = contentView.getMeasuredWidth();
8546            int height = contentView.getMeasuredHeight();
8547            final int offset = TextView.this.getSelectionStart();
8548            final int line = mLayout.getLineForOffset(offset);
8549            final int lineBottom = mLayout.getLineBottom(line);
8550            float primaryHorizontal = mLayout.getPrimaryHorizontal(offset);
8551
8552            final Rect bounds = sCursorControllerTempRect;
8553            bounds.left = (int) (primaryHorizontal - width / 2.0f);
8554            bounds.top = lineBottom;
8555
8556            bounds.right = bounds.left + width;
8557            bounds.bottom = bounds.top + height;
8558
8559            convertFromViewportToContentCoordinates(bounds);
8560
8561            final int[] coords = mTempCoords;
8562            TextView.this.getLocationInWindow(coords);
8563            coords[0] += bounds.left;
8564            coords[1] += bounds.top;
8565
8566            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
8567            final int screenHeight = displayMetrics.heightPixels;
8568
8569            // Vertical clipping
8570            if (coords[1] + height > screenHeight) {
8571                // Try to position above current line instead
8572                // TODO use top layout instead, reverse suggestion order,
8573                // try full screen vertical down if it still does not fit. TBD with designers.
8574
8575                // Update dimensions from new view
8576                contentView = mContainer.getContentView();
8577                width = contentView.getMeasuredWidth();
8578                height = contentView.getMeasuredHeight();
8579
8580                final int lineTop = mLayout.getLineTop(line);
8581                final int lineHeight = lineBottom - lineTop;
8582                coords[1] -= height + lineHeight;
8583            }
8584
8585            // Horizontal clipping
8586            coords[0] = Math.max(0, coords[0]);
8587            coords[0] = Math.min(displayMetrics.widthPixels - width, coords[0]);
8588
8589            mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]);
8590        }
8591    }
8592
8593    void showSuggestions() {
8594        if (mSuggestionsPopupWindow == null) {
8595            mSuggestionsPopupWindow = new SuggestionsPopupWindow();
8596        }
8597        hideControllers();
8598        mSuggestionsPopupWindow.show();
8599    }
8600
8601    void hideSuggestions() {
8602        if (mSuggestionsPopupWindow != null) {
8603            mSuggestionsPopupWindow.hide();
8604        }
8605    }
8606
8607    /**
8608     * If provided, this ActionMode.Callback will be used to create the ActionMode when text
8609     * selection is initiated in this View.
8610     *
8611     * The standard implementation populates the menu with a subset of Select All, Cut, Copy and
8612     * Paste actions, depending on what this View supports.
8613     *
8614     * A custom implementation can add new entries in the default menu in its
8615     * {@link ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The default actions
8616     * can also be removed from the menu using {@link Menu#removeItem(int)} and passing
8617     * {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} or
8618     * {@link android.R.id#paste} ids as parameters.
8619     *
8620     * Returning false from {@link ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will
8621     * prevent the action mode from being started.
8622     *
8623     * Action click events should be handled by the custom implementation of
8624     * {@link ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}.
8625     *
8626     * Note that text selection mode is not started when a TextView receives focus and the
8627     * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in
8628     * that case, to allow for quick replacement.
8629     */
8630    public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) {
8631        mCustomSelectionActionModeCallback = actionModeCallback;
8632    }
8633
8634    /**
8635     * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null.
8636     *
8637     * @return The current custom selection callback.
8638     */
8639    public ActionMode.Callback getCustomSelectionActionModeCallback() {
8640        return mCustomSelectionActionModeCallback;
8641    }
8642
8643    /**
8644     *
8645     * @return true if the selection mode was actually started.
8646     */
8647    private boolean startSelectionActionMode() {
8648        if (mSelectionActionMode != null) {
8649            // Selection action mode is already started
8650            return false;
8651        }
8652
8653        if (!canSelectText() || !requestFocus()) {
8654            Log.w(LOG_TAG, "TextView does not support text selection. Action mode cancelled.");
8655            return false;
8656        }
8657
8658        boolean currentWordSelected = selectCurrentWord();
8659        if (!currentWordSelected) {
8660            // No word found under cursor or text selection not permitted.
8661            return false;
8662        }
8663
8664        ActionMode.Callback actionModeCallback = new SelectionActionModeCallback();
8665        mSelectionActionMode = startActionMode(actionModeCallback);
8666        final boolean selectionStarted = mSelectionActionMode != null;
8667
8668        if (selectionStarted && !mTextIsSelectable) {
8669            // Show the IME to be able to replace text, except when selecting non editable text.
8670            final InputMethodManager imm = InputMethodManager.peekInstance();
8671            if (imm != null) imm.showSoftInput(this, 0, null);
8672        }
8673
8674        return selectionStarted;
8675    }
8676
8677    private void stopSelectionActionMode() {
8678        if (mSelectionActionMode != null) {
8679            // This will hide the mSelectionModifierCursorController
8680            mSelectionActionMode.finish();
8681        }
8682    }
8683
8684    /**
8685     * Paste clipboard content between min and max positions.
8686     */
8687    private void paste(int min, int max) {
8688        ClipboardManager clipboard =
8689            (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
8690        ClipData clip = clipboard.getPrimaryClip();
8691        if (clip != null) {
8692            boolean didFirst = false;
8693            for (int i=0; i<clip.getItemCount(); i++) {
8694                CharSequence paste = clip.getItemAt(i).coerceToText(getContext());
8695                if (paste != null) {
8696                    if (!didFirst) {
8697                        long minMax = prepareSpacesAroundPaste(min, max, paste);
8698                        min = extractRangeStartFromLong(minMax);
8699                        max = extractRangeEndFromLong(minMax);
8700                        Selection.setSelection((Spannable) mText, max);
8701                        ((Editable) mText).replace(min, max, paste);
8702                        didFirst = true;
8703                    } else {
8704                        ((Editable) mText).insert(getSelectionEnd(), "\n");
8705                        ((Editable) mText).insert(getSelectionEnd(), paste);
8706                    }
8707                }
8708            }
8709            stopSelectionActionMode();
8710            sLastCutOrCopyTime = 0;
8711        }
8712    }
8713
8714    private void setPrimaryClip(ClipData clip) {
8715        ClipboardManager clipboard = (ClipboardManager) getContext().
8716                getSystemService(Context.CLIPBOARD_SERVICE);
8717        clipboard.setPrimaryClip(clip);
8718        sLastCutOrCopyTime = SystemClock.uptimeMillis();
8719    }
8720
8721    /**
8722     * An ActionMode Callback class that is used to provide actions while in text selection mode.
8723     *
8724     * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending
8725     * on which of these this TextView supports.
8726     */
8727    private class SelectionActionModeCallback implements ActionMode.Callback {
8728
8729        @Override
8730        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
8731            TypedArray styledAttributes = mContext.obtainStyledAttributes(R.styleable.Theme);
8732
8733            mode.setTitle(mContext.getString(com.android.internal.R.string.textSelectionCABTitle));
8734            mode.setSubtitle(null);
8735
8736            menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll).
8737                    setAlphabeticShortcut('a').
8738                    setShowAsAction(
8739                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
8740
8741            if (canCut()) {
8742                menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut).
8743                    setIcon(styledAttributes.getResourceId(
8744                            R.styleable.Theme_actionModeCutDrawable, 0)).
8745                    setAlphabeticShortcut('x').
8746                    setShowAsAction(
8747                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
8748            }
8749
8750            if (canCopy()) {
8751                menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy).
8752                    setIcon(styledAttributes.getResourceId(
8753                            R.styleable.Theme_actionModeCopyDrawable, 0)).
8754                    setAlphabeticShortcut('c').
8755                    setShowAsAction(
8756                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
8757            }
8758
8759            if (canPaste()) {
8760                menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste).
8761                        setIcon(styledAttributes.getResourceId(
8762                                R.styleable.Theme_actionModePasteDrawable, 0)).
8763                        setAlphabeticShortcut('v').
8764                        setShowAsAction(
8765                                MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
8766            }
8767
8768            styledAttributes.recycle();
8769
8770            if (mCustomSelectionActionModeCallback != null) {
8771                if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) {
8772                    // The custom mode can choose to cancel the action mode
8773                    return false;
8774                }
8775            }
8776
8777            if (menu.hasVisibleItems() || mode.getCustomView() != null) {
8778                getSelectionController().show();
8779                return true;
8780            } else {
8781                return false;
8782            }
8783        }
8784
8785        @Override
8786        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
8787            if (mCustomSelectionActionModeCallback != null) {
8788                return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu);
8789            }
8790            return true;
8791        }
8792
8793        @Override
8794        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
8795            if (mCustomSelectionActionModeCallback != null &&
8796                 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) {
8797                return true;
8798            }
8799            return onTextContextMenuItem(item.getItemId());
8800        }
8801
8802        @Override
8803        public void onDestroyActionMode(ActionMode mode) {
8804            if (mCustomSelectionActionModeCallback != null) {
8805                mCustomSelectionActionModeCallback.onDestroyActionMode(mode);
8806            }
8807            Selection.setSelection((Spannable) mText, getSelectionEnd());
8808
8809            if (mSelectionModifierCursorController != null) {
8810                mSelectionModifierCursorController.hide();
8811            }
8812
8813            mSelectionActionMode = null;
8814        }
8815    }
8816
8817    private class PastePopupWindow implements OnClickListener {
8818        private final PopupWindow mContainer;
8819        private final View[] mPasteViews = new View[4];
8820        private final int[] mPasteViewLayouts = new int[] {
8821                mTextEditPasteWindowLayout,  mTextEditNoPasteWindowLayout,
8822                mTextEditSidePasteWindowLayout, mTextEditSideNoPasteWindowLayout };
8823
8824        public PastePopupWindow() {
8825            mContainer = new PopupWindow(TextView.this.mContext, null,
8826                    com.android.internal.R.attr.textSelectHandleWindowStyle);
8827            mContainer.setSplitTouchEnabled(true);
8828            mContainer.setClippingEnabled(false);
8829            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
8830
8831            mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
8832            mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
8833        }
8834
8835        private int viewIndex(boolean onTop) {
8836            return (onTop ? 0 : 1<<1) + (canPaste() ? 0 : 1<<0);
8837        }
8838
8839        private void updateContent(boolean onTop) {
8840            final int viewIndex = viewIndex(onTop);
8841            View view = mPasteViews[viewIndex];
8842
8843            if (view == null) {
8844                final int layout = mPasteViewLayouts[viewIndex];
8845                LayoutInflater inflater = (LayoutInflater)TextView.this.mContext.
8846                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
8847                if (inflater != null) {
8848                    view = inflater.inflate(layout, null);
8849                }
8850
8851                if (view == null) {
8852                    throw new IllegalArgumentException("Unable to inflate TextEdit paste window");
8853                }
8854
8855                final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
8856                view.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
8857                        ViewGroup.LayoutParams.WRAP_CONTENT));
8858                view.measure(size, size);
8859
8860                view.setOnClickListener(this);
8861
8862                mPasteViews[viewIndex] = view;
8863            }
8864
8865            mContainer.setContentView(view);
8866        }
8867
8868        public void show() {
8869            updateContent(true);
8870            positionAtCursor();
8871        }
8872
8873        public void hide() {
8874            mContainer.dismiss();
8875        }
8876
8877        public boolean isShowing() {
8878            return mContainer.isShowing();
8879        }
8880
8881        @Override
8882        public void onClick(View v) {
8883            if (canPaste()) {
8884                paste(getSelectionStart(), getSelectionEnd());
8885            }
8886            hide();
8887        }
8888
8889        void positionAtCursor() {
8890            View contentView = mContainer.getContentView();
8891            int width = contentView.getMeasuredWidth();
8892            int height = contentView.getMeasuredHeight();
8893            final int offset = TextView.this.getSelectionStart();
8894            final int line = mLayout.getLineForOffset(offset);
8895            final int lineTop = mLayout.getLineTop(line);
8896            float primaryHorizontal = mLayout.getPrimaryHorizontal(offset);
8897
8898            final Rect bounds = sCursorControllerTempRect;
8899            bounds.left = (int) (primaryHorizontal - width / 2.0f);
8900            bounds.top = lineTop - height;
8901
8902            bounds.right = bounds.left + width;
8903            bounds.bottom = bounds.top + height;
8904
8905            convertFromViewportToContentCoordinates(bounds);
8906
8907            final int[] coords = mTempCoords;
8908            TextView.this.getLocationInWindow(coords);
8909            coords[0] += bounds.left;
8910            coords[1] += bounds.top;
8911
8912            final int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels;
8913            if (coords[1] < 0) {
8914                updateContent(false);
8915                // Update dimensions from new view
8916                contentView = mContainer.getContentView();
8917                width = contentView.getMeasuredWidth();
8918                height = contentView.getMeasuredHeight();
8919
8920                // Vertical clipping, move under edited line and to the side of insertion cursor
8921                // TODO bottom clipping in case there is no system bar
8922                coords[1] += height;
8923                final int lineBottom = mLayout.getLineBottom(line);
8924                final int lineHeight = lineBottom - lineTop;
8925                coords[1] += lineHeight;
8926
8927                // Move to right hand side of insertion cursor by default. TODO RTL text.
8928                final Drawable handle = mContext.getResources().getDrawable(mTextSelectHandleRes);
8929                final int handleHalfWidth = handle.getIntrinsicWidth() / 2;
8930
8931                if (primaryHorizontal + handleHalfWidth + width < screenWidth) {
8932                    coords[0] += handleHalfWidth + width / 2;
8933                } else {
8934                    coords[0] -= handleHalfWidth + width / 2;
8935                }
8936            } else {
8937                // Horizontal clipping
8938                coords[0] = Math.max(0, coords[0]);
8939                coords[0] = Math.min(screenWidth - width, coords[0]);
8940            }
8941
8942            mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]);
8943        }
8944    }
8945
8946    private abstract class HandleView extends View implements ViewTreeObserver.OnPreDrawListener {
8947        protected Drawable mDrawable;
8948        private final PopupWindow mContainer;
8949        // Position with respect to the parent TextView
8950        private int mPositionX, mPositionY;
8951        private boolean mIsDragging;
8952        // Offset from touch position to mPosition
8953        private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
8954        protected float mHotspotX;
8955        // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
8956        private float mTouchOffsetY;
8957        // Where the touch position should be on the handle to ensure a maximum cursor visibility
8958        private float mIdealVerticalOffset;
8959        // Parent's (TextView) previous position in window
8960        private int mLastParentX, mLastParentY;
8961        // PopupWindow container absolute position with respect to the enclosing window
8962        private int mContainerPositionX, mContainerPositionY;
8963        // Visible or not (scrolled off screen), whether or not this handle should be visible
8964        private boolean mIsActive = false;
8965
8966        public HandleView() {
8967            super(TextView.this.mContext);
8968            mContainer = new PopupWindow(TextView.this.mContext, null,
8969                    com.android.internal.R.attr.textSelectHandleWindowStyle);
8970            mContainer.setSplitTouchEnabled(true);
8971            mContainer.setClippingEnabled(false);
8972            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
8973            mContainer.setContentView(this);
8974
8975            initDrawable();
8976
8977            final int handleHeight = mDrawable.getIntrinsicHeight();
8978            mTouchOffsetY = -0.3f * handleHeight;
8979            mIdealVerticalOffset = 0.7f * handleHeight;
8980        }
8981
8982        protected abstract void initDrawable();
8983
8984        // Touch-up filter: number of previous positions remembered
8985        private static final int HISTORY_SIZE = 5;
8986        private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
8987        private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
8988        private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
8989        private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
8990        private int mPreviousOffsetIndex = 0;
8991        private int mNumberPreviousOffsets = 0;
8992
8993        private void startTouchUpFilter(int offset) {
8994            mNumberPreviousOffsets = 0;
8995            addPositionToTouchUpFilter(offset);
8996        }
8997
8998        private void addPositionToTouchUpFilter(int offset) {
8999            if (mNumberPreviousOffsets > 0 &&
9000                    mPreviousOffsets[mPreviousOffsetIndex] == offset) {
9001                // Make sure only actual changes of position are recorded.
9002                return;
9003            }
9004
9005            mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
9006            mPreviousOffsets[mPreviousOffsetIndex] = offset;
9007            mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
9008            mNumberPreviousOffsets++;
9009        }
9010
9011        private void filterOnTouchUp() {
9012            final long now = SystemClock.uptimeMillis();
9013            int i = 0;
9014            int index = mPreviousOffsetIndex;
9015            final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
9016            while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
9017                i++;
9018                index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
9019            }
9020
9021            if (i > 0 && i < iMax &&
9022                    (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
9023                updateOffset(mPreviousOffsets[index]);
9024            }
9025        }
9026
9027        @Override
9028        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9029            setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
9030        }
9031
9032        public void show() {
9033            if (isShowing()) {
9034                mContainer.update(mContainerPositionX, mContainerPositionY,
9035                        mRight - mLeft, mBottom - mTop);
9036            } else {
9037                mContainer.showAtLocation(TextView.this, 0,
9038                        mContainerPositionX, mContainerPositionY);
9039
9040                mIsActive = true;
9041
9042                ViewTreeObserver vto = TextView.this.getViewTreeObserver();
9043                vto.addOnPreDrawListener(this);
9044            }
9045        }
9046
9047        protected void dismiss() {
9048            mIsDragging = false;
9049            mContainer.dismiss();
9050        }
9051
9052        public void hide() {
9053            dismiss();
9054
9055            mIsActive = false;
9056
9057            ViewTreeObserver vto = TextView.this.getViewTreeObserver();
9058            vto.removeOnPreDrawListener(this);
9059        }
9060
9061        public boolean isShowing() {
9062            return mContainer.isShowing();
9063        }
9064
9065        private boolean isPositionVisible() {
9066            // Always show a dragging handle.
9067            if (mIsDragging) {
9068                return true;
9069            }
9070
9071            if (isInBatchEditMode()) {
9072                return false;
9073            }
9074
9075            final int extendedPaddingTop = getExtendedPaddingTop();
9076            final int extendedPaddingBottom = getExtendedPaddingBottom();
9077            final int compoundPaddingLeft = getCompoundPaddingLeft();
9078            final int compoundPaddingRight = getCompoundPaddingRight();
9079
9080            final TextView textView = TextView.this;
9081
9082            if (mTempRect == null) mTempRect = new Rect();
9083            final Rect clip = mTempRect;
9084            clip.left = compoundPaddingLeft;
9085            clip.top = extendedPaddingTop;
9086            clip.right = textView.getWidth() - compoundPaddingRight;
9087            clip.bottom = textView.getHeight() - extendedPaddingBottom;
9088
9089            final ViewParent parent = textView.getParent();
9090            if (parent == null || !parent.getChildVisibleRect(textView, clip, null)) {
9091                return false;
9092            }
9093
9094            final int[] coords = mTempCoords;
9095            textView.getLocationInWindow(coords);
9096            final int posX = coords[0] + mPositionX + (int) mHotspotX;
9097            final int posY = coords[1] + mPositionY;
9098
9099            // Offset by 1 to take into account 0.5 and int rounding around getPrimaryHorizontal.
9100            return posX >= clip.left - 1 && posX <= clip.right + 1 &&
9101                    posY >= clip.top && posY <= clip.bottom;
9102        }
9103
9104        public abstract int getCurrentCursorOffset();
9105
9106        public abstract void updateOffset(int offset);
9107
9108        public abstract void updatePosition(float x, float y);
9109
9110        protected void positionAtCursorOffset(int offset) {
9111            addPositionToTouchUpFilter(offset);
9112            final int line = mLayout.getLineForOffset(offset);
9113            final int lineBottom = mLayout.getLineBottom(line);
9114
9115            mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX);
9116            mPositionY = lineBottom;
9117
9118            // Take TextView's padding into account.
9119            mPositionX += viewportToContentHorizontalOffset();
9120            mPositionY += viewportToContentVerticalOffset();
9121        }
9122
9123        protected boolean updateContainerPosition() {
9124            positionAtCursorOffset(getCurrentCursorOffset());
9125
9126            final int previousContainerPositionX = mContainerPositionX;
9127            final int previousContainerPositionY = mContainerPositionY;
9128
9129            TextView.this.getLocationInWindow(mTempCoords);
9130            mContainerPositionX = mTempCoords[0] + mPositionX;
9131            mContainerPositionY = mTempCoords[1] + mPositionY;
9132
9133            return (previousContainerPositionX != mContainerPositionX ||
9134                    previousContainerPositionY != mContainerPositionY);
9135        }
9136
9137        public boolean onPreDraw() {
9138            if (updateContainerPosition()) {
9139                if (mIsDragging) {
9140                    if (mTempCoords[0] != mLastParentX || mTempCoords[1] != mLastParentY) {
9141                        mTouchToWindowOffsetX += mTempCoords[0] - mLastParentX;
9142                        mTouchToWindowOffsetY += mTempCoords[1] - mLastParentY;
9143                        mLastParentX = mTempCoords[0];
9144                        mLastParentY = mTempCoords[1];
9145                    }
9146                }
9147
9148                onHandleMoved();
9149
9150                if (isPositionVisible()) {
9151                    mContainer.update(mContainerPositionX, mContainerPositionY,
9152                            mRight - mLeft, mBottom - mTop);
9153
9154                    if (mIsActive && !isShowing()) {
9155                        show();
9156                    }
9157                } else {
9158                    if (isShowing()) {
9159                        dismiss();
9160                    }
9161                }
9162            }
9163            return true;
9164        }
9165
9166        @Override
9167        protected void onDraw(Canvas c) {
9168            mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
9169            mDrawable.draw(c);
9170        }
9171
9172        @Override
9173        public boolean onTouchEvent(MotionEvent ev) {
9174            switch (ev.getActionMasked()) {
9175                case MotionEvent.ACTION_DOWN: {
9176                    startTouchUpFilter(getCurrentCursorOffset());
9177                    mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
9178                    mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
9179
9180                    final int[] coords = mTempCoords;
9181                    TextView.this.getLocationInWindow(coords);
9182                    mLastParentX = coords[0];
9183                    mLastParentY = coords[1];
9184                    mIsDragging = true;
9185                    break;
9186                }
9187
9188                case MotionEvent.ACTION_MOVE: {
9189                    final float rawX = ev.getRawX();
9190                    final float rawY = ev.getRawY();
9191
9192                    // Vertical hysteresis: vertical down movement tends to snap to ideal offset
9193                    final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
9194                    final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
9195                    float newVerticalOffset;
9196                    if (previousVerticalOffset < mIdealVerticalOffset) {
9197                        newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
9198                        newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
9199                    } else {
9200                        newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
9201                        newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
9202                    }
9203                    mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
9204
9205                    final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX;
9206                    final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
9207
9208                    updatePosition(newPosX, newPosY);
9209                    break;
9210                }
9211
9212                case MotionEvent.ACTION_UP:
9213                    filterOnTouchUp();
9214                    mIsDragging = false;
9215                    break;
9216
9217                case MotionEvent.ACTION_CANCEL:
9218                    mIsDragging = false;
9219                    break;
9220            }
9221            return true;
9222        }
9223
9224        public boolean isDragging() {
9225            return mIsDragging;
9226        }
9227
9228        void onHandleMoved() {
9229            // Does nothing by default
9230        }
9231
9232        public void onDetached() {
9233            // Should be overriden to clean possible Runnable
9234        }
9235    }
9236
9237    private class InsertionHandleView extends HandleView {
9238        private static final int DELAY_BEFORE_FADE_OUT = 4000;
9239        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
9240
9241        // Used to detect taps on the insertion handle, which will affect the PastePopupWindow
9242        private long mTouchTimer;
9243        private float mDownPositionX, mDownPositionY;
9244        private PastePopupWindow mPastePopupWindow;
9245        private Runnable mHider;
9246        private Runnable mPastePopupShower;
9247
9248        @Override
9249        public void show() {
9250            super.show();
9251            hideDelayed();
9252            hidePastePopupWindow();
9253        }
9254
9255        public void show(int delayBeforePaste) {
9256            show();
9257
9258            final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - sLastCutOrCopyTime;
9259            if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) {
9260                delayBeforePaste = 0;
9261            }
9262            if (delayBeforePaste == 0 || canPaste()) {
9263                if (mPastePopupShower == null) {
9264                    mPastePopupShower = new Runnable() {
9265                        public void run() {
9266                            showPastePopupWindow();
9267                        }
9268                    };
9269                }
9270                TextView.this.postDelayed(mPastePopupShower, delayBeforePaste);
9271            }
9272        }
9273
9274        @Override
9275        protected void dismiss() {
9276            super.dismiss();
9277            onDetached();
9278        }
9279
9280        private void hideDelayed() {
9281            removeHiderCallback();
9282            if (mHider == null) {
9283                mHider = new Runnable() {
9284                    public void run() {
9285                        hide();
9286                    }
9287                };
9288            }
9289            TextView.this.postDelayed(mHider, DELAY_BEFORE_FADE_OUT);
9290        }
9291
9292        private void removeHiderCallback() {
9293            if (mHider != null) {
9294                TextView.this.removeCallbacks(mHider);
9295            }
9296        }
9297
9298        @Override
9299        protected void initDrawable() {
9300            if (mSelectHandleCenter == null) {
9301                mSelectHandleCenter = mContext.getResources().getDrawable(
9302                        mTextSelectHandleRes);
9303            }
9304            mDrawable = mSelectHandleCenter;
9305            mHotspotX = mDrawable.getIntrinsicWidth() / 2.0f;
9306        }
9307
9308        @Override
9309        public boolean onTouchEvent(MotionEvent ev) {
9310            final boolean result = super.onTouchEvent(ev);
9311
9312            switch (ev.getActionMasked()) {
9313                case MotionEvent.ACTION_DOWN:
9314                    mDownPositionX = ev.getRawX();
9315                    mDownPositionY = ev.getRawY();
9316                    mTouchTimer = SystemClock.uptimeMillis();
9317                    break;
9318
9319                case MotionEvent.ACTION_UP:
9320                    long delay = SystemClock.uptimeMillis() - mTouchTimer;
9321                    if (delay < ViewConfiguration.getTapTimeout()) {
9322                        final float deltaX = mDownPositionX - ev.getRawX();
9323                        final float deltaY = mDownPositionY - ev.getRawY();
9324                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
9325                        if (distanceSquared < mSquaredTouchSlopDistance) {
9326                            if (mPastePopupWindow != null && mPastePopupWindow.isShowing()) {
9327                                // Tapping on the handle dismisses the displayed paste view,
9328                                mPastePopupWindow.hide();
9329                            } else {
9330                                show(0);
9331                            }
9332                        }
9333                    }
9334                    hideDelayed();
9335                    break;
9336
9337                case MotionEvent.ACTION_CANCEL:
9338                    hideDelayed();
9339                    break;
9340
9341                default:
9342                    break;
9343            }
9344
9345            return result;
9346        }
9347
9348        @Override
9349        public int getCurrentCursorOffset() {
9350            return TextView.this.getSelectionStart();
9351        }
9352
9353        @Override
9354        public void updateOffset(int offset) {
9355            Selection.setSelection((Spannable) mText, offset);
9356        }
9357
9358        @Override
9359        public void updatePosition(float x, float y) {
9360            updateOffset(getOffsetForPosition(x, y));
9361        }
9362
9363        void showPastePopupWindow() {
9364            if (mPastePopupWindow == null) {
9365                mPastePopupWindow = new PastePopupWindow();
9366            }
9367            mPastePopupWindow.show();
9368        }
9369
9370        @Override
9371        void onHandleMoved() {
9372            removeHiderCallback();
9373            hidePastePopupWindow();
9374        }
9375
9376        void hidePastePopupWindow() {
9377            if (mPastePopupShower != null) {
9378                TextView.this.removeCallbacks(mPastePopupShower);
9379            }
9380            if (mPastePopupWindow != null) {
9381                mPastePopupWindow.hide();
9382            }
9383        }
9384
9385        @Override
9386        public void onDetached() {
9387            removeHiderCallback();
9388            hidePastePopupWindow();
9389        }
9390    }
9391
9392    private class SelectionStartHandleView extends HandleView {
9393        @Override
9394        protected void initDrawable() {
9395            if (mSelectHandleLeft == null) {
9396                mSelectHandleLeft = mContext.getResources().getDrawable(
9397                        mTextSelectHandleLeftRes);
9398            }
9399            mDrawable = mSelectHandleLeft;
9400            mHotspotX = mDrawable.getIntrinsicWidth() * 3.0f / 4.0f;
9401        }
9402
9403        @Override
9404        public int getCurrentCursorOffset() {
9405            return TextView.this.getSelectionStart();
9406        }
9407
9408        @Override
9409        public void updateOffset(int offset) {
9410            Selection.setSelection((Spannable) mText, offset, getSelectionEnd());
9411        }
9412
9413        @Override
9414        public void updatePosition(float x, float y) {
9415            final int selectionStart = getSelectionStart();
9416            final int selectionEnd = getSelectionEnd();
9417
9418            int offset = getOffsetForPosition(x, y);
9419
9420            // No need to redraw when the offset is unchanged
9421            if (offset == selectionStart) return;
9422            // Handles can not cross and selection is at least one character
9423            if (offset >= selectionEnd) offset = selectionEnd - 1;
9424
9425            Selection.setSelection((Spannable) mText, offset, selectionEnd);
9426        }
9427    }
9428
9429    private class SelectionEndHandleView extends HandleView {
9430        @Override
9431        protected void initDrawable() {
9432            if (mSelectHandleRight == null) {
9433                mSelectHandleRight = mContext.getResources().getDrawable(
9434                        mTextSelectHandleRightRes);
9435            }
9436            mDrawable = mSelectHandleRight;
9437            mHotspotX = mDrawable.getIntrinsicWidth() / 4.0f;
9438        }
9439
9440        @Override
9441        public int getCurrentCursorOffset() {
9442            return TextView.this.getSelectionEnd();
9443        }
9444
9445        @Override
9446        public void updateOffset(int offset) {
9447            Selection.setSelection((Spannable) mText, getSelectionStart(), offset);
9448        }
9449
9450        @Override
9451        public void updatePosition(float x, float y) {
9452            final int selectionStart = getSelectionStart();
9453            final int selectionEnd = getSelectionEnd();
9454
9455            int offset = getOffsetForPosition(x, y);
9456
9457            // No need to redraw when the offset is unchanged
9458            if (offset == selectionEnd) return;
9459            // Handles can not cross and selection is at least one character
9460            if (offset <= selectionStart) offset = selectionStart + 1;
9461
9462            Selection.setSelection((Spannable) mText, selectionStart, offset);
9463        }
9464    }
9465
9466    /**
9467     * A CursorController instance can be used to control a cursor in the text.
9468     * It is not used outside of {@link TextView}.
9469     * @hide
9470     */
9471    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
9472        /**
9473         * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}.
9474         * See also {@link #hide()}.
9475         */
9476        public void show();
9477
9478        /**
9479         * Hide the cursor controller from screen.
9480         * See also {@link #show()}.
9481         */
9482        public void hide();
9483
9484        /**
9485         * This method is called by {@link #onTouchEvent(MotionEvent)} and gives the controller
9486         * a chance to become active and/or visible.
9487         * @param event The touch event
9488         */
9489        public boolean onTouchEvent(MotionEvent event);
9490
9491        /**
9492         * Called when the view is detached from window. Perform house keeping task, such as
9493         * stopping Runnable thread that would otherwise keep a reference on the context, thus
9494         * preventing the activity from being recycled.
9495         */
9496        public void onDetached();
9497    }
9498
9499    private class InsertionPointCursorController implements CursorController {
9500        private static final int DELAY_BEFORE_PASTE = 2000;
9501
9502        private InsertionHandleView mHandle;
9503
9504        public void show() {
9505            ((InsertionHandleView) getHandle()).show(DELAY_BEFORE_PASTE);
9506        }
9507
9508        public void showWithPaste() {
9509            ((InsertionHandleView) getHandle()).show(0);
9510        }
9511
9512        public void hide() {
9513            if (mHandle != null) {
9514                mHandle.hide();
9515            }
9516        }
9517
9518        public boolean onTouchEvent(MotionEvent ev) {
9519            return false;
9520        }
9521
9522        public void onTouchModeChanged(boolean isInTouchMode) {
9523            if (!isInTouchMode) {
9524                hide();
9525            }
9526        }
9527
9528        private HandleView getHandle() {
9529            if (mHandle == null) {
9530                mHandle = new InsertionHandleView();
9531            }
9532            return mHandle;
9533        }
9534
9535        @Override
9536        public void onDetached() {
9537            final ViewTreeObserver observer = getViewTreeObserver();
9538            observer.removeOnTouchModeChangeListener(this);
9539
9540            if (mHandle != null) mHandle.onDetached();
9541        }
9542    }
9543
9544    private class SelectionModifierCursorController implements CursorController {
9545        // The cursor controller handles, lazily created when shown.
9546        private SelectionStartHandleView mStartHandle;
9547        private SelectionEndHandleView mEndHandle;
9548        // The offsets of that last touch down event. Remembered to start selection there.
9549        private int mMinTouchOffset, mMaxTouchOffset;
9550
9551        // Double tap detection
9552        private long mPreviousTapUpTime = 0;
9553        private float mPreviousTapPositionX, mPreviousTapPositionY;
9554
9555        SelectionModifierCursorController() {
9556            resetTouchOffsets();
9557        }
9558
9559        public void show() {
9560            if (isInBatchEditMode()) {
9561                return;
9562            }
9563
9564            // Lazy object creation has to be done before updatePosition() is called.
9565            if (mStartHandle == null) mStartHandle = new SelectionStartHandleView();
9566            if (mEndHandle == null) mEndHandle = new SelectionEndHandleView();
9567
9568            mStartHandle.show();
9569            mEndHandle.show();
9570
9571            hideInsertionPointCursorController();
9572            hideSuggestions();
9573        }
9574
9575        public void hide() {
9576            if (mStartHandle != null) mStartHandle.hide();
9577            if (mEndHandle != null) mEndHandle.hide();
9578        }
9579
9580        public boolean onTouchEvent(MotionEvent event) {
9581            // This is done even when the View does not have focus, so that long presses can start
9582            // selection and tap can move cursor from this tap position.
9583            if (isTextEditable() || mTextIsSelectable) {
9584                switch (event.getActionMasked()) {
9585                    case MotionEvent.ACTION_DOWN:
9586                        final float x = event.getX();
9587                        final float y = event.getY();
9588
9589                        // Remember finger down position, to be able to start selection from there
9590                        mMinTouchOffset = mMaxTouchOffset = getOffsetForPosition(x, y);
9591
9592                        // Double tap detection
9593                        long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime;
9594                        if (duration <= ViewConfiguration.getDoubleTapTimeout() &&
9595                                isPositionOnText(x, y)) {
9596                            final float deltaX = x - mPreviousTapPositionX;
9597                            final float deltaY = y - mPreviousTapPositionY;
9598                            final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
9599                            if (distanceSquared < mSquaredTouchSlopDistance) {
9600                                showSuggestions();
9601                                mDiscardNextActionUp = true;
9602                            }
9603                        }
9604
9605                        mPreviousTapPositionX = x;
9606                        mPreviousTapPositionY = y;
9607
9608                        break;
9609
9610                    case MotionEvent.ACTION_POINTER_DOWN:
9611                    case MotionEvent.ACTION_POINTER_UP:
9612                        // Handle multi-point gestures. Keep min and max offset positions.
9613                        // Only activated for devices that correctly handle multi-touch.
9614                        if (mContext.getPackageManager().hasSystemFeature(
9615                                PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
9616                            updateMinAndMaxOffsets(event);
9617                        }
9618                        break;
9619
9620                    case MotionEvent.ACTION_UP:
9621                        mPreviousTapUpTime = SystemClock.uptimeMillis();
9622                        break;
9623                }
9624            }
9625            return false;
9626        }
9627
9628        /**
9629         * @param event
9630         */
9631        private void updateMinAndMaxOffsets(MotionEvent event) {
9632            int pointerCount = event.getPointerCount();
9633            for (int index = 0; index < pointerCount; index++) {
9634                int offset = getOffsetForPosition(event.getX(index), event.getY(index));
9635                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
9636                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
9637            }
9638        }
9639
9640        public int getMinTouchOffset() {
9641            return mMinTouchOffset;
9642        }
9643
9644        public int getMaxTouchOffset() {
9645            return mMaxTouchOffset;
9646        }
9647
9648        public void resetTouchOffsets() {
9649            mMinTouchOffset = mMaxTouchOffset = -1;
9650        }
9651
9652        /**
9653         * @return true iff this controller is currently used to move the selection start.
9654         */
9655        public boolean isSelectionStartDragged() {
9656            return mStartHandle != null && mStartHandle.isDragging();
9657        }
9658
9659        public void onTouchModeChanged(boolean isInTouchMode) {
9660            if (!isInTouchMode) {
9661                hide();
9662            }
9663        }
9664
9665        @Override
9666        public void onDetached() {
9667            final ViewTreeObserver observer = getViewTreeObserver();
9668            observer.removeOnTouchModeChangeListener(this);
9669
9670            if (mStartHandle != null) mStartHandle.onDetached();
9671            if (mEndHandle != null) mEndHandle.onDetached();
9672        }
9673    }
9674
9675    private void hideInsertionPointCursorController() {
9676        // No need to create the controller to hide it.
9677        if (mInsertionPointCursorController != null) {
9678            mInsertionPointCursorController.hide();
9679        }
9680    }
9681
9682    /**
9683     * Hides the insertion controller and stops text selection mode, hiding the selection controller
9684     */
9685    private void hideControllers() {
9686        hideInsertionPointCursorController();
9687        stopSelectionActionMode();
9688        hideSuggestions();
9689    }
9690
9691    /**
9692     * Get the character offset closest to the specified absolute position. A typical use case is to
9693     * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method.
9694     *
9695     * @param x The horizontal absolute position of a point on screen
9696     * @param y The vertical absolute position of a point on screen
9697     * @return the character offset for the character whose position is closest to the specified
9698     *  position. Returns -1 if there is no layout.
9699     */
9700    public int getOffsetForPosition(float x, float y) {
9701        if (getLayout() == null) return -1;
9702        final int line = getLineAtCoordinate(y);
9703        final int offset = getOffsetAtCoordinate(line, x);
9704        return offset;
9705    }
9706
9707    private float convertToLocalHorizontalCoordinate(float x) {
9708        x -= getTotalPaddingLeft();
9709        // Clamp the position to inside of the view.
9710        x = Math.max(0.0f, x);
9711        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
9712        x += getScrollX();
9713        return x;
9714    }
9715
9716    private int getLineAtCoordinate(float y) {
9717        y -= getTotalPaddingTop();
9718        // Clamp the position to inside of the view.
9719        y = Math.max(0.0f, y);
9720        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
9721        y += getScrollY();
9722        return getLayout().getLineForVertical((int) y);
9723    }
9724
9725    private int getOffsetAtCoordinate(int line, float x) {
9726        x = convertToLocalHorizontalCoordinate(x);
9727        return getLayout().getOffsetForHorizontal(line, x);
9728    }
9729
9730    /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed
9731     * in the view. Returns false when the position is in the empty space of left/right of text.
9732     */
9733    private boolean isPositionOnText(float x, float y) {
9734        if (getLayout() == null) return false;
9735
9736        final int line = getLineAtCoordinate(y);
9737        x = convertToLocalHorizontalCoordinate(x);
9738
9739        if (x < getLayout().getLineLeft(line)) return false;
9740        if (x > getLayout().getLineRight(line)) return false;
9741        return true;
9742    }
9743
9744    @Override
9745    public boolean onDragEvent(DragEvent event) {
9746        switch (event.getAction()) {
9747            case DragEvent.ACTION_DRAG_STARTED:
9748                return hasInsertionController();
9749
9750            case DragEvent.ACTION_DRAG_ENTERED:
9751                TextView.this.requestFocus();
9752                return true;
9753
9754            case DragEvent.ACTION_DRAG_LOCATION:
9755                final int offset = getOffsetForPosition(event.getX(), event.getY());
9756                Selection.setSelection((Spannable)mText, offset);
9757                return true;
9758
9759            case DragEvent.ACTION_DROP:
9760                onDrop(event);
9761                return true;
9762
9763            case DragEvent.ACTION_DRAG_ENDED:
9764            case DragEvent.ACTION_DRAG_EXITED:
9765            default:
9766                return true;
9767        }
9768    }
9769
9770    private void onDrop(DragEvent event) {
9771        StringBuilder content = new StringBuilder("");
9772        ClipData clipData = event.getClipData();
9773        final int itemCount = clipData.getItemCount();
9774        for (int i=0; i < itemCount; i++) {
9775            Item item = clipData.getItemAt(i);
9776            content.append(item.coerceToText(TextView.this.mContext));
9777        }
9778
9779        final int offset = getOffsetForPosition(event.getX(), event.getY());
9780
9781        Object localState = event.getLocalState();
9782        DragLocalState dragLocalState = null;
9783        if (localState instanceof DragLocalState) {
9784            dragLocalState = (DragLocalState) localState;
9785        }
9786        boolean dragDropIntoItself = dragLocalState != null &&
9787                dragLocalState.sourceTextView == this;
9788
9789        if (dragDropIntoItself) {
9790            if (offset >= dragLocalState.start && offset < dragLocalState.end) {
9791                // A drop inside the original selection discards the drop.
9792                return;
9793            }
9794        }
9795
9796        final int originalLength = mText.length();
9797        long minMax = prepareSpacesAroundPaste(offset, offset, content);
9798        int min = extractRangeStartFromLong(minMax);
9799        int max = extractRangeEndFromLong(minMax);
9800
9801        Selection.setSelection((Spannable) mText, max);
9802        ((Editable) mText).replace(min, max, content);
9803
9804        if (dragDropIntoItself) {
9805            int dragSourceStart = dragLocalState.start;
9806            int dragSourceEnd = dragLocalState.end;
9807            if (max <= dragSourceStart) {
9808                // Inserting text before selection has shifted positions
9809                final int shift = mText.length() - originalLength;
9810                dragSourceStart += shift;
9811                dragSourceEnd += shift;
9812            }
9813
9814            // Delete original selection
9815            ((Editable) mText).delete(dragSourceStart, dragSourceEnd);
9816
9817            // Make sure we do not leave two adjacent spaces.
9818            if ((dragSourceStart == 0 ||
9819                    Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) &&
9820                    (dragSourceStart == mText.length() ||
9821                    Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) {
9822                final int pos = dragSourceStart == mText.length() ?
9823                        dragSourceStart - 1 : dragSourceStart;
9824                ((Editable) mText).delete(pos, pos + 1);
9825            }
9826        }
9827    }
9828
9829    /**
9830     * @return True if this view supports insertion handles.
9831     */
9832    boolean hasInsertionController() {
9833        return mInsertionControllerEnabled;
9834    }
9835
9836    /**
9837     * @return True if this view supports selection handles.
9838     */
9839    boolean hasSelectionController() {
9840        return mSelectionControllerEnabled;
9841    }
9842
9843    InsertionPointCursorController getInsertionController() {
9844        if (!mInsertionControllerEnabled) {
9845            return null;
9846        }
9847
9848        if (mInsertionPointCursorController == null) {
9849            mInsertionPointCursorController = new InsertionPointCursorController();
9850
9851            final ViewTreeObserver observer = getViewTreeObserver();
9852            observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
9853        }
9854
9855        return mInsertionPointCursorController;
9856    }
9857
9858    SelectionModifierCursorController getSelectionController() {
9859        if (!mSelectionControllerEnabled) {
9860            return null;
9861        }
9862
9863        if (mSelectionModifierCursorController == null) {
9864            mSelectionModifierCursorController = new SelectionModifierCursorController();
9865
9866            final ViewTreeObserver observer = getViewTreeObserver();
9867            observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
9868        }
9869
9870        return mSelectionModifierCursorController;
9871    }
9872
9873    boolean isInBatchEditMode() {
9874        final InputMethodState ims = mInputMethodState;
9875        if (ims != null) {
9876            return ims.mBatchEditNesting > 0;
9877        }
9878        return mInBatchEditControllers;
9879    }
9880
9881    @ViewDebug.ExportedProperty(category = "text")
9882    private CharSequence            mText;
9883    private CharSequence            mTransformed;
9884    private BufferType              mBufferType = BufferType.NORMAL;
9885
9886    private int                     mInputType = EditorInfo.TYPE_NULL;
9887    private CharSequence            mHint;
9888    private Layout                  mHintLayout;
9889
9890    private KeyListener             mInput;
9891
9892    private MovementMethod          mMovement;
9893    private TransformationMethod    mTransformation;
9894    private ChangeWatcher           mChangeWatcher;
9895
9896    private ArrayList<TextWatcher>  mListeners = null;
9897
9898    // display attributes
9899    private final TextPaint         mTextPaint;
9900    private boolean                 mUserSetTextScaleX;
9901    private final Paint             mHighlightPaint;
9902    private int                     mHighlightColor = 0xCC475925;
9903    /**
9904     * This is temporarily visible to fix bug 3085564 in webView. Do not rely on
9905     * this field being protected. Will be restored as private when lineHeight
9906     * feature request 3215097 is implemented
9907     * @hide
9908     */
9909    protected Layout                mLayout;
9910
9911    private long                    mShowCursor;
9912    private Blink                   mBlink;
9913    private boolean                 mCursorVisible = true;
9914
9915    // Cursor Controllers.
9916    private InsertionPointCursorController mInsertionPointCursorController;
9917    private SelectionModifierCursorController mSelectionModifierCursorController;
9918    private ActionMode              mSelectionActionMode;
9919    private boolean                 mInsertionControllerEnabled;
9920    private boolean                 mSelectionControllerEnabled;
9921    private boolean                 mInBatchEditControllers;
9922
9923    // These are needed to desambiguate a long click. If the long click comes from ones of these, we
9924    // select from the current cursor position. Otherwise, select from long pressed position.
9925    private boolean                 mDPadCenterIsDown = false;
9926    private boolean                 mEnterKeyIsDown = false;
9927    private boolean                 mContextMenuTriggeredByKey = false;
9928    // Created once and shared by different CursorController helper methods.
9929    // Only one cursor controller is active at any time which prevent race conditions.
9930    private static Rect             sCursorControllerTempRect = new Rect();
9931
9932    private boolean                 mSelectAllOnFocus = false;
9933
9934    private int                     mGravity = Gravity.TOP | Gravity.LEFT;
9935    private boolean                 mHorizontallyScrolling;
9936
9937    private int                     mAutoLinkMask;
9938    private boolean                 mLinksClickable = true;
9939
9940    private float                   mSpacingMult = 1;
9941    private float                   mSpacingAdd = 0;
9942    private boolean                 mTextIsSelectable = false;
9943
9944    private static final int        LINES = 1;
9945    private static final int        EMS = LINES;
9946    private static final int        PIXELS = 2;
9947
9948    private int                     mMaximum = Integer.MAX_VALUE;
9949    private int                     mMaxMode = LINES;
9950    private int                     mMinimum = 0;
9951    private int                     mMinMode = LINES;
9952
9953    private int                     mMaxWidth = Integer.MAX_VALUE;
9954    private int                     mMaxWidthMode = PIXELS;
9955    private int                     mMinWidth = 0;
9956    private int                     mMinWidthMode = PIXELS;
9957
9958    private boolean                 mSingleLine;
9959    private int                     mDesiredHeightAtMeasure = -1;
9960    private boolean                 mIncludePad = true;
9961
9962    // tmp primitives, so we don't alloc them on each draw
9963    private Path                    mHighlightPath;
9964    private boolean                 mHighlightPathBogus = true;
9965    private static final RectF      sTempRect = new RectF();
9966
9967    // XXX should be much larger
9968    private static final int        VERY_WIDE = 16384;
9969
9970    private static final int        BLINK = 500;
9971
9972    private static final int ANIMATED_SCROLL_GAP = 250;
9973    private long mLastScroll;
9974    private Scroller mScroller = null;
9975
9976    private BoringLayout.Metrics mBoring;
9977    private BoringLayout.Metrics mHintBoring;
9978
9979    private BoringLayout mSavedLayout, mSavedHintLayout;
9980
9981    private static final InputFilter[] NO_FILTERS = new InputFilter[0];
9982    private InputFilter[] mFilters = NO_FILTERS;
9983    private static final Spanned EMPTY_SPANNED = new SpannedString("");
9984    private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
9985    // System wide time for last cut or copy action.
9986    private static long sLastCutOrCopyTime;
9987    // Used to highlight a word when it is corrected by the IME
9988    private CorrectionHighlighter mCorrectionHighlighter;
9989    // New state used to change background based on whether this TextView is multiline.
9990    private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline };
9991}
9992