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