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