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