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