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