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