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