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