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