TextView.java revision 324b8d352fda7ca3399bd1fee7d0d3adbd7db35d
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    @android.view.RemotableViewMethod
3265    public void setTextColor(ColorStateList colors) {
3266        if (colors == null) {
3267            throw new NullPointerException();
3268        }
3269
3270        mTextColor = colors;
3271        updateTextColors();
3272    }
3273
3274    /**
3275     * Gets the text colors for the different states (normal, selected, focused) of the TextView.
3276     *
3277     * @see #setTextColor(ColorStateList)
3278     * @see #setTextColor(int)
3279     *
3280     * @attr ref android.R.styleable#TextView_textColor
3281     */
3282    public final ColorStateList getTextColors() {
3283        return mTextColor;
3284    }
3285
3286    /**
3287     * <p>Return the current color selected for normal text.</p>
3288     *
3289     * @return Returns the current text color.
3290     */
3291    @ColorInt
3292    public final int getCurrentTextColor() {
3293        return mCurTextColor;
3294    }
3295
3296    /**
3297     * Sets the color used to display the selection highlight.
3298     *
3299     * @attr ref android.R.styleable#TextView_textColorHighlight
3300     */
3301    @android.view.RemotableViewMethod
3302    public void setHighlightColor(@ColorInt int color) {
3303        if (mHighlightColor != color) {
3304            mHighlightColor = color;
3305            invalidate();
3306        }
3307    }
3308
3309    /**
3310     * @return the color used to display the selection highlight
3311     *
3312     * @see #setHighlightColor(int)
3313     *
3314     * @attr ref android.R.styleable#TextView_textColorHighlight
3315     */
3316    @ColorInt
3317    public int getHighlightColor() {
3318        return mHighlightColor;
3319    }
3320
3321    /**
3322     * Sets whether the soft input method will be made visible when this
3323     * TextView gets focused. The default is true.
3324     */
3325    @android.view.RemotableViewMethod
3326    public final void setShowSoftInputOnFocus(boolean show) {
3327        createEditorIfNeeded();
3328        mEditor.mShowSoftInputOnFocus = show;
3329    }
3330
3331    /**
3332     * Returns whether the soft input method will be made visible when this
3333     * TextView gets focused. The default is true.
3334     */
3335    public final boolean getShowSoftInputOnFocus() {
3336        // When there is no Editor, return default true value
3337        return mEditor == null || mEditor.mShowSoftInputOnFocus;
3338    }
3339
3340    /**
3341     * Gives the text a shadow of the specified blur radius and color, the specified
3342     * distance from its drawn position.
3343     * <p>
3344     * The text shadow produced does not interact with the properties on view
3345     * that are responsible for real time shadows,
3346     * {@link View#getElevation() elevation} and
3347     * {@link View#getTranslationZ() translationZ}.
3348     *
3349     * @see Paint#setShadowLayer(float, float, float, int)
3350     *
3351     * @attr ref android.R.styleable#TextView_shadowColor
3352     * @attr ref android.R.styleable#TextView_shadowDx
3353     * @attr ref android.R.styleable#TextView_shadowDy
3354     * @attr ref android.R.styleable#TextView_shadowRadius
3355     */
3356    public void setShadowLayer(float radius, float dx, float dy, int color) {
3357        mTextPaint.setShadowLayer(radius, dx, dy, color);
3358
3359        mShadowRadius = radius;
3360        mShadowDx = dx;
3361        mShadowDy = dy;
3362        mShadowColor = color;
3363
3364        // Will change text clip region
3365        if (mEditor != null) {
3366            mEditor.invalidateTextDisplayList();
3367            mEditor.invalidateHandlesAndActionMode();
3368        }
3369        invalidate();
3370    }
3371
3372    /**
3373     * Gets the radius of the shadow layer.
3374     *
3375     * @return the radius of the shadow layer. If 0, the shadow layer is not visible
3376     *
3377     * @see #setShadowLayer(float, float, float, int)
3378     *
3379     * @attr ref android.R.styleable#TextView_shadowRadius
3380     */
3381    public float getShadowRadius() {
3382        return mShadowRadius;
3383    }
3384
3385    /**
3386     * @return the horizontal offset of the shadow layer
3387     *
3388     * @see #setShadowLayer(float, float, float, int)
3389     *
3390     * @attr ref android.R.styleable#TextView_shadowDx
3391     */
3392    public float getShadowDx() {
3393        return mShadowDx;
3394    }
3395
3396    /**
3397     * @return the vertical offset of the shadow layer
3398     *
3399     * @see #setShadowLayer(float, float, float, int)
3400     *
3401     * @attr ref android.R.styleable#TextView_shadowDy
3402     */
3403    public float getShadowDy() {
3404        return mShadowDy;
3405    }
3406
3407    /**
3408     * @return the color of the shadow layer
3409     *
3410     * @see #setShadowLayer(float, float, float, int)
3411     *
3412     * @attr ref android.R.styleable#TextView_shadowColor
3413     */
3414    @ColorInt
3415    public int getShadowColor() {
3416        return mShadowColor;
3417    }
3418
3419    /**
3420     * @return the base paint used for the text.  Please use this only to
3421     * consult the Paint's properties and not to change them.
3422     */
3423    public TextPaint getPaint() {
3424        return mTextPaint;
3425    }
3426
3427    /**
3428     * Sets the autolink mask of the text.  See {@link
3429     * android.text.util.Linkify#ALL Linkify.ALL} and peers for
3430     * possible values.
3431     *
3432     * @attr ref android.R.styleable#TextView_autoLink
3433     */
3434    @android.view.RemotableViewMethod
3435    public final void setAutoLinkMask(int mask) {
3436        mAutoLinkMask = mask;
3437    }
3438
3439    /**
3440     * Sets whether the movement method will automatically be set to
3441     * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been
3442     * set to nonzero and links are detected in {@link #setText}.
3443     * The default is true.
3444     *
3445     * @attr ref android.R.styleable#TextView_linksClickable
3446     */
3447    @android.view.RemotableViewMethod
3448    public final void setLinksClickable(boolean whether) {
3449        mLinksClickable = whether;
3450    }
3451
3452    /**
3453     * Returns whether the movement method will automatically be set to
3454     * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been
3455     * set to nonzero and links are detected in {@link #setText}.
3456     * The default is true.
3457     *
3458     * @attr ref android.R.styleable#TextView_linksClickable
3459     */
3460    public final boolean getLinksClickable() {
3461        return mLinksClickable;
3462    }
3463
3464    /**
3465     * Returns the list of URLSpans attached to the text
3466     * (by {@link Linkify} or otherwise) if any.  You can call
3467     * {@link URLSpan#getURL} on them to find where they link to
3468     * or use {@link Spanned#getSpanStart} and {@link Spanned#getSpanEnd}
3469     * to find the region of the text they are attached to.
3470     */
3471    public URLSpan[] getUrls() {
3472        if (mText instanceof Spanned) {
3473            return ((Spanned) mText).getSpans(0, mText.length(), URLSpan.class);
3474        } else {
3475            return new URLSpan[0];
3476        }
3477    }
3478
3479    /**
3480     * Sets the color of the hint text for all the states (disabled, focussed, selected...) of this
3481     * TextView.
3482     *
3483     * @see #setHintTextColor(ColorStateList)
3484     * @see #getHintTextColors()
3485     * @see #setTextColor(int)
3486     *
3487     * @attr ref android.R.styleable#TextView_textColorHint
3488     */
3489    @android.view.RemotableViewMethod
3490    public final void setHintTextColor(@ColorInt int color) {
3491        mHintTextColor = ColorStateList.valueOf(color);
3492        updateTextColors();
3493    }
3494
3495    /**
3496     * Sets the color of the hint text.
3497     *
3498     * @see #getHintTextColors()
3499     * @see #setHintTextColor(int)
3500     * @see #setTextColor(ColorStateList)
3501     * @see #setLinkTextColor(ColorStateList)
3502     *
3503     * @attr ref android.R.styleable#TextView_textColorHint
3504     */
3505    public final void setHintTextColor(ColorStateList colors) {
3506        mHintTextColor = colors;
3507        updateTextColors();
3508    }
3509
3510    /**
3511     * @return the color of the hint text, for the different states of this TextView.
3512     *
3513     * @see #setHintTextColor(ColorStateList)
3514     * @see #setHintTextColor(int)
3515     * @see #setTextColor(ColorStateList)
3516     * @see #setLinkTextColor(ColorStateList)
3517     *
3518     * @attr ref android.R.styleable#TextView_textColorHint
3519     */
3520    public final ColorStateList getHintTextColors() {
3521        return mHintTextColor;
3522    }
3523
3524    /**
3525     * <p>Return the current color selected to paint the hint text.</p>
3526     *
3527     * @return Returns the current hint text color.
3528     */
3529    @ColorInt
3530    public final int getCurrentHintTextColor() {
3531        return mHintTextColor != null ? mCurHintTextColor : mCurTextColor;
3532    }
3533
3534    /**
3535     * Sets the color of links in the text.
3536     *
3537     * @see #setLinkTextColor(ColorStateList)
3538     * @see #getLinkTextColors()
3539     *
3540     * @attr ref android.R.styleable#TextView_textColorLink
3541     */
3542    @android.view.RemotableViewMethod
3543    public final void setLinkTextColor(@ColorInt int color) {
3544        mLinkTextColor = ColorStateList.valueOf(color);
3545        updateTextColors();
3546    }
3547
3548    /**
3549     * Sets the color of links in the text.
3550     *
3551     * @see #setLinkTextColor(int)
3552     * @see #getLinkTextColors()
3553     * @see #setTextColor(ColorStateList)
3554     * @see #setHintTextColor(ColorStateList)
3555     *
3556     * @attr ref android.R.styleable#TextView_textColorLink
3557     */
3558    public final void setLinkTextColor(ColorStateList colors) {
3559        mLinkTextColor = colors;
3560        updateTextColors();
3561    }
3562
3563    /**
3564     * @return the list of colors used to paint the links in the text, for the different states of
3565     * this TextView
3566     *
3567     * @see #setLinkTextColor(ColorStateList)
3568     * @see #setLinkTextColor(int)
3569     *
3570     * @attr ref android.R.styleable#TextView_textColorLink
3571     */
3572    public final ColorStateList getLinkTextColors() {
3573        return mLinkTextColor;
3574    }
3575
3576    /**
3577     * Sets the horizontal alignment of the text and the
3578     * vertical gravity that will be used when there is extra space
3579     * in the TextView beyond what is required for the text itself.
3580     *
3581     * @see android.view.Gravity
3582     * @attr ref android.R.styleable#TextView_gravity
3583     */
3584    public void setGravity(int gravity) {
3585        if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
3586            gravity |= Gravity.START;
3587        }
3588        if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
3589            gravity |= Gravity.TOP;
3590        }
3591
3592        boolean newLayout = false;
3593
3594        if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK)
3595                != (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK)) {
3596            newLayout = true;
3597        }
3598
3599        if (gravity != mGravity) {
3600            invalidate();
3601        }
3602
3603        mGravity = gravity;
3604
3605        if (mLayout != null && newLayout) {
3606            // XXX this is heavy-handed because no actual content changes.
3607            int want = mLayout.getWidth();
3608            int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();
3609
3610            makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
3611                    mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), true);
3612        }
3613    }
3614
3615    /**
3616     * Returns the horizontal and vertical alignment of this TextView.
3617     *
3618     * @see android.view.Gravity
3619     * @attr ref android.R.styleable#TextView_gravity
3620     */
3621    public int getGravity() {
3622        return mGravity;
3623    }
3624
3625    /**
3626     * @return the flags on the Paint being used to display the text.
3627     * @see Paint#getFlags
3628     */
3629    public int getPaintFlags() {
3630        return mTextPaint.getFlags();
3631    }
3632
3633    /**
3634     * Sets flags on the Paint being used to display the text and
3635     * reflows the text if they are different from the old flags.
3636     * @see Paint#setFlags
3637     */
3638    @android.view.RemotableViewMethod
3639    public void setPaintFlags(int flags) {
3640        if (mTextPaint.getFlags() != flags) {
3641            mTextPaint.setFlags(flags);
3642
3643            if (mLayout != null) {
3644                nullLayouts();
3645                requestLayout();
3646                invalidate();
3647            }
3648        }
3649    }
3650
3651    /**
3652     * Sets whether the text should be allowed to be wider than the
3653     * View is.  If false, it will be wrapped to the width of the View.
3654     *
3655     * @attr ref android.R.styleable#TextView_scrollHorizontally
3656     */
3657    public void setHorizontallyScrolling(boolean whether) {
3658        if (mHorizontallyScrolling != whether) {
3659            mHorizontallyScrolling = whether;
3660
3661            if (mLayout != null) {
3662                nullLayouts();
3663                requestLayout();
3664                invalidate();
3665            }
3666        }
3667    }
3668
3669    /**
3670     * Returns whether the text is allowed to be wider than the View is.
3671     * If false, the text will be wrapped to the width of the View.
3672     *
3673     * @attr ref android.R.styleable#TextView_scrollHorizontally
3674     * @hide
3675     */
3676    public boolean getHorizontallyScrolling() {
3677        return mHorizontallyScrolling;
3678    }
3679
3680    /**
3681     * Makes the TextView at least this many lines tall.
3682     *
3683     * Setting this value overrides any other (minimum) height setting. A single line TextView will
3684     * set this value to 1.
3685     *
3686     * @see #getMinLines()
3687     *
3688     * @attr ref android.R.styleable#TextView_minLines
3689     */
3690    @android.view.RemotableViewMethod
3691    public void setMinLines(int minlines) {
3692        mMinimum = minlines;
3693        mMinMode = LINES;
3694
3695        requestLayout();
3696        invalidate();
3697    }
3698
3699    /**
3700     * @return the minimum number of lines displayed in this TextView, or -1 if the minimum
3701     * height was set in pixels instead using {@link #setMinHeight(int) or #setHeight(int)}.
3702     *
3703     * @see #setMinLines(int)
3704     *
3705     * @attr ref android.R.styleable#TextView_minLines
3706     */
3707    public int getMinLines() {
3708        return mMinMode == LINES ? mMinimum : -1;
3709    }
3710
3711    /**
3712     * Makes the TextView at least this many pixels tall.
3713     *
3714     * Setting this value overrides any other (minimum) number of lines setting.
3715     *
3716     * @attr ref android.R.styleable#TextView_minHeight
3717     */
3718    @android.view.RemotableViewMethod
3719    public void setMinHeight(int minHeight) {
3720        mMinimum = minHeight;
3721        mMinMode = PIXELS;
3722
3723        requestLayout();
3724        invalidate();
3725    }
3726
3727    /**
3728     * @return the minimum height of this TextView expressed in pixels, or -1 if the minimum
3729     * height was set in number of lines instead using {@link #setMinLines(int) or #setLines(int)}.
3730     *
3731     * @see #setMinHeight(int)
3732     *
3733     * @attr ref android.R.styleable#TextView_minHeight
3734     */
3735    public int getMinHeight() {
3736        return mMinMode == PIXELS ? mMinimum : -1;
3737    }
3738
3739    /**
3740     * Makes the TextView at most this many lines tall.
3741     *
3742     * Setting this value overrides any other (maximum) height setting.
3743     *
3744     * @attr ref android.R.styleable#TextView_maxLines
3745     */
3746    @android.view.RemotableViewMethod
3747    public void setMaxLines(int maxlines) {
3748        mMaximum = maxlines;
3749        mMaxMode = LINES;
3750
3751        requestLayout();
3752        invalidate();
3753    }
3754
3755    /**
3756     * @return the maximum number of lines displayed in this TextView, or -1 if the maximum
3757     * height was set in pixels instead using {@link #setMaxHeight(int) or #setHeight(int)}.
3758     *
3759     * @see #setMaxLines(int)
3760     *
3761     * @attr ref android.R.styleable#TextView_maxLines
3762     */
3763    public int getMaxLines() {
3764        return mMaxMode == LINES ? mMaximum : -1;
3765    }
3766
3767    /**
3768     * Makes the TextView at most this many pixels tall.  This option is mutually exclusive with the
3769     * {@link #setMaxLines(int)} method.
3770     *
3771     * Setting this value overrides any other (maximum) number of lines setting.
3772     *
3773     * @attr ref android.R.styleable#TextView_maxHeight
3774     */
3775    @android.view.RemotableViewMethod
3776    public void setMaxHeight(int maxHeight) {
3777        mMaximum = maxHeight;
3778        mMaxMode = PIXELS;
3779
3780        requestLayout();
3781        invalidate();
3782    }
3783
3784    /**
3785     * @return the maximum height of this TextView expressed in pixels, or -1 if the maximum
3786     * height was set in number of lines instead using {@link #setMaxLines(int) or #setLines(int)}.
3787     *
3788     * @see #setMaxHeight(int)
3789     *
3790     * @attr ref android.R.styleable#TextView_maxHeight
3791     */
3792    public int getMaxHeight() {
3793        return mMaxMode == PIXELS ? mMaximum : -1;
3794    }
3795
3796    /**
3797     * Makes the TextView exactly this many lines tall.
3798     *
3799     * Note that setting this value overrides any other (minimum / maximum) number of lines or
3800     * height setting. A single line TextView will set this value to 1.
3801     *
3802     * @attr ref android.R.styleable#TextView_lines
3803     */
3804    @android.view.RemotableViewMethod
3805    public void setLines(int lines) {
3806        mMaximum = mMinimum = lines;
3807        mMaxMode = mMinMode = LINES;
3808
3809        requestLayout();
3810        invalidate();
3811    }
3812
3813    /**
3814     * Makes the TextView exactly this many pixels tall.
3815     * You could do the same thing by specifying this number in the
3816     * LayoutParams.
3817     *
3818     * Note that setting this value overrides any other (minimum / maximum) number of lines or
3819     * height setting.
3820     *
3821     * @attr ref android.R.styleable#TextView_height
3822     */
3823    @android.view.RemotableViewMethod
3824    public void setHeight(int pixels) {
3825        mMaximum = mMinimum = pixels;
3826        mMaxMode = mMinMode = PIXELS;
3827
3828        requestLayout();
3829        invalidate();
3830    }
3831
3832    /**
3833     * Makes the TextView at least this many ems wide
3834     *
3835     * @attr ref android.R.styleable#TextView_minEms
3836     */
3837    @android.view.RemotableViewMethod
3838    public void setMinEms(int minems) {
3839        mMinWidth = minems;
3840        mMinWidthMode = EMS;
3841
3842        requestLayout();
3843        invalidate();
3844    }
3845
3846    /**
3847     * @return the minimum width of the TextView, expressed in ems or -1 if the minimum width
3848     * was set in pixels instead (using {@link #setMinWidth(int)} or {@link #setWidth(int)}).
3849     *
3850     * @see #setMinEms(int)
3851     * @see #setEms(int)
3852     *
3853     * @attr ref android.R.styleable#TextView_minEms
3854     */
3855    public int getMinEms() {
3856        return mMinWidthMode == EMS ? mMinWidth : -1;
3857    }
3858
3859    /**
3860     * Makes the TextView at least this many pixels wide
3861     *
3862     * @attr ref android.R.styleable#TextView_minWidth
3863     */
3864    @android.view.RemotableViewMethod
3865    public void setMinWidth(int minpixels) {
3866        mMinWidth = minpixels;
3867        mMinWidthMode = PIXELS;
3868
3869        requestLayout();
3870        invalidate();
3871    }
3872
3873    /**
3874     * @return the minimum width of the TextView, in pixels or -1 if the minimum width
3875     * was set in ems instead (using {@link #setMinEms(int)} or {@link #setEms(int)}).
3876     *
3877     * @see #setMinWidth(int)
3878     * @see #setWidth(int)
3879     *
3880     * @attr ref android.R.styleable#TextView_minWidth
3881     */
3882    public int getMinWidth() {
3883        return mMinWidthMode == PIXELS ? mMinWidth : -1;
3884    }
3885
3886    /**
3887     * Makes the TextView at most this many ems wide
3888     *
3889     * @attr ref android.R.styleable#TextView_maxEms
3890     */
3891    @android.view.RemotableViewMethod
3892    public void setMaxEms(int maxems) {
3893        mMaxWidth = maxems;
3894        mMaxWidthMode = EMS;
3895
3896        requestLayout();
3897        invalidate();
3898    }
3899
3900    /**
3901     * @return the maximum width of the TextView, expressed in ems or -1 if the maximum width
3902     * was set in pixels instead (using {@link #setMaxWidth(int)} or {@link #setWidth(int)}).
3903     *
3904     * @see #setMaxEms(int)
3905     * @see #setEms(int)
3906     *
3907     * @attr ref android.R.styleable#TextView_maxEms
3908     */
3909    public int getMaxEms() {
3910        return mMaxWidthMode == EMS ? mMaxWidth : -1;
3911    }
3912
3913    /**
3914     * Makes the TextView at most this many pixels wide
3915     *
3916     * @attr ref android.R.styleable#TextView_maxWidth
3917     */
3918    @android.view.RemotableViewMethod
3919    public void setMaxWidth(int maxpixels) {
3920        mMaxWidth = maxpixels;
3921        mMaxWidthMode = PIXELS;
3922
3923        requestLayout();
3924        invalidate();
3925    }
3926
3927    /**
3928     * @return the maximum width of the TextView, in pixels or -1 if the maximum width
3929     * was set in ems instead (using {@link #setMaxEms(int)} or {@link #setEms(int)}).
3930     *
3931     * @see #setMaxWidth(int)
3932     * @see #setWidth(int)
3933     *
3934     * @attr ref android.R.styleable#TextView_maxWidth
3935     */
3936    public int getMaxWidth() {
3937        return mMaxWidthMode == PIXELS ? mMaxWidth : -1;
3938    }
3939
3940    /**
3941     * Makes the TextView exactly this many ems wide
3942     *
3943     * @see #setMaxEms(int)
3944     * @see #setMinEms(int)
3945     * @see #getMinEms()
3946     * @see #getMaxEms()
3947     *
3948     * @attr ref android.R.styleable#TextView_ems
3949     */
3950    @android.view.RemotableViewMethod
3951    public void setEms(int ems) {
3952        mMaxWidth = mMinWidth = ems;
3953        mMaxWidthMode = mMinWidthMode = EMS;
3954
3955        requestLayout();
3956        invalidate();
3957    }
3958
3959    /**
3960     * Makes the TextView exactly this many pixels wide.
3961     * You could do the same thing by specifying this number in the
3962     * LayoutParams.
3963     *
3964     * @see #setMaxWidth(int)
3965     * @see #setMinWidth(int)
3966     * @see #getMinWidth()
3967     * @see #getMaxWidth()
3968     *
3969     * @attr ref android.R.styleable#TextView_width
3970     */
3971    @android.view.RemotableViewMethod
3972    public void setWidth(int pixels) {
3973        mMaxWidth = mMinWidth = pixels;
3974        mMaxWidthMode = mMinWidthMode = PIXELS;
3975
3976        requestLayout();
3977        invalidate();
3978    }
3979
3980    /**
3981     * Sets line spacing for this TextView.  Each line will have its height
3982     * multiplied by <code>mult</code> and have <code>add</code> added to it.
3983     *
3984     * @attr ref android.R.styleable#TextView_lineSpacingExtra
3985     * @attr ref android.R.styleable#TextView_lineSpacingMultiplier
3986     */
3987    public void setLineSpacing(float add, float mult) {
3988        if (mSpacingAdd != add || mSpacingMult != mult) {
3989            mSpacingAdd = add;
3990            mSpacingMult = mult;
3991
3992            if (mLayout != null) {
3993                nullLayouts();
3994                requestLayout();
3995                invalidate();
3996            }
3997        }
3998    }
3999
4000    /**
4001     * Gets the line spacing multiplier
4002     *
4003     * @return the value by which each line's height is multiplied to get its actual height.
4004     *
4005     * @see #setLineSpacing(float, float)
4006     * @see #getLineSpacingExtra()
4007     *
4008     * @attr ref android.R.styleable#TextView_lineSpacingMultiplier
4009     */
4010    public float getLineSpacingMultiplier() {
4011        return mSpacingMult;
4012    }
4013
4014    /**
4015     * Gets the line spacing extra space
4016     *
4017     * @return the extra space that is added to the height of each lines of this TextView.
4018     *
4019     * @see #setLineSpacing(float, float)
4020     * @see #getLineSpacingMultiplier()
4021     *
4022     * @attr ref android.R.styleable#TextView_lineSpacingExtra
4023     */
4024    public float getLineSpacingExtra() {
4025        return mSpacingAdd;
4026    }
4027
4028    /**
4029     * Convenience method: Append the specified text to the TextView's
4030     * display buffer, upgrading it to BufferType.EDITABLE if it was
4031     * not already editable.
4032     */
4033    public final void append(CharSequence text) {
4034        append(text, 0, text.length());
4035    }
4036
4037    /**
4038     * Convenience method: Append the specified text slice to the TextView's
4039     * display buffer, upgrading it to BufferType.EDITABLE if it was
4040     * not already editable.
4041     */
4042    public void append(CharSequence text, int start, int end) {
4043        if (!(mText instanceof Editable)) {
4044            setText(mText, BufferType.EDITABLE);
4045        }
4046
4047        ((Editable) mText).append(text, start, end);
4048
4049        if (mAutoLinkMask != 0) {
4050            boolean linksWereAdded = Linkify.addLinks((Spannable) mText, mAutoLinkMask);
4051            // Do not change the movement method for text that support text selection as it
4052            // would prevent an arbitrary cursor displacement.
4053            if (linksWereAdded && mLinksClickable && !textCanBeSelected()) {
4054                setMovementMethod(LinkMovementMethod.getInstance());
4055            }
4056        }
4057    }
4058
4059    private void updateTextColors() {
4060        boolean inval = false;
4061        int color = mTextColor.getColorForState(getDrawableState(), 0);
4062        if (color != mCurTextColor) {
4063            mCurTextColor = color;
4064            inval = true;
4065        }
4066        if (mLinkTextColor != null) {
4067            color = mLinkTextColor.getColorForState(getDrawableState(), 0);
4068            if (color != mTextPaint.linkColor) {
4069                mTextPaint.linkColor = color;
4070                inval = true;
4071            }
4072        }
4073        if (mHintTextColor != null) {
4074            color = mHintTextColor.getColorForState(getDrawableState(), 0);
4075            if (color != mCurHintTextColor) {
4076                mCurHintTextColor = color;
4077                if (mText.length() == 0) {
4078                    inval = true;
4079                }
4080            }
4081        }
4082        if (inval) {
4083            // Text needs to be redrawn with the new color
4084            if (mEditor != null) mEditor.invalidateTextDisplayList();
4085            invalidate();
4086        }
4087    }
4088
4089    @Override
4090    protected void drawableStateChanged() {
4091        super.drawableStateChanged();
4092
4093        if (mTextColor != null && mTextColor.isStateful()
4094                || (mHintTextColor != null && mHintTextColor.isStateful())
4095                || (mLinkTextColor != null && mLinkTextColor.isStateful())) {
4096            updateTextColors();
4097        }
4098
4099        if (mDrawables != null) {
4100            final int[] state = getDrawableState();
4101            for (Drawable dr : mDrawables.mShowing) {
4102                if (dr != null && dr.isStateful() && dr.setState(state)) {
4103                    invalidateDrawable(dr);
4104                }
4105            }
4106        }
4107    }
4108
4109    @Override
4110    public void drawableHotspotChanged(float x, float y) {
4111        super.drawableHotspotChanged(x, y);
4112
4113        if (mDrawables != null) {
4114            for (Drawable dr : mDrawables.mShowing) {
4115                if (dr != null) {
4116                    dr.setHotspot(x, y);
4117                }
4118            }
4119        }
4120    }
4121
4122    @Override
4123    public Parcelable onSaveInstanceState() {
4124        Parcelable superState = super.onSaveInstanceState();
4125
4126        // Save state if we are forced to
4127        final boolean freezesText = getFreezesText();
4128        boolean hasSelection = false;
4129        int start = -1;
4130        int end = -1;
4131
4132        if (mText != null) {
4133            start = getSelectionStart();
4134            end = getSelectionEnd();
4135            if (start >= 0 || end >= 0) {
4136                // Or save state if there is a selection
4137                hasSelection = true;
4138            }
4139        }
4140
4141        if (freezesText || hasSelection) {
4142            SavedState ss = new SavedState(superState);
4143
4144            if (freezesText) {
4145                if (mText instanceof Spanned) {
4146                    final Spannable sp = new SpannableStringBuilder(mText);
4147
4148                    if (mEditor != null) {
4149                        removeMisspelledSpans(sp);
4150                        sp.removeSpan(mEditor.mSuggestionRangeSpan);
4151                    }
4152
4153                    ss.text = sp;
4154                } else {
4155                    ss.text = mText.toString();
4156                }
4157            }
4158
4159            if (hasSelection) {
4160                // XXX Should also save the current scroll position!
4161                ss.selStart = start;
4162                ss.selEnd = end;
4163            }
4164
4165            if (isFocused() && start >= 0 && end >= 0) {
4166                ss.frozenWithFocus = true;
4167            }
4168
4169            ss.error = getError();
4170
4171            if (mEditor != null) {
4172                ss.editorState = mEditor.saveInstanceState();
4173            }
4174            return ss;
4175        }
4176
4177        return superState;
4178    }
4179
4180    void removeMisspelledSpans(Spannable spannable) {
4181        SuggestionSpan[] suggestionSpans = spannable.getSpans(0, spannable.length(),
4182                SuggestionSpan.class);
4183        for (int i = 0; i < suggestionSpans.length; i++) {
4184            int flags = suggestionSpans[i].getFlags();
4185            if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0
4186                    && (flags & SuggestionSpan.FLAG_MISSPELLED) != 0) {
4187                spannable.removeSpan(suggestionSpans[i]);
4188            }
4189        }
4190    }
4191
4192    @Override
4193    public void onRestoreInstanceState(Parcelable state) {
4194        if (!(state instanceof SavedState)) {
4195            super.onRestoreInstanceState(state);
4196            return;
4197        }
4198
4199        SavedState ss = (SavedState) state;
4200        super.onRestoreInstanceState(ss.getSuperState());
4201
4202        // XXX restore buffer type too, as well as lots of other stuff
4203        if (ss.text != null) {
4204            setText(ss.text);
4205        }
4206
4207        if (ss.selStart >= 0 && ss.selEnd >= 0) {
4208            if (mText instanceof Spannable) {
4209                int len = mText.length();
4210
4211                if (ss.selStart > len || ss.selEnd > len) {
4212                    String restored = "";
4213
4214                    if (ss.text != null) {
4215                        restored = "(restored) ";
4216                    }
4217
4218                    Log.e(LOG_TAG, "Saved cursor position " + ss.selStart + "/" + ss.selEnd
4219                            + " out of range for " + restored + "text " + mText);
4220                } else {
4221                    Selection.setSelection((Spannable) mText, ss.selStart, ss.selEnd);
4222
4223                    if (ss.frozenWithFocus) {
4224                        createEditorIfNeeded();
4225                        mEditor.mFrozenWithFocus = true;
4226                    }
4227                }
4228            }
4229        }
4230
4231        if (ss.error != null) {
4232            final CharSequence error = ss.error;
4233            // Display the error later, after the first layout pass
4234            post(new Runnable() {
4235                public void run() {
4236                    if (mEditor == null || !mEditor.mErrorWasChanged) {
4237                        setError(error);
4238                    }
4239                }
4240            });
4241        }
4242
4243        if (ss.editorState != null) {
4244            createEditorIfNeeded();
4245            mEditor.restoreInstanceState(ss.editorState);
4246        }
4247    }
4248
4249    /**
4250     * Control whether this text view saves its entire text contents when
4251     * freezing to an icicle, in addition to dynamic state such as cursor
4252     * position.  By default this is false, not saving the text.  Set to true
4253     * if the text in the text view is not being saved somewhere else in
4254     * persistent storage (such as in a content provider) so that if the
4255     * view is later thawed the user will not lose their data. For
4256     * {@link android.widget.EditText} it is always enabled, regardless of
4257     * the value of the attribute.
4258     *
4259     * @param freezesText Controls whether a frozen icicle should include the
4260     * entire text data: true to include it, false to not.
4261     *
4262     * @attr ref android.R.styleable#TextView_freezesText
4263     */
4264    @android.view.RemotableViewMethod
4265    public void setFreezesText(boolean freezesText) {
4266        mFreezesText = freezesText;
4267    }
4268
4269    /**
4270     * Return whether this text view is including its entire text contents
4271     * in frozen icicles. For {@link android.widget.EditText} it always returns true.
4272     *
4273     * @return Returns true if text is included, false if it isn't.
4274     *
4275     * @see #setFreezesText
4276     */
4277    public boolean getFreezesText() {
4278        return mFreezesText;
4279    }
4280
4281    ///////////////////////////////////////////////////////////////////////////
4282
4283    /**
4284     * Sets the Factory used to create new Editables.
4285     */
4286    public final void setEditableFactory(Editable.Factory factory) {
4287        mEditableFactory = factory;
4288        setText(mText);
4289    }
4290
4291    /**
4292     * Sets the Factory used to create new Spannables.
4293     */
4294    public final void setSpannableFactory(Spannable.Factory factory) {
4295        mSpannableFactory = factory;
4296        setText(mText);
4297    }
4298
4299    /**
4300     * Sets the string value of the TextView. TextView <em>does not</em> accept
4301     * HTML-like formatting, which you can do with text strings in XML resource files.
4302     * To style your strings, attach android.text.style.* objects to a
4303     * {@link android.text.SpannableString SpannableString}, or see the
4304     * <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources">
4305     * Available Resource Types</a> documentation for an example of setting
4306     * formatted text in the XML resource file.
4307     *
4308     * @attr ref android.R.styleable#TextView_text
4309     */
4310    @android.view.RemotableViewMethod
4311    public final void setText(CharSequence text) {
4312        setText(text, mBufferType);
4313    }
4314
4315    /**
4316     * Like {@link #setText(CharSequence)},
4317     * except that the cursor position (if any) is retained in the new text.
4318     *
4319     * @param text The new text to place in the text view.
4320     *
4321     * @see #setText(CharSequence)
4322     */
4323    @android.view.RemotableViewMethod
4324    public final void setTextKeepState(CharSequence text) {
4325        setTextKeepState(text, mBufferType);
4326    }
4327
4328    /**
4329     * Sets the text that this TextView is to display (see
4330     * {@link #setText(CharSequence)}) and also sets whether it is stored
4331     * in a styleable/spannable buffer and whether it is editable.
4332     *
4333     * @attr ref android.R.styleable#TextView_text
4334     * @attr ref android.R.styleable#TextView_bufferType
4335     */
4336    public void setText(CharSequence text, BufferType type) {
4337        setText(text, type, true, 0);
4338
4339        if (mCharWrapper != null) {
4340            mCharWrapper.mChars = null;
4341        }
4342    }
4343
4344    private void setText(CharSequence text, BufferType type,
4345                         boolean notifyBefore, int oldlen) {
4346        if (text == null) {
4347            text = "";
4348        }
4349
4350        // If suggestions are not enabled, remove the suggestion spans from the text
4351        if (!isSuggestionsEnabled()) {
4352            text = removeSuggestionSpans(text);
4353        }
4354
4355        if (!mUserSetTextScaleX) mTextPaint.setTextScaleX(1.0f);
4356
4357        if (text instanceof Spanned
4358                && ((Spanned) text).getSpanStart(TextUtils.TruncateAt.MARQUEE) >= 0) {
4359            if (ViewConfiguration.get(mContext).isFadingMarqueeEnabled()) {
4360                setHorizontalFadingEdgeEnabled(true);
4361                mMarqueeFadeMode = MARQUEE_FADE_NORMAL;
4362            } else {
4363                setHorizontalFadingEdgeEnabled(false);
4364                mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS;
4365            }
4366            setEllipsize(TextUtils.TruncateAt.MARQUEE);
4367        }
4368
4369        int n = mFilters.length;
4370        for (int i = 0; i < n; i++) {
4371            CharSequence out = mFilters[i].filter(text, 0, text.length(), EMPTY_SPANNED, 0, 0);
4372            if (out != null) {
4373                text = out;
4374            }
4375        }
4376
4377        if (notifyBefore) {
4378            if (mText != null) {
4379                oldlen = mText.length();
4380                sendBeforeTextChanged(mText, 0, oldlen, text.length());
4381            } else {
4382                sendBeforeTextChanged("", 0, 0, text.length());
4383            }
4384        }
4385
4386        boolean needEditableForNotification = false;
4387
4388        if (mListeners != null && mListeners.size() != 0) {
4389            needEditableForNotification = true;
4390        }
4391
4392        if (type == BufferType.EDITABLE || getKeyListener() != null
4393                || needEditableForNotification) {
4394            createEditorIfNeeded();
4395            mEditor.forgetUndoRedo();
4396            Editable t = mEditableFactory.newEditable(text);
4397            text = t;
4398            setFilters(t, mFilters);
4399            InputMethodManager imm = InputMethodManager.peekInstance();
4400            if (imm != null) imm.restartInput(this);
4401        } else if (type == BufferType.SPANNABLE || mMovement != null) {
4402            text = mSpannableFactory.newSpannable(text);
4403        } else if (!(text instanceof CharWrapper)) {
4404            text = TextUtils.stringOrSpannedString(text);
4405        }
4406
4407        if (mAutoLinkMask != 0) {
4408            Spannable s2;
4409
4410            if (type == BufferType.EDITABLE || text instanceof Spannable) {
4411                s2 = (Spannable) text;
4412            } else {
4413                s2 = mSpannableFactory.newSpannable(text);
4414            }
4415
4416            if (Linkify.addLinks(s2, mAutoLinkMask)) {
4417                text = s2;
4418                type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE;
4419
4420                /*
4421                 * We must go ahead and set the text before changing the
4422                 * movement method, because setMovementMethod() may call
4423                 * setText() again to try to upgrade the buffer type.
4424                 */
4425                mText = text;
4426
4427                // Do not change the movement method for text that support text selection as it
4428                // would prevent an arbitrary cursor displacement.
4429                if (mLinksClickable && !textCanBeSelected()) {
4430                    setMovementMethod(LinkMovementMethod.getInstance());
4431                }
4432            }
4433        }
4434
4435        mBufferType = type;
4436        mText = text;
4437
4438        if (mTransformation == null) {
4439            mTransformed = text;
4440        } else {
4441            mTransformed = mTransformation.getTransformation(text, this);
4442        }
4443
4444        final int textLength = text.length();
4445
4446        if (text instanceof Spannable && !mAllowTransformationLengthChange) {
4447            Spannable sp = (Spannable) text;
4448
4449            // Remove any ChangeWatchers that might have come from other TextViews.
4450            final ChangeWatcher[] watchers = sp.getSpans(0, sp.length(), ChangeWatcher.class);
4451            final int count = watchers.length;
4452            for (int i = 0; i < count; i++) {
4453                sp.removeSpan(watchers[i]);
4454            }
4455
4456            if (mChangeWatcher == null) mChangeWatcher = new ChangeWatcher();
4457
4458            sp.setSpan(mChangeWatcher, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE
4459                    | (CHANGE_WATCHER_PRIORITY << Spanned.SPAN_PRIORITY_SHIFT));
4460
4461            if (mEditor != null) mEditor.addSpanWatchers(sp);
4462
4463            if (mTransformation != null) {
4464                sp.setSpan(mTransformation, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4465            }
4466
4467            if (mMovement != null) {
4468                mMovement.initialize(this, (Spannable) text);
4469
4470                /*
4471                 * Initializing the movement method will have set the
4472                 * selection, so reset mSelectionMoved to keep that from
4473                 * interfering with the normal on-focus selection-setting.
4474                 */
4475                if (mEditor != null) mEditor.mSelectionMoved = false;
4476            }
4477        }
4478
4479        if (mLayout != null) {
4480            checkForRelayout();
4481        }
4482
4483        sendOnTextChanged(text, 0, oldlen, textLength);
4484        onTextChanged(text, 0, oldlen, textLength);
4485
4486        notifyViewAccessibilityStateChangedIfNeeded(AccessibilityEvent.CONTENT_CHANGE_TYPE_TEXT);
4487
4488        if (needEditableForNotification) {
4489            sendAfterTextChanged((Editable) text);
4490        }
4491
4492        // SelectionModifierCursorController depends on textCanBeSelected, which depends on text
4493        if (mEditor != null) mEditor.prepareCursorControllers();
4494    }
4495
4496    /**
4497     * Sets the TextView to display the specified slice of the specified
4498     * char array.  You must promise that you will not change the contents
4499     * of the array except for right before another call to setText(),
4500     * since the TextView has no way to know that the text
4501     * has changed and that it needs to invalidate and re-layout.
4502     */
4503    public final void setText(char[] text, int start, int len) {
4504        int oldlen = 0;
4505
4506        if (start < 0 || len < 0 || start + len > text.length) {
4507            throw new IndexOutOfBoundsException(start + ", " + len);
4508        }
4509
4510        /*
4511         * We must do the before-notification here ourselves because if
4512         * the old text is a CharWrapper we destroy it before calling
4513         * into the normal path.
4514         */
4515        if (mText != null) {
4516            oldlen = mText.length();
4517            sendBeforeTextChanged(mText, 0, oldlen, len);
4518        } else {
4519            sendBeforeTextChanged("", 0, 0, len);
4520        }
4521
4522        if (mCharWrapper == null) {
4523            mCharWrapper = new CharWrapper(text, start, len);
4524        } else {
4525            mCharWrapper.set(text, start, len);
4526        }
4527
4528        setText(mCharWrapper, mBufferType, false, oldlen);
4529    }
4530
4531    /**
4532     * Like {@link #setText(CharSequence, android.widget.TextView.BufferType)},
4533     * except that the cursor position (if any) is retained in the new text.
4534     *
4535     * @see #setText(CharSequence, android.widget.TextView.BufferType)
4536     */
4537    public final void setTextKeepState(CharSequence text, BufferType type) {
4538        int start = getSelectionStart();
4539        int end = getSelectionEnd();
4540        int len = text.length();
4541
4542        setText(text, type);
4543
4544        if (start >= 0 || end >= 0) {
4545            if (mText instanceof Spannable) {
4546                Selection.setSelection((Spannable) mText,
4547                                       Math.max(0, Math.min(start, len)),
4548                                       Math.max(0, Math.min(end, len)));
4549            }
4550        }
4551    }
4552
4553    @android.view.RemotableViewMethod
4554    public final void setText(@StringRes int resid) {
4555        setText(getContext().getResources().getText(resid));
4556    }
4557
4558    public final void setText(@StringRes int resid, BufferType type) {
4559        setText(getContext().getResources().getText(resid), type);
4560    }
4561
4562    /**
4563     * Sets the text to be displayed when the text of the TextView is empty.
4564     * Null means to use the normal empty text. The hint does not currently
4565     * participate in determining the size of the view.
4566     *
4567     * @attr ref android.R.styleable#TextView_hint
4568     */
4569    @android.view.RemotableViewMethod
4570    public final void setHint(CharSequence hint) {
4571        mHint = TextUtils.stringOrSpannedString(hint);
4572
4573        if (mLayout != null) {
4574            checkForRelayout();
4575        }
4576
4577        if (mText.length() == 0) {
4578            invalidate();
4579        }
4580
4581        // Invalidate display list if hint is currently used
4582        if (mEditor != null && mText.length() == 0 && mHint != null) {
4583            mEditor.invalidateTextDisplayList();
4584        }
4585    }
4586
4587    /**
4588     * Sets the text to be displayed when the text of the TextView is empty,
4589     * from a resource.
4590     *
4591     * @attr ref android.R.styleable#TextView_hint
4592     */
4593    @android.view.RemotableViewMethod
4594    public final void setHint(@StringRes int resid) {
4595        setHint(getContext().getResources().getText(resid));
4596    }
4597
4598    /**
4599     * Returns the hint that is displayed when the text of the TextView
4600     * is empty.
4601     *
4602     * @attr ref android.R.styleable#TextView_hint
4603     */
4604    @ViewDebug.CapturedViewProperty
4605    public CharSequence getHint() {
4606        return mHint;
4607    }
4608
4609    boolean isSingleLine() {
4610        return mSingleLine;
4611    }
4612
4613    private static boolean isMultilineInputType(int type) {
4614        return (type & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE))
4615                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
4616    }
4617
4618    /**
4619     * Removes the suggestion spans.
4620     */
4621    CharSequence removeSuggestionSpans(CharSequence text) {
4622        if (text instanceof Spanned) {
4623            Spannable spannable;
4624            if (text instanceof Spannable) {
4625                spannable = (Spannable) text;
4626            } else {
4627                spannable = new SpannableString(text);
4628                text = spannable;
4629            }
4630
4631            SuggestionSpan[] spans = spannable.getSpans(0, text.length(), SuggestionSpan.class);
4632            for (int i = 0; i < spans.length; i++) {
4633                spannable.removeSpan(spans[i]);
4634            }
4635        }
4636        return text;
4637    }
4638
4639    /**
4640     * Set the type of the content with a constant as defined for {@link EditorInfo#inputType}. This
4641     * will take care of changing the key listener, by calling {@link #setKeyListener(KeyListener)},
4642     * to match the given content type.  If the given content type is {@link EditorInfo#TYPE_NULL}
4643     * then a soft keyboard will not be displayed for this text view.
4644     *
4645     * Note that the maximum number of displayed lines (see {@link #setMaxLines(int)}) will be
4646     * modified if you change the {@link EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE} flag of the input
4647     * type.
4648     *
4649     * @see #getInputType()
4650     * @see #setRawInputType(int)
4651     * @see android.text.InputType
4652     * @attr ref android.R.styleable#TextView_inputType
4653     */
4654    public void setInputType(int type) {
4655        final boolean wasPassword = isPasswordInputType(getInputType());
4656        final boolean wasVisiblePassword = isVisiblePasswordInputType(getInputType());
4657        setInputType(type, false);
4658        final boolean isPassword = isPasswordInputType(type);
4659        final boolean isVisiblePassword = isVisiblePasswordInputType(type);
4660        boolean forceUpdate = false;
4661        if (isPassword) {
4662            setTransformationMethod(PasswordTransformationMethod.getInstance());
4663            setTypefaceFromAttrs(null /* fontFamily */, MONOSPACE, 0);
4664        } else if (isVisiblePassword) {
4665            if (mTransformation == PasswordTransformationMethod.getInstance()) {
4666                forceUpdate = true;
4667            }
4668            setTypefaceFromAttrs(null /* fontFamily */, MONOSPACE, 0);
4669        } else if (wasPassword || wasVisiblePassword) {
4670            // not in password mode, clean up typeface and transformation
4671            setTypefaceFromAttrs(null /* fontFamily */, -1, -1);
4672            if (mTransformation == PasswordTransformationMethod.getInstance()) {
4673                forceUpdate = true;
4674            }
4675        }
4676
4677        boolean singleLine = !isMultilineInputType(type);
4678
4679        // We need to update the single line mode if it has changed or we
4680        // were previously in password mode.
4681        if (mSingleLine != singleLine || forceUpdate) {
4682            // Change single line mode, but only change the transformation if
4683            // we are not in password mode.
4684            applySingleLine(singleLine, !isPassword, true);
4685        }
4686
4687        if (!isSuggestionsEnabled()) {
4688            mText = removeSuggestionSpans(mText);
4689        }
4690
4691        InputMethodManager imm = InputMethodManager.peekInstance();
4692        if (imm != null) imm.restartInput(this);
4693    }
4694
4695    /**
4696     * It would be better to rely on the input type for everything. A password inputType should have
4697     * a password transformation. We should hence use isPasswordInputType instead of this method.
4698     *
4699     * We should:
4700     * - Call setInputType in setKeyListener instead of changing the input type directly (which
4701     * would install the correct transformation).
4702     * - Refuse the installation of a non-password transformation in setTransformation if the input
4703     * type is password.
4704     *
4705     * However, this is like this for legacy reasons and we cannot break existing apps. This method
4706     * is useful since it matches what the user can see (obfuscated text or not).
4707     *
4708     * @return true if the current transformation method is of the password type.
4709     */
4710    boolean hasPasswordTransformationMethod() {
4711        return mTransformation instanceof PasswordTransformationMethod;
4712    }
4713
4714    private static boolean isPasswordInputType(int inputType) {
4715        final int variation =
4716                inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION);
4717        return variation
4718                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)
4719                || variation
4720                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD)
4721                || variation
4722                == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD);
4723    }
4724
4725    private static boolean isVisiblePasswordInputType(int inputType) {
4726        final int variation =
4727                inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION);
4728        return variation
4729                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
4730    }
4731
4732    /**
4733     * Directly change the content type integer of the text view, without
4734     * modifying any other state.
4735     * @see #setInputType(int)
4736     * @see android.text.InputType
4737     * @attr ref android.R.styleable#TextView_inputType
4738     */
4739    public void setRawInputType(int type) {
4740        if (type == InputType.TYPE_NULL && mEditor == null) return; //TYPE_NULL is the default value
4741        createEditorIfNeeded();
4742        mEditor.mInputType = type;
4743    }
4744
4745    private void setInputType(int type, boolean direct) {
4746        final int cls = type & EditorInfo.TYPE_MASK_CLASS;
4747        KeyListener input;
4748        if (cls == EditorInfo.TYPE_CLASS_TEXT) {
4749            boolean autotext = (type & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) != 0;
4750            TextKeyListener.Capitalize cap;
4751            if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) {
4752                cap = TextKeyListener.Capitalize.CHARACTERS;
4753            } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS) != 0) {
4754                cap = TextKeyListener.Capitalize.WORDS;
4755            } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) {
4756                cap = TextKeyListener.Capitalize.SENTENCES;
4757            } else {
4758                cap = TextKeyListener.Capitalize.NONE;
4759            }
4760            input = TextKeyListener.getInstance(autotext, cap);
4761        } else if (cls == EditorInfo.TYPE_CLASS_NUMBER) {
4762            input = DigitsKeyListener.getInstance(
4763                    (type & EditorInfo.TYPE_NUMBER_FLAG_SIGNED) != 0,
4764                    (type & EditorInfo.TYPE_NUMBER_FLAG_DECIMAL) != 0);
4765        } else if (cls == EditorInfo.TYPE_CLASS_DATETIME) {
4766            switch (type & EditorInfo.TYPE_MASK_VARIATION) {
4767                case EditorInfo.TYPE_DATETIME_VARIATION_DATE:
4768                    input = DateKeyListener.getInstance();
4769                    break;
4770                case EditorInfo.TYPE_DATETIME_VARIATION_TIME:
4771                    input = TimeKeyListener.getInstance();
4772                    break;
4773                default:
4774                    input = DateTimeKeyListener.getInstance();
4775                    break;
4776            }
4777        } else if (cls == EditorInfo.TYPE_CLASS_PHONE) {
4778            input = DialerKeyListener.getInstance();
4779        } else {
4780            input = TextKeyListener.getInstance();
4781        }
4782        setRawInputType(type);
4783        if (direct) {
4784            createEditorIfNeeded();
4785            mEditor.mKeyListener = input;
4786        } else {
4787            setKeyListenerOnly(input);
4788        }
4789    }
4790
4791    /**
4792     * Get the type of the editable content.
4793     *
4794     * @see #setInputType(int)
4795     * @see android.text.InputType
4796     */
4797    public int getInputType() {
4798        return mEditor == null ? EditorInfo.TYPE_NULL : mEditor.mInputType;
4799    }
4800
4801    /**
4802     * Change the editor type integer associated with the text view, which
4803     * will be reported to an IME with {@link EditorInfo#imeOptions} when it
4804     * has focus.
4805     * @see #getImeOptions
4806     * @see android.view.inputmethod.EditorInfo
4807     * @attr ref android.R.styleable#TextView_imeOptions
4808     */
4809    public void setImeOptions(int imeOptions) {
4810        createEditorIfNeeded();
4811        mEditor.createInputContentTypeIfNeeded();
4812        mEditor.mInputContentType.imeOptions = imeOptions;
4813    }
4814
4815    /**
4816     * Get the type of the IME editor.
4817     *
4818     * @see #setImeOptions(int)
4819     * @see android.view.inputmethod.EditorInfo
4820     */
4821    public int getImeOptions() {
4822        return mEditor != null && mEditor.mInputContentType != null
4823                ? mEditor.mInputContentType.imeOptions : EditorInfo.IME_NULL;
4824    }
4825
4826    /**
4827     * Change the custom IME action associated with the text view, which
4828     * will be reported to an IME with {@link EditorInfo#actionLabel}
4829     * and {@link EditorInfo#actionId} when it has focus.
4830     * @see #getImeActionLabel
4831     * @see #getImeActionId
4832     * @see android.view.inputmethod.EditorInfo
4833     * @attr ref android.R.styleable#TextView_imeActionLabel
4834     * @attr ref android.R.styleable#TextView_imeActionId
4835     */
4836    public void setImeActionLabel(CharSequence label, int actionId) {
4837        createEditorIfNeeded();
4838        mEditor.createInputContentTypeIfNeeded();
4839        mEditor.mInputContentType.imeActionLabel = label;
4840        mEditor.mInputContentType.imeActionId = actionId;
4841    }
4842
4843    /**
4844     * Get the IME action label previous set with {@link #setImeActionLabel}.
4845     *
4846     * @see #setImeActionLabel
4847     * @see android.view.inputmethod.EditorInfo
4848     */
4849    public CharSequence getImeActionLabel() {
4850        return mEditor != null && mEditor.mInputContentType != null
4851                ? mEditor.mInputContentType.imeActionLabel : null;
4852    }
4853
4854    /**
4855     * Get the IME action ID previous set with {@link #setImeActionLabel}.
4856     *
4857     * @see #setImeActionLabel
4858     * @see android.view.inputmethod.EditorInfo
4859     */
4860    public int getImeActionId() {
4861        return mEditor != null && mEditor.mInputContentType != null
4862                ? mEditor.mInputContentType.imeActionId : 0;
4863    }
4864
4865    /**
4866     * Set a special listener to be called when an action is performed
4867     * on the text view.  This will be called when the enter key is pressed,
4868     * or when an action supplied to the IME is selected by the user.  Setting
4869     * this means that the normal hard key event will not insert a newline
4870     * into the text view, even if it is multi-line; holding down the ALT
4871     * modifier will, however, allow the user to insert a newline character.
4872     */
4873    public void setOnEditorActionListener(OnEditorActionListener l) {
4874        createEditorIfNeeded();
4875        mEditor.createInputContentTypeIfNeeded();
4876        mEditor.mInputContentType.onEditorActionListener = l;
4877    }
4878
4879    /**
4880     * Called when an attached input method calls
4881     * {@link InputConnection#performEditorAction(int)
4882     * InputConnection.performEditorAction()}
4883     * for this text view.  The default implementation will call your action
4884     * listener supplied to {@link #setOnEditorActionListener}, or perform
4885     * a standard operation for {@link EditorInfo#IME_ACTION_NEXT
4886     * EditorInfo.IME_ACTION_NEXT}, {@link EditorInfo#IME_ACTION_PREVIOUS
4887     * EditorInfo.IME_ACTION_PREVIOUS}, or {@link EditorInfo#IME_ACTION_DONE
4888     * EditorInfo.IME_ACTION_DONE}.
4889     *
4890     * <p>For backwards compatibility, if no IME options have been set and the
4891     * text view would not normally advance focus on enter, then
4892     * the NEXT and DONE actions received here will be turned into an enter
4893     * key down/up pair to go through the normal key handling.
4894     *
4895     * @param actionCode The code of the action being performed.
4896     *
4897     * @see #setOnEditorActionListener
4898     */
4899    public void onEditorAction(int actionCode) {
4900        final Editor.InputContentType ict = mEditor == null ? null : mEditor.mInputContentType;
4901        if (ict != null) {
4902            if (ict.onEditorActionListener != null) {
4903                if (ict.onEditorActionListener.onEditorAction(this,
4904                        actionCode, null)) {
4905                    return;
4906                }
4907            }
4908
4909            // This is the handling for some default action.
4910            // Note that for backwards compatibility we don't do this
4911            // default handling if explicit ime options have not been given,
4912            // instead turning this into the normal enter key codes that an
4913            // app may be expecting.
4914            if (actionCode == EditorInfo.IME_ACTION_NEXT) {
4915                View v = focusSearch(FOCUS_FORWARD);
4916                if (v != null) {
4917                    if (!v.requestFocus(FOCUS_FORWARD)) {
4918                        throw new IllegalStateException("focus search returned a view "
4919                                + "that wasn't able to take focus!");
4920                    }
4921                }
4922                return;
4923
4924            } else if (actionCode == EditorInfo.IME_ACTION_PREVIOUS) {
4925                View v = focusSearch(FOCUS_BACKWARD);
4926                if (v != null) {
4927                    if (!v.requestFocus(FOCUS_BACKWARD)) {
4928                        throw new IllegalStateException("focus search returned a view "
4929                                + "that wasn't able to take focus!");
4930                    }
4931                }
4932                return;
4933
4934            } else if (actionCode == EditorInfo.IME_ACTION_DONE) {
4935                InputMethodManager imm = InputMethodManager.peekInstance();
4936                if (imm != null && imm.isActive(this)) {
4937                    imm.hideSoftInputFromWindow(getWindowToken(), 0);
4938                }
4939                return;
4940            }
4941        }
4942
4943        ViewRootImpl viewRootImpl = getViewRootImpl();
4944        if (viewRootImpl != null) {
4945            long eventTime = SystemClock.uptimeMillis();
4946            viewRootImpl.dispatchKeyFromIme(
4947                    new KeyEvent(eventTime, eventTime,
4948                    KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0,
4949                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
4950                    KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE
4951                    | KeyEvent.FLAG_EDITOR_ACTION));
4952            viewRootImpl.dispatchKeyFromIme(
4953                    new KeyEvent(SystemClock.uptimeMillis(), eventTime,
4954                    KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0,
4955                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
4956                    KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE
4957                    | KeyEvent.FLAG_EDITOR_ACTION));
4958        }
4959    }
4960
4961    /**
4962     * Set the private content type of the text, which is the
4963     * {@link EditorInfo#privateImeOptions EditorInfo.privateImeOptions}
4964     * field that will be filled in when creating an input connection.
4965     *
4966     * @see #getPrivateImeOptions()
4967     * @see EditorInfo#privateImeOptions
4968     * @attr ref android.R.styleable#TextView_privateImeOptions
4969     */
4970    public void setPrivateImeOptions(String type) {
4971        createEditorIfNeeded();
4972        mEditor.createInputContentTypeIfNeeded();
4973        mEditor.mInputContentType.privateImeOptions = type;
4974    }
4975
4976    /**
4977     * Get the private type of the content.
4978     *
4979     * @see #setPrivateImeOptions(String)
4980     * @see EditorInfo#privateImeOptions
4981     */
4982    public String getPrivateImeOptions() {
4983        return mEditor != null && mEditor.mInputContentType != null
4984                ? mEditor.mInputContentType.privateImeOptions : null;
4985    }
4986
4987    /**
4988     * Set the extra input data of the text, which is the
4989     * {@link EditorInfo#extras TextBoxAttribute.extras}
4990     * Bundle that will be filled in when creating an input connection.  The
4991     * given integer is the resource ID of an XML resource holding an
4992     * {@link android.R.styleable#InputExtras &lt;input-extras&gt;} XML tree.
4993     *
4994     * @see #getInputExtras(boolean)
4995     * @see EditorInfo#extras
4996     * @attr ref android.R.styleable#TextView_editorExtras
4997     */
4998    public void setInputExtras(@XmlRes int xmlResId) throws XmlPullParserException, IOException {
4999        createEditorIfNeeded();
5000        XmlResourceParser parser = getResources().getXml(xmlResId);
5001        mEditor.createInputContentTypeIfNeeded();
5002        mEditor.mInputContentType.extras = new Bundle();
5003        getResources().parseBundleExtras(parser, mEditor.mInputContentType.extras);
5004    }
5005
5006    /**
5007     * Retrieve the input extras currently associated with the text view, which
5008     * can be viewed as well as modified.
5009     *
5010     * @param create If true, the extras will be created if they don't already
5011     * exist.  Otherwise, null will be returned if none have been created.
5012     * @see #setInputExtras(int)
5013     * @see EditorInfo#extras
5014     * @attr ref android.R.styleable#TextView_editorExtras
5015     */
5016    public Bundle getInputExtras(boolean create) {
5017        if (mEditor == null && !create) return null;
5018        createEditorIfNeeded();
5019        if (mEditor.mInputContentType == null) {
5020            if (!create) return null;
5021            mEditor.createInputContentTypeIfNeeded();
5022        }
5023        if (mEditor.mInputContentType.extras == null) {
5024            if (!create) return null;
5025            mEditor.mInputContentType.extras = new Bundle();
5026        }
5027        return mEditor.mInputContentType.extras;
5028    }
5029
5030    /**
5031     * Change "hint" locales associated with the text view, which will be reported to an IME with
5032     * {@link EditorInfo#hintLocales} when it has focus.
5033     *
5034     * <p><strong>Note:</strong> If you want new "hint" to take effect immediately you need to
5035     * call {@link InputMethodManager#restartInput(View)}.</p>
5036     * @param hintLocales List of the languages that the user is supposed to switch to no matter
5037     * what input method subtype is currently used. Set {@code null} to clear the current "hint".
5038     * @see #getImeHIntLocales()
5039     * @see android.view.inputmethod.EditorInfo#hintLocales
5040     */
5041    public void setImeHintLocales(@Nullable LocaleList hintLocales) {
5042        createEditorIfNeeded();
5043        mEditor.createInputContentTypeIfNeeded();
5044        mEditor.mInputContentType.imeHintLocales = hintLocales;
5045    }
5046
5047    /**
5048     * @return The current languages list "hint". {@code null} when no "hint" is available.
5049     * @see #setImeHintLocales(LocaleList)
5050     * @see android.view.inputmethod.EditorInfo#hintLocales
5051     */
5052    @Nullable
5053    public LocaleList getImeHintLocales() {
5054        if (mEditor == null) {
5055            return null;
5056        }
5057        if (mEditor.mInputContentType == null) {
5058            return null;
5059        }
5060        return mEditor.mInputContentType.imeHintLocales;
5061    }
5062
5063    /**
5064     * Returns the error message that was set to be displayed with
5065     * {@link #setError}, or <code>null</code> if no error was set
5066     * or if it the error was cleared by the widget after user input.
5067     */
5068    public CharSequence getError() {
5069        return mEditor == null ? null : mEditor.mError;
5070    }
5071
5072    /**
5073     * Sets the right-hand compound drawable of the TextView to the "error"
5074     * icon and sets an error message that will be displayed in a popup when
5075     * the TextView has focus.  The icon and error message will be reset to
5076     * null when any key events cause changes to the TextView's text.  If the
5077     * <code>error</code> is <code>null</code>, the error message and icon
5078     * will be cleared.
5079     */
5080    @android.view.RemotableViewMethod
5081    public void setError(CharSequence error) {
5082        if (error == null) {
5083            setError(null, null);
5084        } else {
5085            Drawable dr = getContext().getDrawable(
5086                    com.android.internal.R.drawable.indicator_input_error);
5087
5088            dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());
5089            setError(error, dr);
5090        }
5091    }
5092
5093    /**
5094     * Sets the right-hand compound drawable of the TextView to the specified
5095     * icon and sets an error message that will be displayed in a popup when
5096     * the TextView has focus.  The icon and error message will be reset to
5097     * null when any key events cause changes to the TextView's text.  The
5098     * drawable must already have had {@link Drawable#setBounds} set on it.
5099     * If the <code>error</code> is <code>null</code>, the error message will
5100     * be cleared (and you should provide a <code>null</code> icon as well).
5101     */
5102    public void setError(CharSequence error, Drawable icon) {
5103        createEditorIfNeeded();
5104        mEditor.setError(error, icon);
5105        notifyViewAccessibilityStateChangedIfNeeded(
5106                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5107    }
5108
5109    @Override
5110    protected boolean setFrame(int l, int t, int r, int b) {
5111        boolean result = super.setFrame(l, t, r, b);
5112
5113        if (mEditor != null) mEditor.setFrame();
5114
5115        restartMarqueeIfNeeded();
5116
5117        return result;
5118    }
5119
5120    private void restartMarqueeIfNeeded() {
5121        if (mRestartMarquee && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
5122            mRestartMarquee = false;
5123            startMarquee();
5124        }
5125    }
5126
5127    /**
5128     * Sets the list of input filters that will be used if the buffer is
5129     * Editable. Has no effect otherwise.
5130     *
5131     * @attr ref android.R.styleable#TextView_maxLength
5132     */
5133    public void setFilters(InputFilter[] filters) {
5134        if (filters == null) {
5135            throw new IllegalArgumentException();
5136        }
5137
5138        mFilters = filters;
5139
5140        if (mText instanceof Editable) {
5141            setFilters((Editable) mText, filters);
5142        }
5143    }
5144
5145    /**
5146     * Sets the list of input filters on the specified Editable,
5147     * and includes mInput in the list if it is an InputFilter.
5148     */
5149    private void setFilters(Editable e, InputFilter[] filters) {
5150        if (mEditor != null) {
5151            final boolean undoFilter = mEditor.mUndoInputFilter != null;
5152            final boolean keyFilter = mEditor.mKeyListener instanceof InputFilter;
5153            int num = 0;
5154            if (undoFilter) num++;
5155            if (keyFilter) num++;
5156            if (num > 0) {
5157                InputFilter[] nf = new InputFilter[filters.length + num];
5158
5159                System.arraycopy(filters, 0, nf, 0, filters.length);
5160                num = 0;
5161                if (undoFilter) {
5162                    nf[filters.length] = mEditor.mUndoInputFilter;
5163                    num++;
5164                }
5165                if (keyFilter) {
5166                    nf[filters.length + num] = (InputFilter) mEditor.mKeyListener;
5167                }
5168
5169                e.setFilters(nf);
5170                return;
5171            }
5172        }
5173        e.setFilters(filters);
5174    }
5175
5176    /**
5177     * Returns the current list of input filters.
5178     *
5179     * @attr ref android.R.styleable#TextView_maxLength
5180     */
5181    public InputFilter[] getFilters() {
5182        return mFilters;
5183    }
5184
5185    /////////////////////////////////////////////////////////////////////////
5186
5187    private int getBoxHeight(Layout l) {
5188        Insets opticalInsets = isLayoutModeOptical(mParent) ? getOpticalInsets() : Insets.NONE;
5189        int padding = (l == mHintLayout)
5190                ? getCompoundPaddingTop() + getCompoundPaddingBottom()
5191                : getExtendedPaddingTop() + getExtendedPaddingBottom();
5192        return getMeasuredHeight() - padding + opticalInsets.top + opticalInsets.bottom;
5193    }
5194
5195    int getVerticalOffset(boolean forceNormal) {
5196        int voffset = 0;
5197        final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
5198
5199        Layout l = mLayout;
5200        if (!forceNormal && mText.length() == 0 && mHintLayout != null) {
5201            l = mHintLayout;
5202        }
5203
5204        if (gravity != Gravity.TOP) {
5205            int boxht = getBoxHeight(l);
5206            int textht = l.getHeight();
5207
5208            if (textht < boxht) {
5209                if (gravity == Gravity.BOTTOM) {
5210                    voffset = boxht - textht;
5211                } else { // (gravity == Gravity.CENTER_VERTICAL)
5212                    voffset = (boxht - textht) >> 1;
5213                }
5214            }
5215        }
5216        return voffset;
5217    }
5218
5219    private int getBottomVerticalOffset(boolean forceNormal) {
5220        int voffset = 0;
5221        final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
5222
5223        Layout l = mLayout;
5224        if (!forceNormal && mText.length() == 0 && mHintLayout != null) {
5225            l = mHintLayout;
5226        }
5227
5228        if (gravity != Gravity.BOTTOM) {
5229            int boxht = getBoxHeight(l);
5230            int textht = l.getHeight();
5231
5232            if (textht < boxht) {
5233                if (gravity == Gravity.TOP) {
5234                    voffset = boxht - textht;
5235                } else { // (gravity == Gravity.CENTER_VERTICAL)
5236                    voffset = (boxht - textht) >> 1;
5237                }
5238            }
5239        }
5240        return voffset;
5241    }
5242
5243    void invalidateCursorPath() {
5244        if (mHighlightPathBogus) {
5245            invalidateCursor();
5246        } else {
5247            final int horizontalPadding = getCompoundPaddingLeft();
5248            final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true);
5249
5250            if (mEditor.mCursorCount == 0) {
5251                synchronized (TEMP_RECTF) {
5252                    /*
5253                     * The reason for this concern about the thickness of the
5254                     * cursor and doing the floor/ceil on the coordinates is that
5255                     * some EditTexts (notably textfields in the Browser) have
5256                     * anti-aliased text where not all the characters are
5257                     * necessarily at integer-multiple locations.  This should
5258                     * make sure the entire cursor gets invalidated instead of
5259                     * sometimes missing half a pixel.
5260                     */
5261                    float thick = (float) Math.ceil(mTextPaint.getStrokeWidth());
5262                    if (thick < 1.0f) {
5263                        thick = 1.0f;
5264                    }
5265
5266                    thick /= 2.0f;
5267
5268                    // mHighlightPath is guaranteed to be non null at that point.
5269                    mHighlightPath.computeBounds(TEMP_RECTF, false);
5270
5271                    invalidate((int) Math.floor(horizontalPadding + TEMP_RECTF.left - thick),
5272                            (int) Math.floor(verticalPadding + TEMP_RECTF.top - thick),
5273                            (int) Math.ceil(horizontalPadding + TEMP_RECTF.right + thick),
5274                            (int) Math.ceil(verticalPadding + TEMP_RECTF.bottom + thick));
5275                }
5276            } else {
5277                for (int i = 0; i < mEditor.mCursorCount; i++) {
5278                    Rect bounds = mEditor.mCursorDrawable[i].getBounds();
5279                    invalidate(bounds.left + horizontalPadding, bounds.top + verticalPadding,
5280                            bounds.right + horizontalPadding, bounds.bottom + verticalPadding);
5281                }
5282            }
5283        }
5284    }
5285
5286    void invalidateCursor() {
5287        int where = getSelectionEnd();
5288
5289        invalidateCursor(where, where, where);
5290    }
5291
5292    private void invalidateCursor(int a, int b, int c) {
5293        if (a >= 0 || b >= 0 || c >= 0) {
5294            int start = Math.min(Math.min(a, b), c);
5295            int end = Math.max(Math.max(a, b), c);
5296            invalidateRegion(start, end, true /* Also invalidates blinking cursor */);
5297        }
5298    }
5299
5300    /**
5301     * Invalidates the region of text enclosed between the start and end text offsets.
5302     */
5303    void invalidateRegion(int start, int end, boolean invalidateCursor) {
5304        if (mLayout == null) {
5305            invalidate();
5306        } else {
5307            int lineStart = mLayout.getLineForOffset(start);
5308            int top = mLayout.getLineTop(lineStart);
5309
5310            // This is ridiculous, but the descent from the line above
5311            // can hang down into the line we really want to redraw,
5312            // so we have to invalidate part of the line above to make
5313            // sure everything that needs to be redrawn really is.
5314            // (But not the whole line above, because that would cause
5315            // the same problem with the descenders on the line above it!)
5316            if (lineStart > 0) {
5317                top -= mLayout.getLineDescent(lineStart - 1);
5318            }
5319
5320            int lineEnd;
5321
5322            if (start == end) {
5323                lineEnd = lineStart;
5324            } else {
5325                lineEnd = mLayout.getLineForOffset(end);
5326            }
5327
5328            int bottom = mLayout.getLineBottom(lineEnd);
5329
5330            // mEditor can be null in case selection is set programmatically.
5331            if (invalidateCursor && mEditor != null) {
5332                for (int i = 0; i < mEditor.mCursorCount; i++) {
5333                    Rect bounds = mEditor.mCursorDrawable[i].getBounds();
5334                    top = Math.min(top, bounds.top);
5335                    bottom = Math.max(bottom, bounds.bottom);
5336                }
5337            }
5338
5339            final int compoundPaddingLeft = getCompoundPaddingLeft();
5340            final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true);
5341
5342            int left, right;
5343            if (lineStart == lineEnd && !invalidateCursor) {
5344                left = (int) mLayout.getPrimaryHorizontal(start);
5345                right = (int) (mLayout.getPrimaryHorizontal(end) + 1.0);
5346                left += compoundPaddingLeft;
5347                right += compoundPaddingLeft;
5348            } else {
5349                // Rectangle bounding box when the region spans several lines
5350                left = compoundPaddingLeft;
5351                right = getWidth() - getCompoundPaddingRight();
5352            }
5353
5354            invalidate(mScrollX + left, verticalPadding + top,
5355                    mScrollX + right, verticalPadding + bottom);
5356        }
5357    }
5358
5359    private void registerForPreDraw() {
5360        if (!mPreDrawRegistered) {
5361            getViewTreeObserver().addOnPreDrawListener(this);
5362            mPreDrawRegistered = true;
5363        }
5364    }
5365
5366    private void unregisterForPreDraw() {
5367        getViewTreeObserver().removeOnPreDrawListener(this);
5368        mPreDrawRegistered = false;
5369        mPreDrawListenerDetached = false;
5370    }
5371
5372    /**
5373     * {@inheritDoc}
5374     */
5375    @Override
5376    public boolean onPreDraw() {
5377        if (mLayout == null) {
5378            assumeLayout();
5379        }
5380
5381        if (mMovement != null) {
5382            /* This code also provides auto-scrolling when a cursor is moved using a
5383             * CursorController (insertion point or selection limits).
5384             * For selection, ensure start or end is visible depending on controller's state.
5385             */
5386            int curs = getSelectionEnd();
5387            // Do not create the controller if it is not already created.
5388            if (mEditor != null && mEditor.mSelectionModifierCursorController != null
5389                    && mEditor.mSelectionModifierCursorController.isSelectionStartDragged()) {
5390                curs = getSelectionStart();
5391            }
5392
5393            /*
5394             * TODO: This should really only keep the end in view if
5395             * it already was before the text changed.  I'm not sure
5396             * of a good way to tell from here if it was.
5397             */
5398            if (curs < 0 && (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
5399                curs = mText.length();
5400            }
5401
5402            if (curs >= 0) {
5403                bringPointIntoView(curs);
5404            }
5405        } else {
5406            bringTextIntoView();
5407        }
5408
5409        // This has to be checked here since:
5410        // - onFocusChanged cannot start it when focus is given to a view with selected text (after
5411        //   a screen rotation) since layout is not yet initialized at that point.
5412        if (mEditor != null && mEditor.mCreatedWithASelection) {
5413            mEditor.refreshTextActionMode();
5414            mEditor.mCreatedWithASelection = false;
5415        }
5416
5417        unregisterForPreDraw();
5418
5419        return true;
5420    }
5421
5422    @Override
5423    protected void onAttachedToWindow() {
5424        super.onAttachedToWindow();
5425
5426        if (mEditor != null) mEditor.onAttachedToWindow();
5427
5428        if (mPreDrawListenerDetached) {
5429            getViewTreeObserver().addOnPreDrawListener(this);
5430            mPreDrawListenerDetached = false;
5431        }
5432    }
5433
5434    /** @hide */
5435    @Override
5436    protected void onDetachedFromWindowInternal() {
5437        if (mPreDrawRegistered) {
5438            getViewTreeObserver().removeOnPreDrawListener(this);
5439            mPreDrawListenerDetached = true;
5440        }
5441
5442        resetResolvedDrawables();
5443
5444        if (mEditor != null) mEditor.onDetachedFromWindow();
5445
5446        super.onDetachedFromWindowInternal();
5447    }
5448
5449    @Override
5450    public void onScreenStateChanged(int screenState) {
5451        super.onScreenStateChanged(screenState);
5452        if (mEditor != null) mEditor.onScreenStateChanged(screenState);
5453    }
5454
5455    @Override
5456    protected boolean isPaddingOffsetRequired() {
5457        return mShadowRadius != 0 || mDrawables != null;
5458    }
5459
5460    @Override
5461    protected int getLeftPaddingOffset() {
5462        return getCompoundPaddingLeft() - mPaddingLeft
5463                + (int) Math.min(0, mShadowDx - mShadowRadius);
5464    }
5465
5466    @Override
5467    protected int getTopPaddingOffset() {
5468        return (int) Math.min(0, mShadowDy - mShadowRadius);
5469    }
5470
5471    @Override
5472    protected int getBottomPaddingOffset() {
5473        return (int) Math.max(0, mShadowDy + mShadowRadius);
5474    }
5475
5476    @Override
5477    protected int getRightPaddingOffset() {
5478        return -(getCompoundPaddingRight() - mPaddingRight)
5479                + (int) Math.max(0, mShadowDx + mShadowRadius);
5480    }
5481
5482    @Override
5483    protected boolean verifyDrawable(@NonNull Drawable who) {
5484        final boolean verified = super.verifyDrawable(who);
5485        if (!verified && mDrawables != null) {
5486            for (Drawable dr : mDrawables.mShowing) {
5487                if (who == dr) {
5488                    return true;
5489                }
5490            }
5491        }
5492        return verified;
5493    }
5494
5495    @Override
5496    public void jumpDrawablesToCurrentState() {
5497        super.jumpDrawablesToCurrentState();
5498        if (mDrawables != null) {
5499            for (Drawable dr : mDrawables.mShowing) {
5500                if (dr != null) {
5501                    dr.jumpToCurrentState();
5502                }
5503            }
5504        }
5505    }
5506
5507    @Override
5508    public void invalidateDrawable(@NonNull Drawable drawable) {
5509        boolean handled = false;
5510
5511        if (verifyDrawable(drawable)) {
5512            final Rect dirty = drawable.getBounds();
5513            int scrollX = mScrollX;
5514            int scrollY = mScrollY;
5515
5516            // IMPORTANT: The coordinates below are based on the coordinates computed
5517            // for each compound drawable in onDraw(). Make sure to update each section
5518            // accordingly.
5519            final TextView.Drawables drawables = mDrawables;
5520            if (drawables != null) {
5521                if (drawable == drawables.mShowing[Drawables.LEFT]) {
5522                    final int compoundPaddingTop = getCompoundPaddingTop();
5523                    final int compoundPaddingBottom = getCompoundPaddingBottom();
5524                    final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
5525
5526                    scrollX += mPaddingLeft;
5527                    scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2;
5528                    handled = true;
5529                } else if (drawable == drawables.mShowing[Drawables.RIGHT]) {
5530                    final int compoundPaddingTop = getCompoundPaddingTop();
5531                    final int compoundPaddingBottom = getCompoundPaddingBottom();
5532                    final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
5533
5534                    scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight);
5535                    scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2;
5536                    handled = true;
5537                } else if (drawable == drawables.mShowing[Drawables.TOP]) {
5538                    final int compoundPaddingLeft = getCompoundPaddingLeft();
5539                    final int compoundPaddingRight = getCompoundPaddingRight();
5540                    final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft;
5541
5542                    scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2;
5543                    scrollY += mPaddingTop;
5544                    handled = true;
5545                } else if (drawable == drawables.mShowing[Drawables.BOTTOM]) {
5546                    final int compoundPaddingLeft = getCompoundPaddingLeft();
5547                    final int compoundPaddingRight = getCompoundPaddingRight();
5548                    final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft;
5549
5550                    scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2;
5551                    scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom);
5552                    handled = true;
5553                }
5554            }
5555
5556            if (handled) {
5557                invalidate(dirty.left + scrollX, dirty.top + scrollY,
5558                        dirty.right + scrollX, dirty.bottom + scrollY);
5559            }
5560        }
5561
5562        if (!handled) {
5563            super.invalidateDrawable(drawable);
5564        }
5565    }
5566
5567    @Override
5568    public boolean hasOverlappingRendering() {
5569        // horizontal fading edge causes SaveLayerAlpha, which doesn't support alpha modulation
5570        return ((getBackground() != null && getBackground().getCurrent() != null)
5571                || mText instanceof Spannable || hasSelection()
5572                || isHorizontalFadingEdgeEnabled());
5573    }
5574
5575    /**
5576     *
5577     * Returns the state of the {@code textIsSelectable} flag (See
5578     * {@link #setTextIsSelectable setTextIsSelectable()}). Although you have to set this flag
5579     * to allow users to select and copy text in a non-editable TextView, the content of an
5580     * {@link EditText} can always be selected, independently of the value of this flag.
5581     * <p>
5582     *
5583     * @return True if the text displayed in this TextView can be selected by the user.
5584     *
5585     * @attr ref android.R.styleable#TextView_textIsSelectable
5586     */
5587    public boolean isTextSelectable() {
5588        return mEditor == null ? false : mEditor.mTextIsSelectable;
5589    }
5590
5591    /**
5592     * Sets whether the content of this view is selectable by the user. The default is
5593     * {@code false}, meaning that the content is not selectable.
5594     * <p>
5595     * When you use a TextView to display a useful piece of information to the user (such as a
5596     * contact's address), make it selectable, so that the user can select and copy its
5597     * content. You can also use set the XML attribute
5598     * {@link android.R.styleable#TextView_textIsSelectable} to "true".
5599     * <p>
5600     * When you call this method to set the value of {@code textIsSelectable}, it sets
5601     * the flags {@code focusable}, {@code focusableInTouchMode}, {@code clickable},
5602     * and {@code longClickable} to the same value. These flags correspond to the attributes
5603     * {@link android.R.styleable#View_focusable android:focusable},
5604     * {@link android.R.styleable#View_focusableInTouchMode android:focusableInTouchMode},
5605     * {@link android.R.styleable#View_clickable android:clickable}, and
5606     * {@link android.R.styleable#View_longClickable android:longClickable}. To restore any of these
5607     * flags to a state you had set previously, call one or more of the following methods:
5608     * {@link #setFocusable(boolean) setFocusable()},
5609     * {@link #setFocusableInTouchMode(boolean) setFocusableInTouchMode()},
5610     * {@link #setClickable(boolean) setClickable()} or
5611     * {@link #setLongClickable(boolean) setLongClickable()}.
5612     *
5613     * @param selectable Whether the content of this TextView should be selectable.
5614     */
5615    public void setTextIsSelectable(boolean selectable) {
5616        if (!selectable && mEditor == null) return; // false is default value with no edit data
5617
5618        createEditorIfNeeded();
5619        if (mEditor.mTextIsSelectable == selectable) return;
5620
5621        mEditor.mTextIsSelectable = selectable;
5622        setFocusableInTouchMode(selectable);
5623        setFocusable(selectable);
5624        setClickable(selectable);
5625        setLongClickable(selectable);
5626
5627        // mInputType should already be EditorInfo.TYPE_NULL and mInput should be null
5628
5629        setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null);
5630        setText(mText, selectable ? BufferType.SPANNABLE : BufferType.NORMAL);
5631
5632        // Called by setText above, but safer in case of future code changes
5633        mEditor.prepareCursorControllers();
5634    }
5635
5636    @Override
5637    protected int[] onCreateDrawableState(int extraSpace) {
5638        final int[] drawableState;
5639
5640        if (mSingleLine) {
5641            drawableState = super.onCreateDrawableState(extraSpace);
5642        } else {
5643            drawableState = super.onCreateDrawableState(extraSpace + 1);
5644            mergeDrawableStates(drawableState, MULTILINE_STATE_SET);
5645        }
5646
5647        if (isTextSelectable()) {
5648            // Disable pressed state, which was introduced when TextView was made clickable.
5649            // Prevents text color change.
5650            // setClickable(false) would have a similar effect, but it also disables focus changes
5651            // and long press actions, which are both needed by text selection.
5652            final int length = drawableState.length;
5653            for (int i = 0; i < length; i++) {
5654                if (drawableState[i] == R.attr.state_pressed) {
5655                    final int[] nonPressedState = new int[length - 1];
5656                    System.arraycopy(drawableState, 0, nonPressedState, 0, i);
5657                    System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1);
5658                    return nonPressedState;
5659                }
5660            }
5661        }
5662
5663        return drawableState;
5664    }
5665
5666    private Path getUpdatedHighlightPath() {
5667        Path highlight = null;
5668        Paint highlightPaint = mHighlightPaint;
5669
5670        final int selStart = getSelectionStart();
5671        final int selEnd = getSelectionEnd();
5672        if (mMovement != null && (isFocused() || isPressed()) && selStart >= 0) {
5673            if (selStart == selEnd) {
5674                if (mEditor != null && mEditor.isCursorVisible()
5675                        && (SystemClock.uptimeMillis() - mEditor.mShowCursor)
5676                        % (2 * Editor.BLINK) < Editor.BLINK) {
5677                    if (mHighlightPathBogus) {
5678                        if (mHighlightPath == null) mHighlightPath = new Path();
5679                        mHighlightPath.reset();
5680                        mLayout.getCursorPath(selStart, mHighlightPath, mText);
5681                        mEditor.updateCursorsPositions();
5682                        mHighlightPathBogus = false;
5683                    }
5684
5685                    // XXX should pass to skin instead of drawing directly
5686                    highlightPaint.setColor(mCurTextColor);
5687                    highlightPaint.setStyle(Paint.Style.STROKE);
5688                    highlight = mHighlightPath;
5689                }
5690            } else {
5691                if (mHighlightPathBogus) {
5692                    if (mHighlightPath == null) mHighlightPath = new Path();
5693                    mHighlightPath.reset();
5694                    mLayout.getSelectionPath(selStart, selEnd, mHighlightPath);
5695                    mHighlightPathBogus = false;
5696                }
5697
5698                // XXX should pass to skin instead of drawing directly
5699                highlightPaint.setColor(mHighlightColor);
5700                highlightPaint.setStyle(Paint.Style.FILL);
5701
5702                highlight = mHighlightPath;
5703            }
5704        }
5705        return highlight;
5706    }
5707
5708    /**
5709     * @hide
5710     */
5711    public int getHorizontalOffsetForDrawables() {
5712        return 0;
5713    }
5714
5715    @Override
5716    protected void onDraw(Canvas canvas) {
5717        restartMarqueeIfNeeded();
5718
5719        // Draw the background for this view
5720        super.onDraw(canvas);
5721
5722        final int compoundPaddingLeft = getCompoundPaddingLeft();
5723        final int compoundPaddingTop = getCompoundPaddingTop();
5724        final int compoundPaddingRight = getCompoundPaddingRight();
5725        final int compoundPaddingBottom = getCompoundPaddingBottom();
5726        final int scrollX = mScrollX;
5727        final int scrollY = mScrollY;
5728        final int right = mRight;
5729        final int left = mLeft;
5730        final int bottom = mBottom;
5731        final int top = mTop;
5732        final boolean isLayoutRtl = isLayoutRtl();
5733        final int offset = getHorizontalOffsetForDrawables();
5734        final int leftOffset = isLayoutRtl ? 0 : offset;
5735        final int rightOffset = isLayoutRtl ? offset : 0;
5736
5737        final Drawables dr = mDrawables;
5738        if (dr != null) {
5739            /*
5740             * Compound, not extended, because the icon is not clipped
5741             * if the text height is smaller.
5742             */
5743
5744            int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop;
5745            int hspace = right - left - compoundPaddingRight - compoundPaddingLeft;
5746
5747            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
5748            // Make sure to update invalidateDrawable() when changing this code.
5749            if (dr.mShowing[Drawables.LEFT] != null) {
5750                canvas.save();
5751                canvas.translate(scrollX + mPaddingLeft + leftOffset,
5752                        scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightLeft) / 2);
5753                dr.mShowing[Drawables.LEFT].draw(canvas);
5754                canvas.restore();
5755            }
5756
5757            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
5758            // Make sure to update invalidateDrawable() when changing this code.
5759            if (dr.mShowing[Drawables.RIGHT] != null) {
5760                canvas.save();
5761                canvas.translate(scrollX + right - left - mPaddingRight
5762                        - dr.mDrawableSizeRight - rightOffset,
5763                         scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2);
5764                dr.mShowing[Drawables.RIGHT].draw(canvas);
5765                canvas.restore();
5766            }
5767
5768            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
5769            // Make sure to update invalidateDrawable() when changing this code.
5770            if (dr.mShowing[Drawables.TOP] != null) {
5771                canvas.save();
5772                canvas.translate(scrollX + compoundPaddingLeft
5773                        + (hspace - dr.mDrawableWidthTop) / 2, scrollY + mPaddingTop);
5774                dr.mShowing[Drawables.TOP].draw(canvas);
5775                canvas.restore();
5776            }
5777
5778            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
5779            // Make sure to update invalidateDrawable() when changing this code.
5780            if (dr.mShowing[Drawables.BOTTOM] != null) {
5781                canvas.save();
5782                canvas.translate(scrollX + compoundPaddingLeft
5783                        + (hspace - dr.mDrawableWidthBottom) / 2,
5784                         scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom);
5785                dr.mShowing[Drawables.BOTTOM].draw(canvas);
5786                canvas.restore();
5787            }
5788        }
5789
5790        int color = mCurTextColor;
5791
5792        if (mLayout == null) {
5793            assumeLayout();
5794        }
5795
5796        Layout layout = mLayout;
5797
5798        if (mHint != null && mText.length() == 0) {
5799            if (mHintTextColor != null) {
5800                color = mCurHintTextColor;
5801            }
5802
5803            layout = mHintLayout;
5804        }
5805
5806        mTextPaint.setColor(color);
5807        mTextPaint.drawableState = getDrawableState();
5808
5809        canvas.save();
5810        /*  Would be faster if we didn't have to do this. Can we chop the
5811            (displayable) text so that we don't need to do this ever?
5812        */
5813
5814        int extendedPaddingTop = getExtendedPaddingTop();
5815        int extendedPaddingBottom = getExtendedPaddingBottom();
5816
5817        final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
5818        final int maxScrollY = mLayout.getHeight() - vspace;
5819
5820        float clipLeft = compoundPaddingLeft + scrollX;
5821        float clipTop = (scrollY == 0) ? 0 : extendedPaddingTop + scrollY;
5822        float clipRight = right - left - getCompoundPaddingRight() + scrollX;
5823        float clipBottom = bottom - top + scrollY
5824                - ((scrollY == maxScrollY) ? 0 : extendedPaddingBottom);
5825
5826        if (mShadowRadius != 0) {
5827            clipLeft += Math.min(0, mShadowDx - mShadowRadius);
5828            clipRight += Math.max(0, mShadowDx + mShadowRadius);
5829
5830            clipTop += Math.min(0, mShadowDy - mShadowRadius);
5831            clipBottom += Math.max(0, mShadowDy + mShadowRadius);
5832        }
5833
5834        canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom);
5835
5836        int voffsetText = 0;
5837        int voffsetCursor = 0;
5838
5839        // translate in by our padding
5840        /* shortcircuit calling getVerticaOffset() */
5841        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
5842            voffsetText = getVerticalOffset(false);
5843            voffsetCursor = getVerticalOffset(true);
5844        }
5845        canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText);
5846
5847        final int layoutDirection = getLayoutDirection();
5848        final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
5849        if (isMarqueeFadeEnabled()) {
5850            if (!mSingleLine && getLineCount() == 1 && canMarquee()
5851                    && (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) {
5852                final int width = mRight - mLeft;
5853                final int padding = getCompoundPaddingLeft() + getCompoundPaddingRight();
5854                final float dx = mLayout.getLineRight(0) - (width - padding);
5855                canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f);
5856            }
5857
5858            if (mMarquee != null && mMarquee.isRunning()) {
5859                final float dx = -mMarquee.getScroll();
5860                canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f);
5861            }
5862        }
5863
5864        final int cursorOffsetVertical = voffsetCursor - voffsetText;
5865
5866        Path highlight = getUpdatedHighlightPath();
5867        if (mEditor != null) {
5868            mEditor.onDraw(canvas, layout, highlight, mHighlightPaint, cursorOffsetVertical);
5869        } else {
5870            layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
5871        }
5872
5873        if (mMarquee != null && mMarquee.shouldDrawGhost()) {
5874            final float dx = mMarquee.getGhostOffset();
5875            canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f);
5876            layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
5877        }
5878
5879        canvas.restore();
5880    }
5881
5882    @Override
5883    public void getFocusedRect(Rect r) {
5884        if (mLayout == null) {
5885            super.getFocusedRect(r);
5886            return;
5887        }
5888
5889        int selEnd = getSelectionEnd();
5890        if (selEnd < 0) {
5891            super.getFocusedRect(r);
5892            return;
5893        }
5894
5895        int selStart = getSelectionStart();
5896        if (selStart < 0 || selStart >= selEnd) {
5897            int line = mLayout.getLineForOffset(selEnd);
5898            r.top = mLayout.getLineTop(line);
5899            r.bottom = mLayout.getLineBottom(line);
5900            r.left = (int) mLayout.getPrimaryHorizontal(selEnd) - 2;
5901            r.right = r.left + 4;
5902        } else {
5903            int lineStart = mLayout.getLineForOffset(selStart);
5904            int lineEnd = mLayout.getLineForOffset(selEnd);
5905            r.top = mLayout.getLineTop(lineStart);
5906            r.bottom = mLayout.getLineBottom(lineEnd);
5907            if (lineStart == lineEnd) {
5908                r.left = (int) mLayout.getPrimaryHorizontal(selStart);
5909                r.right = (int) mLayout.getPrimaryHorizontal(selEnd);
5910            } else {
5911                // Selection extends across multiple lines -- make the focused
5912                // rect cover the entire width.
5913                if (mHighlightPathBogus) {
5914                    if (mHighlightPath == null) mHighlightPath = new Path();
5915                    mHighlightPath.reset();
5916                    mLayout.getSelectionPath(selStart, selEnd, mHighlightPath);
5917                    mHighlightPathBogus = false;
5918                }
5919                synchronized (TEMP_RECTF) {
5920                    mHighlightPath.computeBounds(TEMP_RECTF, true);
5921                    r.left = (int) TEMP_RECTF.left - 1;
5922                    r.right = (int) TEMP_RECTF.right + 1;
5923                }
5924            }
5925        }
5926
5927        // Adjust for padding and gravity.
5928        int paddingLeft = getCompoundPaddingLeft();
5929        int paddingTop = getExtendedPaddingTop();
5930        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
5931            paddingTop += getVerticalOffset(false);
5932        }
5933        r.offset(paddingLeft, paddingTop);
5934        int paddingBottom = getExtendedPaddingBottom();
5935        r.bottom += paddingBottom;
5936    }
5937
5938    /**
5939     * Return the number of lines of text, or 0 if the internal Layout has not
5940     * been built.
5941     */
5942    public int getLineCount() {
5943        return mLayout != null ? mLayout.getLineCount() : 0;
5944    }
5945
5946    /**
5947     * Return the baseline for the specified line (0...getLineCount() - 1)
5948     * If bounds is not null, return the top, left, right, bottom extents
5949     * of the specified line in it. If the internal Layout has not been built,
5950     * return 0 and set bounds to (0, 0, 0, 0)
5951     * @param line which line to examine (0..getLineCount() - 1)
5952     * @param bounds Optional. If not null, it returns the extent of the line
5953     * @return the Y-coordinate of the baseline
5954     */
5955    public int getLineBounds(int line, Rect bounds) {
5956        if (mLayout == null) {
5957            if (bounds != null) {
5958                bounds.set(0, 0, 0, 0);
5959            }
5960            return 0;
5961        } else {
5962            int baseline = mLayout.getLineBounds(line, bounds);
5963
5964            int voffset = getExtendedPaddingTop();
5965            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
5966                voffset += getVerticalOffset(true);
5967            }
5968            if (bounds != null) {
5969                bounds.offset(getCompoundPaddingLeft(), voffset);
5970            }
5971            return baseline + voffset;
5972        }
5973    }
5974
5975    @Override
5976    public int getBaseline() {
5977        if (mLayout == null) {
5978            return super.getBaseline();
5979        }
5980
5981        return getBaselineOffset() + mLayout.getLineBaseline(0);
5982    }
5983
5984    int getBaselineOffset() {
5985        int voffset = 0;
5986        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
5987            voffset = getVerticalOffset(true);
5988        }
5989
5990        if (isLayoutModeOptical(mParent)) {
5991            voffset -= getOpticalInsets().top;
5992        }
5993
5994        return getExtendedPaddingTop() + voffset;
5995    }
5996
5997    /**
5998     * @hide
5999     */
6000    @Override
6001    protected int getFadeTop(boolean offsetRequired) {
6002        if (mLayout == null) return 0;
6003
6004        int voffset = 0;
6005        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
6006            voffset = getVerticalOffset(true);
6007        }
6008
6009        if (offsetRequired) voffset += getTopPaddingOffset();
6010
6011        return getExtendedPaddingTop() + voffset;
6012    }
6013
6014    /**
6015     * @hide
6016     */
6017    @Override
6018    protected int getFadeHeight(boolean offsetRequired) {
6019        return mLayout != null ? mLayout.getHeight() : 0;
6020    }
6021
6022    @Override
6023    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
6024        if (mText instanceof Spannable && mLinksClickable) {
6025            final float x = event.getX(pointerIndex);
6026            final float y = event.getY(pointerIndex);
6027            final int offset = getOffsetForPosition(x, y);
6028            final ClickableSpan[] clickables = ((Spannable) mText).getSpans(offset, offset,
6029                    ClickableSpan.class);
6030            if (clickables.length > 0) {
6031                return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_HAND);
6032            }
6033        }
6034        if (isTextSelectable() || isTextEditable()) {
6035            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_TEXT);
6036        }
6037        return super.onResolvePointerIcon(event, pointerIndex);
6038    }
6039
6040    @Override
6041    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
6042        // Note: If the IME is in fullscreen mode and IMS#mExtractEditText is in text action mode,
6043        // InputMethodService#onKeyDown and InputMethodService#onKeyUp are responsible to call
6044        // InputMethodService#mExtractEditText.maybeHandleBackInTextActionMode(event).
6045        if (keyCode == KeyEvent.KEYCODE_BACK && handleBackInTextActionModeIfNeeded(event)) {
6046            return true;
6047        }
6048        return super.onKeyPreIme(keyCode, event);
6049    }
6050
6051    /**
6052     * @hide
6053     */
6054    public boolean handleBackInTextActionModeIfNeeded(KeyEvent event) {
6055        // Do nothing unless mEditor is in text action mode.
6056        if (mEditor == null || mEditor.mTextActionMode == null) {
6057            return false;
6058        }
6059
6060        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
6061            KeyEvent.DispatcherState state = getKeyDispatcherState();
6062            if (state != null) {
6063                state.startTracking(event, this);
6064            }
6065            return true;
6066        } else if (event.getAction() == KeyEvent.ACTION_UP) {
6067            KeyEvent.DispatcherState state = getKeyDispatcherState();
6068            if (state != null) {
6069                state.handleUpEvent(event);
6070            }
6071            if (event.isTracking() && !event.isCanceled()) {
6072                stopTextActionMode();
6073                return true;
6074            }
6075        }
6076        return false;
6077    }
6078
6079    @Override
6080    public boolean onKeyDown(int keyCode, KeyEvent event) {
6081        final int which = doKeyDown(keyCode, event, null);
6082        if (which == KEY_EVENT_NOT_HANDLED) {
6083            return super.onKeyDown(keyCode, event);
6084        }
6085
6086        return true;
6087    }
6088
6089    @Override
6090    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6091        KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN);
6092        final int which = doKeyDown(keyCode, down, event);
6093        if (which == KEY_EVENT_NOT_HANDLED) {
6094            // Go through default dispatching.
6095            return super.onKeyMultiple(keyCode, repeatCount, event);
6096        }
6097        if (which == KEY_EVENT_HANDLED) {
6098            // Consumed the whole thing.
6099            return true;
6100        }
6101
6102        repeatCount--;
6103
6104        // We are going to dispatch the remaining events to either the input
6105        // or movement method.  To do this, we will just send a repeated stream
6106        // of down and up events until we have done the complete repeatCount.
6107        // It would be nice if those interfaces had an onKeyMultiple() method,
6108        // but adding that is a more complicated change.
6109        KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP);
6110        if (which == KEY_DOWN_HANDLED_BY_KEY_LISTENER) {
6111            // mEditor and mEditor.mInput are not null from doKeyDown
6112            mEditor.mKeyListener.onKeyUp(this, (Editable) mText, keyCode, up);
6113            while (--repeatCount > 0) {
6114                mEditor.mKeyListener.onKeyDown(this, (Editable) mText, keyCode, down);
6115                mEditor.mKeyListener.onKeyUp(this, (Editable) mText, keyCode, up);
6116            }
6117            hideErrorIfUnchanged();
6118
6119        } else if (which == KEY_DOWN_HANDLED_BY_MOVEMENT_METHOD) {
6120            // mMovement is not null from doKeyDown
6121            mMovement.onKeyUp(this, (Spannable) mText, keyCode, up);
6122            while (--repeatCount > 0) {
6123                mMovement.onKeyDown(this, (Spannable) mText, keyCode, down);
6124                mMovement.onKeyUp(this, (Spannable) mText, keyCode, up);
6125            }
6126        }
6127
6128        return true;
6129    }
6130
6131    /**
6132     * Returns true if pressing ENTER in this field advances focus instead
6133     * of inserting the character.  This is true mostly in single-line fields,
6134     * but also in mail addresses and subjects which will display on multiple
6135     * lines but where it doesn't make sense to insert newlines.
6136     */
6137    private boolean shouldAdvanceFocusOnEnter() {
6138        if (getKeyListener() == null) {
6139            return false;
6140        }
6141
6142        if (mSingleLine) {
6143            return true;
6144        }
6145
6146        if (mEditor != null
6147                && (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS)
6148                        == EditorInfo.TYPE_CLASS_TEXT) {
6149            int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION;
6150            if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
6151                    || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) {
6152                return true;
6153            }
6154        }
6155
6156        return false;
6157    }
6158
6159    /**
6160     * Returns true if pressing TAB in this field advances focus instead
6161     * of inserting the character.  Insert tabs only in multi-line editors.
6162     */
6163    private boolean shouldAdvanceFocusOnTab() {
6164        if (getKeyListener() != null && !mSingleLine && mEditor != null
6165                && (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS)
6166                        == EditorInfo.TYPE_CLASS_TEXT) {
6167            int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION;
6168            if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE
6169                    || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) {
6170                return false;
6171            }
6172        }
6173        return true;
6174    }
6175
6176    private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) {
6177        if (!isEnabled()) {
6178            return KEY_EVENT_NOT_HANDLED;
6179        }
6180
6181        // If this is the initial keydown, we don't want to prevent a movement away from this view.
6182        // While this shouldn't be necessary because any time we're preventing default movement we
6183        // should be restricting the focus to remain within this view, thus we'll also receive
6184        // the key up event, occasionally key up events will get dropped and we don't want to
6185        // prevent the user from traversing out of this on the next key down.
6186        if (event.getRepeatCount() == 0 && !KeyEvent.isModifierKey(keyCode)) {
6187            mPreventDefaultMovement = false;
6188        }
6189
6190        switch (keyCode) {
6191            case KeyEvent.KEYCODE_ENTER:
6192                if (event.hasNoModifiers()) {
6193                    // When mInputContentType is set, we know that we are
6194                    // running in a "modern" cupcake environment, so don't need
6195                    // to worry about the application trying to capture
6196                    // enter key events.
6197                    if (mEditor != null && mEditor.mInputContentType != null) {
6198                        // If there is an action listener, given them a
6199                        // chance to consume the event.
6200                        if (mEditor.mInputContentType.onEditorActionListener != null
6201                                && mEditor.mInputContentType.onEditorActionListener.onEditorAction(
6202                                        this, EditorInfo.IME_NULL, event)) {
6203                            mEditor.mInputContentType.enterDown = true;
6204                            // We are consuming the enter key for them.
6205                            return KEY_EVENT_HANDLED;
6206                        }
6207                    }
6208
6209                    // If our editor should move focus when enter is pressed, or
6210                    // this is a generated event from an IME action button, then
6211                    // don't let it be inserted into the text.
6212                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
6213                            || shouldAdvanceFocusOnEnter()) {
6214                        if (hasOnClickListeners()) {
6215                            return KEY_EVENT_NOT_HANDLED;
6216                        }
6217                        return KEY_EVENT_HANDLED;
6218                    }
6219                }
6220                break;
6221
6222            case KeyEvent.KEYCODE_DPAD_CENTER:
6223                if (event.hasNoModifiers()) {
6224                    if (shouldAdvanceFocusOnEnter()) {
6225                        return KEY_EVENT_NOT_HANDLED;
6226                    }
6227                }
6228                break;
6229
6230            case KeyEvent.KEYCODE_TAB:
6231                if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
6232                    if (shouldAdvanceFocusOnTab()) {
6233                        return KEY_EVENT_NOT_HANDLED;
6234                    }
6235                }
6236                break;
6237
6238                // Has to be done on key down (and not on key up) to correctly be intercepted.
6239            case KeyEvent.KEYCODE_BACK:
6240                if (mEditor != null && mEditor.mTextActionMode != null) {
6241                    stopTextActionMode();
6242                    return KEY_EVENT_HANDLED;
6243                }
6244                break;
6245
6246            case KeyEvent.KEYCODE_CUT:
6247                if (event.hasNoModifiers() && canCut()) {
6248                    if (onTextContextMenuItem(ID_CUT)) {
6249                        return KEY_EVENT_HANDLED;
6250                    }
6251                }
6252                break;
6253
6254            case KeyEvent.KEYCODE_COPY:
6255                if (event.hasNoModifiers() && canCopy()) {
6256                    if (onTextContextMenuItem(ID_COPY)) {
6257                        return KEY_EVENT_HANDLED;
6258                    }
6259                }
6260                break;
6261
6262            case KeyEvent.KEYCODE_PASTE:
6263                if (event.hasNoModifiers() && canPaste()) {
6264                    if (onTextContextMenuItem(ID_PASTE)) {
6265                        return KEY_EVENT_HANDLED;
6266                    }
6267                }
6268                break;
6269        }
6270
6271        if (mEditor != null && mEditor.mKeyListener != null) {
6272            boolean doDown = true;
6273            if (otherEvent != null) {
6274                try {
6275                    beginBatchEdit();
6276                    final boolean handled = mEditor.mKeyListener.onKeyOther(this, (Editable) mText,
6277                            otherEvent);
6278                    hideErrorIfUnchanged();
6279                    doDown = false;
6280                    if (handled) {
6281                        return KEY_EVENT_HANDLED;
6282                    }
6283                } catch (AbstractMethodError e) {
6284                    // onKeyOther was added after 1.0, so if it isn't
6285                    // implemented we need to try to dispatch as a regular down.
6286                } finally {
6287                    endBatchEdit();
6288                }
6289            }
6290
6291            if (doDown) {
6292                beginBatchEdit();
6293                final boolean handled = mEditor.mKeyListener.onKeyDown(this, (Editable) mText,
6294                        keyCode, event);
6295                endBatchEdit();
6296                hideErrorIfUnchanged();
6297                if (handled) return KEY_DOWN_HANDLED_BY_KEY_LISTENER;
6298            }
6299        }
6300
6301        // bug 650865: sometimes we get a key event before a layout.
6302        // don't try to move around if we don't know the layout.
6303
6304        if (mMovement != null && mLayout != null) {
6305            boolean doDown = true;
6306            if (otherEvent != null) {
6307                try {
6308                    boolean handled = mMovement.onKeyOther(this, (Spannable) mText,
6309                            otherEvent);
6310                    doDown = false;
6311                    if (handled) {
6312                        return KEY_EVENT_HANDLED;
6313                    }
6314                } catch (AbstractMethodError e) {
6315                    // onKeyOther was added after 1.0, so if it isn't
6316                    // implemented we need to try to dispatch as a regular down.
6317                }
6318            }
6319            if (doDown) {
6320                if (mMovement.onKeyDown(this, (Spannable) mText, keyCode, event)) {
6321                    if (event.getRepeatCount() == 0 && !KeyEvent.isModifierKey(keyCode)) {
6322                        mPreventDefaultMovement = true;
6323                    }
6324                    return KEY_DOWN_HANDLED_BY_MOVEMENT_METHOD;
6325                }
6326            }
6327        }
6328
6329        return mPreventDefaultMovement && !KeyEvent.isModifierKey(keyCode)
6330                ? KEY_EVENT_HANDLED : KEY_EVENT_NOT_HANDLED;
6331    }
6332
6333    /**
6334     * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)}
6335     * can be recorded.
6336     * @hide
6337     */
6338    public void resetErrorChangedFlag() {
6339        /*
6340         * Keep track of what the error was before doing the input
6341         * so that if an input filter changed the error, we leave
6342         * that error showing.  Otherwise, we take down whatever
6343         * error was showing when the user types something.
6344         */
6345        if (mEditor != null) mEditor.mErrorWasChanged = false;
6346    }
6347
6348    /**
6349     * @hide
6350     */
6351    public void hideErrorIfUnchanged() {
6352        if (mEditor != null && mEditor.mError != null && !mEditor.mErrorWasChanged) {
6353            setError(null, null);
6354        }
6355    }
6356
6357    @Override
6358    public boolean onKeyUp(int keyCode, KeyEvent event) {
6359        if (!isEnabled()) {
6360            return super.onKeyUp(keyCode, event);
6361        }
6362
6363        if (!KeyEvent.isModifierKey(keyCode)) {
6364            mPreventDefaultMovement = false;
6365        }
6366
6367        switch (keyCode) {
6368            case KeyEvent.KEYCODE_DPAD_CENTER:
6369                if (event.hasNoModifiers()) {
6370                    /*
6371                     * If there is a click listener, just call through to
6372                     * super, which will invoke it.
6373                     *
6374                     * If there isn't a click listener, try to show the soft
6375                     * input method.  (It will also
6376                     * call performClick(), but that won't do anything in
6377                     * this case.)
6378                     */
6379                    if (!hasOnClickListeners()) {
6380                        if (mMovement != null && mText instanceof Editable
6381                                && mLayout != null && onCheckIsTextEditor()) {
6382                            InputMethodManager imm = InputMethodManager.peekInstance();
6383                            viewClicked(imm);
6384                            if (imm != null && getShowSoftInputOnFocus()) {
6385                                imm.showSoftInput(this, 0);
6386                            }
6387                        }
6388                    }
6389                }
6390                return super.onKeyUp(keyCode, event);
6391
6392            case KeyEvent.KEYCODE_ENTER:
6393                if (event.hasNoModifiers()) {
6394                    if (mEditor != null && mEditor.mInputContentType != null
6395                            && mEditor.mInputContentType.onEditorActionListener != null
6396                            && mEditor.mInputContentType.enterDown) {
6397                        mEditor.mInputContentType.enterDown = false;
6398                        if (mEditor.mInputContentType.onEditorActionListener.onEditorAction(
6399                                this, EditorInfo.IME_NULL, event)) {
6400                            return true;
6401                        }
6402                    }
6403
6404                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
6405                            || shouldAdvanceFocusOnEnter()) {
6406                        /*
6407                         * If there is a click listener, just call through to
6408                         * super, which will invoke it.
6409                         *
6410                         * If there isn't a click listener, try to advance focus,
6411                         * but still call through to super, which will reset the
6412                         * pressed state and longpress state.  (It will also
6413                         * call performClick(), but that won't do anything in
6414                         * this case.)
6415                         */
6416                        if (!hasOnClickListeners()) {
6417                            View v = focusSearch(FOCUS_DOWN);
6418
6419                            if (v != null) {
6420                                if (!v.requestFocus(FOCUS_DOWN)) {
6421                                    throw new IllegalStateException("focus search returned a view "
6422                                            + "that wasn't able to take focus!");
6423                                }
6424
6425                                /*
6426                                 * Return true because we handled the key; super
6427                                 * will return false because there was no click
6428                                 * listener.
6429                                 */
6430                                super.onKeyUp(keyCode, event);
6431                                return true;
6432                            } else if ((event.getFlags()
6433                                    & KeyEvent.FLAG_EDITOR_ACTION) != 0) {
6434                                // No target for next focus, but make sure the IME
6435                                // if this came from it.
6436                                InputMethodManager imm = InputMethodManager.peekInstance();
6437                                if (imm != null && imm.isActive(this)) {
6438                                    imm.hideSoftInputFromWindow(getWindowToken(), 0);
6439                                }
6440                            }
6441                        }
6442                    }
6443                    return super.onKeyUp(keyCode, event);
6444                }
6445                break;
6446        }
6447
6448        if (mEditor != null && mEditor.mKeyListener != null) {
6449            if (mEditor.mKeyListener.onKeyUp(this, (Editable) mText, keyCode, event)) {
6450                return true;
6451            }
6452        }
6453
6454        if (mMovement != null && mLayout != null) {
6455            if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event)) {
6456                return true;
6457            }
6458        }
6459
6460        return super.onKeyUp(keyCode, event);
6461    }
6462
6463    @Override
6464    public boolean onCheckIsTextEditor() {
6465        return mEditor != null && mEditor.mInputType != EditorInfo.TYPE_NULL;
6466    }
6467
6468    @Override
6469    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6470        if (onCheckIsTextEditor() && isEnabled()) {
6471            mEditor.createInputMethodStateIfNeeded();
6472            outAttrs.inputType = getInputType();
6473            if (mEditor.mInputContentType != null) {
6474                outAttrs.imeOptions = mEditor.mInputContentType.imeOptions;
6475                outAttrs.privateImeOptions = mEditor.mInputContentType.privateImeOptions;
6476                outAttrs.actionLabel = mEditor.mInputContentType.imeActionLabel;
6477                outAttrs.actionId = mEditor.mInputContentType.imeActionId;
6478                outAttrs.extras = mEditor.mInputContentType.extras;
6479                outAttrs.hintLocales = mEditor.mInputContentType.imeHintLocales;
6480            } else {
6481                outAttrs.imeOptions = EditorInfo.IME_NULL;
6482                outAttrs.hintLocales = null;
6483            }
6484            if (focusSearch(FOCUS_DOWN) != null) {
6485                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT;
6486            }
6487            if (focusSearch(FOCUS_UP) != null) {
6488                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS;
6489            }
6490            if ((outAttrs.imeOptions & EditorInfo.IME_MASK_ACTION)
6491                    == EditorInfo.IME_ACTION_UNSPECIFIED) {
6492                if ((outAttrs.imeOptions & EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) {
6493                    // An action has not been set, but the enter key will move to
6494                    // the next focus, so set the action to that.
6495                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT;
6496                } else {
6497                    // An action has not been set, and there is no focus to move
6498                    // to, so let's just supply a "done" action.
6499                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
6500                }
6501                if (!shouldAdvanceFocusOnEnter()) {
6502                    outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
6503                }
6504            }
6505            if (isMultilineInputType(outAttrs.inputType)) {
6506                // Multi-line text editors should always show an enter key.
6507                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
6508            }
6509            outAttrs.hintText = mHint;
6510            if (mText instanceof Editable) {
6511                InputConnection ic = new EditableInputConnection(this);
6512                outAttrs.initialSelStart = getSelectionStart();
6513                outAttrs.initialSelEnd = getSelectionEnd();
6514                outAttrs.initialCapsMode = ic.getCursorCapsMode(getInputType());
6515                return ic;
6516            }
6517        }
6518        return null;
6519    }
6520
6521    /**
6522     * If this TextView contains editable content, extract a portion of it
6523     * based on the information in <var>request</var> in to <var>outText</var>.
6524     * @return Returns true if the text was successfully extracted, else false.
6525     */
6526    public boolean extractText(ExtractedTextRequest request, ExtractedText outText) {
6527        createEditorIfNeeded();
6528        return mEditor.extractText(request, outText);
6529    }
6530
6531    /**
6532     * This is used to remove all style-impacting spans from text before new
6533     * extracted text is being replaced into it, so that we don't have any
6534     * lingering spans applied during the replace.
6535     */
6536    static void removeParcelableSpans(Spannable spannable, int start, int end) {
6537        Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class);
6538        int i = spans.length;
6539        while (i > 0) {
6540            i--;
6541            spannable.removeSpan(spans[i]);
6542        }
6543    }
6544
6545    /**
6546     * Apply to this text view the given extracted text, as previously
6547     * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}.
6548     */
6549    public void setExtractedText(ExtractedText text) {
6550        Editable content = getEditableText();
6551        if (text.text != null) {
6552            if (content == null) {
6553                setText(text.text, TextView.BufferType.EDITABLE);
6554            } else {
6555                int start = 0;
6556                int end = content.length();
6557
6558                if (text.partialStartOffset >= 0) {
6559                    final int N = content.length();
6560                    start = text.partialStartOffset;
6561                    if (start > N) start = N;
6562                    end = text.partialEndOffset;
6563                    if (end > N) end = N;
6564                }
6565
6566                removeParcelableSpans(content, start, end);
6567                if (TextUtils.equals(content.subSequence(start, end), text.text)) {
6568                    if (text.text instanceof Spanned) {
6569                        // OK to copy spans only.
6570                        TextUtils.copySpansFrom((Spanned) text.text, 0, end - start,
6571                                Object.class, content, start);
6572                    }
6573                } else {
6574                    content.replace(start, end, text.text);
6575                }
6576            }
6577        }
6578
6579        // Now set the selection position...  make sure it is in range, to
6580        // avoid crashes.  If this is a partial update, it is possible that
6581        // the underlying text may have changed, causing us problems here.
6582        // Also we just don't want to trust clients to do the right thing.
6583        Spannable sp = (Spannable) getText();
6584        final int N = sp.length();
6585        int start = text.selectionStart;
6586        if (start < 0) {
6587            start = 0;
6588        } else if (start > N) {
6589            start = N;
6590        }
6591        int end = text.selectionEnd;
6592        if (end < 0) {
6593            end = 0;
6594        } else if (end > N) {
6595            end = N;
6596        }
6597        Selection.setSelection(sp, start, end);
6598
6599        // Finally, update the selection mode.
6600        if ((text.flags & ExtractedText.FLAG_SELECTING) != 0) {
6601            MetaKeyKeyListener.startSelecting(this, sp);
6602        } else {
6603            MetaKeyKeyListener.stopSelecting(this, sp);
6604        }
6605    }
6606
6607    /**
6608     * @hide
6609     */
6610    public void setExtracting(ExtractedTextRequest req) {
6611        if (mEditor.mInputMethodState != null) {
6612            mEditor.mInputMethodState.mExtractedTextRequest = req;
6613        }
6614        // This would stop a possible selection mode, but no such mode is started in case
6615        // extracted mode will start. Some text is selected though, and will trigger an action mode
6616        // in the extracted view.
6617        mEditor.hideCursorAndSpanControllers();
6618        stopTextActionMode();
6619        if (mEditor.mSelectionModifierCursorController != null) {
6620            mEditor.mSelectionModifierCursorController.resetTouchOffsets();
6621        }
6622    }
6623
6624    /**
6625     * Called by the framework in response to a text completion from
6626     * the current input method, provided by it calling
6627     * {@link InputConnection#commitCompletion
6628     * InputConnection.commitCompletion()}.  The default implementation does
6629     * nothing; text views that are supporting auto-completion should override
6630     * this to do their desired behavior.
6631     *
6632     * @param text The auto complete text the user has selected.
6633     */
6634    public void onCommitCompletion(CompletionInfo text) {
6635        // intentionally empty
6636    }
6637
6638    /**
6639     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
6640     * a dictionary) from the current input method, provided by it calling
6641     * {@link InputConnection#commitCorrection(CorrectionInfo) InputConnection.commitCorrection()}.
6642     * The default implementation flashes the background of the corrected word to provide
6643     * feedback to the user.
6644     *
6645     * @param info The auto correct info about the text that was corrected.
6646     */
6647    public void onCommitCorrection(CorrectionInfo info) {
6648        if (mEditor != null) mEditor.onCommitCorrection(info);
6649    }
6650
6651    public void beginBatchEdit() {
6652        if (mEditor != null) mEditor.beginBatchEdit();
6653    }
6654
6655    public void endBatchEdit() {
6656        if (mEditor != null) mEditor.endBatchEdit();
6657    }
6658
6659    /**
6660     * Called by the framework in response to a request to begin a batch
6661     * of edit operations through a call to link {@link #beginBatchEdit()}.
6662     */
6663    public void onBeginBatchEdit() {
6664        // intentionally empty
6665    }
6666
6667    /**
6668     * Called by the framework in response to a request to end a batch
6669     * of edit operations through a call to link {@link #endBatchEdit}.
6670     */
6671    public void onEndBatchEdit() {
6672        // intentionally empty
6673    }
6674
6675    /**
6676     * Called by the framework in response to a private command from the
6677     * current method, provided by it calling
6678     * {@link InputConnection#performPrivateCommand
6679     * InputConnection.performPrivateCommand()}.
6680     *
6681     * @param action The action name of the command.
6682     * @param data Any additional data for the command.  This may be null.
6683     * @return Return true if you handled the command, else false.
6684     */
6685    public boolean onPrivateIMECommand(String action, Bundle data) {
6686        return false;
6687    }
6688
6689    private void nullLayouts() {
6690        if (mLayout instanceof BoringLayout && mSavedLayout == null) {
6691            mSavedLayout = (BoringLayout) mLayout;
6692        }
6693        if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) {
6694            mSavedHintLayout = (BoringLayout) mHintLayout;
6695        }
6696
6697        mSavedMarqueeModeLayout = mLayout = mHintLayout = null;
6698
6699        mBoring = mHintBoring = null;
6700
6701        // Since it depends on the value of mLayout
6702        if (mEditor != null) mEditor.prepareCursorControllers();
6703    }
6704
6705    /**
6706     * Make a new Layout based on the already-measured size of the view,
6707     * on the assumption that it was measured correctly at some point.
6708     */
6709    private void assumeLayout() {
6710        int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6711
6712        if (width < 1) {
6713            width = 0;
6714        }
6715
6716        int physicalWidth = width;
6717
6718        if (mHorizontallyScrolling) {
6719            width = VERY_WIDE;
6720        }
6721
6722        makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING,
6723                      physicalWidth, false);
6724    }
6725
6726    private Layout.Alignment getLayoutAlignment() {
6727        Layout.Alignment alignment;
6728        switch (getTextAlignment()) {
6729            case TEXT_ALIGNMENT_GRAVITY:
6730                switch (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) {
6731                    case Gravity.START:
6732                        alignment = Layout.Alignment.ALIGN_NORMAL;
6733                        break;
6734                    case Gravity.END:
6735                        alignment = Layout.Alignment.ALIGN_OPPOSITE;
6736                        break;
6737                    case Gravity.LEFT:
6738                        alignment = Layout.Alignment.ALIGN_LEFT;
6739                        break;
6740                    case Gravity.RIGHT:
6741                        alignment = Layout.Alignment.ALIGN_RIGHT;
6742                        break;
6743                    case Gravity.CENTER_HORIZONTAL:
6744                        alignment = Layout.Alignment.ALIGN_CENTER;
6745                        break;
6746                    default:
6747                        alignment = Layout.Alignment.ALIGN_NORMAL;
6748                        break;
6749                }
6750                break;
6751            case TEXT_ALIGNMENT_TEXT_START:
6752                alignment = Layout.Alignment.ALIGN_NORMAL;
6753                break;
6754            case TEXT_ALIGNMENT_TEXT_END:
6755                alignment = Layout.Alignment.ALIGN_OPPOSITE;
6756                break;
6757            case TEXT_ALIGNMENT_CENTER:
6758                alignment = Layout.Alignment.ALIGN_CENTER;
6759                break;
6760            case TEXT_ALIGNMENT_VIEW_START:
6761                alignment = (getLayoutDirection() == LAYOUT_DIRECTION_RTL)
6762                        ? Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT;
6763                break;
6764            case TEXT_ALIGNMENT_VIEW_END:
6765                alignment = (getLayoutDirection() == LAYOUT_DIRECTION_RTL)
6766                        ? Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT;
6767                break;
6768            case TEXT_ALIGNMENT_INHERIT:
6769                // This should never happen as we have already resolved the text alignment
6770                // but better safe than sorry so we just fall through
6771            default:
6772                alignment = Layout.Alignment.ALIGN_NORMAL;
6773                break;
6774        }
6775        return alignment;
6776    }
6777
6778    /**
6779     * The width passed in is now the desired layout width,
6780     * not the full view width with padding.
6781     * {@hide}
6782     */
6783    protected void makeNewLayout(int wantWidth, int hintWidth,
6784                                 BoringLayout.Metrics boring,
6785                                 BoringLayout.Metrics hintBoring,
6786                                 int ellipsisWidth, boolean bringIntoView) {
6787        stopMarquee();
6788
6789        // Update "old" cached values
6790        mOldMaximum = mMaximum;
6791        mOldMaxMode = mMaxMode;
6792
6793        mHighlightPathBogus = true;
6794
6795        if (wantWidth < 0) {
6796            wantWidth = 0;
6797        }
6798        if (hintWidth < 0) {
6799            hintWidth = 0;
6800        }
6801
6802        Layout.Alignment alignment = getLayoutAlignment();
6803        final boolean testDirChange = mSingleLine && mLayout != null
6804                && (alignment == Layout.Alignment.ALIGN_NORMAL
6805                        || alignment == Layout.Alignment.ALIGN_OPPOSITE);
6806        int oldDir = 0;
6807        if (testDirChange) oldDir = mLayout.getParagraphDirection(0);
6808        boolean shouldEllipsize = mEllipsize != null && getKeyListener() == null;
6809        final boolean switchEllipsize = mEllipsize == TruncateAt.MARQUEE
6810                && mMarqueeFadeMode != MARQUEE_FADE_NORMAL;
6811        TruncateAt effectiveEllipsize = mEllipsize;
6812        if (mEllipsize == TruncateAt.MARQUEE
6813                && mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
6814            effectiveEllipsize = TruncateAt.END_SMALL;
6815        }
6816
6817        if (mTextDir == null) {
6818            mTextDir = getTextDirectionHeuristic();
6819        }
6820
6821        mLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize,
6822                effectiveEllipsize, effectiveEllipsize == mEllipsize);
6823        if (switchEllipsize) {
6824            TruncateAt oppositeEllipsize = effectiveEllipsize == TruncateAt.MARQUEE
6825                    ? TruncateAt.END : TruncateAt.MARQUEE;
6826            mSavedMarqueeModeLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment,
6827                    shouldEllipsize, oppositeEllipsize, effectiveEllipsize != mEllipsize);
6828        }
6829
6830        shouldEllipsize = mEllipsize != null;
6831        mHintLayout = null;
6832
6833        if (mHint != null) {
6834            if (shouldEllipsize) hintWidth = wantWidth;
6835
6836            if (hintBoring == UNKNOWN_BORING) {
6837                hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir,
6838                                                   mHintBoring);
6839                if (hintBoring != null) {
6840                    mHintBoring = hintBoring;
6841                }
6842            }
6843
6844            if (hintBoring != null) {
6845                if (hintBoring.width <= hintWidth
6846                        && (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) {
6847                    if (mSavedHintLayout != null) {
6848                        mHintLayout = mSavedHintLayout.replaceOrMake(mHint, mTextPaint,
6849                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6850                                hintBoring, mIncludePad);
6851                    } else {
6852                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
6853                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6854                                hintBoring, mIncludePad);
6855                    }
6856
6857                    mSavedHintLayout = (BoringLayout) mHintLayout;
6858                } else if (shouldEllipsize && hintBoring.width <= hintWidth) {
6859                    if (mSavedHintLayout != null) {
6860                        mHintLayout = mSavedHintLayout.replaceOrMake(mHint, mTextPaint,
6861                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6862                                hintBoring, mIncludePad, mEllipsize,
6863                                ellipsisWidth);
6864                    } else {
6865                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
6866                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6867                                hintBoring, mIncludePad, mEllipsize,
6868                                ellipsisWidth);
6869                    }
6870                }
6871            }
6872            // TODO: code duplication with makeSingleLayout()
6873            if (mHintLayout == null) {
6874                StaticLayout.Builder builder = StaticLayout.Builder.obtain(mHint, 0,
6875                        mHint.length(), mTextPaint, hintWidth)
6876                        .setAlignment(alignment)
6877                        .setTextDirection(mTextDir)
6878                        .setLineSpacing(mSpacingAdd, mSpacingMult)
6879                        .setIncludePad(mIncludePad)
6880                        .setBreakStrategy(mBreakStrategy)
6881                        .setHyphenationFrequency(mHyphenationFrequency);
6882                if (shouldEllipsize) {
6883                    builder.setEllipsize(mEllipsize)
6884                            .setEllipsizedWidth(ellipsisWidth)
6885                            .setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
6886                }
6887                mHintLayout = builder.build();
6888            }
6889        }
6890
6891        if (bringIntoView || (testDirChange && oldDir != mLayout.getParagraphDirection(0))) {
6892            registerForPreDraw();
6893        }
6894
6895        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6896            if (!compressText(ellipsisWidth)) {
6897                final int height = mLayoutParams.height;
6898                // If the size of the view does not depend on the size of the text, try to
6899                // start the marquee immediately
6900                if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) {
6901                    startMarquee();
6902                } else {
6903                    // Defer the start of the marquee until we know our width (see setFrame())
6904                    mRestartMarquee = true;
6905                }
6906            }
6907        }
6908
6909        // CursorControllers need a non-null mLayout
6910        if (mEditor != null) mEditor.prepareCursorControllers();
6911    }
6912
6913    /**
6914     * @hide
6915     */
6916    protected Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth,
6917            Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize,
6918            boolean useSaved) {
6919        Layout result = null;
6920        if (mText instanceof Spannable) {
6921            result = new DynamicLayout(mText, mTransformed, mTextPaint, wantWidth,
6922                    alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad,
6923                    mBreakStrategy, mHyphenationFrequency,
6924                    getKeyListener() == null ? effectiveEllipsize : null, ellipsisWidth);
6925        } else {
6926            if (boring == UNKNOWN_BORING) {
6927                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
6928                if (boring != null) {
6929                    mBoring = boring;
6930                }
6931            }
6932
6933            if (boring != null) {
6934                if (boring.width <= wantWidth
6935                        && (effectiveEllipsize == null || boring.width <= ellipsisWidth)) {
6936                    if (useSaved && mSavedLayout != null) {
6937                        result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint,
6938                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
6939                                boring, mIncludePad);
6940                    } else {
6941                        result = BoringLayout.make(mTransformed, mTextPaint,
6942                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
6943                                boring, mIncludePad);
6944                    }
6945
6946                    if (useSaved) {
6947                        mSavedLayout = (BoringLayout) result;
6948                    }
6949                } else if (shouldEllipsize && boring.width <= wantWidth) {
6950                    if (useSaved && mSavedLayout != null) {
6951                        result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint,
6952                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
6953                                boring, mIncludePad, effectiveEllipsize,
6954                                ellipsisWidth);
6955                    } else {
6956                        result = BoringLayout.make(mTransformed, mTextPaint,
6957                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
6958                                boring, mIncludePad, effectiveEllipsize,
6959                                ellipsisWidth);
6960                    }
6961                }
6962            }
6963        }
6964        if (result == null) {
6965            StaticLayout.Builder builder = StaticLayout.Builder.obtain(mTransformed,
6966                    0, mTransformed.length(), mTextPaint, wantWidth)
6967                    .setAlignment(alignment)
6968                    .setTextDirection(mTextDir)
6969                    .setLineSpacing(mSpacingAdd, mSpacingMult)
6970                    .setIncludePad(mIncludePad)
6971                    .setBreakStrategy(mBreakStrategy)
6972                    .setHyphenationFrequency(mHyphenationFrequency);
6973            if (shouldEllipsize) {
6974                builder.setEllipsize(effectiveEllipsize)
6975                        .setEllipsizedWidth(ellipsisWidth)
6976                        .setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
6977            }
6978            // TODO: explore always setting maxLines
6979            result = builder.build();
6980        }
6981        return result;
6982    }
6983
6984    private boolean compressText(float width) {
6985        if (isHardwareAccelerated()) return false;
6986
6987        // Only compress the text if it hasn't been compressed by the previous pass
6988        if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX
6989                && mTextPaint.getTextScaleX() == 1.0f) {
6990            final float textWidth = mLayout.getLineWidth(0);
6991            final float overflow = (textWidth + 1.0f - width) / width;
6992            if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) {
6993                mTextPaint.setTextScaleX(1.0f - overflow - 0.005f);
6994                post(new Runnable() {
6995                    public void run() {
6996                        requestLayout();
6997                    }
6998                });
6999                return true;
7000            }
7001        }
7002
7003        return false;
7004    }
7005
7006    private static int desired(Layout layout) {
7007        int n = layout.getLineCount();
7008        CharSequence text = layout.getText();
7009        float max = 0;
7010
7011        // if any line was wrapped, we can't use it.
7012        // but it's ok for the last line not to have a newline
7013
7014        for (int i = 0; i < n - 1; i++) {
7015            if (text.charAt(layout.getLineEnd(i) - 1) != '\n') {
7016                return -1;
7017            }
7018        }
7019
7020        for (int i = 0; i < n; i++) {
7021            max = Math.max(max, layout.getLineWidth(i));
7022        }
7023
7024        return (int) Math.ceil(max);
7025    }
7026
7027    /**
7028     * Set whether the TextView includes extra top and bottom padding to make
7029     * room for accents that go above the normal ascent and descent.
7030     * The default is true.
7031     *
7032     * @see #getIncludeFontPadding()
7033     *
7034     * @attr ref android.R.styleable#TextView_includeFontPadding
7035     */
7036    public void setIncludeFontPadding(boolean includepad) {
7037        if (mIncludePad != includepad) {
7038            mIncludePad = includepad;
7039
7040            if (mLayout != null) {
7041                nullLayouts();
7042                requestLayout();
7043                invalidate();
7044            }
7045        }
7046    }
7047
7048    /**
7049     * Gets whether the TextView includes extra top and bottom padding to make
7050     * room for accents that go above the normal ascent and descent.
7051     *
7052     * @see #setIncludeFontPadding(boolean)
7053     *
7054     * @attr ref android.R.styleable#TextView_includeFontPadding
7055     */
7056    public boolean getIncludeFontPadding() {
7057        return mIncludePad;
7058    }
7059
7060    private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics();
7061
7062    @Override
7063    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
7064        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
7065        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
7066        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
7067        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
7068
7069        int width;
7070        int height;
7071
7072        BoringLayout.Metrics boring = UNKNOWN_BORING;
7073        BoringLayout.Metrics hintBoring = UNKNOWN_BORING;
7074
7075        if (mTextDir == null) {
7076            mTextDir = getTextDirectionHeuristic();
7077        }
7078
7079        int des = -1;
7080        boolean fromexisting = false;
7081
7082        if (widthMode == MeasureSpec.EXACTLY) {
7083            // Parent has told us how big to be. So be it.
7084            width = widthSize;
7085        } else {
7086            if (mLayout != null && mEllipsize == null) {
7087                des = desired(mLayout);
7088            }
7089
7090            if (des < 0) {
7091                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
7092                if (boring != null) {
7093                    mBoring = boring;
7094                }
7095            } else {
7096                fromexisting = true;
7097            }
7098
7099            if (boring == null || boring == UNKNOWN_BORING) {
7100                if (des < 0) {
7101                    des = (int) Math.ceil(Layout.getDesiredWidth(mTransformed, 0,
7102                            mTransformed.length(), mTextPaint, mTextDir));
7103                }
7104                width = des;
7105            } else {
7106                width = boring.width;
7107            }
7108
7109            final Drawables dr = mDrawables;
7110            if (dr != null) {
7111                width = Math.max(width, dr.mDrawableWidthTop);
7112                width = Math.max(width, dr.mDrawableWidthBottom);
7113            }
7114
7115            if (mHint != null) {
7116                int hintDes = -1;
7117                int hintWidth;
7118
7119                if (mHintLayout != null && mEllipsize == null) {
7120                    hintDes = desired(mHintLayout);
7121                }
7122
7123                if (hintDes < 0) {
7124                    hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, mHintBoring);
7125                    if (hintBoring != null) {
7126                        mHintBoring = hintBoring;
7127                    }
7128                }
7129
7130                if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
7131                    if (hintDes < 0) {
7132                        hintDes = (int) Math.ceil(Layout.getDesiredWidth(mHint, 0, mHint.length(),
7133                                mTextPaint, mTextDir));
7134                    }
7135                    hintWidth = hintDes;
7136                } else {
7137                    hintWidth = hintBoring.width;
7138                }
7139
7140                if (hintWidth > width) {
7141                    width = hintWidth;
7142                }
7143            }
7144
7145            width += getCompoundPaddingLeft() + getCompoundPaddingRight();
7146
7147            if (mMaxWidthMode == EMS) {
7148                width = Math.min(width, mMaxWidth * getLineHeight());
7149            } else {
7150                width = Math.min(width, mMaxWidth);
7151            }
7152
7153            if (mMinWidthMode == EMS) {
7154                width = Math.max(width, mMinWidth * getLineHeight());
7155            } else {
7156                width = Math.max(width, mMinWidth);
7157            }
7158
7159            // Check against our minimum width
7160            width = Math.max(width, getSuggestedMinimumWidth());
7161
7162            if (widthMode == MeasureSpec.AT_MOST) {
7163                width = Math.min(widthSize, width);
7164            }
7165        }
7166
7167        int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight();
7168        int unpaddedWidth = want;
7169
7170        if (mHorizontallyScrolling) want = VERY_WIDE;
7171
7172        int hintWant = want;
7173        int hintWidth = (mHintLayout == null) ? hintWant : mHintLayout.getWidth();
7174
7175        if (mLayout == null) {
7176            makeNewLayout(want, hintWant, boring, hintBoring,
7177                          width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
7178        } else {
7179            final boolean layoutChanged = (mLayout.getWidth() != want) || (hintWidth != hintWant)
7180                    || (mLayout.getEllipsizedWidth()
7181                            != width - getCompoundPaddingLeft() - getCompoundPaddingRight());
7182
7183            final boolean widthChanged = (mHint == null) && (mEllipsize == null)
7184                    && (want > mLayout.getWidth())
7185                    && (mLayout instanceof BoringLayout
7186                            || (fromexisting && des >= 0 && des <= want));
7187
7188            final boolean maximumChanged = (mMaxMode != mOldMaxMode) || (mMaximum != mOldMaximum);
7189
7190            if (layoutChanged || maximumChanged) {
7191                if (!maximumChanged && widthChanged) {
7192                    mLayout.increaseWidthTo(want);
7193                } else {
7194                    makeNewLayout(want, hintWant, boring, hintBoring,
7195                            width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
7196                }
7197            } else {
7198                // Nothing has changed
7199            }
7200        }
7201
7202        if (heightMode == MeasureSpec.EXACTLY) {
7203            // Parent has told us how big to be. So be it.
7204            height = heightSize;
7205            mDesiredHeightAtMeasure = -1;
7206        } else {
7207            int desired = getDesiredHeight();
7208
7209            height = desired;
7210            mDesiredHeightAtMeasure = desired;
7211
7212            if (heightMode == MeasureSpec.AT_MOST) {
7213                height = Math.min(desired, heightSize);
7214            }
7215        }
7216
7217        int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
7218        if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) {
7219            unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum));
7220        }
7221
7222        /*
7223         * We didn't let makeNewLayout() register to bring the cursor into view,
7224         * so do it here if there is any possibility that it is needed.
7225         */
7226        if (mMovement != null
7227                || mLayout.getWidth() > unpaddedWidth
7228                || mLayout.getHeight() > unpaddedHeight) {
7229            registerForPreDraw();
7230        } else {
7231            scrollTo(0, 0);
7232        }
7233
7234        setMeasuredDimension(width, height);
7235    }
7236
7237    private int getDesiredHeight() {
7238        return Math.max(
7239                getDesiredHeight(mLayout, true),
7240                getDesiredHeight(mHintLayout, mEllipsize != null));
7241    }
7242
7243    private int getDesiredHeight(Layout layout, boolean cap) {
7244        if (layout == null) {
7245            return 0;
7246        }
7247
7248        int linecount = layout.getLineCount();
7249        int pad = getCompoundPaddingTop() + getCompoundPaddingBottom();
7250        int desired = layout.getLineTop(linecount);
7251
7252        final Drawables dr = mDrawables;
7253        if (dr != null) {
7254            desired = Math.max(desired, dr.mDrawableHeightLeft);
7255            desired = Math.max(desired, dr.mDrawableHeightRight);
7256        }
7257
7258        desired += pad;
7259
7260        if (mMaxMode == LINES) {
7261            /*
7262             * Don't cap the hint to a certain number of lines.
7263             * (Do cap it, though, if we have a maximum pixel height.)
7264             */
7265            if (cap) {
7266                if (linecount > mMaximum) {
7267                    desired = layout.getLineTop(mMaximum);
7268
7269                    if (dr != null) {
7270                        desired = Math.max(desired, dr.mDrawableHeightLeft);
7271                        desired = Math.max(desired, dr.mDrawableHeightRight);
7272                    }
7273
7274                    desired += pad;
7275                    linecount = mMaximum;
7276                }
7277            }
7278        } else {
7279            desired = Math.min(desired, mMaximum);
7280        }
7281
7282        if (mMinMode == LINES) {
7283            if (linecount < mMinimum) {
7284                desired += getLineHeight() * (mMinimum - linecount);
7285            }
7286        } else {
7287            desired = Math.max(desired, mMinimum);
7288        }
7289
7290        // Check against our minimum height
7291        desired = Math.max(desired, getSuggestedMinimumHeight());
7292
7293        return desired;
7294    }
7295
7296    /**
7297     * Check whether a change to the existing text layout requires a
7298     * new view layout.
7299     */
7300    private void checkForResize() {
7301        boolean sizeChanged = false;
7302
7303        if (mLayout != null) {
7304            // Check if our width changed
7305            if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) {
7306                sizeChanged = true;
7307                invalidate();
7308            }
7309
7310            // Check if our height changed
7311            if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) {
7312                int desiredHeight = getDesiredHeight();
7313
7314                if (desiredHeight != this.getHeight()) {
7315                    sizeChanged = true;
7316                }
7317            } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) {
7318                if (mDesiredHeightAtMeasure >= 0) {
7319                    int desiredHeight = getDesiredHeight();
7320
7321                    if (desiredHeight != mDesiredHeightAtMeasure) {
7322                        sizeChanged = true;
7323                    }
7324                }
7325            }
7326        }
7327
7328        if (sizeChanged) {
7329            requestLayout();
7330            // caller will have already invalidated
7331        }
7332    }
7333
7334    /**
7335     * Check whether entirely new text requires a new view layout
7336     * or merely a new text layout.
7337     */
7338    private void checkForRelayout() {
7339        // If we have a fixed width, we can just swap in a new text layout
7340        // if the text height stays the same or if the view height is fixed.
7341
7342        if (((mLayoutParams.width != LayoutParams.WRAP_CONTENT && mLayoutParams.width != 0)
7343                || (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth))
7344                && (mHint == null || mHintLayout != null)
7345                && (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) {
7346            // Static width, so try making a new text layout.
7347
7348            int oldht = mLayout.getHeight();
7349            int want = mLayout.getWidth();
7350            int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();
7351
7352            /*
7353             * No need to bring the text into view, since the size is not
7354             * changing (unless we do the requestLayout(), in which case it
7355             * will happen at measure).
7356             */
7357            makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
7358                          mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(),
7359                          false);
7360
7361            if (mEllipsize != TextUtils.TruncateAt.MARQUEE) {
7362                // In a fixed-height view, so use our new text layout.
7363                if (mLayoutParams.height != LayoutParams.WRAP_CONTENT
7364                        && mLayoutParams.height != LayoutParams.MATCH_PARENT) {
7365                    invalidate();
7366                    return;
7367                }
7368
7369                // Dynamic height, but height has stayed the same,
7370                // so use our new text layout.
7371                if (mLayout.getHeight() == oldht
7372                        && (mHintLayout == null || mHintLayout.getHeight() == oldht)) {
7373                    invalidate();
7374                    return;
7375                }
7376            }
7377
7378            // We lose: the height has changed and we have a dynamic height.
7379            // Request a new view layout using our new text layout.
7380            requestLayout();
7381            invalidate();
7382        } else {
7383            // Dynamic width, so we have no choice but to request a new
7384            // view layout with a new text layout.
7385            nullLayouts();
7386            requestLayout();
7387            invalidate();
7388        }
7389    }
7390
7391    @Override
7392    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
7393        super.onLayout(changed, left, top, right, bottom);
7394        if (mDeferScroll >= 0) {
7395            int curs = mDeferScroll;
7396            mDeferScroll = -1;
7397            bringPointIntoView(Math.min(curs, mText.length()));
7398        }
7399    }
7400
7401    private boolean isShowingHint() {
7402        return TextUtils.isEmpty(mText) && !TextUtils.isEmpty(mHint);
7403    }
7404
7405    /**
7406     * Returns true if anything changed.
7407     */
7408    private boolean bringTextIntoView() {
7409        Layout layout = isShowingHint() ? mHintLayout : mLayout;
7410        int line = 0;
7411        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
7412            line = layout.getLineCount() - 1;
7413        }
7414
7415        Layout.Alignment a = layout.getParagraphAlignment(line);
7416        int dir = layout.getParagraphDirection(line);
7417        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
7418        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
7419        int ht = layout.getHeight();
7420
7421        int scrollx, scrolly;
7422
7423        // Convert to left, center, or right alignment.
7424        if (a == Layout.Alignment.ALIGN_NORMAL) {
7425            a = dir == Layout.DIR_LEFT_TO_RIGHT
7426                    ? Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT;
7427        } else if (a == Layout.Alignment.ALIGN_OPPOSITE) {
7428            a = dir == Layout.DIR_LEFT_TO_RIGHT
7429                    ? Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT;
7430        }
7431
7432        if (a == Layout.Alignment.ALIGN_CENTER) {
7433            /*
7434             * Keep centered if possible, or, if it is too wide to fit,
7435             * keep leading edge in view.
7436             */
7437
7438            int left = (int) Math.floor(layout.getLineLeft(line));
7439            int right = (int) Math.ceil(layout.getLineRight(line));
7440
7441            if (right - left < hspace) {
7442                scrollx = (right + left) / 2 - hspace / 2;
7443            } else {
7444                if (dir < 0) {
7445                    scrollx = right - hspace;
7446                } else {
7447                    scrollx = left;
7448                }
7449            }
7450        } else if (a == Layout.Alignment.ALIGN_RIGHT) {
7451            int right = (int) Math.ceil(layout.getLineRight(line));
7452            scrollx = right - hspace;
7453        } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default)
7454            scrollx = (int) Math.floor(layout.getLineLeft(line));
7455        }
7456
7457        if (ht < vspace) {
7458            scrolly = 0;
7459        } else {
7460            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
7461                scrolly = ht - vspace;
7462            } else {
7463                scrolly = 0;
7464            }
7465        }
7466
7467        if (scrollx != mScrollX || scrolly != mScrollY) {
7468            scrollTo(scrollx, scrolly);
7469            return true;
7470        } else {
7471            return false;
7472        }
7473    }
7474
7475    /**
7476     * Move the point, specified by the offset, into the view if it is needed.
7477     * This has to be called after layout. Returns true if anything changed.
7478     */
7479    public boolean bringPointIntoView(int offset) {
7480        if (isLayoutRequested()) {
7481            mDeferScroll = offset;
7482            return false;
7483        }
7484        boolean changed = false;
7485
7486        Layout layout = isShowingHint() ? mHintLayout : mLayout;
7487
7488        if (layout == null) return changed;
7489
7490        int line = layout.getLineForOffset(offset);
7491
7492        int grav;
7493
7494        switch (layout.getParagraphAlignment(line)) {
7495            case ALIGN_LEFT:
7496                grav = 1;
7497                break;
7498            case ALIGN_RIGHT:
7499                grav = -1;
7500                break;
7501            case ALIGN_NORMAL:
7502                grav = layout.getParagraphDirection(line);
7503                break;
7504            case ALIGN_OPPOSITE:
7505                grav = -layout.getParagraphDirection(line);
7506                break;
7507            case ALIGN_CENTER:
7508            default:
7509                grav = 0;
7510                break;
7511        }
7512
7513        // We only want to clamp the cursor to fit within the layout width
7514        // in left-to-right modes, because in a right to left alignment,
7515        // we want to scroll to keep the line-right on the screen, as other
7516        // lines are likely to have text flush with the right margin, which
7517        // we want to keep visible.
7518        // A better long-term solution would probably be to measure both
7519        // the full line and a blank-trimmed version, and, for example, use
7520        // the latter measurement for centering and right alignment, but for
7521        // the time being we only implement the cursor clamping in left to
7522        // right where it is most likely to be annoying.
7523        final boolean clamped = grav > 0;
7524        // FIXME: Is it okay to truncate this, or should we round?
7525        final int x = (int) layout.getPrimaryHorizontal(offset, clamped);
7526        final int top = layout.getLineTop(line);
7527        final int bottom = layout.getLineTop(line + 1);
7528
7529        int left = (int) Math.floor(layout.getLineLeft(line));
7530        int right = (int) Math.ceil(layout.getLineRight(line));
7531        int ht = layout.getHeight();
7532
7533        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
7534        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
7535        if (!mHorizontallyScrolling && right - left > hspace && right > x) {
7536            // If cursor has been clamped, make sure we don't scroll.
7537            right = Math.max(x, left + hspace);
7538        }
7539
7540        int hslack = (bottom - top) / 2;
7541        int vslack = hslack;
7542
7543        if (vslack > vspace / 4) {
7544            vslack = vspace / 4;
7545        }
7546        if (hslack > hspace / 4) {
7547            hslack = hspace / 4;
7548        }
7549
7550        int hs = mScrollX;
7551        int vs = mScrollY;
7552
7553        if (top - vs < vslack) {
7554            vs = top - vslack;
7555        }
7556        if (bottom - vs > vspace - vslack) {
7557            vs = bottom - (vspace - vslack);
7558        }
7559        if (ht - vs < vspace) {
7560            vs = ht - vspace;
7561        }
7562        if (0 - vs > 0) {
7563            vs = 0;
7564        }
7565
7566        if (grav != 0) {
7567            if (x - hs < hslack) {
7568                hs = x - hslack;
7569            }
7570            if (x - hs > hspace - hslack) {
7571                hs = x - (hspace - hslack);
7572            }
7573        }
7574
7575        if (grav < 0) {
7576            if (left - hs > 0) {
7577                hs = left;
7578            }
7579            if (right - hs < hspace) {
7580                hs = right - hspace;
7581            }
7582        } else if (grav > 0) {
7583            if (right - hs < hspace) {
7584                hs = right - hspace;
7585            }
7586            if (left - hs > 0) {
7587                hs = left;
7588            }
7589        } else /* grav == 0 */ {
7590            if (right - left <= hspace) {
7591                /*
7592                 * If the entire text fits, center it exactly.
7593                 */
7594                hs = left - (hspace - (right - left)) / 2;
7595            } else if (x > right - hslack) {
7596                /*
7597                 * If we are near the right edge, keep the right edge
7598                 * at the edge of the view.
7599                 */
7600                hs = right - hspace;
7601            } else if (x < left + hslack) {
7602                /*
7603                 * If we are near the left edge, keep the left edge
7604                 * at the edge of the view.
7605                 */
7606                hs = left;
7607            } else if (left > hs) {
7608                /*
7609                 * Is there whitespace visible at the left?  Fix it if so.
7610                 */
7611                hs = left;
7612            } else if (right < hs + hspace) {
7613                /*
7614                 * Is there whitespace visible at the right?  Fix it if so.
7615                 */
7616                hs = right - hspace;
7617            } else {
7618                /*
7619                 * Otherwise, float as needed.
7620                 */
7621                if (x - hs < hslack) {
7622                    hs = x - hslack;
7623                }
7624                if (x - hs > hspace - hslack) {
7625                    hs = x - (hspace - hslack);
7626                }
7627            }
7628        }
7629
7630        if (hs != mScrollX || vs != mScrollY) {
7631            if (mScroller == null) {
7632                scrollTo(hs, vs);
7633            } else {
7634                long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
7635                int dx = hs - mScrollX;
7636                int dy = vs - mScrollY;
7637
7638                if (duration > ANIMATED_SCROLL_GAP) {
7639                    mScroller.startScroll(mScrollX, mScrollY, dx, dy);
7640                    awakenScrollBars(mScroller.getDuration());
7641                    invalidate();
7642                } else {
7643                    if (!mScroller.isFinished()) {
7644                        mScroller.abortAnimation();
7645                    }
7646
7647                    scrollBy(dx, dy);
7648                }
7649
7650                mLastScroll = AnimationUtils.currentAnimationTimeMillis();
7651            }
7652
7653            changed = true;
7654        }
7655
7656        if (isFocused()) {
7657            // This offsets because getInterestingRect() is in terms of viewport coordinates, but
7658            // requestRectangleOnScreen() is in terms of content coordinates.
7659
7660            // The offsets here are to ensure the rectangle we are using is
7661            // within our view bounds, in case the cursor is on the far left
7662            // or right.  If it isn't withing the bounds, then this request
7663            // will be ignored.
7664            if (mTempRect == null) mTempRect = new Rect();
7665            mTempRect.set(x - 2, top, x + 2, bottom);
7666            getInterestingRect(mTempRect, line);
7667            mTempRect.offset(mScrollX, mScrollY);
7668
7669            if (requestRectangleOnScreen(mTempRect)) {
7670                changed = true;
7671            }
7672        }
7673
7674        return changed;
7675    }
7676
7677    /**
7678     * Move the cursor, if needed, so that it is at an offset that is visible
7679     * to the user.  This will not move the cursor if it represents more than
7680     * one character (a selection range).  This will only work if the
7681     * TextView contains spannable text; otherwise it will do nothing.
7682     *
7683     * @return True if the cursor was actually moved, false otherwise.
7684     */
7685    public boolean moveCursorToVisibleOffset() {
7686        if (!(mText instanceof Spannable)) {
7687            return false;
7688        }
7689        int start = getSelectionStart();
7690        int end = getSelectionEnd();
7691        if (start != end) {
7692            return false;
7693        }
7694
7695        // First: make sure the line is visible on screen:
7696
7697        int line = mLayout.getLineForOffset(start);
7698
7699        final int top = mLayout.getLineTop(line);
7700        final int bottom = mLayout.getLineTop(line + 1);
7701        final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
7702        int vslack = (bottom - top) / 2;
7703        if (vslack > vspace / 4) {
7704            vslack = vspace / 4;
7705        }
7706        final int vs = mScrollY;
7707
7708        if (top < (vs + vslack)) {
7709            line = mLayout.getLineForVertical(vs + vslack + (bottom - top));
7710        } else if (bottom > (vspace + vs - vslack)) {
7711            line = mLayout.getLineForVertical(vspace + vs - vslack - (bottom - top));
7712        }
7713
7714        // Next: make sure the character is visible on screen:
7715
7716        final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
7717        final int hs = mScrollX;
7718        final int leftChar = mLayout.getOffsetForHorizontal(line, hs);
7719        final int rightChar = mLayout.getOffsetForHorizontal(line, hspace + hs);
7720
7721        // line might contain bidirectional text
7722        final int lowChar = leftChar < rightChar ? leftChar : rightChar;
7723        final int highChar = leftChar > rightChar ? leftChar : rightChar;
7724
7725        int newStart = start;
7726        if (newStart < lowChar) {
7727            newStart = lowChar;
7728        } else if (newStart > highChar) {
7729            newStart = highChar;
7730        }
7731
7732        if (newStart != start) {
7733            Selection.setSelection((Spannable) mText, newStart);
7734            return true;
7735        }
7736
7737        return false;
7738    }
7739
7740    @Override
7741    public void computeScroll() {
7742        if (mScroller != null) {
7743            if (mScroller.computeScrollOffset()) {
7744                mScrollX = mScroller.getCurrX();
7745                mScrollY = mScroller.getCurrY();
7746                invalidateParentCaches();
7747                postInvalidate();  // So we draw again
7748            }
7749        }
7750    }
7751
7752    private void getInterestingRect(Rect r, int line) {
7753        convertFromViewportToContentCoordinates(r);
7754
7755        // Rectangle can can be expanded on first and last line to take
7756        // padding into account.
7757        // TODO Take left/right padding into account too?
7758        if (line == 0) r.top -= getExtendedPaddingTop();
7759        if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom();
7760    }
7761
7762    private void convertFromViewportToContentCoordinates(Rect r) {
7763        final int horizontalOffset = viewportToContentHorizontalOffset();
7764        r.left += horizontalOffset;
7765        r.right += horizontalOffset;
7766
7767        final int verticalOffset = viewportToContentVerticalOffset();
7768        r.top += verticalOffset;
7769        r.bottom += verticalOffset;
7770    }
7771
7772    int viewportToContentHorizontalOffset() {
7773        return getCompoundPaddingLeft() - mScrollX;
7774    }
7775
7776    int viewportToContentVerticalOffset() {
7777        int offset = getExtendedPaddingTop() - mScrollY;
7778        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
7779            offset += getVerticalOffset(false);
7780        }
7781        return offset;
7782    }
7783
7784    @Override
7785    public void debug(int depth) {
7786        super.debug(depth);
7787
7788        String output = debugIndent(depth);
7789        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
7790                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
7791                + "} ";
7792
7793        if (mText != null) {
7794
7795            output += "mText=\"" + mText + "\" ";
7796            if (mLayout != null) {
7797                output += "mLayout width=" + mLayout.getWidth()
7798                        + " height=" + mLayout.getHeight();
7799            }
7800        } else {
7801            output += "mText=NULL";
7802        }
7803        Log.d(VIEW_LOG_TAG, output);
7804    }
7805
7806    /**
7807     * Convenience for {@link Selection#getSelectionStart}.
7808     */
7809    @ViewDebug.ExportedProperty(category = "text")
7810    public int getSelectionStart() {
7811        return Selection.getSelectionStart(getText());
7812    }
7813
7814    /**
7815     * Convenience for {@link Selection#getSelectionEnd}.
7816     */
7817    @ViewDebug.ExportedProperty(category = "text")
7818    public int getSelectionEnd() {
7819        return Selection.getSelectionEnd(getText());
7820    }
7821
7822    /**
7823     * Return true iff there is a selection inside this text view.
7824     */
7825    public boolean hasSelection() {
7826        final int selectionStart = getSelectionStart();
7827        final int selectionEnd = getSelectionEnd();
7828
7829        return selectionStart >= 0 && selectionStart != selectionEnd;
7830    }
7831
7832    String getSelectedText() {
7833        if (!hasSelection()) {
7834            return null;
7835        }
7836
7837        final int start = getSelectionStart();
7838        final int end = getSelectionEnd();
7839        return String.valueOf(
7840                start > end ? mText.subSequence(end, start) : mText.subSequence(start, end));
7841    }
7842
7843    /**
7844     * Sets the properties of this field (lines, horizontally scrolling,
7845     * transformation method) to be for a single-line input.
7846     *
7847     * @attr ref android.R.styleable#TextView_singleLine
7848     */
7849    public void setSingleLine() {
7850        setSingleLine(true);
7851    }
7852
7853    /**
7854     * Sets the properties of this field to transform input to ALL CAPS
7855     * display. This may use a "small caps" formatting if available.
7856     * This setting will be ignored if this field is editable or selectable.
7857     *
7858     * This call replaces the current transformation method. Disabling this
7859     * will not necessarily restore the previous behavior from before this
7860     * was enabled.
7861     *
7862     * @see #setTransformationMethod(TransformationMethod)
7863     * @attr ref android.R.styleable#TextView_textAllCaps
7864     */
7865    public void setAllCaps(boolean allCaps) {
7866        if (allCaps) {
7867            setTransformationMethod(new AllCapsTransformationMethod(getContext()));
7868        } else {
7869            setTransformationMethod(null);
7870        }
7871    }
7872
7873    /**
7874     * If true, sets the properties of this field (number of lines, horizontally scrolling,
7875     * transformation method) to be for a single-line input; if false, restores these to the default
7876     * conditions.
7877     *
7878     * Note that the default conditions are not necessarily those that were in effect prior this
7879     * method, and you may want to reset these properties to your custom values.
7880     *
7881     * @attr ref android.R.styleable#TextView_singleLine
7882     */
7883    @android.view.RemotableViewMethod
7884    public void setSingleLine(boolean singleLine) {
7885        // Could be used, but may break backward compatibility.
7886        // if (mSingleLine == singleLine) return;
7887        setInputTypeSingleLine(singleLine);
7888        applySingleLine(singleLine, true, true);
7889    }
7890
7891    /**
7892     * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType.
7893     * @param singleLine
7894     */
7895    private void setInputTypeSingleLine(boolean singleLine) {
7896        if (mEditor != null
7897                && (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS)
7898                        == EditorInfo.TYPE_CLASS_TEXT) {
7899            if (singleLine) {
7900                mEditor.mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
7901            } else {
7902                mEditor.mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
7903            }
7904        }
7905    }
7906
7907    private void applySingleLine(boolean singleLine, boolean applyTransformation,
7908            boolean changeMaxLines) {
7909        mSingleLine = singleLine;
7910        if (singleLine) {
7911            setLines(1);
7912            setHorizontallyScrolling(true);
7913            if (applyTransformation) {
7914                setTransformationMethod(SingleLineTransformationMethod.getInstance());
7915            }
7916        } else {
7917            if (changeMaxLines) {
7918                setMaxLines(Integer.MAX_VALUE);
7919            }
7920            setHorizontallyScrolling(false);
7921            if (applyTransformation) {
7922                setTransformationMethod(null);
7923            }
7924        }
7925    }
7926
7927    /**
7928     * Causes words in the text that are longer than the view's width
7929     * to be ellipsized instead of broken in the middle.  You may also
7930     * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling}
7931     * to constrain the text to a single line.  Use <code>null</code>
7932     * to turn off ellipsizing.
7933     *
7934     * If {@link #setMaxLines} has been used to set two or more lines,
7935     * only {@link android.text.TextUtils.TruncateAt#END} and
7936     * {@link android.text.TextUtils.TruncateAt#MARQUEE} are supported
7937     * (other ellipsizing types will not do anything).
7938     *
7939     * @attr ref android.R.styleable#TextView_ellipsize
7940     */
7941    public void setEllipsize(TextUtils.TruncateAt where) {
7942        // TruncateAt is an enum. != comparison is ok between these singleton objects.
7943        if (mEllipsize != where) {
7944            mEllipsize = where;
7945
7946            if (mLayout != null) {
7947                nullLayouts();
7948                requestLayout();
7949                invalidate();
7950            }
7951        }
7952    }
7953
7954    /**
7955     * Sets how many times to repeat the marquee animation. Only applied if the
7956     * TextView has marquee enabled. Set to -1 to repeat indefinitely.
7957     *
7958     * @see #getMarqueeRepeatLimit()
7959     *
7960     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
7961     */
7962    public void setMarqueeRepeatLimit(int marqueeLimit) {
7963        mMarqueeRepeatLimit = marqueeLimit;
7964    }
7965
7966    /**
7967     * Gets the number of times the marquee animation is repeated. Only meaningful if the
7968     * TextView has marquee enabled.
7969     *
7970     * @return the number of times the marquee animation is repeated. -1 if the animation
7971     * repeats indefinitely
7972     *
7973     * @see #setMarqueeRepeatLimit(int)
7974     *
7975     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
7976     */
7977    public int getMarqueeRepeatLimit() {
7978        return mMarqueeRepeatLimit;
7979    }
7980
7981    /**
7982     * Returns where, if anywhere, words that are longer than the view
7983     * is wide should be ellipsized.
7984     */
7985    @ViewDebug.ExportedProperty
7986    public TextUtils.TruncateAt getEllipsize() {
7987        return mEllipsize;
7988    }
7989
7990    /**
7991     * Set the TextView so that when it takes focus, all the text is
7992     * selected.
7993     *
7994     * @attr ref android.R.styleable#TextView_selectAllOnFocus
7995     */
7996    @android.view.RemotableViewMethod
7997    public void setSelectAllOnFocus(boolean selectAllOnFocus) {
7998        createEditorIfNeeded();
7999        mEditor.mSelectAllOnFocus = selectAllOnFocus;
8000
8001        if (selectAllOnFocus && !(mText instanceof Spannable)) {
8002            setText(mText, BufferType.SPANNABLE);
8003        }
8004    }
8005
8006    /**
8007     * Set whether the cursor is visible. The default is true. Note that this property only
8008     * makes sense for editable TextView.
8009     *
8010     * @see #isCursorVisible()
8011     *
8012     * @attr ref android.R.styleable#TextView_cursorVisible
8013     */
8014    @android.view.RemotableViewMethod
8015    public void setCursorVisible(boolean visible) {
8016        if (visible && mEditor == null) return; // visible is the default value with no edit data
8017        createEditorIfNeeded();
8018        if (mEditor.mCursorVisible != visible) {
8019            mEditor.mCursorVisible = visible;
8020            invalidate();
8021
8022            mEditor.makeBlink();
8023
8024            // InsertionPointCursorController depends on mCursorVisible
8025            mEditor.prepareCursorControllers();
8026        }
8027    }
8028
8029    /**
8030     * @return whether or not the cursor is visible (assuming this TextView is editable)
8031     *
8032     * @see #setCursorVisible(boolean)
8033     *
8034     * @attr ref android.R.styleable#TextView_cursorVisible
8035     */
8036    public boolean isCursorVisible() {
8037        // true is the default value
8038        return mEditor == null ? true : mEditor.mCursorVisible;
8039    }
8040
8041    private boolean canMarquee() {
8042        int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
8043        return width > 0 && (mLayout.getLineWidth(0) > width
8044                || (mMarqueeFadeMode != MARQUEE_FADE_NORMAL && mSavedMarqueeModeLayout != null
8045                        && mSavedMarqueeModeLayout.getLineWidth(0) > width));
8046    }
8047
8048    private void startMarquee() {
8049        // Do not ellipsize EditText
8050        if (getKeyListener() != null) return;
8051
8052        if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
8053            return;
8054        }
8055
8056        if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected())
8057                && getLineCount() == 1 && canMarquee()) {
8058
8059            if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
8060                mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_FADE;
8061                final Layout tmp = mLayout;
8062                mLayout = mSavedMarqueeModeLayout;
8063                mSavedMarqueeModeLayout = tmp;
8064                setHorizontalFadingEdgeEnabled(true);
8065                requestLayout();
8066                invalidate();
8067            }
8068
8069            if (mMarquee == null) mMarquee = new Marquee(this);
8070            mMarquee.start(mMarqueeRepeatLimit);
8071        }
8072    }
8073
8074    private void stopMarquee() {
8075        if (mMarquee != null && !mMarquee.isStopped()) {
8076            mMarquee.stop();
8077        }
8078
8079        if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_FADE) {
8080            mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS;
8081            final Layout tmp = mSavedMarqueeModeLayout;
8082            mSavedMarqueeModeLayout = mLayout;
8083            mLayout = tmp;
8084            setHorizontalFadingEdgeEnabled(false);
8085            requestLayout();
8086            invalidate();
8087        }
8088    }
8089
8090    private void startStopMarquee(boolean start) {
8091        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
8092            if (start) {
8093                startMarquee();
8094            } else {
8095                stopMarquee();
8096            }
8097        }
8098    }
8099
8100    /**
8101     * This method is called when the text is changed, in case any subclasses
8102     * would like to know.
8103     *
8104     * Within <code>text</code>, the <code>lengthAfter</code> characters
8105     * beginning at <code>start</code> have just replaced old text that had
8106     * length <code>lengthBefore</code>. It is an error to attempt to make
8107     * changes to <code>text</code> from this callback.
8108     *
8109     * @param text The text the TextView is displaying
8110     * @param start The offset of the start of the range of the text that was
8111     * modified
8112     * @param lengthBefore The length of the former text that has been replaced
8113     * @param lengthAfter The length of the replacement modified text
8114     */
8115    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
8116        // intentionally empty, template pattern method can be overridden by subclasses
8117    }
8118
8119    /**
8120     * This method is called when the selection has changed, in case any
8121     * subclasses would like to know.
8122     *
8123     * @param selStart The new selection start location.
8124     * @param selEnd The new selection end location.
8125     */
8126    protected void onSelectionChanged(int selStart, int selEnd) {
8127        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8128    }
8129
8130    /**
8131     * Adds a TextWatcher to the list of those whose methods are called
8132     * whenever this TextView's text changes.
8133     * <p>
8134     * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
8135     * not called after {@link #setText} calls.  Now, doing {@link #setText}
8136     * if there are any text changed listeners forces the buffer type to
8137     * Editable if it would not otherwise be and does call this method.
8138     */
8139    public void addTextChangedListener(TextWatcher watcher) {
8140        if (mListeners == null) {
8141            mListeners = new ArrayList<TextWatcher>();
8142        }
8143
8144        mListeners.add(watcher);
8145    }
8146
8147    /**
8148     * Removes the specified TextWatcher from the list of those whose
8149     * methods are called
8150     * whenever this TextView's text changes.
8151     */
8152    public void removeTextChangedListener(TextWatcher watcher) {
8153        if (mListeners != null) {
8154            int i = mListeners.indexOf(watcher);
8155
8156            if (i >= 0) {
8157                mListeners.remove(i);
8158            }
8159        }
8160    }
8161
8162    private void sendBeforeTextChanged(CharSequence text, int start, int before, int after) {
8163        if (mListeners != null) {
8164            final ArrayList<TextWatcher> list = mListeners;
8165            final int count = list.size();
8166            for (int i = 0; i < count; i++) {
8167                list.get(i).beforeTextChanged(text, start, before, after);
8168            }
8169        }
8170
8171        // The spans that are inside or intersect the modified region no longer make sense
8172        removeIntersectingNonAdjacentSpans(start, start + before, SpellCheckSpan.class);
8173        removeIntersectingNonAdjacentSpans(start, start + before, SuggestionSpan.class);
8174    }
8175
8176    // Removes all spans that are inside or actually overlap the start..end range
8177    private <T> void removeIntersectingNonAdjacentSpans(int start, int end, Class<T> type) {
8178        if (!(mText instanceof Editable)) return;
8179        Editable text = (Editable) mText;
8180
8181        T[] spans = text.getSpans(start, end, type);
8182        final int length = spans.length;
8183        for (int i = 0; i < length; i++) {
8184            final int spanStart = text.getSpanStart(spans[i]);
8185            final int spanEnd = text.getSpanEnd(spans[i]);
8186            if (spanEnd == start || spanStart == end) break;
8187            text.removeSpan(spans[i]);
8188        }
8189    }
8190
8191    void removeAdjacentSuggestionSpans(final int pos) {
8192        if (!(mText instanceof Editable)) return;
8193        final Editable text = (Editable) mText;
8194
8195        final SuggestionSpan[] spans = text.getSpans(pos, pos, SuggestionSpan.class);
8196        final int length = spans.length;
8197        for (int i = 0; i < length; i++) {
8198            final int spanStart = text.getSpanStart(spans[i]);
8199            final int spanEnd = text.getSpanEnd(spans[i]);
8200            if (spanEnd == pos || spanStart == pos) {
8201                if (SpellChecker.haveWordBoundariesChanged(text, pos, pos, spanStart, spanEnd)) {
8202                    text.removeSpan(spans[i]);
8203                }
8204            }
8205        }
8206    }
8207
8208    /**
8209     * Not private so it can be called from an inner class without going
8210     * through a thunk.
8211     */
8212    void sendOnTextChanged(CharSequence text, int start, int before, int after) {
8213        if (mListeners != null) {
8214            final ArrayList<TextWatcher> list = mListeners;
8215            final int count = list.size();
8216            for (int i = 0; i < count; i++) {
8217                list.get(i).onTextChanged(text, start, before, after);
8218            }
8219        }
8220
8221        if (mEditor != null) mEditor.sendOnTextChanged(start, after);
8222    }
8223
8224    /**
8225     * Not private so it can be called from an inner class without going
8226     * through a thunk.
8227     */
8228    void sendAfterTextChanged(Editable text) {
8229        if (mListeners != null) {
8230            final ArrayList<TextWatcher> list = mListeners;
8231            final int count = list.size();
8232            for (int i = 0; i < count; i++) {
8233                list.get(i).afterTextChanged(text);
8234            }
8235        }
8236        hideErrorIfUnchanged();
8237    }
8238
8239    void updateAfterEdit() {
8240        invalidate();
8241        int curs = getSelectionStart();
8242
8243        if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
8244            registerForPreDraw();
8245        }
8246
8247        checkForResize();
8248
8249        if (curs >= 0) {
8250            mHighlightPathBogus = true;
8251            if (mEditor != null) mEditor.makeBlink();
8252            bringPointIntoView(curs);
8253        }
8254    }
8255
8256    /**
8257     * Not private so it can be called from an inner class without going
8258     * through a thunk.
8259     */
8260    void handleTextChanged(CharSequence buffer, int start, int before, int after) {
8261        sLastCutCopyOrTextChangedTime = 0;
8262
8263        final Editor.InputMethodState ims = mEditor == null ? null : mEditor.mInputMethodState;
8264        if (ims == null || ims.mBatchEditNesting == 0) {
8265            updateAfterEdit();
8266        }
8267        if (ims != null) {
8268            ims.mContentChanged = true;
8269            if (ims.mChangedStart < 0) {
8270                ims.mChangedStart = start;
8271                ims.mChangedEnd = start + before;
8272            } else {
8273                ims.mChangedStart = Math.min(ims.mChangedStart, start);
8274                ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta);
8275            }
8276            ims.mChangedDelta += after - before;
8277        }
8278        resetErrorChangedFlag();
8279        sendOnTextChanged(buffer, start, before, after);
8280        onTextChanged(buffer, start, before, after);
8281    }
8282
8283    /**
8284     * Not private so it can be called from an inner class without going
8285     * through a thunk.
8286     */
8287    void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) {
8288        // XXX Make the start and end move together if this ends up
8289        // spending too much time invalidating.
8290
8291        boolean selChanged = false;
8292        int newSelStart = -1, newSelEnd = -1;
8293
8294        final Editor.InputMethodState ims = mEditor == null ? null : mEditor.mInputMethodState;
8295
8296        if (what == Selection.SELECTION_END) {
8297            selChanged = true;
8298            newSelEnd = newStart;
8299
8300            if (oldStart >= 0 || newStart >= 0) {
8301                invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart);
8302                checkForResize();
8303                registerForPreDraw();
8304                if (mEditor != null) mEditor.makeBlink();
8305            }
8306        }
8307
8308        if (what == Selection.SELECTION_START) {
8309            selChanged = true;
8310            newSelStart = newStart;
8311
8312            if (oldStart >= 0 || newStart >= 0) {
8313                int end = Selection.getSelectionEnd(buf);
8314                invalidateCursor(end, oldStart, newStart);
8315            }
8316        }
8317
8318        if (selChanged) {
8319            mHighlightPathBogus = true;
8320            if (mEditor != null && !isFocused()) mEditor.mSelectionMoved = true;
8321
8322            if ((buf.getSpanFlags(what) & Spanned.SPAN_INTERMEDIATE) == 0) {
8323                if (newSelStart < 0) {
8324                    newSelStart = Selection.getSelectionStart(buf);
8325                }
8326                if (newSelEnd < 0) {
8327                    newSelEnd = Selection.getSelectionEnd(buf);
8328                }
8329
8330                if (mEditor != null) {
8331                    mEditor.refreshTextActionMode();
8332                    if (!hasSelection() && mEditor.mTextActionMode == null && hasTransientState()) {
8333                        // User generated selection has been removed.
8334                        setHasTransientState(false);
8335                    }
8336                }
8337                onSelectionChanged(newSelStart, newSelEnd);
8338            }
8339        }
8340
8341        if (what instanceof UpdateAppearance || what instanceof ParagraphStyle
8342                || what instanceof CharacterStyle) {
8343            if (ims == null || ims.mBatchEditNesting == 0) {
8344                invalidate();
8345                mHighlightPathBogus = true;
8346                checkForResize();
8347            } else {
8348                ims.mContentChanged = true;
8349            }
8350            if (mEditor != null) {
8351                if (oldStart >= 0) mEditor.invalidateTextDisplayList(mLayout, oldStart, oldEnd);
8352                if (newStart >= 0) mEditor.invalidateTextDisplayList(mLayout, newStart, newEnd);
8353                mEditor.invalidateHandlesAndActionMode();
8354            }
8355        }
8356
8357        if (MetaKeyKeyListener.isMetaTracker(buf, what)) {
8358            mHighlightPathBogus = true;
8359            if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) {
8360                ims.mSelectionModeChanged = true;
8361            }
8362
8363            if (Selection.getSelectionStart(buf) >= 0) {
8364                if (ims == null || ims.mBatchEditNesting == 0) {
8365                    invalidateCursor();
8366                } else {
8367                    ims.mCursorChanged = true;
8368                }
8369            }
8370        }
8371
8372        if (what instanceof ParcelableSpan) {
8373            // If this is a span that can be sent to a remote process,
8374            // the current extract editor would be interested in it.
8375            if (ims != null && ims.mExtractedTextRequest != null) {
8376                if (ims.mBatchEditNesting != 0) {
8377                    if (oldStart >= 0) {
8378                        if (ims.mChangedStart > oldStart) {
8379                            ims.mChangedStart = oldStart;
8380                        }
8381                        if (ims.mChangedStart > oldEnd) {
8382                            ims.mChangedStart = oldEnd;
8383                        }
8384                    }
8385                    if (newStart >= 0) {
8386                        if (ims.mChangedStart > newStart) {
8387                            ims.mChangedStart = newStart;
8388                        }
8389                        if (ims.mChangedStart > newEnd) {
8390                            ims.mChangedStart = newEnd;
8391                        }
8392                    }
8393                } else {
8394                    if (DEBUG_EXTRACT) {
8395                        Log.v(LOG_TAG, "Span change outside of batch: "
8396                                + oldStart + "-" + oldEnd + ","
8397                                + newStart + "-" + newEnd + " " + what);
8398                    }
8399                    ims.mContentChanged = true;
8400                }
8401            }
8402        }
8403
8404        if (mEditor != null && mEditor.mSpellChecker != null && newStart < 0
8405                && what instanceof SpellCheckSpan) {
8406            mEditor.mSpellChecker.onSpellCheckSpanRemoved((SpellCheckSpan) what);
8407        }
8408    }
8409
8410    @Override
8411    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
8412        if (isTemporarilyDetached()) {
8413            // If we are temporarily in the detach state, then do nothing.
8414            super.onFocusChanged(focused, direction, previouslyFocusedRect);
8415            return;
8416        }
8417
8418        if (mEditor != null) mEditor.onFocusChanged(focused, direction);
8419
8420        if (focused) {
8421            if (mText instanceof Spannable) {
8422                Spannable sp = (Spannable) mText;
8423                MetaKeyKeyListener.resetMetaState(sp);
8424            }
8425        }
8426
8427        startStopMarquee(focused);
8428
8429        if (mTransformation != null) {
8430            mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect);
8431        }
8432
8433        super.onFocusChanged(focused, direction, previouslyFocusedRect);
8434    }
8435
8436    @Override
8437    public void onWindowFocusChanged(boolean hasWindowFocus) {
8438        super.onWindowFocusChanged(hasWindowFocus);
8439
8440        if (mEditor != null) mEditor.onWindowFocusChanged(hasWindowFocus);
8441
8442        startStopMarquee(hasWindowFocus);
8443    }
8444
8445    @Override
8446    protected void onVisibilityChanged(View changedView, int visibility) {
8447        super.onVisibilityChanged(changedView, visibility);
8448        if (mEditor != null && visibility != VISIBLE) {
8449            mEditor.hideCursorAndSpanControllers();
8450            stopTextActionMode();
8451        }
8452    }
8453
8454    /**
8455     * Use {@link BaseInputConnection#removeComposingSpans
8456     * BaseInputConnection.removeComposingSpans()} to remove any IME composing
8457     * state from this text view.
8458     */
8459    public void clearComposingText() {
8460        if (mText instanceof Spannable) {
8461            BaseInputConnection.removeComposingSpans((Spannable) mText);
8462        }
8463    }
8464
8465    @Override
8466    public void setSelected(boolean selected) {
8467        boolean wasSelected = isSelected();
8468
8469        super.setSelected(selected);
8470
8471        if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
8472            if (selected) {
8473                startMarquee();
8474            } else {
8475                stopMarquee();
8476            }
8477        }
8478    }
8479
8480    @Override
8481    public boolean onTouchEvent(MotionEvent event) {
8482        final int action = event.getActionMasked();
8483        if (mEditor != null) {
8484            mEditor.onTouchEvent(event);
8485
8486            if (mEditor.mSelectionModifierCursorController != null
8487                    && mEditor.mSelectionModifierCursorController.isDragAcceleratorActive()) {
8488                return true;
8489            }
8490        }
8491
8492        final boolean superResult = super.onTouchEvent(event);
8493
8494        /*
8495         * Don't handle the release after a long press, because it will move the selection away from
8496         * whatever the menu action was trying to affect. If the long press should have triggered an
8497         * insertion action mode, we can now actually show it.
8498         */
8499        if (mEditor != null && mEditor.mDiscardNextActionUp && action == MotionEvent.ACTION_UP) {
8500            mEditor.mDiscardNextActionUp = false;
8501
8502            if (mEditor.mIsInsertionActionModeStartPending) {
8503                mEditor.startInsertionActionMode();
8504                mEditor.mIsInsertionActionModeStartPending = false;
8505            }
8506            return superResult;
8507        }
8508
8509        final boolean touchIsFinished = (action == MotionEvent.ACTION_UP)
8510                && (mEditor == null || !mEditor.mIgnoreActionUpEvent) && isFocused();
8511
8512        if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()
8513                && mText instanceof Spannable && mLayout != null) {
8514            boolean handled = false;
8515
8516            if (mMovement != null) {
8517                handled |= mMovement.onTouchEvent(this, (Spannable) mText, event);
8518            }
8519
8520            final boolean textIsSelectable = isTextSelectable();
8521            if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && textIsSelectable) {
8522                // The LinkMovementMethod which should handle taps on links has not been installed
8523                // on non editable text that support text selection.
8524                // We reproduce its behavior here to open links for these.
8525                ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(),
8526                        getSelectionEnd(), ClickableSpan.class);
8527
8528                if (links.length > 0) {
8529                    links[0].onClick(this);
8530                    handled = true;
8531                }
8532            }
8533
8534            if (touchIsFinished && (isTextEditable() || textIsSelectable)) {
8535                // Show the IME, except when selecting in read-only text.
8536                final InputMethodManager imm = InputMethodManager.peekInstance();
8537                viewClicked(imm);
8538                if (!textIsSelectable && mEditor.mShowSoftInputOnFocus) {
8539                    handled |= imm != null && imm.showSoftInput(this, 0);
8540                }
8541
8542                // The above condition ensures that the mEditor is not null
8543                mEditor.onTouchUpEvent(event);
8544
8545                handled = true;
8546            }
8547
8548            if (handled) {
8549                return true;
8550            }
8551        }
8552
8553        return superResult;
8554    }
8555
8556    @Override
8557    public boolean onGenericMotionEvent(MotionEvent event) {
8558        if (mMovement != null && mText instanceof Spannable && mLayout != null) {
8559            try {
8560                if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) {
8561                    return true;
8562                }
8563            } catch (AbstractMethodError ex) {
8564                // onGenericMotionEvent was added to the MovementMethod interface in API 12.
8565                // Ignore its absence in case third party applications implemented the
8566                // interface directly.
8567            }
8568        }
8569        return super.onGenericMotionEvent(event);
8570    }
8571
8572    @Override
8573    protected void onCreateContextMenu(ContextMenu menu) {
8574        if (mEditor != null) {
8575            mEditor.onCreateContextMenu(menu);
8576        }
8577    }
8578
8579    @Override
8580    public boolean showContextMenu() {
8581        if (mEditor != null) {
8582            mEditor.setContextMenuAnchor(Float.NaN, Float.NaN);
8583        }
8584        return super.showContextMenu();
8585    }
8586
8587    @Override
8588    public boolean showContextMenu(float x, float y) {
8589        if (mEditor != null) {
8590            mEditor.setContextMenuAnchor(x, y);
8591        }
8592        return super.showContextMenu(x, y);
8593    }
8594
8595    /**
8596     * @return True iff this TextView contains a text that can be edited, or if this is
8597     * a selectable TextView.
8598     */
8599    boolean isTextEditable() {
8600        return mText instanceof Editable && onCheckIsTextEditor() && isEnabled();
8601    }
8602
8603    /**
8604     * Returns true, only while processing a touch gesture, if the initial
8605     * touch down event caused focus to move to the text view and as a result
8606     * its selection changed.  Only valid while processing the touch gesture
8607     * of interest, in an editable text view.
8608     */
8609    public boolean didTouchFocusSelect() {
8610        return mEditor != null && mEditor.mTouchFocusSelected;
8611    }
8612
8613    @Override
8614    public void cancelLongPress() {
8615        super.cancelLongPress();
8616        if (mEditor != null) mEditor.mIgnoreActionUpEvent = true;
8617    }
8618
8619    @Override
8620    public boolean onTrackballEvent(MotionEvent event) {
8621        if (mMovement != null && mText instanceof Spannable && mLayout != null) {
8622            if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) {
8623                return true;
8624            }
8625        }
8626
8627        return super.onTrackballEvent(event);
8628    }
8629
8630    public void setScroller(Scroller s) {
8631        mScroller = s;
8632    }
8633
8634    @Override
8635    protected float getLeftFadingEdgeStrength() {
8636        if (isMarqueeFadeEnabled() && mMarquee != null && !mMarquee.isStopped()) {
8637            final Marquee marquee = mMarquee;
8638            if (marquee.shouldDrawLeftFade()) {
8639                return getHorizontalFadingEdgeStrength(marquee.getScroll(), 0.0f);
8640            } else {
8641                return 0.0f;
8642            }
8643        } else if (getLineCount() == 1) {
8644            final float lineLeft = getLayout().getLineLeft(0);
8645            if (lineLeft > mScrollX) return 0.0f;
8646            return getHorizontalFadingEdgeStrength(mScrollX, lineLeft);
8647        }
8648        return super.getLeftFadingEdgeStrength();
8649    }
8650
8651    @Override
8652    protected float getRightFadingEdgeStrength() {
8653        if (isMarqueeFadeEnabled() && mMarquee != null && !mMarquee.isStopped()) {
8654            final Marquee marquee = mMarquee;
8655            return getHorizontalFadingEdgeStrength(marquee.getMaxFadeScroll(), marquee.getScroll());
8656        } else if (getLineCount() == 1) {
8657            final float rightEdge = mScrollX +
8658                    (getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight());
8659            final float lineRight = getLayout().getLineRight(0);
8660            if (lineRight < rightEdge) return 0.0f;
8661            return getHorizontalFadingEdgeStrength(rightEdge, lineRight);
8662        }
8663        return super.getRightFadingEdgeStrength();
8664    }
8665
8666    /**
8667     * Calculates the fading edge strength as the ratio of the distance between two
8668     * horizontal positions to {@link View#getHorizontalFadingEdgeLength()}. Uses the absolute
8669     * value for the distance calculation.
8670     *
8671     * @param position1 A horizontal position.
8672     * @param position2 A horizontal position.
8673     * @return Fading edge strength between [0.0f, 1.0f].
8674     */
8675    @FloatRange(from = 0.0, to = 1.0)
8676    private float getHorizontalFadingEdgeStrength(float position1, float position2) {
8677        final int horizontalFadingEdgeLength = getHorizontalFadingEdgeLength();
8678        if (horizontalFadingEdgeLength == 0) return 0.0f;
8679        final float diff = Math.abs(position1 - position2);
8680        if (diff > horizontalFadingEdgeLength) return 1.0f;
8681        return diff / horizontalFadingEdgeLength;
8682    }
8683
8684    private boolean isMarqueeFadeEnabled() {
8685        return mEllipsize == TextUtils.TruncateAt.MARQUEE
8686                && mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS;
8687    }
8688
8689    @Override
8690    protected int computeHorizontalScrollRange() {
8691        if (mLayout != null) {
8692            return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT
8693                    ? (int) mLayout.getLineWidth(0) : mLayout.getWidth();
8694        }
8695
8696        return super.computeHorizontalScrollRange();
8697    }
8698
8699    @Override
8700    protected int computeVerticalScrollRange() {
8701        if (mLayout != null) {
8702            return mLayout.getHeight();
8703        }
8704        return super.computeVerticalScrollRange();
8705    }
8706
8707    @Override
8708    protected int computeVerticalScrollExtent() {
8709        return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
8710    }
8711
8712    @Override
8713    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
8714        super.findViewsWithText(outViews, searched, flags);
8715        if (!outViews.contains(this) && (flags & FIND_VIEWS_WITH_TEXT) != 0
8716                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mText)) {
8717            String searchedLowerCase = searched.toString().toLowerCase();
8718            String textLowerCase = mText.toString().toLowerCase();
8719            if (textLowerCase.contains(searchedLowerCase)) {
8720                outViews.add(this);
8721            }
8722        }
8723    }
8724
8725    public enum BufferType {
8726        NORMAL, SPANNABLE, EDITABLE,
8727    }
8728
8729    /**
8730     * Returns the TextView_textColor attribute from the TypedArray, if set, or
8731     * the TextAppearance_textColor from the TextView_textAppearance attribute,
8732     * if TextView_textColor was not set directly.
8733     *
8734     * @removed
8735     */
8736    public static ColorStateList getTextColors(Context context, TypedArray attrs) {
8737        if (attrs == null) {
8738            // Preserve behavior prior to removal of this API.
8739            throw new NullPointerException();
8740        }
8741
8742        // It's not safe to use this method from apps. The parameter 'attrs'
8743        // must have been obtained using the TextView filter array which is not
8744        // available to the SDK. As such, we grab a default TypedArray with the
8745        // right filter instead here.
8746        final TypedArray a = context.obtainStyledAttributes(R.styleable.TextView);
8747        ColorStateList colors = a.getColorStateList(R.styleable.TextView_textColor);
8748        if (colors == null) {
8749            final int ap = a.getResourceId(R.styleable.TextView_textAppearance, 0);
8750            if (ap != 0) {
8751                final TypedArray appearance = context.obtainStyledAttributes(
8752                        ap, R.styleable.TextAppearance);
8753                colors = appearance.getColorStateList(R.styleable.TextAppearance_textColor);
8754                appearance.recycle();
8755            }
8756        }
8757        a.recycle();
8758
8759        return colors;
8760    }
8761
8762    /**
8763     * Returns the default color from the TextView_textColor attribute from the
8764     * AttributeSet, if set, or the default color from the
8765     * TextAppearance_textColor from the TextView_textAppearance attribute, if
8766     * TextView_textColor was not set directly.
8767     *
8768     * @removed
8769     */
8770    public static int getTextColor(Context context, TypedArray attrs, int def) {
8771        final ColorStateList colors = getTextColors(context, attrs);
8772        if (colors == null) {
8773            return def;
8774        } else {
8775            return colors.getDefaultColor();
8776        }
8777    }
8778
8779    @Override
8780    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8781        if (event.hasModifiers(KeyEvent.META_CTRL_ON)) {
8782            // Handle Ctrl-only shortcuts.
8783            switch (keyCode) {
8784                case KeyEvent.KEYCODE_A:
8785                    if (canSelectText()) {
8786                        return onTextContextMenuItem(ID_SELECT_ALL);
8787                    }
8788                    break;
8789                case KeyEvent.KEYCODE_Z:
8790                    if (canUndo()) {
8791                        return onTextContextMenuItem(ID_UNDO);
8792                    }
8793                    break;
8794                case KeyEvent.KEYCODE_X:
8795                    if (canCut()) {
8796                        return onTextContextMenuItem(ID_CUT);
8797                    }
8798                    break;
8799                case KeyEvent.KEYCODE_C:
8800                    if (canCopy()) {
8801                        return onTextContextMenuItem(ID_COPY);
8802                    }
8803                    break;
8804                case KeyEvent.KEYCODE_V:
8805                    if (canPaste()) {
8806                        return onTextContextMenuItem(ID_PASTE);
8807                    }
8808                    break;
8809            }
8810        } else if (event.hasModifiers(KeyEvent.META_CTRL_ON | KeyEvent.META_SHIFT_ON)) {
8811            // Handle Ctrl-Shift shortcuts.
8812            switch (keyCode) {
8813                case KeyEvent.KEYCODE_Z:
8814                    if (canRedo()) {
8815                        return onTextContextMenuItem(ID_REDO);
8816                    }
8817                    break;
8818                case KeyEvent.KEYCODE_V:
8819                    if (canPaste()) {
8820                        return onTextContextMenuItem(ID_PASTE_AS_PLAIN_TEXT);
8821                    }
8822            }
8823        }
8824        return super.onKeyShortcut(keyCode, event);
8825    }
8826
8827    /**
8828     * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the
8829     * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have
8830     * a selection controller (see {@link Editor#prepareCursorControllers()}), but this is not
8831     * sufficient.
8832     */
8833    boolean canSelectText() {
8834        return mText.length() != 0 && mEditor != null && mEditor.hasSelectionController();
8835    }
8836
8837    /**
8838     * Test based on the <i>intrinsic</i> charateristics of the TextView.
8839     * The text must be spannable and the movement method must allow for arbitary selection.
8840     *
8841     * See also {@link #canSelectText()}.
8842     */
8843    boolean textCanBeSelected() {
8844        // prepareCursorController() relies on this method.
8845        // If you change this condition, make sure prepareCursorController is called anywhere
8846        // the value of this condition might be changed.
8847        if (mMovement == null || !mMovement.canSelectArbitrarily()) return false;
8848        return isTextEditable()
8849                || (isTextSelectable() && mText instanceof Spannable && isEnabled());
8850    }
8851
8852    private Locale getTextServicesLocale(boolean allowNullLocale) {
8853        // Start fetching the text services locale asynchronously.
8854        updateTextServicesLocaleAsync();
8855        // If !allowNullLocale and there is no cached text services locale, just return the default
8856        // locale.
8857        return (mCurrentSpellCheckerLocaleCache == null && !allowNullLocale) ? Locale.getDefault()
8858                : mCurrentSpellCheckerLocaleCache;
8859    }
8860
8861    /**
8862     * This is a temporary method. Future versions may support multi-locale text.
8863     * Caveat: This method may not return the latest text services locale, but this should be
8864     * acceptable and it's more important to make this method asynchronous.
8865     *
8866     * @return The locale that should be used for a word iterator
8867     * in this TextView, based on the current spell checker settings,
8868     * the current IME's locale, or the system default locale.
8869     * Please note that a word iterator in this TextView is different from another word iterator
8870     * used by SpellChecker.java of TextView. This method should be used for the former.
8871     * @hide
8872     */
8873    // TODO: Support multi-locale
8874    // TODO: Update the text services locale immediately after the keyboard locale is switched
8875    // by catching intent of keyboard switch event
8876    public Locale getTextServicesLocale() {
8877        return getTextServicesLocale(false /* allowNullLocale */);
8878    }
8879
8880    /**
8881     * @return true if this TextView is specialized for showing and interacting with the extracted
8882     * text in a full-screen input method.
8883     * @hide
8884     */
8885    public boolean isInExtractedMode() {
8886        return false;
8887    }
8888
8889    /**
8890     * This is a temporary method. Future versions may support multi-locale text.
8891     * Caveat: This method may not return the latest spell checker locale, but this should be
8892     * acceptable and it's more important to make this method asynchronous.
8893     *
8894     * @return The locale that should be used for a spell checker in this TextView,
8895     * based on the current spell checker settings, the current IME's locale, or the system default
8896     * locale.
8897     * @hide
8898     */
8899    public Locale getSpellCheckerLocale() {
8900        return getTextServicesLocale(true /* allowNullLocale */);
8901    }
8902
8903    private void updateTextServicesLocaleAsync() {
8904        // AsyncTask.execute() uses a serial executor which means we don't have
8905        // to lock around updateTextServicesLocaleLocked() to prevent it from
8906        // being executed n times in parallel.
8907        AsyncTask.execute(new Runnable() {
8908            @Override
8909            public void run() {
8910                updateTextServicesLocaleLocked();
8911            }
8912        });
8913    }
8914
8915    private void updateTextServicesLocaleLocked() {
8916        final TextServicesManager textServicesManager = (TextServicesManager)
8917                mContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);
8918        final SpellCheckerSubtype subtype = textServicesManager.getCurrentSpellCheckerSubtype(true);
8919        final Locale locale;
8920        if (subtype != null) {
8921            locale = subtype.getLocaleObject();
8922        } else {
8923            locale = null;
8924        }
8925        mCurrentSpellCheckerLocaleCache = locale;
8926    }
8927
8928    void onLocaleChanged() {
8929        mEditor.onLocaleChanged();
8930    }
8931
8932    /**
8933     * This method is used by the ArrowKeyMovementMethod to jump from one word to the other.
8934     * Made available to achieve a consistent behavior.
8935     * @hide
8936     */
8937    public WordIterator getWordIterator() {
8938        if (mEditor != null) {
8939            return mEditor.getWordIterator();
8940        } else {
8941            return null;
8942        }
8943    }
8944
8945    /** @hide */
8946    @Override
8947    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
8948        super.onPopulateAccessibilityEventInternal(event);
8949
8950        final CharSequence text = getTextForAccessibility();
8951        if (!TextUtils.isEmpty(text)) {
8952            event.getText().add(text);
8953        }
8954    }
8955
8956    /**
8957     * @return true if the user has explicitly allowed accessibility services
8958     * to speak passwords.
8959     */
8960    private boolean shouldSpeakPasswordsForAccessibility() {
8961        return (Settings.Secure.getIntForUser(mContext.getContentResolver(),
8962                Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD, 0,
8963                UserHandle.USER_CURRENT_OR_SELF) == 1);
8964    }
8965
8966    @Override
8967    public CharSequence getAccessibilityClassName() {
8968        return TextView.class.getName();
8969    }
8970
8971    @Override
8972    public void onProvideStructure(ViewStructure structure) {
8973        super.onProvideStructure(structure);
8974        final boolean isPassword = hasPasswordTransformationMethod()
8975                || isPasswordInputType(getInputType());
8976        if (!isPassword) {
8977            if (mLayout == null) {
8978                assumeLayout();
8979            }
8980            Layout layout = mLayout;
8981            final int lineCount = layout.getLineCount();
8982            if (lineCount <= 1) {
8983                // Simple case: this is a single line.
8984                structure.setText(getText(), getSelectionStart(), getSelectionEnd());
8985            } else {
8986                // Complex case: multi-line, could be scrolled or within a scroll container
8987                // so some lines are not visible.
8988                final int[] tmpCords = new int[2];
8989                getLocationInWindow(tmpCords);
8990                final int topWindowLocation = tmpCords[1];
8991                View root = this;
8992                ViewParent viewParent = getParent();
8993                while (viewParent instanceof View) {
8994                    root = (View) viewParent;
8995                    viewParent = root.getParent();
8996                }
8997                final int windowHeight = root.getHeight();
8998                final int topLine;
8999                final int bottomLine;
9000                if (topWindowLocation >= 0) {
9001                    // The top of the view is fully within its window; start text at line 0.
9002                    topLine = getLineAtCoordinateUnclamped(0);
9003                    bottomLine = getLineAtCoordinateUnclamped(windowHeight - 1);
9004                } else {
9005                    // The top of hte window has scrolled off the top of the window; figure out
9006                    // the starting line for this.
9007                    topLine = getLineAtCoordinateUnclamped(-topWindowLocation);
9008                    bottomLine = getLineAtCoordinateUnclamped(windowHeight - 1 - topWindowLocation);
9009                }
9010                // We want to return some contextual lines above/below the lines that are
9011                // actually visible.
9012                int expandedTopLine = topLine - (bottomLine - topLine) / 2;
9013                if (expandedTopLine < 0) {
9014                    expandedTopLine = 0;
9015                }
9016                int expandedBottomLine = bottomLine + (bottomLine - topLine) / 2;
9017                if (expandedBottomLine >= lineCount) {
9018                    expandedBottomLine = lineCount - 1;
9019                }
9020                // Convert lines into character offsets.
9021                int expandedTopChar = layout.getLineStart(expandedTopLine);
9022                int expandedBottomChar = layout.getLineEnd(expandedBottomLine);
9023                // Take into account selection -- if there is a selection, we need to expand
9024                // the text we are returning to include that selection.
9025                final int selStart = getSelectionStart();
9026                final int selEnd = getSelectionEnd();
9027                if (selStart < selEnd) {
9028                    if (selStart < expandedTopChar) {
9029                        expandedTopChar = selStart;
9030                    }
9031                    if (selEnd > expandedBottomChar) {
9032                        expandedBottomChar = selEnd;
9033                    }
9034                }
9035                // Get the text and trim it to the range we are reporting.
9036                CharSequence text = getText();
9037                if (expandedTopChar > 0 || expandedBottomChar < text.length()) {
9038                    text = text.subSequence(expandedTopChar, expandedBottomChar);
9039                }
9040                structure.setText(text, selStart - expandedTopChar, selEnd - expandedTopChar);
9041                final int[] lineOffsets = new int[bottomLine - topLine + 1];
9042                final int[] lineBaselines = new int[bottomLine - topLine + 1];
9043                final int baselineOffset = getBaselineOffset();
9044                for (int i = topLine; i <= bottomLine; i++) {
9045                    lineOffsets[i - topLine] = layout.getLineStart(i);
9046                    lineBaselines[i - topLine] = layout.getLineBaseline(i) + baselineOffset;
9047                }
9048                structure.setTextLines(lineOffsets, lineBaselines);
9049            }
9050
9051            // Extract style information that applies to the TextView as a whole.
9052            int style = 0;
9053            int typefaceStyle = getTypefaceStyle();
9054            if ((typefaceStyle & Typeface.BOLD) != 0) {
9055                style |= AssistStructure.ViewNode.TEXT_STYLE_BOLD;
9056            }
9057            if ((typefaceStyle & Typeface.ITALIC) != 0) {
9058                style |= AssistStructure.ViewNode.TEXT_STYLE_ITALIC;
9059            }
9060
9061            // Global styles can also be set via TextView.setPaintFlags().
9062            int paintFlags = mTextPaint.getFlags();
9063            if ((paintFlags & Paint.FAKE_BOLD_TEXT_FLAG) != 0) {
9064                style |= AssistStructure.ViewNode.TEXT_STYLE_BOLD;
9065            }
9066            if ((paintFlags & Paint.UNDERLINE_TEXT_FLAG) != 0) {
9067                style |= AssistStructure.ViewNode.TEXT_STYLE_UNDERLINE;
9068            }
9069            if ((paintFlags & Paint.STRIKE_THRU_TEXT_FLAG) != 0) {
9070                style |= AssistStructure.ViewNode.TEXT_STYLE_STRIKE_THRU;
9071            }
9072
9073            // TextView does not have its own text background color. A background is either part
9074            // of the View (and can be any drawable) or a BackgroundColorSpan inside the text.
9075            structure.setTextStyle(getTextSize(), getCurrentTextColor(),
9076                    AssistStructure.ViewNode.TEXT_COLOR_UNDEFINED /* bgColor */, style);
9077        }
9078        structure.setHint(getHint());
9079    }
9080
9081    /** @hide */
9082    @Override
9083    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
9084        super.onInitializeAccessibilityEventInternal(event);
9085
9086        final boolean isPassword = hasPasswordTransformationMethod();
9087        event.setPassword(isPassword);
9088
9089        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) {
9090            event.setFromIndex(Selection.getSelectionStart(mText));
9091            event.setToIndex(Selection.getSelectionEnd(mText));
9092            event.setItemCount(mText.length());
9093        }
9094    }
9095
9096    /** @hide */
9097    @Override
9098    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
9099        super.onInitializeAccessibilityNodeInfoInternal(info);
9100
9101        final boolean isPassword = hasPasswordTransformationMethod();
9102        info.setPassword(isPassword);
9103        info.setText(getTextForAccessibility());
9104
9105        if (mBufferType == BufferType.EDITABLE) {
9106            info.setEditable(true);
9107            if (isEnabled()) {
9108                info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_TEXT);
9109            }
9110        }
9111
9112        if (mEditor != null) {
9113            info.setInputType(mEditor.mInputType);
9114
9115            if (mEditor.mError != null) {
9116                info.setContentInvalid(true);
9117                info.setError(mEditor.mError);
9118            }
9119        }
9120
9121        if (!TextUtils.isEmpty(mText)) {
9122            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
9123            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
9124            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
9125                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
9126                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE
9127                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH
9128                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE);
9129            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
9130        }
9131
9132        if (isFocused()) {
9133            if (canCopy()) {
9134                info.addAction(AccessibilityNodeInfo.ACTION_COPY);
9135            }
9136            if (canPaste()) {
9137                info.addAction(AccessibilityNodeInfo.ACTION_PASTE);
9138            }
9139            if (canCut()) {
9140                info.addAction(AccessibilityNodeInfo.ACTION_CUT);
9141            }
9142            if (canShare()) {
9143                info.addAction(new AccessibilityNodeInfo.AccessibilityAction(
9144                        ACCESSIBILITY_ACTION_SHARE,
9145                        getResources().getString(com.android.internal.R.string.share)));
9146            }
9147            if (canProcessText()) {  // also implies mEditor is not null.
9148                mEditor.mProcessTextIntentActionsHandler.onInitializeAccessibilityNodeInfo(info);
9149            }
9150        }
9151
9152        // Check for known input filter types.
9153        final int numFilters = mFilters.length;
9154        for (int i = 0; i < numFilters; i++) {
9155            final InputFilter filter = mFilters[i];
9156            if (filter instanceof InputFilter.LengthFilter) {
9157                info.setMaxTextLength(((InputFilter.LengthFilter) filter).getMax());
9158            }
9159        }
9160
9161        if (!isSingleLine()) {
9162            info.setMultiLine(true);
9163        }
9164    }
9165
9166    /**
9167     * Performs an accessibility action after it has been offered to the
9168     * delegate.
9169     *
9170     * @hide
9171     */
9172    @Override
9173    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
9174        if (mEditor != null
9175                && mEditor.mProcessTextIntentActionsHandler.performAccessibilityAction(action)) {
9176            return true;
9177        }
9178        switch (action) {
9179            case AccessibilityNodeInfo.ACTION_CLICK: {
9180                return performAccessibilityActionClick(arguments);
9181            }
9182            case AccessibilityNodeInfo.ACTION_COPY: {
9183                if (isFocused() && canCopy()) {
9184                    if (onTextContextMenuItem(ID_COPY)) {
9185                        return true;
9186                    }
9187                }
9188            } return false;
9189            case AccessibilityNodeInfo.ACTION_PASTE: {
9190                if (isFocused() && canPaste()) {
9191                    if (onTextContextMenuItem(ID_PASTE)) {
9192                        return true;
9193                    }
9194                }
9195            } return false;
9196            case AccessibilityNodeInfo.ACTION_CUT: {
9197                if (isFocused() && canCut()) {
9198                    if (onTextContextMenuItem(ID_CUT)) {
9199                        return true;
9200                    }
9201                }
9202            } return false;
9203            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
9204                ensureIterableTextForAccessibilitySelectable();
9205                CharSequence text = getIterableTextForAccessibility();
9206                if (text == null) {
9207                    return false;
9208                }
9209                final int start = (arguments != null) ? arguments.getInt(
9210                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
9211                final int end = (arguments != null) ? arguments.getInt(
9212                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
9213                if ((getSelectionStart() != start || getSelectionEnd() != end)) {
9214                    // No arguments clears the selection.
9215                    if (start == end && end == -1) {
9216                        Selection.removeSelection((Spannable) text);
9217                        return true;
9218                    }
9219                    if (start >= 0 && start <= end && end <= text.length()) {
9220                        Selection.setSelection((Spannable) text, start, end);
9221                        // Make sure selection mode is engaged.
9222                        if (mEditor != null) {
9223                            mEditor.startSelectionActionMode();
9224                        }
9225                        return true;
9226                    }
9227                }
9228            } return false;
9229            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY:
9230            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
9231                ensureIterableTextForAccessibilitySelectable();
9232                return super.performAccessibilityActionInternal(action, arguments);
9233            }
9234            case ACCESSIBILITY_ACTION_SHARE: {
9235                if (isFocused() && canShare()) {
9236                    if (onTextContextMenuItem(ID_SHARE)) {
9237                        return true;
9238                    }
9239                }
9240            } return false;
9241            case AccessibilityNodeInfo.ACTION_SET_TEXT: {
9242                if (!isEnabled() || (mBufferType != BufferType.EDITABLE)) {
9243                    return false;
9244                }
9245                CharSequence text = (arguments != null) ? arguments.getCharSequence(
9246                        AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE) : null;
9247                setText(text);
9248                if (mText != null) {
9249                    int updatedTextLength = mText.length();
9250                    if (updatedTextLength > 0) {
9251                        Selection.setSelection((Spannable) mText, updatedTextLength);
9252                    }
9253                }
9254            } return true;
9255            default: {
9256                return super.performAccessibilityActionInternal(action, arguments);
9257            }
9258        }
9259    }
9260
9261    private boolean performAccessibilityActionClick(Bundle arguments) {
9262        boolean handled = false;
9263
9264        if (!isEnabled()) {
9265            return false;
9266        }
9267
9268        if (isClickable() || isLongClickable()) {
9269            // Simulate View.onTouchEvent for an ACTION_UP event
9270            if (isFocusable() && !isFocused()) {
9271                requestFocus();
9272            }
9273
9274            performClick();
9275            handled = true;
9276        }
9277
9278        // Show the IME, except when selecting in read-only text.
9279        if ((mMovement != null || onCheckIsTextEditor()) && hasSpannableText() && mLayout != null
9280                && (isTextEditable() || isTextSelectable()) && isFocused()) {
9281            final InputMethodManager imm = InputMethodManager.peekInstance();
9282            viewClicked(imm);
9283            if (!isTextSelectable() && mEditor.mShowSoftInputOnFocus && imm != null) {
9284                handled |= imm.showSoftInput(this, 0);
9285            }
9286        }
9287
9288        return handled;
9289    }
9290
9291    private boolean hasSpannableText() {
9292        return mText != null && mText instanceof Spannable;
9293    }
9294
9295    /** @hide */
9296    @Override
9297    public void sendAccessibilityEventInternal(int eventType) {
9298        if (eventType == AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED && mEditor != null) {
9299            mEditor.mProcessTextIntentActionsHandler.initializeAccessibilityActions();
9300        }
9301
9302        // Do not send scroll events since first they are not interesting for
9303        // accessibility and second such events a generated too frequently.
9304        // For details see the implementation of bringTextIntoView().
9305        if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
9306            return;
9307        }
9308        super.sendAccessibilityEventInternal(eventType);
9309    }
9310
9311    /**
9312     * Returns the text that should be exposed to accessibility services.
9313     * <p>
9314     * This approximates what is displayed visually. If the user has specified
9315     * that accessibility services should speak passwords, this method will
9316     * bypass any password transformation method and return unobscured text.
9317     *
9318     * @return the text that should be exposed to accessibility services, may
9319     *         be {@code null} if no text is set
9320     */
9321    @Nullable
9322    private CharSequence getTextForAccessibility() {
9323        // If the text is empty, we must be showing the hint text.
9324        if (TextUtils.isEmpty(mText)) {
9325            return mHint;
9326        }
9327
9328        // Check whether we need to bypass the transformation
9329        // method and expose unobscured text.
9330        if (hasPasswordTransformationMethod() && shouldSpeakPasswordsForAccessibility()) {
9331            return mText;
9332        }
9333
9334        // Otherwise, speak whatever text is being displayed.
9335        return mTransformed;
9336    }
9337
9338    void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText,
9339            int fromIndex, int removedCount, int addedCount) {
9340        AccessibilityEvent event =
9341                AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
9342        event.setFromIndex(fromIndex);
9343        event.setRemovedCount(removedCount);
9344        event.setAddedCount(addedCount);
9345        event.setBeforeText(beforeText);
9346        sendAccessibilityEventUnchecked(event);
9347    }
9348
9349    /**
9350     * Returns whether this text view is a current input method target.  The
9351     * default implementation just checks with {@link InputMethodManager}.
9352     */
9353    public boolean isInputMethodTarget() {
9354        InputMethodManager imm = InputMethodManager.peekInstance();
9355        return imm != null && imm.isActive(this);
9356    }
9357
9358    static final int ID_SELECT_ALL = android.R.id.selectAll;
9359    static final int ID_UNDO = android.R.id.undo;
9360    static final int ID_REDO = android.R.id.redo;
9361    static final int ID_CUT = android.R.id.cut;
9362    static final int ID_COPY = android.R.id.copy;
9363    static final int ID_PASTE = android.R.id.paste;
9364    static final int ID_SHARE = android.R.id.shareText;
9365    static final int ID_PASTE_AS_PLAIN_TEXT = android.R.id.pasteAsPlainText;
9366    static final int ID_REPLACE = android.R.id.replaceText;
9367
9368    /**
9369     * Called when a context menu option for the text view is selected.  Currently
9370     * this will be one of {@link android.R.id#selectAll}, {@link android.R.id#cut},
9371     * {@link android.R.id#copy}, {@link android.R.id#paste} or {@link android.R.id#shareText}.
9372     *
9373     * @return true if the context menu item action was performed.
9374     */
9375    public boolean onTextContextMenuItem(int id) {
9376        int min = 0;
9377        int max = mText.length();
9378
9379        if (isFocused()) {
9380            final int selStart = getSelectionStart();
9381            final int selEnd = getSelectionEnd();
9382
9383            min = Math.max(0, Math.min(selStart, selEnd));
9384            max = Math.max(0, Math.max(selStart, selEnd));
9385        }
9386
9387        switch (id) {
9388            case ID_SELECT_ALL:
9389                selectAllText();
9390                return true;
9391
9392            case ID_UNDO:
9393                if (mEditor != null) {
9394                    mEditor.undo();
9395                }
9396                return true;  // Returns true even if nothing was undone.
9397
9398            case ID_REDO:
9399                if (mEditor != null) {
9400                    mEditor.redo();
9401                }
9402                return true;  // Returns true even if nothing was undone.
9403
9404            case ID_PASTE:
9405                paste(min, max, true /* withFormatting */);
9406                return true;
9407
9408            case ID_PASTE_AS_PLAIN_TEXT:
9409                paste(min, max, false /* withFormatting */);
9410                return true;
9411
9412            case ID_CUT:
9413                setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
9414                deleteText_internal(min, max);
9415                return true;
9416
9417            case ID_COPY:
9418                setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
9419                stopTextActionMode();
9420                return true;
9421
9422            case ID_REPLACE:
9423                if (mEditor != null) {
9424                    mEditor.replace();
9425                }
9426                return true;
9427
9428            case ID_SHARE:
9429                shareSelectedText();
9430                return true;
9431        }
9432        return false;
9433    }
9434
9435    CharSequence getTransformedText(int start, int end) {
9436        return removeSuggestionSpans(mTransformed.subSequence(start, end));
9437    }
9438
9439    @Override
9440    public boolean performLongClick() {
9441        boolean handled = false;
9442
9443        if (mEditor != null) {
9444            mEditor.mIsBeingLongClicked = true;
9445        }
9446
9447        if (super.performLongClick()) {
9448            handled = true;
9449        }
9450
9451        if (mEditor != null) {
9452            handled |= mEditor.performLongClick(handled);
9453            mEditor.mIsBeingLongClicked = false;
9454        }
9455
9456        if (handled) {
9457            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
9458            if (mEditor != null) mEditor.mDiscardNextActionUp = true;
9459        }
9460
9461        return handled;
9462    }
9463
9464    @Override
9465    protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) {
9466        super.onScrollChanged(horiz, vert, oldHoriz, oldVert);
9467        if (mEditor != null) {
9468            mEditor.onScrollChanged();
9469        }
9470    }
9471
9472    /**
9473     * Return whether or not suggestions are enabled on this TextView. The suggestions are generated
9474     * by the IME or by the spell checker as the user types. This is done by adding
9475     * {@link SuggestionSpan}s to the text.
9476     *
9477     * When suggestions are enabled (default), this list of suggestions will be displayed when the
9478     * user asks for them on these parts of the text. This value depends on the inputType of this
9479     * TextView.
9480     *
9481     * The class of the input type must be {@link InputType#TYPE_CLASS_TEXT}.
9482     *
9483     * In addition, the type variation must be one of
9484     * {@link InputType#TYPE_TEXT_VARIATION_NORMAL},
9485     * {@link InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT},
9486     * {@link InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE},
9487     * {@link InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or
9488     * {@link InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}.
9489     *
9490     * And finally, the {@link InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS} flag must <i>not</i> be set.
9491     *
9492     * @return true if the suggestions popup window is enabled, based on the inputType.
9493     */
9494    public boolean isSuggestionsEnabled() {
9495        if (mEditor == null) return false;
9496        if ((mEditor.mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) {
9497            return false;
9498        }
9499        if ((mEditor.mInputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) > 0) return false;
9500
9501        final int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION;
9502        return (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL
9503                || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT
9504                || variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE
9505                || variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE
9506                || variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT);
9507    }
9508
9509    /**
9510     * If provided, this ActionMode.Callback will be used to create the ActionMode when text
9511     * selection is initiated in this View.
9512     *
9513     * <p>The standard implementation populates the menu with a subset of Select All, Cut, Copy,
9514     * Paste, Replace and Share actions, depending on what this View supports.
9515     *
9516     * <p>A custom implementation can add new entries in the default menu in its
9517     * {@link android.view.ActionMode.Callback#onPrepareActionMode(ActionMode, android.view.Menu)}
9518     * method. The default actions can also be removed from the menu using
9519     * {@link android.view.Menu#removeItem(int)} and passing {@link android.R.id#selectAll},
9520     * {@link android.R.id#cut}, {@link android.R.id#copy}, {@link android.R.id#paste},
9521     * {@link android.R.id#replaceText} or {@link android.R.id#shareText} ids as parameters.
9522     *
9523     * <p>Returning false from
9524     * {@link android.view.ActionMode.Callback#onCreateActionMode(ActionMode, android.view.Menu)}
9525     * will prevent the action mode from being started.
9526     *
9527     * <p>Action click events should be handled by the custom implementation of
9528     * {@link android.view.ActionMode.Callback#onActionItemClicked(ActionMode,
9529     * android.view.MenuItem)}.
9530     *
9531     * <p>Note that text selection mode is not started when a TextView receives focus and the
9532     * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in
9533     * that case, to allow for quick replacement.
9534     */
9535    public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) {
9536        createEditorIfNeeded();
9537        mEditor.mCustomSelectionActionModeCallback = actionModeCallback;
9538    }
9539
9540    /**
9541     * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null.
9542     *
9543     * @return The current custom selection callback.
9544     */
9545    public ActionMode.Callback getCustomSelectionActionModeCallback() {
9546        return mEditor == null ? null : mEditor.mCustomSelectionActionModeCallback;
9547    }
9548
9549    /**
9550     * If provided, this ActionMode.Callback will be used to create the ActionMode when text
9551     * insertion is initiated in this View.
9552     * The standard implementation populates the menu with a subset of Select All,
9553     * Paste and Replace actions, depending on what this View supports.
9554     *
9555     * <p>A custom implementation can add new entries in the default menu in its
9556     * {@link android.view.ActionMode.Callback#onPrepareActionMode(android.view.ActionMode,
9557     * android.view.Menu)} method. The default actions can also be removed from the menu using
9558     * {@link android.view.Menu#removeItem(int)} and passing {@link android.R.id#selectAll},
9559     * {@link android.R.id#paste} or {@link android.R.id#replaceText} ids as parameters.</p>
9560     *
9561     * <p>Returning false from
9562     * {@link android.view.ActionMode.Callback#onCreateActionMode(android.view.ActionMode,
9563     * android.view.Menu)} will prevent the action mode from being started.</p>
9564     *
9565     * <p>Action click events should be handled by the custom implementation of
9566     * {@link android.view.ActionMode.Callback#onActionItemClicked(android.view.ActionMode,
9567     * android.view.MenuItem)}.</p>
9568     *
9569     * <p>Note that text insertion mode is not started when a TextView receives focus and the
9570     * {@link android.R.attr#selectAllOnFocus} flag has been set.</p>
9571     */
9572    public void setCustomInsertionActionModeCallback(ActionMode.Callback actionModeCallback) {
9573        createEditorIfNeeded();
9574        mEditor.mCustomInsertionActionModeCallback = actionModeCallback;
9575    }
9576
9577    /**
9578     * Retrieves the value set in {@link #setCustomInsertionActionModeCallback}. Default is null.
9579     *
9580     * @return The current custom insertion callback.
9581     */
9582    public ActionMode.Callback getCustomInsertionActionModeCallback() {
9583        return mEditor == null ? null : mEditor.mCustomInsertionActionModeCallback;
9584    }
9585
9586    /**
9587     * @hide
9588     */
9589    protected void stopTextActionMode() {
9590        if (mEditor != null) {
9591            mEditor.stopTextActionMode();
9592        }
9593    }
9594
9595    boolean canUndo() {
9596        return mEditor != null && mEditor.canUndo();
9597    }
9598
9599    boolean canRedo() {
9600        return mEditor != null && mEditor.canRedo();
9601    }
9602
9603    boolean canCut() {
9604        if (hasPasswordTransformationMethod()) {
9605            return false;
9606        }
9607
9608        if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mEditor != null
9609                && mEditor.mKeyListener != null) {
9610            return true;
9611        }
9612
9613        return false;
9614    }
9615
9616    boolean canCopy() {
9617        if (hasPasswordTransformationMethod()) {
9618            return false;
9619        }
9620
9621        if (mText.length() > 0 && hasSelection() && mEditor != null) {
9622            return true;
9623        }
9624
9625        return false;
9626    }
9627
9628    boolean canShare() {
9629        if (!getContext().canStartActivityForResult() || !isDeviceProvisioned()) {
9630            return false;
9631        }
9632        return canCopy();
9633    }
9634
9635    boolean isDeviceProvisioned() {
9636        if (mDeviceProvisionedState == DEVICE_PROVISIONED_UNKNOWN) {
9637            mDeviceProvisionedState = Settings.Global.getInt(
9638                    mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 0
9639                    ? DEVICE_PROVISIONED_YES
9640                    : DEVICE_PROVISIONED_NO;
9641        }
9642        return mDeviceProvisionedState == DEVICE_PROVISIONED_YES;
9643    }
9644
9645    boolean canPaste() {
9646        return (mText instanceof Editable
9647                && mEditor != null && mEditor.mKeyListener != null
9648                && getSelectionStart() >= 0
9649                && getSelectionEnd() >= 0
9650                && ((ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE))
9651                        .hasPrimaryClip());
9652    }
9653
9654    boolean canProcessText() {
9655        if (getId() == View.NO_ID) {
9656            return false;
9657        }
9658        return canShare();
9659    }
9660
9661    boolean canSelectAllText() {
9662        return canSelectText() && !hasPasswordTransformationMethod()
9663                && !(getSelectionStart() == 0 && getSelectionEnd() == mText.length());
9664    }
9665
9666    boolean selectAllText() {
9667        final int length = mText.length();
9668        Selection.setSelection((Spannable) mText, 0, length);
9669        return length > 0;
9670    }
9671
9672    void replaceSelectionWithText(CharSequence text) {
9673        ((Editable) mText).replace(getSelectionStart(), getSelectionEnd(), text);
9674    }
9675
9676    /**
9677     * Paste clipboard content between min and max positions.
9678     */
9679    private void paste(int min, int max, boolean withFormatting) {
9680        ClipboardManager clipboard =
9681                (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
9682        ClipData clip = clipboard.getPrimaryClip();
9683        if (clip != null) {
9684            boolean didFirst = false;
9685            for (int i = 0; i < clip.getItemCount(); i++) {
9686                final CharSequence paste;
9687                if (withFormatting) {
9688                    paste = clip.getItemAt(i).coerceToStyledText(getContext());
9689                } else {
9690                    // Get an item as text and remove all spans by toString().
9691                    final CharSequence text = clip.getItemAt(i).coerceToText(getContext());
9692                    paste = (text instanceof Spanned) ? text.toString() : text;
9693                }
9694                if (paste != null) {
9695                    if (!didFirst) {
9696                        Selection.setSelection((Spannable) mText, max);
9697                        ((Editable) mText).replace(min, max, paste);
9698                        didFirst = true;
9699                    } else {
9700                        ((Editable) mText).insert(getSelectionEnd(), "\n");
9701                        ((Editable) mText).insert(getSelectionEnd(), paste);
9702                    }
9703                }
9704            }
9705            sLastCutCopyOrTextChangedTime = 0;
9706        }
9707    }
9708
9709    private void shareSelectedText() {
9710        String selectedText = getSelectedText();
9711        if (selectedText != null && !selectedText.isEmpty()) {
9712            Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
9713            sharingIntent.setType("text/plain");
9714            sharingIntent.removeExtra(android.content.Intent.EXTRA_TEXT);
9715            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, selectedText);
9716            getContext().startActivity(Intent.createChooser(sharingIntent, null));
9717            Selection.setSelection((Spannable) mText, getSelectionEnd());
9718        }
9719    }
9720
9721    private void setPrimaryClip(ClipData clip) {
9722        ClipboardManager clipboard =
9723                (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
9724        clipboard.setPrimaryClip(clip);
9725        sLastCutCopyOrTextChangedTime = SystemClock.uptimeMillis();
9726    }
9727
9728    /**
9729     * Get the character offset closest to the specified absolute position. A typical use case is to
9730     * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method.
9731     *
9732     * @param x The horizontal absolute position of a point on screen
9733     * @param y The vertical absolute position of a point on screen
9734     * @return the character offset for the character whose position is closest to the specified
9735     *  position. Returns -1 if there is no layout.
9736     */
9737    public int getOffsetForPosition(float x, float y) {
9738        if (getLayout() == null) return -1;
9739        final int line = getLineAtCoordinate(y);
9740        final int offset = getOffsetAtCoordinate(line, x);
9741        return offset;
9742    }
9743
9744    float convertToLocalHorizontalCoordinate(float x) {
9745        x -= getTotalPaddingLeft();
9746        // Clamp the position to inside of the view.
9747        x = Math.max(0.0f, x);
9748        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
9749        x += getScrollX();
9750        return x;
9751    }
9752
9753    int getLineAtCoordinate(float y) {
9754        y -= getTotalPaddingTop();
9755        // Clamp the position to inside of the view.
9756        y = Math.max(0.0f, y);
9757        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
9758        y += getScrollY();
9759        return getLayout().getLineForVertical((int) y);
9760    }
9761
9762    int getLineAtCoordinateUnclamped(float y) {
9763        y -= getTotalPaddingTop();
9764        y += getScrollY();
9765        return getLayout().getLineForVertical((int) y);
9766    }
9767
9768    int getOffsetAtCoordinate(int line, float x) {
9769        x = convertToLocalHorizontalCoordinate(x);
9770        return getLayout().getOffsetForHorizontal(line, x);
9771    }
9772
9773    @Override
9774    public boolean onDragEvent(DragEvent event) {
9775        switch (event.getAction()) {
9776            case DragEvent.ACTION_DRAG_STARTED:
9777                return mEditor != null && mEditor.hasInsertionController();
9778
9779            case DragEvent.ACTION_DRAG_ENTERED:
9780                TextView.this.requestFocus();
9781                return true;
9782
9783            case DragEvent.ACTION_DRAG_LOCATION:
9784                final int offset = getOffsetForPosition(event.getX(), event.getY());
9785                Selection.setSelection((Spannable) mText, offset);
9786                return true;
9787
9788            case DragEvent.ACTION_DROP:
9789                if (mEditor != null) mEditor.onDrop(event);
9790                return true;
9791
9792            case DragEvent.ACTION_DRAG_ENDED:
9793            case DragEvent.ACTION_DRAG_EXITED:
9794            default:
9795                return true;
9796        }
9797    }
9798
9799    boolean isInBatchEditMode() {
9800        if (mEditor == null) return false;
9801        final Editor.InputMethodState ims = mEditor.mInputMethodState;
9802        if (ims != null) {
9803            return ims.mBatchEditNesting > 0;
9804        }
9805        return mEditor.mInBatchEditControllers;
9806    }
9807
9808    @Override
9809    public void onRtlPropertiesChanged(int layoutDirection) {
9810        super.onRtlPropertiesChanged(layoutDirection);
9811
9812        final TextDirectionHeuristic newTextDir = getTextDirectionHeuristic();
9813        if (mTextDir != newTextDir) {
9814            mTextDir = newTextDir;
9815            if (mLayout != null) {
9816                checkForRelayout();
9817            }
9818        }
9819    }
9820
9821    /**
9822     * @hide
9823     */
9824    protected TextDirectionHeuristic getTextDirectionHeuristic() {
9825        if (hasPasswordTransformationMethod()) {
9826            // passwords fields should be LTR
9827            return TextDirectionHeuristics.LTR;
9828        }
9829
9830        // Always need to resolve layout direction first
9831        final boolean defaultIsRtl = (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
9832
9833        // Now, we can select the heuristic
9834        switch (getTextDirection()) {
9835            default:
9836            case TEXT_DIRECTION_FIRST_STRONG:
9837                return (defaultIsRtl ? TextDirectionHeuristics.FIRSTSTRONG_RTL :
9838                        TextDirectionHeuristics.FIRSTSTRONG_LTR);
9839            case TEXT_DIRECTION_ANY_RTL:
9840                return TextDirectionHeuristics.ANYRTL_LTR;
9841            case TEXT_DIRECTION_LTR:
9842                return TextDirectionHeuristics.LTR;
9843            case TEXT_DIRECTION_RTL:
9844                return TextDirectionHeuristics.RTL;
9845            case TEXT_DIRECTION_LOCALE:
9846                return TextDirectionHeuristics.LOCALE;
9847            case TEXT_DIRECTION_FIRST_STRONG_LTR:
9848                return TextDirectionHeuristics.FIRSTSTRONG_LTR;
9849            case TEXT_DIRECTION_FIRST_STRONG_RTL:
9850                return TextDirectionHeuristics.FIRSTSTRONG_RTL;
9851        }
9852    }
9853
9854    /**
9855     * @hide
9856     */
9857    @Override
9858    public void onResolveDrawables(int layoutDirection) {
9859        // No need to resolve twice
9860        if (mLastLayoutDirection == layoutDirection) {
9861            return;
9862        }
9863        mLastLayoutDirection = layoutDirection;
9864
9865        // Resolve drawables
9866        if (mDrawables != null) {
9867            if (mDrawables.resolveWithLayoutDirection(layoutDirection)) {
9868                prepareDrawableForDisplay(mDrawables.mShowing[Drawables.LEFT]);
9869                prepareDrawableForDisplay(mDrawables.mShowing[Drawables.RIGHT]);
9870                applyCompoundDrawableTint();
9871            }
9872        }
9873    }
9874
9875    /**
9876     * Prepares a drawable for display by propagating layout direction and
9877     * drawable state.
9878     *
9879     * @param dr the drawable to prepare
9880     */
9881    private void prepareDrawableForDisplay(@Nullable Drawable dr) {
9882        if (dr == null) {
9883            return;
9884        }
9885
9886        dr.setLayoutDirection(getLayoutDirection());
9887
9888        if (dr.isStateful()) {
9889            dr.setState(getDrawableState());
9890            dr.jumpToCurrentState();
9891        }
9892    }
9893
9894    /**
9895     * @hide
9896     */
9897    protected void resetResolvedDrawables() {
9898        super.resetResolvedDrawables();
9899        mLastLayoutDirection = -1;
9900    }
9901
9902    /**
9903     * @hide
9904     */
9905    protected void viewClicked(InputMethodManager imm) {
9906        if (imm != null) {
9907            imm.viewClicked(this);
9908        }
9909    }
9910
9911    /**
9912     * Deletes the range of text [start, end[.
9913     * @hide
9914     */
9915    protected void deleteText_internal(int start, int end) {
9916        ((Editable) mText).delete(start, end);
9917    }
9918
9919    /**
9920     * Replaces the range of text [start, end[ by replacement text
9921     * @hide
9922     */
9923    protected void replaceText_internal(int start, int end, CharSequence text) {
9924        ((Editable) mText).replace(start, end, text);
9925    }
9926
9927    /**
9928     * Sets a span on the specified range of text
9929     * @hide
9930     */
9931    protected void setSpan_internal(Object span, int start, int end, int flags) {
9932        ((Editable) mText).setSpan(span, start, end, flags);
9933    }
9934
9935    /**
9936     * Moves the cursor to the specified offset position in text
9937     * @hide
9938     */
9939    protected void setCursorPosition_internal(int start, int end) {
9940        Selection.setSelection(((Editable) mText), start, end);
9941    }
9942
9943    /**
9944     * An Editor should be created as soon as any of the editable-specific fields (grouped
9945     * inside the Editor object) is assigned to a non-default value.
9946     * This method will create the Editor if needed.
9947     *
9948     * A standard TextView (as well as buttons, checkboxes...) should not qualify and hence will
9949     * have a null Editor, unlike an EditText. Inconsistent in-between states will have an
9950     * Editor for backward compatibility, as soon as one of these fields is assigned.
9951     *
9952     * Also note that for performance reasons, the mEditor is created when needed, but not
9953     * reset when no more edit-specific fields are needed.
9954     */
9955    private void createEditorIfNeeded() {
9956        if (mEditor == null) {
9957            mEditor = new Editor(this);
9958        }
9959    }
9960
9961    /**
9962     * @hide
9963     */
9964    @Override
9965    public CharSequence getIterableTextForAccessibility() {
9966        return mText;
9967    }
9968
9969    private void ensureIterableTextForAccessibilitySelectable() {
9970        if (!(mText instanceof Spannable)) {
9971            setText(mText, BufferType.SPANNABLE);
9972        }
9973    }
9974
9975    /**
9976     * @hide
9977     */
9978    @Override
9979    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9980        switch (granularity) {
9981            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE: {
9982                Spannable text = (Spannable) getIterableTextForAccessibility();
9983                if (!TextUtils.isEmpty(text) && getLayout() != null) {
9984                    AccessibilityIterators.LineTextSegmentIterator iterator =
9985                            AccessibilityIterators.LineTextSegmentIterator.getInstance();
9986                    iterator.initialize(text, getLayout());
9987                    return iterator;
9988                }
9989            } break;
9990            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE: {
9991                Spannable text = (Spannable) getIterableTextForAccessibility();
9992                if (!TextUtils.isEmpty(text) && getLayout() != null) {
9993                    AccessibilityIterators.PageTextSegmentIterator iterator =
9994                            AccessibilityIterators.PageTextSegmentIterator.getInstance();
9995                    iterator.initialize(this);
9996                    return iterator;
9997                }
9998            } break;
9999        }
10000        return super.getIteratorForGranularity(granularity);
10001    }
10002
10003    /**
10004     * @hide
10005     */
10006    @Override
10007    public int getAccessibilitySelectionStart() {
10008        return getSelectionStart();
10009    }
10010
10011    /**
10012     * @hide
10013     */
10014    public boolean isAccessibilitySelectionExtendable() {
10015        return true;
10016    }
10017
10018    /**
10019     * @hide
10020     */
10021    @Override
10022    public int getAccessibilitySelectionEnd() {
10023        return getSelectionEnd();
10024    }
10025
10026    /**
10027     * @hide
10028     */
10029    @Override
10030    public void setAccessibilitySelection(int start, int end) {
10031        if (getAccessibilitySelectionStart() == start
10032                && getAccessibilitySelectionEnd() == end) {
10033            return;
10034        }
10035        CharSequence text = getIterableTextForAccessibility();
10036        if (Math.min(start, end) >= 0 && Math.max(start, end) <= text.length()) {
10037            Selection.setSelection((Spannable) text, start, end);
10038        } else {
10039            Selection.removeSelection((Spannable) text);
10040        }
10041        // Hide all selection controllers used for adjusting selection
10042        // since we are doing so explicitlty by other means and these
10043        // controllers interact with how selection behaves.
10044        if (mEditor != null) {
10045            mEditor.hideCursorAndSpanControllers();
10046            mEditor.stopTextActionMode();
10047        }
10048    }
10049
10050    /** @hide */
10051    @Override
10052    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
10053        super.encodeProperties(stream);
10054
10055        TruncateAt ellipsize = getEllipsize();
10056        stream.addProperty("text:ellipsize", ellipsize == null ? null : ellipsize.name());
10057        stream.addProperty("text:textSize", getTextSize());
10058        stream.addProperty("text:scaledTextSize", getScaledTextSize());
10059        stream.addProperty("text:typefaceStyle", getTypefaceStyle());
10060        stream.addProperty("text:selectionStart", getSelectionStart());
10061        stream.addProperty("text:selectionEnd", getSelectionEnd());
10062        stream.addProperty("text:curTextColor", mCurTextColor);
10063        stream.addProperty("text:text", mText == null ? null : mText.toString());
10064        stream.addProperty("text:gravity", mGravity);
10065    }
10066
10067    /**
10068     * User interface state that is stored by TextView for implementing
10069     * {@link View#onSaveInstanceState}.
10070     */
10071    public static class SavedState extends BaseSavedState {
10072        int selStart = -1;
10073        int selEnd = -1;
10074        CharSequence text;
10075        boolean frozenWithFocus;
10076        CharSequence error;
10077        ParcelableParcel editorState;  // Optional state from Editor.
10078
10079        SavedState(Parcelable superState) {
10080            super(superState);
10081        }
10082
10083        @Override
10084        public void writeToParcel(Parcel out, int flags) {
10085            super.writeToParcel(out, flags);
10086            out.writeInt(selStart);
10087            out.writeInt(selEnd);
10088            out.writeInt(frozenWithFocus ? 1 : 0);
10089            TextUtils.writeToParcel(text, out, flags);
10090
10091            if (error == null) {
10092                out.writeInt(0);
10093            } else {
10094                out.writeInt(1);
10095                TextUtils.writeToParcel(error, out, flags);
10096            }
10097
10098            if (editorState == null) {
10099                out.writeInt(0);
10100            } else {
10101                out.writeInt(1);
10102                editorState.writeToParcel(out, flags);
10103            }
10104        }
10105
10106        @Override
10107        public String toString() {
10108            String str = "TextView.SavedState{"
10109                    + Integer.toHexString(System.identityHashCode(this))
10110                    + " start=" + selStart + " end=" + selEnd;
10111            if (text != null) {
10112                str += " text=" + text;
10113            }
10114            return str + "}";
10115        }
10116
10117        @SuppressWarnings("hiding")
10118        public static final Parcelable.Creator<SavedState> CREATOR =
10119                new Parcelable.Creator<SavedState>() {
10120                    public SavedState createFromParcel(Parcel in) {
10121                        return new SavedState(in);
10122                    }
10123
10124                    public SavedState[] newArray(int size) {
10125                        return new SavedState[size];
10126                    }
10127                };
10128
10129        private SavedState(Parcel in) {
10130            super(in);
10131            selStart = in.readInt();
10132            selEnd = in.readInt();
10133            frozenWithFocus = (in.readInt() != 0);
10134            text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
10135
10136            if (in.readInt() != 0) {
10137                error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
10138            }
10139
10140            if (in.readInt() != 0) {
10141                editorState = ParcelableParcel.CREATOR.createFromParcel(in);
10142            }
10143        }
10144    }
10145
10146    private static class CharWrapper implements CharSequence, GetChars, GraphicsOperations {
10147        private char[] mChars;
10148        private int mStart, mLength;
10149
10150        public CharWrapper(char[] chars, int start, int len) {
10151            mChars = chars;
10152            mStart = start;
10153            mLength = len;
10154        }
10155
10156        /* package */ void set(char[] chars, int start, int len) {
10157            mChars = chars;
10158            mStart = start;
10159            mLength = len;
10160        }
10161
10162        public int length() {
10163            return mLength;
10164        }
10165
10166        public char charAt(int off) {
10167            return mChars[off + mStart];
10168        }
10169
10170        @Override
10171        public String toString() {
10172            return new String(mChars, mStart, mLength);
10173        }
10174
10175        public CharSequence subSequence(int start, int end) {
10176            if (start < 0 || end < 0 || start > mLength || end > mLength) {
10177                throw new IndexOutOfBoundsException(start + ", " + end);
10178            }
10179
10180            return new String(mChars, start + mStart, end - start);
10181        }
10182
10183        public void getChars(int start, int end, char[] buf, int off) {
10184            if (start < 0 || end < 0 || start > mLength || end > mLength) {
10185                throw new IndexOutOfBoundsException(start + ", " + end);
10186            }
10187
10188            System.arraycopy(mChars, start + mStart, buf, off, end - start);
10189        }
10190
10191        public void drawText(Canvas c, int start, int end,
10192                             float x, float y, Paint p) {
10193            c.drawText(mChars, start + mStart, end - start, x, y, p);
10194        }
10195
10196        public void drawTextRun(Canvas c, int start, int end,
10197                int contextStart, int contextEnd, float x, float y, boolean isRtl, Paint p) {
10198            int count = end - start;
10199            int contextCount = contextEnd - contextStart;
10200            c.drawTextRun(mChars, start + mStart, count, contextStart + mStart,
10201                    contextCount, x, y, isRtl, p);
10202        }
10203
10204        public float measureText(int start, int end, Paint p) {
10205            return p.measureText(mChars, start + mStart, end - start);
10206        }
10207
10208        public int getTextWidths(int start, int end, float[] widths, Paint p) {
10209            return p.getTextWidths(mChars, start + mStart, end - start, widths);
10210        }
10211
10212        public float getTextRunAdvances(int start, int end, int contextStart,
10213                int contextEnd, boolean isRtl, float[] advances, int advancesIndex,
10214                Paint p) {
10215            int count = end - start;
10216            int contextCount = contextEnd - contextStart;
10217            return p.getTextRunAdvances(mChars, start + mStart, count,
10218                    contextStart + mStart, contextCount, isRtl, advances,
10219                    advancesIndex);
10220        }
10221
10222        public int getTextRunCursor(int contextStart, int contextEnd, int dir,
10223                int offset, int cursorOpt, Paint p) {
10224            int contextCount = contextEnd - contextStart;
10225            return p.getTextRunCursor(mChars, contextStart + mStart,
10226                    contextCount, dir, offset + mStart, cursorOpt);
10227        }
10228    }
10229
10230    private static final class Marquee {
10231        // TODO: Add an option to configure this
10232        private static final float MARQUEE_DELTA_MAX = 0.07f;
10233        private static final int MARQUEE_DELAY = 1200;
10234        private static final int MARQUEE_DP_PER_SECOND = 30;
10235
10236        private static final byte MARQUEE_STOPPED = 0x0;
10237        private static final byte MARQUEE_STARTING = 0x1;
10238        private static final byte MARQUEE_RUNNING = 0x2;
10239
10240        private final WeakReference<TextView> mView;
10241        private final Choreographer mChoreographer;
10242
10243        private byte mStatus = MARQUEE_STOPPED;
10244        private final float mPixelsPerSecond;
10245        private float mMaxScroll;
10246        private float mMaxFadeScroll;
10247        private float mGhostStart;
10248        private float mGhostOffset;
10249        private float mFadeStop;
10250        private int mRepeatLimit;
10251
10252        private float mScroll;
10253        private long mLastAnimationMs;
10254
10255        Marquee(TextView v) {
10256            final float density = v.getContext().getResources().getDisplayMetrics().density;
10257            mPixelsPerSecond = MARQUEE_DP_PER_SECOND * density;
10258            mView = new WeakReference<TextView>(v);
10259            mChoreographer = Choreographer.getInstance();
10260        }
10261
10262        private Choreographer.FrameCallback mTickCallback = new Choreographer.FrameCallback() {
10263            @Override
10264            public void doFrame(long frameTimeNanos) {
10265                tick();
10266            }
10267        };
10268
10269        private Choreographer.FrameCallback mStartCallback = new Choreographer.FrameCallback() {
10270            @Override
10271            public void doFrame(long frameTimeNanos) {
10272                mStatus = MARQUEE_RUNNING;
10273                mLastAnimationMs = mChoreographer.getFrameTime();
10274                tick();
10275            }
10276        };
10277
10278        private Choreographer.FrameCallback mRestartCallback = new Choreographer.FrameCallback() {
10279            @Override
10280            public void doFrame(long frameTimeNanos) {
10281                if (mStatus == MARQUEE_RUNNING) {
10282                    if (mRepeatLimit >= 0) {
10283                        mRepeatLimit--;
10284                    }
10285                    start(mRepeatLimit);
10286                }
10287            }
10288        };
10289
10290        void tick() {
10291            if (mStatus != MARQUEE_RUNNING) {
10292                return;
10293            }
10294
10295            mChoreographer.removeFrameCallback(mTickCallback);
10296
10297            final TextView textView = mView.get();
10298            if (textView != null && (textView.isFocused() || textView.isSelected())) {
10299                long currentMs = mChoreographer.getFrameTime();
10300                long deltaMs = currentMs - mLastAnimationMs;
10301                mLastAnimationMs = currentMs;
10302                float deltaPx = deltaMs / 1000f * mPixelsPerSecond;
10303                mScroll += deltaPx;
10304                if (mScroll > mMaxScroll) {
10305                    mScroll = mMaxScroll;
10306                    mChoreographer.postFrameCallbackDelayed(mRestartCallback, MARQUEE_DELAY);
10307                } else {
10308                    mChoreographer.postFrameCallback(mTickCallback);
10309                }
10310                textView.invalidate();
10311            }
10312        }
10313
10314        void stop() {
10315            mStatus = MARQUEE_STOPPED;
10316            mChoreographer.removeFrameCallback(mStartCallback);
10317            mChoreographer.removeFrameCallback(mRestartCallback);
10318            mChoreographer.removeFrameCallback(mTickCallback);
10319            resetScroll();
10320        }
10321
10322        private void resetScroll() {
10323            mScroll = 0.0f;
10324            final TextView textView = mView.get();
10325            if (textView != null) textView.invalidate();
10326        }
10327
10328        void start(int repeatLimit) {
10329            if (repeatLimit == 0) {
10330                stop();
10331                return;
10332            }
10333            mRepeatLimit = repeatLimit;
10334            final TextView textView = mView.get();
10335            if (textView != null && textView.mLayout != null) {
10336                mStatus = MARQUEE_STARTING;
10337                mScroll = 0.0f;
10338                final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft()
10339                        - textView.getCompoundPaddingRight();
10340                final float lineWidth = textView.mLayout.getLineWidth(0);
10341                final float gap = textWidth / 3.0f;
10342                mGhostStart = lineWidth - textWidth + gap;
10343                mMaxScroll = mGhostStart + textWidth;
10344                mGhostOffset = lineWidth + gap;
10345                mFadeStop = lineWidth + textWidth / 6.0f;
10346                mMaxFadeScroll = mGhostStart + lineWidth + lineWidth;
10347
10348                textView.invalidate();
10349                mChoreographer.postFrameCallback(mStartCallback);
10350            }
10351        }
10352
10353        float getGhostOffset() {
10354            return mGhostOffset;
10355        }
10356
10357        float getScroll() {
10358            return mScroll;
10359        }
10360
10361        float getMaxFadeScroll() {
10362            return mMaxFadeScroll;
10363        }
10364
10365        boolean shouldDrawLeftFade() {
10366            return mScroll <= mFadeStop;
10367        }
10368
10369        boolean shouldDrawGhost() {
10370            return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart;
10371        }
10372
10373        boolean isRunning() {
10374            return mStatus == MARQUEE_RUNNING;
10375        }
10376
10377        boolean isStopped() {
10378            return mStatus == MARQUEE_STOPPED;
10379        }
10380    }
10381
10382    private class ChangeWatcher implements TextWatcher, SpanWatcher {
10383
10384        private CharSequence mBeforeText;
10385
10386        public void beforeTextChanged(CharSequence buffer, int start,
10387                                      int before, int after) {
10388            if (DEBUG_EXTRACT) {
10389                Log.v(LOG_TAG, "beforeTextChanged start=" + start
10390                        + " before=" + before + " after=" + after + ": " + buffer);
10391            }
10392
10393            if (AccessibilityManager.getInstance(mContext).isEnabled()
10394                    && ((!isPasswordInputType(getInputType()) && !hasPasswordTransformationMethod())
10395                            || shouldSpeakPasswordsForAccessibility())) {
10396                mBeforeText = buffer.toString();
10397            }
10398
10399            TextView.this.sendBeforeTextChanged(buffer, start, before, after);
10400        }
10401
10402        public void onTextChanged(CharSequence buffer, int start, int before, int after) {
10403            if (DEBUG_EXTRACT) {
10404                Log.v(LOG_TAG, "onTextChanged start=" + start
10405                        + " before=" + before + " after=" + after + ": " + buffer);
10406            }
10407            TextView.this.handleTextChanged(buffer, start, before, after);
10408
10409            if (AccessibilityManager.getInstance(mContext).isEnabled()
10410                    && (isFocused() || isSelected() && isShown())) {
10411                sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after);
10412                mBeforeText = null;
10413            }
10414        }
10415
10416        public void afterTextChanged(Editable buffer) {
10417            if (DEBUG_EXTRACT) {
10418                Log.v(LOG_TAG, "afterTextChanged: " + buffer);
10419            }
10420            TextView.this.sendAfterTextChanged(buffer);
10421
10422            if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) {
10423                MetaKeyKeyListener.stopSelecting(TextView.this, buffer);
10424            }
10425        }
10426
10427        public void onSpanChanged(Spannable buf, Object what, int s, int e, int st, int en) {
10428            if (DEBUG_EXTRACT) {
10429                Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e
10430                        + " st=" + st + " en=" + en + " what=" + what + ": " + buf);
10431            }
10432            TextView.this.spanChange(buf, what, s, st, e, en);
10433        }
10434
10435        public void onSpanAdded(Spannable buf, Object what, int s, int e) {
10436            if (DEBUG_EXTRACT) {
10437                Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e + " what=" + what + ": " + buf);
10438            }
10439            TextView.this.spanChange(buf, what, -1, s, -1, e);
10440        }
10441
10442        public void onSpanRemoved(Spannable buf, Object what, int s, int e) {
10443            if (DEBUG_EXTRACT) {
10444                Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e + " what=" + what + ": " + buf);
10445            }
10446            TextView.this.spanChange(buf, what, s, -1, e, -1);
10447        }
10448    }
10449}
10450