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