TextView.java revision 7d6f6c938cd99b42ce3355c291d32216ae83ae8f
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 Layout that is currently being used to display the hint text.
1316     * This can be null.
1317     */
1318    final Layout getHintLayout() {
1319        return mHintLayout;
1320    }
1321
1322    /**
1323     * @return the current key listener for this TextView.
1324     * This will frequently be null for non-EditText TextViews.
1325     *
1326     * @attr ref android.R.styleable#TextView_numeric
1327     * @attr ref android.R.styleable#TextView_digits
1328     * @attr ref android.R.styleable#TextView_phoneNumber
1329     * @attr ref android.R.styleable#TextView_inputMethod
1330     * @attr ref android.R.styleable#TextView_capitalize
1331     * @attr ref android.R.styleable#TextView_autoText
1332     */
1333    public final KeyListener getKeyListener() {
1334        return mEditor == null ? null : mEditor.mKeyListener;
1335    }
1336
1337    /**
1338     * Sets the key listener to be used with this TextView.  This can be null
1339     * to disallow user input.  Note that this method has significant and
1340     * subtle interactions with soft keyboards and other input method:
1341     * see {@link KeyListener#getInputType() KeyListener.getContentType()}
1342     * for important details.  Calling this method will replace the current
1343     * content type of the text view with the content type returned by the
1344     * key listener.
1345     * <p>
1346     * Be warned that if you want a TextView with a key listener or movement
1347     * method not to be focusable, or if you want a TextView without a
1348     * key listener or movement method to be focusable, you must call
1349     * {@link #setFocusable} again after calling this to get the focusability
1350     * back the way you want it.
1351     *
1352     * @attr ref android.R.styleable#TextView_numeric
1353     * @attr ref android.R.styleable#TextView_digits
1354     * @attr ref android.R.styleable#TextView_phoneNumber
1355     * @attr ref android.R.styleable#TextView_inputMethod
1356     * @attr ref android.R.styleable#TextView_capitalize
1357     * @attr ref android.R.styleable#TextView_autoText
1358     */
1359    public void setKeyListener(KeyListener input) {
1360        setKeyListenerOnly(input);
1361        fixFocusableAndClickableSettings();
1362
1363        if (input != null) {
1364            createEditorIfNeeded();
1365            try {
1366                mEditor.mInputType = mEditor.mKeyListener.getInputType();
1367            } catch (IncompatibleClassChangeError e) {
1368                mEditor.mInputType = EditorInfo.TYPE_CLASS_TEXT;
1369            }
1370            // Change inputType, without affecting transformation.
1371            // No need to applySingleLine since mSingleLine is unchanged.
1372            setInputTypeSingleLine(mSingleLine);
1373        } else {
1374            if (mEditor != null) mEditor.mInputType = EditorInfo.TYPE_NULL;
1375        }
1376
1377        InputMethodManager imm = InputMethodManager.peekInstance();
1378        if (imm != null) imm.restartInput(this);
1379    }
1380
1381    private void setKeyListenerOnly(KeyListener input) {
1382        if (mEditor == null && input == null) return; // null is the default value
1383
1384        createEditorIfNeeded();
1385        if (mEditor.mKeyListener != input) {
1386            mEditor.mKeyListener = input;
1387            if (input != null && !(mText instanceof Editable)) {
1388                setText(mText);
1389            }
1390
1391            setFilters((Editable) mText, mFilters);
1392        }
1393    }
1394
1395    /**
1396     * @return the movement method being used for this TextView.
1397     * This will frequently be null for non-EditText TextViews.
1398     */
1399    public final MovementMethod getMovementMethod() {
1400        return mMovement;
1401    }
1402
1403    /**
1404     * Sets the movement method (arrow key handler) to be used for
1405     * this TextView.  This can be null to disallow using the arrow keys
1406     * to move the cursor or scroll the view.
1407     * <p>
1408     * Be warned that if you want a TextView with a key listener or movement
1409     * method not to be focusable, or if you want a TextView without a
1410     * key listener or movement method to be focusable, you must call
1411     * {@link #setFocusable} again after calling this to get the focusability
1412     * back the way you want it.
1413     */
1414    public final void setMovementMethod(MovementMethod movement) {
1415        if (mMovement != movement) {
1416            mMovement = movement;
1417
1418            if (movement != null && !(mText instanceof Spannable)) {
1419                setText(mText);
1420            }
1421
1422            fixFocusableAndClickableSettings();
1423
1424            // SelectionModifierCursorController depends on textCanBeSelected, which depends on
1425            // mMovement
1426            if (mEditor != null) mEditor.prepareCursorControllers();
1427        }
1428    }
1429
1430    private void fixFocusableAndClickableSettings() {
1431        if (mMovement != null || (mEditor != null && mEditor.mKeyListener != null)) {
1432            setFocusable(true);
1433            setClickable(true);
1434            setLongClickable(true);
1435        } else {
1436            setFocusable(false);
1437            setClickable(false);
1438            setLongClickable(false);
1439        }
1440    }
1441
1442    /**
1443     * @return the current transformation method for this TextView.
1444     * This will frequently be null except for single-line and password
1445     * fields.
1446     *
1447     * @attr ref android.R.styleable#TextView_password
1448     * @attr ref android.R.styleable#TextView_singleLine
1449     */
1450    public final TransformationMethod getTransformationMethod() {
1451        return mTransformation;
1452    }
1453
1454    /**
1455     * Sets the transformation that is applied to the text that this
1456     * TextView is displaying.
1457     *
1458     * @attr ref android.R.styleable#TextView_password
1459     * @attr ref android.R.styleable#TextView_singleLine
1460     */
1461    public final void setTransformationMethod(TransformationMethod method) {
1462        if (method == mTransformation) {
1463            // Avoid the setText() below if the transformation is
1464            // the same.
1465            return;
1466        }
1467        if (mTransformation != null) {
1468            if (mText instanceof Spannable) {
1469                ((Spannable) mText).removeSpan(mTransformation);
1470            }
1471        }
1472
1473        mTransformation = method;
1474
1475        if (method instanceof TransformationMethod2) {
1476            TransformationMethod2 method2 = (TransformationMethod2) method;
1477            mAllowTransformationLengthChange = !isTextSelectable() && !(mText instanceof Editable);
1478            method2.setLengthChangesAllowed(mAllowTransformationLengthChange);
1479        } else {
1480            mAllowTransformationLengthChange = false;
1481        }
1482
1483        setText(mText);
1484
1485        if (hasPasswordTransformationMethod()) {
1486            notifyAccessibilityStateChanged();
1487        }
1488    }
1489
1490    /**
1491     * Returns the top padding of the view, plus space for the top
1492     * Drawable if any.
1493     */
1494    public int getCompoundPaddingTop() {
1495        final Drawables dr = mDrawables;
1496        if (dr == null || dr.mDrawableTop == null) {
1497            return mPaddingTop;
1498        } else {
1499            return mPaddingTop + dr.mDrawablePadding + dr.mDrawableSizeTop;
1500        }
1501    }
1502
1503    /**
1504     * Returns the bottom padding of the view, plus space for the bottom
1505     * Drawable if any.
1506     */
1507    public int getCompoundPaddingBottom() {
1508        final Drawables dr = mDrawables;
1509        if (dr == null || dr.mDrawableBottom == null) {
1510            return mPaddingBottom;
1511        } else {
1512            return mPaddingBottom + dr.mDrawablePadding + dr.mDrawableSizeBottom;
1513        }
1514    }
1515
1516    /**
1517     * Returns the left padding of the view, plus space for the left
1518     * Drawable if any.
1519     */
1520    public int getCompoundPaddingLeft() {
1521        final Drawables dr = mDrawables;
1522        if (dr == null || dr.mDrawableLeft == null) {
1523            return mPaddingLeft;
1524        } else {
1525            return mPaddingLeft + dr.mDrawablePadding + dr.mDrawableSizeLeft;
1526        }
1527    }
1528
1529    /**
1530     * Returns the right padding of the view, plus space for the right
1531     * Drawable if any.
1532     */
1533    public int getCompoundPaddingRight() {
1534        final Drawables dr = mDrawables;
1535        if (dr == null || dr.mDrawableRight == null) {
1536            return mPaddingRight;
1537        } else {
1538            return mPaddingRight + dr.mDrawablePadding + dr.mDrawableSizeRight;
1539        }
1540    }
1541
1542    /**
1543     * Returns the start padding of the view, plus space for the start
1544     * Drawable if any.
1545     */
1546    public int getCompoundPaddingStart() {
1547        resolveDrawables();
1548        switch(getResolvedLayoutDirection()) {
1549            default:
1550            case LAYOUT_DIRECTION_LTR:
1551                return getCompoundPaddingLeft();
1552            case LAYOUT_DIRECTION_RTL:
1553                return getCompoundPaddingRight();
1554        }
1555    }
1556
1557    /**
1558     * Returns the end padding of the view, plus space for the end
1559     * Drawable if any.
1560     */
1561    public int getCompoundPaddingEnd() {
1562        resolveDrawables();
1563        switch(getResolvedLayoutDirection()) {
1564            default:
1565            case LAYOUT_DIRECTION_LTR:
1566                return getCompoundPaddingRight();
1567            case LAYOUT_DIRECTION_RTL:
1568                return getCompoundPaddingLeft();
1569        }
1570    }
1571
1572    /**
1573     * Returns the extended top padding of the view, including both the
1574     * top Drawable if any and any extra space to keep more than maxLines
1575     * of text from showing.  It is only valid to call this after measuring.
1576     */
1577    public int getExtendedPaddingTop() {
1578        if (mMaxMode != LINES) {
1579            return getCompoundPaddingTop();
1580        }
1581
1582        if (mLayout.getLineCount() <= mMaximum) {
1583            return getCompoundPaddingTop();
1584        }
1585
1586        int top = getCompoundPaddingTop();
1587        int bottom = getCompoundPaddingBottom();
1588        int viewht = getHeight() - top - bottom;
1589        int layoutht = mLayout.getLineTop(mMaximum);
1590
1591        if (layoutht >= viewht) {
1592            return top;
1593        }
1594
1595        final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
1596        if (gravity == Gravity.TOP) {
1597            return top;
1598        } else if (gravity == Gravity.BOTTOM) {
1599            return top + viewht - layoutht;
1600        } else { // (gravity == Gravity.CENTER_VERTICAL)
1601            return top + (viewht - layoutht) / 2;
1602        }
1603    }
1604
1605    /**
1606     * Returns the extended bottom padding of the view, including both the
1607     * bottom Drawable if any and any extra space to keep more than maxLines
1608     * of text from showing.  It is only valid to call this after measuring.
1609     */
1610    public int getExtendedPaddingBottom() {
1611        if (mMaxMode != LINES) {
1612            return getCompoundPaddingBottom();
1613        }
1614
1615        if (mLayout.getLineCount() <= mMaximum) {
1616            return getCompoundPaddingBottom();
1617        }
1618
1619        int top = getCompoundPaddingTop();
1620        int bottom = getCompoundPaddingBottom();
1621        int viewht = getHeight() - top - bottom;
1622        int layoutht = mLayout.getLineTop(mMaximum);
1623
1624        if (layoutht >= viewht) {
1625            return bottom;
1626        }
1627
1628        final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
1629        if (gravity == Gravity.TOP) {
1630            return bottom + viewht - layoutht;
1631        } else if (gravity == Gravity.BOTTOM) {
1632            return bottom;
1633        } else { // (gravity == Gravity.CENTER_VERTICAL)
1634            return bottom + (viewht - layoutht) / 2;
1635        }
1636    }
1637
1638    /**
1639     * Returns the total left padding of the view, including the left
1640     * Drawable if any.
1641     */
1642    public int getTotalPaddingLeft() {
1643        return getCompoundPaddingLeft();
1644    }
1645
1646    /**
1647     * Returns the total right padding of the view, including the right
1648     * Drawable if any.
1649     */
1650    public int getTotalPaddingRight() {
1651        return getCompoundPaddingRight();
1652    }
1653
1654    /**
1655     * Returns the total start padding of the view, including the start
1656     * Drawable if any.
1657     */
1658    public int getTotalPaddingStart() {
1659        return getCompoundPaddingStart();
1660    }
1661
1662    /**
1663     * Returns the total end padding of the view, including the end
1664     * Drawable if any.
1665     */
1666    public int getTotalPaddingEnd() {
1667        return getCompoundPaddingEnd();
1668    }
1669
1670    /**
1671     * Returns the total top padding of the view, including the top
1672     * Drawable if any, the extra space to keep more than maxLines
1673     * from showing, and the vertical offset for gravity, if any.
1674     */
1675    public int getTotalPaddingTop() {
1676        return getExtendedPaddingTop() + getVerticalOffset(true);
1677    }
1678
1679    /**
1680     * Returns the total bottom padding of the view, including the bottom
1681     * Drawable if any, the extra space to keep more than maxLines
1682     * from showing, and the vertical offset for gravity, if any.
1683     */
1684    public int getTotalPaddingBottom() {
1685        return getExtendedPaddingBottom() + getBottomVerticalOffset(true);
1686    }
1687
1688    /**
1689     * Sets the Drawables (if any) to appear to the left of, above,
1690     * to the right of, and below the text.  Use null if you do not
1691     * want a Drawable there.  The Drawables must already have had
1692     * {@link Drawable#setBounds} called.
1693     *
1694     * @attr ref android.R.styleable#TextView_drawableLeft
1695     * @attr ref android.R.styleable#TextView_drawableTop
1696     * @attr ref android.R.styleable#TextView_drawableRight
1697     * @attr ref android.R.styleable#TextView_drawableBottom
1698     */
1699    public void setCompoundDrawables(Drawable left, Drawable top,
1700                                     Drawable right, Drawable bottom) {
1701        Drawables dr = mDrawables;
1702
1703        final boolean drawables = left != null || top != null
1704                || right != null || bottom != null;
1705
1706        if (!drawables) {
1707            // Clearing drawables...  can we free the data structure?
1708            if (dr != null) {
1709                if (dr.mDrawablePadding == 0) {
1710                    mDrawables = null;
1711                } else {
1712                    // We need to retain the last set padding, so just clear
1713                    // out all of the fields in the existing structure.
1714                    if (dr.mDrawableLeft != null) dr.mDrawableLeft.setCallback(null);
1715                    dr.mDrawableLeft = null;
1716                    if (dr.mDrawableTop != null) dr.mDrawableTop.setCallback(null);
1717                    dr.mDrawableTop = null;
1718                    if (dr.mDrawableRight != null) dr.mDrawableRight.setCallback(null);
1719                    dr.mDrawableRight = null;
1720                    if (dr.mDrawableBottom != null) dr.mDrawableBottom.setCallback(null);
1721                    dr.mDrawableBottom = null;
1722                    dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0;
1723                    dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0;
1724                    dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0;
1725                    dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0;
1726                }
1727            }
1728        } else {
1729            if (dr == null) {
1730                mDrawables = dr = new Drawables();
1731            }
1732
1733            if (dr.mDrawableLeft != left && dr.mDrawableLeft != null) {
1734                dr.mDrawableLeft.setCallback(null);
1735            }
1736            dr.mDrawableLeft = left;
1737
1738            if (dr.mDrawableTop != top && dr.mDrawableTop != null) {
1739                dr.mDrawableTop.setCallback(null);
1740            }
1741            dr.mDrawableTop = top;
1742
1743            if (dr.mDrawableRight != right && dr.mDrawableRight != null) {
1744                dr.mDrawableRight.setCallback(null);
1745            }
1746            dr.mDrawableRight = right;
1747
1748            if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) {
1749                dr.mDrawableBottom.setCallback(null);
1750            }
1751            dr.mDrawableBottom = bottom;
1752
1753            final Rect compoundRect = dr.mCompoundRect;
1754            int[] state;
1755
1756            state = getDrawableState();
1757
1758            if (left != null) {
1759                left.setState(state);
1760                left.copyBounds(compoundRect);
1761                left.setCallback(this);
1762                dr.mDrawableSizeLeft = compoundRect.width();
1763                dr.mDrawableHeightLeft = compoundRect.height();
1764            } else {
1765                dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0;
1766            }
1767
1768            if (right != null) {
1769                right.setState(state);
1770                right.copyBounds(compoundRect);
1771                right.setCallback(this);
1772                dr.mDrawableSizeRight = compoundRect.width();
1773                dr.mDrawableHeightRight = compoundRect.height();
1774            } else {
1775                dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0;
1776            }
1777
1778            if (top != null) {
1779                top.setState(state);
1780                top.copyBounds(compoundRect);
1781                top.setCallback(this);
1782                dr.mDrawableSizeTop = compoundRect.height();
1783                dr.mDrawableWidthTop = compoundRect.width();
1784            } else {
1785                dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0;
1786            }
1787
1788            if (bottom != null) {
1789                bottom.setState(state);
1790                bottom.copyBounds(compoundRect);
1791                bottom.setCallback(this);
1792                dr.mDrawableSizeBottom = compoundRect.height();
1793                dr.mDrawableWidthBottom = compoundRect.width();
1794            } else {
1795                dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0;
1796            }
1797        }
1798
1799        invalidate();
1800        requestLayout();
1801    }
1802
1803    /**
1804     * Sets the Drawables (if any) to appear to the left of, above,
1805     * to the right of, and below the text.  Use 0 if you do not
1806     * want a Drawable there. The Drawables' bounds will be set to
1807     * their intrinsic bounds.
1808     *
1809     * @param left Resource identifier of the left Drawable.
1810     * @param top Resource identifier of the top Drawable.
1811     * @param right Resource identifier of the right Drawable.
1812     * @param bottom Resource identifier of the bottom Drawable.
1813     *
1814     * @attr ref android.R.styleable#TextView_drawableLeft
1815     * @attr ref android.R.styleable#TextView_drawableTop
1816     * @attr ref android.R.styleable#TextView_drawableRight
1817     * @attr ref android.R.styleable#TextView_drawableBottom
1818     */
1819    @android.view.RemotableViewMethod
1820    public void setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) {
1821        final Resources resources = getContext().getResources();
1822        setCompoundDrawablesWithIntrinsicBounds(left != 0 ? resources.getDrawable(left) : null,
1823                top != 0 ? resources.getDrawable(top) : null,
1824                right != 0 ? resources.getDrawable(right) : null,
1825                bottom != 0 ? resources.getDrawable(bottom) : null);
1826    }
1827
1828    /**
1829     * Sets the Drawables (if any) to appear to the left of, above,
1830     * to the right of, and below the text.  Use null if you do not
1831     * want a Drawable there. The Drawables' bounds will be set to
1832     * their intrinsic bounds.
1833     *
1834     * @attr ref android.R.styleable#TextView_drawableLeft
1835     * @attr ref android.R.styleable#TextView_drawableTop
1836     * @attr ref android.R.styleable#TextView_drawableRight
1837     * @attr ref android.R.styleable#TextView_drawableBottom
1838     */
1839    public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top,
1840            Drawable right, Drawable bottom) {
1841
1842        if (left != null) {
1843            left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight());
1844        }
1845        if (right != null) {
1846            right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight());
1847        }
1848        if (top != null) {
1849            top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight());
1850        }
1851        if (bottom != null) {
1852            bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight());
1853        }
1854        setCompoundDrawables(left, top, right, bottom);
1855    }
1856
1857    /**
1858     * Sets the Drawables (if any) to appear to the start of, above,
1859     * to the end of, and below the text.  Use null if you do not
1860     * want a Drawable there.  The Drawables must already have had
1861     * {@link Drawable#setBounds} called.
1862     *
1863     * @attr ref android.R.styleable#TextView_drawableStart
1864     * @attr ref android.R.styleable#TextView_drawableTop
1865     * @attr ref android.R.styleable#TextView_drawableEnd
1866     * @attr ref android.R.styleable#TextView_drawableBottom
1867     */
1868    public void setCompoundDrawablesRelative(Drawable start, Drawable top,
1869                                     Drawable end, Drawable bottom) {
1870        Drawables dr = mDrawables;
1871
1872        final boolean drawables = start != null || top != null
1873                || end != null || bottom != null;
1874
1875        if (!drawables) {
1876            // Clearing drawables...  can we free the data structure?
1877            if (dr != null) {
1878                if (dr.mDrawablePadding == 0) {
1879                    mDrawables = null;
1880                } else {
1881                    // We need to retain the last set padding, so just clear
1882                    // out all of the fields in the existing structure.
1883                    if (dr.mDrawableStart != null) dr.mDrawableStart.setCallback(null);
1884                    dr.mDrawableStart = null;
1885                    if (dr.mDrawableTop != null) dr.mDrawableTop.setCallback(null);
1886                    dr.mDrawableTop = null;
1887                    if (dr.mDrawableEnd != null) dr.mDrawableEnd.setCallback(null);
1888                    dr.mDrawableEnd = null;
1889                    if (dr.mDrawableBottom != null) dr.mDrawableBottom.setCallback(null);
1890                    dr.mDrawableBottom = null;
1891                    dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0;
1892                    dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0;
1893                    dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0;
1894                    dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0;
1895                }
1896            }
1897        } else {
1898            if (dr == null) {
1899                mDrawables = dr = new Drawables();
1900            }
1901
1902            if (dr.mDrawableStart != start && dr.mDrawableStart != null) {
1903                dr.mDrawableStart.setCallback(null);
1904            }
1905            dr.mDrawableStart = start;
1906
1907            if (dr.mDrawableTop != top && dr.mDrawableTop != null) {
1908                dr.mDrawableTop.setCallback(null);
1909            }
1910            dr.mDrawableTop = top;
1911
1912            if (dr.mDrawableEnd != end && dr.mDrawableEnd != null) {
1913                dr.mDrawableEnd.setCallback(null);
1914            }
1915            dr.mDrawableEnd = end;
1916
1917            if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) {
1918                dr.mDrawableBottom.setCallback(null);
1919            }
1920            dr.mDrawableBottom = bottom;
1921
1922            final Rect compoundRect = dr.mCompoundRect;
1923            int[] state;
1924
1925            state = getDrawableState();
1926
1927            if (start != null) {
1928                start.setState(state);
1929                start.copyBounds(compoundRect);
1930                start.setCallback(this);
1931                dr.mDrawableSizeStart = compoundRect.width();
1932                dr.mDrawableHeightStart = compoundRect.height();
1933            } else {
1934                dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0;
1935            }
1936
1937            if (end != null) {
1938                end.setState(state);
1939                end.copyBounds(compoundRect);
1940                end.setCallback(this);
1941                dr.mDrawableSizeEnd = compoundRect.width();
1942                dr.mDrawableHeightEnd = compoundRect.height();
1943            } else {
1944                dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0;
1945            }
1946
1947            if (top != null) {
1948                top.setState(state);
1949                top.copyBounds(compoundRect);
1950                top.setCallback(this);
1951                dr.mDrawableSizeTop = compoundRect.height();
1952                dr.mDrawableWidthTop = compoundRect.width();
1953            } else {
1954                dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0;
1955            }
1956
1957            if (bottom != null) {
1958                bottom.setState(state);
1959                bottom.copyBounds(compoundRect);
1960                bottom.setCallback(this);
1961                dr.mDrawableSizeBottom = compoundRect.height();
1962                dr.mDrawableWidthBottom = compoundRect.width();
1963            } else {
1964                dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0;
1965            }
1966        }
1967
1968        resolveDrawables();
1969        invalidate();
1970        requestLayout();
1971    }
1972
1973    /**
1974     * Sets the Drawables (if any) to appear to the start of, above,
1975     * to the end of, and below the text.  Use 0 if you do not
1976     * want a Drawable there. The Drawables' bounds will be set to
1977     * their intrinsic bounds.
1978     *
1979     * @param start Resource identifier of the start Drawable.
1980     * @param top Resource identifier of the top Drawable.
1981     * @param end Resource identifier of the end Drawable.
1982     * @param bottom Resource identifier of the bottom Drawable.
1983     *
1984     * @attr ref android.R.styleable#TextView_drawableStart
1985     * @attr ref android.R.styleable#TextView_drawableTop
1986     * @attr ref android.R.styleable#TextView_drawableEnd
1987     * @attr ref android.R.styleable#TextView_drawableBottom
1988     */
1989    @android.view.RemotableViewMethod
1990    public void setCompoundDrawablesRelativeWithIntrinsicBounds(int start, int top, int end,
1991            int bottom) {
1992        resetResolvedDrawables();
1993        final Resources resources = getContext().getResources();
1994        setCompoundDrawablesRelativeWithIntrinsicBounds(
1995                start != 0 ? resources.getDrawable(start) : null,
1996                top != 0 ? resources.getDrawable(top) : null,
1997                end != 0 ? resources.getDrawable(end) : null,
1998                bottom != 0 ? resources.getDrawable(bottom) : null);
1999    }
2000
2001    /**
2002     * Sets the Drawables (if any) to appear to the start of, above,
2003     * to the end of, and below the text.  Use null if you do not
2004     * want a Drawable there. The Drawables' bounds will be set to
2005     * their intrinsic bounds.
2006     *
2007     * @attr ref android.R.styleable#TextView_drawableStart
2008     * @attr ref android.R.styleable#TextView_drawableTop
2009     * @attr ref android.R.styleable#TextView_drawableEnd
2010     * @attr ref android.R.styleable#TextView_drawableBottom
2011     */
2012    public void setCompoundDrawablesRelativeWithIntrinsicBounds(Drawable start, Drawable top,
2013            Drawable end, Drawable bottom) {
2014
2015        resetResolvedDrawables();
2016        if (start != null) {
2017            start.setBounds(0, 0, start.getIntrinsicWidth(), start.getIntrinsicHeight());
2018        }
2019        if (end != null) {
2020            end.setBounds(0, 0, end.getIntrinsicWidth(), end.getIntrinsicHeight());
2021        }
2022        if (top != null) {
2023            top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight());
2024        }
2025        if (bottom != null) {
2026            bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight());
2027        }
2028        setCompoundDrawablesRelative(start, top, end, bottom);
2029    }
2030
2031    /**
2032     * Returns drawables for the left, top, right, and bottom borders.
2033     *
2034     * @attr ref android.R.styleable#TextView_drawableLeft
2035     * @attr ref android.R.styleable#TextView_drawableTop
2036     * @attr ref android.R.styleable#TextView_drawableRight
2037     * @attr ref android.R.styleable#TextView_drawableBottom
2038     */
2039    public Drawable[] getCompoundDrawables() {
2040        final Drawables dr = mDrawables;
2041        if (dr != null) {
2042            return new Drawable[] {
2043                dr.mDrawableLeft, dr.mDrawableTop, dr.mDrawableRight, dr.mDrawableBottom
2044            };
2045        } else {
2046            return new Drawable[] { null, null, null, null };
2047        }
2048    }
2049
2050    /**
2051     * Returns drawables for the start, top, end, and bottom borders.
2052     *
2053     * @attr ref android.R.styleable#TextView_drawableStart
2054     * @attr ref android.R.styleable#TextView_drawableTop
2055     * @attr ref android.R.styleable#TextView_drawableEnd
2056     * @attr ref android.R.styleable#TextView_drawableBottom
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    @Override
4582    public boolean hasOverlappingRendering() {
4583        return (getBackground() != null || mText instanceof Spannable || hasSelection());
4584    }
4585
4586    /**
4587     * When a TextView is used to display a useful piece of information to the user (such as a
4588     * contact's address), it should be made selectable, so that the user can select and copy this
4589     * content.
4590     *
4591     * Use {@link #setTextIsSelectable(boolean)} or the
4592     * {@link android.R.styleable#TextView_textIsSelectable} XML attribute to make this TextView
4593     * selectable (text is not selectable by default).
4594     *
4595     * Note that this method simply returns the state of this flag. Although this flag has to be set
4596     * in order to select text in non-editable TextView, the content of an {@link EditText} can
4597     * always be selected, independently of the value of this flag.
4598     *
4599     * @return True if the text displayed in this TextView can be selected by the user.
4600     *
4601     * @attr ref android.R.styleable#TextView_textIsSelectable
4602     */
4603    public boolean isTextSelectable() {
4604        return mEditor == null ? false : mEditor.mTextIsSelectable;
4605    }
4606
4607    /**
4608     * Sets whether or not (default) the content of this view is selectable by the user.
4609     *
4610     * Note that this methods affect the {@link #setFocusable(boolean)},
4611     * {@link #setFocusableInTouchMode(boolean)} {@link #setClickable(boolean)} and
4612     * {@link #setLongClickable(boolean)} states and you may want to restore these if they were
4613     * customized.
4614     *
4615     * See {@link #isTextSelectable} for details.
4616     *
4617     * @param selectable Whether or not the content of this TextView should be selectable.
4618     */
4619    public void setTextIsSelectable(boolean selectable) {
4620        if (!selectable && mEditor == null) return; // false is default value with no edit data
4621
4622        createEditorIfNeeded();
4623        if (mEditor.mTextIsSelectable == selectable) return;
4624
4625        mEditor.mTextIsSelectable = selectable;
4626        setFocusableInTouchMode(selectable);
4627        setFocusable(selectable);
4628        setClickable(selectable);
4629        setLongClickable(selectable);
4630
4631        // mInputType should already be EditorInfo.TYPE_NULL and mInput should be null
4632
4633        setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null);
4634        setText(mText, selectable ? BufferType.SPANNABLE : BufferType.NORMAL);
4635
4636        // Called by setText above, but safer in case of future code changes
4637        mEditor.prepareCursorControllers();
4638    }
4639
4640    @Override
4641    protected int[] onCreateDrawableState(int extraSpace) {
4642        final int[] drawableState;
4643
4644        if (mSingleLine) {
4645            drawableState = super.onCreateDrawableState(extraSpace);
4646        } else {
4647            drawableState = super.onCreateDrawableState(extraSpace + 1);
4648            mergeDrawableStates(drawableState, MULTILINE_STATE_SET);
4649        }
4650
4651        if (isTextSelectable()) {
4652            // Disable pressed state, which was introduced when TextView was made clickable.
4653            // Prevents text color change.
4654            // setClickable(false) would have a similar effect, but it also disables focus changes
4655            // and long press actions, which are both needed by text selection.
4656            final int length = drawableState.length;
4657            for (int i = 0; i < length; i++) {
4658                if (drawableState[i] == R.attr.state_pressed) {
4659                    final int[] nonPressedState = new int[length - 1];
4660                    System.arraycopy(drawableState, 0, nonPressedState, 0, i);
4661                    System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1);
4662                    return nonPressedState;
4663                }
4664            }
4665        }
4666
4667        return drawableState;
4668    }
4669
4670    private Path getUpdatedHighlightPath() {
4671        Path highlight = null;
4672        Paint highlightPaint = mHighlightPaint;
4673
4674        final int selStart = getSelectionStart();
4675        final int selEnd = getSelectionEnd();
4676        if (mMovement != null && (isFocused() || isPressed()) && selStart >= 0) {
4677            if (selStart == selEnd) {
4678                if (mEditor != null && mEditor.isCursorVisible() &&
4679                        (SystemClock.uptimeMillis() - mEditor.mShowCursor) %
4680                        (2 * Editor.BLINK) < Editor.BLINK) {
4681                    if (mHighlightPathBogus) {
4682                        if (mHighlightPath == null) mHighlightPath = new Path();
4683                        mHighlightPath.reset();
4684                        mLayout.getCursorPath(selStart, mHighlightPath, mText);
4685                        mEditor.updateCursorsPositions();
4686                        mHighlightPathBogus = false;
4687                    }
4688
4689                    // XXX should pass to skin instead of drawing directly
4690                    highlightPaint.setColor(mCurTextColor);
4691                    highlightPaint.setStyle(Paint.Style.STROKE);
4692                    highlight = mHighlightPath;
4693                }
4694            } else {
4695                if (mHighlightPathBogus) {
4696                    if (mHighlightPath == null) mHighlightPath = new Path();
4697                    mHighlightPath.reset();
4698                    mLayout.getSelectionPath(selStart, selEnd, mHighlightPath);
4699                    mHighlightPathBogus = false;
4700                }
4701
4702                // XXX should pass to skin instead of drawing directly
4703                highlightPaint.setColor(mHighlightColor);
4704                highlightPaint.setStyle(Paint.Style.FILL);
4705
4706                highlight = mHighlightPath;
4707            }
4708        }
4709        return highlight;
4710    }
4711
4712    @Override
4713    protected void onDraw(Canvas canvas) {
4714        restartMarqueeIfNeeded();
4715
4716        // Draw the background for this view
4717        super.onDraw(canvas);
4718
4719        final int compoundPaddingLeft = getCompoundPaddingLeft();
4720        final int compoundPaddingTop = getCompoundPaddingTop();
4721        final int compoundPaddingRight = getCompoundPaddingRight();
4722        final int compoundPaddingBottom = getCompoundPaddingBottom();
4723        final int scrollX = mScrollX;
4724        final int scrollY = mScrollY;
4725        final int right = mRight;
4726        final int left = mLeft;
4727        final int bottom = mBottom;
4728        final int top = mTop;
4729
4730        final Drawables dr = mDrawables;
4731        if (dr != null) {
4732            /*
4733             * Compound, not extended, because the icon is not clipped
4734             * if the text height is smaller.
4735             */
4736
4737            int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop;
4738            int hspace = right - left - compoundPaddingRight - compoundPaddingLeft;
4739
4740            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4741            // Make sure to update invalidateDrawable() when changing this code.
4742            if (dr.mDrawableLeft != null) {
4743                canvas.save();
4744                canvas.translate(scrollX + mPaddingLeft,
4745                                 scrollY + compoundPaddingTop +
4746                                 (vspace - dr.mDrawableHeightLeft) / 2);
4747                dr.mDrawableLeft.draw(canvas);
4748                canvas.restore();
4749            }
4750
4751            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4752            // Make sure to update invalidateDrawable() when changing this code.
4753            if (dr.mDrawableRight != null) {
4754                canvas.save();
4755                canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight,
4756                         scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2);
4757                dr.mDrawableRight.draw(canvas);
4758                canvas.restore();
4759            }
4760
4761            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4762            // Make sure to update invalidateDrawable() when changing this code.
4763            if (dr.mDrawableTop != null) {
4764                canvas.save();
4765                canvas.translate(scrollX + compoundPaddingLeft +
4766                        (hspace - dr.mDrawableWidthTop) / 2, scrollY + mPaddingTop);
4767                dr.mDrawableTop.draw(canvas);
4768                canvas.restore();
4769            }
4770
4771            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4772            // Make sure to update invalidateDrawable() when changing this code.
4773            if (dr.mDrawableBottom != null) {
4774                canvas.save();
4775                canvas.translate(scrollX + compoundPaddingLeft +
4776                        (hspace - dr.mDrawableWidthBottom) / 2,
4777                         scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom);
4778                dr.mDrawableBottom.draw(canvas);
4779                canvas.restore();
4780            }
4781        }
4782
4783        int color = mCurTextColor;
4784
4785        if (mLayout == null) {
4786            assumeLayout();
4787        }
4788
4789        Layout layout = mLayout;
4790
4791        if (mHint != null && mText.length() == 0) {
4792            if (mHintTextColor != null) {
4793                color = mCurHintTextColor;
4794            }
4795
4796            layout = mHintLayout;
4797        }
4798
4799        mTextPaint.setColor(color);
4800        mTextPaint.drawableState = getDrawableState();
4801
4802        canvas.save();
4803        /*  Would be faster if we didn't have to do this. Can we chop the
4804            (displayable) text so that we don't need to do this ever?
4805        */
4806
4807        int extendedPaddingTop = getExtendedPaddingTop();
4808        int extendedPaddingBottom = getExtendedPaddingBottom();
4809
4810        final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
4811        final int maxScrollY = mLayout.getHeight() - vspace;
4812
4813        float clipLeft = compoundPaddingLeft + scrollX;
4814        float clipTop = (scrollY == 0) ? 0 : extendedPaddingTop + scrollY;
4815        float clipRight = right - left - compoundPaddingRight + scrollX;
4816        float clipBottom = bottom - top + scrollY -
4817                ((scrollY == maxScrollY) ? 0 : extendedPaddingBottom);
4818
4819        if (mShadowRadius != 0) {
4820            clipLeft += Math.min(0, mShadowDx - mShadowRadius);
4821            clipRight += Math.max(0, mShadowDx + mShadowRadius);
4822
4823            clipTop += Math.min(0, mShadowDy - mShadowRadius);
4824            clipBottom += Math.max(0, mShadowDy + mShadowRadius);
4825        }
4826
4827        canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom);
4828
4829        int voffsetText = 0;
4830        int voffsetCursor = 0;
4831
4832        // translate in by our padding
4833        /* shortcircuit calling getVerticaOffset() */
4834        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4835            voffsetText = getVerticalOffset(false);
4836            voffsetCursor = getVerticalOffset(true);
4837        }
4838        canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText);
4839
4840        final boolean isLayoutRtl = isLayoutRtl();
4841
4842        final int layoutDirection = getResolvedLayoutDirection();
4843        final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
4844        if (mEllipsize == TextUtils.TruncateAt.MARQUEE &&
4845                mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
4846            if (!mSingleLine && getLineCount() == 1 && canMarquee() &&
4847                    (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) {
4848                final int width = mRight - mLeft;
4849                final int padding = getCompoundPaddingLeft() + getCompoundPaddingRight();
4850                final float dx = mLayout.getLineRight(0) - (width - padding);
4851                canvas.translate(isLayoutRtl ? -dx : +dx, 0.0f);
4852            }
4853
4854            if (mMarquee != null && mMarquee.isRunning()) {
4855                final float dx = -mMarquee.getScroll();
4856                canvas.translate(isLayoutRtl ? -dx : +dx, 0.0f);
4857            }
4858        }
4859
4860        final int cursorOffsetVertical = voffsetCursor - voffsetText;
4861
4862        Path highlight = getUpdatedHighlightPath();
4863        if (mEditor != null) {
4864            mEditor.onDraw(canvas, layout, highlight, mHighlightPaint, cursorOffsetVertical);
4865        } else {
4866            layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
4867        }
4868
4869        if (mMarquee != null && mMarquee.shouldDrawGhost()) {
4870            final int dx = (int) mMarquee.getGhostOffset();
4871            canvas.translate(isLayoutRtl ? -dx : dx, 0.0f);
4872            layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
4873        }
4874
4875        canvas.restore();
4876    }
4877
4878    @Override
4879    public void getFocusedRect(Rect r) {
4880        if (mLayout == null) {
4881            super.getFocusedRect(r);
4882            return;
4883        }
4884
4885        int selEnd = getSelectionEnd();
4886        if (selEnd < 0) {
4887            super.getFocusedRect(r);
4888            return;
4889        }
4890
4891        int selStart = getSelectionStart();
4892        if (selStart < 0 || selStart >= selEnd) {
4893            int line = mLayout.getLineForOffset(selEnd);
4894            r.top = mLayout.getLineTop(line);
4895            r.bottom = mLayout.getLineBottom(line);
4896            r.left = (int) mLayout.getPrimaryHorizontal(selEnd) - 2;
4897            r.right = r.left + 4;
4898        } else {
4899            int lineStart = mLayout.getLineForOffset(selStart);
4900            int lineEnd = mLayout.getLineForOffset(selEnd);
4901            r.top = mLayout.getLineTop(lineStart);
4902            r.bottom = mLayout.getLineBottom(lineEnd);
4903            if (lineStart == lineEnd) {
4904                r.left = (int) mLayout.getPrimaryHorizontal(selStart);
4905                r.right = (int) mLayout.getPrimaryHorizontal(selEnd);
4906            } else {
4907                // Selection extends across multiple lines -- make the focused
4908                // rect cover the entire width.
4909                if (mHighlightPathBogus) {
4910                    if (mHighlightPath == null) mHighlightPath = new Path();
4911                    mHighlightPath.reset();
4912                    mLayout.getSelectionPath(selStart, selEnd, mHighlightPath);
4913                    mHighlightPathBogus = false;
4914                }
4915                synchronized (TEMP_RECTF) {
4916                    mHighlightPath.computeBounds(TEMP_RECTF, true);
4917                    r.left = (int)TEMP_RECTF.left-1;
4918                    r.right = (int)TEMP_RECTF.right+1;
4919                }
4920            }
4921        }
4922
4923        // Adjust for padding and gravity.
4924        int paddingLeft = getCompoundPaddingLeft();
4925        int paddingTop = getExtendedPaddingTop();
4926        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4927            paddingTop += getVerticalOffset(false);
4928        }
4929        r.offset(paddingLeft, paddingTop);
4930        int paddingBottom = getExtendedPaddingBottom();
4931        r.bottom += paddingBottom;
4932    }
4933
4934    /**
4935     * Return the number of lines of text, or 0 if the internal Layout has not
4936     * been built.
4937     */
4938    public int getLineCount() {
4939        return mLayout != null ? mLayout.getLineCount() : 0;
4940    }
4941
4942    /**
4943     * Return the baseline for the specified line (0...getLineCount() - 1)
4944     * If bounds is not null, return the top, left, right, bottom extents
4945     * of the specified line in it. If the internal Layout has not been built,
4946     * return 0 and set bounds to (0, 0, 0, 0)
4947     * @param line which line to examine (0..getLineCount() - 1)
4948     * @param bounds Optional. If not null, it returns the extent of the line
4949     * @return the Y-coordinate of the baseline
4950     */
4951    public int getLineBounds(int line, Rect bounds) {
4952        if (mLayout == null) {
4953            if (bounds != null) {
4954                bounds.set(0, 0, 0, 0);
4955            }
4956            return 0;
4957        }
4958        else {
4959            int baseline = mLayout.getLineBounds(line, bounds);
4960
4961            int voffset = getExtendedPaddingTop();
4962            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4963                voffset += getVerticalOffset(true);
4964            }
4965            if (bounds != null) {
4966                bounds.offset(getCompoundPaddingLeft(), voffset);
4967            }
4968            return baseline + voffset;
4969        }
4970    }
4971
4972    @Override
4973    public int getBaseline() {
4974        if (mLayout == null) {
4975            return super.getBaseline();
4976        }
4977
4978        int voffset = 0;
4979        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4980            voffset = getVerticalOffset(true);
4981        }
4982
4983        return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0);
4984    }
4985
4986    /**
4987     * @hide
4988     */
4989    @Override
4990    protected int getFadeTop(boolean offsetRequired) {
4991        if (mLayout == null) return 0;
4992
4993        int voffset = 0;
4994        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4995            voffset = getVerticalOffset(true);
4996        }
4997
4998        if (offsetRequired) voffset += getTopPaddingOffset();
4999
5000        return getExtendedPaddingTop() + voffset;
5001    }
5002
5003    /**
5004     * @hide
5005     */
5006    @Override
5007    protected int getFadeHeight(boolean offsetRequired) {
5008        return mLayout != null ? mLayout.getHeight() : 0;
5009    }
5010
5011    @Override
5012    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
5013        if (keyCode == KeyEvent.KEYCODE_BACK) {
5014            boolean isInSelectionMode = mEditor != null && mEditor.mSelectionActionMode != null;
5015
5016            if (isInSelectionMode) {
5017                if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
5018                    KeyEvent.DispatcherState state = getKeyDispatcherState();
5019                    if (state != null) {
5020                        state.startTracking(event, this);
5021                    }
5022                    return true;
5023                } else if (event.getAction() == KeyEvent.ACTION_UP) {
5024                    KeyEvent.DispatcherState state = getKeyDispatcherState();
5025                    if (state != null) {
5026                        state.handleUpEvent(event);
5027                    }
5028                    if (event.isTracking() && !event.isCanceled()) {
5029                        stopSelectionActionMode();
5030                        return true;
5031                    }
5032                }
5033            }
5034        }
5035        return super.onKeyPreIme(keyCode, event);
5036    }
5037
5038    @Override
5039    public boolean onKeyDown(int keyCode, KeyEvent event) {
5040        int which = doKeyDown(keyCode, event, null);
5041        if (which == 0) {
5042            // Go through default dispatching.
5043            return super.onKeyDown(keyCode, event);
5044        }
5045
5046        return true;
5047    }
5048
5049    @Override
5050    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
5051        KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN);
5052
5053        int which = doKeyDown(keyCode, down, event);
5054        if (which == 0) {
5055            // Go through default dispatching.
5056            return super.onKeyMultiple(keyCode, repeatCount, event);
5057        }
5058        if (which == -1) {
5059            // Consumed the whole thing.
5060            return true;
5061        }
5062
5063        repeatCount--;
5064
5065        // We are going to dispatch the remaining events to either the input
5066        // or movement method.  To do this, we will just send a repeated stream
5067        // of down and up events until we have done the complete repeatCount.
5068        // It would be nice if those interfaces had an onKeyMultiple() method,
5069        // but adding that is a more complicated change.
5070        KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP);
5071        if (which == 1) {
5072            // mEditor and mEditor.mInput are not null from doKeyDown
5073            mEditor.mKeyListener.onKeyUp(this, (Editable)mText, keyCode, up);
5074            while (--repeatCount > 0) {
5075                mEditor.mKeyListener.onKeyDown(this, (Editable)mText, keyCode, down);
5076                mEditor.mKeyListener.onKeyUp(this, (Editable)mText, keyCode, up);
5077            }
5078            hideErrorIfUnchanged();
5079
5080        } else if (which == 2) {
5081            // mMovement is not null from doKeyDown
5082            mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
5083            while (--repeatCount > 0) {
5084                mMovement.onKeyDown(this, (Spannable)mText, keyCode, down);
5085                mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
5086            }
5087        }
5088
5089        return true;
5090    }
5091
5092    /**
5093     * Returns true if pressing ENTER in this field advances focus instead
5094     * of inserting the character.  This is true mostly in single-line fields,
5095     * but also in mail addresses and subjects which will display on multiple
5096     * lines but where it doesn't make sense to insert newlines.
5097     */
5098    private boolean shouldAdvanceFocusOnEnter() {
5099        if (getKeyListener() == null) {
5100            return false;
5101        }
5102
5103        if (mSingleLine) {
5104            return true;
5105        }
5106
5107        if (mEditor != null &&
5108                (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
5109            int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION;
5110            if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
5111                    || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) {
5112                return true;
5113            }
5114        }
5115
5116        return false;
5117    }
5118
5119    /**
5120     * Returns true if pressing TAB in this field advances focus instead
5121     * of inserting the character.  Insert tabs only in multi-line editors.
5122     */
5123    private boolean shouldAdvanceFocusOnTab() {
5124        if (getKeyListener() != null && !mSingleLine && mEditor != null &&
5125                (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
5126            int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION;
5127            if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE
5128                    || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) {
5129                return false;
5130            }
5131        }
5132        return true;
5133    }
5134
5135    private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) {
5136        if (!isEnabled()) {
5137            return 0;
5138        }
5139
5140        switch (keyCode) {
5141            case KeyEvent.KEYCODE_ENTER:
5142                if (event.hasNoModifiers()) {
5143                    // When mInputContentType is set, we know that we are
5144                    // running in a "modern" cupcake environment, so don't need
5145                    // to worry about the application trying to capture
5146                    // enter key events.
5147                    if (mEditor != null && mEditor.mInputContentType != null) {
5148                        // If there is an action listener, given them a
5149                        // chance to consume the event.
5150                        if (mEditor.mInputContentType.onEditorActionListener != null &&
5151                                mEditor.mInputContentType.onEditorActionListener.onEditorAction(
5152                                this, EditorInfo.IME_NULL, event)) {
5153                            mEditor.mInputContentType.enterDown = true;
5154                            // We are consuming the enter key for them.
5155                            return -1;
5156                        }
5157                    }
5158
5159                    // If our editor should move focus when enter is pressed, or
5160                    // this is a generated event from an IME action button, then
5161                    // don't let it be inserted into the text.
5162                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
5163                            || shouldAdvanceFocusOnEnter()) {
5164                        if (hasOnClickListeners()) {
5165                            return 0;
5166                        }
5167                        return -1;
5168                    }
5169                }
5170                break;
5171
5172            case KeyEvent.KEYCODE_DPAD_CENTER:
5173                if (event.hasNoModifiers()) {
5174                    if (shouldAdvanceFocusOnEnter()) {
5175                        return 0;
5176                    }
5177                }
5178                break;
5179
5180            case KeyEvent.KEYCODE_TAB:
5181                if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
5182                    if (shouldAdvanceFocusOnTab()) {
5183                        return 0;
5184                    }
5185                }
5186                break;
5187
5188                // Has to be done on key down (and not on key up) to correctly be intercepted.
5189            case KeyEvent.KEYCODE_BACK:
5190                if (mEditor != null && mEditor.mSelectionActionMode != null) {
5191                    stopSelectionActionMode();
5192                    return -1;
5193                }
5194                break;
5195        }
5196
5197        if (mEditor != null && mEditor.mKeyListener != null) {
5198            resetErrorChangedFlag();
5199
5200            boolean doDown = true;
5201            if (otherEvent != null) {
5202                try {
5203                    beginBatchEdit();
5204                    final boolean handled = mEditor.mKeyListener.onKeyOther(this, (Editable) mText,
5205                            otherEvent);
5206                    hideErrorIfUnchanged();
5207                    doDown = false;
5208                    if (handled) {
5209                        return -1;
5210                    }
5211                } catch (AbstractMethodError e) {
5212                    // onKeyOther was added after 1.0, so if it isn't
5213                    // implemented we need to try to dispatch as a regular down.
5214                } finally {
5215                    endBatchEdit();
5216                }
5217            }
5218
5219            if (doDown) {
5220                beginBatchEdit();
5221                final boolean handled = mEditor.mKeyListener.onKeyDown(this, (Editable) mText,
5222                        keyCode, event);
5223                endBatchEdit();
5224                hideErrorIfUnchanged();
5225                if (handled) return 1;
5226            }
5227        }
5228
5229        // bug 650865: sometimes we get a key event before a layout.
5230        // don't try to move around if we don't know the layout.
5231
5232        if (mMovement != null && mLayout != null) {
5233            boolean doDown = true;
5234            if (otherEvent != null) {
5235                try {
5236                    boolean handled = mMovement.onKeyOther(this, (Spannable) mText,
5237                            otherEvent);
5238                    doDown = false;
5239                    if (handled) {
5240                        return -1;
5241                    }
5242                } catch (AbstractMethodError e) {
5243                    // onKeyOther was added after 1.0, so if it isn't
5244                    // implemented we need to try to dispatch as a regular down.
5245                }
5246            }
5247            if (doDown) {
5248                if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event))
5249                    return 2;
5250            }
5251        }
5252
5253        return 0;
5254    }
5255
5256    /**
5257     * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)}
5258     * can be recorded.
5259     * @hide
5260     */
5261    public void resetErrorChangedFlag() {
5262        /*
5263         * Keep track of what the error was before doing the input
5264         * so that if an input filter changed the error, we leave
5265         * that error showing.  Otherwise, we take down whatever
5266         * error was showing when the user types something.
5267         */
5268        if (mEditor != null) mEditor.mErrorWasChanged = false;
5269    }
5270
5271    /**
5272     * @hide
5273     */
5274    public void hideErrorIfUnchanged() {
5275        if (mEditor != null && mEditor.mError != null && !mEditor.mErrorWasChanged) {
5276            setError(null, null);
5277        }
5278    }
5279
5280    @Override
5281    public boolean onKeyUp(int keyCode, KeyEvent event) {
5282        if (!isEnabled()) {
5283            return super.onKeyUp(keyCode, event);
5284        }
5285
5286        switch (keyCode) {
5287            case KeyEvent.KEYCODE_DPAD_CENTER:
5288                if (event.hasNoModifiers()) {
5289                    /*
5290                     * If there is a click listener, just call through to
5291                     * super, which will invoke it.
5292                     *
5293                     * If there isn't a click listener, try to show the soft
5294                     * input method.  (It will also
5295                     * call performClick(), but that won't do anything in
5296                     * this case.)
5297                     */
5298                    if (!hasOnClickListeners()) {
5299                        if (mMovement != null && mText instanceof Editable
5300                                && mLayout != null && onCheckIsTextEditor()) {
5301                            InputMethodManager imm = InputMethodManager.peekInstance();
5302                            viewClicked(imm);
5303                            if (imm != null && getShowSoftInputOnFocus()) {
5304                                imm.showSoftInput(this, 0);
5305                            }
5306                        }
5307                    }
5308                }
5309                return super.onKeyUp(keyCode, event);
5310
5311            case KeyEvent.KEYCODE_ENTER:
5312                if (event.hasNoModifiers()) {
5313                    if (mEditor != null && mEditor.mInputContentType != null
5314                            && mEditor.mInputContentType.onEditorActionListener != null
5315                            && mEditor.mInputContentType.enterDown) {
5316                        mEditor.mInputContentType.enterDown = false;
5317                        if (mEditor.mInputContentType.onEditorActionListener.onEditorAction(
5318                                this, EditorInfo.IME_NULL, event)) {
5319                            return true;
5320                        }
5321                    }
5322
5323                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
5324                            || shouldAdvanceFocusOnEnter()) {
5325                        /*
5326                         * If there is a click listener, just call through to
5327                         * super, which will invoke it.
5328                         *
5329                         * If there isn't a click listener, try to advance focus,
5330                         * but still call through to super, which will reset the
5331                         * pressed state and longpress state.  (It will also
5332                         * call performClick(), but that won't do anything in
5333                         * this case.)
5334                         */
5335                        if (!hasOnClickListeners()) {
5336                            View v = focusSearch(FOCUS_DOWN);
5337
5338                            if (v != null) {
5339                                if (!v.requestFocus(FOCUS_DOWN)) {
5340                                    throw new IllegalStateException(
5341                                            "focus search returned a view " +
5342                                            "that wasn't able to take focus!");
5343                                }
5344
5345                                /*
5346                                 * Return true because we handled the key; super
5347                                 * will return false because there was no click
5348                                 * listener.
5349                                 */
5350                                super.onKeyUp(keyCode, event);
5351                                return true;
5352                            } else if ((event.getFlags()
5353                                    & KeyEvent.FLAG_EDITOR_ACTION) != 0) {
5354                                // No target for next focus, but make sure the IME
5355                                // if this came from it.
5356                                InputMethodManager imm = InputMethodManager.peekInstance();
5357                                if (imm != null && imm.isActive(this)) {
5358                                    imm.hideSoftInputFromWindow(getWindowToken(), 0);
5359                                }
5360                            }
5361                        }
5362                    }
5363                    return super.onKeyUp(keyCode, event);
5364                }
5365                break;
5366        }
5367
5368        if (mEditor != null && mEditor.mKeyListener != null)
5369            if (mEditor.mKeyListener.onKeyUp(this, (Editable) mText, keyCode, event))
5370                return true;
5371
5372        if (mMovement != null && mLayout != null)
5373            if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event))
5374                return true;
5375
5376        return super.onKeyUp(keyCode, event);
5377    }
5378
5379    @Override
5380    public boolean onCheckIsTextEditor() {
5381        return mEditor != null && mEditor.mInputType != EditorInfo.TYPE_NULL;
5382    }
5383
5384    @Override
5385    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
5386        if (onCheckIsTextEditor() && isEnabled()) {
5387            mEditor.createInputMethodStateIfNeeded();
5388            outAttrs.inputType = getInputType();
5389            if (mEditor.mInputContentType != null) {
5390                outAttrs.imeOptions = mEditor.mInputContentType.imeOptions;
5391                outAttrs.privateImeOptions = mEditor.mInputContentType.privateImeOptions;
5392                outAttrs.actionLabel = mEditor.mInputContentType.imeActionLabel;
5393                outAttrs.actionId = mEditor.mInputContentType.imeActionId;
5394                outAttrs.extras = mEditor.mInputContentType.extras;
5395            } else {
5396                outAttrs.imeOptions = EditorInfo.IME_NULL;
5397            }
5398            if (focusSearch(FOCUS_DOWN) != null) {
5399                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT;
5400            }
5401            if (focusSearch(FOCUS_UP) != null) {
5402                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS;
5403            }
5404            if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION)
5405                    == EditorInfo.IME_ACTION_UNSPECIFIED) {
5406                if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) {
5407                    // An action has not been set, but the enter key will move to
5408                    // the next focus, so set the action to that.
5409                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT;
5410                } else {
5411                    // An action has not been set, and there is no focus to move
5412                    // to, so let's just supply a "done" action.
5413                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
5414                }
5415                if (!shouldAdvanceFocusOnEnter()) {
5416                    outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
5417                }
5418            }
5419            if (isMultilineInputType(outAttrs.inputType)) {
5420                // Multi-line text editors should always show an enter key.
5421                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
5422            }
5423            outAttrs.hintText = mHint;
5424            if (mText instanceof Editable) {
5425                InputConnection ic = new EditableInputConnection(this);
5426                outAttrs.initialSelStart = getSelectionStart();
5427                outAttrs.initialSelEnd = getSelectionEnd();
5428                outAttrs.initialCapsMode = ic.getCursorCapsMode(getInputType());
5429                return ic;
5430            }
5431        }
5432        return null;
5433    }
5434
5435    /**
5436     * If this TextView contains editable content, extract a portion of it
5437     * based on the information in <var>request</var> in to <var>outText</var>.
5438     * @return Returns true if the text was successfully extracted, else false.
5439     */
5440    public boolean extractText(ExtractedTextRequest request, ExtractedText outText) {
5441        createEditorIfNeeded();
5442        return mEditor.extractText(request, outText);
5443    }
5444
5445    /**
5446     * This is used to remove all style-impacting spans from text before new
5447     * extracted text is being replaced into it, so that we don't have any
5448     * lingering spans applied during the replace.
5449     */
5450    static void removeParcelableSpans(Spannable spannable, int start, int end) {
5451        Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class);
5452        int i = spans.length;
5453        while (i > 0) {
5454            i--;
5455            spannable.removeSpan(spans[i]);
5456        }
5457    }
5458
5459    /**
5460     * Apply to this text view the given extracted text, as previously
5461     * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}.
5462     */
5463    public void setExtractedText(ExtractedText text) {
5464        Editable content = getEditableText();
5465        if (text.text != null) {
5466            if (content == null) {
5467                setText(text.text, TextView.BufferType.EDITABLE);
5468            } else if (text.partialStartOffset < 0) {
5469                removeParcelableSpans(content, 0, content.length());
5470                content.replace(0, content.length(), text.text);
5471            } else {
5472                final int N = content.length();
5473                int start = text.partialStartOffset;
5474                if (start > N) start = N;
5475                int end = text.partialEndOffset;
5476                if (end > N) end = N;
5477                removeParcelableSpans(content, start, end);
5478                content.replace(start, end, text.text);
5479            }
5480        }
5481
5482        // Now set the selection position...  make sure it is in range, to
5483        // avoid crashes.  If this is a partial update, it is possible that
5484        // the underlying text may have changed, causing us problems here.
5485        // Also we just don't want to trust clients to do the right thing.
5486        Spannable sp = (Spannable)getText();
5487        final int N = sp.length();
5488        int start = text.selectionStart;
5489        if (start < 0) start = 0;
5490        else if (start > N) start = N;
5491        int end = text.selectionEnd;
5492        if (end < 0) end = 0;
5493        else if (end > N) end = N;
5494        Selection.setSelection(sp, start, end);
5495
5496        // Finally, update the selection mode.
5497        if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) {
5498            MetaKeyKeyListener.startSelecting(this, sp);
5499        } else {
5500            MetaKeyKeyListener.stopSelecting(this, sp);
5501        }
5502    }
5503
5504    /**
5505     * @hide
5506     */
5507    public void setExtracting(ExtractedTextRequest req) {
5508        if (mEditor.mInputMethodState != null) {
5509            mEditor.mInputMethodState.mExtractedTextRequest = req;
5510        }
5511        // This would stop a possible selection mode, but no such mode is started in case
5512        // extracted mode will start. Some text is selected though, and will trigger an action mode
5513        // in the extracted view.
5514        mEditor.hideControllers();
5515    }
5516
5517    /**
5518     * Called by the framework in response to a text completion from
5519     * the current input method, provided by it calling
5520     * {@link InputConnection#commitCompletion
5521     * InputConnection.commitCompletion()}.  The default implementation does
5522     * nothing; text views that are supporting auto-completion should override
5523     * this to do their desired behavior.
5524     *
5525     * @param text The auto complete text the user has selected.
5526     */
5527    public void onCommitCompletion(CompletionInfo text) {
5528        // intentionally empty
5529    }
5530
5531    /**
5532     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
5533     * a dictionnary) from the current input method, provided by it calling
5534     * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
5535     * implementation flashes the background of the corrected word to provide feedback to the user.
5536     *
5537     * @param info The auto correct info about the text that was corrected.
5538     */
5539    public void onCommitCorrection(CorrectionInfo info) {
5540        if (mEditor != null) mEditor.onCommitCorrection(info);
5541    }
5542
5543    public void beginBatchEdit() {
5544        if (mEditor != null) mEditor.beginBatchEdit();
5545    }
5546
5547    public void endBatchEdit() {
5548        if (mEditor != null) mEditor.endBatchEdit();
5549    }
5550
5551    /**
5552     * Called by the framework in response to a request to begin a batch
5553     * of edit operations through a call to link {@link #beginBatchEdit()}.
5554     */
5555    public void onBeginBatchEdit() {
5556        // intentionally empty
5557    }
5558
5559    /**
5560     * Called by the framework in response to a request to end a batch
5561     * of edit operations through a call to link {@link #endBatchEdit}.
5562     */
5563    public void onEndBatchEdit() {
5564        // intentionally empty
5565    }
5566
5567    /**
5568     * Called by the framework in response to a private command from the
5569     * current method, provided by it calling
5570     * {@link InputConnection#performPrivateCommand
5571     * InputConnection.performPrivateCommand()}.
5572     *
5573     * @param action The action name of the command.
5574     * @param data Any additional data for the command.  This may be null.
5575     * @return Return true if you handled the command, else false.
5576     */
5577    public boolean onPrivateIMECommand(String action, Bundle data) {
5578        return false;
5579    }
5580
5581    private void nullLayouts() {
5582        if (mLayout instanceof BoringLayout && mSavedLayout == null) {
5583            mSavedLayout = (BoringLayout) mLayout;
5584        }
5585        if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) {
5586            mSavedHintLayout = (BoringLayout) mHintLayout;
5587        }
5588
5589        mSavedMarqueeModeLayout = mLayout = mHintLayout = null;
5590
5591        mBoring = mHintBoring = null;
5592
5593        // Since it depends on the value of mLayout
5594        if (mEditor != null) mEditor.prepareCursorControllers();
5595    }
5596
5597    /**
5598     * Make a new Layout based on the already-measured size of the view,
5599     * on the assumption that it was measured correctly at some point.
5600     */
5601    private void assumeLayout() {
5602        int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5603
5604        if (width < 1) {
5605            width = 0;
5606        }
5607
5608        int physicalWidth = width;
5609
5610        if (mHorizontallyScrolling) {
5611            width = VERY_WIDE;
5612        }
5613
5614        makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING,
5615                      physicalWidth, false);
5616    }
5617
5618    @Override
5619    public void onResolvedLayoutDirectionReset() {
5620        if (mLayoutAlignment != null) {
5621            int resolvedTextAlignment = getResolvedTextAlignment();
5622            if (resolvedTextAlignment == TEXT_ALIGNMENT_VIEW_START ||
5623                 resolvedTextAlignment == TEXT_ALIGNMENT_VIEW_END) {
5624                mLayoutAlignment = null;
5625            }
5626        }
5627    }
5628
5629    private Layout.Alignment getLayoutAlignment() {
5630        if (mLayoutAlignment == null) {
5631            int textAlign = getResolvedTextAlignment();
5632            switch (textAlign) {
5633                case TEXT_ALIGNMENT_GRAVITY:
5634                    switch (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) {
5635                        case Gravity.START:
5636                            mLayoutAlignment = Layout.Alignment.ALIGN_NORMAL;
5637                            break;
5638                        case Gravity.END:
5639                            mLayoutAlignment = Layout.Alignment.ALIGN_OPPOSITE;
5640                            break;
5641                        case Gravity.LEFT:
5642                            mLayoutAlignment = Layout.Alignment.ALIGN_LEFT;
5643                            break;
5644                        case Gravity.RIGHT:
5645                            mLayoutAlignment = Layout.Alignment.ALIGN_RIGHT;
5646                            break;
5647                        case Gravity.CENTER_HORIZONTAL:
5648                            mLayoutAlignment = Layout.Alignment.ALIGN_CENTER;
5649                            break;
5650                        default:
5651                            mLayoutAlignment = Layout.Alignment.ALIGN_NORMAL;
5652                            break;
5653                    }
5654                    break;
5655                case TEXT_ALIGNMENT_TEXT_START:
5656                    mLayoutAlignment = Layout.Alignment.ALIGN_NORMAL;
5657                    break;
5658                case TEXT_ALIGNMENT_TEXT_END:
5659                    mLayoutAlignment = Layout.Alignment.ALIGN_OPPOSITE;
5660                    break;
5661                case TEXT_ALIGNMENT_CENTER:
5662                    mLayoutAlignment = Layout.Alignment.ALIGN_CENTER;
5663                    break;
5664                case TEXT_ALIGNMENT_VIEW_START:
5665                    mLayoutAlignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
5666                            Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT;
5667                    break;
5668                case TEXT_ALIGNMENT_VIEW_END:
5669                    mLayoutAlignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
5670                            Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT;
5671                    break;
5672                case TEXT_ALIGNMENT_INHERIT:
5673                    // This should never happen as we have already resolved the text alignment
5674                    // but better safe than sorry so we just fall through
5675                default:
5676                    mLayoutAlignment = Layout.Alignment.ALIGN_NORMAL;
5677                    break;
5678            }
5679        }
5680        return mLayoutAlignment;
5681    }
5682
5683    /**
5684     * The width passed in is now the desired layout width,
5685     * not the full view width with padding.
5686     * {@hide}
5687     */
5688    protected void makeNewLayout(int wantWidth, int hintWidth,
5689                                 BoringLayout.Metrics boring,
5690                                 BoringLayout.Metrics hintBoring,
5691                                 int ellipsisWidth, boolean bringIntoView) {
5692        stopMarquee();
5693
5694        // Update "old" cached values
5695        mOldMaximum = mMaximum;
5696        mOldMaxMode = mMaxMode;
5697
5698        mHighlightPathBogus = true;
5699
5700        if (wantWidth < 0) {
5701            wantWidth = 0;
5702        }
5703        if (hintWidth < 0) {
5704            hintWidth = 0;
5705        }
5706
5707        Layout.Alignment alignment = getLayoutAlignment();
5708        boolean shouldEllipsize = mEllipsize != null && getKeyListener() == null;
5709        final boolean switchEllipsize = mEllipsize == TruncateAt.MARQUEE &&
5710                mMarqueeFadeMode != MARQUEE_FADE_NORMAL;
5711        TruncateAt effectiveEllipsize = mEllipsize;
5712        if (mEllipsize == TruncateAt.MARQUEE &&
5713                mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
5714            effectiveEllipsize = TruncateAt.END_SMALL;
5715        }
5716
5717        if (mTextDir == null) {
5718            resolveTextDirection();
5719        }
5720
5721        mLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize,
5722                effectiveEllipsize, effectiveEllipsize == mEllipsize);
5723        if (switchEllipsize) {
5724            TruncateAt oppositeEllipsize = effectiveEllipsize == TruncateAt.MARQUEE ?
5725                    TruncateAt.END : TruncateAt.MARQUEE;
5726            mSavedMarqueeModeLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment,
5727                    shouldEllipsize, oppositeEllipsize, effectiveEllipsize != mEllipsize);
5728        }
5729
5730        shouldEllipsize = mEllipsize != null;
5731        mHintLayout = null;
5732
5733        if (mHint != null) {
5734            if (shouldEllipsize) hintWidth = wantWidth;
5735
5736            if (hintBoring == UNKNOWN_BORING) {
5737                hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir,
5738                                                   mHintBoring);
5739                if (hintBoring != null) {
5740                    mHintBoring = hintBoring;
5741                }
5742            }
5743
5744            if (hintBoring != null) {
5745                if (hintBoring.width <= hintWidth &&
5746                    (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) {
5747                    if (mSavedHintLayout != null) {
5748                        mHintLayout = mSavedHintLayout.
5749                                replaceOrMake(mHint, mTextPaint,
5750                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5751                                hintBoring, mIncludePad);
5752                    } else {
5753                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5754                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5755                                hintBoring, mIncludePad);
5756                    }
5757
5758                    mSavedHintLayout = (BoringLayout) mHintLayout;
5759                } else if (shouldEllipsize && hintBoring.width <= hintWidth) {
5760                    if (mSavedHintLayout != null) {
5761                        mHintLayout = mSavedHintLayout.
5762                                replaceOrMake(mHint, mTextPaint,
5763                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5764                                hintBoring, mIncludePad, mEllipsize,
5765                                ellipsisWidth);
5766                    } else {
5767                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5768                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5769                                hintBoring, mIncludePad, mEllipsize,
5770                                ellipsisWidth);
5771                    }
5772                } else if (shouldEllipsize) {
5773                    mHintLayout = new StaticLayout(mHint,
5774                                0, mHint.length(),
5775                                mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult,
5776                                mSpacingAdd, mIncludePad, mEllipsize,
5777                                ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
5778                } else {
5779                    mHintLayout = new StaticLayout(mHint, mTextPaint,
5780                            hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd,
5781                            mIncludePad);
5782                }
5783            } else if (shouldEllipsize) {
5784                mHintLayout = new StaticLayout(mHint,
5785                            0, mHint.length(),
5786                            mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult,
5787                            mSpacingAdd, mIncludePad, mEllipsize,
5788                            ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
5789            } else {
5790                mHintLayout = new StaticLayout(mHint, mTextPaint,
5791                        hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd,
5792                        mIncludePad);
5793            }
5794        }
5795
5796        if (bringIntoView) {
5797            registerForPreDraw();
5798        }
5799
5800        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
5801            if (!compressText(ellipsisWidth)) {
5802                final int height = mLayoutParams.height;
5803                // If the size of the view does not depend on the size of the text, try to
5804                // start the marquee immediately
5805                if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) {
5806                    startMarquee();
5807                } else {
5808                    // Defer the start of the marquee until we know our width (see setFrame())
5809                    mRestartMarquee = true;
5810                }
5811            }
5812        }
5813
5814        // CursorControllers need a non-null mLayout
5815        if (mEditor != null) mEditor.prepareCursorControllers();
5816    }
5817
5818    private Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth,
5819            Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize,
5820            boolean useSaved) {
5821        Layout result = null;
5822        if (mText instanceof Spannable) {
5823            result = new DynamicLayout(mText, mTransformed, mTextPaint, wantWidth,
5824                    alignment, mTextDir, mSpacingMult,
5825                    mSpacingAdd, mIncludePad, getKeyListener() == null ? effectiveEllipsize : null,
5826                            ellipsisWidth);
5827        } else {
5828            if (boring == UNKNOWN_BORING) {
5829                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
5830                if (boring != null) {
5831                    mBoring = boring;
5832                }
5833            }
5834
5835            if (boring != null) {
5836                if (boring.width <= wantWidth &&
5837                        (effectiveEllipsize == null || boring.width <= ellipsisWidth)) {
5838                    if (useSaved && mSavedLayout != null) {
5839                        result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint,
5840                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
5841                                boring, mIncludePad);
5842                    } else {
5843                        result = BoringLayout.make(mTransformed, mTextPaint,
5844                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
5845                                boring, mIncludePad);
5846                    }
5847
5848                    if (useSaved) {
5849                        mSavedLayout = (BoringLayout) result;
5850                    }
5851                } else if (shouldEllipsize && boring.width <= wantWidth) {
5852                    if (useSaved && mSavedLayout != null) {
5853                        result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint,
5854                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
5855                                boring, mIncludePad, effectiveEllipsize,
5856                                ellipsisWidth);
5857                    } else {
5858                        result = BoringLayout.make(mTransformed, mTextPaint,
5859                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
5860                                boring, mIncludePad, effectiveEllipsize,
5861                                ellipsisWidth);
5862                    }
5863                } else if (shouldEllipsize) {
5864                    result = new StaticLayout(mTransformed,
5865                            0, mTransformed.length(),
5866                            mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult,
5867                            mSpacingAdd, mIncludePad, effectiveEllipsize,
5868                            ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
5869                } else {
5870                    result = new StaticLayout(mTransformed, mTextPaint,
5871                            wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd,
5872                            mIncludePad);
5873                }
5874            } else if (shouldEllipsize) {
5875                result = new StaticLayout(mTransformed,
5876                        0, mTransformed.length(),
5877                        mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult,
5878                        mSpacingAdd, mIncludePad, effectiveEllipsize,
5879                        ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
5880            } else {
5881                result = new StaticLayout(mTransformed, mTextPaint,
5882                        wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd,
5883                        mIncludePad);
5884            }
5885        }
5886        return result;
5887    }
5888
5889    private boolean compressText(float width) {
5890        if (isHardwareAccelerated()) return false;
5891
5892        // Only compress the text if it hasn't been compressed by the previous pass
5893        if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX &&
5894                mTextPaint.getTextScaleX() == 1.0f) {
5895            final float textWidth = mLayout.getLineWidth(0);
5896            final float overflow = (textWidth + 1.0f - width) / width;
5897            if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) {
5898                mTextPaint.setTextScaleX(1.0f - overflow - 0.005f);
5899                post(new Runnable() {
5900                    public void run() {
5901                        requestLayout();
5902                    }
5903                });
5904                return true;
5905            }
5906        }
5907
5908        return false;
5909    }
5910
5911    private static int desired(Layout layout) {
5912        int n = layout.getLineCount();
5913        CharSequence text = layout.getText();
5914        float max = 0;
5915
5916        // if any line was wrapped, we can't use it.
5917        // but it's ok for the last line not to have a newline
5918
5919        for (int i = 0; i < n - 1; i++) {
5920            if (text.charAt(layout.getLineEnd(i) - 1) != '\n')
5921                return -1;
5922        }
5923
5924        for (int i = 0; i < n; i++) {
5925            max = Math.max(max, layout.getLineWidth(i));
5926        }
5927
5928        return (int) FloatMath.ceil(max);
5929    }
5930
5931    /**
5932     * Set whether the TextView includes extra top and bottom padding to make
5933     * room for accents that go above the normal ascent and descent.
5934     * The default is true.
5935     *
5936     * @see #getIncludeFontPadding()
5937     *
5938     * @attr ref android.R.styleable#TextView_includeFontPadding
5939     */
5940    public void setIncludeFontPadding(boolean includepad) {
5941        if (mIncludePad != includepad) {
5942            mIncludePad = includepad;
5943
5944            if (mLayout != null) {
5945                nullLayouts();
5946                requestLayout();
5947                invalidate();
5948            }
5949        }
5950    }
5951
5952    /**
5953     * Gets whether the TextView includes extra top and bottom padding to make
5954     * room for accents that go above the normal ascent and descent.
5955     *
5956     * @see #setIncludeFontPadding(boolean)
5957     *
5958     * @attr ref android.R.styleable#TextView_includeFontPadding
5959     */
5960    public boolean getIncludeFontPadding() {
5961        return mIncludePad;
5962    }
5963
5964    private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics();
5965
5966    @Override
5967    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
5968        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
5969        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
5970        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
5971        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
5972
5973        int width;
5974        int height;
5975
5976        BoringLayout.Metrics boring = UNKNOWN_BORING;
5977        BoringLayout.Metrics hintBoring = UNKNOWN_BORING;
5978
5979        if (mTextDir == null) {
5980            resolveTextDirection();
5981        }
5982
5983        int des = -1;
5984        boolean fromexisting = false;
5985
5986        if (widthMode == MeasureSpec.EXACTLY) {
5987            // Parent has told us how big to be. So be it.
5988            width = widthSize;
5989        } else {
5990            if (mLayout != null && mEllipsize == null) {
5991                des = desired(mLayout);
5992            }
5993
5994            if (des < 0) {
5995                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
5996                if (boring != null) {
5997                    mBoring = boring;
5998                }
5999            } else {
6000                fromexisting = true;
6001            }
6002
6003            if (boring == null || boring == UNKNOWN_BORING) {
6004                if (des < 0) {
6005                    des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint));
6006                }
6007                width = des;
6008            } else {
6009                width = boring.width;
6010            }
6011
6012            final Drawables dr = mDrawables;
6013            if (dr != null) {
6014                width = Math.max(width, dr.mDrawableWidthTop);
6015                width = Math.max(width, dr.mDrawableWidthBottom);
6016            }
6017
6018            if (mHint != null) {
6019                int hintDes = -1;
6020                int hintWidth;
6021
6022                if (mHintLayout != null && mEllipsize == null) {
6023                    hintDes = desired(mHintLayout);
6024                }
6025
6026                if (hintDes < 0) {
6027                    hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, mHintBoring);
6028                    if (hintBoring != null) {
6029                        mHintBoring = hintBoring;
6030                    }
6031                }
6032
6033                if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
6034                    if (hintDes < 0) {
6035                        hintDes = (int) FloatMath.ceil(Layout.getDesiredWidth(mHint, mTextPaint));
6036                    }
6037                    hintWidth = hintDes;
6038                } else {
6039                    hintWidth = hintBoring.width;
6040                }
6041
6042                if (hintWidth > width) {
6043                    width = hintWidth;
6044                }
6045            }
6046
6047            width += getCompoundPaddingLeft() + getCompoundPaddingRight();
6048
6049            if (mMaxWidthMode == EMS) {
6050                width = Math.min(width, mMaxWidth * getLineHeight());
6051            } else {
6052                width = Math.min(width, mMaxWidth);
6053            }
6054
6055            if (mMinWidthMode == EMS) {
6056                width = Math.max(width, mMinWidth * getLineHeight());
6057            } else {
6058                width = Math.max(width, mMinWidth);
6059            }
6060
6061            // Check against our minimum width
6062            width = Math.max(width, getSuggestedMinimumWidth());
6063
6064            if (widthMode == MeasureSpec.AT_MOST) {
6065                width = Math.min(widthSize, width);
6066            }
6067        }
6068
6069        int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight();
6070        int unpaddedWidth = want;
6071
6072        if (mHorizontallyScrolling) want = VERY_WIDE;
6073
6074        int hintWant = want;
6075        int hintWidth = (mHintLayout == null) ? hintWant : mHintLayout.getWidth();
6076
6077        if (mLayout == null) {
6078            makeNewLayout(want, hintWant, boring, hintBoring,
6079                          width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
6080        } else {
6081            final boolean layoutChanged = (mLayout.getWidth() != want) ||
6082                    (hintWidth != hintWant) ||
6083                    (mLayout.getEllipsizedWidth() !=
6084                            width - getCompoundPaddingLeft() - getCompoundPaddingRight());
6085
6086            final boolean widthChanged = (mHint == null) &&
6087                    (mEllipsize == null) &&
6088                    (want > mLayout.getWidth()) &&
6089                    (mLayout instanceof BoringLayout || (fromexisting && des >= 0 && des <= want));
6090
6091            final boolean maximumChanged = (mMaxMode != mOldMaxMode) || (mMaximum != mOldMaximum);
6092
6093            if (layoutChanged || maximumChanged) {
6094                if (!maximumChanged && widthChanged) {
6095                    mLayout.increaseWidthTo(want);
6096                } else {
6097                    makeNewLayout(want, hintWant, boring, hintBoring,
6098                            width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
6099                }
6100            } else {
6101                // Nothing has changed
6102            }
6103        }
6104
6105        if (heightMode == MeasureSpec.EXACTLY) {
6106            // Parent has told us how big to be. So be it.
6107            height = heightSize;
6108            mDesiredHeightAtMeasure = -1;
6109        } else {
6110            int desired = getDesiredHeight();
6111
6112            height = desired;
6113            mDesiredHeightAtMeasure = desired;
6114
6115            if (heightMode == MeasureSpec.AT_MOST) {
6116                height = Math.min(desired, heightSize);
6117            }
6118        }
6119
6120        int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
6121        if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) {
6122            unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum));
6123        }
6124
6125        /*
6126         * We didn't let makeNewLayout() register to bring the cursor into view,
6127         * so do it here if there is any possibility that it is needed.
6128         */
6129        if (mMovement != null ||
6130            mLayout.getWidth() > unpaddedWidth ||
6131            mLayout.getHeight() > unpaddedHeight) {
6132            registerForPreDraw();
6133        } else {
6134            scrollTo(0, 0);
6135        }
6136
6137        setMeasuredDimension(width, height);
6138    }
6139
6140    private int getDesiredHeight() {
6141        return Math.max(
6142                getDesiredHeight(mLayout, true),
6143                getDesiredHeight(mHintLayout, mEllipsize != null));
6144    }
6145
6146    private int getDesiredHeight(Layout layout, boolean cap) {
6147        if (layout == null) {
6148            return 0;
6149        }
6150
6151        int linecount = layout.getLineCount();
6152        int pad = getCompoundPaddingTop() + getCompoundPaddingBottom();
6153        int desired = layout.getLineTop(linecount);
6154
6155        final Drawables dr = mDrawables;
6156        if (dr != null) {
6157            desired = Math.max(desired, dr.mDrawableHeightLeft);
6158            desired = Math.max(desired, dr.mDrawableHeightRight);
6159        }
6160
6161        desired += pad;
6162
6163        if (mMaxMode == LINES) {
6164            /*
6165             * Don't cap the hint to a certain number of lines.
6166             * (Do cap it, though, if we have a maximum pixel height.)
6167             */
6168            if (cap) {
6169                if (linecount > mMaximum) {
6170                    desired = layout.getLineTop(mMaximum);
6171
6172                    if (dr != null) {
6173                        desired = Math.max(desired, dr.mDrawableHeightLeft);
6174                        desired = Math.max(desired, dr.mDrawableHeightRight);
6175                    }
6176
6177                    desired += pad;
6178                    linecount = mMaximum;
6179                }
6180            }
6181        } else {
6182            desired = Math.min(desired, mMaximum);
6183        }
6184
6185        if (mMinMode == LINES) {
6186            if (linecount < mMinimum) {
6187                desired += getLineHeight() * (mMinimum - linecount);
6188            }
6189        } else {
6190            desired = Math.max(desired, mMinimum);
6191        }
6192
6193        // Check against our minimum height
6194        desired = Math.max(desired, getSuggestedMinimumHeight());
6195
6196        return desired;
6197    }
6198
6199    /**
6200     * Check whether a change to the existing text layout requires a
6201     * new view layout.
6202     */
6203    private void checkForResize() {
6204        boolean sizeChanged = false;
6205
6206        if (mLayout != null) {
6207            // Check if our width changed
6208            if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) {
6209                sizeChanged = true;
6210                invalidate();
6211            }
6212
6213            // Check if our height changed
6214            if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) {
6215                int desiredHeight = getDesiredHeight();
6216
6217                if (desiredHeight != this.getHeight()) {
6218                    sizeChanged = true;
6219                }
6220            } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) {
6221                if (mDesiredHeightAtMeasure >= 0) {
6222                    int desiredHeight = getDesiredHeight();
6223
6224                    if (desiredHeight != mDesiredHeightAtMeasure) {
6225                        sizeChanged = true;
6226                    }
6227                }
6228            }
6229        }
6230
6231        if (sizeChanged) {
6232            requestLayout();
6233            // caller will have already invalidated
6234        }
6235    }
6236
6237    /**
6238     * Check whether entirely new text requires a new view layout
6239     * or merely a new text layout.
6240     */
6241    private void checkForRelayout() {
6242        // If we have a fixed width, we can just swap in a new text layout
6243        // if the text height stays the same or if the view height is fixed.
6244
6245        if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT ||
6246                (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) &&
6247                (mHint == null || mHintLayout != null) &&
6248                (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) {
6249            // Static width, so try making a new text layout.
6250
6251            int oldht = mLayout.getHeight();
6252            int want = mLayout.getWidth();
6253            int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();
6254
6255            /*
6256             * No need to bring the text into view, since the size is not
6257             * changing (unless we do the requestLayout(), in which case it
6258             * will happen at measure).
6259             */
6260            makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
6261                          mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(),
6262                          false);
6263
6264            if (mEllipsize != TextUtils.TruncateAt.MARQUEE) {
6265                // In a fixed-height view, so use our new text layout.
6266                if (mLayoutParams.height != LayoutParams.WRAP_CONTENT &&
6267                    mLayoutParams.height != LayoutParams.MATCH_PARENT) {
6268                    invalidate();
6269                    return;
6270                }
6271
6272                // Dynamic height, but height has stayed the same,
6273                // so use our new text layout.
6274                if (mLayout.getHeight() == oldht &&
6275                    (mHintLayout == null || mHintLayout.getHeight() == oldht)) {
6276                    invalidate();
6277                    return;
6278                }
6279            }
6280
6281            // We lose: the height has changed and we have a dynamic height.
6282            // Request a new view layout using our new text layout.
6283            requestLayout();
6284            invalidate();
6285        } else {
6286            // Dynamic width, so we have no choice but to request a new
6287            // view layout with a new text layout.
6288            nullLayouts();
6289            requestLayout();
6290            invalidate();
6291        }
6292    }
6293
6294    @Override
6295    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
6296        super.onLayout(changed, left, top, right, bottom);
6297        if (changed && mEditor != null) mEditor.invalidateTextDisplayList();
6298    }
6299
6300    private boolean isShowingHint() {
6301        return TextUtils.isEmpty(mText) && !TextUtils.isEmpty(mHint);
6302    }
6303
6304    /**
6305     * Returns true if anything changed.
6306     */
6307    private boolean bringTextIntoView() {
6308        Layout layout = isShowingHint() ? mHintLayout : mLayout;
6309        int line = 0;
6310        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
6311            line = layout.getLineCount() - 1;
6312        }
6313
6314        Layout.Alignment a = layout.getParagraphAlignment(line);
6315        int dir = layout.getParagraphDirection(line);
6316        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6317        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6318        int ht = layout.getHeight();
6319
6320        int scrollx, scrolly;
6321
6322        // Convert to left, center, or right alignment.
6323        if (a == Layout.Alignment.ALIGN_NORMAL) {
6324            a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_LEFT :
6325                Layout.Alignment.ALIGN_RIGHT;
6326        } else if (a == Layout.Alignment.ALIGN_OPPOSITE){
6327            a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_RIGHT :
6328                Layout.Alignment.ALIGN_LEFT;
6329        }
6330
6331        if (a == Layout.Alignment.ALIGN_CENTER) {
6332            /*
6333             * Keep centered if possible, or, if it is too wide to fit,
6334             * keep leading edge in view.
6335             */
6336
6337            int left = (int) FloatMath.floor(layout.getLineLeft(line));
6338            int right = (int) FloatMath.ceil(layout.getLineRight(line));
6339
6340            if (right - left < hspace) {
6341                scrollx = (right + left) / 2 - hspace / 2;
6342            } else {
6343                if (dir < 0) {
6344                    scrollx = right - hspace;
6345                } else {
6346                    scrollx = left;
6347                }
6348            }
6349        } else if (a == Layout.Alignment.ALIGN_RIGHT) {
6350            int right = (int) FloatMath.ceil(layout.getLineRight(line));
6351            scrollx = right - hspace;
6352        } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default)
6353            scrollx = (int) FloatMath.floor(layout.getLineLeft(line));
6354        }
6355
6356        if (ht < vspace) {
6357            scrolly = 0;
6358        } else {
6359            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
6360                scrolly = ht - vspace;
6361            } else {
6362                scrolly = 0;
6363            }
6364        }
6365
6366        if (scrollx != mScrollX || scrolly != mScrollY) {
6367            scrollTo(scrollx, scrolly);
6368            return true;
6369        } else {
6370            return false;
6371        }
6372    }
6373
6374    /**
6375     * Move the point, specified by the offset, into the view if it is needed.
6376     * This has to be called after layout. Returns true if anything changed.
6377     */
6378    public boolean bringPointIntoView(int offset) {
6379        boolean changed = false;
6380
6381        Layout layout = isShowingHint() ? mHintLayout: mLayout;
6382
6383        if (layout == null) return changed;
6384
6385        int line = layout.getLineForOffset(offset);
6386
6387        // FIXME: Is it okay to truncate this, or should we round?
6388        final int x = (int)layout.getPrimaryHorizontal(offset);
6389        final int top = layout.getLineTop(line);
6390        final int bottom = layout.getLineTop(line + 1);
6391
6392        int left = (int) FloatMath.floor(layout.getLineLeft(line));
6393        int right = (int) FloatMath.ceil(layout.getLineRight(line));
6394        int ht = layout.getHeight();
6395
6396        int grav;
6397
6398        switch (layout.getParagraphAlignment(line)) {
6399            case ALIGN_LEFT:
6400                grav = 1;
6401                break;
6402            case ALIGN_RIGHT:
6403                grav = -1;
6404                break;
6405            case ALIGN_NORMAL:
6406                grav = layout.getParagraphDirection(line);
6407                break;
6408            case ALIGN_OPPOSITE:
6409                grav = -layout.getParagraphDirection(line);
6410                break;
6411            case ALIGN_CENTER:
6412            default:
6413                grav = 0;
6414                break;
6415        }
6416
6417        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6418        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6419
6420        int hslack = (bottom - top) / 2;
6421        int vslack = hslack;
6422
6423        if (vslack > vspace / 4)
6424            vslack = vspace / 4;
6425        if (hslack > hspace / 4)
6426            hslack = hspace / 4;
6427
6428        int hs = mScrollX;
6429        int vs = mScrollY;
6430
6431        if (top - vs < vslack)
6432            vs = top - vslack;
6433        if (bottom - vs > vspace - vslack)
6434            vs = bottom - (vspace - vslack);
6435        if (ht - vs < vspace)
6436            vs = ht - vspace;
6437        if (0 - vs > 0)
6438            vs = 0;
6439
6440        if (grav != 0) {
6441            if (x - hs < hslack) {
6442                hs = x - hslack;
6443            }
6444            if (x - hs > hspace - hslack) {
6445                hs = x - (hspace - hslack);
6446            }
6447        }
6448
6449        if (grav < 0) {
6450            if (left - hs > 0)
6451                hs = left;
6452            if (right - hs < hspace)
6453                hs = right - hspace;
6454        } else if (grav > 0) {
6455            if (right - hs < hspace)
6456                hs = right - hspace;
6457            if (left - hs > 0)
6458                hs = left;
6459        } else /* grav == 0 */ {
6460            if (right - left <= hspace) {
6461                /*
6462                 * If the entire text fits, center it exactly.
6463                 */
6464                hs = left - (hspace - (right - left)) / 2;
6465            } else if (x > right - hslack) {
6466                /*
6467                 * If we are near the right edge, keep the right edge
6468                 * at the edge of the view.
6469                 */
6470                hs = right - hspace;
6471            } else if (x < left + hslack) {
6472                /*
6473                 * If we are near the left edge, keep the left edge
6474                 * at the edge of the view.
6475                 */
6476                hs = left;
6477            } else if (left > hs) {
6478                /*
6479                 * Is there whitespace visible at the left?  Fix it if so.
6480                 */
6481                hs = left;
6482            } else if (right < hs + hspace) {
6483                /*
6484                 * Is there whitespace visible at the right?  Fix it if so.
6485                 */
6486                hs = right - hspace;
6487            } else {
6488                /*
6489                 * Otherwise, float as needed.
6490                 */
6491                if (x - hs < hslack) {
6492                    hs = x - hslack;
6493                }
6494                if (x - hs > hspace - hslack) {
6495                    hs = x - (hspace - hslack);
6496                }
6497            }
6498        }
6499
6500        if (hs != mScrollX || vs != mScrollY) {
6501            if (mScroller == null) {
6502                scrollTo(hs, vs);
6503            } else {
6504                long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
6505                int dx = hs - mScrollX;
6506                int dy = vs - mScrollY;
6507
6508                if (duration > ANIMATED_SCROLL_GAP) {
6509                    mScroller.startScroll(mScrollX, mScrollY, dx, dy);
6510                    awakenScrollBars(mScroller.getDuration());
6511                    invalidate();
6512                } else {
6513                    if (!mScroller.isFinished()) {
6514                        mScroller.abortAnimation();
6515                    }
6516
6517                    scrollBy(dx, dy);
6518                }
6519
6520                mLastScroll = AnimationUtils.currentAnimationTimeMillis();
6521            }
6522
6523            changed = true;
6524        }
6525
6526        if (isFocused()) {
6527            // This offsets because getInterestingRect() is in terms of viewport coordinates, but
6528            // requestRectangleOnScreen() is in terms of content coordinates.
6529
6530            // The offsets here are to ensure the rectangle we are using is
6531            // within our view bounds, in case the cursor is on the far left
6532            // or right.  If it isn't withing the bounds, then this request
6533            // will be ignored.
6534            if (mTempRect == null) mTempRect = new Rect();
6535            mTempRect.set(x - 2, top, x + 2, bottom);
6536            getInterestingRect(mTempRect, line);
6537            mTempRect.offset(mScrollX, mScrollY);
6538
6539            if (requestRectangleOnScreen(mTempRect)) {
6540                changed = true;
6541            }
6542        }
6543
6544        return changed;
6545    }
6546
6547    /**
6548     * Move the cursor, if needed, so that it is at an offset that is visible
6549     * to the user.  This will not move the cursor if it represents more than
6550     * one character (a selection range).  This will only work if the
6551     * TextView contains spannable text; otherwise it will do nothing.
6552     *
6553     * @return True if the cursor was actually moved, false otherwise.
6554     */
6555    public boolean moveCursorToVisibleOffset() {
6556        if (!(mText instanceof Spannable)) {
6557            return false;
6558        }
6559        int start = getSelectionStart();
6560        int end = getSelectionEnd();
6561        if (start != end) {
6562            return false;
6563        }
6564
6565        // First: make sure the line is visible on screen:
6566
6567        int line = mLayout.getLineForOffset(start);
6568
6569        final int top = mLayout.getLineTop(line);
6570        final int bottom = mLayout.getLineTop(line + 1);
6571        final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6572        int vslack = (bottom - top) / 2;
6573        if (vslack > vspace / 4)
6574            vslack = vspace / 4;
6575        final int vs = mScrollY;
6576
6577        if (top < (vs+vslack)) {
6578            line = mLayout.getLineForVertical(vs+vslack+(bottom-top));
6579        } else if (bottom > (vspace+vs-vslack)) {
6580            line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top));
6581        }
6582
6583        // Next: make sure the character is visible on screen:
6584
6585        final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6586        final int hs = mScrollX;
6587        final int leftChar = mLayout.getOffsetForHorizontal(line, hs);
6588        final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs);
6589
6590        // line might contain bidirectional text
6591        final int lowChar = leftChar < rightChar ? leftChar : rightChar;
6592        final int highChar = leftChar > rightChar ? leftChar : rightChar;
6593
6594        int newStart = start;
6595        if (newStart < lowChar) {
6596            newStart = lowChar;
6597        } else if (newStart > highChar) {
6598            newStart = highChar;
6599        }
6600
6601        if (newStart != start) {
6602            Selection.setSelection((Spannable)mText, newStart);
6603            return true;
6604        }
6605
6606        return false;
6607    }
6608
6609    @Override
6610    public void computeScroll() {
6611        if (mScroller != null) {
6612            if (mScroller.computeScrollOffset()) {
6613                mScrollX = mScroller.getCurrX();
6614                mScrollY = mScroller.getCurrY();
6615                invalidateParentCaches();
6616                postInvalidate();  // So we draw again
6617            }
6618        }
6619    }
6620
6621    private void getInterestingRect(Rect r, int line) {
6622        convertFromViewportToContentCoordinates(r);
6623
6624        // Rectangle can can be expanded on first and last line to take
6625        // padding into account.
6626        // TODO Take left/right padding into account too?
6627        if (line == 0) r.top -= getExtendedPaddingTop();
6628        if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom();
6629    }
6630
6631    private void convertFromViewportToContentCoordinates(Rect r) {
6632        final int horizontalOffset = viewportToContentHorizontalOffset();
6633        r.left += horizontalOffset;
6634        r.right += horizontalOffset;
6635
6636        final int verticalOffset = viewportToContentVerticalOffset();
6637        r.top += verticalOffset;
6638        r.bottom += verticalOffset;
6639    }
6640
6641    int viewportToContentHorizontalOffset() {
6642        return getCompoundPaddingLeft() - mScrollX;
6643    }
6644
6645    int viewportToContentVerticalOffset() {
6646        int offset = getExtendedPaddingTop() - mScrollY;
6647        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
6648            offset += getVerticalOffset(false);
6649        }
6650        return offset;
6651    }
6652
6653    @Override
6654    public void debug(int depth) {
6655        super.debug(depth);
6656
6657        String output = debugIndent(depth);
6658        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
6659                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
6660                + "} ";
6661
6662        if (mText != null) {
6663
6664            output += "mText=\"" + mText + "\" ";
6665            if (mLayout != null) {
6666                output += "mLayout width=" + mLayout.getWidth()
6667                        + " height=" + mLayout.getHeight();
6668            }
6669        } else {
6670            output += "mText=NULL";
6671        }
6672        Log.d(VIEW_LOG_TAG, output);
6673    }
6674
6675    /**
6676     * Convenience for {@link Selection#getSelectionStart}.
6677     */
6678    @ViewDebug.ExportedProperty(category = "text")
6679    public int getSelectionStart() {
6680        return Selection.getSelectionStart(getText());
6681    }
6682
6683    /**
6684     * Convenience for {@link Selection#getSelectionEnd}.
6685     */
6686    @ViewDebug.ExportedProperty(category = "text")
6687    public int getSelectionEnd() {
6688        return Selection.getSelectionEnd(getText());
6689    }
6690
6691    /**
6692     * Return true iff there is a selection inside this text view.
6693     */
6694    public boolean hasSelection() {
6695        final int selectionStart = getSelectionStart();
6696        final int selectionEnd = getSelectionEnd();
6697
6698        return selectionStart >= 0 && selectionStart != selectionEnd;
6699    }
6700
6701    /**
6702     * Sets the properties of this field (lines, horizontally scrolling,
6703     * transformation method) to be for a single-line input.
6704     *
6705     * @attr ref android.R.styleable#TextView_singleLine
6706     */
6707    public void setSingleLine() {
6708        setSingleLine(true);
6709    }
6710
6711    /**
6712     * Sets the properties of this field to transform input to ALL CAPS
6713     * display. This may use a "small caps" formatting if available.
6714     * This setting will be ignored if this field is editable or selectable.
6715     *
6716     * This call replaces the current transformation method. Disabling this
6717     * will not necessarily restore the previous behavior from before this
6718     * was enabled.
6719     *
6720     * @see #setTransformationMethod(TransformationMethod)
6721     * @attr ref android.R.styleable#TextView_textAllCaps
6722     */
6723    public void setAllCaps(boolean allCaps) {
6724        if (allCaps) {
6725            setTransformationMethod(new AllCapsTransformationMethod(getContext()));
6726        } else {
6727            setTransformationMethod(null);
6728        }
6729    }
6730
6731    /**
6732     * If true, sets the properties of this field (number of lines, horizontally scrolling,
6733     * transformation method) to be for a single-line input; if false, restores these to the default
6734     * conditions.
6735     *
6736     * Note that the default conditions are not necessarily those that were in effect prior this
6737     * method, and you may want to reset these properties to your custom values.
6738     *
6739     * @attr ref android.R.styleable#TextView_singleLine
6740     */
6741    @android.view.RemotableViewMethod
6742    public void setSingleLine(boolean singleLine) {
6743        // Could be used, but may break backward compatibility.
6744        // if (mSingleLine == singleLine) return;
6745        setInputTypeSingleLine(singleLine);
6746        applySingleLine(singleLine, true, true);
6747    }
6748
6749    /**
6750     * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType.
6751     * @param singleLine
6752     */
6753    private void setInputTypeSingleLine(boolean singleLine) {
6754        if (mEditor != null &&
6755                (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
6756            if (singleLine) {
6757                mEditor.mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
6758            } else {
6759                mEditor.mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
6760            }
6761        }
6762    }
6763
6764    private void applySingleLine(boolean singleLine, boolean applyTransformation,
6765            boolean changeMaxLines) {
6766        mSingleLine = singleLine;
6767        if (singleLine) {
6768            setLines(1);
6769            setHorizontallyScrolling(true);
6770            if (applyTransformation) {
6771                setTransformationMethod(SingleLineTransformationMethod.getInstance());
6772            }
6773        } else {
6774            if (changeMaxLines) {
6775                setMaxLines(Integer.MAX_VALUE);
6776            }
6777            setHorizontallyScrolling(false);
6778            if (applyTransformation) {
6779                setTransformationMethod(null);
6780            }
6781        }
6782    }
6783
6784    /**
6785     * Causes words in the text that are longer than the view is wide
6786     * to be ellipsized instead of broken in the middle.  You may also
6787     * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling}
6788     * to constrain the text to a single line.  Use <code>null</code>
6789     * to turn off ellipsizing.
6790     *
6791     * If {@link #setMaxLines} has been used to set two or more lines,
6792     * {@link android.text.TextUtils.TruncateAt#END} and
6793     * {@link android.text.TextUtils.TruncateAt#MARQUEE}* are only supported
6794     * (other ellipsizing types will not do anything).
6795     *
6796     * @attr ref android.R.styleable#TextView_ellipsize
6797     */
6798    public void setEllipsize(TextUtils.TruncateAt where) {
6799        // TruncateAt is an enum. != comparison is ok between these singleton objects.
6800        if (mEllipsize != where) {
6801            mEllipsize = where;
6802
6803            if (mLayout != null) {
6804                nullLayouts();
6805                requestLayout();
6806                invalidate();
6807            }
6808        }
6809    }
6810
6811    /**
6812     * Sets how many times to repeat the marquee animation. Only applied if the
6813     * TextView has marquee enabled. Set to -1 to repeat indefinitely.
6814     *
6815     * @see #getMarqueeRepeatLimit()
6816     *
6817     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
6818     */
6819    public void setMarqueeRepeatLimit(int marqueeLimit) {
6820        mMarqueeRepeatLimit = marqueeLimit;
6821    }
6822
6823    /**
6824     * Gets the number of times the marquee animation is repeated. Only meaningful if the
6825     * TextView has marquee enabled.
6826     *
6827     * @return the number of times the marquee animation is repeated. -1 if the animation
6828     * repeats indefinitely
6829     *
6830     * @see #setMarqueeRepeatLimit(int)
6831     *
6832     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
6833     */
6834    public int getMarqueeRepeatLimit() {
6835        return mMarqueeRepeatLimit;
6836    }
6837
6838    /**
6839     * Returns where, if anywhere, words that are longer than the view
6840     * is wide should be ellipsized.
6841     */
6842    @ViewDebug.ExportedProperty
6843    public TextUtils.TruncateAt getEllipsize() {
6844        return mEllipsize;
6845    }
6846
6847    /**
6848     * Set the TextView so that when it takes focus, all the text is
6849     * selected.
6850     *
6851     * @attr ref android.R.styleable#TextView_selectAllOnFocus
6852     */
6853    @android.view.RemotableViewMethod
6854    public void setSelectAllOnFocus(boolean selectAllOnFocus) {
6855        createEditorIfNeeded();
6856        mEditor.mSelectAllOnFocus = selectAllOnFocus;
6857
6858        if (selectAllOnFocus && !(mText instanceof Spannable)) {
6859            setText(mText, BufferType.SPANNABLE);
6860        }
6861    }
6862
6863    /**
6864     * Set whether the cursor is visible. The default is true. Note that this property only
6865     * makes sense for editable TextView.
6866     *
6867     * @see #isCursorVisible()
6868     *
6869     * @attr ref android.R.styleable#TextView_cursorVisible
6870     */
6871    @android.view.RemotableViewMethod
6872    public void setCursorVisible(boolean visible) {
6873        if (visible && mEditor == null) return; // visible is the default value with no edit data
6874        createEditorIfNeeded();
6875        if (mEditor.mCursorVisible != visible) {
6876            mEditor.mCursorVisible = visible;
6877            invalidate();
6878
6879            mEditor.makeBlink();
6880
6881            // InsertionPointCursorController depends on mCursorVisible
6882            mEditor.prepareCursorControllers();
6883        }
6884    }
6885
6886    /**
6887     * @return whether or not the cursor is visible (assuming this TextView is editable)
6888     *
6889     * @see #setCursorVisible(boolean)
6890     *
6891     * @attr ref android.R.styleable#TextView_cursorVisible
6892     */
6893    public boolean isCursorVisible() {
6894        // true is the default value
6895        return mEditor == null ? true : mEditor.mCursorVisible;
6896    }
6897
6898    private boolean canMarquee() {
6899        int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight());
6900        return width > 0 && (mLayout.getLineWidth(0) > width ||
6901                (mMarqueeFadeMode != MARQUEE_FADE_NORMAL && mSavedMarqueeModeLayout != null &&
6902                        mSavedMarqueeModeLayout.getLineWidth(0) > width));
6903    }
6904
6905    private void startMarquee() {
6906        // Do not ellipsize EditText
6907        if (getKeyListener() != null) return;
6908
6909        if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
6910            return;
6911        }
6912
6913        if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) &&
6914                getLineCount() == 1 && canMarquee()) {
6915
6916            if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
6917                mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_FADE;
6918                final Layout tmp = mLayout;
6919                mLayout = mSavedMarqueeModeLayout;
6920                mSavedMarqueeModeLayout = tmp;
6921                setHorizontalFadingEdgeEnabled(true);
6922                requestLayout();
6923                invalidate();
6924            }
6925
6926            if (mMarquee == null) mMarquee = new Marquee(this);
6927            mMarquee.start(mMarqueeRepeatLimit);
6928        }
6929    }
6930
6931    private void stopMarquee() {
6932        if (mMarquee != null && !mMarquee.isStopped()) {
6933            mMarquee.stop();
6934        }
6935
6936        if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_FADE) {
6937            mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS;
6938            final Layout tmp = mSavedMarqueeModeLayout;
6939            mSavedMarqueeModeLayout = mLayout;
6940            mLayout = tmp;
6941            setHorizontalFadingEdgeEnabled(false);
6942            requestLayout();
6943            invalidate();
6944        }
6945    }
6946
6947    private void startStopMarquee(boolean start) {
6948        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6949            if (start) {
6950                startMarquee();
6951            } else {
6952                stopMarquee();
6953            }
6954        }
6955    }
6956
6957    /**
6958     * This method is called when the text is changed, in case any subclasses
6959     * would like to know.
6960     *
6961     * Within <code>text</code>, the <code>lengthAfter</code> characters
6962     * beginning at <code>start</code> have just replaced old text that had
6963     * length <code>lengthBefore</code>. It is an error to attempt to make
6964     * changes to <code>text</code> from this callback.
6965     *
6966     * @param text The text the TextView is displaying
6967     * @param start The offset of the start of the range of the text that was
6968     * modified
6969     * @param lengthBefore The length of the former text that has been replaced
6970     * @param lengthAfter The length of the replacement modified text
6971     */
6972    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
6973        // intentionally empty, template pattern method can be overridden by subclasses
6974    }
6975
6976    /**
6977     * This method is called when the selection has changed, in case any
6978     * subclasses would like to know.
6979     *
6980     * @param selStart The new selection start location.
6981     * @param selEnd The new selection end location.
6982     */
6983    protected void onSelectionChanged(int selStart, int selEnd) {
6984        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
6985    }
6986
6987    /**
6988     * Adds a TextWatcher to the list of those whose methods are called
6989     * whenever this TextView's text changes.
6990     * <p>
6991     * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
6992     * not called after {@link #setText} calls.  Now, doing {@link #setText}
6993     * if there are any text changed listeners forces the buffer type to
6994     * Editable if it would not otherwise be and does call this method.
6995     */
6996    public void addTextChangedListener(TextWatcher watcher) {
6997        if (mListeners == null) {
6998            mListeners = new ArrayList<TextWatcher>();
6999        }
7000
7001        mListeners.add(watcher);
7002    }
7003
7004    /**
7005     * Removes the specified TextWatcher from the list of those whose
7006     * methods are called
7007     * whenever this TextView's text changes.
7008     */
7009    public void removeTextChangedListener(TextWatcher watcher) {
7010        if (mListeners != null) {
7011            int i = mListeners.indexOf(watcher);
7012
7013            if (i >= 0) {
7014                mListeners.remove(i);
7015            }
7016        }
7017    }
7018
7019    private void sendBeforeTextChanged(CharSequence text, int start, int before, int after) {
7020        if (mListeners != null) {
7021            final ArrayList<TextWatcher> list = mListeners;
7022            final int count = list.size();
7023            for (int i = 0; i < count; i++) {
7024                list.get(i).beforeTextChanged(text, start, before, after);
7025            }
7026        }
7027
7028        // The spans that are inside or intersect the modified region no longer make sense
7029        removeIntersectingSpans(start, start + before, SpellCheckSpan.class);
7030        removeIntersectingSpans(start, start + before, SuggestionSpan.class);
7031    }
7032
7033    // Removes all spans that are inside or actually overlap the start..end range
7034    private <T> void removeIntersectingSpans(int start, int end, Class<T> type) {
7035        if (!(mText instanceof Editable)) return;
7036        Editable text = (Editable) mText;
7037
7038        T[] spans = text.getSpans(start, end, type);
7039        final int length = spans.length;
7040        for (int i = 0; i < length; i++) {
7041            final int s = text.getSpanStart(spans[i]);
7042            final int e = text.getSpanEnd(spans[i]);
7043            // Spans that are adjacent to the edited region will be handled in
7044            // updateSpellCheckSpans. Result depends on what will be added (space or text)
7045            if (e == start || s == end) break;
7046            text.removeSpan(spans[i]);
7047        }
7048    }
7049
7050    /**
7051     * Not private so it can be called from an inner class without going
7052     * through a thunk.
7053     */
7054    void sendOnTextChanged(CharSequence text, int start, int before, int after) {
7055        if (mListeners != null) {
7056            final ArrayList<TextWatcher> list = mListeners;
7057            final int count = list.size();
7058            for (int i = 0; i < count; i++) {
7059                list.get(i).onTextChanged(text, start, before, after);
7060            }
7061        }
7062
7063        if (mEditor != null) mEditor.sendOnTextChanged(start, after);
7064    }
7065
7066    /**
7067     * Not private so it can be called from an inner class without going
7068     * through a thunk.
7069     */
7070    void sendAfterTextChanged(Editable text) {
7071        if (mListeners != null) {
7072            final ArrayList<TextWatcher> list = mListeners;
7073            final int count = list.size();
7074            for (int i = 0; i < count; i++) {
7075                list.get(i).afterTextChanged(text);
7076            }
7077        }
7078    }
7079
7080    void updateAfterEdit() {
7081        invalidate();
7082        int curs = getSelectionStart();
7083
7084        if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
7085            registerForPreDraw();
7086        }
7087
7088        if (curs >= 0) {
7089            mHighlightPathBogus = true;
7090            if (mEditor != null) mEditor.makeBlink();
7091            bringPointIntoView(curs);
7092        }
7093
7094        checkForResize();
7095    }
7096
7097    /**
7098     * Not private so it can be called from an inner class without going
7099     * through a thunk.
7100     */
7101    void handleTextChanged(CharSequence buffer, int start, int before, int after) {
7102        final Editor.InputMethodState ims = mEditor == null ? null : mEditor.mInputMethodState;
7103        if (ims == null || ims.mBatchEditNesting == 0) {
7104            updateAfterEdit();
7105        }
7106        if (ims != null) {
7107            ims.mContentChanged = true;
7108            if (ims.mChangedStart < 0) {
7109                ims.mChangedStart = start;
7110                ims.mChangedEnd = start+before;
7111            } else {
7112                ims.mChangedStart = Math.min(ims.mChangedStart, start);
7113                ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta);
7114            }
7115            ims.mChangedDelta += after-before;
7116        }
7117
7118        sendOnTextChanged(buffer, start, before, after);
7119        onTextChanged(buffer, start, before, after);
7120    }
7121
7122    /**
7123     * Not private so it can be called from an inner class without going
7124     * through a thunk.
7125     */
7126    void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) {
7127        // XXX Make the start and end move together if this ends up
7128        // spending too much time invalidating.
7129
7130        boolean selChanged = false;
7131        int newSelStart=-1, newSelEnd=-1;
7132
7133        final Editor.InputMethodState ims = mEditor == null ? null : mEditor.mInputMethodState;
7134
7135        if (what == Selection.SELECTION_END) {
7136            selChanged = true;
7137            newSelEnd = newStart;
7138
7139            if (oldStart >= 0 || newStart >= 0) {
7140                invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart);
7141                registerForPreDraw();
7142                if (mEditor != null) mEditor.makeBlink();
7143            }
7144        }
7145
7146        if (what == Selection.SELECTION_START) {
7147            selChanged = true;
7148            newSelStart = newStart;
7149
7150            if (oldStart >= 0 || newStart >= 0) {
7151                int end = Selection.getSelectionEnd(buf);
7152                invalidateCursor(end, oldStart, newStart);
7153            }
7154        }
7155
7156        if (selChanged) {
7157            mHighlightPathBogus = true;
7158            if (mEditor != null && !isFocused()) mEditor.mSelectionMoved = true;
7159
7160            if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) {
7161                if (newSelStart < 0) {
7162                    newSelStart = Selection.getSelectionStart(buf);
7163                }
7164                if (newSelEnd < 0) {
7165                    newSelEnd = Selection.getSelectionEnd(buf);
7166                }
7167                onSelectionChanged(newSelStart, newSelEnd);
7168            }
7169        }
7170
7171        if (what instanceof UpdateAppearance || what instanceof ParagraphStyle ||
7172                what instanceof CharacterStyle) {
7173            if (ims == null || ims.mBatchEditNesting == 0) {
7174                invalidate();
7175                mHighlightPathBogus = true;
7176                checkForResize();
7177            } else {
7178                ims.mContentChanged = true;
7179            }
7180            if (mEditor != null) {
7181                if (oldStart >= 0) mEditor.invalidateTextDisplayList(mLayout, oldStart, oldEnd);
7182                if (newStart >= 0) mEditor.invalidateTextDisplayList(mLayout, newStart, newEnd);
7183            }
7184        }
7185
7186        if (MetaKeyKeyListener.isMetaTracker(buf, what)) {
7187            mHighlightPathBogus = true;
7188            if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) {
7189                ims.mSelectionModeChanged = true;
7190            }
7191
7192            if (Selection.getSelectionStart(buf) >= 0) {
7193                if (ims == null || ims.mBatchEditNesting == 0) {
7194                    invalidateCursor();
7195                } else {
7196                    ims.mCursorChanged = true;
7197                }
7198            }
7199        }
7200
7201        if (what instanceof ParcelableSpan) {
7202            // If this is a span that can be sent to a remote process,
7203            // the current extract editor would be interested in it.
7204            if (ims != null && ims.mExtractedTextRequest != null) {
7205                if (ims.mBatchEditNesting != 0) {
7206                    if (oldStart >= 0) {
7207                        if (ims.mChangedStart > oldStart) {
7208                            ims.mChangedStart = oldStart;
7209                        }
7210                        if (ims.mChangedStart > oldEnd) {
7211                            ims.mChangedStart = oldEnd;
7212                        }
7213                    }
7214                    if (newStart >= 0) {
7215                        if (ims.mChangedStart > newStart) {
7216                            ims.mChangedStart = newStart;
7217                        }
7218                        if (ims.mChangedStart > newEnd) {
7219                            ims.mChangedStart = newEnd;
7220                        }
7221                    }
7222                } else {
7223                    if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: "
7224                            + oldStart + "-" + oldEnd + ","
7225                            + newStart + "-" + newEnd + " " + what);
7226                    ims.mContentChanged = true;
7227                }
7228            }
7229        }
7230
7231        if (mEditor != null && mEditor.mSpellChecker != null && newStart < 0 &&
7232                what instanceof SpellCheckSpan) {
7233            mEditor.mSpellChecker.onSpellCheckSpanRemoved((SpellCheckSpan) what);
7234        }
7235    }
7236
7237    /**
7238     * @hide
7239     */
7240    @Override
7241    public void dispatchFinishTemporaryDetach() {
7242        mDispatchTemporaryDetach = true;
7243        super.dispatchFinishTemporaryDetach();
7244        mDispatchTemporaryDetach = false;
7245    }
7246
7247    @Override
7248    public void onStartTemporaryDetach() {
7249        super.onStartTemporaryDetach();
7250        // Only track when onStartTemporaryDetach() is called directly,
7251        // usually because this instance is an editable field in a list
7252        if (!mDispatchTemporaryDetach) mTemporaryDetach = true;
7253
7254        // Tell the editor that we are temporarily detached. It can use this to preserve
7255        // selection state as needed.
7256        if (mEditor != null) mEditor.mTemporaryDetach = true;
7257    }
7258
7259    @Override
7260    public void onFinishTemporaryDetach() {
7261        super.onFinishTemporaryDetach();
7262        // Only track when onStartTemporaryDetach() is called directly,
7263        // usually because this instance is an editable field in a list
7264        if (!mDispatchTemporaryDetach) mTemporaryDetach = false;
7265        if (mEditor != null) mEditor.mTemporaryDetach = false;
7266    }
7267
7268    @Override
7269    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
7270        if (mTemporaryDetach) {
7271            // If we are temporarily in the detach state, then do nothing.
7272            super.onFocusChanged(focused, direction, previouslyFocusedRect);
7273            return;
7274        }
7275
7276        if (mEditor != null) mEditor.onFocusChanged(focused, direction);
7277
7278        if (focused) {
7279            if (mText instanceof Spannable) {
7280                Spannable sp = (Spannable) mText;
7281                MetaKeyKeyListener.resetMetaState(sp);
7282            }
7283        }
7284
7285        startStopMarquee(focused);
7286
7287        if (mTransformation != null) {
7288            mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect);
7289        }
7290
7291        super.onFocusChanged(focused, direction, previouslyFocusedRect);
7292    }
7293
7294    @Override
7295    public void onWindowFocusChanged(boolean hasWindowFocus) {
7296        super.onWindowFocusChanged(hasWindowFocus);
7297
7298        if (mEditor != null) mEditor.onWindowFocusChanged(hasWindowFocus);
7299
7300        startStopMarquee(hasWindowFocus);
7301    }
7302
7303    @Override
7304    protected void onVisibilityChanged(View changedView, int visibility) {
7305        super.onVisibilityChanged(changedView, visibility);
7306        if (mEditor != null && visibility != VISIBLE) {
7307            mEditor.hideControllers();
7308        }
7309    }
7310
7311    /**
7312     * Use {@link BaseInputConnection#removeComposingSpans
7313     * BaseInputConnection.removeComposingSpans()} to remove any IME composing
7314     * state from this text view.
7315     */
7316    public void clearComposingText() {
7317        if (mText instanceof Spannable) {
7318            BaseInputConnection.removeComposingSpans((Spannable)mText);
7319        }
7320    }
7321
7322    @Override
7323    public void setSelected(boolean selected) {
7324        boolean wasSelected = isSelected();
7325
7326        super.setSelected(selected);
7327
7328        if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
7329            if (selected) {
7330                startMarquee();
7331            } else {
7332                stopMarquee();
7333            }
7334        }
7335    }
7336
7337    @Override
7338    public boolean onTouchEvent(MotionEvent event) {
7339        final int action = event.getActionMasked();
7340
7341        if (mEditor != null) mEditor.onTouchEvent(event);
7342
7343        final boolean superResult = super.onTouchEvent(event);
7344
7345        /*
7346         * Don't handle the release after a long press, because it will
7347         * move the selection away from whatever the menu action was
7348         * trying to affect.
7349         */
7350        if (mEditor != null && mEditor.mDiscardNextActionUp && action == MotionEvent.ACTION_UP) {
7351            mEditor.mDiscardNextActionUp = false;
7352            return superResult;
7353        }
7354
7355        final boolean touchIsFinished = (action == MotionEvent.ACTION_UP) &&
7356                (mEditor == null || !mEditor.mIgnoreActionUpEvent) && isFocused();
7357
7358         if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()
7359                && mText instanceof Spannable && mLayout != null) {
7360            boolean handled = false;
7361
7362            if (mMovement != null) {
7363                handled |= mMovement.onTouchEvent(this, (Spannable) mText, event);
7364            }
7365
7366            final boolean textIsSelectable = isTextSelectable();
7367            if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && textIsSelectable) {
7368                // The LinkMovementMethod which should handle taps on links has not been installed
7369                // on non editable text that support text selection.
7370                // We reproduce its behavior here to open links for these.
7371                ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(),
7372                        getSelectionEnd(), ClickableSpan.class);
7373
7374                if (links.length > 0) {
7375                    links[0].onClick(this);
7376                    handled = true;
7377                }
7378            }
7379
7380            if (touchIsFinished && (isTextEditable() || textIsSelectable)) {
7381                // Show the IME, except when selecting in read-only text.
7382                final InputMethodManager imm = InputMethodManager.peekInstance();
7383                viewClicked(imm);
7384                if (!textIsSelectable && mEditor.mShowSoftInputOnFocus) {
7385                    handled |= imm != null && imm.showSoftInput(this, 0);
7386                }
7387
7388                // The above condition ensures that the mEditor is not null
7389                mEditor.onTouchUpEvent(event);
7390
7391                handled = true;
7392            }
7393
7394            if (handled) {
7395                return true;
7396            }
7397        }
7398
7399        return superResult;
7400    }
7401
7402    @Override
7403    public boolean onGenericMotionEvent(MotionEvent event) {
7404        if (mMovement != null && mText instanceof Spannable && mLayout != null) {
7405            try {
7406                if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) {
7407                    return true;
7408                }
7409            } catch (AbstractMethodError ex) {
7410                // onGenericMotionEvent was added to the MovementMethod interface in API 12.
7411                // Ignore its absence in case third party applications implemented the
7412                // interface directly.
7413            }
7414        }
7415        return super.onGenericMotionEvent(event);
7416    }
7417
7418    /**
7419     * @return True iff this TextView contains a text that can be edited, or if this is
7420     * a selectable TextView.
7421     */
7422    boolean isTextEditable() {
7423        return mText instanceof Editable && onCheckIsTextEditor() && isEnabled();
7424    }
7425
7426    /**
7427     * Returns true, only while processing a touch gesture, if the initial
7428     * touch down event caused focus to move to the text view and as a result
7429     * its selection changed.  Only valid while processing the touch gesture
7430     * of interest, in an editable text view.
7431     */
7432    public boolean didTouchFocusSelect() {
7433        return mEditor != null && mEditor.mTouchFocusSelected;
7434    }
7435
7436    @Override
7437    public void cancelLongPress() {
7438        super.cancelLongPress();
7439        if (mEditor != null) mEditor.mIgnoreActionUpEvent = true;
7440    }
7441
7442    @Override
7443    public boolean onTrackballEvent(MotionEvent event) {
7444        if (mMovement != null && mText instanceof Spannable && mLayout != null) {
7445            if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) {
7446                return true;
7447            }
7448        }
7449
7450        return super.onTrackballEvent(event);
7451    }
7452
7453    public void setScroller(Scroller s) {
7454        mScroller = s;
7455    }
7456
7457    @Override
7458    protected float getLeftFadingEdgeStrength() {
7459        if (mEllipsize == TextUtils.TruncateAt.MARQUEE &&
7460                mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
7461            if (mMarquee != null && !mMarquee.isStopped()) {
7462                final Marquee marquee = mMarquee;
7463                if (marquee.shouldDrawLeftFade()) {
7464                    final float scroll = marquee.getScroll();
7465                    return scroll / getHorizontalFadingEdgeLength();
7466                } else {
7467                    return 0.0f;
7468                }
7469            } else if (getLineCount() == 1) {
7470                final int layoutDirection = getResolvedLayoutDirection();
7471                final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
7472                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
7473                    case Gravity.LEFT:
7474                        return 0.0f;
7475                    case Gravity.RIGHT:
7476                        return (mLayout.getLineRight(0) - (mRight - mLeft) -
7477                                getCompoundPaddingLeft() - getCompoundPaddingRight() -
7478                                mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength();
7479                    case Gravity.CENTER_HORIZONTAL:
7480                        return 0.0f;
7481                }
7482            }
7483        }
7484        return super.getLeftFadingEdgeStrength();
7485    }
7486
7487    @Override
7488    protected float getRightFadingEdgeStrength() {
7489        if (mEllipsize == TextUtils.TruncateAt.MARQUEE &&
7490                mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
7491            if (mMarquee != null && !mMarquee.isStopped()) {
7492                final Marquee marquee = mMarquee;
7493                final float maxFadeScroll = marquee.getMaxFadeScroll();
7494                final float scroll = marquee.getScroll();
7495                return (maxFadeScroll - scroll) / getHorizontalFadingEdgeLength();
7496            } else if (getLineCount() == 1) {
7497                final int layoutDirection = getResolvedLayoutDirection();
7498                final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
7499                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
7500                    case Gravity.LEFT:
7501                        final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() -
7502                                getCompoundPaddingRight();
7503                        final float lineWidth = mLayout.getLineWidth(0);
7504                        return (lineWidth - textWidth) / getHorizontalFadingEdgeLength();
7505                    case Gravity.RIGHT:
7506                        return 0.0f;
7507                    case Gravity.CENTER_HORIZONTAL:
7508                    case Gravity.FILL_HORIZONTAL:
7509                        return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
7510                                getCompoundPaddingLeft() - getCompoundPaddingRight())) /
7511                                getHorizontalFadingEdgeLength();
7512                }
7513            }
7514        }
7515        return super.getRightFadingEdgeStrength();
7516    }
7517
7518    @Override
7519    protected int computeHorizontalScrollRange() {
7520        if (mLayout != null) {
7521            return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ?
7522                    (int) mLayout.getLineWidth(0) : mLayout.getWidth();
7523        }
7524
7525        return super.computeHorizontalScrollRange();
7526    }
7527
7528    @Override
7529    protected int computeVerticalScrollRange() {
7530        if (mLayout != null)
7531            return mLayout.getHeight();
7532
7533        return super.computeVerticalScrollRange();
7534    }
7535
7536    @Override
7537    protected int computeVerticalScrollExtent() {
7538        return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
7539    }
7540
7541    @Override
7542    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
7543        super.findViewsWithText(outViews, searched, flags);
7544        if (!outViews.contains(this) && (flags & FIND_VIEWS_WITH_TEXT) != 0
7545                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mText)) {
7546            String searchedLowerCase = searched.toString().toLowerCase();
7547            String textLowerCase = mText.toString().toLowerCase();
7548            if (textLowerCase.contains(searchedLowerCase)) {
7549                outViews.add(this);
7550            }
7551        }
7552    }
7553
7554    public enum BufferType {
7555        NORMAL, SPANNABLE, EDITABLE,
7556    }
7557
7558    /**
7559     * Returns the TextView_textColor attribute from the
7560     * Resources.StyledAttributes, if set, or the TextAppearance_textColor
7561     * from the TextView_textAppearance attribute, if TextView_textColor
7562     * was not set directly.
7563     */
7564    public static ColorStateList getTextColors(Context context, TypedArray attrs) {
7565        ColorStateList colors;
7566        colors = attrs.getColorStateList(com.android.internal.R.styleable.
7567                                         TextView_textColor);
7568
7569        if (colors == null) {
7570            int ap = attrs.getResourceId(com.android.internal.R.styleable.
7571                                         TextView_textAppearance, -1);
7572            if (ap != -1) {
7573                TypedArray appearance;
7574                appearance = context.obtainStyledAttributes(ap,
7575                                            com.android.internal.R.styleable.TextAppearance);
7576                colors = appearance.getColorStateList(com.android.internal.R.styleable.
7577                                                  TextAppearance_textColor);
7578                appearance.recycle();
7579            }
7580        }
7581
7582        return colors;
7583    }
7584
7585    /**
7586     * Returns the default color from the TextView_textColor attribute
7587     * from the AttributeSet, if set, or the default color from the
7588     * TextAppearance_textColor from the TextView_textAppearance attribute,
7589     * if TextView_textColor was not set directly.
7590     */
7591    public static int getTextColor(Context context,
7592                                   TypedArray attrs,
7593                                   int def) {
7594        ColorStateList colors = getTextColors(context, attrs);
7595
7596        if (colors == null) {
7597            return def;
7598        } else {
7599            return colors.getDefaultColor();
7600        }
7601    }
7602
7603    @Override
7604    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7605        final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK;
7606        if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) {
7607            switch (keyCode) {
7608            case KeyEvent.KEYCODE_A:
7609                if (canSelectText()) {
7610                    return onTextContextMenuItem(ID_SELECT_ALL);
7611                }
7612                break;
7613            case KeyEvent.KEYCODE_X:
7614                if (canCut()) {
7615                    return onTextContextMenuItem(ID_CUT);
7616                }
7617                break;
7618            case KeyEvent.KEYCODE_C:
7619                if (canCopy()) {
7620                    return onTextContextMenuItem(ID_COPY);
7621                }
7622                break;
7623            case KeyEvent.KEYCODE_V:
7624                if (canPaste()) {
7625                    return onTextContextMenuItem(ID_PASTE);
7626                }
7627                break;
7628            }
7629        }
7630        return super.onKeyShortcut(keyCode, event);
7631    }
7632
7633    /**
7634     * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the
7635     * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have
7636     * a selection controller (see {@link Editor#prepareCursorControllers()}), but this is not
7637     * sufficient.
7638     */
7639    private boolean canSelectText() {
7640        return mText.length() != 0 && mEditor != null && mEditor.hasSelectionController();
7641    }
7642
7643    /**
7644     * Test based on the <i>intrinsic</i> charateristics of the TextView.
7645     * The text must be spannable and the movement method must allow for arbitary selection.
7646     *
7647     * See also {@link #canSelectText()}.
7648     */
7649    boolean textCanBeSelected() {
7650        // prepareCursorController() relies on this method.
7651        // If you change this condition, make sure prepareCursorController is called anywhere
7652        // the value of this condition might be changed.
7653        if (mMovement == null || !mMovement.canSelectArbitrarily()) return false;
7654        return isTextEditable() ||
7655                (isTextSelectable() && mText instanceof Spannable && isEnabled());
7656    }
7657
7658    /**
7659     * This is a temporary method. Future versions may support multi-locale text.
7660     *
7661     * @return The locale that should be used for a word iterator and a spell checker
7662     * in this TextView, based on the current spell checker settings,
7663     * the current IME's locale, or the system default locale.
7664     * @hide
7665     */
7666    public Locale getTextServicesLocale() {
7667        Locale locale = Locale.getDefault();
7668        final TextServicesManager textServicesManager = (TextServicesManager)
7669                mContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);
7670        final SpellCheckerSubtype subtype = textServicesManager.getCurrentSpellCheckerSubtype(true);
7671        if (subtype != null) {
7672            locale = SpellCheckerSubtype.constructLocaleFromString(subtype.getLocale());
7673        }
7674        return locale;
7675    }
7676
7677    void onLocaleChanged() {
7678        // Will be re-created on demand in getWordIterator with the proper new locale
7679        mEditor.mWordIterator = null;
7680    }
7681
7682    /**
7683     * This method is used by the ArrowKeyMovementMethod to jump from one word to the other.
7684     * Made available to achieve a consistent behavior.
7685     * @hide
7686     */
7687    public WordIterator getWordIterator() {
7688        if (mEditor != null) {
7689            return mEditor.getWordIterator();
7690        } else {
7691            return null;
7692        }
7693    }
7694
7695    @Override
7696    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7697        super.onPopulateAccessibilityEvent(event);
7698
7699        final boolean isPassword = hasPasswordTransformationMethod();
7700        if (!isPassword || shouldSpeakPasswordsForAccessibility()) {
7701            final CharSequence text = getTextForAccessibility();
7702            if (!TextUtils.isEmpty(text)) {
7703                event.getText().add(text);
7704            }
7705        }
7706    }
7707
7708    /**
7709     * @return true if the user has explicitly allowed accessibility services
7710     * to speak passwords.
7711     */
7712    private boolean shouldSpeakPasswordsForAccessibility() {
7713        return (Settings.Secure.getInt(mContext.getContentResolver(),
7714                Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD, 0) == 1);
7715    }
7716
7717    @Override
7718    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7719        super.onInitializeAccessibilityEvent(event);
7720
7721        event.setClassName(TextView.class.getName());
7722        final boolean isPassword = hasPasswordTransformationMethod();
7723        event.setPassword(isPassword);
7724
7725        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) {
7726            event.setFromIndex(Selection.getSelectionStart(mText));
7727            event.setToIndex(Selection.getSelectionEnd(mText));
7728            event.setItemCount(mText.length());
7729        }
7730    }
7731
7732    @Override
7733    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
7734        super.onInitializeAccessibilityNodeInfo(info);
7735
7736        info.setClassName(TextView.class.getName());
7737        final boolean isPassword = hasPasswordTransformationMethod();
7738        info.setPassword(isPassword);
7739
7740        if (!isPassword) {
7741            info.setText(getTextForAccessibility());
7742        }
7743
7744        if (TextUtils.isEmpty(getContentDescription()) && !TextUtils.isEmpty(mText)) {
7745            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
7746            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
7747            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
7748                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
7749                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE
7750                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH
7751                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE);
7752        }
7753    }
7754
7755    @Override
7756    public void sendAccessibilityEvent(int eventType) {
7757        // Do not send scroll events since first they are not interesting for
7758        // accessibility and second such events a generated too frequently.
7759        // For details see the implementation of bringTextIntoView().
7760        if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
7761            return;
7762        }
7763        super.sendAccessibilityEvent(eventType);
7764    }
7765
7766    /**
7767     * Gets the text reported for accessibility purposes.
7768     *
7769     * @return The accessibility text.
7770     *
7771     * @hide
7772     */
7773    public CharSequence getTextForAccessibility() {
7774        CharSequence text = getText();
7775        if (TextUtils.isEmpty(text)) {
7776            text = getHint();
7777        }
7778        return text;
7779    }
7780
7781    void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText,
7782            int fromIndex, int removedCount, int addedCount) {
7783        AccessibilityEvent event =
7784            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
7785        event.setFromIndex(fromIndex);
7786        event.setRemovedCount(removedCount);
7787        event.setAddedCount(addedCount);
7788        event.setBeforeText(beforeText);
7789        sendAccessibilityEventUnchecked(event);
7790    }
7791
7792    /**
7793     * Returns whether this text view is a current input method target.  The
7794     * default implementation just checks with {@link InputMethodManager}.
7795     */
7796    public boolean isInputMethodTarget() {
7797        InputMethodManager imm = InputMethodManager.peekInstance();
7798        return imm != null && imm.isActive(this);
7799    }
7800
7801    static final int ID_SELECT_ALL = android.R.id.selectAll;
7802    static final int ID_CUT = android.R.id.cut;
7803    static final int ID_COPY = android.R.id.copy;
7804    static final int ID_PASTE = android.R.id.paste;
7805
7806    /**
7807     * Called when a context menu option for the text view is selected.  Currently
7808     * this will be one of {@link android.R.id#selectAll}, {@link android.R.id#cut},
7809     * {@link android.R.id#copy} or {@link android.R.id#paste}.
7810     *
7811     * @return true if the context menu item action was performed.
7812     */
7813    public boolean onTextContextMenuItem(int id) {
7814        int min = 0;
7815        int max = mText.length();
7816
7817        if (isFocused()) {
7818            final int selStart = getSelectionStart();
7819            final int selEnd = getSelectionEnd();
7820
7821            min = Math.max(0, Math.min(selStart, selEnd));
7822            max = Math.max(0, Math.max(selStart, selEnd));
7823        }
7824
7825        switch (id) {
7826            case ID_SELECT_ALL:
7827                // This does not enter text selection mode. Text is highlighted, so that it can be
7828                // bulk edited, like selectAllOnFocus does. Returns true even if text is empty.
7829                selectAllText();
7830                return true;
7831
7832            case ID_PASTE:
7833                paste(min, max);
7834                return true;
7835
7836            case ID_CUT:
7837                setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
7838                deleteText_internal(min, max);
7839                stopSelectionActionMode();
7840                return true;
7841
7842            case ID_COPY:
7843                setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
7844                stopSelectionActionMode();
7845                return true;
7846        }
7847        return false;
7848    }
7849
7850    CharSequence getTransformedText(int start, int end) {
7851        return removeSuggestionSpans(mTransformed.subSequence(start, end));
7852    }
7853
7854    @Override
7855    public boolean performLongClick() {
7856        boolean handled = false;
7857
7858        if (super.performLongClick()) {
7859            handled = true;
7860        }
7861
7862        if (mEditor != null) {
7863            handled |= mEditor.performLongClick(handled);
7864        }
7865
7866        if (handled) {
7867            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
7868            if (mEditor != null) mEditor.mDiscardNextActionUp = true;
7869        }
7870
7871        return handled;
7872    }
7873
7874    @Override
7875    protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) {
7876        super.onScrollChanged(horiz, vert, oldHoriz, oldVert);
7877        if (mEditor != null) {
7878            mEditor.onScrollChanged();
7879        }
7880    }
7881
7882    /**
7883     * Return whether or not suggestions are enabled on this TextView. The suggestions are generated
7884     * by the IME or by the spell checker as the user types. This is done by adding
7885     * {@link SuggestionSpan}s to the text.
7886     *
7887     * When suggestions are enabled (default), this list of suggestions will be displayed when the
7888     * user asks for them on these parts of the text. This value depends on the inputType of this
7889     * TextView.
7890     *
7891     * The class of the input type must be {@link InputType#TYPE_CLASS_TEXT}.
7892     *
7893     * In addition, the type variation must be one of
7894     * {@link InputType#TYPE_TEXT_VARIATION_NORMAL},
7895     * {@link InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT},
7896     * {@link InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE},
7897     * {@link InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or
7898     * {@link InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}.
7899     *
7900     * And finally, the {@link InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS} flag must <i>not</i> be set.
7901     *
7902     * @return true if the suggestions popup window is enabled, based on the inputType.
7903     */
7904    public boolean isSuggestionsEnabled() {
7905        if (mEditor == null) return false;
7906        if ((mEditor.mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) {
7907            return false;
7908        }
7909        if ((mEditor.mInputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) > 0) return false;
7910
7911        final int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION;
7912        return (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL ||
7913                variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT ||
7914                variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE ||
7915                variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE ||
7916                variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT);
7917    }
7918
7919    /**
7920     * If provided, this ActionMode.Callback will be used to create the ActionMode when text
7921     * selection is initiated in this View.
7922     *
7923     * The standard implementation populates the menu with a subset of Select All, Cut, Copy and
7924     * Paste actions, depending on what this View supports.
7925     *
7926     * A custom implementation can add new entries in the default menu in its
7927     * {@link android.view.ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The
7928     * default actions can also be removed from the menu using {@link Menu#removeItem(int)} and
7929     * passing {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy}
7930     * or {@link android.R.id#paste} ids as parameters.
7931     *
7932     * Returning false from
7933     * {@link android.view.ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will prevent
7934     * the action mode from being started.
7935     *
7936     * Action click events should be handled by the custom implementation of
7937     * {@link android.view.ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}.
7938     *
7939     * Note that text selection mode is not started when a TextView receives focus and the
7940     * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in
7941     * that case, to allow for quick replacement.
7942     */
7943    public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) {
7944        createEditorIfNeeded();
7945        mEditor.mCustomSelectionActionModeCallback = actionModeCallback;
7946    }
7947
7948    /**
7949     * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null.
7950     *
7951     * @return The current custom selection callback.
7952     */
7953    public ActionMode.Callback getCustomSelectionActionModeCallback() {
7954        return mEditor == null ? null : mEditor.mCustomSelectionActionModeCallback;
7955    }
7956
7957    /**
7958     * @hide
7959     */
7960    protected void stopSelectionActionMode() {
7961        mEditor.stopSelectionActionMode();
7962    }
7963
7964    boolean canCut() {
7965        if (hasPasswordTransformationMethod()) {
7966            return false;
7967        }
7968
7969        if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mEditor != null &&
7970                mEditor.mKeyListener != null) {
7971            return true;
7972        }
7973
7974        return false;
7975    }
7976
7977    boolean canCopy() {
7978        if (hasPasswordTransformationMethod()) {
7979            return false;
7980        }
7981
7982        if (mText.length() > 0 && hasSelection()) {
7983            return true;
7984        }
7985
7986        return false;
7987    }
7988
7989    boolean canPaste() {
7990        return (mText instanceof Editable &&
7991                mEditor != null && mEditor.mKeyListener != null &&
7992                getSelectionStart() >= 0 &&
7993                getSelectionEnd() >= 0 &&
7994                ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)).
7995                hasPrimaryClip());
7996    }
7997
7998    boolean selectAllText() {
7999        final int length = mText.length();
8000        Selection.setSelection((Spannable) mText, 0, length);
8001        return length > 0;
8002    }
8003
8004    /**
8005     * Prepare text so that there are not zero or two spaces at beginning and end of region defined
8006     * by [min, max] when replacing this region by paste.
8007     * Note that if there were two spaces (or more) at that position before, they are kept. We just
8008     * make sure we do not add an extra one from the paste content.
8009     */
8010    long prepareSpacesAroundPaste(int min, int max, CharSequence paste) {
8011        if (paste.length() > 0) {
8012            if (min > 0) {
8013                final char charBefore = mTransformed.charAt(min - 1);
8014                final char charAfter = paste.charAt(0);
8015
8016                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
8017                    // Two spaces at beginning of paste: remove one
8018                    final int originalLength = mText.length();
8019                    deleteText_internal(min - 1, min);
8020                    // Due to filters, there is no guarantee that exactly one character was
8021                    // removed: count instead.
8022                    final int delta = mText.length() - originalLength;
8023                    min += delta;
8024                    max += delta;
8025                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
8026                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
8027                    // No space at beginning of paste: add one
8028                    final int originalLength = mText.length();
8029                    replaceText_internal(min, min, " ");
8030                    // Taking possible filters into account as above.
8031                    final int delta = mText.length() - originalLength;
8032                    min += delta;
8033                    max += delta;
8034                }
8035            }
8036
8037            if (max < mText.length()) {
8038                final char charBefore = paste.charAt(paste.length() - 1);
8039                final char charAfter = mTransformed.charAt(max);
8040
8041                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
8042                    // Two spaces at end of paste: remove one
8043                    deleteText_internal(max, max + 1);
8044                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
8045                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
8046                    // No space at end of paste: add one
8047                    replaceText_internal(max, max, " ");
8048                }
8049            }
8050        }
8051
8052        return TextUtils.packRangeInLong(min, max);
8053    }
8054
8055    /**
8056     * Paste clipboard content between min and max positions.
8057     */
8058    private void paste(int min, int max) {
8059        ClipboardManager clipboard =
8060            (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
8061        ClipData clip = clipboard.getPrimaryClip();
8062        if (clip != null) {
8063            boolean didFirst = false;
8064            for (int i=0; i<clip.getItemCount(); i++) {
8065                CharSequence paste = clip.getItemAt(i).coerceToStyledText(getContext());
8066                if (paste != null) {
8067                    if (!didFirst) {
8068                        long minMax = prepareSpacesAroundPaste(min, max, paste);
8069                        min = TextUtils.unpackRangeStartFromLong(minMax);
8070                        max = TextUtils.unpackRangeEndFromLong(minMax);
8071                        Selection.setSelection((Spannable) mText, max);
8072                        ((Editable) mText).replace(min, max, paste);
8073                        didFirst = true;
8074                    } else {
8075                        ((Editable) mText).insert(getSelectionEnd(), "\n");
8076                        ((Editable) mText).insert(getSelectionEnd(), paste);
8077                    }
8078                }
8079            }
8080            stopSelectionActionMode();
8081            LAST_CUT_OR_COPY_TIME = 0;
8082        }
8083    }
8084
8085    private void setPrimaryClip(ClipData clip) {
8086        ClipboardManager clipboard = (ClipboardManager) getContext().
8087                getSystemService(Context.CLIPBOARD_SERVICE);
8088        clipboard.setPrimaryClip(clip);
8089        LAST_CUT_OR_COPY_TIME = SystemClock.uptimeMillis();
8090    }
8091
8092    /**
8093     * Get the character offset closest to the specified absolute position. A typical use case is to
8094     * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method.
8095     *
8096     * @param x The horizontal absolute position of a point on screen
8097     * @param y The vertical absolute position of a point on screen
8098     * @return the character offset for the character whose position is closest to the specified
8099     *  position. Returns -1 if there is no layout.
8100     */
8101    public int getOffsetForPosition(float x, float y) {
8102        if (getLayout() == null) return -1;
8103        final int line = getLineAtCoordinate(y);
8104        final int offset = getOffsetAtCoordinate(line, x);
8105        return offset;
8106    }
8107
8108    float convertToLocalHorizontalCoordinate(float x) {
8109        x -= getTotalPaddingLeft();
8110        // Clamp the position to inside of the view.
8111        x = Math.max(0.0f, x);
8112        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
8113        x += getScrollX();
8114        return x;
8115    }
8116
8117    int getLineAtCoordinate(float y) {
8118        y -= getTotalPaddingTop();
8119        // Clamp the position to inside of the view.
8120        y = Math.max(0.0f, y);
8121        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
8122        y += getScrollY();
8123        return getLayout().getLineForVertical((int) y);
8124    }
8125
8126    private int getOffsetAtCoordinate(int line, float x) {
8127        x = convertToLocalHorizontalCoordinate(x);
8128        return getLayout().getOffsetForHorizontal(line, x);
8129    }
8130
8131    @Override
8132    public boolean onDragEvent(DragEvent event) {
8133        switch (event.getAction()) {
8134            case DragEvent.ACTION_DRAG_STARTED:
8135                return mEditor != null && mEditor.hasInsertionController();
8136
8137            case DragEvent.ACTION_DRAG_ENTERED:
8138                TextView.this.requestFocus();
8139                return true;
8140
8141            case DragEvent.ACTION_DRAG_LOCATION:
8142                final int offset = getOffsetForPosition(event.getX(), event.getY());
8143                Selection.setSelection((Spannable)mText, offset);
8144                return true;
8145
8146            case DragEvent.ACTION_DROP:
8147                if (mEditor != null) mEditor.onDrop(event);
8148                return true;
8149
8150            case DragEvent.ACTION_DRAG_ENDED:
8151            case DragEvent.ACTION_DRAG_EXITED:
8152            default:
8153                return true;
8154        }
8155    }
8156
8157    boolean isInBatchEditMode() {
8158        if (mEditor == null) return false;
8159        final Editor.InputMethodState ims = mEditor.mInputMethodState;
8160        if (ims != null) {
8161            return ims.mBatchEditNesting > 0;
8162        }
8163        return mEditor.mInBatchEditControllers;
8164    }
8165
8166    @Override
8167    public void onResolvedTextDirectionChanged() {
8168        if (hasPasswordTransformationMethod()) {
8169            // TODO: take care of the content direction to show the password text and dots justified
8170            // to the left or to the right
8171            mTextDir = TextDirectionHeuristics.LOCALE;
8172            return;
8173        }
8174
8175        // Always need to resolve layout direction first
8176        final boolean defaultIsRtl = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
8177
8178        // Now, we can select the heuristic
8179        int textDir = getResolvedTextDirection();
8180        switch (textDir) {
8181            default:
8182            case TEXT_DIRECTION_FIRST_STRONG:
8183                mTextDir = (defaultIsRtl ? TextDirectionHeuristics.FIRSTSTRONG_RTL :
8184                        TextDirectionHeuristics.FIRSTSTRONG_LTR);
8185                break;
8186            case TEXT_DIRECTION_ANY_RTL:
8187                mTextDir = TextDirectionHeuristics.ANYRTL_LTR;
8188                break;
8189            case TEXT_DIRECTION_LTR:
8190                mTextDir = TextDirectionHeuristics.LTR;
8191                break;
8192            case TEXT_DIRECTION_RTL:
8193                mTextDir = TextDirectionHeuristics.RTL;
8194                break;
8195            case TEXT_DIRECTION_LOCALE:
8196                mTextDir = TextDirectionHeuristics.LOCALE;
8197                break;
8198        }
8199    }
8200
8201    @Override
8202    public void onResolveDrawables(int layoutDirection) {
8203        // No need to resolve twice
8204        if (mResolvedDrawables) {
8205            return;
8206        }
8207        // No drawable to resolve
8208        if (mDrawables == null) {
8209            return;
8210        }
8211        // No relative drawable to resolve
8212        if (mDrawables.mDrawableStart == null && mDrawables.mDrawableEnd == null) {
8213            mResolvedDrawables = true;
8214            return;
8215        }
8216
8217        Drawables dr = mDrawables;
8218        switch(layoutDirection) {
8219            case LAYOUT_DIRECTION_RTL:
8220                if (dr.mDrawableStart != null) {
8221                    dr.mDrawableRight = dr.mDrawableStart;
8222
8223                    dr.mDrawableSizeRight = dr.mDrawableSizeStart;
8224                    dr.mDrawableHeightRight = dr.mDrawableHeightStart;
8225                }
8226                if (dr.mDrawableEnd != null) {
8227                    dr.mDrawableLeft = dr.mDrawableEnd;
8228
8229                    dr.mDrawableSizeLeft = dr.mDrawableSizeEnd;
8230                    dr.mDrawableHeightLeft = dr.mDrawableHeightEnd;
8231                }
8232                break;
8233
8234            case LAYOUT_DIRECTION_LTR:
8235            default:
8236                if (dr.mDrawableStart != null) {
8237                    dr.mDrawableLeft = dr.mDrawableStart;
8238
8239                    dr.mDrawableSizeLeft = dr.mDrawableSizeStart;
8240                    dr.mDrawableHeightLeft = dr.mDrawableHeightStart;
8241                }
8242                if (dr.mDrawableEnd != null) {
8243                    dr.mDrawableRight = dr.mDrawableEnd;
8244
8245                    dr.mDrawableSizeRight = dr.mDrawableSizeEnd;
8246                    dr.mDrawableHeightRight = dr.mDrawableHeightEnd;
8247                }
8248                break;
8249        }
8250        updateDrawablesLayoutDirection(dr, layoutDirection);
8251        mResolvedDrawables = true;
8252    }
8253
8254    private void updateDrawablesLayoutDirection(Drawables dr, int layoutDirection) {
8255        if (dr.mDrawableLeft != null) {
8256            dr.mDrawableLeft.setLayoutDirection(layoutDirection);
8257        }
8258        if (dr.mDrawableRight != null) {
8259            dr.mDrawableRight.setLayoutDirection(layoutDirection);
8260        }
8261        if (dr.mDrawableTop != null) {
8262            dr.mDrawableTop.setLayoutDirection(layoutDirection);
8263        }
8264        if (dr.mDrawableBottom != null) {
8265            dr.mDrawableBottom.setLayoutDirection(layoutDirection);
8266        }
8267    }
8268
8269    protected void resetResolvedDrawables() {
8270        mResolvedDrawables = false;
8271    }
8272
8273    /**
8274     * @hide
8275     */
8276    protected void viewClicked(InputMethodManager imm) {
8277        if (imm != null) {
8278            imm.viewClicked(this);
8279        }
8280    }
8281
8282    /**
8283     * Deletes the range of text [start, end[.
8284     * @hide
8285     */
8286    protected void deleteText_internal(int start, int end) {
8287        ((Editable) mText).delete(start, end);
8288    }
8289
8290    /**
8291     * Replaces the range of text [start, end[ by replacement text
8292     * @hide
8293     */
8294    protected void replaceText_internal(int start, int end, CharSequence text) {
8295        ((Editable) mText).replace(start, end, text);
8296    }
8297
8298    /**
8299     * Sets a span on the specified range of text
8300     * @hide
8301     */
8302    protected void setSpan_internal(Object span, int start, int end, int flags) {
8303        ((Editable) mText).setSpan(span, start, end, flags);
8304    }
8305
8306    /**
8307     * Moves the cursor to the specified offset position in text
8308     * @hide
8309     */
8310    protected void setCursorPosition_internal(int start, int end) {
8311        Selection.setSelection(((Editable) mText), start, end);
8312    }
8313
8314    /**
8315     * An Editor should be created as soon as any of the editable-specific fields (grouped
8316     * inside the Editor object) is assigned to a non-default value.
8317     * This method will create the Editor if needed.
8318     *
8319     * A standard TextView (as well as buttons, checkboxes...) should not qualify and hence will
8320     * have a null Editor, unlike an EditText. Inconsistent in-between states will have an
8321     * Editor for backward compatibility, as soon as one of these fields is assigned.
8322     *
8323     * Also note that for performance reasons, the mEditor is created when needed, but not
8324     * reset when no more edit-specific fields are needed.
8325     */
8326    private void createEditorIfNeeded() {
8327        if (mEditor == null) {
8328            mEditor = new Editor(this);
8329        }
8330    }
8331
8332    /**
8333     * @hide
8334     */
8335    @Override
8336    public CharSequence getIterableTextForAccessibility() {
8337        if (getContentDescription() == null) {
8338            if (!(mText instanceof Spannable)) {
8339                setText(mText, BufferType.SPANNABLE);
8340            }
8341            return mText;
8342        }
8343        return super.getIterableTextForAccessibility();
8344    }
8345
8346    /**
8347     * @hide
8348     */
8349    @Override
8350    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8351        switch (granularity) {
8352            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE: {
8353                Spannable text = (Spannable) getIterableTextForAccessibility();
8354                if (!TextUtils.isEmpty(text) && getLayout() != null) {
8355                    AccessibilityIterators.LineTextSegmentIterator iterator =
8356                        AccessibilityIterators.LineTextSegmentIterator.getInstance();
8357                    iterator.initialize(text, getLayout());
8358                    return iterator;
8359                }
8360            } break;
8361            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE: {
8362                Spannable text = (Spannable) getIterableTextForAccessibility();
8363                if (!TextUtils.isEmpty(text) && getLayout() != null) {
8364                    AccessibilityIterators.PageTextSegmentIterator iterator =
8365                        AccessibilityIterators.PageTextSegmentIterator.getInstance();
8366                    iterator.initialize(this);
8367                    return iterator;
8368                }
8369            } break;
8370        }
8371        return super.getIteratorForGranularity(granularity);
8372    }
8373
8374    /**
8375     * @hide
8376     */
8377    @Override
8378    public int getAccessibilityCursorPosition() {
8379        if (TextUtils.isEmpty(getContentDescription())) {
8380            final int selectionEnd = getSelectionEnd();
8381            if (selectionEnd >= 0) {
8382                return selectionEnd;
8383            }
8384        }
8385        return super.getAccessibilityCursorPosition();
8386    }
8387
8388    /**
8389     * @hide
8390     */
8391    @Override
8392    public void setAccessibilityCursorPosition(int index) {
8393        if (getAccessibilityCursorPosition() == index) {
8394            return;
8395        }
8396        if (TextUtils.isEmpty(getContentDescription())) {
8397            if (index >= 0 && index <= mText.length()) {
8398                Selection.setSelection((Spannable) mText, index);
8399            } else {
8400                Selection.removeSelection((Spannable) mText);
8401            }
8402        } else {
8403            super.setAccessibilityCursorPosition(index);
8404        }
8405    }
8406
8407    /**
8408     * User interface state that is stored by TextView for implementing
8409     * {@link View#onSaveInstanceState}.
8410     */
8411    public static class SavedState extends BaseSavedState {
8412        int selStart;
8413        int selEnd;
8414        CharSequence text;
8415        boolean frozenWithFocus;
8416        CharSequence error;
8417
8418        SavedState(Parcelable superState) {
8419            super(superState);
8420        }
8421
8422        @Override
8423        public void writeToParcel(Parcel out, int flags) {
8424            super.writeToParcel(out, flags);
8425            out.writeInt(selStart);
8426            out.writeInt(selEnd);
8427            out.writeInt(frozenWithFocus ? 1 : 0);
8428            TextUtils.writeToParcel(text, out, flags);
8429
8430            if (error == null) {
8431                out.writeInt(0);
8432            } else {
8433                out.writeInt(1);
8434                TextUtils.writeToParcel(error, out, flags);
8435            }
8436        }
8437
8438        @Override
8439        public String toString() {
8440            String str = "TextView.SavedState{"
8441                    + Integer.toHexString(System.identityHashCode(this))
8442                    + " start=" + selStart + " end=" + selEnd;
8443            if (text != null) {
8444                str += " text=" + text;
8445            }
8446            return str + "}";
8447        }
8448
8449        @SuppressWarnings("hiding")
8450        public static final Parcelable.Creator<SavedState> CREATOR
8451                = new Parcelable.Creator<SavedState>() {
8452            public SavedState createFromParcel(Parcel in) {
8453                return new SavedState(in);
8454            }
8455
8456            public SavedState[] newArray(int size) {
8457                return new SavedState[size];
8458            }
8459        };
8460
8461        private SavedState(Parcel in) {
8462            super(in);
8463            selStart = in.readInt();
8464            selEnd = in.readInt();
8465            frozenWithFocus = (in.readInt() != 0);
8466            text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
8467
8468            if (in.readInt() != 0) {
8469                error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
8470            }
8471        }
8472    }
8473
8474    private static class CharWrapper implements CharSequence, GetChars, GraphicsOperations {
8475        private char[] mChars;
8476        private int mStart, mLength;
8477
8478        public CharWrapper(char[] chars, int start, int len) {
8479            mChars = chars;
8480            mStart = start;
8481            mLength = len;
8482        }
8483
8484        /* package */ void set(char[] chars, int start, int len) {
8485            mChars = chars;
8486            mStart = start;
8487            mLength = len;
8488        }
8489
8490        public int length() {
8491            return mLength;
8492        }
8493
8494        public char charAt(int off) {
8495            return mChars[off + mStart];
8496        }
8497
8498        @Override
8499        public String toString() {
8500            return new String(mChars, mStart, mLength);
8501        }
8502
8503        public CharSequence subSequence(int start, int end) {
8504            if (start < 0 || end < 0 || start > mLength || end > mLength) {
8505                throw new IndexOutOfBoundsException(start + ", " + end);
8506            }
8507
8508            return new String(mChars, start + mStart, end - start);
8509        }
8510
8511        public void getChars(int start, int end, char[] buf, int off) {
8512            if (start < 0 || end < 0 || start > mLength || end > mLength) {
8513                throw new IndexOutOfBoundsException(start + ", " + end);
8514            }
8515
8516            System.arraycopy(mChars, start + mStart, buf, off, end - start);
8517        }
8518
8519        public void drawText(Canvas c, int start, int end,
8520                             float x, float y, Paint p) {
8521            c.drawText(mChars, start + mStart, end - start, x, y, p);
8522        }
8523
8524        public void drawTextRun(Canvas c, int start, int end,
8525                int contextStart, int contextEnd, float x, float y, int flags, Paint p) {
8526            int count = end - start;
8527            int contextCount = contextEnd - contextStart;
8528            c.drawTextRun(mChars, start + mStart, count, contextStart + mStart,
8529                    contextCount, x, y, flags, p);
8530        }
8531
8532        public float measureText(int start, int end, Paint p) {
8533            return p.measureText(mChars, start + mStart, end - start);
8534        }
8535
8536        public int getTextWidths(int start, int end, float[] widths, Paint p) {
8537            return p.getTextWidths(mChars, start + mStart, end - start, widths);
8538        }
8539
8540        public float getTextRunAdvances(int start, int end, int contextStart,
8541                int contextEnd, int flags, float[] advances, int advancesIndex,
8542                Paint p) {
8543            int count = end - start;
8544            int contextCount = contextEnd - contextStart;
8545            return p.getTextRunAdvances(mChars, start + mStart, count,
8546                    contextStart + mStart, contextCount, flags, advances,
8547                    advancesIndex);
8548        }
8549
8550        public float getTextRunAdvances(int start, int end, int contextStart,
8551                int contextEnd, int flags, float[] advances, int advancesIndex,
8552                Paint p, int reserved) {
8553            int count = end - start;
8554            int contextCount = contextEnd - contextStart;
8555            return p.getTextRunAdvances(mChars, start + mStart, count,
8556                    contextStart + mStart, contextCount, flags, advances,
8557                    advancesIndex, reserved);
8558        }
8559
8560        public int getTextRunCursor(int contextStart, int contextEnd, int flags,
8561                int offset, int cursorOpt, Paint p) {
8562            int contextCount = contextEnd - contextStart;
8563            return p.getTextRunCursor(mChars, contextStart + mStart,
8564                    contextCount, flags, offset + mStart, cursorOpt);
8565        }
8566    }
8567
8568    private static final class Marquee extends Handler {
8569        // TODO: Add an option to configure this
8570        private static final float MARQUEE_DELTA_MAX = 0.07f;
8571        private static final int MARQUEE_DELAY = 1200;
8572        private static final int MARQUEE_RESTART_DELAY = 1200;
8573        private static final int MARQUEE_RESOLUTION = 1000 / 30;
8574        private static final int MARQUEE_PIXELS_PER_SECOND = 30;
8575
8576        private static final byte MARQUEE_STOPPED = 0x0;
8577        private static final byte MARQUEE_STARTING = 0x1;
8578        private static final byte MARQUEE_RUNNING = 0x2;
8579
8580        private static final int MESSAGE_START = 0x1;
8581        private static final int MESSAGE_TICK = 0x2;
8582        private static final int MESSAGE_RESTART = 0x3;
8583
8584        private final WeakReference<TextView> mView;
8585
8586        private byte mStatus = MARQUEE_STOPPED;
8587        private final float mScrollUnit;
8588        private float mMaxScroll;
8589        private float mMaxFadeScroll;
8590        private float mGhostStart;
8591        private float mGhostOffset;
8592        private float mFadeStop;
8593        private int mRepeatLimit;
8594
8595        private float mScroll;
8596
8597        Marquee(TextView v) {
8598            final float density = v.getContext().getResources().getDisplayMetrics().density;
8599            mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION;
8600            mView = new WeakReference<TextView>(v);
8601        }
8602
8603        @Override
8604        public void handleMessage(Message msg) {
8605            switch (msg.what) {
8606                case MESSAGE_START:
8607                    mStatus = MARQUEE_RUNNING;
8608                    tick();
8609                    break;
8610                case MESSAGE_TICK:
8611                    tick();
8612                    break;
8613                case MESSAGE_RESTART:
8614                    if (mStatus == MARQUEE_RUNNING) {
8615                        if (mRepeatLimit >= 0) {
8616                            mRepeatLimit--;
8617                        }
8618                        start(mRepeatLimit);
8619                    }
8620                    break;
8621            }
8622        }
8623
8624        void tick() {
8625            if (mStatus != MARQUEE_RUNNING) {
8626                return;
8627            }
8628
8629            removeMessages(MESSAGE_TICK);
8630
8631            final TextView textView = mView.get();
8632            if (textView != null && (textView.isFocused() || textView.isSelected())) {
8633                mScroll += mScrollUnit;
8634                if (mScroll > mMaxScroll) {
8635                    mScroll = mMaxScroll;
8636                    sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY);
8637                } else {
8638                    sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION);
8639                }
8640                textView.invalidate();
8641            }
8642        }
8643
8644        void stop() {
8645            mStatus = MARQUEE_STOPPED;
8646            removeMessages(MESSAGE_START);
8647            removeMessages(MESSAGE_RESTART);
8648            removeMessages(MESSAGE_TICK);
8649            resetScroll();
8650        }
8651
8652        private void resetScroll() {
8653            mScroll = 0.0f;
8654            final TextView textView = mView.get();
8655            if (textView != null) textView.invalidate();
8656        }
8657
8658        void start(int repeatLimit) {
8659            if (repeatLimit == 0) {
8660                stop();
8661                return;
8662            }
8663            mRepeatLimit = repeatLimit;
8664            final TextView textView = mView.get();
8665            if (textView != null && textView.mLayout != null) {
8666                mStatus = MARQUEE_STARTING;
8667                mScroll = 0.0f;
8668                final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() -
8669                        textView.getCompoundPaddingRight();
8670                final float lineWidth = textView.mLayout.getLineWidth(0);
8671                final float gap = textWidth / 3.0f;
8672                mGhostStart = lineWidth - textWidth + gap;
8673                mMaxScroll = mGhostStart + textWidth;
8674                mGhostOffset = lineWidth + gap;
8675                mFadeStop = lineWidth + textWidth / 6.0f;
8676                mMaxFadeScroll = mGhostStart + lineWidth + lineWidth;
8677
8678                textView.invalidate();
8679                sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY);
8680            }
8681        }
8682
8683        float getGhostOffset() {
8684            return mGhostOffset;
8685        }
8686
8687        float getScroll() {
8688            return mScroll;
8689        }
8690
8691        float getMaxFadeScroll() {
8692            return mMaxFadeScroll;
8693        }
8694
8695        boolean shouldDrawLeftFade() {
8696            return mScroll <= mFadeStop;
8697        }
8698
8699        boolean shouldDrawGhost() {
8700            return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart;
8701        }
8702
8703        boolean isRunning() {
8704            return mStatus == MARQUEE_RUNNING;
8705        }
8706
8707        boolean isStopped() {
8708            return mStatus == MARQUEE_STOPPED;
8709        }
8710    }
8711
8712    private class ChangeWatcher implements TextWatcher, SpanWatcher {
8713
8714        private CharSequence mBeforeText;
8715
8716        public void beforeTextChanged(CharSequence buffer, int start,
8717                                      int before, int after) {
8718            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start
8719                    + " before=" + before + " after=" + after + ": " + buffer);
8720
8721            if (AccessibilityManager.getInstance(mContext).isEnabled()
8722                    && !isPasswordInputType(getInputType())
8723                    && !hasPasswordTransformationMethod()) {
8724                mBeforeText = buffer.toString();
8725            }
8726
8727            TextView.this.sendBeforeTextChanged(buffer, start, before, after);
8728        }
8729
8730        public void onTextChanged(CharSequence buffer, int start, int before, int after) {
8731            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start
8732                    + " before=" + before + " after=" + after + ": " + buffer);
8733            TextView.this.handleTextChanged(buffer, start, before, after);
8734
8735            if (AccessibilityManager.getInstance(mContext).isEnabled() &&
8736                    (isFocused() || isSelected() && isShown())) {
8737                sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after);
8738                mBeforeText = null;
8739            }
8740        }
8741
8742        public void afterTextChanged(Editable buffer) {
8743            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer);
8744            TextView.this.sendAfterTextChanged(buffer);
8745
8746            if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) {
8747                MetaKeyKeyListener.stopSelecting(TextView.this, buffer);
8748            }
8749        }
8750
8751        public void onSpanChanged(Spannable buf, Object what, int s, int e, int st, int en) {
8752            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e
8753                    + " st=" + st + " en=" + en + " what=" + what + ": " + buf);
8754            TextView.this.spanChange(buf, what, s, st, e, en);
8755        }
8756
8757        public void onSpanAdded(Spannable buf, Object what, int s, int e) {
8758            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e
8759                    + " what=" + what + ": " + buf);
8760            TextView.this.spanChange(buf, what, -1, s, -1, e);
8761        }
8762
8763        public void onSpanRemoved(Spannable buf, Object what, int s, int e) {
8764            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e
8765                    + " what=" + what + ": " + buf);
8766            TextView.this.spanChange(buf, what, s, -1, e, -1);
8767        }
8768    }
8769}
8770