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