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