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