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