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