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