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