TextView.java revision ea32f94ec4c14fe21b536139762c5332d1b5484c
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.ArrowKeyMovementMethod;
67import android.text.method.DateKeyListener;
68import android.text.method.DateTimeKeyListener;
69import android.text.method.DialerKeyListener;
70import android.text.method.DigitsKeyListener;
71import android.text.method.KeyListener;
72import android.text.method.LinkMovementMethod;
73import android.text.method.MetaKeyKeyListener;
74import android.text.method.MovementMethod;
75import android.text.method.PasswordTransformationMethod;
76import android.text.method.SingleLineTransformationMethod;
77import android.text.method.TextKeyListener;
78import android.text.method.TimeKeyListener;
79import android.text.method.TransformationMethod;
80import android.text.style.ParagraphStyle;
81import android.text.style.URLSpan;
82import android.text.style.UpdateAppearance;
83import android.text.util.Linkify;
84import android.util.AttributeSet;
85import android.util.FloatMath;
86import android.util.Log;
87import android.util.TypedValue;
88import android.view.ContextMenu;
89import android.view.Gravity;
90import android.view.KeyEvent;
91import android.view.LayoutInflater;
92import android.view.MenuItem;
93import android.view.MotionEvent;
94import android.view.View;
95import android.view.ViewConfiguration;
96import android.view.ViewDebug;
97import android.view.ViewGroup.LayoutParams;
98import android.view.ViewRoot;
99import android.view.ViewTreeObserver;
100import android.view.accessibility.AccessibilityEvent;
101import android.view.accessibility.AccessibilityManager;
102import android.view.animation.AnimationUtils;
103import android.view.inputmethod.BaseInputConnection;
104import android.view.inputmethod.CompletionInfo;
105import android.view.inputmethod.EditorInfo;
106import android.view.inputmethod.ExtractedText;
107import android.view.inputmethod.ExtractedTextRequest;
108import android.view.inputmethod.InputConnection;
109import android.view.inputmethod.InputMethodManager;
110import android.widget.RemoteViews.RemoteView;
111
112import java.io.IOException;
113import java.lang.ref.WeakReference;
114import java.util.ArrayList;
115
116/**
117 * Displays text to the user and optionally allows them to edit it.  A TextView
118 * is a complete text editor, however the basic class is configured to not
119 * allow editing; see {@link EditText} for a subclass that configures the text
120 * view for editing.
121 *
122 * <p>
123 * <b>XML attributes</b>
124 * <p>
125 * See {@link android.R.styleable#TextView TextView Attributes},
126 * {@link android.R.styleable#View View Attributes}
127 *
128 * @attr ref android.R.styleable#TextView_text
129 * @attr ref android.R.styleable#TextView_bufferType
130 * @attr ref android.R.styleable#TextView_hint
131 * @attr ref android.R.styleable#TextView_textColor
132 * @attr ref android.R.styleable#TextView_textColorHighlight
133 * @attr ref android.R.styleable#TextView_textColorHint
134 * @attr ref android.R.styleable#TextView_textAppearance
135 * @attr ref android.R.styleable#TextView_textColorLink
136 * @attr ref android.R.styleable#TextView_textSize
137 * @attr ref android.R.styleable#TextView_textScaleX
138 * @attr ref android.R.styleable#TextView_typeface
139 * @attr ref android.R.styleable#TextView_textStyle
140 * @attr ref android.R.styleable#TextView_cursorVisible
141 * @attr ref android.R.styleable#TextView_maxLines
142 * @attr ref android.R.styleable#TextView_maxHeight
143 * @attr ref android.R.styleable#TextView_lines
144 * @attr ref android.R.styleable#TextView_height
145 * @attr ref android.R.styleable#TextView_minLines
146 * @attr ref android.R.styleable#TextView_minHeight
147 * @attr ref android.R.styleable#TextView_maxEms
148 * @attr ref android.R.styleable#TextView_maxWidth
149 * @attr ref android.R.styleable#TextView_ems
150 * @attr ref android.R.styleable#TextView_width
151 * @attr ref android.R.styleable#TextView_minEms
152 * @attr ref android.R.styleable#TextView_minWidth
153 * @attr ref android.R.styleable#TextView_gravity
154 * @attr ref android.R.styleable#TextView_scrollHorizontally
155 * @attr ref android.R.styleable#TextView_password
156 * @attr ref android.R.styleable#TextView_singleLine
157 * @attr ref android.R.styleable#TextView_selectAllOnFocus
158 * @attr ref android.R.styleable#TextView_includeFontPadding
159 * @attr ref android.R.styleable#TextView_maxLength
160 * @attr ref android.R.styleable#TextView_shadowColor
161 * @attr ref android.R.styleable#TextView_shadowDx
162 * @attr ref android.R.styleable#TextView_shadowDy
163 * @attr ref android.R.styleable#TextView_shadowRadius
164 * @attr ref android.R.styleable#TextView_autoLink
165 * @attr ref android.R.styleable#TextView_linksClickable
166 * @attr ref android.R.styleable#TextView_numeric
167 * @attr ref android.R.styleable#TextView_digits
168 * @attr ref android.R.styleable#TextView_phoneNumber
169 * @attr ref android.R.styleable#TextView_inputMethod
170 * @attr ref android.R.styleable#TextView_capitalize
171 * @attr ref android.R.styleable#TextView_autoText
172 * @attr ref android.R.styleable#TextView_editable
173 * @attr ref android.R.styleable#TextView_freezesText
174 * @attr ref android.R.styleable#TextView_ellipsize
175 * @attr ref android.R.styleable#TextView_drawableTop
176 * @attr ref android.R.styleable#TextView_drawableBottom
177 * @attr ref android.R.styleable#TextView_drawableRight
178 * @attr ref android.R.styleable#TextView_drawableLeft
179 * @attr ref android.R.styleable#TextView_drawablePadding
180 * @attr ref android.R.styleable#TextView_lineSpacingExtra
181 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier
182 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
183 * @attr ref android.R.styleable#TextView_inputType
184 * @attr ref android.R.styleable#TextView_imeOptions
185 * @attr ref android.R.styleable#TextView_privateImeOptions
186 * @attr ref android.R.styleable#TextView_imeActionLabel
187 * @attr ref android.R.styleable#TextView_imeActionId
188 * @attr ref android.R.styleable#TextView_editorExtras
189 */
190@RemoteView
191public class TextView extends View implements ViewTreeObserver.OnPreDrawListener {
192    static final String LOG_TAG = "TextView";
193    static final boolean DEBUG_EXTRACT = false;
194
195    private static int PRIORITY = 100;
196
197    private final int[] mTempCoords = new int[2];
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 canSelectText, 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 canSelectText, 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
3756    @Override
3757    protected void onDetachedFromWindow() {
3758        super.onDetachedFromWindow();
3759
3760        if (mPreDrawState != PREDRAW_NOT_REGISTERED) {
3761            final ViewTreeObserver observer = getViewTreeObserver();
3762            if (observer != null) {
3763                observer.removeOnPreDrawListener(this);
3764                mPreDrawState = PREDRAW_NOT_REGISTERED;
3765            }
3766        }
3767
3768        if (mError != null) {
3769            hideError();
3770        }
3771
3772        hideControllers();
3773    }
3774
3775    @Override
3776    protected boolean isPaddingOffsetRequired() {
3777        return mShadowRadius != 0 || mDrawables != null;
3778    }
3779
3780    @Override
3781    protected int getLeftPaddingOffset() {
3782        return getCompoundPaddingLeft() - mPaddingLeft +
3783                (int) Math.min(0, mShadowDx - mShadowRadius);
3784    }
3785
3786    @Override
3787    protected int getTopPaddingOffset() {
3788        return (int) Math.min(0, mShadowDy - mShadowRadius);
3789    }
3790
3791    @Override
3792    protected int getBottomPaddingOffset() {
3793        return (int) Math.max(0, mShadowDy + mShadowRadius);
3794    }
3795
3796    @Override
3797    protected int getRightPaddingOffset() {
3798        return -(getCompoundPaddingRight() - mPaddingRight) +
3799                (int) Math.max(0, mShadowDx + mShadowRadius);
3800    }
3801
3802    @Override
3803    protected boolean verifyDrawable(Drawable who) {
3804        final boolean verified = super.verifyDrawable(who);
3805        if (!verified && mDrawables != null) {
3806            return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop ||
3807                    who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom;
3808        }
3809        return verified;
3810    }
3811
3812    @Override
3813    public void invalidateDrawable(Drawable drawable) {
3814        if (verifyDrawable(drawable)) {
3815            final Rect dirty = drawable.getBounds();
3816            int scrollX = mScrollX;
3817            int scrollY = mScrollY;
3818
3819            // IMPORTANT: The coordinates below are based on the coordinates computed
3820            // for each compound drawable in onDraw(). Make sure to update each section
3821            // accordingly.
3822            final TextView.Drawables drawables = mDrawables;
3823            if (drawables != null) {
3824                if (drawable == drawables.mDrawableLeft) {
3825                    final int compoundPaddingTop = getCompoundPaddingTop();
3826                    final int compoundPaddingBottom = getCompoundPaddingBottom();
3827                    final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
3828
3829                    scrollX += mPaddingLeft;
3830                    scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2;
3831                } else if (drawable == drawables.mDrawableRight) {
3832                    final int compoundPaddingTop = getCompoundPaddingTop();
3833                    final int compoundPaddingBottom = getCompoundPaddingBottom();
3834                    final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
3835
3836                    scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight);
3837                    scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2;
3838                } else if (drawable == drawables.mDrawableTop) {
3839                    final int compoundPaddingLeft = getCompoundPaddingLeft();
3840                    final int compoundPaddingRight = getCompoundPaddingRight();
3841                    final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft;
3842
3843                    scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2;
3844                    scrollY += mPaddingTop;
3845                } else if (drawable == drawables.mDrawableBottom) {
3846                    final int compoundPaddingLeft = getCompoundPaddingLeft();
3847                    final int compoundPaddingRight = getCompoundPaddingRight();
3848                    final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft;
3849
3850                    scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2;
3851                    scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom);
3852                }
3853            }
3854
3855            invalidate(dirty.left + scrollX, dirty.top + scrollY,
3856                    dirty.right + scrollX, dirty.bottom + scrollY);
3857        }
3858    }
3859
3860    @Override
3861    protected void onDraw(Canvas canvas) {
3862        restartMarqueeIfNeeded();
3863
3864        // Draw the background for this view
3865        super.onDraw(canvas);
3866
3867        final int compoundPaddingLeft = getCompoundPaddingLeft();
3868        final int compoundPaddingTop = getCompoundPaddingTop();
3869        final int compoundPaddingRight = getCompoundPaddingRight();
3870        final int compoundPaddingBottom = getCompoundPaddingBottom();
3871        final int scrollX = mScrollX;
3872        final int scrollY = mScrollY;
3873        final int right = mRight;
3874        final int left = mLeft;
3875        final int bottom = mBottom;
3876        final int top = mTop;
3877
3878        final Drawables dr = mDrawables;
3879        if (dr != null) {
3880            /*
3881             * Compound, not extended, because the icon is not clipped
3882             * if the text height is smaller.
3883             */
3884
3885            int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop;
3886            int hspace = right - left - compoundPaddingRight - compoundPaddingLeft;
3887
3888            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
3889            // Make sure to update invalidateDrawable() when changing this code.
3890            if (dr.mDrawableLeft != null) {
3891                canvas.save();
3892                canvas.translate(scrollX + mPaddingLeft,
3893                                 scrollY + compoundPaddingTop +
3894                                 (vspace - dr.mDrawableHeightLeft) / 2);
3895                dr.mDrawableLeft.draw(canvas);
3896                canvas.restore();
3897            }
3898
3899            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
3900            // Make sure to update invalidateDrawable() when changing this code.
3901            if (dr.mDrawableRight != null) {
3902                canvas.save();
3903                canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight,
3904                         scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2);
3905                dr.mDrawableRight.draw(canvas);
3906                canvas.restore();
3907            }
3908
3909            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
3910            // Make sure to update invalidateDrawable() when changing this code.
3911            if (dr.mDrawableTop != null) {
3912                canvas.save();
3913                canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2,
3914                        scrollY + mPaddingTop);
3915                dr.mDrawableTop.draw(canvas);
3916                canvas.restore();
3917            }
3918
3919            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
3920            // Make sure to update invalidateDrawable() when changing this code.
3921            if (dr.mDrawableBottom != null) {
3922                canvas.save();
3923                canvas.translate(scrollX + compoundPaddingLeft +
3924                        (hspace - dr.mDrawableWidthBottom) / 2,
3925                         scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom);
3926                dr.mDrawableBottom.draw(canvas);
3927                canvas.restore();
3928            }
3929        }
3930
3931        if (mPreDrawState == PREDRAW_DONE) {
3932            final ViewTreeObserver observer = getViewTreeObserver();
3933            if (observer != null) {
3934                observer.removeOnPreDrawListener(this);
3935                mPreDrawState = PREDRAW_NOT_REGISTERED;
3936            }
3937        }
3938
3939        int color = mCurTextColor;
3940
3941        if (mLayout == null) {
3942            assumeLayout();
3943        }
3944
3945        Layout layout = mLayout;
3946        int cursorcolor = color;
3947
3948        if (mHint != null && mText.length() == 0) {
3949            if (mHintTextColor != null) {
3950                color = mCurHintTextColor;
3951            }
3952
3953            layout = mHintLayout;
3954        }
3955
3956        mTextPaint.setColor(color);
3957        mTextPaint.drawableState = getDrawableState();
3958
3959        canvas.save();
3960        /*  Would be faster if we didn't have to do this. Can we chop the
3961            (displayable) text so that we don't need to do this ever?
3962        */
3963
3964        int extendedPaddingTop = getExtendedPaddingTop();
3965        int extendedPaddingBottom = getExtendedPaddingBottom();
3966
3967        float clipLeft = compoundPaddingLeft + scrollX;
3968        float clipTop = extendedPaddingTop + scrollY;
3969        float clipRight = right - left - compoundPaddingRight + scrollX;
3970        float clipBottom = bottom - top - extendedPaddingBottom + scrollY;
3971
3972        if (mShadowRadius != 0) {
3973            clipLeft += Math.min(0, mShadowDx - mShadowRadius);
3974            clipRight += Math.max(0, mShadowDx + mShadowRadius);
3975
3976            clipTop += Math.min(0, mShadowDy - mShadowRadius);
3977            clipBottom += Math.max(0, mShadowDy + mShadowRadius);
3978        }
3979
3980        canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom);
3981
3982        int voffsetText = 0;
3983        int voffsetCursor = 0;
3984
3985        // translate in by our padding
3986        {
3987            /* shortcircuit calling getVerticaOffset() */
3988            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
3989                voffsetText = getVerticalOffset(false);
3990                voffsetCursor = getVerticalOffset(true);
3991            }
3992            canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText);
3993        }
3994
3995        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
3996            if (!mSingleLine && getLineCount() == 1 && canMarquee() &&
3997                    (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) {
3998                canvas.translate(mLayout.getLineRight(0) - (mRight - mLeft -
3999                        getCompoundPaddingLeft() - getCompoundPaddingRight()), 0.0f);
4000            }
4001
4002            if (mMarquee != null && mMarquee.isRunning()) {
4003                canvas.translate(-mMarquee.mScroll, 0.0f);
4004            }
4005        }
4006
4007        Path highlight = null;
4008        int selStart = -1, selEnd = -1;
4009
4010        //  If there is no movement method, then there can be no selection.
4011        //  Check that first and attempt to skip everything having to do with
4012        //  the cursor.
4013        //  XXX This is not strictly true -- a program could set the
4014        //  selection manually if it really wanted to.
4015        if (mMovement != null && (isFocused() || isPressed())) {
4016            selStart = getSelectionStart();
4017            selEnd = getSelectionEnd();
4018
4019            if (mCursorVisible && selStart >= 0 && isEnabled()) {
4020                if (mHighlightPath == null)
4021                    mHighlightPath = new Path();
4022
4023                if (selStart == selEnd) {
4024                    if ((SystemClock.uptimeMillis() - mShowCursor) % (2 * BLINK) < BLINK) {
4025                        if (mHighlightPathBogus) {
4026                            mHighlightPath.reset();
4027                            mLayout.getCursorPath(selStart, mHighlightPath, mText);
4028                            mHighlightPathBogus = false;
4029                        }
4030
4031                        // XXX should pass to skin instead of drawing directly
4032                        mHighlightPaint.setColor(cursorcolor);
4033                        mHighlightPaint.setStyle(Paint.Style.STROKE);
4034
4035                        highlight = mHighlightPath;
4036                    }
4037                } else {
4038                    if (mHighlightPathBogus) {
4039                        mHighlightPath.reset();
4040                        mLayout.getSelectionPath(selStart, selEnd, mHighlightPath);
4041                        mHighlightPathBogus = false;
4042                    }
4043
4044                    // XXX should pass to skin instead of drawing directly
4045                    mHighlightPaint.setColor(mHighlightColor);
4046                    mHighlightPaint.setStyle(Paint.Style.FILL);
4047
4048                    highlight = mHighlightPath;
4049                }
4050            }
4051        }
4052
4053        /*  Comment out until we decide what to do about animations
4054        boolean isLinearTextOn = false;
4055        if (currentTransformation != null) {
4056            isLinearTextOn = mTextPaint.isLinearTextOn();
4057            Matrix m = currentTransformation.getMatrix();
4058            if (!m.isIdentity()) {
4059                // mTextPaint.setLinearTextOn(true);
4060            }
4061        }
4062        */
4063
4064        final InputMethodState ims = mInputMethodState;
4065        if (ims != null && ims.mBatchEditNesting == 0) {
4066            InputMethodManager imm = InputMethodManager.peekInstance();
4067            if (imm != null) {
4068                if (imm.isActive(this)) {
4069                    boolean reported = false;
4070                    if (ims.mContentChanged || ims.mSelectionModeChanged) {
4071                        // We are in extract mode and the content has changed
4072                        // in some way... just report complete new text to the
4073                        // input method.
4074                        reported = reportExtractedText();
4075                    }
4076                    if (!reported && highlight != null) {
4077                        int candStart = -1;
4078                        int candEnd = -1;
4079                        if (mText instanceof Spannable) {
4080                            Spannable sp = (Spannable)mText;
4081                            candStart = EditableInputConnection.getComposingSpanStart(sp);
4082                            candEnd = EditableInputConnection.getComposingSpanEnd(sp);
4083                        }
4084                        imm.updateSelection(this, selStart, selEnd, candStart, candEnd);
4085                    }
4086                }
4087
4088                if (imm.isWatchingCursor(this) && highlight != null) {
4089                    highlight.computeBounds(ims.mTmpRectF, true);
4090                    ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0;
4091
4092                    canvas.getMatrix().mapPoints(ims.mTmpOffset);
4093                    ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]);
4094
4095                    ims.mTmpRectF.offset(0, voffsetCursor - voffsetText);
4096
4097                    ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5),
4098                            (int)(ims.mTmpRectF.top + 0.5),
4099                            (int)(ims.mTmpRectF.right + 0.5),
4100                            (int)(ims.mTmpRectF.bottom + 0.5));
4101
4102                    imm.updateCursor(this,
4103                            ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top,
4104                            ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom);
4105                }
4106            }
4107        }
4108
4109        layout.draw(canvas, highlight, mHighlightPaint, voffsetCursor - voffsetText);
4110
4111        if (mMarquee != null && mMarquee.shouldDrawGhost()) {
4112            canvas.translate((int) mMarquee.getGhostOffset(), 0.0f);
4113            layout.draw(canvas, highlight, mHighlightPaint, voffsetCursor - voffsetText);
4114        }
4115
4116        /*  Comment out until we decide what to do about animations
4117        if (currentTransformation != null) {
4118            mTextPaint.setLinearTextOn(isLinearTextOn);
4119        }
4120        */
4121
4122        canvas.restore();
4123
4124        if (mInsertionPointCursorController != null &&
4125                mInsertionPointCursorController.isShowing()) {
4126            mInsertionPointCursorController.updatePosition();
4127        }
4128        if (mSelectionModifierCursorController != null &&
4129                mSelectionModifierCursorController.isShowing()) {
4130            mSelectionModifierCursorController.updatePosition();
4131        }
4132    }
4133
4134    @Override
4135    public void getFocusedRect(Rect r) {
4136        if (mLayout == null) {
4137            super.getFocusedRect(r);
4138            return;
4139        }
4140
4141        int sel = getSelectionEnd();
4142        if (sel < 0) {
4143            super.getFocusedRect(r);
4144            return;
4145        }
4146
4147        int line = mLayout.getLineForOffset(sel);
4148        r.top = mLayout.getLineTop(line);
4149        r.bottom = mLayout.getLineBottom(line);
4150
4151        r.left = (int) mLayout.getPrimaryHorizontal(sel);
4152        r.right = r.left + 1;
4153
4154        // Adjust for padding and gravity.
4155        int paddingLeft = getCompoundPaddingLeft();
4156        int paddingTop = getExtendedPaddingTop();
4157        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4158            paddingTop += getVerticalOffset(false);
4159        }
4160        r.offset(paddingLeft, paddingTop);
4161    }
4162
4163    /**
4164     * Return the number of lines of text, or 0 if the internal Layout has not
4165     * been built.
4166     */
4167    public int getLineCount() {
4168        return mLayout != null ? mLayout.getLineCount() : 0;
4169    }
4170
4171    /**
4172     * Return the baseline for the specified line (0...getLineCount() - 1)
4173     * If bounds is not null, return the top, left, right, bottom extents
4174     * of the specified line in it. If the internal Layout has not been built,
4175     * return 0 and set bounds to (0, 0, 0, 0)
4176     * @param line which line to examine (0..getLineCount() - 1)
4177     * @param bounds Optional. If not null, it returns the extent of the line
4178     * @return the Y-coordinate of the baseline
4179     */
4180    public int getLineBounds(int line, Rect bounds) {
4181        if (mLayout == null) {
4182            if (bounds != null) {
4183                bounds.set(0, 0, 0, 0);
4184            }
4185            return 0;
4186        }
4187        else {
4188            int baseline = mLayout.getLineBounds(line, bounds);
4189
4190            int voffset = getExtendedPaddingTop();
4191            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4192                voffset += getVerticalOffset(true);
4193            }
4194            if (bounds != null) {
4195                bounds.offset(getCompoundPaddingLeft(), voffset);
4196            }
4197            return baseline + voffset;
4198        }
4199    }
4200
4201    @Override
4202    public int getBaseline() {
4203        if (mLayout == null) {
4204            return super.getBaseline();
4205        }
4206
4207        int voffset = 0;
4208        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4209            voffset = getVerticalOffset(true);
4210        }
4211
4212        return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0);
4213    }
4214
4215    @Override
4216    public boolean onKeyDown(int keyCode, KeyEvent event) {
4217        int which = doKeyDown(keyCode, event, null);
4218        if (which == 0) {
4219            // Go through default dispatching.
4220            return super.onKeyDown(keyCode, event);
4221        }
4222
4223        return true;
4224    }
4225
4226    @Override
4227    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4228        KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN);
4229
4230        int which = doKeyDown(keyCode, down, event);
4231        if (which == 0) {
4232            // Go through default dispatching.
4233            return super.onKeyMultiple(keyCode, repeatCount, event);
4234        }
4235        if (which == -1) {
4236            // Consumed the whole thing.
4237            return true;
4238        }
4239
4240        repeatCount--;
4241
4242        // We are going to dispatch the remaining events to either the input
4243        // or movement method.  To do this, we will just send a repeated stream
4244        // of down and up events until we have done the complete repeatCount.
4245        // It would be nice if those interfaces had an onKeyMultiple() method,
4246        // but adding that is a more complicated change.
4247        KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP);
4248        if (which == 1) {
4249            mInput.onKeyUp(this, (Editable)mText, keyCode, up);
4250            while (--repeatCount > 0) {
4251                mInput.onKeyDown(this, (Editable)mText, keyCode, down);
4252                mInput.onKeyUp(this, (Editable)mText, keyCode, up);
4253            }
4254            if (mError != null && !mErrorWasChanged) {
4255                setError(null, null);
4256            }
4257
4258        } else if (which == 2) {
4259            mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
4260            while (--repeatCount > 0) {
4261                mMovement.onKeyDown(this, (Spannable)mText, keyCode, down);
4262                mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
4263            }
4264        }
4265
4266        return true;
4267    }
4268
4269    /**
4270     * Returns true if pressing ENTER in this field advances focus instead
4271     * of inserting the character.  This is true mostly in single-line fields,
4272     * but also in mail addresses and subjects which will display on multiple
4273     * lines but where it doesn't make sense to insert newlines.
4274     */
4275    private boolean shouldAdvanceFocusOnEnter() {
4276        if (mInput == null) {
4277            return false;
4278        }
4279
4280        if (mSingleLine) {
4281            return true;
4282        }
4283
4284        if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
4285            int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION;
4286
4287            if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
4288                variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) {
4289                return true;
4290            }
4291        }
4292
4293        return false;
4294    }
4295
4296    private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) {
4297        if (!isEnabled()) {
4298            return 0;
4299        }
4300
4301        switch (keyCode) {
4302            case KeyEvent.KEYCODE_ENTER:
4303                // If ALT modifier is held, then we always insert a
4304                // newline character.
4305                if ((event.getMetaState()&KeyEvent.META_ALT_ON) == 0) {
4306
4307                    // When mInputContentType is set, we know that we are
4308                    // running in a "modern" cupcake environment, so don't need
4309                    // to worry about the application trying to capture
4310                    // enter key events.
4311                    if (mInputContentType != null) {
4312
4313                        // If there is an action listener, given them a
4314                        // chance to consume the event.
4315                        if (mInputContentType.onEditorActionListener != null &&
4316                                mInputContentType.onEditorActionListener.onEditorAction(
4317                                this, EditorInfo.IME_NULL, event)) {
4318                            mInputContentType.enterDown = true;
4319                            // We are consuming the enter key for them.
4320                            return -1;
4321                        }
4322                    }
4323
4324                    // If our editor should move focus when enter is pressed, or
4325                    // this is a generated event from an IME action button, then
4326                    // don't let it be inserted into the text.
4327                    if ((event.getFlags()&KeyEvent.FLAG_EDITOR_ACTION) != 0
4328                            || shouldAdvanceFocusOnEnter()) {
4329                        return -1;
4330                    }
4331                }
4332                break;
4333
4334            case KeyEvent.KEYCODE_DPAD_CENTER:
4335                if (shouldAdvanceFocusOnEnter()) {
4336                    return 0;
4337                }
4338                break;
4339
4340                // Has to be done on key down (and not on key up) to correctly be intercepted.
4341            case KeyEvent.KEYCODE_BACK:
4342                if (mIsInTextSelectionMode) {
4343                    stopTextSelectionMode();
4344                    return -1;
4345                }
4346                break;
4347        }
4348
4349        if (mInput != null) {
4350            /*
4351             * Keep track of what the error was before doing the input
4352             * so that if an input filter changed the error, we leave
4353             * that error showing.  Otherwise, we take down whatever
4354             * error was showing when the user types something.
4355             */
4356            mErrorWasChanged = false;
4357
4358            boolean doDown = true;
4359            if (otherEvent != null) {
4360                try {
4361                    beginBatchEdit();
4362                    boolean handled = mInput.onKeyOther(this, (Editable) mText,
4363                            otherEvent);
4364                    if (mError != null && !mErrorWasChanged) {
4365                        setError(null, null);
4366                    }
4367                    doDown = false;
4368                    if (handled) {
4369                        return -1;
4370                    }
4371                } catch (AbstractMethodError e) {
4372                    // onKeyOther was added after 1.0, so if it isn't
4373                    // implemented we need to try to dispatch as a regular down.
4374                } finally {
4375                    endBatchEdit();
4376                }
4377            }
4378
4379            if (doDown) {
4380                beginBatchEdit();
4381                if (mInput.onKeyDown(this, (Editable) mText, keyCode, event)) {
4382                    endBatchEdit();
4383                    if (mError != null && !mErrorWasChanged) {
4384                        setError(null, null);
4385                    }
4386                    return 1;
4387                }
4388                endBatchEdit();
4389            }
4390        }
4391
4392        // bug 650865: sometimes we get a key event before a layout.
4393        // don't try to move around if we don't know the layout.
4394
4395        if (mMovement != null && mLayout != null) {
4396            boolean doDown = true;
4397            if (otherEvent != null) {
4398                try {
4399                    boolean handled = mMovement.onKeyOther(this, (Spannable) mText,
4400                            otherEvent);
4401                    doDown = false;
4402                    if (handled) {
4403                        return -1;
4404                    }
4405                } catch (AbstractMethodError e) {
4406                    // onKeyOther was added after 1.0, so if it isn't
4407                    // implemented we need to try to dispatch as a regular down.
4408                }
4409            }
4410            if (doDown) {
4411                if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event))
4412                    return 2;
4413            }
4414        }
4415
4416        return 0;
4417    }
4418
4419    @Override
4420    public boolean onKeyUp(int keyCode, KeyEvent event) {
4421        if (!isEnabled()) {
4422            return super.onKeyUp(keyCode, event);
4423        }
4424
4425        hideControllers();
4426
4427        switch (keyCode) {
4428            case KeyEvent.KEYCODE_DPAD_CENTER:
4429                /*
4430                 * If there is a click listener, just call through to
4431                 * super, which will invoke it.
4432                 *
4433                 * If there isn't a click listener, try to show the soft
4434                 * input method.  (It will also
4435                 * call performClick(), but that won't do anything in
4436                 * this case.)
4437                 */
4438                if (mOnClickListener == null) {
4439                    if (mMovement != null && mText instanceof Editable
4440                            && mLayout != null && onCheckIsTextEditor()) {
4441                        InputMethodManager imm = (InputMethodManager)
4442                                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
4443                        imm.showSoftInput(this, 0);
4444                    }
4445                }
4446                return super.onKeyUp(keyCode, event);
4447
4448            case KeyEvent.KEYCODE_ENTER:
4449                if (mInputContentType != null
4450                        && mInputContentType.onEditorActionListener != null
4451                        && mInputContentType.enterDown) {
4452                    mInputContentType.enterDown = false;
4453                    if (mInputContentType.onEditorActionListener.onEditorAction(
4454                            this, EditorInfo.IME_NULL, event)) {
4455                        return true;
4456                    }
4457                }
4458
4459                if ((event.getFlags()&KeyEvent.FLAG_EDITOR_ACTION) != 0
4460                        || shouldAdvanceFocusOnEnter()) {
4461                    /*
4462                     * If there is a click listener, just call through to
4463                     * super, which will invoke it.
4464                     *
4465                     * If there isn't a click listener, try to advance focus,
4466                     * but still call through to super, which will reset the
4467                     * pressed state and longpress state.  (It will also
4468                     * call performClick(), but that won't do anything in
4469                     * this case.)
4470                     */
4471                    if (mOnClickListener == null) {
4472                        View v = focusSearch(FOCUS_DOWN);
4473
4474                        if (v != null) {
4475                            if (!v.requestFocus(FOCUS_DOWN)) {
4476                                throw new IllegalStateException("focus search returned a view " +
4477                                        "that wasn't able to take focus!");
4478                            }
4479
4480                            /*
4481                             * Return true because we handled the key; super
4482                             * will return false because there was no click
4483                             * listener.
4484                             */
4485                            super.onKeyUp(keyCode, event);
4486                            return true;
4487                        } else if ((event.getFlags()
4488                                & KeyEvent.FLAG_EDITOR_ACTION) != 0) {
4489                            // No target for next focus, but make sure the IME
4490                            // if this came from it.
4491                            InputMethodManager imm = InputMethodManager.peekInstance();
4492                            if (imm != null) {
4493                                imm.hideSoftInputFromWindow(getWindowToken(), 0);
4494                            }
4495                        }
4496                    }
4497
4498                    return super.onKeyUp(keyCode, event);
4499                }
4500                break;
4501        }
4502
4503        if (mInput != null)
4504            if (mInput.onKeyUp(this, (Editable) mText, keyCode, event))
4505                return true;
4506
4507        if (mMovement != null && mLayout != null)
4508            if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event))
4509                return true;
4510
4511        return super.onKeyUp(keyCode, event);
4512    }
4513
4514    @Override public boolean onCheckIsTextEditor() {
4515        return mInputType != EditorInfo.TYPE_NULL;
4516    }
4517
4518    @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4519        if (onCheckIsTextEditor()) {
4520            if (mInputMethodState == null) {
4521                mInputMethodState = new InputMethodState();
4522            }
4523            outAttrs.inputType = mInputType;
4524            if (mInputContentType != null) {
4525                outAttrs.imeOptions = mInputContentType.imeOptions;
4526                outAttrs.privateImeOptions = mInputContentType.privateImeOptions;
4527                outAttrs.actionLabel = mInputContentType.imeActionLabel;
4528                outAttrs.actionId = mInputContentType.imeActionId;
4529                outAttrs.extras = mInputContentType.extras;
4530            } else {
4531                outAttrs.imeOptions = EditorInfo.IME_NULL;
4532            }
4533            if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION)
4534                    == EditorInfo.IME_ACTION_UNSPECIFIED) {
4535                if (focusSearch(FOCUS_DOWN) != null) {
4536                    // An action has not been set, but the enter key will move to
4537                    // the next focus, so set the action to that.
4538                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT;
4539                } else {
4540                    // An action has not been set, and there is no focus to move
4541                    // to, so let's just supply a "done" action.
4542                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
4543                }
4544                if (!shouldAdvanceFocusOnEnter()) {
4545                    outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
4546                }
4547            }
4548            if ((outAttrs.inputType & (InputType.TYPE_MASK_CLASS
4549                    | InputType.TYPE_TEXT_FLAG_MULTI_LINE))
4550                    == (InputType.TYPE_CLASS_TEXT
4551                            | InputType.TYPE_TEXT_FLAG_MULTI_LINE)) {
4552                // Multi-line text editors should always show an enter key.
4553                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
4554            }
4555            outAttrs.hintText = mHint;
4556            if (mText instanceof Editable) {
4557                InputConnection ic = new EditableInputConnection(this);
4558                outAttrs.initialSelStart = getSelectionStart();
4559                outAttrs.initialSelEnd = getSelectionEnd();
4560                outAttrs.initialCapsMode = ic.getCursorCapsMode(mInputType);
4561                return ic;
4562            }
4563        }
4564        return null;
4565    }
4566
4567    /**
4568     * If this TextView contains editable content, extract a portion of it
4569     * based on the information in <var>request</var> in to <var>outText</var>.
4570     * @return Returns true if the text was successfully extracted, else false.
4571     */
4572    public boolean extractText(ExtractedTextRequest request,
4573            ExtractedText outText) {
4574        return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN,
4575                EXTRACT_UNKNOWN, outText);
4576    }
4577
4578    static final int EXTRACT_NOTHING = -2;
4579    static final int EXTRACT_UNKNOWN = -1;
4580
4581    boolean extractTextInternal(ExtractedTextRequest request,
4582            int partialStartOffset, int partialEndOffset, int delta,
4583            ExtractedText outText) {
4584        final CharSequence content = mText;
4585        if (content != null) {
4586            if (partialStartOffset != EXTRACT_NOTHING) {
4587                final int N = content.length();
4588                if (partialStartOffset < 0) {
4589                    outText.partialStartOffset = outText.partialEndOffset = -1;
4590                    partialStartOffset = 0;
4591                    partialEndOffset = N;
4592                } else {
4593                    // Adjust offsets to ensure we contain full spans.
4594                    if (content instanceof Spanned) {
4595                        Spanned spanned = (Spanned)content;
4596                        Object[] spans = spanned.getSpans(partialStartOffset,
4597                                partialEndOffset, ParcelableSpan.class);
4598                        int i = spans.length;
4599                        while (i > 0) {
4600                            i--;
4601                            int j = spanned.getSpanStart(spans[i]);
4602                            if (j < partialStartOffset) partialStartOffset = j;
4603                            j = spanned.getSpanEnd(spans[i]);
4604                            if (j > partialEndOffset) partialEndOffset = j;
4605                        }
4606                    }
4607                    outText.partialStartOffset = partialStartOffset;
4608                    outText.partialEndOffset = partialEndOffset;
4609                    // Now use the delta to determine the actual amount of text
4610                    // we need.
4611                    partialEndOffset += delta;
4612                    if (partialStartOffset > N) {
4613                        partialStartOffset = N;
4614                    } else if (partialStartOffset < 0) {
4615                        partialStartOffset = 0;
4616                    }
4617                    if (partialEndOffset > N) {
4618                        partialEndOffset = N;
4619                    } else if (partialEndOffset < 0) {
4620                        partialEndOffset = 0;
4621                    }
4622                }
4623                if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) {
4624                    outText.text = content.subSequence(partialStartOffset,
4625                            partialEndOffset);
4626                } else {
4627                    outText.text = TextUtils.substring(content, partialStartOffset,
4628                            partialEndOffset);
4629                }
4630            } else {
4631                outText.partialStartOffset = 0;
4632                outText.partialEndOffset = 0;
4633                outText.text = "";
4634            }
4635            outText.flags = 0;
4636            if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) {
4637                outText.flags |= ExtractedText.FLAG_SELECTING;
4638            }
4639            if (mSingleLine) {
4640                outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
4641            }
4642            outText.startOffset = 0;
4643            outText.selectionStart = getSelectionStart();
4644            outText.selectionEnd = getSelectionEnd();
4645            return true;
4646        }
4647        return false;
4648    }
4649
4650    boolean reportExtractedText() {
4651        final InputMethodState ims = mInputMethodState;
4652        if (ims != null) {
4653            final boolean contentChanged = ims.mContentChanged;
4654            if (contentChanged || ims.mSelectionModeChanged) {
4655                ims.mContentChanged = false;
4656                ims.mSelectionModeChanged = false;
4657                final ExtractedTextRequest req = mInputMethodState.mExtracting;
4658                if (req != null) {
4659                    InputMethodManager imm = InputMethodManager.peekInstance();
4660                    if (imm != null) {
4661                        if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start="
4662                                + ims.mChangedStart + " end=" + ims.mChangedEnd
4663                                + " delta=" + ims.mChangedDelta);
4664                        if (ims.mChangedStart < 0 && !contentChanged) {
4665                            ims.mChangedStart = EXTRACT_NOTHING;
4666                        }
4667                        if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd,
4668                                ims.mChangedDelta, ims.mTmpExtracted)) {
4669                            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start="
4670                                    + ims.mTmpExtracted.partialStartOffset
4671                                    + " end=" + ims.mTmpExtracted.partialEndOffset
4672                                    + ": " + ims.mTmpExtracted.text);
4673                            imm.updateExtractedText(this, req.token,
4674                                    mInputMethodState.mTmpExtracted);
4675                            return true;
4676                        }
4677                    }
4678                }
4679            }
4680        }
4681        return false;
4682    }
4683
4684    /**
4685     * This is used to remove all style-impacting spans from text before new
4686     * extracted text is being replaced into it, so that we don't have any
4687     * lingering spans applied during the replace.
4688     */
4689    static void removeParcelableSpans(Spannable spannable, int start, int end) {
4690        Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class);
4691        int i = spans.length;
4692        while (i > 0) {
4693            i--;
4694            spannable.removeSpan(spans[i]);
4695        }
4696    }
4697
4698    /**
4699     * Apply to this text view the given extracted text, as previously
4700     * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}.
4701     */
4702    public void setExtractedText(ExtractedText text) {
4703        Editable content = getEditableText();
4704        if (text.text != null) {
4705            if (content == null) {
4706                setText(text.text, TextView.BufferType.EDITABLE);
4707            } else if (text.partialStartOffset < 0) {
4708                removeParcelableSpans(content, 0, content.length());
4709                content.replace(0, content.length(), text.text);
4710            } else {
4711                final int N = content.length();
4712                int start = text.partialStartOffset;
4713                if (start > N) start = N;
4714                int end = text.partialEndOffset;
4715                if (end > N) end = N;
4716                removeParcelableSpans(content, start, end);
4717                content.replace(start, end, text.text);
4718            }
4719        }
4720
4721        // Now set the selection position...  make sure it is in range, to
4722        // avoid crashes.  If this is a partial update, it is possible that
4723        // the underlying text may have changed, causing us problems here.
4724        // Also we just don't want to trust clients to do the right thing.
4725        Spannable sp = (Spannable)getText();
4726        final int N = sp.length();
4727        int start = text.selectionStart;
4728        if (start < 0) start = 0;
4729        else if (start > N) start = N;
4730        int end = text.selectionEnd;
4731        if (end < 0) end = 0;
4732        else if (end > N) end = N;
4733        Selection.setSelection(sp, start, end);
4734
4735        // Finally, update the selection mode.
4736        if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) {
4737            MetaKeyKeyListener.startSelecting(this, sp);
4738        } else {
4739            MetaKeyKeyListener.stopSelecting(this, sp);
4740        }
4741    }
4742
4743    /**
4744     * @hide
4745     */
4746    public void setExtracting(ExtractedTextRequest req) {
4747        if (mInputMethodState != null) {
4748            mInputMethodState.mExtracting = req;
4749        }
4750        hideControllers();
4751    }
4752
4753    /**
4754     * Called by the framework in response to a text completion from
4755     * the current input method, provided by it calling
4756     * {@link InputConnection#commitCompletion
4757     * InputConnection.commitCompletion()}.  The default implementation does
4758     * nothing; text views that are supporting auto-completion should override
4759     * this to do their desired behavior.
4760     *
4761     * @param text The auto complete text the user has selected.
4762     */
4763    public void onCommitCompletion(CompletionInfo text) {
4764    }
4765
4766    public void beginBatchEdit() {
4767        final InputMethodState ims = mInputMethodState;
4768        if (ims != null) {
4769            int nesting = ++ims.mBatchEditNesting;
4770            if (nesting == 1) {
4771                ims.mCursorChanged = false;
4772                ims.mChangedDelta = 0;
4773                if (ims.mContentChanged) {
4774                    // We already have a pending change from somewhere else,
4775                    // so turn this into a full update.
4776                    ims.mChangedStart = 0;
4777                    ims.mChangedEnd = mText.length();
4778                } else {
4779                    ims.mChangedStart = EXTRACT_UNKNOWN;
4780                    ims.mChangedEnd = EXTRACT_UNKNOWN;
4781                    ims.mContentChanged = false;
4782                }
4783                onBeginBatchEdit();
4784            }
4785        }
4786    }
4787
4788    public void endBatchEdit() {
4789        final InputMethodState ims = mInputMethodState;
4790        if (ims != null) {
4791            int nesting = --ims.mBatchEditNesting;
4792            if (nesting == 0) {
4793                finishBatchEdit(ims);
4794            }
4795        }
4796    }
4797
4798    void ensureEndedBatchEdit() {
4799        final InputMethodState ims = mInputMethodState;
4800        if (ims != null && ims.mBatchEditNesting != 0) {
4801            ims.mBatchEditNesting = 0;
4802            finishBatchEdit(ims);
4803        }
4804    }
4805
4806    void finishBatchEdit(final InputMethodState ims) {
4807        onEndBatchEdit();
4808
4809        if (ims.mContentChanged || ims.mSelectionModeChanged) {
4810            updateAfterEdit();
4811            reportExtractedText();
4812        } else if (ims.mCursorChanged) {
4813            // Cheezy way to get us to report the current cursor location.
4814            invalidateCursor();
4815        }
4816    }
4817
4818    void updateAfterEdit() {
4819        invalidate();
4820        int curs = getSelectionStart();
4821
4822        if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) ==
4823                             Gravity.BOTTOM) {
4824            registerForPreDraw();
4825        }
4826
4827        if (curs >= 0) {
4828            mHighlightPathBogus = true;
4829
4830            if (isFocused()) {
4831                mShowCursor = SystemClock.uptimeMillis();
4832                makeBlink();
4833            }
4834        }
4835
4836        checkForResize();
4837    }
4838
4839    /**
4840     * Called by the framework in response to a request to begin a batch
4841     * of edit operations through a call to link {@link #beginBatchEdit()}.
4842     */
4843    public void onBeginBatchEdit() {
4844    }
4845
4846    /**
4847     * Called by the framework in response to a request to end a batch
4848     * of edit operations through a call to link {@link #endBatchEdit}.
4849     */
4850    public void onEndBatchEdit() {
4851    }
4852
4853    /**
4854     * Called by the framework in response to a private command from the
4855     * current method, provided by it calling
4856     * {@link InputConnection#performPrivateCommand
4857     * InputConnection.performPrivateCommand()}.
4858     *
4859     * @param action The action name of the command.
4860     * @param data Any additional data for the command.  This may be null.
4861     * @return Return true if you handled the command, else false.
4862     */
4863    public boolean onPrivateIMECommand(String action, Bundle data) {
4864        return false;
4865    }
4866
4867    private void nullLayouts() {
4868        if (mLayout instanceof BoringLayout && mSavedLayout == null) {
4869            mSavedLayout = (BoringLayout) mLayout;
4870        }
4871        if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) {
4872            mSavedHintLayout = (BoringLayout) mHintLayout;
4873        }
4874
4875        mLayout = mHintLayout = null;
4876    }
4877
4878    /**
4879     * Make a new Layout based on the already-measured size of the view,
4880     * on the assumption that it was measured correctly at some point.
4881     */
4882    private void assumeLayout() {
4883        int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
4884
4885        if (width < 1) {
4886            width = 0;
4887        }
4888
4889        int physicalWidth = width;
4890
4891        if (mHorizontallyScrolling) {
4892            width = VERY_WIDE;
4893        }
4894
4895        makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING,
4896                      physicalWidth, false);
4897    }
4898
4899    /**
4900     * The width passed in is now the desired layout width,
4901     * not the full view width with padding.
4902     * {@hide}
4903     */
4904    protected void makeNewLayout(int w, int hintWidth,
4905                                 BoringLayout.Metrics boring,
4906                                 BoringLayout.Metrics hintBoring,
4907                                 int ellipsisWidth, boolean bringIntoView) {
4908        stopMarquee();
4909
4910        mHighlightPathBogus = true;
4911
4912        if (w < 0) {
4913            w = 0;
4914        }
4915        if (hintWidth < 0) {
4916            hintWidth = 0;
4917        }
4918
4919        Layout.Alignment alignment;
4920        switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
4921            case Gravity.CENTER_HORIZONTAL:
4922                alignment = Layout.Alignment.ALIGN_CENTER;
4923                break;
4924
4925            case Gravity.RIGHT:
4926                alignment = Layout.Alignment.ALIGN_OPPOSITE;
4927                break;
4928
4929            default:
4930                alignment = Layout.Alignment.ALIGN_NORMAL;
4931        }
4932
4933        boolean shouldEllipsize = mEllipsize != null && mInput == null;
4934
4935        if (mText instanceof Spannable) {
4936            mLayout = new DynamicLayout(mText, mTransformed, mTextPaint, w,
4937                    alignment, mSpacingMult,
4938                    mSpacingAdd, mIncludePad, mInput == null ? mEllipsize : null,
4939                    ellipsisWidth);
4940        } else {
4941            if (boring == UNKNOWN_BORING) {
4942                boring = BoringLayout.isBoring(mTransformed, mTextPaint,
4943                                               mBoring);
4944                if (boring != null) {
4945                    mBoring = boring;
4946                }
4947            }
4948
4949            if (boring != null) {
4950                if (boring.width <= w &&
4951                    (mEllipsize == null || boring.width <= ellipsisWidth)) {
4952                    if (mSavedLayout != null) {
4953                        mLayout = mSavedLayout.
4954                                replaceOrMake(mTransformed, mTextPaint,
4955                                w, alignment, mSpacingMult, mSpacingAdd,
4956                                boring, mIncludePad);
4957                    } else {
4958                        mLayout = BoringLayout.make(mTransformed, mTextPaint,
4959                                w, alignment, mSpacingMult, mSpacingAdd,
4960                                boring, mIncludePad);
4961                    }
4962
4963                    mSavedLayout = (BoringLayout) mLayout;
4964                } else if (shouldEllipsize && boring.width <= w) {
4965                    if (mSavedLayout != null) {
4966                        mLayout = mSavedLayout.
4967                                replaceOrMake(mTransformed, mTextPaint,
4968                                w, alignment, mSpacingMult, mSpacingAdd,
4969                                boring, mIncludePad, mEllipsize,
4970                                ellipsisWidth);
4971                    } else {
4972                        mLayout = BoringLayout.make(mTransformed, mTextPaint,
4973                                w, alignment, mSpacingMult, mSpacingAdd,
4974                                boring, mIncludePad, mEllipsize,
4975                                ellipsisWidth);
4976                    }
4977                } else if (shouldEllipsize) {
4978                    mLayout = new StaticLayout(mTransformed,
4979                                0, mTransformed.length(),
4980                                mTextPaint, w, alignment, mSpacingMult,
4981                                mSpacingAdd, mIncludePad, mEllipsize,
4982                                ellipsisWidth);
4983                } else {
4984                    mLayout = new StaticLayout(mTransformed, mTextPaint,
4985                            w, alignment, mSpacingMult, mSpacingAdd,
4986                            mIncludePad);
4987                }
4988            } else if (shouldEllipsize) {
4989                mLayout = new StaticLayout(mTransformed,
4990                            0, mTransformed.length(),
4991                            mTextPaint, w, alignment, mSpacingMult,
4992                            mSpacingAdd, mIncludePad, mEllipsize,
4993                            ellipsisWidth);
4994            } else {
4995                mLayout = new StaticLayout(mTransformed, mTextPaint,
4996                        w, alignment, mSpacingMult, mSpacingAdd,
4997                        mIncludePad);
4998            }
4999        }
5000
5001        shouldEllipsize = mEllipsize != null;
5002        mHintLayout = null;
5003
5004        if (mHint != null) {
5005            if (shouldEllipsize) hintWidth = w;
5006
5007            if (hintBoring == UNKNOWN_BORING) {
5008                hintBoring = BoringLayout.isBoring(mHint, mTextPaint,
5009                                                   mHintBoring);
5010                if (hintBoring != null) {
5011                    mHintBoring = hintBoring;
5012                }
5013            }
5014
5015            if (hintBoring != null) {
5016                if (hintBoring.width <= hintWidth &&
5017                    (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) {
5018                    if (mSavedHintLayout != null) {
5019                        mHintLayout = mSavedHintLayout.
5020                                replaceOrMake(mHint, mTextPaint,
5021                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5022                                hintBoring, mIncludePad);
5023                    } else {
5024                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5025                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5026                                hintBoring, mIncludePad);
5027                    }
5028
5029                    mSavedHintLayout = (BoringLayout) mHintLayout;
5030                } else if (shouldEllipsize && hintBoring.width <= hintWidth) {
5031                    if (mSavedHintLayout != null) {
5032                        mHintLayout = mSavedHintLayout.
5033                                replaceOrMake(mHint, mTextPaint,
5034                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5035                                hintBoring, mIncludePad, mEllipsize,
5036                                ellipsisWidth);
5037                    } else {
5038                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5039                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5040                                hintBoring, mIncludePad, mEllipsize,
5041                                ellipsisWidth);
5042                    }
5043                } else if (shouldEllipsize) {
5044                    mHintLayout = new StaticLayout(mHint,
5045                                0, mHint.length(),
5046                                mTextPaint, hintWidth, alignment, mSpacingMult,
5047                                mSpacingAdd, mIncludePad, mEllipsize,
5048                                ellipsisWidth);
5049                } else {
5050                    mHintLayout = new StaticLayout(mHint, mTextPaint,
5051                            hintWidth, alignment, mSpacingMult, mSpacingAdd,
5052                            mIncludePad);
5053                }
5054            } else if (shouldEllipsize) {
5055                mHintLayout = new StaticLayout(mHint,
5056                            0, mHint.length(),
5057                            mTextPaint, hintWidth, alignment, mSpacingMult,
5058                            mSpacingAdd, mIncludePad, mEllipsize,
5059                            ellipsisWidth);
5060            } else {
5061                mHintLayout = new StaticLayout(mHint, mTextPaint,
5062                        hintWidth, alignment, mSpacingMult, mSpacingAdd,
5063                        mIncludePad);
5064            }
5065        }
5066
5067        if (bringIntoView) {
5068            registerForPreDraw();
5069        }
5070
5071        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
5072            if (!compressText(ellipsisWidth)) {
5073                final int height = mLayoutParams.height;
5074                // If the size of the view does not depend on the size of the text, try to
5075                // start the marquee immediately
5076                if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) {
5077                    startMarquee();
5078                } else {
5079                    // Defer the start of the marquee until we know our width (see setFrame())
5080                    mRestartMarquee = true;
5081                }
5082            }
5083        }
5084
5085        // CursorControllers need a non-null mLayout
5086        prepareCursorControllers();
5087    }
5088
5089    private boolean compressText(float width) {
5090        // Only compress the text if it hasn't been compressed by the previous pass
5091        if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX &&
5092                mTextPaint.getTextScaleX() == 1.0f) {
5093            final float textWidth = mLayout.getLineWidth(0);
5094            final float overflow = (textWidth + 1.0f - width) / width;
5095            if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) {
5096                mTextPaint.setTextScaleX(1.0f - overflow - 0.005f);
5097                post(new Runnable() {
5098                    public void run() {
5099                        requestLayout();
5100                    }
5101                });
5102                return true;
5103            }
5104        }
5105
5106        return false;
5107    }
5108
5109    private static int desired(Layout layout) {
5110        int n = layout.getLineCount();
5111        CharSequence text = layout.getText();
5112        float max = 0;
5113
5114        // if any line was wrapped, we can't use it.
5115        // but it's ok for the last line not to have a newline
5116
5117        for (int i = 0; i < n - 1; i++) {
5118            if (text.charAt(layout.getLineEnd(i) - 1) != '\n')
5119                return -1;
5120        }
5121
5122        for (int i = 0; i < n; i++) {
5123            max = Math.max(max, layout.getLineWidth(i));
5124        }
5125
5126        return (int) FloatMath.ceil(max);
5127    }
5128
5129    /**
5130     * Set whether the TextView includes extra top and bottom padding to make
5131     * room for accents that go above the normal ascent and descent.
5132     * The default is true.
5133     *
5134     * @attr ref android.R.styleable#TextView_includeFontPadding
5135     */
5136    public void setIncludeFontPadding(boolean includepad) {
5137        mIncludePad = includepad;
5138
5139        if (mLayout != null) {
5140            nullLayouts();
5141            requestLayout();
5142            invalidate();
5143        }
5144    }
5145
5146    private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics();
5147
5148    @Override
5149    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
5150        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
5151        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
5152        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
5153        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
5154
5155        int width;
5156        int height;
5157
5158        BoringLayout.Metrics boring = UNKNOWN_BORING;
5159        BoringLayout.Metrics hintBoring = UNKNOWN_BORING;
5160
5161        int des = -1;
5162        boolean fromexisting = false;
5163
5164        if (widthMode == MeasureSpec.EXACTLY) {
5165            // Parent has told us how big to be. So be it.
5166            width = widthSize;
5167        } else {
5168            if (mLayout != null && mEllipsize == null) {
5169                des = desired(mLayout);
5170            }
5171
5172            if (des < 0) {
5173                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mBoring);
5174                if (boring != null) {
5175                    mBoring = boring;
5176                }
5177            } else {
5178                fromexisting = true;
5179            }
5180
5181            if (boring == null || boring == UNKNOWN_BORING) {
5182                if (des < 0) {
5183                    des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint));
5184                }
5185
5186                width = des;
5187            } else {
5188                width = boring.width;
5189            }
5190
5191            final Drawables dr = mDrawables;
5192            if (dr != null) {
5193                width = Math.max(width, dr.mDrawableWidthTop);
5194                width = Math.max(width, dr.mDrawableWidthBottom);
5195            }
5196
5197            if (mHint != null) {
5198                int hintDes = -1;
5199                int hintWidth;
5200
5201                if (mHintLayout != null && mEllipsize == null) {
5202                    hintDes = desired(mHintLayout);
5203                }
5204
5205                if (hintDes < 0) {
5206                    hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring);
5207                    if (hintBoring != null) {
5208                        mHintBoring = hintBoring;
5209                    }
5210                }
5211
5212                if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
5213                    if (hintDes < 0) {
5214                        hintDes = (int) FloatMath.ceil(
5215                                Layout.getDesiredWidth(mHint, mTextPaint));
5216                    }
5217
5218                    hintWidth = hintDes;
5219                } else {
5220                    hintWidth = hintBoring.width;
5221                }
5222
5223                if (hintWidth > width) {
5224                    width = hintWidth;
5225                }
5226            }
5227
5228            width += getCompoundPaddingLeft() + getCompoundPaddingRight();
5229
5230            if (mMaxWidthMode == EMS) {
5231                width = Math.min(width, mMaxWidth * getLineHeight());
5232            } else {
5233                width = Math.min(width, mMaxWidth);
5234            }
5235
5236            if (mMinWidthMode == EMS) {
5237                width = Math.max(width, mMinWidth * getLineHeight());
5238            } else {
5239                width = Math.max(width, mMinWidth);
5240            }
5241
5242            // Check against our minimum width
5243            width = Math.max(width, getSuggestedMinimumWidth());
5244
5245            if (widthMode == MeasureSpec.AT_MOST) {
5246                width = Math.min(widthSize, width);
5247            }
5248        }
5249
5250        int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight();
5251        int unpaddedWidth = want;
5252        int hintWant = want;
5253
5254        if (mHorizontallyScrolling)
5255            want = VERY_WIDE;
5256
5257        int hintWidth = mHintLayout == null ? hintWant : mHintLayout.getWidth();
5258
5259        if (mLayout == null) {
5260            makeNewLayout(want, hintWant, boring, hintBoring,
5261                          width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
5262        } else if ((mLayout.getWidth() != want) || (hintWidth != hintWant) ||
5263                   (mLayout.getEllipsizedWidth() !=
5264                        width - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
5265            if (mHint == null && mEllipsize == null &&
5266                    want > mLayout.getWidth() &&
5267                    (mLayout instanceof BoringLayout ||
5268                            (fromexisting && des >= 0 && des <= want))) {
5269                mLayout.increaseWidthTo(want);
5270            } else {
5271                makeNewLayout(want, hintWant, boring, hintBoring,
5272                              width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
5273            }
5274        } else {
5275            // Width has not changed.
5276        }
5277
5278        if (heightMode == MeasureSpec.EXACTLY) {
5279            // Parent has told us how big to be. So be it.
5280            height = heightSize;
5281            mDesiredHeightAtMeasure = -1;
5282        } else {
5283            int desired = getDesiredHeight();
5284
5285            height = desired;
5286            mDesiredHeightAtMeasure = desired;
5287
5288            if (heightMode == MeasureSpec.AT_MOST) {
5289                height = Math.min(desired, heightSize);
5290            }
5291        }
5292
5293        int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
5294        if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) {
5295            unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum));
5296        }
5297
5298        /*
5299         * We didn't let makeNewLayout() register to bring the cursor into view,
5300         * so do it here if there is any possibility that it is needed.
5301         */
5302        if (mMovement != null ||
5303            mLayout.getWidth() > unpaddedWidth ||
5304            mLayout.getHeight() > unpaddedHeight) {
5305            registerForPreDraw();
5306        } else {
5307            scrollTo(0, 0);
5308        }
5309
5310        setMeasuredDimension(width, height);
5311    }
5312
5313    private int getDesiredHeight() {
5314        return Math.max(
5315                getDesiredHeight(mLayout, true),
5316                getDesiredHeight(mHintLayout, mEllipsize != null));
5317    }
5318
5319    private int getDesiredHeight(Layout layout, boolean cap) {
5320        if (layout == null) {
5321            return 0;
5322        }
5323
5324        int linecount = layout.getLineCount();
5325        int pad = getCompoundPaddingTop() + getCompoundPaddingBottom();
5326        int desired = layout.getLineTop(linecount);
5327
5328        final Drawables dr = mDrawables;
5329        if (dr != null) {
5330            desired = Math.max(desired, dr.mDrawableHeightLeft);
5331            desired = Math.max(desired, dr.mDrawableHeightRight);
5332        }
5333
5334        desired += pad;
5335
5336        if (mMaxMode == LINES) {
5337            /*
5338             * Don't cap the hint to a certain number of lines.
5339             * (Do cap it, though, if we have a maximum pixel height.)
5340             */
5341            if (cap) {
5342                if (linecount > mMaximum) {
5343                    desired = layout.getLineTop(mMaximum) +
5344                              layout.getBottomPadding();
5345
5346                    if (dr != null) {
5347                        desired = Math.max(desired, dr.mDrawableHeightLeft);
5348                        desired = Math.max(desired, dr.mDrawableHeightRight);
5349                    }
5350
5351                    desired += pad;
5352                    linecount = mMaximum;
5353                }
5354            }
5355        } else {
5356            desired = Math.min(desired, mMaximum);
5357        }
5358
5359        if (mMinMode == LINES) {
5360            if (linecount < mMinimum) {
5361                desired += getLineHeight() * (mMinimum - linecount);
5362            }
5363        } else {
5364            desired = Math.max(desired, mMinimum);
5365        }
5366
5367        // Check against our minimum height
5368        desired = Math.max(desired, getSuggestedMinimumHeight());
5369
5370        return desired;
5371    }
5372
5373    /**
5374     * Check whether a change to the existing text layout requires a
5375     * new view layout.
5376     */
5377    private void checkForResize() {
5378        boolean sizeChanged = false;
5379
5380        if (mLayout != null) {
5381            // Check if our width changed
5382            if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) {
5383                sizeChanged = true;
5384                invalidate();
5385            }
5386
5387            // Check if our height changed
5388            if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) {
5389                int desiredHeight = getDesiredHeight();
5390
5391                if (desiredHeight != this.getHeight()) {
5392                    sizeChanged = true;
5393                }
5394            } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) {
5395                if (mDesiredHeightAtMeasure >= 0) {
5396                    int desiredHeight = getDesiredHeight();
5397
5398                    if (desiredHeight != mDesiredHeightAtMeasure) {
5399                        sizeChanged = true;
5400                    }
5401                }
5402            }
5403        }
5404
5405        if (sizeChanged) {
5406            requestLayout();
5407            // caller will have already invalidated
5408        }
5409    }
5410
5411    /**
5412     * Check whether entirely new text requires a new view layout
5413     * or merely a new text layout.
5414     */
5415    private void checkForRelayout() {
5416        // If we have a fixed width, we can just swap in a new text layout
5417        // if the text height stays the same or if the view height is fixed.
5418
5419        if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT ||
5420                (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) &&
5421                (mHint == null || mHintLayout != null) &&
5422                (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) {
5423            // Static width, so try making a new text layout.
5424
5425            int oldht = mLayout.getHeight();
5426            int want = mLayout.getWidth();
5427            int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();
5428
5429            /*
5430             * No need to bring the text into view, since the size is not
5431             * changing (unless we do the requestLayout(), in which case it
5432             * will happen at measure).
5433             */
5434            makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
5435                          mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(),
5436                          false);
5437
5438            if (mEllipsize != TextUtils.TruncateAt.MARQUEE) {
5439                // In a fixed-height view, so use our new text layout.
5440                if (mLayoutParams.height != LayoutParams.WRAP_CONTENT &&
5441                    mLayoutParams.height != LayoutParams.MATCH_PARENT) {
5442                    invalidate();
5443                    return;
5444                }
5445
5446                // Dynamic height, but height has stayed the same,
5447                // so use our new text layout.
5448                if (mLayout.getHeight() == oldht &&
5449                    (mHintLayout == null || mHintLayout.getHeight() == oldht)) {
5450                    invalidate();
5451                    return;
5452                }
5453            }
5454
5455            // We lose: the height has changed and we have a dynamic height.
5456            // Request a new view layout using our new text layout.
5457            requestLayout();
5458            invalidate();
5459        } else {
5460            // Dynamic width, so we have no choice but to request a new
5461            // view layout with a new text layout.
5462
5463            nullLayouts();
5464            requestLayout();
5465            invalidate();
5466        }
5467    }
5468
5469    /**
5470     * Returns true if anything changed.
5471     */
5472    private boolean bringTextIntoView() {
5473        int line = 0;
5474        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
5475            line = mLayout.getLineCount() - 1;
5476        }
5477
5478        Layout.Alignment a = mLayout.getParagraphAlignment(line);
5479        int dir = mLayout.getParagraphDirection(line);
5480        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5481        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
5482        int ht = mLayout.getHeight();
5483
5484        int scrollx, scrolly;
5485
5486        if (a == Layout.Alignment.ALIGN_CENTER) {
5487            /*
5488             * Keep centered if possible, or, if it is too wide to fit,
5489             * keep leading edge in view.
5490             */
5491
5492            int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
5493            int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
5494
5495            if (right - left < hspace) {
5496                scrollx = (right + left) / 2 - hspace / 2;
5497            } else {
5498                if (dir < 0) {
5499                    scrollx = right - hspace;
5500                } else {
5501                    scrollx = left;
5502                }
5503            }
5504        } else if (a == Layout.Alignment.ALIGN_NORMAL) {
5505            /*
5506             * Keep leading edge in view.
5507             */
5508
5509            if (dir < 0) {
5510                int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
5511                scrollx = right - hspace;
5512            } else {
5513                scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line));
5514            }
5515        } else /* a == Layout.Alignment.ALIGN_OPPOSITE */ {
5516            /*
5517             * Keep trailing edge in view.
5518             */
5519
5520            if (dir < 0) {
5521                scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line));
5522            } else {
5523                int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
5524                scrollx = right - hspace;
5525            }
5526        }
5527
5528        if (ht < vspace) {
5529            scrolly = 0;
5530        } else {
5531            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
5532                scrolly = ht - vspace;
5533            } else {
5534                scrolly = 0;
5535            }
5536        }
5537
5538        if (scrollx != mScrollX || scrolly != mScrollY) {
5539            scrollTo(scrollx, scrolly);
5540            return true;
5541        } else {
5542            return false;
5543        }
5544    }
5545
5546    /**
5547     * Move the point, specified by the offset, into the view if it is needed.
5548     * This has to be called after layout. Returns true if anything changed.
5549     */
5550    public boolean bringPointIntoView(int offset) {
5551        boolean changed = false;
5552
5553        int line = mLayout.getLineForOffset(offset);
5554
5555        // FIXME: Is it okay to truncate this, or should we round?
5556        final int x = (int)mLayout.getPrimaryHorizontal(offset);
5557        final int top = mLayout.getLineTop(line);
5558        final int bottom = mLayout.getLineTop(line + 1);
5559
5560        int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
5561        int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
5562        int ht = mLayout.getHeight();
5563
5564        int grav;
5565
5566        switch (mLayout.getParagraphAlignment(line)) {
5567            case ALIGN_NORMAL:
5568                grav = 1;
5569                break;
5570
5571            case ALIGN_OPPOSITE:
5572                grav = -1;
5573                break;
5574
5575            default:
5576                grav = 0;
5577        }
5578
5579        grav *= mLayout.getParagraphDirection(line);
5580
5581        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5582        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
5583
5584        int hslack = (bottom - top) / 2;
5585        int vslack = hslack;
5586
5587        if (vslack > vspace / 4)
5588            vslack = vspace / 4;
5589        if (hslack > hspace / 4)
5590            hslack = hspace / 4;
5591
5592        int hs = mScrollX;
5593        int vs = mScrollY;
5594
5595        if (top - vs < vslack)
5596            vs = top - vslack;
5597        if (bottom - vs > vspace - vslack)
5598            vs = bottom - (vspace - vslack);
5599        if (ht - vs < vspace)
5600            vs = ht - vspace;
5601        if (0 - vs > 0)
5602            vs = 0;
5603
5604        if (grav != 0) {
5605            if (x - hs < hslack) {
5606                hs = x - hslack;
5607            }
5608            if (x - hs > hspace - hslack) {
5609                hs = x - (hspace - hslack);
5610            }
5611        }
5612
5613        if (grav < 0) {
5614            if (left - hs > 0)
5615                hs = left;
5616            if (right - hs < hspace)
5617                hs = right - hspace;
5618        } else if (grav > 0) {
5619            if (right - hs < hspace)
5620                hs = right - hspace;
5621            if (left - hs > 0)
5622                hs = left;
5623        } else /* grav == 0 */ {
5624            if (right - left <= hspace) {
5625                /*
5626                 * If the entire text fits, center it exactly.
5627                 */
5628                hs = left - (hspace - (right - left)) / 2;
5629            } else if (x > right - hslack) {
5630                /*
5631                 * If we are near the right edge, keep the right edge
5632                 * at the edge of the view.
5633                 */
5634                hs = right - hspace;
5635            } else if (x < left + hslack) {
5636                /*
5637                 * If we are near the left edge, keep the left edge
5638                 * at the edge of the view.
5639                 */
5640                hs = left;
5641            } else if (left > hs) {
5642                /*
5643                 * Is there whitespace visible at the left?  Fix it if so.
5644                 */
5645                hs = left;
5646            } else if (right < hs + hspace) {
5647                /*
5648                 * Is there whitespace visible at the right?  Fix it if so.
5649                 */
5650                hs = right - hspace;
5651            } else {
5652                /*
5653                 * Otherwise, float as needed.
5654                 */
5655                if (x - hs < hslack) {
5656                    hs = x - hslack;
5657                }
5658                if (x - hs > hspace - hslack) {
5659                    hs = x - (hspace - hslack);
5660                }
5661            }
5662        }
5663
5664        if (hs != mScrollX || vs != mScrollY) {
5665            if (mScroller == null) {
5666                scrollTo(hs, vs);
5667            } else {
5668                long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
5669                int dx = hs - mScrollX;
5670                int dy = vs - mScrollY;
5671
5672                if (duration > ANIMATED_SCROLL_GAP) {
5673                    mScroller.startScroll(mScrollX, mScrollY, dx, dy);
5674                    awakenScrollBars(mScroller.getDuration());
5675                    invalidate();
5676                } else {
5677                    if (!mScroller.isFinished()) {
5678                        mScroller.abortAnimation();
5679                    }
5680
5681                    scrollBy(dx, dy);
5682                }
5683
5684                mLastScroll = AnimationUtils.currentAnimationTimeMillis();
5685            }
5686
5687            changed = true;
5688        }
5689
5690        if (isFocused()) {
5691            // This offsets because getInterestingRect() is in terms of
5692            // viewport coordinates, but requestRectangleOnScreen()
5693            // is in terms of content coordinates.
5694
5695            Rect r = new Rect(x, top, x + 1, bottom);
5696            getInterestingRect(r, line);
5697            r.offset(mScrollX, mScrollY);
5698
5699            if (requestRectangleOnScreen(r)) {
5700                changed = true;
5701            }
5702        }
5703
5704        return changed;
5705    }
5706
5707    /**
5708     * Move the cursor, if needed, so that it is at an offset that is visible
5709     * to the user.  This will not move the cursor if it represents more than
5710     * one character (a selection range).  This will only work if the
5711     * TextView contains spannable text; otherwise it will do nothing.
5712     *
5713     * @return True if the cursor was actually moved, false otherwise.
5714     */
5715    public boolean moveCursorToVisibleOffset() {
5716        if (!(mText instanceof Spannable)) {
5717            return false;
5718        }
5719        int start = getSelectionStart();
5720        int end = getSelectionEnd();
5721        if (start != end) {
5722            return false;
5723        }
5724
5725        // First: make sure the line is visible on screen:
5726
5727        int line = mLayout.getLineForOffset(start);
5728
5729        final int top = mLayout.getLineTop(line);
5730        final int bottom = mLayout.getLineTop(line + 1);
5731        final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
5732        int vslack = (bottom - top) / 2;
5733        if (vslack > vspace / 4)
5734            vslack = vspace / 4;
5735        final int vs = mScrollY;
5736
5737        if (top < (vs+vslack)) {
5738            line = mLayout.getLineForVertical(vs+vslack+(bottom-top));
5739        } else if (bottom > (vspace+vs-vslack)) {
5740            line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top));
5741        }
5742
5743        // Next: make sure the character is visible on screen:
5744
5745        final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5746        final int hs = mScrollX;
5747        final int leftChar = mLayout.getOffsetForHorizontal(line, hs);
5748        final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs);
5749
5750        int newStart = start;
5751        if (newStart < leftChar) {
5752            newStart = leftChar;
5753        } else if (newStart > rightChar) {
5754            newStart = rightChar;
5755        }
5756
5757        if (newStart != start) {
5758            Selection.setSelection((Spannable)mText, newStart);
5759            return true;
5760        }
5761
5762        return false;
5763    }
5764
5765    @Override
5766    public void computeScroll() {
5767        if (mScroller != null) {
5768            if (mScroller.computeScrollOffset()) {
5769                mScrollX = mScroller.getCurrX();
5770                mScrollY = mScroller.getCurrY();
5771                postInvalidate();  // So we draw again
5772            }
5773        }
5774    }
5775
5776    private void getInterestingRect(Rect r, int line) {
5777        convertFromViewportToContentCoordinates(r);
5778
5779        // Rectangle can can be expanded on first and last line to take
5780        // padding into account.
5781        // TODO Take left/right padding into account too?
5782        if (line == 0) r.top -= getExtendedPaddingTop();
5783        if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom();
5784    }
5785
5786    private void convertFromViewportToContentCoordinates(Rect r) {
5787        final int horizontalOffset = viewportToContentHorizontalOffset();
5788        r.left += horizontalOffset;
5789        r.right += horizontalOffset;
5790
5791        final int verticalOffset = viewportToContentVerticalOffset();
5792        r.top += verticalOffset;
5793        r.bottom += verticalOffset;
5794    }
5795
5796    private int viewportToContentHorizontalOffset() {
5797        return getCompoundPaddingLeft() - mScrollX;
5798    }
5799
5800    private int viewportToContentVerticalOffset() {
5801        int offset = getExtendedPaddingTop() - mScrollY;
5802        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
5803            offset += getVerticalOffset(false);
5804        }
5805        return offset;
5806    }
5807
5808    @Override
5809    public void debug(int depth) {
5810        super.debug(depth);
5811
5812        String output = debugIndent(depth);
5813        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
5814                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
5815                + "} ";
5816
5817        if (mText != null) {
5818
5819            output += "mText=\"" + mText + "\" ";
5820            if (mLayout != null) {
5821                output += "mLayout width=" + mLayout.getWidth()
5822                        + " height=" + mLayout.getHeight();
5823            }
5824        } else {
5825            output += "mText=NULL";
5826        }
5827        Log.d(VIEW_LOG_TAG, output);
5828    }
5829
5830    /**
5831     * Convenience for {@link Selection#getSelectionStart}.
5832     */
5833    @ViewDebug.ExportedProperty(category = "text")
5834    public int getSelectionStart() {
5835        return Selection.getSelectionStart(getText());
5836    }
5837
5838    /**
5839     * Convenience for {@link Selection#getSelectionEnd}.
5840     */
5841    @ViewDebug.ExportedProperty(category = "text")
5842    public int getSelectionEnd() {
5843        return Selection.getSelectionEnd(getText());
5844    }
5845
5846    /**
5847     * Return true iff there is a selection inside this text view.
5848     */
5849    public boolean hasSelection() {
5850        final int selectionStart = getSelectionStart();
5851        final int selectionEnd = getSelectionEnd();
5852
5853        return selectionStart >= 0 && selectionStart != selectionEnd;
5854    }
5855
5856    /**
5857     * Sets the properties of this field (lines, horizontally scrolling,
5858     * transformation method) to be for a single-line input.
5859     *
5860     * @attr ref android.R.styleable#TextView_singleLine
5861     */
5862    public void setSingleLine() {
5863        setSingleLine(true);
5864    }
5865
5866    /**
5867     * If true, sets the properties of this field (lines, horizontally
5868     * scrolling, transformation method) to be for a single-line input;
5869     * if false, restores these to the default conditions.
5870     * Note that calling this with false restores default conditions,
5871     * not necessarily those that were in effect prior to calling
5872     * it with true.
5873     *
5874     * @attr ref android.R.styleable#TextView_singleLine
5875     */
5876    @android.view.RemotableViewMethod
5877    public void setSingleLine(boolean singleLine) {
5878        if ((mInputType&EditorInfo.TYPE_MASK_CLASS)
5879                == EditorInfo.TYPE_CLASS_TEXT) {
5880            if (singleLine) {
5881                mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
5882            } else {
5883                mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
5884            }
5885        }
5886        applySingleLine(singleLine, true);
5887    }
5888
5889    private void applySingleLine(boolean singleLine, boolean applyTransformation) {
5890        mSingleLine = singleLine;
5891        if (singleLine) {
5892            setLines(1);
5893            setHorizontallyScrolling(true);
5894            if (applyTransformation) {
5895                setTransformationMethod(SingleLineTransformationMethod.
5896                                        getInstance());
5897            }
5898        } else {
5899            setMaxLines(Integer.MAX_VALUE);
5900            setHorizontallyScrolling(false);
5901            if (applyTransformation) {
5902                setTransformationMethod(null);
5903            }
5904        }
5905    }
5906
5907    /**
5908     * Causes words in the text that are longer than the view is wide
5909     * to be ellipsized instead of broken in the middle.  You may also
5910     * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling}
5911     * to constrain the text to a single line.  Use <code>null</code>
5912     * to turn off ellipsizing.
5913     *
5914     * @attr ref android.R.styleable#TextView_ellipsize
5915     */
5916    public void setEllipsize(TextUtils.TruncateAt where) {
5917        mEllipsize = where;
5918
5919        if (mLayout != null) {
5920            nullLayouts();
5921            requestLayout();
5922            invalidate();
5923        }
5924    }
5925
5926    /**
5927     * Sets how many times to repeat the marquee animation. Only applied if the
5928     * TextView has marquee enabled. Set to -1 to repeat indefinitely.
5929     *
5930     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
5931     */
5932    public void setMarqueeRepeatLimit(int marqueeLimit) {
5933        mMarqueeRepeatLimit = marqueeLimit;
5934    }
5935
5936    /**
5937     * Returns where, if anywhere, words that are longer than the view
5938     * is wide should be ellipsized.
5939     */
5940    @ViewDebug.ExportedProperty
5941    public TextUtils.TruncateAt getEllipsize() {
5942        return mEllipsize;
5943    }
5944
5945    /**
5946     * Set the TextView so that when it takes focus, all the text is
5947     * selected.
5948     *
5949     * @attr ref android.R.styleable#TextView_selectAllOnFocus
5950     */
5951    @android.view.RemotableViewMethod
5952    public void setSelectAllOnFocus(boolean selectAllOnFocus) {
5953        mSelectAllOnFocus = selectAllOnFocus;
5954
5955        if (selectAllOnFocus && !(mText instanceof Spannable)) {
5956            setText(mText, BufferType.SPANNABLE);
5957        }
5958    }
5959
5960    /**
5961     * Set whether the cursor is visible.  The default is true.
5962     *
5963     * @attr ref android.R.styleable#TextView_cursorVisible
5964     */
5965    @android.view.RemotableViewMethod
5966    public void setCursorVisible(boolean visible) {
5967        mCursorVisible = visible;
5968        invalidate();
5969
5970        if (visible) {
5971            makeBlink();
5972        } else if (mBlink != null) {
5973            mBlink.removeCallbacks(mBlink);
5974        }
5975
5976        // InsertionPointCursorController depends on mCursorVisible
5977        prepareCursorControllers();
5978    }
5979
5980    private boolean canMarquee() {
5981        int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight());
5982        return width > 0 && mLayout.getLineWidth(0) > width;
5983    }
5984
5985    private void startMarquee() {
5986        // Do not ellipsize EditText
5987        if (mInput != null) return;
5988
5989        if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
5990            return;
5991        }
5992
5993        if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) &&
5994                getLineCount() == 1 && canMarquee()) {
5995
5996            if (mMarquee == null) mMarquee = new Marquee(this);
5997            mMarquee.start(mMarqueeRepeatLimit);
5998        }
5999    }
6000
6001    private void stopMarquee() {
6002        if (mMarquee != null && !mMarquee.isStopped()) {
6003            mMarquee.stop();
6004        }
6005    }
6006
6007    private void startStopMarquee(boolean start) {
6008        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6009            if (start) {
6010                startMarquee();
6011            } else {
6012                stopMarquee();
6013            }
6014        }
6015    }
6016
6017    private static final class Marquee extends Handler {
6018        // TODO: Add an option to configure this
6019        private static final float MARQUEE_DELTA_MAX = 0.07f;
6020        private static final int MARQUEE_DELAY = 1200;
6021        private static final int MARQUEE_RESTART_DELAY = 1200;
6022        private static final int MARQUEE_RESOLUTION = 1000 / 30;
6023        private static final int MARQUEE_PIXELS_PER_SECOND = 30;
6024
6025        private static final byte MARQUEE_STOPPED = 0x0;
6026        private static final byte MARQUEE_STARTING = 0x1;
6027        private static final byte MARQUEE_RUNNING = 0x2;
6028
6029        private static final int MESSAGE_START = 0x1;
6030        private static final int MESSAGE_TICK = 0x2;
6031        private static final int MESSAGE_RESTART = 0x3;
6032
6033        private final WeakReference<TextView> mView;
6034
6035        private byte mStatus = MARQUEE_STOPPED;
6036        private final float mScrollUnit;
6037        private float mMaxScroll;
6038        float mMaxFadeScroll;
6039        private float mGhostStart;
6040        private float mGhostOffset;
6041        private float mFadeStop;
6042        private int mRepeatLimit;
6043
6044        float mScroll;
6045
6046        Marquee(TextView v) {
6047            final float density = v.getContext().getResources().getDisplayMetrics().density;
6048            mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION;
6049            mView = new WeakReference<TextView>(v);
6050        }
6051
6052        @Override
6053        public void handleMessage(Message msg) {
6054            switch (msg.what) {
6055                case MESSAGE_START:
6056                    mStatus = MARQUEE_RUNNING;
6057                    tick();
6058                    break;
6059                case MESSAGE_TICK:
6060                    tick();
6061                    break;
6062                case MESSAGE_RESTART:
6063                    if (mStatus == MARQUEE_RUNNING) {
6064                        if (mRepeatLimit >= 0) {
6065                            mRepeatLimit--;
6066                        }
6067                        start(mRepeatLimit);
6068                    }
6069                    break;
6070            }
6071        }
6072
6073        void tick() {
6074            if (mStatus != MARQUEE_RUNNING) {
6075                return;
6076            }
6077
6078            removeMessages(MESSAGE_TICK);
6079
6080            final TextView textView = mView.get();
6081            if (textView != null && (textView.isFocused() || textView.isSelected())) {
6082                mScroll += mScrollUnit;
6083                if (mScroll > mMaxScroll) {
6084                    mScroll = mMaxScroll;
6085                    sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY);
6086                } else {
6087                    sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION);
6088                }
6089                textView.invalidate();
6090            }
6091        }
6092
6093        void stop() {
6094            mStatus = MARQUEE_STOPPED;
6095            removeMessages(MESSAGE_START);
6096            removeMessages(MESSAGE_RESTART);
6097            removeMessages(MESSAGE_TICK);
6098            resetScroll();
6099        }
6100
6101        private void resetScroll() {
6102            mScroll = 0.0f;
6103            final TextView textView = mView.get();
6104            if (textView != null) textView.invalidate();
6105        }
6106
6107        void start(int repeatLimit) {
6108            if (repeatLimit == 0) {
6109                stop();
6110                return;
6111            }
6112            mRepeatLimit = repeatLimit;
6113            final TextView textView = mView.get();
6114            if (textView != null && textView.mLayout != null) {
6115                mStatus = MARQUEE_STARTING;
6116                mScroll = 0.0f;
6117                final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() -
6118                        textView.getCompoundPaddingRight();
6119                final float lineWidth = textView.mLayout.getLineWidth(0);
6120                final float gap = textWidth / 3.0f;
6121                mGhostStart = lineWidth - textWidth + gap;
6122                mMaxScroll = mGhostStart + textWidth;
6123                mGhostOffset = lineWidth + gap;
6124                mFadeStop = lineWidth + textWidth / 6.0f;
6125                mMaxFadeScroll = mGhostStart + lineWidth + lineWidth;
6126
6127                textView.invalidate();
6128                sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY);
6129            }
6130        }
6131
6132        float getGhostOffset() {
6133            return mGhostOffset;
6134        }
6135
6136        boolean shouldDrawLeftFade() {
6137            return mScroll <= mFadeStop;
6138        }
6139
6140        boolean shouldDrawGhost() {
6141            return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart;
6142        }
6143
6144        boolean isRunning() {
6145            return mStatus == MARQUEE_RUNNING;
6146        }
6147
6148        boolean isStopped() {
6149            return mStatus == MARQUEE_STOPPED;
6150        }
6151    }
6152
6153    /**
6154     * This method is called when the text is changed, in case any
6155     * subclasses would like to know.
6156     *
6157     * @param text The text the TextView is displaying.
6158     * @param start The offset of the start of the range of the text
6159     *              that was modified.
6160     * @param before The offset of the former end of the range of the
6161     *               text that was modified.  If text was simply inserted,
6162     *               this will be the same as <code>start</code>.
6163     *               If text was replaced with new text or deleted, the
6164     *               length of the old text was <code>before-start</code>.
6165     * @param after The offset of the end of the range of the text
6166     *              that was modified.  If text was simply deleted,
6167     *              this will be the same as <code>start</code>.
6168     *              If text was replaced with new text or inserted,
6169     *              the length of the new text is <code>after-start</code>.
6170     */
6171    protected void onTextChanged(CharSequence text,
6172                                 int start, int before, int after) {
6173    }
6174
6175    /**
6176     * This method is called when the selection has changed, in case any
6177     * subclasses would like to know.
6178     *
6179     * @param selStart The new selection start location.
6180     * @param selEnd The new selection end location.
6181     */
6182    protected void onSelectionChanged(int selStart, int selEnd) {
6183    }
6184
6185    /**
6186     * Adds a TextWatcher to the list of those whose methods are called
6187     * whenever this TextView's text changes.
6188     * <p>
6189     * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
6190     * not called after {@link #setText} calls.  Now, doing {@link #setText}
6191     * if there are any text changed listeners forces the buffer type to
6192     * Editable if it would not otherwise be and does call this method.
6193     */
6194    public void addTextChangedListener(TextWatcher watcher) {
6195        if (mListeners == null) {
6196            mListeners = new ArrayList<TextWatcher>();
6197        }
6198
6199        mListeners.add(watcher);
6200    }
6201
6202    /**
6203     * Removes the specified TextWatcher from the list of those whose
6204     * methods are called
6205     * whenever this TextView's text changes.
6206     */
6207    public void removeTextChangedListener(TextWatcher watcher) {
6208        if (mListeners != null) {
6209            int i = mListeners.indexOf(watcher);
6210
6211            if (i >= 0) {
6212                mListeners.remove(i);
6213            }
6214        }
6215    }
6216
6217    private void sendBeforeTextChanged(CharSequence text, int start, int before,
6218                                   int after) {
6219        if (mListeners != null) {
6220            final ArrayList<TextWatcher> list = mListeners;
6221            final int count = list.size();
6222            for (int i = 0; i < count; i++) {
6223                list.get(i).beforeTextChanged(text, start, before, after);
6224            }
6225        }
6226    }
6227
6228    /**
6229     * Not private so it can be called from an inner class without going
6230     * through a thunk.
6231     */
6232    void sendOnTextChanged(CharSequence text, int start, int before,
6233                                   int after) {
6234        if (mListeners != null) {
6235            final ArrayList<TextWatcher> list = mListeners;
6236            final int count = list.size();
6237            for (int i = 0; i < count; i++) {
6238                list.get(i).onTextChanged(text, start, before, after);
6239            }
6240        }
6241    }
6242
6243    /**
6244     * Not private so it can be called from an inner class without going
6245     * through a thunk.
6246     */
6247    void sendAfterTextChanged(Editable text) {
6248        if (mListeners != null) {
6249            final ArrayList<TextWatcher> list = mListeners;
6250            final int count = list.size();
6251            for (int i = 0; i < count; i++) {
6252                list.get(i).afterTextChanged(text);
6253            }
6254        }
6255    }
6256
6257    /**
6258     * Not private so it can be called from an inner class without going
6259     * through a thunk.
6260     */
6261    void handleTextChanged(CharSequence buffer, int start,
6262            int before, int after) {
6263        final InputMethodState ims = mInputMethodState;
6264        if (ims == null || ims.mBatchEditNesting == 0) {
6265            updateAfterEdit();
6266        }
6267        if (ims != null) {
6268            ims.mContentChanged = true;
6269            if (ims.mChangedStart < 0) {
6270                ims.mChangedStart = start;
6271                ims.mChangedEnd = start+before;
6272            } else {
6273                if (ims.mChangedStart > start) ims.mChangedStart = start;
6274                if (ims.mChangedEnd < (start+before)) ims.mChangedEnd = start+before;
6275            }
6276            ims.mChangedDelta += after-before;
6277        }
6278
6279        sendOnTextChanged(buffer, start, before, after);
6280        onTextChanged(buffer, start, before, after);
6281
6282        // Hide the controller if the amount of content changed
6283        if (before != after) {
6284            hideControllers();
6285        }
6286    }
6287
6288    /**
6289     * Not private so it can be called from an inner class without going
6290     * through a thunk.
6291     */
6292    void spanChange(Spanned buf, Object what, int oldStart, int newStart,
6293            int oldEnd, int newEnd) {
6294        // XXX Make the start and end move together if this ends up
6295        // spending too much time invalidating.
6296
6297        boolean selChanged = false;
6298        int newSelStart=-1, newSelEnd=-1;
6299
6300        final InputMethodState ims = mInputMethodState;
6301
6302        if (what == Selection.SELECTION_END) {
6303            mHighlightPathBogus = true;
6304            selChanged = true;
6305            newSelEnd = newStart;
6306
6307            if (!isFocused()) {
6308                mSelectionMoved = true;
6309            }
6310
6311            if (oldStart >= 0 || newStart >= 0) {
6312                invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart);
6313                registerForPreDraw();
6314
6315                if (isFocused()) {
6316                    mShowCursor = SystemClock.uptimeMillis();
6317                    makeBlink();
6318                }
6319            }
6320        }
6321
6322        if (what == Selection.SELECTION_START) {
6323            mHighlightPathBogus = true;
6324            selChanged = true;
6325            newSelStart = newStart;
6326
6327            if (!isFocused()) {
6328                mSelectionMoved = true;
6329            }
6330
6331            if (oldStart >= 0 || newStart >= 0) {
6332                int end = Selection.getSelectionEnd(buf);
6333                invalidateCursor(end, oldStart, newStart);
6334            }
6335        }
6336
6337        if (selChanged) {
6338            if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) {
6339                if (newSelStart < 0) {
6340                    newSelStart = Selection.getSelectionStart(buf);
6341                }
6342                if (newSelEnd < 0) {
6343                    newSelEnd = Selection.getSelectionEnd(buf);
6344                }
6345                onSelectionChanged(newSelStart, newSelEnd);
6346            }
6347        }
6348
6349        if (what instanceof UpdateAppearance ||
6350            what instanceof ParagraphStyle) {
6351            if (ims == null || ims.mBatchEditNesting == 0) {
6352                invalidate();
6353                mHighlightPathBogus = true;
6354                checkForResize();
6355            } else {
6356                ims.mContentChanged = true;
6357            }
6358        }
6359
6360        if (MetaKeyKeyListener.isMetaTracker(buf, what)) {
6361            mHighlightPathBogus = true;
6362            if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) {
6363                ims.mSelectionModeChanged = true;
6364            }
6365
6366            if (Selection.getSelectionStart(buf) >= 0) {
6367                if (ims == null || ims.mBatchEditNesting == 0) {
6368                    invalidateCursor();
6369                } else {
6370                    ims.mCursorChanged = true;
6371                }
6372            }
6373        }
6374
6375        if (what instanceof ParcelableSpan) {
6376            // If this is a span that can be sent to a remote process,
6377            // the current extract editor would be interested in it.
6378            if (ims != null && ims.mExtracting != null) {
6379                if (ims.mBatchEditNesting != 0) {
6380                    if (oldStart >= 0) {
6381                        if (ims.mChangedStart > oldStart) {
6382                            ims.mChangedStart = oldStart;
6383                        }
6384                        if (ims.mChangedStart > oldEnd) {
6385                            ims.mChangedStart = oldEnd;
6386                        }
6387                    }
6388                    if (newStart >= 0) {
6389                        if (ims.mChangedStart > newStart) {
6390                            ims.mChangedStart = newStart;
6391                        }
6392                        if (ims.mChangedStart > newEnd) {
6393                            ims.mChangedStart = newEnd;
6394                        }
6395                    }
6396                } else {
6397                    if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: "
6398                            + oldStart + "-" + oldEnd + ","
6399                            + newStart + "-" + newEnd + what);
6400                    ims.mContentChanged = true;
6401                }
6402            }
6403        }
6404    }
6405
6406    private class ChangeWatcher
6407    implements TextWatcher, SpanWatcher {
6408
6409        private CharSequence mBeforeText;
6410
6411        public void beforeTextChanged(CharSequence buffer, int start,
6412                                      int before, int after) {
6413            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start
6414                    + " before=" + before + " after=" + after + ": " + buffer);
6415
6416            if (AccessibilityManager.getInstance(mContext).isEnabled()
6417                    && !isPasswordInputType(mInputType)) {
6418                mBeforeText = buffer.toString();
6419            }
6420
6421            TextView.this.sendBeforeTextChanged(buffer, start, before, after);
6422        }
6423
6424        public void onTextChanged(CharSequence buffer, int start,
6425                                  int before, int after) {
6426            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start
6427                    + " before=" + before + " after=" + after + ": " + buffer);
6428            TextView.this.handleTextChanged(buffer, start, before, after);
6429
6430            if (AccessibilityManager.getInstance(mContext).isEnabled() &&
6431                    (isFocused() || isSelected() &&
6432                    isShown())) {
6433                sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after);
6434                mBeforeText = null;
6435            }
6436        }
6437
6438        public void afterTextChanged(Editable buffer) {
6439            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer);
6440            TextView.this.sendAfterTextChanged(buffer);
6441
6442            if (MetaKeyKeyListener.getMetaState(buffer,
6443                                 MetaKeyKeyListener.META_SELECTING) != 0) {
6444                MetaKeyKeyListener.stopSelecting(TextView.this, buffer);
6445            }
6446        }
6447
6448        public void onSpanChanged(Spannable buf,
6449                                  Object what, int s, int e, int st, int en) {
6450            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e
6451                    + " st=" + st + " en=" + en + " what=" + what + ": " + buf);
6452            TextView.this.spanChange(buf, what, s, st, e, en);
6453        }
6454
6455        public void onSpanAdded(Spannable buf, Object what, int s, int e) {
6456            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e
6457                    + " what=" + what + ": " + buf);
6458            TextView.this.spanChange(buf, what, -1, s, -1, e);
6459        }
6460
6461        public void onSpanRemoved(Spannable buf, Object what, int s, int e) {
6462            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e
6463                    + " what=" + what + ": " + buf);
6464            TextView.this.spanChange(buf, what, s, -1, e, -1);
6465        }
6466    }
6467
6468    private void makeBlink() {
6469        if (!mCursorVisible) {
6470            if (mBlink != null) {
6471                mBlink.removeCallbacks(mBlink);
6472            }
6473
6474            return;
6475        }
6476
6477        if (mBlink == null)
6478            mBlink = new Blink(this);
6479
6480        mBlink.removeCallbacks(mBlink);
6481        mBlink.postAtTime(mBlink, mShowCursor + BLINK);
6482    }
6483
6484    /**
6485     * @hide
6486     */
6487    @Override
6488    public void dispatchFinishTemporaryDetach() {
6489        mDispatchTemporaryDetach = true;
6490        super.dispatchFinishTemporaryDetach();
6491        mDispatchTemporaryDetach = false;
6492    }
6493
6494    @Override
6495    public void onStartTemporaryDetach() {
6496        super.onStartTemporaryDetach();
6497        // Only track when onStartTemporaryDetach() is called directly,
6498        // usually because this instance is an editable field in a list
6499        if (!mDispatchTemporaryDetach) mTemporaryDetach = true;
6500    }
6501
6502    @Override
6503    public void onFinishTemporaryDetach() {
6504        super.onFinishTemporaryDetach();
6505        // Only track when onStartTemporaryDetach() is called directly,
6506        // usually because this instance is an editable field in a list
6507        if (!mDispatchTemporaryDetach) mTemporaryDetach = false;
6508    }
6509
6510    @Override
6511    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
6512        if (mTemporaryDetach) {
6513            // If we are temporarily in the detach state, then do nothing.
6514            super.onFocusChanged(focused, direction, previouslyFocusedRect);
6515            return;
6516        }
6517
6518        mShowCursor = SystemClock.uptimeMillis();
6519
6520        ensureEndedBatchEdit();
6521
6522        if (focused) {
6523            int selStart = getSelectionStart();
6524            int selEnd = getSelectionEnd();
6525
6526            if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
6527                // Has to be done before onTakeFocus, which can be overloaded.
6528                if (mLastTouchOffset >= 0) {
6529                    // Can happen when a TextView is displayed after its content has been deleted.
6530                    mLastTouchOffset = Math.min(mLastTouchOffset, mText.length());
6531                    Selection.setSelection((Spannable) mText, mLastTouchOffset);
6532                }
6533
6534                if (mMovement != null) {
6535                    mMovement.onTakeFocus(this, (Spannable) mText, direction);
6536                }
6537
6538                if (mSelectAllOnFocus) {
6539                    Selection.setSelection((Spannable) mText, 0, mText.length());
6540                }
6541
6542                // The DecorView does not have focus when the 'Done' ExtractEditText button is
6543                // pressed. Since it is the ViewRoot's mView, it requests focus before
6544                // ExtractEditText clears focus, which gives focus to the ExtractEditText.
6545                // This special case ensure that we keep current selection in that case.
6546                // It would be better to know why the DecorView does not have focus at that time.
6547                if (((this instanceof ExtractEditText) || mSelectionMoved) &&
6548                        selStart >= 0 && selEnd >= 0) {
6549                    /*
6550                     * Someone intentionally set the selection, so let them
6551                     * do whatever it is that they wanted to do instead of
6552                     * the default on-focus behavior.  We reset the selection
6553                     * here instead of just skipping the onTakeFocus() call
6554                     * because some movement methods do something other than
6555                     * just setting the selection in theirs and we still
6556                     * need to go through that path.
6557                     */
6558                    Selection.setSelection((Spannable) mText, selStart, selEnd);
6559                }
6560                mTouchFocusSelected = true;
6561            }
6562
6563            mFrozenWithFocus = false;
6564            mSelectionMoved = false;
6565
6566            if (mText instanceof Spannable) {
6567                Spannable sp = (Spannable) mText;
6568                MetaKeyKeyListener.resetMetaState(sp);
6569            }
6570
6571            makeBlink();
6572
6573            if (mError != null) {
6574                showError();
6575            }
6576        } else {
6577            if (mError != null) {
6578                hideError();
6579            }
6580            // Don't leave us in the middle of a batch edit.
6581            onEndBatchEdit();
6582
6583            hideInsertionPointCursorController();
6584            if (this instanceof ExtractEditText) {
6585                // terminateTextSelectionMode would remove selection, which we want to keep when
6586                // ExtractEditText goes out of focus.
6587                mIsInTextSelectionMode = false;
6588            } else {
6589                terminateTextSelectionMode();
6590            }
6591        }
6592
6593        startStopMarquee(focused);
6594
6595        if (mTransformation != null) {
6596            mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect);
6597        }
6598
6599        super.onFocusChanged(focused, direction, previouslyFocusedRect);
6600    }
6601
6602    @Override
6603    public void onWindowFocusChanged(boolean hasWindowFocus) {
6604        super.onWindowFocusChanged(hasWindowFocus);
6605
6606        if (hasWindowFocus) {
6607            if (mBlink != null) {
6608                mBlink.uncancel();
6609
6610                if (isFocused()) {
6611                    mShowCursor = SystemClock.uptimeMillis();
6612                    makeBlink();
6613                }
6614            }
6615        } else {
6616            if (mBlink != null) {
6617                mBlink.cancel();
6618            }
6619            // Don't leave us in the middle of a batch edit.
6620            onEndBatchEdit();
6621            if (mInputContentType != null) {
6622                mInputContentType.enterDown = false;
6623            }
6624            hideControllers();
6625        }
6626
6627        startStopMarquee(hasWindowFocus);
6628    }
6629
6630    @Override
6631    protected void onVisibilityChanged(View changedView, int visibility) {
6632        super.onVisibilityChanged(changedView, visibility);
6633        if (visibility != VISIBLE) {
6634            hideControllers();
6635        }
6636    }
6637
6638    /**
6639     * Use {@link BaseInputConnection#removeComposingSpans
6640     * BaseInputConnection.removeComposingSpans()} to remove any IME composing
6641     * state from this text view.
6642     */
6643    public void clearComposingText() {
6644        if (mText instanceof Spannable) {
6645            BaseInputConnection.removeComposingSpans((Spannable)mText);
6646        }
6647    }
6648
6649    @Override
6650    public void setSelected(boolean selected) {
6651        boolean wasSelected = isSelected();
6652
6653        super.setSelected(selected);
6654
6655        if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6656            if (selected) {
6657                startMarquee();
6658            } else {
6659                stopMarquee();
6660            }
6661        }
6662    }
6663
6664    private void onTapUpEvent(int prevStart, int prevEnd) {
6665        final int start = getSelectionStart();
6666        final int end = getSelectionEnd();
6667
6668        if (start == end) {
6669            if (start >= prevStart && start < prevEnd) {
6670                // Restore previous selection
6671                Selection.setSelection((Spannable)mText, prevStart, prevEnd);
6672                // Tapping inside the selection displays the cut/copy/paste context menu.
6673                showContextMenu();
6674                return;
6675            } else {
6676                // Tapping outside stops selection mode, if any
6677                stopTextSelectionMode();
6678
6679                if (mInsertionPointCursorController != null) {
6680                    mInsertionPointCursorController.show();
6681                }
6682            }
6683        }
6684    }
6685
6686    class CommitSelectionReceiver extends ResultReceiver {
6687        private final int mPrevStart, mPrevEnd;
6688
6689        public CommitSelectionReceiver(int prevStart, int prevEnd) {
6690            super(getHandler());
6691            mPrevStart = prevStart;
6692            mPrevEnd = prevEnd;
6693        }
6694
6695        @Override
6696        protected void onReceiveResult(int resultCode, Bundle resultData) {
6697            // If this tap was actually used to show the IMM, leave cursor or selection unchanged
6698            // by restoring its previous position.
6699            if (resultCode == InputMethodManager.RESULT_SHOWN) {
6700                final int len = mText.length();
6701                int start = Math.min(len, mPrevStart);
6702                int end = Math.min(len, mPrevEnd);
6703                Selection.setSelection((Spannable)mText, start, end);
6704
6705                if (hasSelection()) {
6706                    startTextSelectionMode();
6707                }
6708            }
6709        }
6710    }
6711
6712    @Override
6713    public boolean onTouchEvent(MotionEvent event) {
6714        final int action = event.getActionMasked();
6715        if (action == MotionEvent.ACTION_DOWN) {
6716            if (mInsertionPointCursorController != null) {
6717                mInsertionPointCursorController.onTouchEvent(event);
6718            }
6719            if (mSelectionModifierCursorController != null) {
6720                mSelectionModifierCursorController.onTouchEvent(event);
6721            }
6722
6723            // Reset this state; it will be re-set if super.onTouchEvent
6724            // causes focus to move to the view.
6725            mTouchFocusSelected = false;
6726            mScrolled = false;
6727        }
6728
6729        final boolean superResult = super.onTouchEvent(event);
6730
6731        /*
6732         * Don't handle the release after a long press, because it will
6733         * move the selection away from whatever the menu action was
6734         * trying to affect.
6735         */
6736        if (mEatTouchRelease && action == MotionEvent.ACTION_UP) {
6737            mEatTouchRelease = false;
6738            return superResult;
6739        }
6740
6741        if ((mMovement != null || onCheckIsTextEditor()) && mText instanceof Spannable && mLayout != null) {
6742            if (mInsertionPointCursorController != null) {
6743                mInsertionPointCursorController.onTouchEvent(event);
6744            }
6745            if (mSelectionModifierCursorController != null) {
6746                mSelectionModifierCursorController.onTouchEvent(event);
6747            }
6748
6749            boolean handled = false;
6750
6751            // Save previous selection, in case this event is used to show the IME.
6752            int oldSelStart = getSelectionStart();
6753            int oldSelEnd = getSelectionEnd();
6754
6755            final int oldScrollX = mScrollX;
6756            final int oldScrollY = mScrollY;
6757
6758            if (mMovement != null) {
6759                handled |= mMovement.onTouchEvent(this, (Spannable) mText, event);
6760            }
6761
6762            if (isTextEditable()) {
6763                if (mScrollX != oldScrollX || mScrollY != oldScrollY) {
6764                    // Hide insertion anchor while scrolling. Leave selection.
6765                    hideInsertionPointCursorController();
6766                    if (mSelectionModifierCursorController != null &&
6767                            mSelectionModifierCursorController.isShowing()) {
6768                        mSelectionModifierCursorController.updatePosition();
6769                    }
6770                }
6771                if (action == MotionEvent.ACTION_UP && isFocused() && !mScrolled) {
6772                    InputMethodManager imm = (InputMethodManager)
6773                          getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
6774
6775                    CommitSelectionReceiver csr = null;
6776                    if (getSelectionStart() != oldSelStart || getSelectionEnd() != oldSelEnd ||
6777                            didTouchFocusSelect()) {
6778                        csr = new CommitSelectionReceiver(oldSelStart, oldSelEnd);
6779                    }
6780
6781                    handled |= imm.showSoftInput(this, 0, csr) && (csr != null);
6782
6783                    // Cannot be done by CommitSelectionReceiver, which might not always be called,
6784                    // for instance when dealing with an ExtractEditText.
6785                    onTapUpEvent(oldSelStart, oldSelEnd);
6786                }
6787            }
6788
6789            if (handled) {
6790                return true;
6791            }
6792        }
6793
6794        return superResult;
6795    }
6796
6797    private void prepareCursorControllers() {
6798        // TODO Add an extra android:cursorController flag to disable the controller?
6799        if (mCursorVisible && mLayout != null) {
6800            if (mInsertionPointCursorController == null) {
6801                mInsertionPointCursorController = new InsertionPointCursorController();
6802            }
6803        } else {
6804            mInsertionPointCursorController = null;
6805        }
6806
6807        if (canSelectText() && mLayout != null) {
6808            if (mSelectionModifierCursorController == null) {
6809                mSelectionModifierCursorController = new SelectionModifierCursorController();
6810            }
6811        } else {
6812            // Stop selection mode if the controller becomes unavailable.
6813            stopTextSelectionMode();
6814            mSelectionModifierCursorController = null;
6815        }
6816    }
6817
6818    /**
6819     * @return True iff this TextView contains a text that can be edited.
6820     */
6821    private boolean isTextEditable() {
6822        return mText instanceof Editable && onCheckIsTextEditor();
6823    }
6824
6825    /**
6826     * Returns true, only while processing a touch gesture, if the initial
6827     * touch down event caused focus to move to the text view and as a result
6828     * its selection changed.  Only valid while processing the touch gesture
6829     * of interest.
6830     */
6831    public boolean didTouchFocusSelect() {
6832        return mTouchFocusSelected;
6833    }
6834
6835    @Override
6836    public void cancelLongPress() {
6837        super.cancelLongPress();
6838        mScrolled = true;
6839    }
6840
6841    @Override
6842    public boolean onTrackballEvent(MotionEvent event) {
6843        if (mMovement != null && mText instanceof Spannable &&
6844            mLayout != null) {
6845            if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) {
6846                return true;
6847            }
6848        }
6849
6850        return super.onTrackballEvent(event);
6851    }
6852
6853    public void setScroller(Scroller s) {
6854        mScroller = s;
6855    }
6856
6857    private static class Blink extends Handler implements Runnable {
6858        private final WeakReference<TextView> mView;
6859        private boolean mCancelled;
6860
6861        public Blink(TextView v) {
6862            mView = new WeakReference<TextView>(v);
6863        }
6864
6865        public void run() {
6866            if (mCancelled) {
6867                return;
6868            }
6869
6870            removeCallbacks(Blink.this);
6871
6872            TextView tv = mView.get();
6873
6874            if (tv != null && tv.isFocused()) {
6875                int st = tv.getSelectionStart();
6876                int en = tv.getSelectionEnd();
6877
6878                if (st == en && st >= 0 && en >= 0) {
6879                    if (tv.mLayout != null) {
6880                        tv.invalidateCursorPath();
6881                    }
6882
6883                    postAtTime(this, SystemClock.uptimeMillis() + BLINK);
6884                }
6885            }
6886        }
6887
6888        void cancel() {
6889            if (!mCancelled) {
6890                removeCallbacks(Blink.this);
6891                mCancelled = true;
6892            }
6893        }
6894
6895        void uncancel() {
6896            mCancelled = false;
6897        }
6898    }
6899
6900    @Override
6901    protected float getLeftFadingEdgeStrength() {
6902        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6903            if (mMarquee != null && !mMarquee.isStopped()) {
6904                final Marquee marquee = mMarquee;
6905                if (marquee.shouldDrawLeftFade()) {
6906                    return marquee.mScroll / getHorizontalFadingEdgeLength();
6907                } else {
6908                    return 0.0f;
6909                }
6910            } else if (getLineCount() == 1) {
6911                switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
6912                    case Gravity.LEFT:
6913                        return 0.0f;
6914                    case Gravity.RIGHT:
6915                        return (mLayout.getLineRight(0) - (mRight - mLeft) -
6916                                getCompoundPaddingLeft() - getCompoundPaddingRight() -
6917                                mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength();
6918                    case Gravity.CENTER_HORIZONTAL:
6919                        return 0.0f;
6920                }
6921            }
6922        }
6923        return super.getLeftFadingEdgeStrength();
6924    }
6925
6926    @Override
6927    protected float getRightFadingEdgeStrength() {
6928        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6929            if (mMarquee != null && !mMarquee.isStopped()) {
6930                final Marquee marquee = mMarquee;
6931                return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength();
6932            } else if (getLineCount() == 1) {
6933                switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
6934                    case Gravity.LEFT:
6935                        final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() -
6936                                getCompoundPaddingRight();
6937                        final float lineWidth = mLayout.getLineWidth(0);
6938                        return (lineWidth - textWidth) / getHorizontalFadingEdgeLength();
6939                    case Gravity.RIGHT:
6940                        return 0.0f;
6941                    case Gravity.CENTER_HORIZONTAL:
6942                        return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
6943                                getCompoundPaddingLeft() - getCompoundPaddingRight())) /
6944                                getHorizontalFadingEdgeLength();
6945                }
6946            }
6947        }
6948        return super.getRightFadingEdgeStrength();
6949    }
6950
6951    @Override
6952    protected int computeHorizontalScrollRange() {
6953        if (mLayout != null)
6954            return mLayout.getWidth();
6955
6956        return super.computeHorizontalScrollRange();
6957    }
6958
6959    @Override
6960    protected int computeVerticalScrollRange() {
6961        if (mLayout != null)
6962            return mLayout.getHeight();
6963
6964        return super.computeVerticalScrollRange();
6965    }
6966
6967    @Override
6968    protected int computeVerticalScrollExtent() {
6969        return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
6970    }
6971
6972    public enum BufferType {
6973        NORMAL, SPANNABLE, EDITABLE,
6974    }
6975
6976    /**
6977     * Returns the TextView_textColor attribute from the
6978     * Resources.StyledAttributes, if set, or the TextAppearance_textColor
6979     * from the TextView_textAppearance attribute, if TextView_textColor
6980     * was not set directly.
6981     */
6982    public static ColorStateList getTextColors(Context context, TypedArray attrs) {
6983        ColorStateList colors;
6984        colors = attrs.getColorStateList(com.android.internal.R.styleable.
6985                                         TextView_textColor);
6986
6987        if (colors == null) {
6988            int ap = attrs.getResourceId(com.android.internal.R.styleable.
6989                                         TextView_textAppearance, -1);
6990            if (ap != -1) {
6991                TypedArray appearance;
6992                appearance = context.obtainStyledAttributes(ap,
6993                                            com.android.internal.R.styleable.TextAppearance);
6994                colors = appearance.getColorStateList(com.android.internal.R.styleable.
6995                                                  TextAppearance_textColor);
6996                appearance.recycle();
6997            }
6998        }
6999
7000        return colors;
7001    }
7002
7003    /**
7004     * Returns the default color from the TextView_textColor attribute
7005     * from the AttributeSet, if set, or the default color from the
7006     * TextAppearance_textColor from the TextView_textAppearance attribute,
7007     * if TextView_textColor was not set directly.
7008     */
7009    public static int getTextColor(Context context,
7010                                   TypedArray attrs,
7011                                   int def) {
7012        ColorStateList colors = getTextColors(context, attrs);
7013
7014        if (colors == null) {
7015            return def;
7016        } else {
7017            return colors.getDefaultColor();
7018        }
7019    }
7020
7021    @Override
7022    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7023        switch (keyCode) {
7024        case KeyEvent.KEYCODE_A:
7025            if (canSelectAll()) {
7026                return onTextContextMenuItem(ID_SELECT_ALL);
7027            }
7028
7029            break;
7030
7031        case KeyEvent.KEYCODE_X:
7032            if (canCut()) {
7033                return onTextContextMenuItem(ID_CUT);
7034            }
7035
7036            break;
7037
7038        case KeyEvent.KEYCODE_C:
7039            if (canCopy()) {
7040                return onTextContextMenuItem(ID_COPY);
7041            }
7042
7043            break;
7044
7045        case KeyEvent.KEYCODE_V:
7046            if (canPaste()) {
7047                return onTextContextMenuItem(ID_PASTE);
7048            }
7049
7050            break;
7051        }
7052
7053        return super.onKeyShortcut(keyCode, event);
7054    }
7055
7056    private boolean canSelectAll() {
7057        return canSelectText() && mText.length() != 0;
7058    }
7059
7060    private boolean canSelectText() {
7061        // prepareCursorController() relies on this method.
7062        // If you change this condition, make sure prepareCursorController is called anywhere
7063        // the value of this condition might be changed.
7064        return (mText instanceof Spannable &&
7065                mMovement != null &&
7066                mMovement.canSelectArbitrarily());
7067    }
7068
7069    private boolean canCut() {
7070        if (mTransformation instanceof PasswordTransformationMethod) {
7071            return false;
7072        }
7073
7074        if (mText.length() > 0 && hasSelection()) {
7075            if (mText instanceof Editable && mInput != null) {
7076                return true;
7077            }
7078        }
7079
7080        return false;
7081    }
7082
7083    private boolean canCopy() {
7084        if (mTransformation instanceof PasswordTransformationMethod) {
7085            return false;
7086        }
7087
7088        if (mText.length() > 0 && hasSelection()) {
7089            return true;
7090        }
7091
7092        return false;
7093    }
7094
7095    private boolean canPaste() {
7096        return (mText instanceof Editable &&
7097                mInput != null &&
7098                getSelectionStart() >= 0 &&
7099                getSelectionEnd() >= 0 &&
7100                ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)).
7101                hasText());
7102    }
7103
7104    /**
7105     * Returns the offsets delimiting the 'word' located at position offset.
7106     *
7107     * @param offset An offset in the text.
7108     * @return The offsets for the start and end of the word located at <code>offset</code>.
7109     * The two ints offsets are packed in a long, with the starting offset shifted by 32 bits.
7110     * Returns a negative value if no valid word was found.
7111     */
7112    private long getWordLimitsAt(int offset) {
7113        /*
7114         * Quick return if the input type is one where adding words
7115         * to the dictionary doesn't make any sense.
7116         */
7117        int klass = mInputType & InputType.TYPE_MASK_CLASS;
7118        if (klass == InputType.TYPE_CLASS_NUMBER ||
7119            klass == InputType.TYPE_CLASS_PHONE ||
7120            klass == InputType.TYPE_CLASS_DATETIME) {
7121            return -1;
7122        }
7123
7124        int variation = mInputType & InputType.TYPE_MASK_VARIATION;
7125        if (variation == InputType.TYPE_TEXT_VARIATION_URI ||
7126            variation == InputType.TYPE_TEXT_VARIATION_PASSWORD ||
7127            variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ||
7128            variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
7129            variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
7130            return -1;
7131        }
7132
7133        int len = mText.length();
7134        int end = Math.min(offset, len);
7135
7136        if (end < 0) {
7137            return -1;
7138        }
7139
7140        int start = end;
7141
7142        for (; start > 0; start--) {
7143            char c = mTransformed.charAt(start - 1);
7144            int type = Character.getType(c);
7145
7146            if (c != '\'' &&
7147                type != Character.UPPERCASE_LETTER &&
7148                type != Character.LOWERCASE_LETTER &&
7149                type != Character.TITLECASE_LETTER &&
7150                type != Character.MODIFIER_LETTER &&
7151                type != Character.DECIMAL_DIGIT_NUMBER) {
7152                break;
7153            }
7154        }
7155
7156        for (; end < len; end++) {
7157            char c = mTransformed.charAt(end);
7158            int type = Character.getType(c);
7159
7160            if (c != '\'' &&
7161                type != Character.UPPERCASE_LETTER &&
7162                type != Character.LOWERCASE_LETTER &&
7163                type != Character.TITLECASE_LETTER &&
7164                type != Character.MODIFIER_LETTER &&
7165                type != Character.DECIMAL_DIGIT_NUMBER) {
7166                break;
7167            }
7168        }
7169
7170        if (start == end) {
7171            return -1;
7172        }
7173
7174        if (end - start > 48) {
7175            return -1;
7176        }
7177
7178        boolean hasLetter = false;
7179        for (int i = start; i < end; i++) {
7180            if (Character.isLetter(mTransformed.charAt(i))) {
7181                hasLetter = true;
7182                break;
7183            }
7184        }
7185
7186        if (!hasLetter) {
7187            return -1;
7188        }
7189
7190        // Two ints packed in a long
7191        return (((long) start) << 32) | end;
7192    }
7193
7194    private void selectCurrentWord() {
7195        // In case selection mode is started after an orientation change or after a select all,
7196        // use the current selection instead of creating one
7197        if (hasSelection()) {
7198            return;
7199        }
7200
7201        int selectionStart, selectionEnd;
7202
7203        // selectionModifierCursorController is not null at that point
7204        SelectionModifierCursorController selectionModifierCursorController =
7205            ((SelectionModifierCursorController) mSelectionModifierCursorController);
7206        int minOffset = selectionModifierCursorController.getMinTouchOffset();
7207        int maxOffset = selectionModifierCursorController.getMaxTouchOffset();
7208
7209        if (minOffset == maxOffset) {
7210            int offset = Math.max(0, Math.min(minOffset, mTransformed.length()));
7211
7212            // Tolerance, number of charaters around tapped position
7213            final int range = 1;
7214            final int max = mTransformed.length() - 1;
7215
7216            // 'Smart' word selection: detect position between words
7217            for (int i = -range; i <= range; i++) {
7218                int index = offset + i;
7219                if (index >= 0 && index <= max) {
7220                    if (Character.isSpaceChar(mTransformed.charAt(index))) {
7221                        // Select current space
7222                        selectionStart = index;
7223                        selectionEnd = selectionStart + 1;
7224
7225                        // Extend selection to maximum space range
7226                        while (selectionStart > 0 &&
7227                                Character.isSpaceChar(mTransformed.charAt(selectionStart - 1))) {
7228                            selectionStart--;
7229                        }
7230                        while (selectionEnd < max &&
7231                                Character.isSpaceChar(mTransformed.charAt(selectionEnd))) {
7232                            selectionEnd++;
7233                        }
7234
7235                        Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
7236                        return;
7237                    }
7238                }
7239            }
7240
7241            // 'Smart' word selection: detect position at beginning or end of text.
7242            if (offset <= range) {
7243                Selection.setSelection((Spannable) mText, 0, 0);
7244                return;
7245            }
7246            if (offset >= (max - range)) {
7247                Selection.setSelection((Spannable) mText, max + 1, max + 1);
7248                return;
7249            }
7250        }
7251
7252        long wordLimits = getWordLimitsAt(minOffset);
7253        if (wordLimits >= 0) {
7254            selectionStart = (int) (wordLimits >>> 32);
7255        } else {
7256            selectionStart = Math.max(minOffset - 5, 0);
7257        }
7258
7259        wordLimits = getWordLimitsAt(maxOffset);
7260        if (wordLimits >= 0) {
7261            selectionEnd = (int) (wordLimits & 0x00000000FFFFFFFFL);
7262        } else {
7263            selectionEnd = Math.min(maxOffset + 5, mText.length());
7264        }
7265
7266        Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
7267    }
7268
7269    private String getWordForDictionary() {
7270        if (mLastTouchOffset < 0) {
7271            return null;
7272        }
7273
7274        long wordLimits = getWordLimitsAt(mLastTouchOffset);
7275        if (wordLimits >= 0) {
7276            int start = (int) (wordLimits >>> 32);
7277            int end = (int) (wordLimits & 0x00000000FFFFFFFFL);
7278            return mTransformed.subSequence(start, end).toString();
7279        } else {
7280            return null;
7281        }
7282    }
7283
7284    @Override
7285    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
7286        if (!isShown()) {
7287            return false;
7288        }
7289
7290        final boolean isPassword = isPasswordInputType(mInputType);
7291
7292        if (!isPassword) {
7293            CharSequence text = getText();
7294            if (TextUtils.isEmpty(text)) {
7295                text = getHint();
7296            }
7297            if (!TextUtils.isEmpty(text)) {
7298                if (text.length() > AccessibilityEvent.MAX_TEXT_LENGTH) {
7299                    text = text.subSequence(0, AccessibilityEvent.MAX_TEXT_LENGTH + 1);
7300                }
7301                event.getText().add(text);
7302            }
7303        } else {
7304            event.setPassword(isPassword);
7305        }
7306        return false;
7307    }
7308
7309    void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText,
7310            int fromIndex, int removedCount, int addedCount) {
7311        AccessibilityEvent event =
7312            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
7313        event.setFromIndex(fromIndex);
7314        event.setRemovedCount(removedCount);
7315        event.setAddedCount(addedCount);
7316        event.setBeforeText(beforeText);
7317        sendAccessibilityEventUnchecked(event);
7318    }
7319
7320    @Override
7321    protected void onCreateContextMenu(ContextMenu menu) {
7322        super.onCreateContextMenu(menu);
7323        boolean added = false;
7324
7325        if (mIsInTextSelectionMode) {
7326            MenuHandler handler = new MenuHandler();
7327
7328            if (canCut()) {
7329                menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut).
7330                     setOnMenuItemClickListener(handler).
7331                     setAlphabeticShortcut('x');
7332                added = true;
7333            }
7334
7335            if (canCopy()) {
7336                menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy).
7337                     setOnMenuItemClickListener(handler).
7338                     setAlphabeticShortcut('c');
7339                added = true;
7340            }
7341
7342            if (canPaste()) {
7343                menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste).
7344                     setOnMenuItemClickListener(handler).
7345                     setAlphabeticShortcut('v');
7346                added = true;
7347            }
7348        } else {
7349            /*
7350            if (!isFocused()) {
7351                if (isFocusable() && mInput != null) {
7352                    if (canCopy()) {
7353                        MenuHandler handler = new MenuHandler();
7354                        menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy).
7355                             setOnMenuItemClickListener(handler).
7356                             setAlphabeticShortcut('c');
7357                        menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle);
7358                    }
7359                }
7360
7361                //return;
7362            }
7363             */
7364            MenuHandler handler = new MenuHandler();
7365
7366            if (canSelectText()) {
7367                menu.add(0, ID_START_SELECTING_TEXT, 0, com.android.internal.R.string.selectText).
7368                setOnMenuItemClickListener(handler);
7369                added = true;
7370            }
7371
7372            if (canSelectAll()) {
7373                menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll).
7374                     setOnMenuItemClickListener(handler).
7375                     setAlphabeticShortcut('a');
7376                added = true;
7377            }
7378
7379            if (mText instanceof Spanned) {
7380                int selStart = getSelectionStart();
7381                int selEnd = getSelectionEnd();
7382
7383                int min = Math.min(selStart, selEnd);
7384                int max = Math.max(selStart, selEnd);
7385
7386                URLSpan[] urls = ((Spanned) mText).getSpans(min, max,
7387                        URLSpan.class);
7388                if (urls.length == 1) {
7389                    menu.add(0, ID_COPY_URL, 0, com.android.internal.R.string.copyUrl).
7390                         setOnMenuItemClickListener(handler);
7391                    added = true;
7392                }
7393            }
7394
7395            // Paste location is too imprecise. Only allow on empty text fields.
7396            if (canPaste() && textIsOnlySpaces()) {
7397                menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste).
7398                     setOnMenuItemClickListener(handler).
7399                     setAlphabeticShortcut('v');
7400                added = true;
7401            }
7402
7403            if (isInputMethodTarget()) {
7404                menu.add(1, ID_SWITCH_INPUT_METHOD, 0, com.android.internal.R.string.inputMethod).
7405                     setOnMenuItemClickListener(handler);
7406                added = true;
7407            }
7408
7409            String word = getWordForDictionary();
7410            if (word != null) {
7411                menu.add(1, ID_ADD_TO_DICTIONARY, 0,
7412                     getContext().getString(com.android.internal.R.string.addToDictionary, word)).
7413                     setOnMenuItemClickListener(handler);
7414                added = true;
7415
7416            }
7417        }
7418
7419        if (added) {
7420            menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle);
7421        }
7422    }
7423
7424    private boolean textIsOnlySpaces() {
7425        final int length = mTransformed.length();
7426        for (int i = 0; i < length; i++) {
7427            if (!Character.isSpaceChar(mTransformed.charAt(i))) {
7428                return false;
7429            }
7430        }
7431        return true;
7432    }
7433
7434    /**
7435     * Returns whether this text view is a current input method target.  The
7436     * default implementation just checks with {@link InputMethodManager}.
7437     */
7438    public boolean isInputMethodTarget() {
7439        InputMethodManager imm = InputMethodManager.peekInstance();
7440        return imm != null && imm.isActive(this);
7441    }
7442
7443    // Context menu entries
7444    private static final int ID_SELECT_ALL = android.R.id.selectAll;
7445    private static final int ID_START_SELECTING_TEXT = android.R.id.startSelectingText;
7446    private static final int ID_CUT = android.R.id.cut;
7447    private static final int ID_COPY = android.R.id.copy;
7448    private static final int ID_PASTE = android.R.id.paste;
7449    private static final int ID_COPY_URL = android.R.id.copyUrl;
7450    private static final int ID_SWITCH_INPUT_METHOD = android.R.id.switchInputMethod;
7451    private static final int ID_ADD_TO_DICTIONARY = android.R.id.addToDictionary;
7452
7453    private class MenuHandler implements MenuItem.OnMenuItemClickListener {
7454        public boolean onMenuItemClick(MenuItem item) {
7455            return onTextContextMenuItem(item.getItemId());
7456        }
7457    }
7458
7459    /**
7460     * Called when a context menu option for the text view is selected.  Currently
7461     * this will be one of: {@link android.R.id#selectAll},
7462     * {@link android.R.id#startSelectingText},
7463     * {@link android.R.id#cut}, {@link android.R.id#copy},
7464     * {@link android.R.id#paste}, {@link android.R.id#copyUrl},
7465     * or {@link android.R.id#switchInputMethod}.
7466     */
7467    public boolean onTextContextMenuItem(int id) {
7468        int min = 0;
7469        int max = mText.length();
7470
7471        if (isFocused()) {
7472            final int selStart = getSelectionStart();
7473            final int selEnd = getSelectionEnd();
7474
7475            min = Math.max(0, Math.min(selStart, selEnd));
7476            max = Math.max(0, Math.max(selStart, selEnd));
7477        }
7478
7479        ClipboardManager clip = (ClipboardManager)getContext()
7480                .getSystemService(Context.CLIPBOARD_SERVICE);
7481
7482        switch (id) {
7483            case ID_SELECT_ALL:
7484                Selection.setSelection((Spannable) mText, 0, mText.length());
7485                startTextSelectionMode();
7486                return true;
7487
7488            case ID_START_SELECTING_TEXT:
7489                startTextSelectionMode();
7490                return true;
7491
7492            case ID_CUT:
7493                clip.setText(mTransformed.subSequence(min, max));
7494                ((Editable) mText).delete(min, max);
7495                stopTextSelectionMode();
7496                return true;
7497
7498            case ID_COPY:
7499                clip.setText(mTransformed.subSequence(min, max));
7500                stopTextSelectionMode();
7501                return true;
7502
7503            case ID_PASTE:
7504                CharSequence paste = clip.getText();
7505
7506                if (paste != null && paste.length() > 0) {
7507                    // Paste adds/removes spaces before or after insertion as needed.
7508
7509                    if (Character.isSpaceChar(paste.charAt(0))) {
7510                        if (min > 0 && Character.isSpaceChar(mTransformed.charAt(min - 1))) {
7511                            // Two spaces at beginning of paste: remove one
7512                            ((Editable) mText).replace(min - 1, min, "");
7513                            min = min - 1;
7514                            max = max - 1;
7515                        }
7516                    } else {
7517                        if (min > 0 && !Character.isSpaceChar(mTransformed.charAt(min - 1))) {
7518                            // No space at beginning of paste: add one
7519                            ((Editable) mText).replace(min, min, " ");
7520                            min = min + 1;
7521                            max = max + 1;
7522                        }
7523                    }
7524
7525                    if (Character.isSpaceChar(paste.charAt(paste.length() - 1))) {
7526                        if (max < mText.length() && Character.isSpaceChar(mTransformed.charAt(max))) {
7527                            // Two spaces at end of paste: remove one
7528                            ((Editable) mText).replace(max, max + 1, "");
7529                        }
7530                    } else {
7531                        if (max < mText.length() && !Character.isSpaceChar(mTransformed.charAt(max))) {
7532                            // No space at end of paste: add one
7533                            ((Editable) mText).replace(max, max, " ");
7534                        }
7535                    }
7536
7537                    Selection.setSelection((Spannable) mText, max);
7538                    ((Editable) mText).replace(min, max, paste);
7539                    stopTextSelectionMode();
7540                }
7541                return true;
7542
7543            case ID_COPY_URL:
7544                URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class);
7545                if (urls.length == 1) {
7546                    clip.setText(urls[0].getURL());
7547                }
7548                return true;
7549
7550            case ID_SWITCH_INPUT_METHOD:
7551                InputMethodManager imm = InputMethodManager.peekInstance();
7552                if (imm != null) {
7553                    imm.showInputMethodPicker();
7554                }
7555                return true;
7556
7557            case ID_ADD_TO_DICTIONARY:
7558                String word = getWordForDictionary();
7559
7560                if (word != null) {
7561                    Intent i = new Intent("com.android.settings.USER_DICTIONARY_INSERT");
7562                    i.putExtra("word", word);
7563                    i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
7564                    getContext().startActivity(i);
7565                }
7566                return true;
7567            }
7568
7569        return false;
7570    }
7571
7572    @Override
7573    public boolean performLongClick() {
7574        if (super.performLongClick()) {
7575            mEatTouchRelease = true;
7576            return true;
7577        }
7578
7579        return false;
7580    }
7581
7582    private void startTextSelectionMode() {
7583        if (!mIsInTextSelectionMode) {
7584            if (mSelectionModifierCursorController == null) {
7585                Log.w(LOG_TAG, "TextView has no selection controller. Action mode cancelled.");
7586                return;
7587            }
7588
7589            if (!requestFocus()) {
7590                return;
7591            }
7592
7593            selectCurrentWord();
7594            mSelectionModifierCursorController.show();
7595            mIsInTextSelectionMode = true;
7596        }
7597    }
7598
7599    /**
7600     * Same as {@link #stopTextSelectionMode()}, except that there is no cursor controller
7601     * fade out animation. Needed since the drawable and their alpha values are shared by all
7602     * TextViews. Switching from one TextView to another would fade the cursor controllers in the
7603     * new one otherwise.
7604     */
7605    private void terminateTextSelectionMode() {
7606        stopTextSelectionMode();
7607        if (mSelectionModifierCursorController != null) {
7608            SelectionModifierCursorController selectionModifierCursorController =
7609                (SelectionModifierCursorController) mSelectionModifierCursorController;
7610            selectionModifierCursorController.cancelFadeOutAnimation();
7611        }
7612    }
7613
7614    private void stopTextSelectionMode() {
7615        if (mIsInTextSelectionMode) {
7616            Selection.setSelection((Spannable) mText, getSelectionEnd());
7617            if (mSelectionModifierCursorController != null) {
7618                mSelectionModifierCursorController.hide();
7619            }
7620
7621            mIsInTextSelectionMode = false;
7622        }
7623    }
7624
7625    /**
7626     * A CursorController instance can be used to control a cursor in the text.
7627     * It is not used outside of {@link TextView}.
7628     * @hide
7629     */
7630    private interface CursorController {
7631        /**
7632         * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}.
7633         * See also {@link #hide()}.
7634         */
7635        public void show();
7636
7637        /**
7638         * Hide the cursor controller from screen.
7639         * See also {@link #show()}.
7640         */
7641        public void hide();
7642
7643        /**
7644         * @return true if the CursorController is currently visible
7645         */
7646        public boolean isShowing();
7647
7648        /**
7649         * Update the controller's position.
7650         */
7651        public void updatePosition(HandleView handle, int x, int y);
7652
7653        public void updatePosition();
7654
7655        /**
7656         * This method is called by {@link #onTouchEvent(MotionEvent)} and gives the controller
7657         * a chance to become active and/or visible.
7658         * @param event The touch event
7659         */
7660        public boolean onTouchEvent(MotionEvent event);
7661    }
7662
7663    private class HandleView extends View {
7664        private boolean mPositionOnTop = false;
7665        private Drawable mDrawable;
7666        private PopupWindow mContainer;
7667        private int mPositionX;
7668        private int mPositionY;
7669        private CursorController mController;
7670        private boolean mIsDragging;
7671        private float mOffsetX;
7672        private float mOffsetY;
7673        private float mHotspotX;
7674        private float mHotspotY;
7675
7676        public HandleView(CursorController controller, Drawable handle) {
7677            super(TextView.this.mContext);
7678            mController = controller;
7679            mDrawable = handle;
7680            mContainer = new PopupWindow(TextView.this.mContext, null,
7681                    com.android.internal.R.attr.textSelectHandleWindowStyle);
7682            mContainer.setSplitTouchEnabled(true);
7683            mContainer.setClippingEnabled(false);
7684            mHotspotX = mDrawable.getIntrinsicWidth() * 0.5f;
7685            mHotspotY = -mDrawable.getIntrinsicHeight() * 0.2f;
7686        }
7687
7688        @Override
7689        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
7690            setMeasuredDimension(mDrawable.getIntrinsicWidth(),
7691                    mDrawable.getIntrinsicHeight());
7692        }
7693
7694        public void show() {
7695            if (!isPositionInBounds()) {
7696                hide();
7697                return;
7698            }
7699            mContainer.setContentView(this);
7700            final int[] coords = mTempCoords;
7701            TextView.this.getLocationInWindow(coords);
7702            coords[0] += mPositionX;
7703            coords[1] += mPositionY;
7704            mContainer.showAtLocation(TextView.this, 0, coords[0], coords[1]);
7705        }
7706
7707        public void hide() {
7708            mIsDragging = false;
7709            mContainer.dismiss();
7710        }
7711
7712        public boolean isShowing() {
7713            return mContainer.isShowing();
7714        }
7715
7716        private boolean isPositionInBounds() {
7717            final int extendedPaddingTop = getExtendedPaddingTop();
7718            final int extendedPaddingBottom = getExtendedPaddingBottom();
7719            final int compoundPaddingLeft = getCompoundPaddingLeft();
7720            final int compoundPaddingRight = getCompoundPaddingRight();
7721
7722            final TextView hostView = TextView.this;
7723            final int handleWidth = mDrawable.getIntrinsicWidth();
7724            final int left = 0;
7725            final int right = hostView.getWidth();
7726            final int top = 0;
7727            final int bottom = hostView.getHeight();
7728
7729            final int clipLeft = left + compoundPaddingLeft - (int) (handleWidth * 0.75f);
7730            final int clipTop = top + extendedPaddingTop;
7731            final int clipRight = right - compoundPaddingRight + (int) (handleWidth * 0.25f);
7732            final int clipBottom = bottom - extendedPaddingBottom;
7733
7734            return mPositionX >= clipLeft && mPositionX <= clipRight &&
7735                    mPositionY >= clipTop && mPositionY <= clipBottom;
7736        }
7737
7738        private void moveTo(int x, int y) {
7739            mPositionX = x - TextView.this.mScrollX;
7740            mPositionY = y - TextView.this.mScrollY;
7741            if (isPositionInBounds()) {
7742                if (mContainer.isShowing()){
7743                    final int[] coords = mTempCoords;
7744                    TextView.this.getLocationInWindow(coords);
7745                    coords[0] += mPositionX;
7746                    coords[1] += mPositionY;
7747                    mContainer.update(coords[0], coords[1], mRight - mLeft, mBottom - mTop);
7748                } else {
7749                    show();
7750                }
7751            } else {
7752                hide();
7753            }
7754        }
7755
7756        @Override
7757        public void onDraw(Canvas c) {
7758            mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
7759            if (mPositionOnTop) {
7760                c.save();
7761                c.rotate(180, (mRight - mLeft) / 2, (mBottom - mTop) / 2);
7762                mDrawable.draw(c);
7763                c.restore();
7764            } else {
7765                mDrawable.draw(c);
7766            }
7767        }
7768
7769        @Override
7770        public boolean onTouchEvent(MotionEvent ev) {
7771            switch (ev.getActionMasked()) {
7772            case MotionEvent.ACTION_DOWN: {
7773                final float rawX = ev.getRawX();
7774                final float rawY = ev.getRawY();
7775                mOffsetX = rawX - mPositionX;
7776                mOffsetY = rawY - mPositionY;
7777                mIsDragging = true;
7778                break;
7779            }
7780            case MotionEvent.ACTION_MOVE: {
7781                final float rawX = ev.getRawX();
7782                final float rawY = ev.getRawY();
7783                final float newPosX = rawX - mOffsetX + mHotspotX;
7784                final float newPosY = rawY - mOffsetY + mHotspotY;
7785
7786                mController.updatePosition(this, (int) Math.round(newPosX),
7787                        (int) Math.round(newPosY));
7788
7789                break;
7790            }
7791            case MotionEvent.ACTION_UP:
7792            case MotionEvent.ACTION_CANCEL:
7793                mIsDragging = false;
7794            }
7795            return true;
7796        }
7797
7798        public boolean isDragging() {
7799            return mIsDragging;
7800        }
7801
7802        void positionAtCursor(final int offset, boolean bottom) {
7803            final int width = mDrawable.getIntrinsicWidth();
7804            final int height = mDrawable.getIntrinsicHeight();
7805            final int line = mLayout.getLineForOffset(offset);
7806            final int lineTop = mLayout.getLineTop(line);
7807            final int lineBottom = mLayout.getLineBottom(line);
7808
7809            final Rect bounds = sCursorControllerTempRect;
7810            bounds.left = (int) (mLayout.getPrimaryHorizontal(offset) - width / 2.0)
7811                + TextView.this.mScrollX;
7812            bounds.top = (bottom ? lineBottom : lineTop) + TextView.this.mScrollY;
7813
7814            bounds.right = bounds.left + width;
7815            bounds.bottom = bounds.top + height;
7816
7817            convertFromViewportToContentCoordinates(bounds);
7818            moveTo(bounds.left, bounds.top);
7819        }
7820    }
7821
7822    private class InsertionPointCursorController implements CursorController {
7823        private static final int DELAY_BEFORE_FADE_OUT = 4100;
7824
7825        // The cursor controller image
7826        private final HandleView mHandle;
7827
7828        private final Runnable mHider = new Runnable() {
7829            public void run() {
7830                hide();
7831            }
7832        };
7833
7834        InsertionPointCursorController() {
7835            Resources res = mContext.getResources();
7836            mHandle = new HandleView(this, res.getDrawable(mTextSelectHandleRes));
7837        }
7838
7839        public void show() {
7840            updatePosition();
7841            mHandle.show();
7842            hideDelayed(DELAY_BEFORE_FADE_OUT);
7843        }
7844
7845        public void hide() {
7846            mHandle.hide();
7847            TextView.this.removeCallbacks(mHider);
7848        }
7849
7850        private void hideDelayed(int msec) {
7851            TextView.this.removeCallbacks(mHider);
7852            TextView.this.postDelayed(mHider, msec);
7853        }
7854
7855        public boolean isShowing() {
7856            return mHandle.isShowing();
7857        }
7858
7859        public void updatePosition(HandleView handle, int x, int y) {
7860            final int previousOffset = getSelectionStart();
7861            int offset = getHysteresisOffset(x, y, previousOffset);
7862
7863            if (offset != previousOffset) {
7864                Selection.setSelection((Spannable) mText, offset);
7865                updatePosition();
7866            }
7867            hideDelayed(DELAY_BEFORE_FADE_OUT);
7868        }
7869
7870        public void updatePosition() {
7871            final int offset = getSelectionStart();
7872
7873            if (offset < 0) {
7874                // Should never happen, safety check.
7875                Log.w(LOG_TAG, "Update cursor controller position called with no cursor");
7876                hide();
7877                return;
7878            }
7879
7880            mHandle.positionAtCursor(offset, true);
7881        }
7882
7883        public boolean onTouchEvent(MotionEvent ev) {
7884            return false;
7885        }
7886    }
7887
7888    private class SelectionModifierCursorController implements CursorController {
7889        // The cursor controller images
7890        private HandleView mStartHandle, mEndHandle;
7891        // The offsets of that last touch down event. Remembered to start selection there.
7892        private int mMinTouchOffset, mMaxTouchOffset;
7893        // Whether selection anchors are active
7894        private boolean mIsShowing;
7895
7896        SelectionModifierCursorController() {
7897            Resources res = mContext.getResources();
7898            mStartHandle = new HandleView(this, res.getDrawable(mTextSelectHandleLeftRes));
7899            mEndHandle = new HandleView(this, res.getDrawable(mTextSelectHandleRightRes));
7900        }
7901
7902        public void show() {
7903            mIsShowing = true;
7904            updatePosition();
7905            mStartHandle.show();
7906            mEndHandle.show();
7907            hideInsertionPointCursorController();
7908        }
7909
7910        public void hide() {
7911            mStartHandle.hide();
7912            mEndHandle.hide();
7913            mIsShowing = false;
7914        }
7915
7916        public boolean isShowing() {
7917            return mIsShowing;
7918        }
7919
7920        public void cancelFadeOutAnimation() {
7921            hide();
7922        }
7923
7924        public void updatePosition(HandleView handle, int x, int y) {
7925            int selectionStart = getSelectionStart();
7926            int selectionEnd = getSelectionEnd();
7927
7928            final int previousOffset = handle == mStartHandle ? selectionStart : selectionEnd;
7929            int offset = getHysteresisOffset(x, y, previousOffset);
7930
7931            // Handle the case where start and end are swapped, making sure start <= end
7932            if (handle == mStartHandle) {
7933                if (offset <= selectionEnd) {
7934                    if (selectionStart == offset) {
7935                        return; // no change, no need to redraw;
7936                    }
7937                    selectionStart = offset;
7938                } else {
7939                    selectionStart = selectionEnd;
7940                    selectionEnd = offset;
7941                    HandleView temp = mStartHandle;
7942                    mStartHandle = mEndHandle;
7943                    mEndHandle = temp;
7944                }
7945            } else {
7946                if (offset >= selectionStart) {
7947                    if (selectionEnd == offset) {
7948                        return; // no change, no need to redraw;
7949                    }
7950                    selectionEnd = offset;
7951                } else {
7952                    selectionEnd = selectionStart;
7953                    selectionStart = offset;
7954                    HandleView temp = mStartHandle;
7955                    mStartHandle = mEndHandle;
7956                    mEndHandle = temp;
7957                }
7958            }
7959
7960            Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
7961            updatePosition();
7962        }
7963
7964        public void updatePosition() {
7965            final int selectionStart = getSelectionStart();
7966            final int selectionEnd = getSelectionEnd();
7967
7968            if ((selectionStart < 0) || (selectionEnd < 0)) {
7969                // Should never happen, safety check.
7970                Log.w(LOG_TAG, "Update selection controller position called with no cursor");
7971                hide();
7972                return;
7973            }
7974
7975            boolean oneLineSelection = mLayout.getLineForOffset(selectionStart) ==
7976                    mLayout.getLineForOffset(selectionEnd);
7977            mStartHandle.positionAtCursor(selectionStart, oneLineSelection);
7978            mEndHandle.positionAtCursor(selectionEnd, true);
7979        }
7980
7981        public boolean onTouchEvent(MotionEvent event) {
7982            if (isFocused() && isTextEditable()) {
7983                switch (event.getActionMasked()) {
7984                    case MotionEvent.ACTION_DOWN:
7985                        final int x = (int) event.getX();
7986                        final int y = (int) event.getY();
7987
7988                        // Remember finger down position, to be able to start selection from there
7989                        mMinTouchOffset = mMaxTouchOffset = mLastTouchOffset = getOffset(x, y);
7990
7991                        break;
7992
7993                    case MotionEvent.ACTION_POINTER_DOWN:
7994                    case MotionEvent.ACTION_POINTER_UP:
7995                        // Handle multi-point gestures. Keep min and max offset positions.
7996                        // Only activated for devices that correctly handle multi-touch.
7997                        if (mContext.getPackageManager().hasSystemFeature(
7998                                PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
7999                            updateMinAndMaxOffsets(event);
8000                        }
8001                        break;
8002                }
8003            }
8004            return false;
8005        }
8006
8007        /**
8008         * @param event
8009         */
8010        private void updateMinAndMaxOffsets(MotionEvent event) {
8011            int pointerCount = event.getPointerCount();
8012            for (int index = 0; index < pointerCount; index++) {
8013                final int x = (int) event.getX(index);
8014                final int y = (int) event.getY(index);
8015                int offset = getOffset(x, y);
8016                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
8017                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
8018            }
8019        }
8020
8021        public int getMinTouchOffset() {
8022            return mMinTouchOffset;
8023        }
8024
8025        public int getMaxTouchOffset() {
8026            return mMaxTouchOffset;
8027        }
8028
8029        /**
8030         * @return true iff this controller is currently used to move the selection start.
8031         */
8032        public boolean isSelectionStartDragged() {
8033            return mStartHandle.isDragging();
8034        }
8035    }
8036
8037    private void hideInsertionPointCursorController() {
8038        if (mInsertionPointCursorController != null) {
8039            mInsertionPointCursorController.hide();
8040        }
8041    }
8042
8043    private void hideControllers() {
8044        hideInsertionPointCursorController();
8045        stopTextSelectionMode();
8046    }
8047
8048    private int getOffsetForHorizontal(int line, int x) {
8049        x -= getTotalPaddingLeft();
8050        // Clamp the position to inside of the view.
8051        x = Math.max(0, x);
8052        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
8053        x += getScrollX();
8054        return getLayout().getOffsetForHorizontal(line, x);
8055    }
8056
8057    /**
8058     * Get the offset character closest to the specified absolute position.
8059     *
8060     * @param x The horizontal absolute position of a point on screen
8061     * @param y The vertical absolute position of a point on screen
8062     * @return the character offset for the character whose position is closest to the specified
8063     *  position. Returns -1 if there is no layout.
8064     *
8065     * @hide
8066     */
8067    public int getOffset(int x, int y) {
8068        if (getLayout() == null) return -1;
8069
8070        y -= getTotalPaddingTop();
8071        // Clamp the position to inside of the view.
8072        y = Math.max(0, y);
8073        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
8074        y += getScrollY();
8075
8076        final int line = getLayout().getLineForVertical(y);
8077        final int offset = getOffsetForHorizontal(line, x);
8078        return offset;
8079    }
8080
8081    int getHysteresisOffset(int x, int y, int previousOffset) {
8082        final Layout layout = getLayout();
8083        if (layout == null) return -1;
8084
8085        y -= getTotalPaddingTop();
8086        // Clamp the position to inside of the view.
8087        y = Math.max(0, y);
8088        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
8089        y += getScrollY();
8090
8091        int line = getLayout().getLineForVertical(y);
8092
8093        final int previousLine = layout.getLineForOffset(previousOffset);
8094        final int previousLineTop = layout.getLineTop(previousLine);
8095        final int previousLineBottom = layout.getLineBottom(previousLine);
8096        final int hysteresisThreshold = (previousLineBottom - previousLineTop) / 6;
8097
8098        // If new line is just before or after previous line and y position is less than
8099        // hysteresisThreshold away from previous line, keep cursor on previous line.
8100        if (((line == previousLine + 1) && ((y - previousLineBottom) < hysteresisThreshold)) ||
8101            ((line == previousLine - 1) && ((previousLineTop - y)    < hysteresisThreshold))) {
8102            line = previousLine;
8103        }
8104
8105        return getOffsetForHorizontal(line, x);
8106    }
8107
8108    @ViewDebug.ExportedProperty
8109    private CharSequence            mText;
8110    private CharSequence            mTransformed;
8111    private BufferType              mBufferType = BufferType.NORMAL;
8112
8113    private int                     mInputType = EditorInfo.TYPE_NULL;
8114    private CharSequence            mHint;
8115    private Layout                  mHintLayout;
8116
8117    private KeyListener             mInput;
8118
8119    private MovementMethod          mMovement;
8120    private TransformationMethod    mTransformation;
8121    private ChangeWatcher           mChangeWatcher;
8122
8123    private ArrayList<TextWatcher>  mListeners = null;
8124
8125    // display attributes
8126    private final TextPaint         mTextPaint;
8127    private boolean                 mUserSetTextScaleX;
8128    private final Paint             mHighlightPaint;
8129    private int                     mHighlightColor = 0xCC475925;
8130    private Layout                  mLayout;
8131
8132    private long                    mShowCursor;
8133    private Blink                   mBlink;
8134    private boolean                 mCursorVisible = true;
8135
8136    // Cursor Controllers. Null when disabled.
8137    private CursorController        mInsertionPointCursorController;
8138    private CursorController        mSelectionModifierCursorController;
8139    private boolean                 mIsInTextSelectionMode = false;
8140    private int                     mLastTouchOffset = -1;
8141    // Created once and shared by different CursorController helper methods.
8142    // Only one cursor controller is active at any time which prevent race conditions.
8143    private static Rect             sCursorControllerTempRect = new Rect();
8144
8145    private boolean                 mSelectAllOnFocus = false;
8146
8147    private int                     mGravity = Gravity.TOP | Gravity.LEFT;
8148    private boolean                 mHorizontallyScrolling;
8149
8150    private int                     mAutoLinkMask;
8151    private boolean                 mLinksClickable = true;
8152
8153    private float                   mSpacingMult = 1;
8154    private float                   mSpacingAdd = 0;
8155
8156    private static final int        LINES = 1;
8157    private static final int        EMS = LINES;
8158    private static final int        PIXELS = 2;
8159
8160    private int                     mMaximum = Integer.MAX_VALUE;
8161    private int                     mMaxMode = LINES;
8162    private int                     mMinimum = 0;
8163    private int                     mMinMode = LINES;
8164
8165    private int                     mMaxWidth = Integer.MAX_VALUE;
8166    private int                     mMaxWidthMode = PIXELS;
8167    private int                     mMinWidth = 0;
8168    private int                     mMinWidthMode = PIXELS;
8169
8170    private boolean                 mSingleLine;
8171    private int                     mDesiredHeightAtMeasure = -1;
8172    private boolean                 mIncludePad = true;
8173
8174    // tmp primitives, so we don't alloc them on each draw
8175    private Path                    mHighlightPath;
8176    private boolean                 mHighlightPathBogus = true;
8177    private static final RectF      sTempRect = new RectF();
8178
8179    // XXX should be much larger
8180    private static final int        VERY_WIDE = 16384;
8181
8182    private static final int        BLINK = 500;
8183
8184    private static final int ANIMATED_SCROLL_GAP = 250;
8185    private long mLastScroll;
8186    private Scroller mScroller = null;
8187
8188    private BoringLayout.Metrics mBoring;
8189    private BoringLayout.Metrics mHintBoring;
8190
8191    private BoringLayout mSavedLayout, mSavedHintLayout;
8192
8193    private static final InputFilter[] NO_FILTERS = new InputFilter[0];
8194    private InputFilter[] mFilters = NO_FILTERS;
8195    private static final Spanned EMPTY_SPANNED = new SpannedString("");
8196}
8197