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