TextView.java revision 8fbe1a0cfc0354067c10e5e788519c19f4b39349
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.inputmethodservice.ExtractEditText;
50import android.os.AsyncTask;
51import android.os.Bundle;
52import android.os.Parcel;
53import android.os.Parcelable;
54import android.os.ParcelableParcel;
55import android.os.SystemClock;
56import android.os.UserHandle;
57import android.provider.Settings;
58import android.text.BoringLayout;
59import android.text.DynamicLayout;
60import android.text.Editable;
61import android.text.GetChars;
62import android.text.GraphicsOperations;
63import android.text.InputFilter;
64import android.text.InputType;
65import android.text.Layout;
66import android.text.ParcelableSpan;
67import android.text.Selection;
68import android.text.SpanWatcher;
69import android.text.Spannable;
70import android.text.SpannableString;
71import android.text.SpannableStringBuilder;
72import android.text.Spanned;
73import android.text.SpannedString;
74import android.text.StaticLayout;
75import android.text.TextDirectionHeuristic;
76import android.text.TextDirectionHeuristics;
77import android.text.TextPaint;
78import android.text.TextUtils;
79import android.text.TextUtils.TruncateAt;
80import android.text.TextWatcher;
81import android.text.method.AllCapsTransformationMethod;
82import android.text.method.ArrowKeyMovementMethod;
83import android.text.method.DateKeyListener;
84import android.text.method.DateTimeKeyListener;
85import android.text.method.DialerKeyListener;
86import android.text.method.DigitsKeyListener;
87import android.text.method.KeyListener;
88import android.text.method.LinkMovementMethod;
89import android.text.method.MetaKeyKeyListener;
90import android.text.method.MovementMethod;
91import android.text.method.PasswordTransformationMethod;
92import android.text.method.SingleLineTransformationMethod;
93import android.text.method.TextKeyListener;
94import android.text.method.TimeKeyListener;
95import android.text.method.TransformationMethod;
96import android.text.method.TransformationMethod2;
97import android.text.method.WordIterator;
98import android.text.style.CharacterStyle;
99import android.text.style.ClickableSpan;
100import android.text.style.ParagraphStyle;
101import android.text.style.SpellCheckSpan;
102import android.text.style.SuggestionSpan;
103import android.text.style.URLSpan;
104import android.text.style.UpdateAppearance;
105import android.text.util.Linkify;
106import android.util.AttributeSet;
107import android.util.Log;
108import android.util.TypedValue;
109import android.view.AccessibilityIterators.TextSegmentIterator;
110import android.view.ActionMode;
111import android.view.Choreographer;
112import android.view.DragEvent;
113import android.view.Gravity;
114import android.view.HapticFeedbackConstants;
115import android.view.KeyCharacterMap;
116import android.view.KeyEvent;
117import android.view.MotionEvent;
118import android.view.View;
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            mEditor.startSelectionActionMode();
5236            mEditor.mCreatedWithASelection = false;
5237        }
5238
5239        // Phone specific code (there is no ExtractEditText on tablets).
5240        // ExtractEditText does not call onFocus when it is displayed, and mHasSelectionOnFocus can
5241        // not be set. Do the test here instead.
5242        if (isInExtractedMode() && hasSelection() && mEditor != null
5243                && mEditor.mTextActionMode == null && isShown() && hasWindowFocus()) {
5244            mEditor.startSelectionActionMode();
5245        }
5246
5247        unregisterForPreDraw();
5248
5249        return true;
5250    }
5251
5252    @Override
5253    protected void onAttachedToWindow() {
5254        super.onAttachedToWindow();
5255
5256        mTemporaryDetach = false;
5257
5258        if (mEditor != null) mEditor.onAttachedToWindow();
5259
5260        if (mPreDrawListenerDetached) {
5261            getViewTreeObserver().addOnPreDrawListener(this);
5262            mPreDrawListenerDetached = false;
5263        }
5264    }
5265
5266    /** @hide */
5267    @Override
5268    protected void onDetachedFromWindowInternal() {
5269        if (mPreDrawRegistered) {
5270            getViewTreeObserver().removeOnPreDrawListener(this);
5271            mPreDrawListenerDetached = true;
5272        }
5273
5274        resetResolvedDrawables();
5275
5276        if (mEditor != null) mEditor.onDetachedFromWindow();
5277
5278        super.onDetachedFromWindowInternal();
5279    }
5280
5281    @Override
5282    public void onScreenStateChanged(int screenState) {
5283        super.onScreenStateChanged(screenState);
5284        if (mEditor != null) mEditor.onScreenStateChanged(screenState);
5285    }
5286
5287    @Override
5288    protected boolean isPaddingOffsetRequired() {
5289        return mShadowRadius != 0 || mDrawables != null;
5290    }
5291
5292    @Override
5293    protected int getLeftPaddingOffset() {
5294        return getCompoundPaddingLeft() - mPaddingLeft +
5295                (int) Math.min(0, mShadowDx - mShadowRadius);
5296    }
5297
5298    @Override
5299    protected int getTopPaddingOffset() {
5300        return (int) Math.min(0, mShadowDy - mShadowRadius);
5301    }
5302
5303    @Override
5304    protected int getBottomPaddingOffset() {
5305        return (int) Math.max(0, mShadowDy + mShadowRadius);
5306    }
5307
5308    private int getFudgedPaddingRight() {
5309        // Add sufficient space for cursor and tone marks
5310        int cursorWidth = 2 + (int)mTextPaint.density; // adequate for Material cursors
5311        return Math.max(0, getCompoundPaddingRight() - (cursorWidth - 1));
5312    }
5313
5314    @Override
5315    protected int getRightPaddingOffset() {
5316        return -(getFudgedPaddingRight() - mPaddingRight) +
5317                (int) Math.max(0, mShadowDx + mShadowRadius);
5318    }
5319
5320    @Override
5321    protected boolean verifyDrawable(Drawable who) {
5322        final boolean verified = super.verifyDrawable(who);
5323        if (!verified && mDrawables != null) {
5324            for (Drawable dr : mDrawables.mShowing) {
5325                if (who == dr) {
5326                    return true;
5327                }
5328            }
5329        }
5330        return verified;
5331    }
5332
5333    @Override
5334    public void jumpDrawablesToCurrentState() {
5335        super.jumpDrawablesToCurrentState();
5336        if (mDrawables != null) {
5337            for (Drawable dr : mDrawables.mShowing) {
5338                if (dr != null) {
5339                    dr.jumpToCurrentState();
5340                }
5341            }
5342        }
5343    }
5344
5345    @Override
5346    public void invalidateDrawable(Drawable drawable) {
5347        boolean handled = false;
5348
5349        if (verifyDrawable(drawable)) {
5350            final Rect dirty = drawable.getBounds();
5351            int scrollX = mScrollX;
5352            int scrollY = mScrollY;
5353
5354            // IMPORTANT: The coordinates below are based on the coordinates computed
5355            // for each compound drawable in onDraw(). Make sure to update each section
5356            // accordingly.
5357            final TextView.Drawables drawables = mDrawables;
5358            if (drawables != null) {
5359                if (drawable == drawables.mShowing[Drawables.LEFT]) {
5360                    final int compoundPaddingTop = getCompoundPaddingTop();
5361                    final int compoundPaddingBottom = getCompoundPaddingBottom();
5362                    final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
5363
5364                    scrollX += mPaddingLeft;
5365                    scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2;
5366                    handled = true;
5367                } else if (drawable == drawables.mShowing[Drawables.RIGHT]) {
5368                    final int compoundPaddingTop = getCompoundPaddingTop();
5369                    final int compoundPaddingBottom = getCompoundPaddingBottom();
5370                    final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
5371
5372                    scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight);
5373                    scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2;
5374                    handled = true;
5375                } else if (drawable == drawables.mShowing[Drawables.TOP]) {
5376                    final int compoundPaddingLeft = getCompoundPaddingLeft();
5377                    final int compoundPaddingRight = getCompoundPaddingRight();
5378                    final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft;
5379
5380                    scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2;
5381                    scrollY += mPaddingTop;
5382                    handled = true;
5383                } else if (drawable == drawables.mShowing[Drawables.BOTTOM]) {
5384                    final int compoundPaddingLeft = getCompoundPaddingLeft();
5385                    final int compoundPaddingRight = getCompoundPaddingRight();
5386                    final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft;
5387
5388                    scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2;
5389                    scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom);
5390                    handled = true;
5391                }
5392            }
5393
5394            if (handled) {
5395                invalidate(dirty.left + scrollX, dirty.top + scrollY,
5396                        dirty.right + scrollX, dirty.bottom + scrollY);
5397            }
5398        }
5399
5400        if (!handled) {
5401            super.invalidateDrawable(drawable);
5402        }
5403    }
5404
5405    @Override
5406    public boolean hasOverlappingRendering() {
5407        // horizontal fading edge causes SaveLayerAlpha, which doesn't support alpha modulation
5408        return ((getBackground() != null && getBackground().getCurrent() != null)
5409                || mText instanceof Spannable || hasSelection()
5410                || isHorizontalFadingEdgeEnabled());
5411    }
5412
5413    /**
5414     *
5415     * Returns the state of the {@code textIsSelectable} flag (See
5416     * {@link #setTextIsSelectable setTextIsSelectable()}). Although you have to set this flag
5417     * to allow users to select and copy text in a non-editable TextView, the content of an
5418     * {@link EditText} can always be selected, independently of the value of this flag.
5419     * <p>
5420     *
5421     * @return True if the text displayed in this TextView can be selected by the user.
5422     *
5423     * @attr ref android.R.styleable#TextView_textIsSelectable
5424     */
5425    public boolean isTextSelectable() {
5426        return mEditor == null ? false : mEditor.mTextIsSelectable;
5427    }
5428
5429    /**
5430     * Sets whether the content of this view is selectable by the user. The default is
5431     * {@code false}, meaning that the content is not selectable.
5432     * <p>
5433     * When you use a TextView to display a useful piece of information to the user (such as a
5434     * contact's address), make it selectable, so that the user can select and copy its
5435     * content. You can also use set the XML attribute
5436     * {@link android.R.styleable#TextView_textIsSelectable} to "true".
5437     * <p>
5438     * When you call this method to set the value of {@code textIsSelectable}, it sets
5439     * the flags {@code focusable}, {@code focusableInTouchMode}, {@code clickable},
5440     * and {@code longClickable} to the same value. These flags correspond to the attributes
5441     * {@link android.R.styleable#View_focusable android:focusable},
5442     * {@link android.R.styleable#View_focusableInTouchMode android:focusableInTouchMode},
5443     * {@link android.R.styleable#View_clickable android:clickable}, and
5444     * {@link android.R.styleable#View_longClickable android:longClickable}. To restore any of these
5445     * flags to a state you had set previously, call one or more of the following methods:
5446     * {@link #setFocusable(boolean) setFocusable()},
5447     * {@link #setFocusableInTouchMode(boolean) setFocusableInTouchMode()},
5448     * {@link #setClickable(boolean) setClickable()} or
5449     * {@link #setLongClickable(boolean) setLongClickable()}.
5450     *
5451     * @param selectable Whether the content of this TextView should be selectable.
5452     */
5453    public void setTextIsSelectable(boolean selectable) {
5454        if (!selectable && mEditor == null) return; // false is default value with no edit data
5455
5456        createEditorIfNeeded();
5457        if (mEditor.mTextIsSelectable == selectable) return;
5458
5459        mEditor.mTextIsSelectable = selectable;
5460        setFocusableInTouchMode(selectable);
5461        setFocusable(selectable);
5462        setClickable(selectable);
5463        setLongClickable(selectable);
5464
5465        // mInputType should already be EditorInfo.TYPE_NULL and mInput should be null
5466
5467        setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null);
5468        setText(mText, selectable ? BufferType.SPANNABLE : BufferType.NORMAL);
5469
5470        // Called by setText above, but safer in case of future code changes
5471        mEditor.prepareCursorControllers();
5472    }
5473
5474    @Override
5475    protected int[] onCreateDrawableState(int extraSpace) {
5476        final int[] drawableState;
5477
5478        if (mSingleLine) {
5479            drawableState = super.onCreateDrawableState(extraSpace);
5480        } else {
5481            drawableState = super.onCreateDrawableState(extraSpace + 1);
5482            mergeDrawableStates(drawableState, MULTILINE_STATE_SET);
5483        }
5484
5485        if (isTextSelectable()) {
5486            // Disable pressed state, which was introduced when TextView was made clickable.
5487            // Prevents text color change.
5488            // setClickable(false) would have a similar effect, but it also disables focus changes
5489            // and long press actions, which are both needed by text selection.
5490            final int length = drawableState.length;
5491            for (int i = 0; i < length; i++) {
5492                if (drawableState[i] == R.attr.state_pressed) {
5493                    final int[] nonPressedState = new int[length - 1];
5494                    System.arraycopy(drawableState, 0, nonPressedState, 0, i);
5495                    System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1);
5496                    return nonPressedState;
5497                }
5498            }
5499        }
5500
5501        return drawableState;
5502    }
5503
5504    private Path getUpdatedHighlightPath() {
5505        Path highlight = null;
5506        Paint highlightPaint = mHighlightPaint;
5507
5508        final int selStart = getSelectionStart();
5509        final int selEnd = getSelectionEnd();
5510        if (mMovement != null && (isFocused() || isPressed()) && selStart >= 0) {
5511            if (selStart == selEnd) {
5512                if (mEditor != null && mEditor.isCursorVisible() &&
5513                        (SystemClock.uptimeMillis() - mEditor.mShowCursor) %
5514                        (2 * Editor.BLINK) < Editor.BLINK) {
5515                    if (mHighlightPathBogus) {
5516                        if (mHighlightPath == null) mHighlightPath = new Path();
5517                        mHighlightPath.reset();
5518                        mLayout.getCursorPath(selStart, mHighlightPath, mText);
5519                        mEditor.updateCursorsPositions();
5520                        mHighlightPathBogus = false;
5521                    }
5522
5523                    // XXX should pass to skin instead of drawing directly
5524                    highlightPaint.setColor(mCurTextColor);
5525                    highlightPaint.setStyle(Paint.Style.STROKE);
5526                    highlight = mHighlightPath;
5527                }
5528            } else {
5529                if (mHighlightPathBogus) {
5530                    if (mHighlightPath == null) mHighlightPath = new Path();
5531                    mHighlightPath.reset();
5532                    mLayout.getSelectionPath(selStart, selEnd, mHighlightPath);
5533                    mHighlightPathBogus = false;
5534                }
5535
5536                // XXX should pass to skin instead of drawing directly
5537                highlightPaint.setColor(mHighlightColor);
5538                highlightPaint.setStyle(Paint.Style.FILL);
5539
5540                highlight = mHighlightPath;
5541            }
5542        }
5543        return highlight;
5544    }
5545
5546    /**
5547     * @hide
5548     */
5549    public int getHorizontalOffsetForDrawables() {
5550        return 0;
5551    }
5552
5553    @Override
5554    protected void onDraw(Canvas canvas) {
5555        restartMarqueeIfNeeded();
5556
5557        // Draw the background for this view
5558        super.onDraw(canvas);
5559
5560        final int compoundPaddingLeft = getCompoundPaddingLeft();
5561        final int compoundPaddingTop = getCompoundPaddingTop();
5562        final int compoundPaddingRight = getCompoundPaddingRight();
5563        final int compoundPaddingBottom = getCompoundPaddingBottom();
5564        final int scrollX = mScrollX;
5565        final int scrollY = mScrollY;
5566        final int right = mRight;
5567        final int left = mLeft;
5568        final int bottom = mBottom;
5569        final int top = mTop;
5570        final boolean isLayoutRtl = isLayoutRtl();
5571        final int offset = getHorizontalOffsetForDrawables();
5572        final int leftOffset = isLayoutRtl ? 0 : offset;
5573        final int rightOffset = isLayoutRtl ? offset : 0 ;
5574
5575        final Drawables dr = mDrawables;
5576        if (dr != null) {
5577            /*
5578             * Compound, not extended, because the icon is not clipped
5579             * if the text height is smaller.
5580             */
5581
5582            int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop;
5583            int hspace = right - left - compoundPaddingRight - compoundPaddingLeft;
5584
5585            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
5586            // Make sure to update invalidateDrawable() when changing this code.
5587            if (dr.mShowing[Drawables.LEFT] != null) {
5588                canvas.save();
5589                canvas.translate(scrollX + mPaddingLeft + leftOffset,
5590                                 scrollY + compoundPaddingTop +
5591                                 (vspace - dr.mDrawableHeightLeft) / 2);
5592                dr.mShowing[Drawables.LEFT].draw(canvas);
5593                canvas.restore();
5594            }
5595
5596            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
5597            // Make sure to update invalidateDrawable() when changing this code.
5598            if (dr.mShowing[Drawables.RIGHT] != null) {
5599                canvas.save();
5600                canvas.translate(scrollX + right - left - mPaddingRight
5601                        - dr.mDrawableSizeRight - rightOffset,
5602                         scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2);
5603                dr.mShowing[Drawables.RIGHT].draw(canvas);
5604                canvas.restore();
5605            }
5606
5607            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
5608            // Make sure to update invalidateDrawable() when changing this code.
5609            if (dr.mShowing[Drawables.TOP] != null) {
5610                canvas.save();
5611                canvas.translate(scrollX + compoundPaddingLeft +
5612                        (hspace - dr.mDrawableWidthTop) / 2, scrollY + mPaddingTop);
5613                dr.mShowing[Drawables.TOP].draw(canvas);
5614                canvas.restore();
5615            }
5616
5617            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
5618            // Make sure to update invalidateDrawable() when changing this code.
5619            if (dr.mShowing[Drawables.BOTTOM] != null) {
5620                canvas.save();
5621                canvas.translate(scrollX + compoundPaddingLeft +
5622                        (hspace - dr.mDrawableWidthBottom) / 2,
5623                         scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom);
5624                dr.mShowing[Drawables.BOTTOM].draw(canvas);
5625                canvas.restore();
5626            }
5627        }
5628
5629        int color = mCurTextColor;
5630
5631        if (mLayout == null) {
5632            assumeLayout();
5633        }
5634
5635        Layout layout = mLayout;
5636
5637        if (mHint != null && mText.length() == 0) {
5638            if (mHintTextColor != null) {
5639                color = mCurHintTextColor;
5640            }
5641
5642            layout = mHintLayout;
5643        }
5644
5645        mTextPaint.setColor(color);
5646        mTextPaint.drawableState = getDrawableState();
5647
5648        canvas.save();
5649        /*  Would be faster if we didn't have to do this. Can we chop the
5650            (displayable) text so that we don't need to do this ever?
5651        */
5652
5653        int extendedPaddingTop = getExtendedPaddingTop();
5654        int extendedPaddingBottom = getExtendedPaddingBottom();
5655
5656        final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
5657        final int maxScrollY = mLayout.getHeight() - vspace;
5658
5659        float clipLeft = compoundPaddingLeft + scrollX;
5660        float clipTop = (scrollY == 0) ? 0 : extendedPaddingTop + scrollY;
5661        float clipRight = right - left - getFudgedPaddingRight() + scrollX;
5662        float clipBottom = bottom - top + scrollY -
5663                ((scrollY == maxScrollY) ? 0 : extendedPaddingBottom);
5664
5665        if (mShadowRadius != 0) {
5666            clipLeft += Math.min(0, mShadowDx - mShadowRadius);
5667            clipRight += Math.max(0, mShadowDx + mShadowRadius);
5668
5669            clipTop += Math.min(0, mShadowDy - mShadowRadius);
5670            clipBottom += Math.max(0, mShadowDy + mShadowRadius);
5671        }
5672
5673        canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom);
5674
5675        int voffsetText = 0;
5676        int voffsetCursor = 0;
5677
5678        // translate in by our padding
5679        /* shortcircuit calling getVerticaOffset() */
5680        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
5681            voffsetText = getVerticalOffset(false);
5682            voffsetCursor = getVerticalOffset(true);
5683        }
5684        canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText);
5685
5686        final int layoutDirection = getLayoutDirection();
5687        final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
5688        if (mEllipsize == TextUtils.TruncateAt.MARQUEE &&
5689                mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
5690            if (!mSingleLine && getLineCount() == 1 && canMarquee() &&
5691                    (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) {
5692                final int width = mRight - mLeft;
5693                final int padding = getCompoundPaddingLeft() + getCompoundPaddingRight();
5694                final float dx = mLayout.getLineRight(0) - (width - padding);
5695                canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f);
5696            }
5697
5698            if (mMarquee != null && mMarquee.isRunning()) {
5699                final float dx = -mMarquee.getScroll();
5700                canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f);
5701            }
5702        }
5703
5704        final int cursorOffsetVertical = voffsetCursor - voffsetText;
5705
5706        Path highlight = getUpdatedHighlightPath();
5707        if (mEditor != null) {
5708            mEditor.onDraw(canvas, layout, highlight, mHighlightPaint, cursorOffsetVertical);
5709        } else {
5710            layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
5711        }
5712
5713        if (mMarquee != null && mMarquee.shouldDrawGhost()) {
5714            final float dx = mMarquee.getGhostOffset();
5715            canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f);
5716            layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
5717        }
5718
5719        canvas.restore();
5720    }
5721
5722    @Override
5723    public void getFocusedRect(Rect r) {
5724        if (mLayout == null) {
5725            super.getFocusedRect(r);
5726            return;
5727        }
5728
5729        int selEnd = getSelectionEnd();
5730        if (selEnd < 0) {
5731            super.getFocusedRect(r);
5732            return;
5733        }
5734
5735        int selStart = getSelectionStart();
5736        if (selStart < 0 || selStart >= selEnd) {
5737            int line = mLayout.getLineForOffset(selEnd);
5738            r.top = mLayout.getLineTop(line);
5739            r.bottom = mLayout.getLineBottom(line);
5740            r.left = (int) mLayout.getPrimaryHorizontal(selEnd) - 2;
5741            r.right = r.left + 4;
5742        } else {
5743            int lineStart = mLayout.getLineForOffset(selStart);
5744            int lineEnd = mLayout.getLineForOffset(selEnd);
5745            r.top = mLayout.getLineTop(lineStart);
5746            r.bottom = mLayout.getLineBottom(lineEnd);
5747            if (lineStart == lineEnd) {
5748                r.left = (int) mLayout.getPrimaryHorizontal(selStart);
5749                r.right = (int) mLayout.getPrimaryHorizontal(selEnd);
5750            } else {
5751                // Selection extends across multiple lines -- make the focused
5752                // rect cover the entire width.
5753                if (mHighlightPathBogus) {
5754                    if (mHighlightPath == null) mHighlightPath = new Path();
5755                    mHighlightPath.reset();
5756                    mLayout.getSelectionPath(selStart, selEnd, mHighlightPath);
5757                    mHighlightPathBogus = false;
5758                }
5759                synchronized (TEMP_RECTF) {
5760                    mHighlightPath.computeBounds(TEMP_RECTF, true);
5761                    r.left = (int)TEMP_RECTF.left-1;
5762                    r.right = (int)TEMP_RECTF.right+1;
5763                }
5764            }
5765        }
5766
5767        // Adjust for padding and gravity.
5768        int paddingLeft = getCompoundPaddingLeft();
5769        int paddingTop = getExtendedPaddingTop();
5770        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
5771            paddingTop += getVerticalOffset(false);
5772        }
5773        r.offset(paddingLeft, paddingTop);
5774        int paddingBottom = getExtendedPaddingBottom();
5775        r.bottom += paddingBottom;
5776    }
5777
5778    /**
5779     * Return the number of lines of text, or 0 if the internal Layout has not
5780     * been built.
5781     */
5782    public int getLineCount() {
5783        return mLayout != null ? mLayout.getLineCount() : 0;
5784    }
5785
5786    /**
5787     * Return the baseline for the specified line (0...getLineCount() - 1)
5788     * If bounds is not null, return the top, left, right, bottom extents
5789     * of the specified line in it. If the internal Layout has not been built,
5790     * return 0 and set bounds to (0, 0, 0, 0)
5791     * @param line which line to examine (0..getLineCount() - 1)
5792     * @param bounds Optional. If not null, it returns the extent of the line
5793     * @return the Y-coordinate of the baseline
5794     */
5795    public int getLineBounds(int line, Rect bounds) {
5796        if (mLayout == null) {
5797            if (bounds != null) {
5798                bounds.set(0, 0, 0, 0);
5799            }
5800            return 0;
5801        }
5802        else {
5803            int baseline = mLayout.getLineBounds(line, bounds);
5804
5805            int voffset = getExtendedPaddingTop();
5806            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
5807                voffset += getVerticalOffset(true);
5808            }
5809            if (bounds != null) {
5810                bounds.offset(getCompoundPaddingLeft(), voffset);
5811            }
5812            return baseline + voffset;
5813        }
5814    }
5815
5816    @Override
5817    public int getBaseline() {
5818        if (mLayout == null) {
5819            return super.getBaseline();
5820        }
5821
5822        int voffset = 0;
5823        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
5824            voffset = getVerticalOffset(true);
5825        }
5826
5827        if (isLayoutModeOptical(mParent)) {
5828            voffset -= getOpticalInsets().top;
5829        }
5830
5831        return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0);
5832    }
5833
5834    /**
5835     * @hide
5836     */
5837    @Override
5838    protected int getFadeTop(boolean offsetRequired) {
5839        if (mLayout == null) return 0;
5840
5841        int voffset = 0;
5842        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
5843            voffset = getVerticalOffset(true);
5844        }
5845
5846        if (offsetRequired) voffset += getTopPaddingOffset();
5847
5848        return getExtendedPaddingTop() + voffset;
5849    }
5850
5851    /**
5852     * @hide
5853     */
5854    @Override
5855    protected int getFadeHeight(boolean offsetRequired) {
5856        return mLayout != null ? mLayout.getHeight() : 0;
5857    }
5858
5859    @Override
5860    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
5861        // Note: If the IME is in fullscreen mode and IMS#mExtractEditText is in text action mode,
5862        // InputMethodService#onKeyDown and InputMethodService#onKeyUp are responsible to call
5863        // InputMethodService#mExtractEditText.maybeHandleBackInTextActionMode(event).
5864        if (keyCode == KeyEvent.KEYCODE_BACK && handleBackInTextActionModeIfNeeded(event)) {
5865            return true;
5866        }
5867        return super.onKeyPreIme(keyCode, event);
5868    }
5869
5870    /**
5871     * @hide
5872     */
5873    public boolean handleBackInTextActionModeIfNeeded(KeyEvent event) {
5874        // Do nothing unless mEditor is in text action mode.
5875        if (mEditor == null || mEditor.mTextActionMode == null) {
5876            return false;
5877        }
5878
5879        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
5880            KeyEvent.DispatcherState state = getKeyDispatcherState();
5881            if (state != null) {
5882                state.startTracking(event, this);
5883            }
5884            return true;
5885        } else if (event.getAction() == KeyEvent.ACTION_UP) {
5886            KeyEvent.DispatcherState state = getKeyDispatcherState();
5887            if (state != null) {
5888                state.handleUpEvent(event);
5889            }
5890            if (event.isTracking() && !event.isCanceled()) {
5891                stopTextActionMode();
5892                return true;
5893            }
5894        }
5895        return false;
5896    }
5897
5898    @Override
5899    public boolean onKeyDown(int keyCode, KeyEvent event) {
5900        int which = doKeyDown(keyCode, event, null);
5901        if (which == 0) {
5902            return super.onKeyDown(keyCode, event);
5903        }
5904
5905        return true;
5906    }
5907
5908    @Override
5909    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
5910        KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN);
5911
5912        int which = doKeyDown(keyCode, down, event);
5913        if (which == 0) {
5914            // Go through default dispatching.
5915            return super.onKeyMultiple(keyCode, repeatCount, event);
5916        }
5917        if (which == -1) {
5918            // Consumed the whole thing.
5919            return true;
5920        }
5921
5922        repeatCount--;
5923
5924        // We are going to dispatch the remaining events to either the input
5925        // or movement method.  To do this, we will just send a repeated stream
5926        // of down and up events until we have done the complete repeatCount.
5927        // It would be nice if those interfaces had an onKeyMultiple() method,
5928        // but adding that is a more complicated change.
5929        KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP);
5930        if (which == 1) {
5931            // mEditor and mEditor.mInput are not null from doKeyDown
5932            mEditor.mKeyListener.onKeyUp(this, (Editable)mText, keyCode, up);
5933            while (--repeatCount > 0) {
5934                mEditor.mKeyListener.onKeyDown(this, (Editable)mText, keyCode, down);
5935                mEditor.mKeyListener.onKeyUp(this, (Editable)mText, keyCode, up);
5936            }
5937            hideErrorIfUnchanged();
5938
5939        } else if (which == 2) {
5940            // mMovement is not null from doKeyDown
5941            mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
5942            while (--repeatCount > 0) {
5943                mMovement.onKeyDown(this, (Spannable)mText, keyCode, down);
5944                mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
5945            }
5946        }
5947
5948        return true;
5949    }
5950
5951    /**
5952     * Returns true if pressing ENTER in this field advances focus instead
5953     * of inserting the character.  This is true mostly in single-line fields,
5954     * but also in mail addresses and subjects which will display on multiple
5955     * lines but where it doesn't make sense to insert newlines.
5956     */
5957    private boolean shouldAdvanceFocusOnEnter() {
5958        if (getKeyListener() == null) {
5959            return false;
5960        }
5961
5962        if (mSingleLine) {
5963            return true;
5964        }
5965
5966        if (mEditor != null &&
5967                (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
5968            int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION;
5969            if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
5970                    || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) {
5971                return true;
5972            }
5973        }
5974
5975        return false;
5976    }
5977
5978    /**
5979     * Returns true if pressing TAB in this field advances focus instead
5980     * of inserting the character.  Insert tabs only in multi-line editors.
5981     */
5982    private boolean shouldAdvanceFocusOnTab() {
5983        if (getKeyListener() != null && !mSingleLine && mEditor != null &&
5984                (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
5985            int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION;
5986            if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE
5987                    || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) {
5988                return false;
5989            }
5990        }
5991        return true;
5992    }
5993
5994    private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) {
5995        if (!isEnabled()) {
5996            return 0;
5997        }
5998
5999        // If this is the initial keydown, we don't want to prevent a movement away from this view.
6000        // While this shouldn't be necessary because any time we're preventing default movement we
6001        // should be restricting the focus to remain within this view, thus we'll also receive
6002        // the key up event, occasionally key up events will get dropped and we don't want to
6003        // prevent the user from traversing out of this on the next key down.
6004        if (event.getRepeatCount() == 0 && !KeyEvent.isModifierKey(keyCode)) {
6005            mPreventDefaultMovement = false;
6006        }
6007
6008        switch (keyCode) {
6009            case KeyEvent.KEYCODE_ENTER:
6010                if (event.hasNoModifiers()) {
6011                    // When mInputContentType is set, we know that we are
6012                    // running in a "modern" cupcake environment, so don't need
6013                    // to worry about the application trying to capture
6014                    // enter key events.
6015                    if (mEditor != null && mEditor.mInputContentType != null) {
6016                        // If there is an action listener, given them a
6017                        // chance to consume the event.
6018                        if (mEditor.mInputContentType.onEditorActionListener != null &&
6019                                mEditor.mInputContentType.onEditorActionListener.onEditorAction(
6020                                this, EditorInfo.IME_NULL, event)) {
6021                            mEditor.mInputContentType.enterDown = true;
6022                            // We are consuming the enter key for them.
6023                            return -1;
6024                        }
6025                    }
6026
6027                    // If our editor should move focus when enter is pressed, or
6028                    // this is a generated event from an IME action button, then
6029                    // don't let it be inserted into the text.
6030                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
6031                            || shouldAdvanceFocusOnEnter()) {
6032                        if (hasOnClickListeners()) {
6033                            return 0;
6034                        }
6035                        return -1;
6036                    }
6037                }
6038                break;
6039
6040            case KeyEvent.KEYCODE_DPAD_CENTER:
6041                if (event.hasNoModifiers()) {
6042                    if (shouldAdvanceFocusOnEnter()) {
6043                        return 0;
6044                    }
6045                }
6046                break;
6047
6048            case KeyEvent.KEYCODE_TAB:
6049                if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
6050                    if (shouldAdvanceFocusOnTab()) {
6051                        return 0;
6052                    }
6053                }
6054                break;
6055
6056                // Has to be done on key down (and not on key up) to correctly be intercepted.
6057            case KeyEvent.KEYCODE_BACK:
6058                if (mEditor != null && mEditor.mTextActionMode != null) {
6059                    stopTextActionMode();
6060                    return -1;
6061                }
6062                break;
6063        }
6064
6065        if (mEditor != null && mEditor.mKeyListener != null) {
6066            boolean doDown = true;
6067            if (otherEvent != null) {
6068                try {
6069                    beginBatchEdit();
6070                    final boolean handled = mEditor.mKeyListener.onKeyOther(this, (Editable) mText,
6071                            otherEvent);
6072                    hideErrorIfUnchanged();
6073                    doDown = false;
6074                    if (handled) {
6075                        return -1;
6076                    }
6077                } catch (AbstractMethodError e) {
6078                    // onKeyOther was added after 1.0, so if it isn't
6079                    // implemented we need to try to dispatch as a regular down.
6080                } finally {
6081                    endBatchEdit();
6082                }
6083            }
6084
6085            if (doDown) {
6086                beginBatchEdit();
6087                final boolean handled = mEditor.mKeyListener.onKeyDown(this, (Editable) mText,
6088                        keyCode, event);
6089                endBatchEdit();
6090                hideErrorIfUnchanged();
6091                if (handled) return 1;
6092            }
6093        }
6094
6095        // bug 650865: sometimes we get a key event before a layout.
6096        // don't try to move around if we don't know the layout.
6097
6098        if (mMovement != null && mLayout != null) {
6099            boolean doDown = true;
6100            if (otherEvent != null) {
6101                try {
6102                    boolean handled = mMovement.onKeyOther(this, (Spannable) mText,
6103                            otherEvent);
6104                    doDown = false;
6105                    if (handled) {
6106                        return -1;
6107                    }
6108                } catch (AbstractMethodError e) {
6109                    // onKeyOther was added after 1.0, so if it isn't
6110                    // implemented we need to try to dispatch as a regular down.
6111                }
6112            }
6113            if (doDown) {
6114                if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) {
6115                    if (event.getRepeatCount() == 0 && !KeyEvent.isModifierKey(keyCode)) {
6116                        mPreventDefaultMovement = true;
6117                    }
6118                    return 2;
6119                }
6120            }
6121        }
6122
6123        return mPreventDefaultMovement && !KeyEvent.isModifierKey(keyCode) ? -1 : 0;
6124    }
6125
6126    /**
6127     * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)}
6128     * can be recorded.
6129     * @hide
6130     */
6131    public void resetErrorChangedFlag() {
6132        /*
6133         * Keep track of what the error was before doing the input
6134         * so that if an input filter changed the error, we leave
6135         * that error showing.  Otherwise, we take down whatever
6136         * error was showing when the user types something.
6137         */
6138        if (mEditor != null) mEditor.mErrorWasChanged = false;
6139    }
6140
6141    /**
6142     * @hide
6143     */
6144    public void hideErrorIfUnchanged() {
6145        if (mEditor != null && mEditor.mError != null && !mEditor.mErrorWasChanged) {
6146            setError(null, null);
6147        }
6148    }
6149
6150    @Override
6151    public boolean onKeyUp(int keyCode, KeyEvent event) {
6152        if (!isEnabled()) {
6153            return super.onKeyUp(keyCode, event);
6154        }
6155
6156        if (!KeyEvent.isModifierKey(keyCode)) {
6157            mPreventDefaultMovement = false;
6158        }
6159
6160        switch (keyCode) {
6161            case KeyEvent.KEYCODE_DPAD_CENTER:
6162                if (event.hasNoModifiers()) {
6163                    /*
6164                     * If there is a click listener, just call through to
6165                     * super, which will invoke it.
6166                     *
6167                     * If there isn't a click listener, try to show the soft
6168                     * input method.  (It will also
6169                     * call performClick(), but that won't do anything in
6170                     * this case.)
6171                     */
6172                    if (!hasOnClickListeners()) {
6173                        if (mMovement != null && mText instanceof Editable
6174                                && mLayout != null && onCheckIsTextEditor()) {
6175                            InputMethodManager imm = InputMethodManager.peekInstance();
6176                            viewClicked(imm);
6177                            if (imm != null && getShowSoftInputOnFocus()) {
6178                                imm.showSoftInput(this, 0);
6179                            }
6180                        }
6181                    }
6182                }
6183                return super.onKeyUp(keyCode, event);
6184
6185            case KeyEvent.KEYCODE_ENTER:
6186                if (event.hasNoModifiers()) {
6187                    if (mEditor != null && mEditor.mInputContentType != null
6188                            && mEditor.mInputContentType.onEditorActionListener != null
6189                            && mEditor.mInputContentType.enterDown) {
6190                        mEditor.mInputContentType.enterDown = false;
6191                        if (mEditor.mInputContentType.onEditorActionListener.onEditorAction(
6192                                this, EditorInfo.IME_NULL, event)) {
6193                            return true;
6194                        }
6195                    }
6196
6197                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
6198                            || shouldAdvanceFocusOnEnter()) {
6199                        /*
6200                         * If there is a click listener, just call through to
6201                         * super, which will invoke it.
6202                         *
6203                         * If there isn't a click listener, try to advance focus,
6204                         * but still call through to super, which will reset the
6205                         * pressed state and longpress state.  (It will also
6206                         * call performClick(), but that won't do anything in
6207                         * this case.)
6208                         */
6209                        if (!hasOnClickListeners()) {
6210                            View v = focusSearch(FOCUS_DOWN);
6211
6212                            if (v != null) {
6213                                if (!v.requestFocus(FOCUS_DOWN)) {
6214                                    throw new IllegalStateException(
6215                                            "focus search returned a view " +
6216                                            "that wasn't able to take focus!");
6217                                }
6218
6219                                /*
6220                                 * Return true because we handled the key; super
6221                                 * will return false because there was no click
6222                                 * listener.
6223                                 */
6224                                super.onKeyUp(keyCode, event);
6225                                return true;
6226                            } else if ((event.getFlags()
6227                                    & KeyEvent.FLAG_EDITOR_ACTION) != 0) {
6228                                // No target for next focus, but make sure the IME
6229                                // if this came from it.
6230                                InputMethodManager imm = InputMethodManager.peekInstance();
6231                                if (imm != null && imm.isActive(this)) {
6232                                    imm.hideSoftInputFromWindow(getWindowToken(), 0);
6233                                }
6234                            }
6235                        }
6236                    }
6237                    return super.onKeyUp(keyCode, event);
6238                }
6239                break;
6240        }
6241
6242        if (mEditor != null && mEditor.mKeyListener != null)
6243            if (mEditor.mKeyListener.onKeyUp(this, (Editable) mText, keyCode, event))
6244                return true;
6245
6246        if (mMovement != null && mLayout != null)
6247            if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event))
6248                return true;
6249
6250        return super.onKeyUp(keyCode, event);
6251    }
6252
6253    @Override
6254    public boolean onCheckIsTextEditor() {
6255        return mEditor != null && mEditor.mInputType != EditorInfo.TYPE_NULL;
6256    }
6257
6258    @Override
6259    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6260        if (onCheckIsTextEditor() && isEnabled()) {
6261            mEditor.createInputMethodStateIfNeeded();
6262            outAttrs.inputType = getInputType();
6263            if (mEditor.mInputContentType != null) {
6264                outAttrs.imeOptions = mEditor.mInputContentType.imeOptions;
6265                outAttrs.privateImeOptions = mEditor.mInputContentType.privateImeOptions;
6266                outAttrs.actionLabel = mEditor.mInputContentType.imeActionLabel;
6267                outAttrs.actionId = mEditor.mInputContentType.imeActionId;
6268                outAttrs.extras = mEditor.mInputContentType.extras;
6269            } else {
6270                outAttrs.imeOptions = EditorInfo.IME_NULL;
6271            }
6272            if (focusSearch(FOCUS_DOWN) != null) {
6273                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT;
6274            }
6275            if (focusSearch(FOCUS_UP) != null) {
6276                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS;
6277            }
6278            if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION)
6279                    == EditorInfo.IME_ACTION_UNSPECIFIED) {
6280                if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) {
6281                    // An action has not been set, but the enter key will move to
6282                    // the next focus, so set the action to that.
6283                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT;
6284                } else {
6285                    // An action has not been set, and there is no focus to move
6286                    // to, so let's just supply a "done" action.
6287                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
6288                }
6289                if (!shouldAdvanceFocusOnEnter()) {
6290                    outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
6291                }
6292            }
6293            if (isMultilineInputType(outAttrs.inputType)) {
6294                // Multi-line text editors should always show an enter key.
6295                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
6296            }
6297            outAttrs.hintText = mHint;
6298            if (mText instanceof Editable) {
6299                InputConnection ic = new EditableInputConnection(this);
6300                outAttrs.initialSelStart = getSelectionStart();
6301                outAttrs.initialSelEnd = getSelectionEnd();
6302                outAttrs.initialCapsMode = ic.getCursorCapsMode(getInputType());
6303                return ic;
6304            }
6305        }
6306        return null;
6307    }
6308
6309    /**
6310     * If this TextView contains editable content, extract a portion of it
6311     * based on the information in <var>request</var> in to <var>outText</var>.
6312     * @return Returns true if the text was successfully extracted, else false.
6313     */
6314    public boolean extractText(ExtractedTextRequest request, ExtractedText outText) {
6315        createEditorIfNeeded();
6316        return mEditor.extractText(request, outText);
6317    }
6318
6319    /**
6320     * This is used to remove all style-impacting spans from text before new
6321     * extracted text is being replaced into it, so that we don't have any
6322     * lingering spans applied during the replace.
6323     */
6324    static void removeParcelableSpans(Spannable spannable, int start, int end) {
6325        Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class);
6326        int i = spans.length;
6327        while (i > 0) {
6328            i--;
6329            spannable.removeSpan(spans[i]);
6330        }
6331    }
6332
6333    /**
6334     * Apply to this text view the given extracted text, as previously
6335     * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}.
6336     */
6337    public void setExtractedText(ExtractedText text) {
6338        Editable content = getEditableText();
6339        if (text.text != null) {
6340            if (content == null) {
6341                setText(text.text, TextView.BufferType.EDITABLE);
6342            } else if (text.partialStartOffset < 0) {
6343                removeParcelableSpans(content, 0, content.length());
6344                content.replace(0, content.length(), text.text);
6345            } else {
6346                final int N = content.length();
6347                int start = text.partialStartOffset;
6348                if (start > N) start = N;
6349                int end = text.partialEndOffset;
6350                if (end > N) end = N;
6351                removeParcelableSpans(content, start, end);
6352                content.replace(start, end, text.text);
6353            }
6354        }
6355
6356        // Now set the selection position...  make sure it is in range, to
6357        // avoid crashes.  If this is a partial update, it is possible that
6358        // the underlying text may have changed, causing us problems here.
6359        // Also we just don't want to trust clients to do the right thing.
6360        Spannable sp = (Spannable)getText();
6361        final int N = sp.length();
6362        int start = text.selectionStart;
6363        if (start < 0) start = 0;
6364        else if (start > N) start = N;
6365        int end = text.selectionEnd;
6366        if (end < 0) end = 0;
6367        else if (end > N) end = N;
6368        Selection.setSelection(sp, start, end);
6369
6370        // Finally, update the selection mode.
6371        if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) {
6372            MetaKeyKeyListener.startSelecting(this, sp);
6373        } else {
6374            MetaKeyKeyListener.stopSelecting(this, sp);
6375        }
6376    }
6377
6378    /**
6379     * @hide
6380     */
6381    public void setExtracting(ExtractedTextRequest req) {
6382        if (mEditor.mInputMethodState != null) {
6383            mEditor.mInputMethodState.mExtractedTextRequest = req;
6384        }
6385        // This would stop a possible selection mode, but no such mode is started in case
6386        // extracted mode will start. Some text is selected though, and will trigger an action mode
6387        // in the extracted view.
6388        mEditor.hideCursorAndSpanControllers();
6389        stopTextActionMode();
6390    }
6391
6392    /**
6393     * Called by the framework in response to a text completion from
6394     * the current input method, provided by it calling
6395     * {@link InputConnection#commitCompletion
6396     * InputConnection.commitCompletion()}.  The default implementation does
6397     * nothing; text views that are supporting auto-completion should override
6398     * this to do their desired behavior.
6399     *
6400     * @param text The auto complete text the user has selected.
6401     */
6402    public void onCommitCompletion(CompletionInfo text) {
6403        // intentionally empty
6404    }
6405
6406    /**
6407     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
6408     * a dictionnary) from the current input method, provided by it calling
6409     * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
6410     * implementation flashes the background of the corrected word to provide feedback to the user.
6411     *
6412     * @param info The auto correct info about the text that was corrected.
6413     */
6414    public void onCommitCorrection(CorrectionInfo info) {
6415        if (mEditor != null) mEditor.onCommitCorrection(info);
6416    }
6417
6418    public void beginBatchEdit() {
6419        if (mEditor != null) mEditor.beginBatchEdit();
6420    }
6421
6422    public void endBatchEdit() {
6423        if (mEditor != null) mEditor.endBatchEdit();
6424    }
6425
6426    /**
6427     * Called by the framework in response to a request to begin a batch
6428     * of edit operations through a call to link {@link #beginBatchEdit()}.
6429     */
6430    public void onBeginBatchEdit() {
6431        // intentionally empty
6432    }
6433
6434    /**
6435     * Called by the framework in response to a request to end a batch
6436     * of edit operations through a call to link {@link #endBatchEdit}.
6437     */
6438    public void onEndBatchEdit() {
6439        // intentionally empty
6440    }
6441
6442    /**
6443     * Called by the framework in response to a private command from the
6444     * current method, provided by it calling
6445     * {@link InputConnection#performPrivateCommand
6446     * InputConnection.performPrivateCommand()}.
6447     *
6448     * @param action The action name of the command.
6449     * @param data Any additional data for the command.  This may be null.
6450     * @return Return true if you handled the command, else false.
6451     */
6452    public boolean onPrivateIMECommand(String action, Bundle data) {
6453        return false;
6454    }
6455
6456    private void nullLayouts() {
6457        if (mLayout instanceof BoringLayout && mSavedLayout == null) {
6458            mSavedLayout = (BoringLayout) mLayout;
6459        }
6460        if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) {
6461            mSavedHintLayout = (BoringLayout) mHintLayout;
6462        }
6463
6464        mSavedMarqueeModeLayout = mLayout = mHintLayout = null;
6465
6466        mBoring = mHintBoring = null;
6467
6468        // Since it depends on the value of mLayout
6469        if (mEditor != null) mEditor.prepareCursorControllers();
6470    }
6471
6472    /**
6473     * Make a new Layout based on the already-measured size of the view,
6474     * on the assumption that it was measured correctly at some point.
6475     */
6476    private void assumeLayout() {
6477        int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6478
6479        if (width < 1) {
6480            width = 0;
6481        }
6482
6483        int physicalWidth = width;
6484
6485        if (mHorizontallyScrolling) {
6486            width = VERY_WIDE;
6487        }
6488
6489        makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING,
6490                      physicalWidth, false);
6491    }
6492
6493    private Layout.Alignment getLayoutAlignment() {
6494        Layout.Alignment alignment;
6495        switch (getTextAlignment()) {
6496            case TEXT_ALIGNMENT_GRAVITY:
6497                switch (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) {
6498                    case Gravity.START:
6499                        alignment = Layout.Alignment.ALIGN_NORMAL;
6500                        break;
6501                    case Gravity.END:
6502                        alignment = Layout.Alignment.ALIGN_OPPOSITE;
6503                        break;
6504                    case Gravity.LEFT:
6505                        alignment = Layout.Alignment.ALIGN_LEFT;
6506                        break;
6507                    case Gravity.RIGHT:
6508                        alignment = Layout.Alignment.ALIGN_RIGHT;
6509                        break;
6510                    case Gravity.CENTER_HORIZONTAL:
6511                        alignment = Layout.Alignment.ALIGN_CENTER;
6512                        break;
6513                    default:
6514                        alignment = Layout.Alignment.ALIGN_NORMAL;
6515                        break;
6516                }
6517                break;
6518            case TEXT_ALIGNMENT_TEXT_START:
6519                alignment = Layout.Alignment.ALIGN_NORMAL;
6520                break;
6521            case TEXT_ALIGNMENT_TEXT_END:
6522                alignment = Layout.Alignment.ALIGN_OPPOSITE;
6523                break;
6524            case TEXT_ALIGNMENT_CENTER:
6525                alignment = Layout.Alignment.ALIGN_CENTER;
6526                break;
6527            case TEXT_ALIGNMENT_VIEW_START:
6528                alignment = (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
6529                        Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT;
6530                break;
6531            case TEXT_ALIGNMENT_VIEW_END:
6532                alignment = (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
6533                        Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT;
6534                break;
6535            case TEXT_ALIGNMENT_INHERIT:
6536                // This should never happen as we have already resolved the text alignment
6537                // but better safe than sorry so we just fall through
6538            default:
6539                alignment = Layout.Alignment.ALIGN_NORMAL;
6540                break;
6541        }
6542        return alignment;
6543    }
6544
6545    /**
6546     * The width passed in is now the desired layout width,
6547     * not the full view width with padding.
6548     * {@hide}
6549     */
6550    protected void makeNewLayout(int wantWidth, int hintWidth,
6551                                 BoringLayout.Metrics boring,
6552                                 BoringLayout.Metrics hintBoring,
6553                                 int ellipsisWidth, boolean bringIntoView) {
6554        stopMarquee();
6555
6556        // Update "old" cached values
6557        mOldMaximum = mMaximum;
6558        mOldMaxMode = mMaxMode;
6559
6560        mHighlightPathBogus = true;
6561
6562        if (wantWidth < 0) {
6563            wantWidth = 0;
6564        }
6565        if (hintWidth < 0) {
6566            hintWidth = 0;
6567        }
6568
6569        Layout.Alignment alignment = getLayoutAlignment();
6570        final boolean testDirChange = mSingleLine && mLayout != null &&
6571            (alignment == Layout.Alignment.ALIGN_NORMAL ||
6572             alignment == Layout.Alignment.ALIGN_OPPOSITE);
6573        int oldDir = 0;
6574        if (testDirChange) oldDir = mLayout.getParagraphDirection(0);
6575        boolean shouldEllipsize = mEllipsize != null && getKeyListener() == null;
6576        final boolean switchEllipsize = mEllipsize == TruncateAt.MARQUEE &&
6577                mMarqueeFadeMode != MARQUEE_FADE_NORMAL;
6578        TruncateAt effectiveEllipsize = mEllipsize;
6579        if (mEllipsize == TruncateAt.MARQUEE &&
6580                mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
6581            effectiveEllipsize = TruncateAt.END_SMALL;
6582        }
6583
6584        if (mTextDir == null) {
6585            mTextDir = getTextDirectionHeuristic();
6586        }
6587
6588        mLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize,
6589                effectiveEllipsize, effectiveEllipsize == mEllipsize);
6590        if (switchEllipsize) {
6591            TruncateAt oppositeEllipsize = effectiveEllipsize == TruncateAt.MARQUEE ?
6592                    TruncateAt.END : TruncateAt.MARQUEE;
6593            mSavedMarqueeModeLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment,
6594                    shouldEllipsize, oppositeEllipsize, effectiveEllipsize != mEllipsize);
6595        }
6596
6597        shouldEllipsize = mEllipsize != null;
6598        mHintLayout = null;
6599
6600        if (mHint != null) {
6601            if (shouldEllipsize) hintWidth = wantWidth;
6602
6603            if (hintBoring == UNKNOWN_BORING) {
6604                hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir,
6605                                                   mHintBoring);
6606                if (hintBoring != null) {
6607                    mHintBoring = hintBoring;
6608                }
6609            }
6610
6611            if (hintBoring != null) {
6612                if (hintBoring.width <= hintWidth &&
6613                    (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) {
6614                    if (mSavedHintLayout != null) {
6615                        mHintLayout = mSavedHintLayout.
6616                                replaceOrMake(mHint, mTextPaint,
6617                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6618                                hintBoring, mIncludePad);
6619                    } else {
6620                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
6621                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6622                                hintBoring, mIncludePad);
6623                    }
6624
6625                    mSavedHintLayout = (BoringLayout) mHintLayout;
6626                } else if (shouldEllipsize && hintBoring.width <= hintWidth) {
6627                    if (mSavedHintLayout != null) {
6628                        mHintLayout = mSavedHintLayout.
6629                                replaceOrMake(mHint, mTextPaint,
6630                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6631                                hintBoring, mIncludePad, mEllipsize,
6632                                ellipsisWidth);
6633                    } else {
6634                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
6635                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6636                                hintBoring, mIncludePad, mEllipsize,
6637                                ellipsisWidth);
6638                    }
6639                }
6640            }
6641            // TODO: code duplication with makeSingleLayout()
6642            if (mHintLayout == null) {
6643                StaticLayout.Builder builder = StaticLayout.Builder.obtain(mHint, 0,
6644                        mHint.length(), mTextPaint, hintWidth)
6645                        .setAlignment(alignment)
6646                        .setTextDirection(mTextDir)
6647                        .setLineSpacing(mSpacingAdd, mSpacingMult)
6648                        .setIncludePad(mIncludePad)
6649                        .setBreakStrategy(mBreakStrategy)
6650                        .setHyphenationFrequency(mHyphenationFrequency);
6651                if (shouldEllipsize) {
6652                    builder.setEllipsize(mEllipsize)
6653                            .setEllipsizedWidth(ellipsisWidth)
6654                            .setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
6655                }
6656                mHintLayout = builder.build();
6657            }
6658        }
6659
6660        if (bringIntoView || (testDirChange && oldDir != mLayout.getParagraphDirection(0))) {
6661            registerForPreDraw();
6662        }
6663
6664        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6665            if (!compressText(ellipsisWidth)) {
6666                final int height = mLayoutParams.height;
6667                // If the size of the view does not depend on the size of the text, try to
6668                // start the marquee immediately
6669                if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) {
6670                    startMarquee();
6671                } else {
6672                    // Defer the start of the marquee until we know our width (see setFrame())
6673                    mRestartMarquee = true;
6674                }
6675            }
6676        }
6677
6678        // CursorControllers need a non-null mLayout
6679        if (mEditor != null) mEditor.prepareCursorControllers();
6680    }
6681
6682    private Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth,
6683            Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize,
6684            boolean useSaved) {
6685        Layout result = null;
6686        if (mText instanceof Spannable) {
6687            result = new DynamicLayout(mText, mTransformed, mTextPaint, wantWidth,
6688                    alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad,
6689                    mBreakStrategy, mHyphenationFrequency,
6690                    getKeyListener() == null ? effectiveEllipsize : null, ellipsisWidth);
6691        } else {
6692            if (boring == UNKNOWN_BORING) {
6693                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
6694                if (boring != null) {
6695                    mBoring = boring;
6696                }
6697            }
6698
6699            if (boring != null) {
6700                if (boring.width <= wantWidth &&
6701                        (effectiveEllipsize == null || boring.width <= ellipsisWidth)) {
6702                    if (useSaved && mSavedLayout != null) {
6703                        result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint,
6704                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
6705                                boring, mIncludePad);
6706                    } else {
6707                        result = BoringLayout.make(mTransformed, mTextPaint,
6708                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
6709                                boring, mIncludePad);
6710                    }
6711
6712                    if (useSaved) {
6713                        mSavedLayout = (BoringLayout) result;
6714                    }
6715                } else if (shouldEllipsize && boring.width <= wantWidth) {
6716                    if (useSaved && mSavedLayout != null) {
6717                        result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint,
6718                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
6719                                boring, mIncludePad, effectiveEllipsize,
6720                                ellipsisWidth);
6721                    } else {
6722                        result = BoringLayout.make(mTransformed, mTextPaint,
6723                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
6724                                boring, mIncludePad, effectiveEllipsize,
6725                                ellipsisWidth);
6726                    }
6727                }
6728            }
6729        }
6730        if (result == null) {
6731            StaticLayout.Builder builder = StaticLayout.Builder.obtain(mTransformed,
6732                    0, mTransformed.length(), mTextPaint, wantWidth)
6733                    .setAlignment(alignment)
6734                    .setTextDirection(mTextDir)
6735                    .setLineSpacing(mSpacingAdd, mSpacingMult)
6736                    .setIncludePad(mIncludePad)
6737                    .setBreakStrategy(mBreakStrategy)
6738                    .setHyphenationFrequency(mHyphenationFrequency);
6739            if (shouldEllipsize) {
6740                builder.setEllipsize(effectiveEllipsize)
6741                        .setEllipsizedWidth(ellipsisWidth)
6742                        .setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
6743            }
6744            // TODO: explore always setting maxLines
6745            result = builder.build();
6746        }
6747        return result;
6748    }
6749
6750    private boolean compressText(float width) {
6751        if (isHardwareAccelerated()) return false;
6752
6753        // Only compress the text if it hasn't been compressed by the previous pass
6754        if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX &&
6755                mTextPaint.getTextScaleX() == 1.0f) {
6756            final float textWidth = mLayout.getLineWidth(0);
6757            final float overflow = (textWidth + 1.0f - width) / width;
6758            if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) {
6759                mTextPaint.setTextScaleX(1.0f - overflow - 0.005f);
6760                post(new Runnable() {
6761                    public void run() {
6762                        requestLayout();
6763                    }
6764                });
6765                return true;
6766            }
6767        }
6768
6769        return false;
6770    }
6771
6772    private static int desired(Layout layout) {
6773        int n = layout.getLineCount();
6774        CharSequence text = layout.getText();
6775        float max = 0;
6776
6777        // if any line was wrapped, we can't use it.
6778        // but it's ok for the last line not to have a newline
6779
6780        for (int i = 0; i < n - 1; i++) {
6781            if (text.charAt(layout.getLineEnd(i) - 1) != '\n')
6782                return -1;
6783        }
6784
6785        for (int i = 0; i < n; i++) {
6786            max = Math.max(max, layout.getLineWidth(i));
6787        }
6788
6789        return (int) Math.ceil(max);
6790    }
6791
6792    /**
6793     * Set whether the TextView includes extra top and bottom padding to make
6794     * room for accents that go above the normal ascent and descent.
6795     * The default is true.
6796     *
6797     * @see #getIncludeFontPadding()
6798     *
6799     * @attr ref android.R.styleable#TextView_includeFontPadding
6800     */
6801    public void setIncludeFontPadding(boolean includepad) {
6802        if (mIncludePad != includepad) {
6803            mIncludePad = includepad;
6804
6805            if (mLayout != null) {
6806                nullLayouts();
6807                requestLayout();
6808                invalidate();
6809            }
6810        }
6811    }
6812
6813    /**
6814     * Gets whether the TextView includes extra top and bottom padding to make
6815     * room for accents that go above the normal ascent and descent.
6816     *
6817     * @see #setIncludeFontPadding(boolean)
6818     *
6819     * @attr ref android.R.styleable#TextView_includeFontPadding
6820     */
6821    public boolean getIncludeFontPadding() {
6822        return mIncludePad;
6823    }
6824
6825    private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics();
6826
6827    @Override
6828    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
6829        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
6830        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
6831        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
6832        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
6833
6834        int width;
6835        int height;
6836
6837        BoringLayout.Metrics boring = UNKNOWN_BORING;
6838        BoringLayout.Metrics hintBoring = UNKNOWN_BORING;
6839
6840        if (mTextDir == null) {
6841            mTextDir = getTextDirectionHeuristic();
6842        }
6843
6844        int des = -1;
6845        boolean fromexisting = false;
6846
6847        if (widthMode == MeasureSpec.EXACTLY) {
6848            // Parent has told us how big to be. So be it.
6849            width = widthSize;
6850        } else {
6851            if (mLayout != null && mEllipsize == null) {
6852                des = desired(mLayout);
6853            }
6854
6855            if (des < 0) {
6856                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
6857                if (boring != null) {
6858                    mBoring = boring;
6859                }
6860            } else {
6861                fromexisting = true;
6862            }
6863
6864            if (boring == null || boring == UNKNOWN_BORING) {
6865                if (des < 0) {
6866                    des = (int) Math.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint));
6867                }
6868                width = des;
6869            } else {
6870                width = boring.width;
6871            }
6872
6873            final Drawables dr = mDrawables;
6874            if (dr != null) {
6875                width = Math.max(width, dr.mDrawableWidthTop);
6876                width = Math.max(width, dr.mDrawableWidthBottom);
6877            }
6878
6879            if (mHint != null) {
6880                int hintDes = -1;
6881                int hintWidth;
6882
6883                if (mHintLayout != null && mEllipsize == null) {
6884                    hintDes = desired(mHintLayout);
6885                }
6886
6887                if (hintDes < 0) {
6888                    hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, mHintBoring);
6889                    if (hintBoring != null) {
6890                        mHintBoring = hintBoring;
6891                    }
6892                }
6893
6894                if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
6895                    if (hintDes < 0) {
6896                        hintDes = (int) Math.ceil(Layout.getDesiredWidth(mHint, mTextPaint));
6897                    }
6898                    hintWidth = hintDes;
6899                } else {
6900                    hintWidth = hintBoring.width;
6901                }
6902
6903                if (hintWidth > width) {
6904                    width = hintWidth;
6905                }
6906            }
6907
6908            width += getCompoundPaddingLeft() + getCompoundPaddingRight();
6909
6910            if (mMaxWidthMode == EMS) {
6911                width = Math.min(width, mMaxWidth * getLineHeight());
6912            } else {
6913                width = Math.min(width, mMaxWidth);
6914            }
6915
6916            if (mMinWidthMode == EMS) {
6917                width = Math.max(width, mMinWidth * getLineHeight());
6918            } else {
6919                width = Math.max(width, mMinWidth);
6920            }
6921
6922            // Check against our minimum width
6923            width = Math.max(width, getSuggestedMinimumWidth());
6924
6925            if (widthMode == MeasureSpec.AT_MOST) {
6926                width = Math.min(widthSize, width);
6927            }
6928        }
6929
6930        int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight();
6931        int unpaddedWidth = want;
6932
6933        if (mHorizontallyScrolling) want = VERY_WIDE;
6934
6935        int hintWant = want;
6936        int hintWidth = (mHintLayout == null) ? hintWant : mHintLayout.getWidth();
6937
6938        if (mLayout == null) {
6939            makeNewLayout(want, hintWant, boring, hintBoring,
6940                          width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
6941        } else {
6942            final boolean layoutChanged = (mLayout.getWidth() != want) ||
6943                    (hintWidth != hintWant) ||
6944                    (mLayout.getEllipsizedWidth() !=
6945                            width - getCompoundPaddingLeft() - getCompoundPaddingRight());
6946
6947            final boolean widthChanged = (mHint == null) &&
6948                    (mEllipsize == null) &&
6949                    (want > mLayout.getWidth()) &&
6950                    (mLayout instanceof BoringLayout || (fromexisting && des >= 0 && des <= want));
6951
6952            final boolean maximumChanged = (mMaxMode != mOldMaxMode) || (mMaximum != mOldMaximum);
6953
6954            if (layoutChanged || maximumChanged) {
6955                if (!maximumChanged && widthChanged) {
6956                    mLayout.increaseWidthTo(want);
6957                } else {
6958                    makeNewLayout(want, hintWant, boring, hintBoring,
6959                            width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
6960                }
6961            } else {
6962                // Nothing has changed
6963            }
6964        }
6965
6966        if (heightMode == MeasureSpec.EXACTLY) {
6967            // Parent has told us how big to be. So be it.
6968            height = heightSize;
6969            mDesiredHeightAtMeasure = -1;
6970        } else {
6971            int desired = getDesiredHeight();
6972
6973            height = desired;
6974            mDesiredHeightAtMeasure = desired;
6975
6976            if (heightMode == MeasureSpec.AT_MOST) {
6977                height = Math.min(desired, heightSize);
6978            }
6979        }
6980
6981        int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
6982        if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) {
6983            unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum));
6984        }
6985
6986        /*
6987         * We didn't let makeNewLayout() register to bring the cursor into view,
6988         * so do it here if there is any possibility that it is needed.
6989         */
6990        if (mMovement != null ||
6991            mLayout.getWidth() > unpaddedWidth ||
6992            mLayout.getHeight() > unpaddedHeight) {
6993            registerForPreDraw();
6994        } else {
6995            scrollTo(0, 0);
6996        }
6997
6998        setMeasuredDimension(width, height);
6999    }
7000
7001    private int getDesiredHeight() {
7002        return Math.max(
7003                getDesiredHeight(mLayout, true),
7004                getDesiredHeight(mHintLayout, mEllipsize != null));
7005    }
7006
7007    private int getDesiredHeight(Layout layout, boolean cap) {
7008        if (layout == null) {
7009            return 0;
7010        }
7011
7012        int linecount = layout.getLineCount();
7013        int pad = getCompoundPaddingTop() + getCompoundPaddingBottom();
7014        int desired = layout.getLineTop(linecount);
7015
7016        final Drawables dr = mDrawables;
7017        if (dr != null) {
7018            desired = Math.max(desired, dr.mDrawableHeightLeft);
7019            desired = Math.max(desired, dr.mDrawableHeightRight);
7020        }
7021
7022        desired += pad;
7023
7024        if (mMaxMode == LINES) {
7025            /*
7026             * Don't cap the hint to a certain number of lines.
7027             * (Do cap it, though, if we have a maximum pixel height.)
7028             */
7029            if (cap) {
7030                if (linecount > mMaximum) {
7031                    desired = layout.getLineTop(mMaximum);
7032
7033                    if (dr != null) {
7034                        desired = Math.max(desired, dr.mDrawableHeightLeft);
7035                        desired = Math.max(desired, dr.mDrawableHeightRight);
7036                    }
7037
7038                    desired += pad;
7039                    linecount = mMaximum;
7040                }
7041            }
7042        } else {
7043            desired = Math.min(desired, mMaximum);
7044        }
7045
7046        if (mMinMode == LINES) {
7047            if (linecount < mMinimum) {
7048                desired += getLineHeight() * (mMinimum - linecount);
7049            }
7050        } else {
7051            desired = Math.max(desired, mMinimum);
7052        }
7053
7054        // Check against our minimum height
7055        desired = Math.max(desired, getSuggestedMinimumHeight());
7056
7057        return desired;
7058    }
7059
7060    /**
7061     * Check whether a change to the existing text layout requires a
7062     * new view layout.
7063     */
7064    private void checkForResize() {
7065        boolean sizeChanged = false;
7066
7067        if (mLayout != null) {
7068            // Check if our width changed
7069            if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) {
7070                sizeChanged = true;
7071                invalidate();
7072            }
7073
7074            // Check if our height changed
7075            if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) {
7076                int desiredHeight = getDesiredHeight();
7077
7078                if (desiredHeight != this.getHeight()) {
7079                    sizeChanged = true;
7080                }
7081            } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) {
7082                if (mDesiredHeightAtMeasure >= 0) {
7083                    int desiredHeight = getDesiredHeight();
7084
7085                    if (desiredHeight != mDesiredHeightAtMeasure) {
7086                        sizeChanged = true;
7087                    }
7088                }
7089            }
7090        }
7091
7092        if (sizeChanged) {
7093            requestLayout();
7094            // caller will have already invalidated
7095        }
7096    }
7097
7098    /**
7099     * Check whether entirely new text requires a new view layout
7100     * or merely a new text layout.
7101     */
7102    private void checkForRelayout() {
7103        // If we have a fixed width, we can just swap in a new text layout
7104        // if the text height stays the same or if the view height is fixed.
7105
7106        if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT ||
7107                (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) &&
7108                (mHint == null || mHintLayout != null) &&
7109                (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) {
7110            // Static width, so try making a new text layout.
7111
7112            int oldht = mLayout.getHeight();
7113            int want = mLayout.getWidth();
7114            int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();
7115
7116            /*
7117             * No need to bring the text into view, since the size is not
7118             * changing (unless we do the requestLayout(), in which case it
7119             * will happen at measure).
7120             */
7121            makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
7122                          mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(),
7123                          false);
7124
7125            if (mEllipsize != TextUtils.TruncateAt.MARQUEE) {
7126                // In a fixed-height view, so use our new text layout.
7127                if (mLayoutParams.height != LayoutParams.WRAP_CONTENT &&
7128                    mLayoutParams.height != LayoutParams.MATCH_PARENT) {
7129                    invalidate();
7130                    return;
7131                }
7132
7133                // Dynamic height, but height has stayed the same,
7134                // so use our new text layout.
7135                if (mLayout.getHeight() == oldht &&
7136                    (mHintLayout == null || mHintLayout.getHeight() == oldht)) {
7137                    invalidate();
7138                    return;
7139                }
7140            }
7141
7142            // We lose: the height has changed and we have a dynamic height.
7143            // Request a new view layout using our new text layout.
7144            requestLayout();
7145            invalidate();
7146        } else {
7147            // Dynamic width, so we have no choice but to request a new
7148            // view layout with a new text layout.
7149            nullLayouts();
7150            requestLayout();
7151            invalidate();
7152        }
7153    }
7154
7155    @Override
7156    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
7157        super.onLayout(changed, left, top, right, bottom);
7158        if (mDeferScroll >= 0) {
7159            int curs = mDeferScroll;
7160            mDeferScroll = -1;
7161            bringPointIntoView(Math.min(curs, mText.length()));
7162        }
7163    }
7164
7165    private boolean isShowingHint() {
7166        return TextUtils.isEmpty(mText) && !TextUtils.isEmpty(mHint);
7167    }
7168
7169    /**
7170     * Returns true if anything changed.
7171     */
7172    private boolean bringTextIntoView() {
7173        Layout layout = isShowingHint() ? mHintLayout : mLayout;
7174        int line = 0;
7175        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
7176            line = layout.getLineCount() - 1;
7177        }
7178
7179        Layout.Alignment a = layout.getParagraphAlignment(line);
7180        int dir = layout.getParagraphDirection(line);
7181        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
7182        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
7183        int ht = layout.getHeight();
7184
7185        int scrollx, scrolly;
7186
7187        // Convert to left, center, or right alignment.
7188        if (a == Layout.Alignment.ALIGN_NORMAL) {
7189            a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_LEFT :
7190                Layout.Alignment.ALIGN_RIGHT;
7191        } else if (a == Layout.Alignment.ALIGN_OPPOSITE){
7192            a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_RIGHT :
7193                Layout.Alignment.ALIGN_LEFT;
7194        }
7195
7196        if (a == Layout.Alignment.ALIGN_CENTER) {
7197            /*
7198             * Keep centered if possible, or, if it is too wide to fit,
7199             * keep leading edge in view.
7200             */
7201
7202            int left = (int) Math.floor(layout.getLineLeft(line));
7203            int right = (int) Math.ceil(layout.getLineRight(line));
7204
7205            if (right - left < hspace) {
7206                scrollx = (right + left) / 2 - hspace / 2;
7207            } else {
7208                if (dir < 0) {
7209                    scrollx = right - hspace;
7210                } else {
7211                    scrollx = left;
7212                }
7213            }
7214        } else if (a == Layout.Alignment.ALIGN_RIGHT) {
7215            int right = (int) Math.ceil(layout.getLineRight(line));
7216            scrollx = right - hspace;
7217        } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default)
7218            scrollx = (int) Math.floor(layout.getLineLeft(line));
7219        }
7220
7221        if (ht < vspace) {
7222            scrolly = 0;
7223        } else {
7224            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
7225                scrolly = ht - vspace;
7226            } else {
7227                scrolly = 0;
7228            }
7229        }
7230
7231        if (scrollx != mScrollX || scrolly != mScrollY) {
7232            scrollTo(scrollx, scrolly);
7233            return true;
7234        } else {
7235            return false;
7236        }
7237    }
7238
7239    /**
7240     * Move the point, specified by the offset, into the view if it is needed.
7241     * This has to be called after layout. Returns true if anything changed.
7242     */
7243    public boolean bringPointIntoView(int offset) {
7244        if (isLayoutRequested()) {
7245            mDeferScroll = offset;
7246            return false;
7247        }
7248        boolean changed = false;
7249
7250        Layout layout = isShowingHint() ? mHintLayout: mLayout;
7251
7252        if (layout == null) return changed;
7253
7254        int line = layout.getLineForOffset(offset);
7255
7256        int grav;
7257
7258        switch (layout.getParagraphAlignment(line)) {
7259            case ALIGN_LEFT:
7260                grav = 1;
7261                break;
7262            case ALIGN_RIGHT:
7263                grav = -1;
7264                break;
7265            case ALIGN_NORMAL:
7266                grav = layout.getParagraphDirection(line);
7267                break;
7268            case ALIGN_OPPOSITE:
7269                grav = -layout.getParagraphDirection(line);
7270                break;
7271            case ALIGN_CENTER:
7272            default:
7273                grav = 0;
7274                break;
7275        }
7276
7277        // We only want to clamp the cursor to fit within the layout width
7278        // in left-to-right modes, because in a right to left alignment,
7279        // we want to scroll to keep the line-right on the screen, as other
7280        // lines are likely to have text flush with the right margin, which
7281        // we want to keep visible.
7282        // A better long-term solution would probably be to measure both
7283        // the full line and a blank-trimmed version, and, for example, use
7284        // the latter measurement for centering and right alignment, but for
7285        // the time being we only implement the cursor clamping in left to
7286        // right where it is most likely to be annoying.
7287        final boolean clamped = grav > 0;
7288        // FIXME: Is it okay to truncate this, or should we round?
7289        final int x = (int)layout.getPrimaryHorizontal(offset, clamped);
7290        final int top = layout.getLineTop(line);
7291        final int bottom = layout.getLineTop(line + 1);
7292
7293        int left = (int) Math.floor(layout.getLineLeft(line));
7294        int right = (int) Math.ceil(layout.getLineRight(line));
7295        int ht = layout.getHeight();
7296
7297        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
7298        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
7299        if (!mHorizontallyScrolling && right - left > hspace && right > x) {
7300            // If cursor has been clamped, make sure we don't scroll.
7301            right = Math.max(x, left + hspace);
7302        }
7303
7304        int hslack = (bottom - top) / 2;
7305        int vslack = hslack;
7306
7307        if (vslack > vspace / 4)
7308            vslack = vspace / 4;
7309        if (hslack > hspace / 4)
7310            hslack = hspace / 4;
7311
7312        int hs = mScrollX;
7313        int vs = mScrollY;
7314
7315        if (top - vs < vslack)
7316            vs = top - vslack;
7317        if (bottom - vs > vspace - vslack)
7318            vs = bottom - (vspace - vslack);
7319        if (ht - vs < vspace)
7320            vs = ht - vspace;
7321        if (0 - vs > 0)
7322            vs = 0;
7323
7324        if (grav != 0) {
7325            if (x - hs < hslack) {
7326                hs = x - hslack;
7327            }
7328            if (x - hs > hspace - hslack) {
7329                hs = x - (hspace - hslack);
7330            }
7331        }
7332
7333        if (grav < 0) {
7334            if (left - hs > 0)
7335                hs = left;
7336            if (right - hs < hspace)
7337                hs = right - hspace;
7338        } else if (grav > 0) {
7339            if (right - hs < hspace)
7340                hs = right - hspace;
7341            if (left - hs > 0)
7342                hs = left;
7343        } else /* grav == 0 */ {
7344            if (right - left <= hspace) {
7345                /*
7346                 * If the entire text fits, center it exactly.
7347                 */
7348                hs = left - (hspace - (right - left)) / 2;
7349            } else if (x > right - hslack) {
7350                /*
7351                 * If we are near the right edge, keep the right edge
7352                 * at the edge of the view.
7353                 */
7354                hs = right - hspace;
7355            } else if (x < left + hslack) {
7356                /*
7357                 * If we are near the left edge, keep the left edge
7358                 * at the edge of the view.
7359                 */
7360                hs = left;
7361            } else if (left > hs) {
7362                /*
7363                 * Is there whitespace visible at the left?  Fix it if so.
7364                 */
7365                hs = left;
7366            } else if (right < hs + hspace) {
7367                /*
7368                 * Is there whitespace visible at the right?  Fix it if so.
7369                 */
7370                hs = right - hspace;
7371            } else {
7372                /*
7373                 * Otherwise, float as needed.
7374                 */
7375                if (x - hs < hslack) {
7376                    hs = x - hslack;
7377                }
7378                if (x - hs > hspace - hslack) {
7379                    hs = x - (hspace - hslack);
7380                }
7381            }
7382        }
7383
7384        if (hs != mScrollX || vs != mScrollY) {
7385            if (mScroller == null) {
7386                scrollTo(hs, vs);
7387            } else {
7388                long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
7389                int dx = hs - mScrollX;
7390                int dy = vs - mScrollY;
7391
7392                if (duration > ANIMATED_SCROLL_GAP) {
7393                    mScroller.startScroll(mScrollX, mScrollY, dx, dy);
7394                    awakenScrollBars(mScroller.getDuration());
7395                    invalidate();
7396                } else {
7397                    if (!mScroller.isFinished()) {
7398                        mScroller.abortAnimation();
7399                    }
7400
7401                    scrollBy(dx, dy);
7402                }
7403
7404                mLastScroll = AnimationUtils.currentAnimationTimeMillis();
7405            }
7406
7407            changed = true;
7408        }
7409
7410        if (isFocused()) {
7411            // This offsets because getInterestingRect() is in terms of viewport coordinates, but
7412            // requestRectangleOnScreen() is in terms of content coordinates.
7413
7414            // The offsets here are to ensure the rectangle we are using is
7415            // within our view bounds, in case the cursor is on the far left
7416            // or right.  If it isn't withing the bounds, then this request
7417            // will be ignored.
7418            if (mTempRect == null) mTempRect = new Rect();
7419            mTempRect.set(x - 2, top, x + 2, bottom);
7420            getInterestingRect(mTempRect, line);
7421            mTempRect.offset(mScrollX, mScrollY);
7422
7423            if (requestRectangleOnScreen(mTempRect)) {
7424                changed = true;
7425            }
7426        }
7427
7428        return changed;
7429    }
7430
7431    /**
7432     * Move the cursor, if needed, so that it is at an offset that is visible
7433     * to the user.  This will not move the cursor if it represents more than
7434     * one character (a selection range).  This will only work if the
7435     * TextView contains spannable text; otherwise it will do nothing.
7436     *
7437     * @return True if the cursor was actually moved, false otherwise.
7438     */
7439    public boolean moveCursorToVisibleOffset() {
7440        if (!(mText instanceof Spannable)) {
7441            return false;
7442        }
7443        int start = getSelectionStart();
7444        int end = getSelectionEnd();
7445        if (start != end) {
7446            return false;
7447        }
7448
7449        // First: make sure the line is visible on screen:
7450
7451        int line = mLayout.getLineForOffset(start);
7452
7453        final int top = mLayout.getLineTop(line);
7454        final int bottom = mLayout.getLineTop(line + 1);
7455        final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
7456        int vslack = (bottom - top) / 2;
7457        if (vslack > vspace / 4)
7458            vslack = vspace / 4;
7459        final int vs = mScrollY;
7460
7461        if (top < (vs+vslack)) {
7462            line = mLayout.getLineForVertical(vs+vslack+(bottom-top));
7463        } else if (bottom > (vspace+vs-vslack)) {
7464            line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top));
7465        }
7466
7467        // Next: make sure the character is visible on screen:
7468
7469        final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
7470        final int hs = mScrollX;
7471        final int leftChar = mLayout.getOffsetForHorizontal(line, hs);
7472        final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs);
7473
7474        // line might contain bidirectional text
7475        final int lowChar = leftChar < rightChar ? leftChar : rightChar;
7476        final int highChar = leftChar > rightChar ? leftChar : rightChar;
7477
7478        int newStart = start;
7479        if (newStart < lowChar) {
7480            newStart = lowChar;
7481        } else if (newStart > highChar) {
7482            newStart = highChar;
7483        }
7484
7485        if (newStart != start) {
7486            Selection.setSelection((Spannable)mText, newStart);
7487            return true;
7488        }
7489
7490        return false;
7491    }
7492
7493    @Override
7494    public void computeScroll() {
7495        if (mScroller != null) {
7496            if (mScroller.computeScrollOffset()) {
7497                mScrollX = mScroller.getCurrX();
7498                mScrollY = mScroller.getCurrY();
7499                invalidateParentCaches();
7500                postInvalidate();  // So we draw again
7501            }
7502        }
7503    }
7504
7505    private void getInterestingRect(Rect r, int line) {
7506        convertFromViewportToContentCoordinates(r);
7507
7508        // Rectangle can can be expanded on first and last line to take
7509        // padding into account.
7510        // TODO Take left/right padding into account too?
7511        if (line == 0) r.top -= getExtendedPaddingTop();
7512        if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom();
7513    }
7514
7515    private void convertFromViewportToContentCoordinates(Rect r) {
7516        final int horizontalOffset = viewportToContentHorizontalOffset();
7517        r.left += horizontalOffset;
7518        r.right += horizontalOffset;
7519
7520        final int verticalOffset = viewportToContentVerticalOffset();
7521        r.top += verticalOffset;
7522        r.bottom += verticalOffset;
7523    }
7524
7525    int viewportToContentHorizontalOffset() {
7526        return getCompoundPaddingLeft() - mScrollX;
7527    }
7528
7529    int viewportToContentVerticalOffset() {
7530        int offset = getExtendedPaddingTop() - mScrollY;
7531        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
7532            offset += getVerticalOffset(false);
7533        }
7534        return offset;
7535    }
7536
7537    @Override
7538    public void debug(int depth) {
7539        super.debug(depth);
7540
7541        String output = debugIndent(depth);
7542        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
7543                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
7544                + "} ";
7545
7546        if (mText != null) {
7547
7548            output += "mText=\"" + mText + "\" ";
7549            if (mLayout != null) {
7550                output += "mLayout width=" + mLayout.getWidth()
7551                        + " height=" + mLayout.getHeight();
7552            }
7553        } else {
7554            output += "mText=NULL";
7555        }
7556        Log.d(VIEW_LOG_TAG, output);
7557    }
7558
7559    /**
7560     * Convenience for {@link Selection#getSelectionStart}.
7561     */
7562    @ViewDebug.ExportedProperty(category = "text")
7563    public int getSelectionStart() {
7564        return Selection.getSelectionStart(getText());
7565    }
7566
7567    /**
7568     * Convenience for {@link Selection#getSelectionEnd}.
7569     */
7570    @ViewDebug.ExportedProperty(category = "text")
7571    public int getSelectionEnd() {
7572        return Selection.getSelectionEnd(getText());
7573    }
7574
7575    /**
7576     * Return true iff there is a selection inside this text view.
7577     */
7578    public boolean hasSelection() {
7579        final int selectionStart = getSelectionStart();
7580        final int selectionEnd = getSelectionEnd();
7581
7582        return selectionStart >= 0 && selectionStart != selectionEnd;
7583    }
7584
7585    String getSelectedText() {
7586        if (!hasSelection()) {
7587            return null;
7588        }
7589
7590        final int start = getSelectionStart();
7591        final int end = getSelectionEnd();
7592        return String.valueOf(
7593                start > end ? mText.subSequence(end, start) : mText.subSequence(start, end));
7594    }
7595
7596    /**
7597     * Sets the properties of this field (lines, horizontally scrolling,
7598     * transformation method) to be for a single-line input.
7599     *
7600     * @attr ref android.R.styleable#TextView_singleLine
7601     */
7602    public void setSingleLine() {
7603        setSingleLine(true);
7604    }
7605
7606    /**
7607     * Sets the properties of this field to transform input to ALL CAPS
7608     * display. This may use a "small caps" formatting if available.
7609     * This setting will be ignored if this field is editable or selectable.
7610     *
7611     * This call replaces the current transformation method. Disabling this
7612     * will not necessarily restore the previous behavior from before this
7613     * was enabled.
7614     *
7615     * @see #setTransformationMethod(TransformationMethod)
7616     * @attr ref android.R.styleable#TextView_textAllCaps
7617     */
7618    public void setAllCaps(boolean allCaps) {
7619        if (allCaps) {
7620            setTransformationMethod(new AllCapsTransformationMethod(getContext()));
7621        } else {
7622            setTransformationMethod(null);
7623        }
7624    }
7625
7626    /**
7627     * If true, sets the properties of this field (number of lines, horizontally scrolling,
7628     * transformation method) to be for a single-line input; if false, restores these to the default
7629     * conditions.
7630     *
7631     * Note that the default conditions are not necessarily those that were in effect prior this
7632     * method, and you may want to reset these properties to your custom values.
7633     *
7634     * @attr ref android.R.styleable#TextView_singleLine
7635     */
7636    @android.view.RemotableViewMethod
7637    public void setSingleLine(boolean singleLine) {
7638        // Could be used, but may break backward compatibility.
7639        // if (mSingleLine == singleLine) return;
7640        setInputTypeSingleLine(singleLine);
7641        applySingleLine(singleLine, true, true);
7642    }
7643
7644    /**
7645     * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType.
7646     * @param singleLine
7647     */
7648    private void setInputTypeSingleLine(boolean singleLine) {
7649        if (mEditor != null &&
7650                (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
7651            if (singleLine) {
7652                mEditor.mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
7653            } else {
7654                mEditor.mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
7655            }
7656        }
7657    }
7658
7659    private void applySingleLine(boolean singleLine, boolean applyTransformation,
7660            boolean changeMaxLines) {
7661        mSingleLine = singleLine;
7662        if (singleLine) {
7663            setLines(1);
7664            setHorizontallyScrolling(true);
7665            if (applyTransformation) {
7666                setTransformationMethod(SingleLineTransformationMethod.getInstance());
7667            }
7668        } else {
7669            if (changeMaxLines) {
7670                setMaxLines(Integer.MAX_VALUE);
7671            }
7672            setHorizontallyScrolling(false);
7673            if (applyTransformation) {
7674                setTransformationMethod(null);
7675            }
7676        }
7677    }
7678
7679    /**
7680     * Causes words in the text that are longer than the view is wide
7681     * to be ellipsized instead of broken in the middle.  You may also
7682     * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling}
7683     * to constrain the text to a single line.  Use <code>null</code>
7684     * to turn off ellipsizing.
7685     *
7686     * If {@link #setMaxLines} has been used to set two or more lines,
7687     * only {@link android.text.TextUtils.TruncateAt#END} and
7688     * {@link android.text.TextUtils.TruncateAt#MARQUEE} are supported
7689     * (other ellipsizing types will not do anything).
7690     *
7691     * @attr ref android.R.styleable#TextView_ellipsize
7692     */
7693    public void setEllipsize(TextUtils.TruncateAt where) {
7694        // TruncateAt is an enum. != comparison is ok between these singleton objects.
7695        if (mEllipsize != where) {
7696            mEllipsize = where;
7697
7698            if (mLayout != null) {
7699                nullLayouts();
7700                requestLayout();
7701                invalidate();
7702            }
7703        }
7704    }
7705
7706    /**
7707     * Sets how many times to repeat the marquee animation. Only applied if the
7708     * TextView has marquee enabled. Set to -1 to repeat indefinitely.
7709     *
7710     * @see #getMarqueeRepeatLimit()
7711     *
7712     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
7713     */
7714    public void setMarqueeRepeatLimit(int marqueeLimit) {
7715        mMarqueeRepeatLimit = marqueeLimit;
7716    }
7717
7718    /**
7719     * Gets the number of times the marquee animation is repeated. Only meaningful if the
7720     * TextView has marquee enabled.
7721     *
7722     * @return the number of times the marquee animation is repeated. -1 if the animation
7723     * repeats indefinitely
7724     *
7725     * @see #setMarqueeRepeatLimit(int)
7726     *
7727     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
7728     */
7729    public int getMarqueeRepeatLimit() {
7730        return mMarqueeRepeatLimit;
7731    }
7732
7733    /**
7734     * Returns where, if anywhere, words that are longer than the view
7735     * is wide should be ellipsized.
7736     */
7737    @ViewDebug.ExportedProperty
7738    public TextUtils.TruncateAt getEllipsize() {
7739        return mEllipsize;
7740    }
7741
7742    /**
7743     * Set the TextView so that when it takes focus, all the text is
7744     * selected.
7745     *
7746     * @attr ref android.R.styleable#TextView_selectAllOnFocus
7747     */
7748    @android.view.RemotableViewMethod
7749    public void setSelectAllOnFocus(boolean selectAllOnFocus) {
7750        createEditorIfNeeded();
7751        mEditor.mSelectAllOnFocus = selectAllOnFocus;
7752
7753        if (selectAllOnFocus && !(mText instanceof Spannable)) {
7754            setText(mText, BufferType.SPANNABLE);
7755        }
7756    }
7757
7758    /**
7759     * Set whether the cursor is visible. The default is true. Note that this property only
7760     * makes sense for editable TextView.
7761     *
7762     * @see #isCursorVisible()
7763     *
7764     * @attr ref android.R.styleable#TextView_cursorVisible
7765     */
7766    @android.view.RemotableViewMethod
7767    public void setCursorVisible(boolean visible) {
7768        if (visible && mEditor == null) return; // visible is the default value with no edit data
7769        createEditorIfNeeded();
7770        if (mEditor.mCursorVisible != visible) {
7771            mEditor.mCursorVisible = visible;
7772            invalidate();
7773
7774            mEditor.makeBlink();
7775
7776            // InsertionPointCursorController depends on mCursorVisible
7777            mEditor.prepareCursorControllers();
7778        }
7779    }
7780
7781    /**
7782     * @return whether or not the cursor is visible (assuming this TextView is editable)
7783     *
7784     * @see #setCursorVisible(boolean)
7785     *
7786     * @attr ref android.R.styleable#TextView_cursorVisible
7787     */
7788    public boolean isCursorVisible() {
7789        // true is the default value
7790        return mEditor == null ? true : mEditor.mCursorVisible;
7791    }
7792
7793    private boolean canMarquee() {
7794        int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight());
7795        return width > 0 && (mLayout.getLineWidth(0) > width ||
7796                (mMarqueeFadeMode != MARQUEE_FADE_NORMAL && mSavedMarqueeModeLayout != null &&
7797                        mSavedMarqueeModeLayout.getLineWidth(0) > width));
7798    }
7799
7800    private void startMarquee() {
7801        // Do not ellipsize EditText
7802        if (getKeyListener() != null) return;
7803
7804        if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
7805            return;
7806        }
7807
7808        if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) &&
7809                getLineCount() == 1 && canMarquee()) {
7810
7811            if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
7812                mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_FADE;
7813                final Layout tmp = mLayout;
7814                mLayout = mSavedMarqueeModeLayout;
7815                mSavedMarqueeModeLayout = tmp;
7816                setHorizontalFadingEdgeEnabled(true);
7817                requestLayout();
7818                invalidate();
7819            }
7820
7821            if (mMarquee == null) mMarquee = new Marquee(this);
7822            mMarquee.start(mMarqueeRepeatLimit);
7823        }
7824    }
7825
7826    private void stopMarquee() {
7827        if (mMarquee != null && !mMarquee.isStopped()) {
7828            mMarquee.stop();
7829        }
7830
7831        if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_FADE) {
7832            mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS;
7833            final Layout tmp = mSavedMarqueeModeLayout;
7834            mSavedMarqueeModeLayout = mLayout;
7835            mLayout = tmp;
7836            setHorizontalFadingEdgeEnabled(false);
7837            requestLayout();
7838            invalidate();
7839        }
7840    }
7841
7842    private void startStopMarquee(boolean start) {
7843        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
7844            if (start) {
7845                startMarquee();
7846            } else {
7847                stopMarquee();
7848            }
7849        }
7850    }
7851
7852    /**
7853     * This method is called when the text is changed, in case any subclasses
7854     * would like to know.
7855     *
7856     * Within <code>text</code>, the <code>lengthAfter</code> characters
7857     * beginning at <code>start</code> have just replaced old text that had
7858     * length <code>lengthBefore</code>. It is an error to attempt to make
7859     * changes to <code>text</code> from this callback.
7860     *
7861     * @param text The text the TextView is displaying
7862     * @param start The offset of the start of the range of the text that was
7863     * modified
7864     * @param lengthBefore The length of the former text that has been replaced
7865     * @param lengthAfter The length of the replacement modified text
7866     */
7867    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
7868        // intentionally empty, template pattern method can be overridden by subclasses
7869    }
7870
7871    /**
7872     * This method is called when the selection has changed, in case any
7873     * subclasses would like to know.
7874     *
7875     * @param selStart The new selection start location.
7876     * @param selEnd The new selection end location.
7877     */
7878    protected void onSelectionChanged(int selStart, int selEnd) {
7879        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7880    }
7881
7882    /**
7883     * Adds a TextWatcher to the list of those whose methods are called
7884     * whenever this TextView's text changes.
7885     * <p>
7886     * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
7887     * not called after {@link #setText} calls.  Now, doing {@link #setText}
7888     * if there are any text changed listeners forces the buffer type to
7889     * Editable if it would not otherwise be and does call this method.
7890     */
7891    public void addTextChangedListener(TextWatcher watcher) {
7892        if (mListeners == null) {
7893            mListeners = new ArrayList<TextWatcher>();
7894        }
7895
7896        mListeners.add(watcher);
7897    }
7898
7899    /**
7900     * Removes the specified TextWatcher from the list of those whose
7901     * methods are called
7902     * whenever this TextView's text changes.
7903     */
7904    public void removeTextChangedListener(TextWatcher watcher) {
7905        if (mListeners != null) {
7906            int i = mListeners.indexOf(watcher);
7907
7908            if (i >= 0) {
7909                mListeners.remove(i);
7910            }
7911        }
7912    }
7913
7914    private void sendBeforeTextChanged(CharSequence text, int start, int before, int after) {
7915        if (mListeners != null) {
7916            final ArrayList<TextWatcher> list = mListeners;
7917            final int count = list.size();
7918            for (int i = 0; i < count; i++) {
7919                list.get(i).beforeTextChanged(text, start, before, after);
7920            }
7921        }
7922
7923        // The spans that are inside or intersect the modified region no longer make sense
7924        removeIntersectingNonAdjacentSpans(start, start + before, SpellCheckSpan.class);
7925        removeIntersectingNonAdjacentSpans(start, start + before, SuggestionSpan.class);
7926    }
7927
7928    // Removes all spans that are inside or actually overlap the start..end range
7929    private <T> void removeIntersectingNonAdjacentSpans(int start, int end, Class<T> type) {
7930        if (!(mText instanceof Editable)) return;
7931        Editable text = (Editable) mText;
7932
7933        T[] spans = text.getSpans(start, end, type);
7934        final int length = spans.length;
7935        for (int i = 0; i < length; i++) {
7936            final int spanStart = text.getSpanStart(spans[i]);
7937            final int spanEnd = text.getSpanEnd(spans[i]);
7938            if (spanEnd == start || spanStart == end) break;
7939            text.removeSpan(spans[i]);
7940        }
7941    }
7942
7943    void removeAdjacentSuggestionSpans(final int pos) {
7944        if (!(mText instanceof Editable)) return;
7945        final Editable text = (Editable) mText;
7946
7947        final SuggestionSpan[] spans = text.getSpans(pos, pos, SuggestionSpan.class);
7948        final int length = spans.length;
7949        for (int i = 0; i < length; i++) {
7950            final int spanStart = text.getSpanStart(spans[i]);
7951            final int spanEnd = text.getSpanEnd(spans[i]);
7952            if (spanEnd == pos || spanStart == pos) {
7953                if (SpellChecker.haveWordBoundariesChanged(text, pos, pos, spanStart, spanEnd)) {
7954                    text.removeSpan(spans[i]);
7955                }
7956            }
7957        }
7958    }
7959
7960    /**
7961     * Not private so it can be called from an inner class without going
7962     * through a thunk.
7963     */
7964    void sendOnTextChanged(CharSequence text, int start, int before, int after) {
7965        if (mListeners != null) {
7966            final ArrayList<TextWatcher> list = mListeners;
7967            final int count = list.size();
7968            for (int i = 0; i < count; i++) {
7969                list.get(i).onTextChanged(text, start, before, after);
7970            }
7971        }
7972
7973        if (mEditor != null) mEditor.sendOnTextChanged(start, after);
7974    }
7975
7976    /**
7977     * Not private so it can be called from an inner class without going
7978     * through a thunk.
7979     */
7980    void sendAfterTextChanged(Editable text) {
7981        if (mListeners != null) {
7982            final ArrayList<TextWatcher> list = mListeners;
7983            final int count = list.size();
7984            for (int i = 0; i < count; i++) {
7985                list.get(i).afterTextChanged(text);
7986            }
7987        }
7988        hideErrorIfUnchanged();
7989    }
7990
7991    void updateAfterEdit() {
7992        invalidate();
7993        int curs = getSelectionStart();
7994
7995        if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
7996            registerForPreDraw();
7997        }
7998
7999        checkForResize();
8000
8001        if (curs >= 0) {
8002            mHighlightPathBogus = true;
8003            if (mEditor != null) mEditor.makeBlink();
8004            bringPointIntoView(curs);
8005        }
8006    }
8007
8008    /**
8009     * Not private so it can be called from an inner class without going
8010     * through a thunk.
8011     */
8012    void handleTextChanged(CharSequence buffer, int start, int before, int after) {
8013        sLastCutCopyOrTextChangedTime = 0;
8014
8015        final Editor.InputMethodState ims = mEditor == null ? null : mEditor.mInputMethodState;
8016        if (ims == null || ims.mBatchEditNesting == 0) {
8017            updateAfterEdit();
8018        }
8019        if (ims != null) {
8020            ims.mContentChanged = true;
8021            if (ims.mChangedStart < 0) {
8022                ims.mChangedStart = start;
8023                ims.mChangedEnd = start+before;
8024            } else {
8025                ims.mChangedStart = Math.min(ims.mChangedStart, start);
8026                ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta);
8027            }
8028            ims.mChangedDelta += after-before;
8029        }
8030        resetErrorChangedFlag();
8031        sendOnTextChanged(buffer, start, before, after);
8032        onTextChanged(buffer, start, before, after);
8033    }
8034
8035    /**
8036     * Not private so it can be called from an inner class without going
8037     * through a thunk.
8038     */
8039    void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) {
8040        // XXX Make the start and end move together if this ends up
8041        // spending too much time invalidating.
8042
8043        boolean selChanged = false;
8044        int newSelStart=-1, newSelEnd=-1;
8045
8046        final Editor.InputMethodState ims = mEditor == null ? null : mEditor.mInputMethodState;
8047
8048        if (what == Selection.SELECTION_END) {
8049            selChanged = true;
8050            newSelEnd = newStart;
8051
8052            if (oldStart >= 0 || newStart >= 0) {
8053                invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart);
8054                checkForResize();
8055                registerForPreDraw();
8056                if (mEditor != null) mEditor.makeBlink();
8057            }
8058        }
8059
8060        if (what == Selection.SELECTION_START) {
8061            selChanged = true;
8062            newSelStart = newStart;
8063
8064            if (oldStart >= 0 || newStart >= 0) {
8065                int end = Selection.getSelectionEnd(buf);
8066                invalidateCursor(end, oldStart, newStart);
8067            }
8068        }
8069
8070        if (selChanged) {
8071            mHighlightPathBogus = true;
8072            if (mEditor != null && !isFocused()) mEditor.mSelectionMoved = true;
8073
8074            if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) {
8075                if (newSelStart < 0) {
8076                    newSelStart = Selection.getSelectionStart(buf);
8077                }
8078                if (newSelEnd < 0) {
8079                    newSelEnd = Selection.getSelectionEnd(buf);
8080                }
8081                onSelectionChanged(newSelStart, newSelEnd);
8082            }
8083        }
8084
8085        if (what instanceof UpdateAppearance || what instanceof ParagraphStyle ||
8086                what instanceof CharacterStyle) {
8087            if (ims == null || ims.mBatchEditNesting == 0) {
8088                invalidate();
8089                mHighlightPathBogus = true;
8090                checkForResize();
8091            } else {
8092                ims.mContentChanged = true;
8093            }
8094            if (mEditor != null) {
8095                if (oldStart >= 0) mEditor.invalidateTextDisplayList(mLayout, oldStart, oldEnd);
8096                if (newStart >= 0) mEditor.invalidateTextDisplayList(mLayout, newStart, newEnd);
8097            }
8098        }
8099
8100        if (MetaKeyKeyListener.isMetaTracker(buf, what)) {
8101            mHighlightPathBogus = true;
8102            if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) {
8103                ims.mSelectionModeChanged = true;
8104            }
8105
8106            if (Selection.getSelectionStart(buf) >= 0) {
8107                if (ims == null || ims.mBatchEditNesting == 0) {
8108                    invalidateCursor();
8109                } else {
8110                    ims.mCursorChanged = true;
8111                }
8112            }
8113        }
8114
8115        if (what instanceof ParcelableSpan) {
8116            // If this is a span that can be sent to a remote process,
8117            // the current extract editor would be interested in it.
8118            if (ims != null && ims.mExtractedTextRequest != null) {
8119                if (ims.mBatchEditNesting != 0) {
8120                    if (oldStart >= 0) {
8121                        if (ims.mChangedStart > oldStart) {
8122                            ims.mChangedStart = oldStart;
8123                        }
8124                        if (ims.mChangedStart > oldEnd) {
8125                            ims.mChangedStart = oldEnd;
8126                        }
8127                    }
8128                    if (newStart >= 0) {
8129                        if (ims.mChangedStart > newStart) {
8130                            ims.mChangedStart = newStart;
8131                        }
8132                        if (ims.mChangedStart > newEnd) {
8133                            ims.mChangedStart = newEnd;
8134                        }
8135                    }
8136                } else {
8137                    if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: "
8138                            + oldStart + "-" + oldEnd + ","
8139                            + newStart + "-" + newEnd + " " + what);
8140                    ims.mContentChanged = true;
8141                }
8142            }
8143        }
8144
8145        if (mEditor != null && mEditor.mSpellChecker != null && newStart < 0 &&
8146                what instanceof SpellCheckSpan) {
8147            mEditor.mSpellChecker.onSpellCheckSpanRemoved((SpellCheckSpan) what);
8148        }
8149    }
8150
8151    /**
8152     * @hide
8153     */
8154    @Override
8155    public void dispatchFinishTemporaryDetach() {
8156        mDispatchTemporaryDetach = true;
8157        super.dispatchFinishTemporaryDetach();
8158        mDispatchTemporaryDetach = false;
8159    }
8160
8161    @Override
8162    public void onStartTemporaryDetach() {
8163        super.onStartTemporaryDetach();
8164        // Only track when onStartTemporaryDetach() is called directly,
8165        // usually because this instance is an editable field in a list
8166        if (!mDispatchTemporaryDetach) mTemporaryDetach = true;
8167
8168        // Tell the editor that we are temporarily detached. It can use this to preserve
8169        // selection state as needed.
8170        if (mEditor != null) mEditor.mTemporaryDetach = true;
8171    }
8172
8173    @Override
8174    public void onFinishTemporaryDetach() {
8175        super.onFinishTemporaryDetach();
8176        // Only track when onStartTemporaryDetach() is called directly,
8177        // usually because this instance is an editable field in a list
8178        if (!mDispatchTemporaryDetach) mTemporaryDetach = false;
8179        if (mEditor != null) mEditor.mTemporaryDetach = false;
8180    }
8181
8182    @Override
8183    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
8184        if (mTemporaryDetach) {
8185            // If we are temporarily in the detach state, then do nothing.
8186            super.onFocusChanged(focused, direction, previouslyFocusedRect);
8187            return;
8188        }
8189
8190        if (mEditor != null) mEditor.onFocusChanged(focused, direction);
8191
8192        if (focused) {
8193            if (mText instanceof Spannable) {
8194                Spannable sp = (Spannable) mText;
8195                MetaKeyKeyListener.resetMetaState(sp);
8196            }
8197        }
8198
8199        startStopMarquee(focused);
8200
8201        if (mTransformation != null) {
8202            mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect);
8203        }
8204
8205        super.onFocusChanged(focused, direction, previouslyFocusedRect);
8206    }
8207
8208    @Override
8209    public void onWindowFocusChanged(boolean hasWindowFocus) {
8210        super.onWindowFocusChanged(hasWindowFocus);
8211
8212        if (mEditor != null) mEditor.onWindowFocusChanged(hasWindowFocus);
8213
8214        startStopMarquee(hasWindowFocus);
8215    }
8216
8217    @Override
8218    protected void onVisibilityChanged(View changedView, int visibility) {
8219        super.onVisibilityChanged(changedView, visibility);
8220        if (mEditor != null && visibility != VISIBLE) {
8221            mEditor.hideCursorAndSpanControllers();
8222            stopTextActionMode();
8223        }
8224    }
8225
8226    /**
8227     * Use {@link BaseInputConnection#removeComposingSpans
8228     * BaseInputConnection.removeComposingSpans()} to remove any IME composing
8229     * state from this text view.
8230     */
8231    public void clearComposingText() {
8232        if (mText instanceof Spannable) {
8233            BaseInputConnection.removeComposingSpans((Spannable)mText);
8234        }
8235    }
8236
8237    @Override
8238    public void setSelected(boolean selected) {
8239        boolean wasSelected = isSelected();
8240
8241        super.setSelected(selected);
8242
8243        if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
8244            if (selected) {
8245                startMarquee();
8246            } else {
8247                stopMarquee();
8248            }
8249        }
8250    }
8251
8252    @Override
8253    public boolean onTouchEvent(MotionEvent event) {
8254        final int action = event.getActionMasked();
8255
8256        if (mEditor != null && action == MotionEvent.ACTION_DOWN) {
8257            // Detect double tap and inform the Editor.
8258            if (mFirstTouch && (SystemClock.uptimeMillis() - mLastTouchUpTime) <=
8259                    ViewConfiguration.getDoubleTapTimeout()) {
8260                mEditor.mDoubleTap = true;
8261                mFirstTouch = false;
8262            } else {
8263                mEditor.mDoubleTap = false;
8264                mFirstTouch = true;
8265            }
8266        }
8267
8268        if (action == MotionEvent.ACTION_UP) {
8269            mLastTouchUpTime = SystemClock.uptimeMillis();
8270        }
8271
8272        if (mEditor != null) {
8273            mEditor.onTouchEvent(event);
8274
8275            if (mEditor.mSelectionModifierCursorController != null &&
8276                    mEditor.mSelectionModifierCursorController.isDragAcceleratorActive()) {
8277                return true;
8278            }
8279        }
8280
8281        final boolean superResult = super.onTouchEvent(event);
8282
8283        /*
8284         * Don't handle the release after a long press, because it will move the selection away from
8285         * whatever the menu action was trying to affect. If the long press should have triggered an
8286         * insertion action mode, we can now actually show it.
8287         */
8288        if (mEditor != null && mEditor.mDiscardNextActionUp && action == MotionEvent.ACTION_UP) {
8289            mEditor.mDiscardNextActionUp = false;
8290
8291            if (mEditor.mIsInsertionActionModeStartPending) {
8292                mEditor.startInsertionActionMode();
8293                mEditor.mIsInsertionActionModeStartPending = false;
8294            }
8295            return superResult;
8296        }
8297
8298        final boolean touchIsFinished = (action == MotionEvent.ACTION_UP) &&
8299                (mEditor == null || !mEditor.mIgnoreActionUpEvent) && isFocused();
8300
8301         if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()
8302                && mText instanceof Spannable && mLayout != null) {
8303            boolean handled = false;
8304
8305            if (mMovement != null) {
8306                handled |= mMovement.onTouchEvent(this, (Spannable) mText, event);
8307            }
8308
8309            final boolean textIsSelectable = isTextSelectable();
8310            if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && textIsSelectable) {
8311                // The LinkMovementMethod which should handle taps on links has not been installed
8312                // on non editable text that support text selection.
8313                // We reproduce its behavior here to open links for these.
8314                ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(),
8315                        getSelectionEnd(), ClickableSpan.class);
8316
8317                if (links.length > 0) {
8318                    links[0].onClick(this);
8319                    handled = true;
8320                }
8321            }
8322
8323            if (touchIsFinished && (isTextEditable() || textIsSelectable)) {
8324                // Show the IME, except when selecting in read-only text.
8325                final InputMethodManager imm = InputMethodManager.peekInstance();
8326                viewClicked(imm);
8327                if (!textIsSelectable && mEditor.mShowSoftInputOnFocus) {
8328                    handled |= imm != null && imm.showSoftInput(this, 0);
8329                }
8330
8331                // The above condition ensures that the mEditor is not null
8332                mEditor.onTouchUpEvent(event);
8333
8334                handled = true;
8335            }
8336
8337            if (handled) {
8338                return true;
8339            }
8340        }
8341
8342        return superResult;
8343    }
8344
8345    @Override
8346    public boolean onGenericMotionEvent(MotionEvent event) {
8347        if (mMovement != null && mText instanceof Spannable && mLayout != null) {
8348            try {
8349                if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) {
8350                    return true;
8351                }
8352            } catch (AbstractMethodError ex) {
8353                // onGenericMotionEvent was added to the MovementMethod interface in API 12.
8354                // Ignore its absence in case third party applications implemented the
8355                // interface directly.
8356            }
8357        }
8358        return super.onGenericMotionEvent(event);
8359    }
8360
8361    /**
8362     * @return True iff this TextView contains a text that can be edited, or if this is
8363     * a selectable TextView.
8364     */
8365    boolean isTextEditable() {
8366        return mText instanceof Editable && onCheckIsTextEditor() && isEnabled();
8367    }
8368
8369    /**
8370     * Returns true, only while processing a touch gesture, if the initial
8371     * touch down event caused focus to move to the text view and as a result
8372     * its selection changed.  Only valid while processing the touch gesture
8373     * of interest, in an editable text view.
8374     */
8375    public boolean didTouchFocusSelect() {
8376        return mEditor != null && mEditor.mTouchFocusSelected;
8377    }
8378
8379    @Override
8380    public void cancelLongPress() {
8381        super.cancelLongPress();
8382        if (mEditor != null) mEditor.mIgnoreActionUpEvent = true;
8383    }
8384
8385    @Override
8386    public boolean onTrackballEvent(MotionEvent event) {
8387        if (mMovement != null && mText instanceof Spannable && mLayout != null) {
8388            if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) {
8389                return true;
8390            }
8391        }
8392
8393        return super.onTrackballEvent(event);
8394    }
8395
8396    public void setScroller(Scroller s) {
8397        mScroller = s;
8398    }
8399
8400    @Override
8401    protected float getLeftFadingEdgeStrength() {
8402        if (mEllipsize == TextUtils.TruncateAt.MARQUEE &&
8403                mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
8404            if (mMarquee != null && !mMarquee.isStopped()) {
8405                final Marquee marquee = mMarquee;
8406                if (marquee.shouldDrawLeftFade()) {
8407                    final float scroll = marquee.getScroll();
8408                    return scroll / getHorizontalFadingEdgeLength();
8409                } else {
8410                    return 0.0f;
8411                }
8412            } else if (getLineCount() == 1) {
8413                final int layoutDirection = getLayoutDirection();
8414                final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
8415                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
8416                    case Gravity.LEFT:
8417                        return 0.0f;
8418                    case Gravity.RIGHT:
8419                        return (mLayout.getLineRight(0) - (mRight - mLeft) -
8420                                getCompoundPaddingLeft() - getCompoundPaddingRight() -
8421                                mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength();
8422                    case Gravity.CENTER_HORIZONTAL:
8423                    case Gravity.FILL_HORIZONTAL:
8424                        final int textDirection = mLayout.getParagraphDirection(0);
8425                        if (textDirection == Layout.DIR_LEFT_TO_RIGHT) {
8426                            return 0.0f;
8427                        } else {
8428                            return (mLayout.getLineRight(0) - (mRight - mLeft) -
8429                                getCompoundPaddingLeft() - getCompoundPaddingRight() -
8430                                mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength();
8431                        }
8432                }
8433            }
8434        }
8435        return super.getLeftFadingEdgeStrength();
8436    }
8437
8438    @Override
8439    protected float getRightFadingEdgeStrength() {
8440        if (mEllipsize == TextUtils.TruncateAt.MARQUEE &&
8441                mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
8442            if (mMarquee != null && !mMarquee.isStopped()) {
8443                final Marquee marquee = mMarquee;
8444                final float maxFadeScroll = marquee.getMaxFadeScroll();
8445                final float scroll = marquee.getScroll();
8446                return (maxFadeScroll - scroll) / getHorizontalFadingEdgeLength();
8447            } else if (getLineCount() == 1) {
8448                final int layoutDirection = getLayoutDirection();
8449                final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
8450                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
8451                    case Gravity.LEFT:
8452                        final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() -
8453                                getCompoundPaddingRight();
8454                        final float lineWidth = mLayout.getLineWidth(0);
8455                        return (lineWidth - textWidth) / getHorizontalFadingEdgeLength();
8456                    case Gravity.RIGHT:
8457                        return 0.0f;
8458                    case Gravity.CENTER_HORIZONTAL:
8459                    case Gravity.FILL_HORIZONTAL:
8460                        final int textDirection = mLayout.getParagraphDirection(0);
8461                        if (textDirection == Layout.DIR_RIGHT_TO_LEFT) {
8462                            return 0.0f;
8463                        } else {
8464                            return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
8465                                getCompoundPaddingLeft() - getCompoundPaddingRight())) /
8466                                getHorizontalFadingEdgeLength();
8467                        }
8468                }
8469            }
8470        }
8471        return super.getRightFadingEdgeStrength();
8472    }
8473
8474    @Override
8475    protected int computeHorizontalScrollRange() {
8476        if (mLayout != null) {
8477            return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ?
8478                    (int) mLayout.getLineWidth(0) : mLayout.getWidth();
8479        }
8480
8481        return super.computeHorizontalScrollRange();
8482    }
8483
8484    @Override
8485    protected int computeVerticalScrollRange() {
8486        if (mLayout != null)
8487            return mLayout.getHeight();
8488
8489        return super.computeVerticalScrollRange();
8490    }
8491
8492    @Override
8493    protected int computeVerticalScrollExtent() {
8494        return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
8495    }
8496
8497    @Override
8498    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
8499        super.findViewsWithText(outViews, searched, flags);
8500        if (!outViews.contains(this) && (flags & FIND_VIEWS_WITH_TEXT) != 0
8501                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mText)) {
8502            String searchedLowerCase = searched.toString().toLowerCase();
8503            String textLowerCase = mText.toString().toLowerCase();
8504            if (textLowerCase.contains(searchedLowerCase)) {
8505                outViews.add(this);
8506            }
8507        }
8508    }
8509
8510    public enum BufferType {
8511        NORMAL, SPANNABLE, EDITABLE,
8512    }
8513
8514    /**
8515     * Returns the TextView_textColor attribute from the TypedArray, if set, or
8516     * the TextAppearance_textColor from the TextView_textAppearance attribute,
8517     * if TextView_textColor was not set directly.
8518     *
8519     * @removed
8520     */
8521    public static ColorStateList getTextColors(Context context, TypedArray attrs) {
8522        if (attrs == null) {
8523            // Preserve behavior prior to removal of this API.
8524            throw new NullPointerException();
8525        }
8526
8527        // It's not safe to use this method from apps. The parameter 'attrs'
8528        // must have been obtained using the TextView filter array which is not
8529        // available to the SDK. As such, we grab a default TypedArray with the
8530        // right filter instead here.
8531        final TypedArray a = context.obtainStyledAttributes(R.styleable.TextView);
8532        ColorStateList colors = a.getColorStateList(R.styleable.TextView_textColor);
8533        if (colors == null) {
8534            final int ap = a.getResourceId(R.styleable.TextView_textAppearance, 0);
8535            if (ap != 0) {
8536                final TypedArray appearance = context.obtainStyledAttributes(
8537                        ap, R.styleable.TextAppearance);
8538                colors = appearance.getColorStateList(R.styleable.TextAppearance_textColor);
8539                appearance.recycle();
8540            }
8541        }
8542        a.recycle();
8543
8544        return colors;
8545    }
8546
8547    /**
8548     * Returns the default color from the TextView_textColor attribute from the
8549     * AttributeSet, if set, or the default color from the
8550     * TextAppearance_textColor from the TextView_textAppearance attribute, if
8551     * TextView_textColor was not set directly.
8552     *
8553     * @removed
8554     */
8555    public static int getTextColor(Context context, TypedArray attrs, int def) {
8556        final ColorStateList colors = getTextColors(context, attrs);
8557        if (colors == null) {
8558            return def;
8559        } else {
8560            return colors.getDefaultColor();
8561        }
8562    }
8563
8564    @Override
8565    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8566        if (event.hasModifiers(KeyEvent.META_CTRL_ON)) {
8567            // Handle Ctrl-only shortcuts.
8568            switch (keyCode) {
8569            case KeyEvent.KEYCODE_A:
8570                if (canSelectText()) {
8571                    return onTextContextMenuItem(ID_SELECT_ALL);
8572                }
8573                break;
8574            case KeyEvent.KEYCODE_Z:
8575                if (canUndo()) {
8576                    return onTextContextMenuItem(ID_UNDO);
8577                }
8578                break;
8579            case KeyEvent.KEYCODE_X:
8580                if (canCut()) {
8581                    return onTextContextMenuItem(ID_CUT);
8582                }
8583                break;
8584            case KeyEvent.KEYCODE_C:
8585                if (canCopy()) {
8586                    return onTextContextMenuItem(ID_COPY);
8587                }
8588                break;
8589            case KeyEvent.KEYCODE_V:
8590                if (canPaste()) {
8591                    return onTextContextMenuItem(ID_PASTE);
8592                }
8593                break;
8594            }
8595        } else if (event.hasModifiers(KeyEvent.META_CTRL_ON | KeyEvent.META_SHIFT_ON)) {
8596            // Handle Ctrl-Shift shortcuts.
8597            switch (keyCode) {
8598                case KeyEvent.KEYCODE_Z:
8599                    if (canRedo()) {
8600                        return onTextContextMenuItem(ID_REDO);
8601                    }
8602                    break;
8603                case KeyEvent.KEYCODE_V:
8604                    if (canPaste()) {
8605                        return onTextContextMenuItem(ID_PASTE_AS_PLAIN_TEXT);
8606                    }
8607            }
8608        }
8609        return super.onKeyShortcut(keyCode, event);
8610    }
8611
8612    /**
8613     * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the
8614     * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have
8615     * a selection controller (see {@link Editor#prepareCursorControllers()}), but this is not
8616     * sufficient.
8617     */
8618    boolean canSelectText() {
8619        return mText.length() != 0 && mEditor != null && mEditor.hasSelectionController();
8620    }
8621
8622    /**
8623     * Test based on the <i>intrinsic</i> charateristics of the TextView.
8624     * The text must be spannable and the movement method must allow for arbitary selection.
8625     *
8626     * See also {@link #canSelectText()}.
8627     */
8628    boolean textCanBeSelected() {
8629        // prepareCursorController() relies on this method.
8630        // If you change this condition, make sure prepareCursorController is called anywhere
8631        // the value of this condition might be changed.
8632        if (mMovement == null || !mMovement.canSelectArbitrarily()) return false;
8633        return isTextEditable() ||
8634                (isTextSelectable() && mText instanceof Spannable && isEnabled());
8635    }
8636
8637    private Locale getTextServicesLocale(boolean allowNullLocale) {
8638        // Start fetching the text services locale asynchronously.
8639        updateTextServicesLocaleAsync();
8640        // If !allowNullLocale and there is no cached text services locale, just return the default
8641        // locale.
8642        return (mCurrentSpellCheckerLocaleCache == null && !allowNullLocale) ? Locale.getDefault()
8643                : mCurrentSpellCheckerLocaleCache;
8644    }
8645
8646    /**
8647     * This is a temporary method. Future versions may support multi-locale text.
8648     * Caveat: This method may not return the latest text services locale, but this should be
8649     * acceptable and it's more important to make this method asynchronous.
8650     *
8651     * @return The locale that should be used for a word iterator
8652     * in this TextView, based on the current spell checker settings,
8653     * the current IME's locale, or the system default locale.
8654     * Please note that a word iterator in this TextView is different from another word iterator
8655     * used by SpellChecker.java of TextView. This method should be used for the former.
8656     * @hide
8657     */
8658    // TODO: Support multi-locale
8659    // TODO: Update the text services locale immediately after the keyboard locale is switched
8660    // by catching intent of keyboard switch event
8661    public Locale getTextServicesLocale() {
8662        return getTextServicesLocale(false /* allowNullLocale */);
8663    }
8664
8665    /**
8666     * @return true if this TextView is specialized for showing and interacting with the extracted
8667     * text in a full-screen input method.
8668     * @hide
8669     */
8670    public boolean isInExtractedMode() {
8671        return false;
8672    }
8673
8674    /**
8675     * This is a temporary method. Future versions may support multi-locale text.
8676     * Caveat: This method may not return the latest spell checker locale, but this should be
8677     * acceptable and it's more important to make this method asynchronous.
8678     *
8679     * @return The locale that should be used for a spell checker in this TextView,
8680     * based on the current spell checker settings, the current IME's locale, or the system default
8681     * locale.
8682     * @hide
8683     */
8684    public Locale getSpellCheckerLocale() {
8685        return getTextServicesLocale(true /* allowNullLocale */);
8686    }
8687
8688    private void updateTextServicesLocaleAsync() {
8689        // AsyncTask.execute() uses a serial executor which means we don't have
8690        // to lock around updateTextServicesLocaleLocked() to prevent it from
8691        // being executed n times in parallel.
8692        AsyncTask.execute(new Runnable() {
8693            @Override
8694            public void run() {
8695                updateTextServicesLocaleLocked();
8696            }
8697        });
8698    }
8699
8700    private void updateTextServicesLocaleLocked() {
8701        final TextServicesManager textServicesManager = (TextServicesManager)
8702                mContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);
8703        final SpellCheckerSubtype subtype = textServicesManager.getCurrentSpellCheckerSubtype(true);
8704        final Locale locale;
8705        if (subtype != null) {
8706            locale = SpellCheckerSubtype.constructLocaleFromString(subtype.getLocale());
8707        } else {
8708            locale = null;
8709        }
8710        mCurrentSpellCheckerLocaleCache = locale;
8711    }
8712
8713    void onLocaleChanged() {
8714        // Will be re-created on demand in getWordIterator with the proper new locale
8715        mEditor.mWordIterator = null;
8716    }
8717
8718    /**
8719     * This method is used by the ArrowKeyMovementMethod to jump from one word to the other.
8720     * Made available to achieve a consistent behavior.
8721     * @hide
8722     */
8723    public WordIterator getWordIterator() {
8724        if (mEditor != null) {
8725            return mEditor.getWordIterator();
8726        } else {
8727            return null;
8728        }
8729    }
8730
8731    /** @hide */
8732    @Override
8733    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
8734        super.onPopulateAccessibilityEventInternal(event);
8735
8736        final boolean isPassword = hasPasswordTransformationMethod();
8737        if (!isPassword || shouldSpeakPasswordsForAccessibility()) {
8738            final CharSequence text = getTextForAccessibility();
8739            if (!TextUtils.isEmpty(text)) {
8740                event.getText().add(text);
8741            }
8742        }
8743    }
8744
8745    /**
8746     * @return true if the user has explicitly allowed accessibility services
8747     * to speak passwords.
8748     */
8749    private boolean shouldSpeakPasswordsForAccessibility() {
8750        return (Settings.Secure.getIntForUser(mContext.getContentResolver(),
8751                Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD, 0,
8752                UserHandle.USER_CURRENT_OR_SELF) == 1);
8753    }
8754
8755    @Override
8756    public CharSequence getAccessibilityClassName() {
8757        return TextView.class.getName();
8758    }
8759
8760    @Override
8761    public void onProvideStructure(ViewStructure structure) {
8762        super.onProvideStructure(structure);
8763        final boolean isPassword = hasPasswordTransformationMethod()
8764                || isPasswordInputType(getInputType());
8765        if (!isPassword) {
8766            structure.setText(getText(), getSelectionStart(), getSelectionEnd());
8767
8768            // Extract style information that applies to the TextView as a whole.
8769            int style = 0;
8770            int typefaceStyle = getTypefaceStyle();
8771            if ((typefaceStyle & Typeface.BOLD) != 0) {
8772                style |= AssistStructure.ViewNode.TEXT_STYLE_BOLD;
8773            }
8774            if ((typefaceStyle & Typeface.ITALIC) != 0) {
8775                style |= AssistStructure.ViewNode.TEXT_STYLE_ITALIC;
8776            }
8777
8778            // Global styles can also be set via TextView.setPaintFlags().
8779            int paintFlags = mTextPaint.getFlags();
8780            if ((paintFlags & Paint.FAKE_BOLD_TEXT_FLAG) != 0) {
8781                style |= AssistStructure.ViewNode.TEXT_STYLE_BOLD;
8782            }
8783            if ((paintFlags & Paint.UNDERLINE_TEXT_FLAG) != 0) {
8784                style |= AssistStructure.ViewNode.TEXT_STYLE_UNDERLINE;
8785            }
8786            if ((paintFlags & Paint.STRIKE_THRU_TEXT_FLAG) != 0) {
8787                style |= AssistStructure.ViewNode.TEXT_STYLE_STRIKE_THRU;
8788            }
8789
8790            // TextView does not have its own text background color. A background is either part
8791            // of the View (and can be any drawable) or a BackgroundColorSpan inside the text.
8792            structure.setTextStyle(getTextSize(), getCurrentTextColor(),
8793                    AssistStructure.ViewNode.TEXT_COLOR_UNDEFINED /* bgColor */, style);
8794        }
8795        structure.setHint(getHint());
8796    }
8797
8798    /** @hide */
8799    @Override
8800    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
8801        super.onInitializeAccessibilityEventInternal(event);
8802
8803        final boolean isPassword = hasPasswordTransformationMethod();
8804        event.setPassword(isPassword);
8805
8806        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) {
8807            event.setFromIndex(Selection.getSelectionStart(mText));
8808            event.setToIndex(Selection.getSelectionEnd(mText));
8809            event.setItemCount(mText.length());
8810        }
8811    }
8812
8813    /** @hide */
8814    @Override
8815    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
8816        super.onInitializeAccessibilityNodeInfoInternal(info);
8817
8818        final boolean isPassword = hasPasswordTransformationMethod();
8819        info.setPassword(isPassword);
8820
8821        if (!isPassword || shouldSpeakPasswordsForAccessibility()) {
8822            info.setText(getTextForAccessibility());
8823        }
8824
8825        if (mBufferType == BufferType.EDITABLE) {
8826            info.setEditable(true);
8827        }
8828
8829        if (mEditor != null) {
8830            info.setInputType(mEditor.mInputType);
8831
8832            if (mEditor.mError != null) {
8833                info.setContentInvalid(true);
8834                info.setError(mEditor.mError);
8835            }
8836        }
8837
8838        if (!TextUtils.isEmpty(mText)) {
8839            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
8840            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
8841            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
8842                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
8843                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE
8844                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH
8845                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE);
8846            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
8847        }
8848
8849        if (isFocused()) {
8850            if (canCopy()) {
8851                info.addAction(AccessibilityNodeInfo.ACTION_COPY);
8852            }
8853            if (canPaste()) {
8854                info.addAction(AccessibilityNodeInfo.ACTION_PASTE);
8855            }
8856            if (canCut()) {
8857                info.addAction(AccessibilityNodeInfo.ACTION_CUT);
8858            }
8859            if (canShare()) {
8860                info.addAction(new AccessibilityNodeInfo.AccessibilityAction(
8861                        ACCESSIBILITY_ACTION_SHARE,
8862                        getResources().getString(com.android.internal.R.string.share)));
8863            }
8864            if (canProcessText()) {  // also implies mEditor is not null.
8865                mEditor.mProcessTextIntentActionsHandler.onInitializeAccessibilityNodeInfo(info);
8866            }
8867        }
8868
8869        // Check for known input filter types.
8870        final int numFilters = mFilters.length;
8871        for (int i = 0; i < numFilters; i++) {
8872            final InputFilter filter = mFilters[i];
8873            if (filter instanceof InputFilter.LengthFilter) {
8874                info.setMaxTextLength(((InputFilter.LengthFilter) filter).getMax());
8875            }
8876        }
8877
8878        if (!isSingleLine()) {
8879            info.setMultiLine(true);
8880        }
8881    }
8882
8883    /**
8884     * Performs an accessibility action after it has been offered to the
8885     * delegate.
8886     *
8887     * @hide
8888     */
8889    @Override
8890    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8891        if (mEditor != null
8892                && mEditor.mProcessTextIntentActionsHandler.performAccessibilityAction(action)) {
8893            return true;
8894        }
8895        switch (action) {
8896            case AccessibilityNodeInfo.ACTION_CLICK: {
8897                boolean handled = false;
8898
8899                // Simulate View.onTouchEvent for an ACTION_UP event.
8900                if (isClickable() || isLongClickable()) {
8901                    if (isFocusable() && !isFocused()) {
8902                        requestFocus();
8903                    }
8904
8905                    performClick();
8906                    handled = true;
8907                }
8908
8909                // Simulate TextView.onTouchEvent for an ACTION_UP event.
8910                if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()
8911                        && mText instanceof Spannable && mLayout != null
8912                        && (isTextEditable() || isTextSelectable()) && isFocused()) {
8913                    // Show the IME, except when selecting in read-only text.
8914                    final InputMethodManager imm = InputMethodManager.peekInstance();
8915                    viewClicked(imm);
8916                    if (!isTextSelectable() && mEditor.mShowSoftInputOnFocus && imm != null) {
8917                        handled |= imm.showSoftInput(this, 0);
8918                    }
8919                }
8920
8921                return handled;
8922            }
8923            case AccessibilityNodeInfo.ACTION_COPY: {
8924                if (isFocused() && canCopy()) {
8925                    if (onTextContextMenuItem(ID_COPY)) {
8926                        return true;
8927                    }
8928                }
8929            } return false;
8930            case AccessibilityNodeInfo.ACTION_PASTE: {
8931                if (isFocused() && canPaste()) {
8932                    if (onTextContextMenuItem(ID_PASTE)) {
8933                        return true;
8934                    }
8935                }
8936            } return false;
8937            case AccessibilityNodeInfo.ACTION_CUT: {
8938                if (isFocused() && canCut()) {
8939                    if (onTextContextMenuItem(ID_CUT)) {
8940                        return true;
8941                    }
8942                }
8943            } return false;
8944            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8945                ensureIterableTextForAccessibilitySelectable();
8946                CharSequence text = getIterableTextForAccessibility();
8947                if (text == null) {
8948                    return false;
8949                }
8950                final int start = (arguments != null) ? arguments.getInt(
8951                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8952                final int end = (arguments != null) ? arguments.getInt(
8953                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8954                if ((getSelectionStart() != start || getSelectionEnd() != end)) {
8955                    // No arguments clears the selection.
8956                    if (start == end && end == -1) {
8957                        Selection.removeSelection((Spannable) text);
8958                        return true;
8959                    }
8960                    if (start >= 0 && start <= end && end <= text.length()) {
8961                        Selection.setSelection((Spannable) text, start, end);
8962                        // Make sure selection mode is engaged.
8963                        if (mEditor != null) {
8964                            mEditor.startSelectionActionMode();
8965                        }
8966                        return true;
8967                    }
8968                }
8969            } return false;
8970            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY:
8971            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8972                ensureIterableTextForAccessibilitySelectable();
8973                return super.performAccessibilityActionInternal(action, arguments);
8974            }
8975            case ACCESSIBILITY_ACTION_SHARE: {
8976                if (isFocused() && canShare()) {
8977                    if (onTextContextMenuItem(ID_SHARE)) {
8978                        return true;
8979                    }
8980                }
8981            } return false;
8982            default: {
8983                return super.performAccessibilityActionInternal(action, arguments);
8984            }
8985        }
8986    }
8987
8988    /** @hide */
8989    @Override
8990    public void sendAccessibilityEventInternal(int eventType) {
8991        if (eventType == AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED && mEditor != null) {
8992            mEditor.mProcessTextIntentActionsHandler.initializeAccessibilityActions();
8993        }
8994
8995        // Do not send scroll events since first they are not interesting for
8996        // accessibility and second such events a generated too frequently.
8997        // For details see the implementation of bringTextIntoView().
8998        if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
8999            return;
9000        }
9001        super.sendAccessibilityEventInternal(eventType);
9002    }
9003
9004    /**
9005     * Gets the text reported for accessibility purposes.
9006     *
9007     * @return The accessibility text.
9008     *
9009     * @hide
9010     */
9011    public CharSequence getTextForAccessibility() {
9012        CharSequence text = getText();
9013        if (TextUtils.isEmpty(text)) {
9014            text = getHint();
9015        }
9016        return text;
9017    }
9018
9019    void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText,
9020            int fromIndex, int removedCount, int addedCount) {
9021        AccessibilityEvent event =
9022            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
9023        event.setFromIndex(fromIndex);
9024        event.setRemovedCount(removedCount);
9025        event.setAddedCount(addedCount);
9026        event.setBeforeText(beforeText);
9027        sendAccessibilityEventUnchecked(event);
9028    }
9029
9030    /**
9031     * Returns whether this text view is a current input method target.  The
9032     * default implementation just checks with {@link InputMethodManager}.
9033     */
9034    public boolean isInputMethodTarget() {
9035        InputMethodManager imm = InputMethodManager.peekInstance();
9036        return imm != null && imm.isActive(this);
9037    }
9038
9039    static final int ID_SELECT_ALL = android.R.id.selectAll;
9040    static final int ID_UNDO = android.R.id.undo;
9041    static final int ID_REDO = android.R.id.redo;
9042    static final int ID_CUT = android.R.id.cut;
9043    static final int ID_COPY = android.R.id.copy;
9044    static final int ID_PASTE = android.R.id.paste;
9045    static final int ID_SHARE = android.R.id.shareText;
9046    static final int ID_PASTE_AS_PLAIN_TEXT = android.R.id.pasteAsPlainText;
9047    static final int ID_REPLACE = android.R.id.replaceText;
9048
9049    /**
9050     * Called when a context menu option for the text view is selected.  Currently
9051     * this will be one of {@link android.R.id#selectAll}, {@link android.R.id#cut},
9052     * {@link android.R.id#copy}, {@link android.R.id#paste} or {@link android.R.id#shareText}.
9053     *
9054     * @return true if the context menu item action was performed.
9055     */
9056    public boolean onTextContextMenuItem(int id) {
9057        int min = 0;
9058        int max = mText.length();
9059
9060        if (isFocused()) {
9061            final int selStart = getSelectionStart();
9062            final int selEnd = getSelectionEnd();
9063
9064            min = Math.max(0, Math.min(selStart, selEnd));
9065            max = Math.max(0, Math.max(selStart, selEnd));
9066        }
9067
9068        switch (id) {
9069            case ID_SELECT_ALL:
9070                // This starts an action mode if triggered from another action mode. Text is
9071                // highlighted, so that it can be bulk edited, like selectAllOnFocus does. Returns
9072                // true even if text is empty.
9073                boolean shouldRestartActionMode =
9074                        mEditor != null && mEditor.mTextActionMode != null;
9075                stopTextActionMode();
9076                selectAllText();
9077                if (shouldRestartActionMode) {
9078                    mEditor.startSelectionActionMode();
9079                }
9080                return true;
9081
9082            case ID_UNDO:
9083                if (mEditor != null) {
9084                    mEditor.undo();
9085                }
9086                return true;  // Returns true even if nothing was undone.
9087
9088            case ID_REDO:
9089                if (mEditor != null) {
9090                    mEditor.redo();
9091                }
9092                return true;  // Returns true even if nothing was undone.
9093
9094            case ID_PASTE:
9095                paste(min, max, true /* withFormatting */);
9096                return true;
9097
9098            case ID_PASTE_AS_PLAIN_TEXT:
9099                paste(min, max, false /* withFormatting */);
9100                return true;
9101
9102            case ID_CUT:
9103                setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
9104                deleteText_internal(min, max);
9105                stopTextActionMode();
9106                return true;
9107
9108            case ID_COPY:
9109                setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
9110                stopTextActionMode();
9111                return true;
9112
9113            case ID_REPLACE:
9114                if (mEditor != null) {
9115                    mEditor.replace();
9116                }
9117                return true;
9118
9119            case ID_SHARE:
9120                shareSelectedText();
9121                return true;
9122        }
9123        return false;
9124    }
9125
9126    CharSequence getTransformedText(int start, int end) {
9127        return removeSuggestionSpans(mTransformed.subSequence(start, end));
9128    }
9129
9130    @Override
9131    public boolean performLongClick() {
9132        boolean handled = false;
9133
9134        if (super.performLongClick()) {
9135            handled = true;
9136        }
9137
9138        if (mEditor != null) {
9139            handled |= mEditor.performLongClick(handled);
9140        }
9141
9142        if (handled) {
9143            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
9144            if (mEditor != null) mEditor.mDiscardNextActionUp = true;
9145        }
9146
9147        return handled;
9148    }
9149
9150    @Override
9151    protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) {
9152        super.onScrollChanged(horiz, vert, oldHoriz, oldVert);
9153        if (mEditor != null) {
9154            mEditor.onScrollChanged();
9155        }
9156    }
9157
9158    /**
9159     * Return whether or not suggestions are enabled on this TextView. The suggestions are generated
9160     * by the IME or by the spell checker as the user types. This is done by adding
9161     * {@link SuggestionSpan}s to the text.
9162     *
9163     * When suggestions are enabled (default), this list of suggestions will be displayed when the
9164     * user asks for them on these parts of the text. This value depends on the inputType of this
9165     * TextView.
9166     *
9167     * The class of the input type must be {@link InputType#TYPE_CLASS_TEXT}.
9168     *
9169     * In addition, the type variation must be one of
9170     * {@link InputType#TYPE_TEXT_VARIATION_NORMAL},
9171     * {@link InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT},
9172     * {@link InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE},
9173     * {@link InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or
9174     * {@link InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}.
9175     *
9176     * And finally, the {@link InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS} flag must <i>not</i> be set.
9177     *
9178     * @return true if the suggestions popup window is enabled, based on the inputType.
9179     */
9180    public boolean isSuggestionsEnabled() {
9181        if (mEditor == null) return false;
9182        if ((mEditor.mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) {
9183            return false;
9184        }
9185        if ((mEditor.mInputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) > 0) return false;
9186
9187        final int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION;
9188        return (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL ||
9189                variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT ||
9190                variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE ||
9191                variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE ||
9192                variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT);
9193    }
9194
9195    /**
9196     * If provided, this ActionMode.Callback will be used to create the ActionMode when text
9197     * selection is initiated in this View.
9198     *
9199     * The standard implementation populates the menu with a subset of Select All, Cut, Copy,
9200     * Paste, Replace and Share actions, depending on what this View supports.
9201     *
9202     * A custom implementation can add new entries in the default menu in its
9203     * {@link android.view.ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The
9204     * default actions can also be removed from the menu using
9205     * {@link android.view.Menu#removeItem(int)} and passing {@link android.R.id#selectAll},
9206     * {@link android.R.id#cut}, {@link android.R.id#copy}, {@link android.R.id#paste},
9207     * {@link android.R.id#replaceText} or {@link android.R.id#shareText} ids as parameters.
9208     *
9209     * Returning false from
9210     * {@link android.view.ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will prevent
9211     * the action mode from being started.
9212     *
9213     * Action click events should be handled by the custom implementation of
9214     * {@link android.view.ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}.
9215     *
9216     * Note that text selection mode is not started when a TextView receives focus and the
9217     * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in
9218     * that case, to allow for quick replacement.
9219     */
9220    public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) {
9221        createEditorIfNeeded();
9222        mEditor.mCustomSelectionActionModeCallback = actionModeCallback;
9223    }
9224
9225    /**
9226     * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null.
9227     *
9228     * @return The current custom selection callback.
9229     */
9230    public ActionMode.Callback getCustomSelectionActionModeCallback() {
9231        return mEditor == null ? null : mEditor.mCustomSelectionActionModeCallback;
9232    }
9233
9234    /**
9235     * If provided, this ActionMode.Callback will be used to create the ActionMode when text
9236     * insertion is initiated in this View.
9237     * The standard implementation populates the menu with a subset of Select All,
9238     * Paste and Replace actions, depending on what this View supports.
9239     *
9240     * <p>A custom implementation can add new entries in the default menu in its
9241     * {@link android.view.ActionMode.Callback#onPrepareActionMode(android.view.ActionMode,
9242     * android.view.Menu)} method. The default actions can also be removed from the menu using
9243     * {@link android.view.Menu#removeItem(int)} and passing {@link android.R.id#selectAll},
9244     * {@link android.R.id#paste} or {@link android.R.id#replaceText} ids as parameters.</p>
9245     *
9246     * <p>Returning false from
9247     * {@link android.view.ActionMode.Callback#onCreateActionMode(android.view.ActionMode,
9248     * android.view.Menu)} will prevent the action mode from being started.</p>
9249     *
9250     * <p>Action click events should be handled by the custom implementation of
9251     * {@link android.view.ActionMode.Callback#onActionItemClicked(android.view.ActionMode,
9252     * android.view.MenuItem)}.</p>
9253     *
9254     * <p>Note that text insertion mode is not started when a TextView receives focus and the
9255     * {@link android.R.attr#selectAllOnFocus} flag has been set.</p>
9256     */
9257    public void setCustomInsertionActionModeCallback(ActionMode.Callback actionModeCallback) {
9258        createEditorIfNeeded();
9259        mEditor.mCustomInsertionActionModeCallback = actionModeCallback;
9260    }
9261
9262    /**
9263     * Retrieves the value set in {@link #setCustomInsertionActionModeCallback}. Default is null.
9264     *
9265     * @return The current custom insertion callback.
9266     */
9267    public ActionMode.Callback getCustomInsertionActionModeCallback() {
9268        return mEditor == null ? null : mEditor.mCustomInsertionActionModeCallback;
9269    }
9270
9271    /**
9272     * @hide
9273     */
9274    protected void stopTextActionMode() {
9275        if (mEditor != null) {
9276            mEditor.stopTextActionMode();
9277        }
9278    }
9279
9280    boolean canUndo() {
9281        return mEditor != null && mEditor.canUndo();
9282    }
9283
9284    boolean canRedo() {
9285        return mEditor != null && mEditor.canRedo();
9286    }
9287
9288    boolean canCut() {
9289        if (hasPasswordTransformationMethod()) {
9290            return false;
9291        }
9292
9293        if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mEditor != null &&
9294                mEditor.mKeyListener != null) {
9295            return true;
9296        }
9297
9298        return false;
9299    }
9300
9301    boolean canCopy() {
9302        if (hasPasswordTransformationMethod()) {
9303            return false;
9304        }
9305
9306        if (mText.length() > 0 && hasSelection() && mEditor != null) {
9307            return true;
9308        }
9309
9310        return false;
9311    }
9312
9313    boolean canShare() {
9314        return canCopy();
9315    }
9316
9317    boolean canPaste() {
9318        return (mText instanceof Editable &&
9319                mEditor != null && mEditor.mKeyListener != null &&
9320                getSelectionStart() >= 0 &&
9321                getSelectionEnd() >= 0 &&
9322                ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)).
9323                hasPrimaryClip());
9324    }
9325
9326    boolean canProcessText() {
9327        if (!getContext().canStartActivityForResult() || getId() == View.NO_ID
9328                || hasPasswordTransformationMethod()) {
9329            return false;
9330        }
9331
9332        if (mText.length() > 0 && hasSelection() && mEditor != null) {
9333            return true;
9334        }
9335
9336        return false;
9337    }
9338
9339    boolean canSelectAllText() {
9340        return canSelectText() && !hasPasswordTransformationMethod()
9341                && !(getSelectionStart() == 0 && getSelectionEnd() == mText.length());
9342    }
9343
9344    boolean selectAllText() {
9345        // Need to hide insert point cursor controller before settings selection, otherwise insert
9346        // point cursor controller obtains cursor update event and update cursor with cancelling
9347        // selection.
9348        if (mEditor != null) {
9349            mEditor.hideInsertionPointCursorController();
9350        }
9351        final int length = mText.length();
9352        Selection.setSelection((Spannable) mText, 0, length);
9353        return length > 0;
9354    }
9355
9356    void replaceSelectionWithText(CharSequence text) {
9357        ((Editable) mText).replace(getSelectionStart(), getSelectionEnd(), text);
9358    }
9359
9360    /**
9361     * Paste clipboard content between min and max positions.
9362     */
9363    private void paste(int min, int max, boolean withFormatting) {
9364        ClipboardManager clipboard =
9365            (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
9366        ClipData clip = clipboard.getPrimaryClip();
9367        if (clip != null) {
9368            boolean didFirst = false;
9369            for (int i=0; i<clip.getItemCount(); i++) {
9370                final CharSequence paste;
9371                if (withFormatting) {
9372                    paste = clip.getItemAt(i).coerceToStyledText(getContext());
9373                } else {
9374                    // Get an item as text and remove all spans by toString().
9375                    final CharSequence text = clip.getItemAt(i).coerceToText(getContext());
9376                    paste = (text instanceof Spanned) ? text.toString() : text;
9377                }
9378                if (paste != null) {
9379                    if (!didFirst) {
9380                        Selection.setSelection((Spannable) mText, max);
9381                        ((Editable) mText).replace(min, max, paste);
9382                        didFirst = true;
9383                    } else {
9384                        ((Editable) mText).insert(getSelectionEnd(), "\n");
9385                        ((Editable) mText).insert(getSelectionEnd(), paste);
9386                    }
9387                }
9388            }
9389            stopTextActionMode();
9390            sLastCutCopyOrTextChangedTime = 0;
9391        }
9392    }
9393
9394    private void shareSelectedText() {
9395        String selectedText = getSelectedText();
9396        if (selectedText != null && !selectedText.isEmpty()) {
9397            Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
9398            sharingIntent.setType("text/plain");
9399            sharingIntent.removeExtra(android.content.Intent.EXTRA_TEXT);
9400            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, selectedText);
9401            getContext().startActivity(Intent.createChooser(sharingIntent, null));
9402            stopTextActionMode();
9403        }
9404    }
9405
9406    private void setPrimaryClip(ClipData clip) {
9407        ClipboardManager clipboard = (ClipboardManager) getContext().
9408                getSystemService(Context.CLIPBOARD_SERVICE);
9409        clipboard.setPrimaryClip(clip);
9410        sLastCutCopyOrTextChangedTime = SystemClock.uptimeMillis();
9411    }
9412
9413    /**
9414     * Get the character offset closest to the specified absolute position. A typical use case is to
9415     * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method.
9416     *
9417     * @param x The horizontal absolute position of a point on screen
9418     * @param y The vertical absolute position of a point on screen
9419     * @return the character offset for the character whose position is closest to the specified
9420     *  position. Returns -1 if there is no layout.
9421     */
9422    public int getOffsetForPosition(float x, float y) {
9423        if (getLayout() == null) return -1;
9424        final int line = getLineAtCoordinate(y);
9425        final int offset = getOffsetAtCoordinate(line, x);
9426        return offset;
9427    }
9428
9429    float convertToLocalHorizontalCoordinate(float x) {
9430        x -= getTotalPaddingLeft();
9431        // Clamp the position to inside of the view.
9432        x = Math.max(0.0f, x);
9433        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
9434        x += getScrollX();
9435        return x;
9436    }
9437
9438    int getLineAtCoordinate(float y) {
9439        y -= getTotalPaddingTop();
9440        // Clamp the position to inside of the view.
9441        y = Math.max(0.0f, y);
9442        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
9443        y += getScrollY();
9444        return getLayout().getLineForVertical((int) y);
9445    }
9446
9447    int getOffsetAtCoordinate(int line, float x) {
9448        x = convertToLocalHorizontalCoordinate(x);
9449        return getLayout().getOffsetForHorizontal(line, x);
9450    }
9451
9452    @Override
9453    public boolean onDragEvent(DragEvent event) {
9454        switch (event.getAction()) {
9455            case DragEvent.ACTION_DRAG_STARTED:
9456                return mEditor != null && mEditor.hasInsertionController();
9457
9458            case DragEvent.ACTION_DRAG_ENTERED:
9459                TextView.this.requestFocus();
9460                return true;
9461
9462            case DragEvent.ACTION_DRAG_LOCATION:
9463                final int offset = getOffsetForPosition(event.getX(), event.getY());
9464                Selection.setSelection((Spannable)mText, offset);
9465                return true;
9466
9467            case DragEvent.ACTION_DROP:
9468                if (mEditor != null) mEditor.onDrop(event);
9469                return true;
9470
9471            case DragEvent.ACTION_DRAG_ENDED:
9472            case DragEvent.ACTION_DRAG_EXITED:
9473            default:
9474                return true;
9475        }
9476    }
9477
9478    boolean isInBatchEditMode() {
9479        if (mEditor == null) return false;
9480        final Editor.InputMethodState ims = mEditor.mInputMethodState;
9481        if (ims != null) {
9482            return ims.mBatchEditNesting > 0;
9483        }
9484        return mEditor.mInBatchEditControllers;
9485    }
9486
9487    @Override
9488    public void onRtlPropertiesChanged(int layoutDirection) {
9489        super.onRtlPropertiesChanged(layoutDirection);
9490
9491        final TextDirectionHeuristic newTextDir = getTextDirectionHeuristic();
9492        if (mTextDir != newTextDir) {
9493            mTextDir = newTextDir;
9494            if (mLayout != null) {
9495                checkForRelayout();
9496            }
9497        }
9498    }
9499
9500    TextDirectionHeuristic getTextDirectionHeuristic() {
9501        if (hasPasswordTransformationMethod()) {
9502            // passwords fields should be LTR
9503            return TextDirectionHeuristics.LTR;
9504        }
9505
9506        // Always need to resolve layout direction first
9507        final boolean defaultIsRtl = (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
9508
9509        // Now, we can select the heuristic
9510        switch (getTextDirection()) {
9511            default:
9512            case TEXT_DIRECTION_FIRST_STRONG:
9513                return (defaultIsRtl ? TextDirectionHeuristics.FIRSTSTRONG_RTL :
9514                        TextDirectionHeuristics.FIRSTSTRONG_LTR);
9515            case TEXT_DIRECTION_ANY_RTL:
9516                return TextDirectionHeuristics.ANYRTL_LTR;
9517            case TEXT_DIRECTION_LTR:
9518                return TextDirectionHeuristics.LTR;
9519            case TEXT_DIRECTION_RTL:
9520                return TextDirectionHeuristics.RTL;
9521            case TEXT_DIRECTION_LOCALE:
9522                return TextDirectionHeuristics.LOCALE;
9523            case TEXT_DIRECTION_FIRST_STRONG_LTR:
9524                return TextDirectionHeuristics.FIRSTSTRONG_LTR;
9525            case TEXT_DIRECTION_FIRST_STRONG_RTL:
9526                return TextDirectionHeuristics.FIRSTSTRONG_RTL;
9527        }
9528    }
9529
9530    /**
9531     * @hide
9532     */
9533    @Override
9534    public void onResolveDrawables(int layoutDirection) {
9535        // No need to resolve twice
9536        if (mLastLayoutDirection == layoutDirection) {
9537            return;
9538        }
9539        mLastLayoutDirection = layoutDirection;
9540
9541        // Resolve drawables
9542        if (mDrawables != null) {
9543            mDrawables.resolveWithLayoutDirection(layoutDirection);
9544        }
9545    }
9546
9547    /**
9548     * @hide
9549     */
9550    protected void resetResolvedDrawables() {
9551        super.resetResolvedDrawables();
9552        mLastLayoutDirection = -1;
9553    }
9554
9555    /**
9556     * @hide
9557     */
9558    protected void viewClicked(InputMethodManager imm) {
9559        if (imm != null) {
9560            imm.viewClicked(this);
9561        }
9562    }
9563
9564    /**
9565     * Deletes the range of text [start, end[.
9566     * @hide
9567     */
9568    protected void deleteText_internal(int start, int end) {
9569        ((Editable) mText).delete(start, end);
9570    }
9571
9572    /**
9573     * Replaces the range of text [start, end[ by replacement text
9574     * @hide
9575     */
9576    protected void replaceText_internal(int start, int end, CharSequence text) {
9577        ((Editable) mText).replace(start, end, text);
9578    }
9579
9580    /**
9581     * Sets a span on the specified range of text
9582     * @hide
9583     */
9584    protected void setSpan_internal(Object span, int start, int end, int flags) {
9585        ((Editable) mText).setSpan(span, start, end, flags);
9586    }
9587
9588    /**
9589     * Moves the cursor to the specified offset position in text
9590     * @hide
9591     */
9592    protected void setCursorPosition_internal(int start, int end) {
9593        Selection.setSelection(((Editable) mText), start, end);
9594    }
9595
9596    /**
9597     * An Editor should be created as soon as any of the editable-specific fields (grouped
9598     * inside the Editor object) is assigned to a non-default value.
9599     * This method will create the Editor if needed.
9600     *
9601     * A standard TextView (as well as buttons, checkboxes...) should not qualify and hence will
9602     * have a null Editor, unlike an EditText. Inconsistent in-between states will have an
9603     * Editor for backward compatibility, as soon as one of these fields is assigned.
9604     *
9605     * Also note that for performance reasons, the mEditor is created when needed, but not
9606     * reset when no more edit-specific fields are needed.
9607     */
9608    private void createEditorIfNeeded() {
9609        if (mEditor == null) {
9610            mEditor = new Editor(this);
9611        }
9612    }
9613
9614    /**
9615     * @hide
9616     */
9617    @Override
9618    public CharSequence getIterableTextForAccessibility() {
9619        return mText;
9620    }
9621
9622    private void ensureIterableTextForAccessibilitySelectable() {
9623        if (!(mText instanceof Spannable)) {
9624            setText(mText, BufferType.SPANNABLE);
9625        }
9626    }
9627
9628    /**
9629     * @hide
9630     */
9631    @Override
9632    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9633        switch (granularity) {
9634            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE: {
9635                Spannable text = (Spannable) getIterableTextForAccessibility();
9636                if (!TextUtils.isEmpty(text) && getLayout() != null) {
9637                    AccessibilityIterators.LineTextSegmentIterator iterator =
9638                        AccessibilityIterators.LineTextSegmentIterator.getInstance();
9639                    iterator.initialize(text, getLayout());
9640                    return iterator;
9641                }
9642            } break;
9643            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE: {
9644                Spannable text = (Spannable) getIterableTextForAccessibility();
9645                if (!TextUtils.isEmpty(text) && getLayout() != null) {
9646                    AccessibilityIterators.PageTextSegmentIterator iterator =
9647                        AccessibilityIterators.PageTextSegmentIterator.getInstance();
9648                    iterator.initialize(this);
9649                    return iterator;
9650                }
9651            } break;
9652        }
9653        return super.getIteratorForGranularity(granularity);
9654    }
9655
9656    /**
9657     * @hide
9658     */
9659    @Override
9660    public int getAccessibilitySelectionStart() {
9661        return getSelectionStart();
9662    }
9663
9664    /**
9665     * @hide
9666     */
9667    public boolean isAccessibilitySelectionExtendable() {
9668        return true;
9669    }
9670
9671    /**
9672     * @hide
9673     */
9674    @Override
9675    public int getAccessibilitySelectionEnd() {
9676        return getSelectionEnd();
9677    }
9678
9679    /**
9680     * @hide
9681     */
9682    @Override
9683    public void setAccessibilitySelection(int start, int end) {
9684        if (getAccessibilitySelectionStart() == start
9685                && getAccessibilitySelectionEnd() == end) {
9686            return;
9687        }
9688        // Hide all selection controllers used for adjusting selection
9689        // since we are doing so explicitlty by other means and these
9690        // controllers interact with how selection behaves.
9691        if (mEditor != null) {
9692            mEditor.hideCursorAndSpanControllers();
9693            mEditor.stopTextActionMode();
9694        }
9695        CharSequence text = getIterableTextForAccessibility();
9696        if (Math.min(start, end) >= 0 && Math.max(start, end) <= text.length()) {
9697            Selection.setSelection((Spannable) text, start, end);
9698        } else {
9699            Selection.removeSelection((Spannable) text);
9700        }
9701    }
9702
9703    /** @hide */
9704    @Override
9705    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
9706        super.encodeProperties(stream);
9707
9708        TruncateAt ellipsize = getEllipsize();
9709        stream.addProperty("text:ellipsize", ellipsize == null ? null : ellipsize.name());
9710        stream.addProperty("text:textSize", getTextSize());
9711        stream.addProperty("text:scaledTextSize", getScaledTextSize());
9712        stream.addProperty("text:typefaceStyle", getTypefaceStyle());
9713        stream.addProperty("text:selectionStart", getSelectionStart());
9714        stream.addProperty("text:selectionEnd", getSelectionEnd());
9715        stream.addProperty("text:curTextColor", mCurTextColor);
9716        stream.addProperty("text:text", mText == null ? null : mText.toString());
9717        stream.addProperty("text:gravity", mGravity);
9718    }
9719
9720    /**
9721     * User interface state that is stored by TextView for implementing
9722     * {@link View#onSaveInstanceState}.
9723     */
9724    public static class SavedState extends BaseSavedState {
9725        int selStart;
9726        int selEnd;
9727        CharSequence text;
9728        boolean frozenWithFocus;
9729        CharSequence error;
9730        ParcelableParcel editorState;  // Optional state from Editor.
9731
9732        SavedState(Parcelable superState) {
9733            super(superState);
9734        }
9735
9736        @Override
9737        public void writeToParcel(Parcel out, int flags) {
9738            super.writeToParcel(out, flags);
9739            out.writeInt(selStart);
9740            out.writeInt(selEnd);
9741            out.writeInt(frozenWithFocus ? 1 : 0);
9742            TextUtils.writeToParcel(text, out, flags);
9743
9744            if (error == null) {
9745                out.writeInt(0);
9746            } else {
9747                out.writeInt(1);
9748                TextUtils.writeToParcel(error, out, flags);
9749            }
9750
9751            if (editorState == null) {
9752                out.writeInt(0);
9753            } else {
9754                out.writeInt(1);
9755                editorState.writeToParcel(out, flags);
9756            }
9757        }
9758
9759        @Override
9760        public String toString() {
9761            String str = "TextView.SavedState{"
9762                    + Integer.toHexString(System.identityHashCode(this))
9763                    + " start=" + selStart + " end=" + selEnd;
9764            if (text != null) {
9765                str += " text=" + text;
9766            }
9767            return str + "}";
9768        }
9769
9770        @SuppressWarnings("hiding")
9771        public static final Parcelable.Creator<SavedState> CREATOR
9772                = new Parcelable.Creator<SavedState>() {
9773            public SavedState createFromParcel(Parcel in) {
9774                return new SavedState(in);
9775            }
9776
9777            public SavedState[] newArray(int size) {
9778                return new SavedState[size];
9779            }
9780        };
9781
9782        private SavedState(Parcel in) {
9783            super(in);
9784            selStart = in.readInt();
9785            selEnd = in.readInt();
9786            frozenWithFocus = (in.readInt() != 0);
9787            text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
9788
9789            if (in.readInt() != 0) {
9790                error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
9791            }
9792
9793            if (in.readInt() != 0) {
9794                editorState = ParcelableParcel.CREATOR.createFromParcel(in);
9795            }
9796        }
9797    }
9798
9799    private static class CharWrapper implements CharSequence, GetChars, GraphicsOperations {
9800        private char[] mChars;
9801        private int mStart, mLength;
9802
9803        public CharWrapper(char[] chars, int start, int len) {
9804            mChars = chars;
9805            mStart = start;
9806            mLength = len;
9807        }
9808
9809        /* package */ void set(char[] chars, int start, int len) {
9810            mChars = chars;
9811            mStart = start;
9812            mLength = len;
9813        }
9814
9815        public int length() {
9816            return mLength;
9817        }
9818
9819        public char charAt(int off) {
9820            return mChars[off + mStart];
9821        }
9822
9823        @Override
9824        public String toString() {
9825            return new String(mChars, mStart, mLength);
9826        }
9827
9828        public CharSequence subSequence(int start, int end) {
9829            if (start < 0 || end < 0 || start > mLength || end > mLength) {
9830                throw new IndexOutOfBoundsException(start + ", " + end);
9831            }
9832
9833            return new String(mChars, start + mStart, end - start);
9834        }
9835
9836        public void getChars(int start, int end, char[] buf, int off) {
9837            if (start < 0 || end < 0 || start > mLength || end > mLength) {
9838                throw new IndexOutOfBoundsException(start + ", " + end);
9839            }
9840
9841            System.arraycopy(mChars, start + mStart, buf, off, end - start);
9842        }
9843
9844        public void drawText(Canvas c, int start, int end,
9845                             float x, float y, Paint p) {
9846            c.drawText(mChars, start + mStart, end - start, x, y, p);
9847        }
9848
9849        public void drawTextRun(Canvas c, int start, int end,
9850                int contextStart, int contextEnd, float x, float y, boolean isRtl, Paint p) {
9851            int count = end - start;
9852            int contextCount = contextEnd - contextStart;
9853            c.drawTextRun(mChars, start + mStart, count, contextStart + mStart,
9854                    contextCount, x, y, isRtl, p);
9855        }
9856
9857        public float measureText(int start, int end, Paint p) {
9858            return p.measureText(mChars, start + mStart, end - start);
9859        }
9860
9861        public int getTextWidths(int start, int end, float[] widths, Paint p) {
9862            return p.getTextWidths(mChars, start + mStart, end - start, widths);
9863        }
9864
9865        public float getTextRunAdvances(int start, int end, int contextStart,
9866                int contextEnd, boolean isRtl, float[] advances, int advancesIndex,
9867                Paint p) {
9868            int count = end - start;
9869            int contextCount = contextEnd - contextStart;
9870            return p.getTextRunAdvances(mChars, start + mStart, count,
9871                    contextStart + mStart, contextCount, isRtl, advances,
9872                    advancesIndex);
9873        }
9874
9875        public int getTextRunCursor(int contextStart, int contextEnd, int dir,
9876                int offset, int cursorOpt, Paint p) {
9877            int contextCount = contextEnd - contextStart;
9878            return p.getTextRunCursor(mChars, contextStart + mStart,
9879                    contextCount, dir, offset + mStart, cursorOpt);
9880        }
9881    }
9882
9883    private static final class Marquee {
9884        // TODO: Add an option to configure this
9885        private static final float MARQUEE_DELTA_MAX = 0.07f;
9886        private static final int MARQUEE_DELAY = 1200;
9887        private static final int MARQUEE_DP_PER_SECOND = 30;
9888
9889        private static final byte MARQUEE_STOPPED = 0x0;
9890        private static final byte MARQUEE_STARTING = 0x1;
9891        private static final byte MARQUEE_RUNNING = 0x2;
9892
9893        private final WeakReference<TextView> mView;
9894        private final Choreographer mChoreographer;
9895
9896        private byte mStatus = MARQUEE_STOPPED;
9897        private final float mPixelsPerSecond;
9898        private float mMaxScroll;
9899        private float mMaxFadeScroll;
9900        private float mGhostStart;
9901        private float mGhostOffset;
9902        private float mFadeStop;
9903        private int mRepeatLimit;
9904
9905        private float mScroll;
9906        private long mLastAnimationMs;
9907
9908        Marquee(TextView v) {
9909            final float density = v.getContext().getResources().getDisplayMetrics().density;
9910            mPixelsPerSecond = MARQUEE_DP_PER_SECOND * density;
9911            mView = new WeakReference<TextView>(v);
9912            mChoreographer = Choreographer.getInstance();
9913        }
9914
9915        private Choreographer.FrameCallback mTickCallback = new Choreographer.FrameCallback() {
9916            @Override
9917            public void doFrame(long frameTimeNanos) {
9918                tick();
9919            }
9920        };
9921
9922        private Choreographer.FrameCallback mStartCallback = new Choreographer.FrameCallback() {
9923            @Override
9924            public void doFrame(long frameTimeNanos) {
9925                mStatus = MARQUEE_RUNNING;
9926                mLastAnimationMs = mChoreographer.getFrameTime();
9927                tick();
9928            }
9929        };
9930
9931        private Choreographer.FrameCallback mRestartCallback = new Choreographer.FrameCallback() {
9932            @Override
9933            public void doFrame(long frameTimeNanos) {
9934                if (mStatus == MARQUEE_RUNNING) {
9935                    if (mRepeatLimit >= 0) {
9936                        mRepeatLimit--;
9937                    }
9938                    start(mRepeatLimit);
9939                }
9940            }
9941        };
9942
9943        void tick() {
9944            if (mStatus != MARQUEE_RUNNING) {
9945                return;
9946            }
9947
9948            mChoreographer.removeFrameCallback(mTickCallback);
9949
9950            final TextView textView = mView.get();
9951            if (textView != null && (textView.isFocused() || textView.isSelected())) {
9952                long currentMs = mChoreographer.getFrameTime();
9953                long deltaMs = currentMs - mLastAnimationMs;
9954                mLastAnimationMs = currentMs;
9955                float deltaPx = deltaMs / 1000f * mPixelsPerSecond;
9956                mScroll += deltaPx;
9957                if (mScroll > mMaxScroll) {
9958                    mScroll = mMaxScroll;
9959                    mChoreographer.postFrameCallbackDelayed(mRestartCallback, MARQUEE_DELAY);
9960                } else {
9961                    mChoreographer.postFrameCallback(mTickCallback);
9962                }
9963                textView.invalidate();
9964            }
9965        }
9966
9967        void stop() {
9968            mStatus = MARQUEE_STOPPED;
9969            mChoreographer.removeFrameCallback(mStartCallback);
9970            mChoreographer.removeFrameCallback(mRestartCallback);
9971            mChoreographer.removeFrameCallback(mTickCallback);
9972            resetScroll();
9973        }
9974
9975        private void resetScroll() {
9976            mScroll = 0.0f;
9977            final TextView textView = mView.get();
9978            if (textView != null) textView.invalidate();
9979        }
9980
9981        void start(int repeatLimit) {
9982            if (repeatLimit == 0) {
9983                stop();
9984                return;
9985            }
9986            mRepeatLimit = repeatLimit;
9987            final TextView textView = mView.get();
9988            if (textView != null && textView.mLayout != null) {
9989                mStatus = MARQUEE_STARTING;
9990                mScroll = 0.0f;
9991                final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() -
9992                        textView.getCompoundPaddingRight();
9993                final float lineWidth = textView.mLayout.getLineWidth(0);
9994                final float gap = textWidth / 3.0f;
9995                mGhostStart = lineWidth - textWidth + gap;
9996                mMaxScroll = mGhostStart + textWidth;
9997                mGhostOffset = lineWidth + gap;
9998                mFadeStop = lineWidth + textWidth / 6.0f;
9999                mMaxFadeScroll = mGhostStart + lineWidth + lineWidth;
10000
10001                textView.invalidate();
10002                mChoreographer.postFrameCallback(mStartCallback);
10003            }
10004        }
10005
10006        float getGhostOffset() {
10007            return mGhostOffset;
10008        }
10009
10010        float getScroll() {
10011            return mScroll;
10012        }
10013
10014        float getMaxFadeScroll() {
10015            return mMaxFadeScroll;
10016        }
10017
10018        boolean shouldDrawLeftFade() {
10019            return mScroll <= mFadeStop;
10020        }
10021
10022        boolean shouldDrawGhost() {
10023            return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart;
10024        }
10025
10026        boolean isRunning() {
10027            return mStatus == MARQUEE_RUNNING;
10028        }
10029
10030        boolean isStopped() {
10031            return mStatus == MARQUEE_STOPPED;
10032        }
10033    }
10034
10035    private class ChangeWatcher implements TextWatcher, SpanWatcher {
10036
10037        private CharSequence mBeforeText;
10038
10039        public void beforeTextChanged(CharSequence buffer, int start,
10040                                      int before, int after) {
10041            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start
10042                    + " before=" + before + " after=" + after + ": " + buffer);
10043
10044            if (AccessibilityManager.getInstance(mContext).isEnabled()
10045                    && ((!isPasswordInputType(getInputType()) && !hasPasswordTransformationMethod())
10046                            || shouldSpeakPasswordsForAccessibility())) {
10047                mBeforeText = buffer.toString();
10048            }
10049
10050            TextView.this.sendBeforeTextChanged(buffer, start, before, after);
10051        }
10052
10053        public void onTextChanged(CharSequence buffer, int start, int before, int after) {
10054            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start
10055                    + " before=" + before + " after=" + after + ": " + buffer);
10056            TextView.this.handleTextChanged(buffer, start, before, after);
10057
10058            if (AccessibilityManager.getInstance(mContext).isEnabled() &&
10059                    (isFocused() || isSelected() && isShown())) {
10060                sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after);
10061                mBeforeText = null;
10062            }
10063        }
10064
10065        public void afterTextChanged(Editable buffer) {
10066            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer);
10067            TextView.this.sendAfterTextChanged(buffer);
10068
10069            if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) {
10070                MetaKeyKeyListener.stopSelecting(TextView.this, buffer);
10071            }
10072        }
10073
10074        public void onSpanChanged(Spannable buf, Object what, int s, int e, int st, int en) {
10075            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e
10076                    + " st=" + st + " en=" + en + " what=" + what + ": " + buf);
10077            TextView.this.spanChange(buf, what, s, st, e, en);
10078        }
10079
10080        public void onSpanAdded(Spannable buf, Object what, int s, int e) {
10081            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e
10082                    + " what=" + what + ": " + buf);
10083            TextView.this.spanChange(buf, what, -1, s, -1, e);
10084        }
10085
10086        public void onSpanRemoved(Spannable buf, Object what, int s, int e) {
10087            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e
10088                    + " what=" + what + ": " + buf);
10089            TextView.this.spanChange(buf, what, s, -1, e, -1);
10090        }
10091    }
10092}
10093