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