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