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