TextView.java revision baaace59f68eb7baf6d6526b6678de6cb6de6543
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                    // Adjust offsets to ensure we contain full spans.
4608                    if (content instanceof Spanned) {
4609                        Spanned spanned = (Spanned)content;
4610                        Object[] spans = spanned.getSpans(partialStartOffset,
4611                                partialEndOffset, ParcelableSpan.class);
4612                        int i = spans.length;
4613                        while (i > 0) {
4614                            i--;
4615                            int j = spanned.getSpanStart(spans[i]);
4616                            if (j < partialStartOffset) partialStartOffset = j;
4617                            j = spanned.getSpanEnd(spans[i]);
4618                            if (j > partialEndOffset) partialEndOffset = j;
4619                        }
4620                    }
4621                    outText.partialStartOffset = partialStartOffset;
4622                    outText.partialEndOffset = partialEndOffset;
4623                    // Now use the delta to determine the actual amount of text
4624                    // we need.
4625                    partialEndOffset += delta;
4626                    if (partialStartOffset > N) {
4627                        partialStartOffset = N;
4628                    } else if (partialStartOffset < 0) {
4629                        partialStartOffset = 0;
4630                    }
4631                    if (partialEndOffset > N) {
4632                        partialEndOffset = N;
4633                    } else if (partialEndOffset < 0) {
4634                        partialEndOffset = 0;
4635                    }
4636                }
4637                if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) {
4638                    outText.text = content.subSequence(partialStartOffset,
4639                            partialEndOffset);
4640                } else {
4641                    outText.text = TextUtils.substring(content, partialStartOffset,
4642                            partialEndOffset);
4643                }
4644            } else {
4645                outText.partialStartOffset = 0;
4646                outText.partialEndOffset = 0;
4647                outText.text = "";
4648            }
4649            outText.flags = 0;
4650            if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) {
4651                outText.flags |= ExtractedText.FLAG_SELECTING;
4652            }
4653            if (mSingleLine) {
4654                outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
4655            }
4656            outText.startOffset = 0;
4657            outText.selectionStart = getSelectionStart();
4658            outText.selectionEnd = getSelectionEnd();
4659            return true;
4660        }
4661        return false;
4662    }
4663
4664    boolean reportExtractedText() {
4665        final InputMethodState ims = mInputMethodState;
4666        if (ims != null) {
4667            final boolean contentChanged = ims.mContentChanged;
4668            if (contentChanged || ims.mSelectionModeChanged) {
4669                ims.mContentChanged = false;
4670                ims.mSelectionModeChanged = false;
4671                final ExtractedTextRequest req = mInputMethodState.mExtracting;
4672                if (req != null) {
4673                    InputMethodManager imm = InputMethodManager.peekInstance();
4674                    if (imm != null) {
4675                        if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start="
4676                                + ims.mChangedStart + " end=" + ims.mChangedEnd
4677                                + " delta=" + ims.mChangedDelta);
4678                        if (ims.mChangedStart < 0 && !contentChanged) {
4679                            ims.mChangedStart = EXTRACT_NOTHING;
4680                        }
4681                        if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd,
4682                                ims.mChangedDelta, ims.mTmpExtracted)) {
4683                            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start="
4684                                    + ims.mTmpExtracted.partialStartOffset
4685                                    + " end=" + ims.mTmpExtracted.partialEndOffset
4686                                    + ": " + ims.mTmpExtracted.text);
4687                            imm.updateExtractedText(this, req.token,
4688                                    mInputMethodState.mTmpExtracted);
4689                            return true;
4690                        }
4691                    }
4692                }
4693            }
4694        }
4695        return false;
4696    }
4697
4698    /**
4699     * This is used to remove all style-impacting spans from text before new
4700     * extracted text is being replaced into it, so that we don't have any
4701     * lingering spans applied during the replace.
4702     */
4703    static void removeParcelableSpans(Spannable spannable, int start, int end) {
4704        Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class);
4705        int i = spans.length;
4706        while (i > 0) {
4707            i--;
4708            spannable.removeSpan(spans[i]);
4709        }
4710    }
4711
4712    /**
4713     * Apply to this text view the given extracted text, as previously
4714     * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}.
4715     */
4716    public void setExtractedText(ExtractedText text) {
4717        Editable content = getEditableText();
4718        if (text.text != null) {
4719            if (content == null) {
4720                setText(text.text, TextView.BufferType.EDITABLE);
4721            } else if (text.partialStartOffset < 0) {
4722                removeParcelableSpans(content, 0, content.length());
4723                content.replace(0, content.length(), text.text);
4724            } else {
4725                final int N = content.length();
4726                int start = text.partialStartOffset;
4727                if (start > N) start = N;
4728                int end = text.partialEndOffset;
4729                if (end > N) end = N;
4730                removeParcelableSpans(content, start, end);
4731                content.replace(start, end, text.text);
4732            }
4733        }
4734
4735        // Now set the selection position...  make sure it is in range, to
4736        // avoid crashes.  If this is a partial update, it is possible that
4737        // the underlying text may have changed, causing us problems here.
4738        // Also we just don't want to trust clients to do the right thing.
4739        Spannable sp = (Spannable)getText();
4740        final int N = sp.length();
4741        int start = text.selectionStart;
4742        if (start < 0) start = 0;
4743        else if (start > N) start = N;
4744        int end = text.selectionEnd;
4745        if (end < 0) end = 0;
4746        else if (end > N) end = N;
4747        Selection.setSelection(sp, start, end);
4748
4749        // Finally, update the selection mode.
4750        if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) {
4751            MetaKeyKeyListener.startSelecting(this, sp);
4752        } else {
4753            MetaKeyKeyListener.stopSelecting(this, sp);
4754        }
4755    }
4756
4757    /**
4758     * @hide
4759     */
4760    public void setExtracting(ExtractedTextRequest req) {
4761        if (mInputMethodState != null) {
4762            mInputMethodState.mExtracting = req;
4763        }
4764        hideControllers();
4765    }
4766
4767    /**
4768     * Called by the framework in response to a text completion from
4769     * the current input method, provided by it calling
4770     * {@link InputConnection#commitCompletion
4771     * InputConnection.commitCompletion()}.  The default implementation does
4772     * nothing; text views that are supporting auto-completion should override
4773     * this to do their desired behavior.
4774     *
4775     * @param text The auto complete text the user has selected.
4776     */
4777    public void onCommitCompletion(CompletionInfo text) {
4778    }
4779
4780    public void beginBatchEdit() {
4781        final InputMethodState ims = mInputMethodState;
4782        if (ims != null) {
4783            int nesting = ++ims.mBatchEditNesting;
4784            if (nesting == 1) {
4785                ims.mCursorChanged = false;
4786                ims.mChangedDelta = 0;
4787                if (ims.mContentChanged) {
4788                    // We already have a pending change from somewhere else,
4789                    // so turn this into a full update.
4790                    ims.mChangedStart = 0;
4791                    ims.mChangedEnd = mText.length();
4792                } else {
4793                    ims.mChangedStart = EXTRACT_UNKNOWN;
4794                    ims.mChangedEnd = EXTRACT_UNKNOWN;
4795                    ims.mContentChanged = false;
4796                }
4797                onBeginBatchEdit();
4798            }
4799        }
4800    }
4801
4802    public void endBatchEdit() {
4803        final InputMethodState ims = mInputMethodState;
4804        if (ims != null) {
4805            int nesting = --ims.mBatchEditNesting;
4806            if (nesting == 0) {
4807                finishBatchEdit(ims);
4808            }
4809        }
4810    }
4811
4812    void ensureEndedBatchEdit() {
4813        final InputMethodState ims = mInputMethodState;
4814        if (ims != null && ims.mBatchEditNesting != 0) {
4815            ims.mBatchEditNesting = 0;
4816            finishBatchEdit(ims);
4817        }
4818    }
4819
4820    void finishBatchEdit(final InputMethodState ims) {
4821        onEndBatchEdit();
4822
4823        if (ims.mContentChanged || ims.mSelectionModeChanged) {
4824            updateAfterEdit();
4825            reportExtractedText();
4826        } else if (ims.mCursorChanged) {
4827            // Cheezy way to get us to report the current cursor location.
4828            invalidateCursor();
4829        }
4830    }
4831
4832    void updateAfterEdit() {
4833        invalidate();
4834        int curs = getSelectionStart();
4835
4836        if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) ==
4837                             Gravity.BOTTOM) {
4838            registerForPreDraw();
4839        }
4840
4841        if (curs >= 0) {
4842            mHighlightPathBogus = true;
4843
4844            if (isFocused()) {
4845                mShowCursor = SystemClock.uptimeMillis();
4846                makeBlink();
4847            }
4848        }
4849
4850        checkForResize();
4851    }
4852
4853    /**
4854     * Called by the framework in response to a request to begin a batch
4855     * of edit operations through a call to link {@link #beginBatchEdit()}.
4856     */
4857    public void onBeginBatchEdit() {
4858    }
4859
4860    /**
4861     * Called by the framework in response to a request to end a batch
4862     * of edit operations through a call to link {@link #endBatchEdit}.
4863     */
4864    public void onEndBatchEdit() {
4865    }
4866
4867    /**
4868     * Called by the framework in response to a private command from the
4869     * current method, provided by it calling
4870     * {@link InputConnection#performPrivateCommand
4871     * InputConnection.performPrivateCommand()}.
4872     *
4873     * @param action The action name of the command.
4874     * @param data Any additional data for the command.  This may be null.
4875     * @return Return true if you handled the command, else false.
4876     */
4877    public boolean onPrivateIMECommand(String action, Bundle data) {
4878        return false;
4879    }
4880
4881    private void nullLayouts() {
4882        if (mLayout instanceof BoringLayout && mSavedLayout == null) {
4883            mSavedLayout = (BoringLayout) mLayout;
4884        }
4885        if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) {
4886            mSavedHintLayout = (BoringLayout) mHintLayout;
4887        }
4888
4889        mLayout = mHintLayout = null;
4890    }
4891
4892    /**
4893     * Make a new Layout based on the already-measured size of the view,
4894     * on the assumption that it was measured correctly at some point.
4895     */
4896    private void assumeLayout() {
4897        int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
4898
4899        if (width < 1) {
4900            width = 0;
4901        }
4902
4903        int physicalWidth = width;
4904
4905        if (mHorizontallyScrolling) {
4906            width = VERY_WIDE;
4907        }
4908
4909        makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING,
4910                      physicalWidth, false);
4911    }
4912
4913    /**
4914     * The width passed in is now the desired layout width,
4915     * not the full view width with padding.
4916     * {@hide}
4917     */
4918    protected void makeNewLayout(int w, int hintWidth,
4919                                 BoringLayout.Metrics boring,
4920                                 BoringLayout.Metrics hintBoring,
4921                                 int ellipsisWidth, boolean bringIntoView) {
4922        stopMarquee();
4923
4924        mHighlightPathBogus = true;
4925
4926        if (w < 0) {
4927            w = 0;
4928        }
4929        if (hintWidth < 0) {
4930            hintWidth = 0;
4931        }
4932
4933        Layout.Alignment alignment;
4934        switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
4935            case Gravity.CENTER_HORIZONTAL:
4936                alignment = Layout.Alignment.ALIGN_CENTER;
4937                break;
4938
4939            case Gravity.RIGHT:
4940                alignment = Layout.Alignment.ALIGN_OPPOSITE;
4941                break;
4942
4943            default:
4944                alignment = Layout.Alignment.ALIGN_NORMAL;
4945        }
4946
4947        boolean shouldEllipsize = mEllipsize != null && mInput == null;
4948
4949        if (mText instanceof Spannable) {
4950            mLayout = new DynamicLayout(mText, mTransformed, mTextPaint, w,
4951                    alignment, mSpacingMult,
4952                    mSpacingAdd, mIncludePad, mInput == null ? mEllipsize : null,
4953                    ellipsisWidth);
4954        } else {
4955            if (boring == UNKNOWN_BORING) {
4956                boring = BoringLayout.isBoring(mTransformed, mTextPaint,
4957                                               mBoring);
4958                if (boring != null) {
4959                    mBoring = boring;
4960                }
4961            }
4962
4963            if (boring != null) {
4964                if (boring.width <= w &&
4965                    (mEllipsize == null || boring.width <= ellipsisWidth)) {
4966                    if (mSavedLayout != null) {
4967                        mLayout = mSavedLayout.
4968                                replaceOrMake(mTransformed, mTextPaint,
4969                                w, alignment, mSpacingMult, mSpacingAdd,
4970                                boring, mIncludePad);
4971                    } else {
4972                        mLayout = BoringLayout.make(mTransformed, mTextPaint,
4973                                w, alignment, mSpacingMult, mSpacingAdd,
4974                                boring, mIncludePad);
4975                    }
4976
4977                    mSavedLayout = (BoringLayout) mLayout;
4978                } else if (shouldEllipsize && boring.width <= w) {
4979                    if (mSavedLayout != null) {
4980                        mLayout = mSavedLayout.
4981                                replaceOrMake(mTransformed, mTextPaint,
4982                                w, alignment, mSpacingMult, mSpacingAdd,
4983                                boring, mIncludePad, mEllipsize,
4984                                ellipsisWidth);
4985                    } else {
4986                        mLayout = BoringLayout.make(mTransformed, mTextPaint,
4987                                w, alignment, mSpacingMult, mSpacingAdd,
4988                                boring, mIncludePad, mEllipsize,
4989                                ellipsisWidth);
4990                    }
4991                } else if (shouldEllipsize) {
4992                    mLayout = new StaticLayout(mTransformed,
4993                                0, mTransformed.length(),
4994                                mTextPaint, w, alignment, mSpacingMult,
4995                                mSpacingAdd, mIncludePad, mEllipsize,
4996                                ellipsisWidth);
4997                } else {
4998                    mLayout = new StaticLayout(mTransformed, mTextPaint,
4999                            w, alignment, mSpacingMult, mSpacingAdd,
5000                            mIncludePad);
5001                }
5002            } else if (shouldEllipsize) {
5003                mLayout = new StaticLayout(mTransformed,
5004                            0, mTransformed.length(),
5005                            mTextPaint, w, alignment, mSpacingMult,
5006                            mSpacingAdd, mIncludePad, mEllipsize,
5007                            ellipsisWidth);
5008            } else {
5009                mLayout = new StaticLayout(mTransformed, mTextPaint,
5010                        w, alignment, mSpacingMult, mSpacingAdd,
5011                        mIncludePad);
5012            }
5013        }
5014
5015        shouldEllipsize = mEllipsize != null;
5016        mHintLayout = null;
5017
5018        if (mHint != null) {
5019            if (shouldEllipsize) hintWidth = w;
5020
5021            if (hintBoring == UNKNOWN_BORING) {
5022                hintBoring = BoringLayout.isBoring(mHint, mTextPaint,
5023                                                   mHintBoring);
5024                if (hintBoring != null) {
5025                    mHintBoring = hintBoring;
5026                }
5027            }
5028
5029            if (hintBoring != null) {
5030                if (hintBoring.width <= hintWidth &&
5031                    (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) {
5032                    if (mSavedHintLayout != null) {
5033                        mHintLayout = mSavedHintLayout.
5034                                replaceOrMake(mHint, mTextPaint,
5035                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5036                                hintBoring, mIncludePad);
5037                    } else {
5038                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5039                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5040                                hintBoring, mIncludePad);
5041                    }
5042
5043                    mSavedHintLayout = (BoringLayout) mHintLayout;
5044                } else if (shouldEllipsize && hintBoring.width <= hintWidth) {
5045                    if (mSavedHintLayout != null) {
5046                        mHintLayout = mSavedHintLayout.
5047                                replaceOrMake(mHint, mTextPaint,
5048                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5049                                hintBoring, mIncludePad, mEllipsize,
5050                                ellipsisWidth);
5051                    } else {
5052                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5053                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5054                                hintBoring, mIncludePad, mEllipsize,
5055                                ellipsisWidth);
5056                    }
5057                } else if (shouldEllipsize) {
5058                    mHintLayout = new StaticLayout(mHint,
5059                                0, mHint.length(),
5060                                mTextPaint, hintWidth, alignment, mSpacingMult,
5061                                mSpacingAdd, mIncludePad, mEllipsize,
5062                                ellipsisWidth);
5063                } else {
5064                    mHintLayout = new StaticLayout(mHint, mTextPaint,
5065                            hintWidth, alignment, mSpacingMult, mSpacingAdd,
5066                            mIncludePad);
5067                }
5068            } else if (shouldEllipsize) {
5069                mHintLayout = new StaticLayout(mHint,
5070                            0, mHint.length(),
5071                            mTextPaint, hintWidth, alignment, mSpacingMult,
5072                            mSpacingAdd, mIncludePad, mEllipsize,
5073                            ellipsisWidth);
5074            } else {
5075                mHintLayout = new StaticLayout(mHint, mTextPaint,
5076                        hintWidth, alignment, mSpacingMult, mSpacingAdd,
5077                        mIncludePad);
5078            }
5079        }
5080
5081        if (bringIntoView) {
5082            registerForPreDraw();
5083        }
5084
5085        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
5086            if (!compressText(ellipsisWidth)) {
5087                final int height = mLayoutParams.height;
5088                // If the size of the view does not depend on the size of the text, try to
5089                // start the marquee immediately
5090                if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) {
5091                    startMarquee();
5092                } else {
5093                    // Defer the start of the marquee until we know our width (see setFrame())
5094                    mRestartMarquee = true;
5095                }
5096            }
5097        }
5098
5099        // CursorControllers need a non-null mLayout
5100        prepareCursorControllers();
5101    }
5102
5103    private boolean compressText(float width) {
5104        // Only compress the text if it hasn't been compressed by the previous pass
5105        if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX &&
5106                mTextPaint.getTextScaleX() == 1.0f) {
5107            final float textWidth = mLayout.getLineWidth(0);
5108            final float overflow = (textWidth + 1.0f - width) / width;
5109            if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) {
5110                mTextPaint.setTextScaleX(1.0f - overflow - 0.005f);
5111                post(new Runnable() {
5112                    public void run() {
5113                        requestLayout();
5114                    }
5115                });
5116                return true;
5117            }
5118        }
5119
5120        return false;
5121    }
5122
5123    private static int desired(Layout layout) {
5124        int n = layout.getLineCount();
5125        CharSequence text = layout.getText();
5126        float max = 0;
5127
5128        // if any line was wrapped, we can't use it.
5129        // but it's ok for the last line not to have a newline
5130
5131        for (int i = 0; i < n - 1; i++) {
5132            if (text.charAt(layout.getLineEnd(i) - 1) != '\n')
5133                return -1;
5134        }
5135
5136        for (int i = 0; i < n; i++) {
5137            max = Math.max(max, layout.getLineWidth(i));
5138        }
5139
5140        return (int) FloatMath.ceil(max);
5141    }
5142
5143    /**
5144     * Set whether the TextView includes extra top and bottom padding to make
5145     * room for accents that go above the normal ascent and descent.
5146     * The default is true.
5147     *
5148     * @attr ref android.R.styleable#TextView_includeFontPadding
5149     */
5150    public void setIncludeFontPadding(boolean includepad) {
5151        mIncludePad = includepad;
5152
5153        if (mLayout != null) {
5154            nullLayouts();
5155            requestLayout();
5156            invalidate();
5157        }
5158    }
5159
5160    private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics();
5161
5162    @Override
5163    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
5164        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
5165        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
5166        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
5167        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
5168
5169        int width;
5170        int height;
5171
5172        BoringLayout.Metrics boring = UNKNOWN_BORING;
5173        BoringLayout.Metrics hintBoring = UNKNOWN_BORING;
5174
5175        int des = -1;
5176        boolean fromexisting = false;
5177
5178        if (widthMode == MeasureSpec.EXACTLY) {
5179            // Parent has told us how big to be. So be it.
5180            width = widthSize;
5181        } else {
5182            if (mLayout != null && mEllipsize == null) {
5183                des = desired(mLayout);
5184            }
5185
5186            if (des < 0) {
5187                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mBoring);
5188                if (boring != null) {
5189                    mBoring = boring;
5190                }
5191            } else {
5192                fromexisting = true;
5193            }
5194
5195            if (boring == null || boring == UNKNOWN_BORING) {
5196                if (des < 0) {
5197                    des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint));
5198                }
5199
5200                width = des;
5201            } else {
5202                width = boring.width;
5203            }
5204
5205            final Drawables dr = mDrawables;
5206            if (dr != null) {
5207                width = Math.max(width, dr.mDrawableWidthTop);
5208                width = Math.max(width, dr.mDrawableWidthBottom);
5209            }
5210
5211            if (mHint != null) {
5212                int hintDes = -1;
5213                int hintWidth;
5214
5215                if (mHintLayout != null && mEllipsize == null) {
5216                    hintDes = desired(mHintLayout);
5217                }
5218
5219                if (hintDes < 0) {
5220                    hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring);
5221                    if (hintBoring != null) {
5222                        mHintBoring = hintBoring;
5223                    }
5224                }
5225
5226                if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
5227                    if (hintDes < 0) {
5228                        hintDes = (int) FloatMath.ceil(
5229                                Layout.getDesiredWidth(mHint, mTextPaint));
5230                    }
5231
5232                    hintWidth = hintDes;
5233                } else {
5234                    hintWidth = hintBoring.width;
5235                }
5236
5237                if (hintWidth > width) {
5238                    width = hintWidth;
5239                }
5240            }
5241
5242            width += getCompoundPaddingLeft() + getCompoundPaddingRight();
5243
5244            if (mMaxWidthMode == EMS) {
5245                width = Math.min(width, mMaxWidth * getLineHeight());
5246            } else {
5247                width = Math.min(width, mMaxWidth);
5248            }
5249
5250            if (mMinWidthMode == EMS) {
5251                width = Math.max(width, mMinWidth * getLineHeight());
5252            } else {
5253                width = Math.max(width, mMinWidth);
5254            }
5255
5256            // Check against our minimum width
5257            width = Math.max(width, getSuggestedMinimumWidth());
5258
5259            if (widthMode == MeasureSpec.AT_MOST) {
5260                width = Math.min(widthSize, width);
5261            }
5262        }
5263
5264        int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight();
5265        int unpaddedWidth = want;
5266        int hintWant = want;
5267
5268        if (mHorizontallyScrolling)
5269            want = VERY_WIDE;
5270
5271        int hintWidth = mHintLayout == null ? hintWant : mHintLayout.getWidth();
5272
5273        if (mLayout == null) {
5274            makeNewLayout(want, hintWant, boring, hintBoring,
5275                          width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
5276        } else if ((mLayout.getWidth() != want) || (hintWidth != hintWant) ||
5277                   (mLayout.getEllipsizedWidth() !=
5278                        width - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
5279            if (mHint == null && mEllipsize == null &&
5280                    want > mLayout.getWidth() &&
5281                    (mLayout instanceof BoringLayout ||
5282                            (fromexisting && des >= 0 && des <= want))) {
5283                mLayout.increaseWidthTo(want);
5284            } else {
5285                makeNewLayout(want, hintWant, boring, hintBoring,
5286                              width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
5287            }
5288        } else {
5289            // Width has not changed.
5290        }
5291
5292        if (heightMode == MeasureSpec.EXACTLY) {
5293            // Parent has told us how big to be. So be it.
5294            height = heightSize;
5295            mDesiredHeightAtMeasure = -1;
5296        } else {
5297            int desired = getDesiredHeight();
5298
5299            height = desired;
5300            mDesiredHeightAtMeasure = desired;
5301
5302            if (heightMode == MeasureSpec.AT_MOST) {
5303                height = Math.min(desired, heightSize);
5304            }
5305        }
5306
5307        int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
5308        if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) {
5309            unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum));
5310        }
5311
5312        /*
5313         * We didn't let makeNewLayout() register to bring the cursor into view,
5314         * so do it here if there is any possibility that it is needed.
5315         */
5316        if (mMovement != null ||
5317            mLayout.getWidth() > unpaddedWidth ||
5318            mLayout.getHeight() > unpaddedHeight) {
5319            registerForPreDraw();
5320        } else {
5321            scrollTo(0, 0);
5322        }
5323
5324        setMeasuredDimension(width, height);
5325    }
5326
5327    private int getDesiredHeight() {
5328        return Math.max(
5329                getDesiredHeight(mLayout, true),
5330                getDesiredHeight(mHintLayout, mEllipsize != null));
5331    }
5332
5333    private int getDesiredHeight(Layout layout, boolean cap) {
5334        if (layout == null) {
5335            return 0;
5336        }
5337
5338        int linecount = layout.getLineCount();
5339        int pad = getCompoundPaddingTop() + getCompoundPaddingBottom();
5340        int desired = layout.getLineTop(linecount);
5341
5342        final Drawables dr = mDrawables;
5343        if (dr != null) {
5344            desired = Math.max(desired, dr.mDrawableHeightLeft);
5345            desired = Math.max(desired, dr.mDrawableHeightRight);
5346        }
5347
5348        desired += pad;
5349
5350        if (mMaxMode == LINES) {
5351            /*
5352             * Don't cap the hint to a certain number of lines.
5353             * (Do cap it, though, if we have a maximum pixel height.)
5354             */
5355            if (cap) {
5356                if (linecount > mMaximum) {
5357                    desired = layout.getLineTop(mMaximum) +
5358                              layout.getBottomPadding();
5359
5360                    if (dr != null) {
5361                        desired = Math.max(desired, dr.mDrawableHeightLeft);
5362                        desired = Math.max(desired, dr.mDrawableHeightRight);
5363                    }
5364
5365                    desired += pad;
5366                    linecount = mMaximum;
5367                }
5368            }
5369        } else {
5370            desired = Math.min(desired, mMaximum);
5371        }
5372
5373        if (mMinMode == LINES) {
5374            if (linecount < mMinimum) {
5375                desired += getLineHeight() * (mMinimum - linecount);
5376            }
5377        } else {
5378            desired = Math.max(desired, mMinimum);
5379        }
5380
5381        // Check against our minimum height
5382        desired = Math.max(desired, getSuggestedMinimumHeight());
5383
5384        return desired;
5385    }
5386
5387    /**
5388     * Check whether a change to the existing text layout requires a
5389     * new view layout.
5390     */
5391    private void checkForResize() {
5392        boolean sizeChanged = false;
5393
5394        if (mLayout != null) {
5395            // Check if our width changed
5396            if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) {
5397                sizeChanged = true;
5398                invalidate();
5399            }
5400
5401            // Check if our height changed
5402            if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) {
5403                int desiredHeight = getDesiredHeight();
5404
5405                if (desiredHeight != this.getHeight()) {
5406                    sizeChanged = true;
5407                }
5408            } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) {
5409                if (mDesiredHeightAtMeasure >= 0) {
5410                    int desiredHeight = getDesiredHeight();
5411
5412                    if (desiredHeight != mDesiredHeightAtMeasure) {
5413                        sizeChanged = true;
5414                    }
5415                }
5416            }
5417        }
5418
5419        if (sizeChanged) {
5420            requestLayout();
5421            // caller will have already invalidated
5422        }
5423    }
5424
5425    /**
5426     * Check whether entirely new text requires a new view layout
5427     * or merely a new text layout.
5428     */
5429    private void checkForRelayout() {
5430        // If we have a fixed width, we can just swap in a new text layout
5431        // if the text height stays the same or if the view height is fixed.
5432
5433        if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT ||
5434                (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) &&
5435                (mHint == null || mHintLayout != null) &&
5436                (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) {
5437            // Static width, so try making a new text layout.
5438
5439            int oldht = mLayout.getHeight();
5440            int want = mLayout.getWidth();
5441            int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();
5442
5443            /*
5444             * No need to bring the text into view, since the size is not
5445             * changing (unless we do the requestLayout(), in which case it
5446             * will happen at measure).
5447             */
5448            makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
5449                          mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(),
5450                          false);
5451
5452            if (mEllipsize != TextUtils.TruncateAt.MARQUEE) {
5453                // In a fixed-height view, so use our new text layout.
5454                if (mLayoutParams.height != LayoutParams.WRAP_CONTENT &&
5455                    mLayoutParams.height != LayoutParams.MATCH_PARENT) {
5456                    invalidate();
5457                    return;
5458                }
5459
5460                // Dynamic height, but height has stayed the same,
5461                // so use our new text layout.
5462                if (mLayout.getHeight() == oldht &&
5463                    (mHintLayout == null || mHintLayout.getHeight() == oldht)) {
5464                    invalidate();
5465                    return;
5466                }
5467            }
5468
5469            // We lose: the height has changed and we have a dynamic height.
5470            // Request a new view layout using our new text layout.
5471            requestLayout();
5472            invalidate();
5473        } else {
5474            // Dynamic width, so we have no choice but to request a new
5475            // view layout with a new text layout.
5476
5477            nullLayouts();
5478            requestLayout();
5479            invalidate();
5480        }
5481    }
5482
5483    /**
5484     * Returns true if anything changed.
5485     */
5486    private boolean bringTextIntoView() {
5487        int line = 0;
5488        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
5489            line = mLayout.getLineCount() - 1;
5490        }
5491
5492        Layout.Alignment a = mLayout.getParagraphAlignment(line);
5493        int dir = mLayout.getParagraphDirection(line);
5494        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5495        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
5496        int ht = mLayout.getHeight();
5497
5498        int scrollx, scrolly;
5499
5500        if (a == Layout.Alignment.ALIGN_CENTER) {
5501            /*
5502             * Keep centered if possible, or, if it is too wide to fit,
5503             * keep leading edge in view.
5504             */
5505
5506            int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
5507            int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
5508
5509            if (right - left < hspace) {
5510                scrollx = (right + left) / 2 - hspace / 2;
5511            } else {
5512                if (dir < 0) {
5513                    scrollx = right - hspace;
5514                } else {
5515                    scrollx = left;
5516                }
5517            }
5518        } else if (a == Layout.Alignment.ALIGN_NORMAL) {
5519            /*
5520             * Keep leading edge in view.
5521             */
5522
5523            if (dir < 0) {
5524                int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
5525                scrollx = right - hspace;
5526            } else {
5527                scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line));
5528            }
5529        } else /* a == Layout.Alignment.ALIGN_OPPOSITE */ {
5530            /*
5531             * Keep trailing edge in view.
5532             */
5533
5534            if (dir < 0) {
5535                scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line));
5536            } else {
5537                int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
5538                scrollx = right - hspace;
5539            }
5540        }
5541
5542        if (ht < vspace) {
5543            scrolly = 0;
5544        } else {
5545            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
5546                scrolly = ht - vspace;
5547            } else {
5548                scrolly = 0;
5549            }
5550        }
5551
5552        if (scrollx != mScrollX || scrolly != mScrollY) {
5553            scrollTo(scrollx, scrolly);
5554            return true;
5555        } else {
5556            return false;
5557        }
5558    }
5559
5560    /**
5561     * Move the point, specified by the offset, into the view if it is needed.
5562     * This has to be called after layout. Returns true if anything changed.
5563     */
5564    public boolean bringPointIntoView(int offset) {
5565        boolean changed = false;
5566
5567        int line = mLayout.getLineForOffset(offset);
5568
5569        // FIXME: Is it okay to truncate this, or should we round?
5570        final int x = (int)mLayout.getPrimaryHorizontal(offset);
5571        final int top = mLayout.getLineTop(line);
5572        final int bottom = mLayout.getLineTop(line + 1);
5573
5574        int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
5575        int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
5576        int ht = mLayout.getHeight();
5577
5578        int grav;
5579
5580        switch (mLayout.getParagraphAlignment(line)) {
5581            case ALIGN_NORMAL:
5582                grav = 1;
5583                break;
5584
5585            case ALIGN_OPPOSITE:
5586                grav = -1;
5587                break;
5588
5589            default:
5590                grav = 0;
5591        }
5592
5593        grav *= mLayout.getParagraphDirection(line);
5594
5595        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5596        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
5597
5598        int hslack = (bottom - top) / 2;
5599        int vslack = hslack;
5600
5601        if (vslack > vspace / 4)
5602            vslack = vspace / 4;
5603        if (hslack > hspace / 4)
5604            hslack = hspace / 4;
5605
5606        int hs = mScrollX;
5607        int vs = mScrollY;
5608
5609        if (top - vs < vslack)
5610            vs = top - vslack;
5611        if (bottom - vs > vspace - vslack)
5612            vs = bottom - (vspace - vslack);
5613        if (ht - vs < vspace)
5614            vs = ht - vspace;
5615        if (0 - vs > 0)
5616            vs = 0;
5617
5618        if (grav != 0) {
5619            if (x - hs < hslack) {
5620                hs = x - hslack;
5621            }
5622            if (x - hs > hspace - hslack) {
5623                hs = x - (hspace - hslack);
5624            }
5625        }
5626
5627        if (grav < 0) {
5628            if (left - hs > 0)
5629                hs = left;
5630            if (right - hs < hspace)
5631                hs = right - hspace;
5632        } else if (grav > 0) {
5633            if (right - hs < hspace)
5634                hs = right - hspace;
5635            if (left - hs > 0)
5636                hs = left;
5637        } else /* grav == 0 */ {
5638            if (right - left <= hspace) {
5639                /*
5640                 * If the entire text fits, center it exactly.
5641                 */
5642                hs = left - (hspace - (right - left)) / 2;
5643            } else if (x > right - hslack) {
5644                /*
5645                 * If we are near the right edge, keep the right edge
5646                 * at the edge of the view.
5647                 */
5648                hs = right - hspace;
5649            } else if (x < left + hslack) {
5650                /*
5651                 * If we are near the left edge, keep the left edge
5652                 * at the edge of the view.
5653                 */
5654                hs = left;
5655            } else if (left > hs) {
5656                /*
5657                 * Is there whitespace visible at the left?  Fix it if so.
5658                 */
5659                hs = left;
5660            } else if (right < hs + hspace) {
5661                /*
5662                 * Is there whitespace visible at the right?  Fix it if so.
5663                 */
5664                hs = right - hspace;
5665            } else {
5666                /*
5667                 * Otherwise, float as needed.
5668                 */
5669                if (x - hs < hslack) {
5670                    hs = x - hslack;
5671                }
5672                if (x - hs > hspace - hslack) {
5673                    hs = x - (hspace - hslack);
5674                }
5675            }
5676        }
5677
5678        if (hs != mScrollX || vs != mScrollY) {
5679            if (mScroller == null) {
5680                scrollTo(hs, vs);
5681            } else {
5682                long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
5683                int dx = hs - mScrollX;
5684                int dy = vs - mScrollY;
5685
5686                if (duration > ANIMATED_SCROLL_GAP) {
5687                    mScroller.startScroll(mScrollX, mScrollY, dx, dy);
5688                    awakenScrollBars(mScroller.getDuration());
5689                    invalidate();
5690                } else {
5691                    if (!mScroller.isFinished()) {
5692                        mScroller.abortAnimation();
5693                    }
5694
5695                    scrollBy(dx, dy);
5696                }
5697
5698                mLastScroll = AnimationUtils.currentAnimationTimeMillis();
5699            }
5700
5701            changed = true;
5702        }
5703
5704        if (isFocused()) {
5705            // This offsets because getInterestingRect() is in terms of
5706            // viewport coordinates, but requestRectangleOnScreen()
5707            // is in terms of content coordinates.
5708
5709            Rect r = new Rect(x, top, x + 1, bottom);
5710            getInterestingRect(r, line);
5711            r.offset(mScrollX, mScrollY);
5712
5713            if (requestRectangleOnScreen(r)) {
5714                changed = true;
5715            }
5716        }
5717
5718        return changed;
5719    }
5720
5721    /**
5722     * Move the cursor, if needed, so that it is at an offset that is visible
5723     * to the user.  This will not move the cursor if it represents more than
5724     * one character (a selection range).  This will only work if the
5725     * TextView contains spannable text; otherwise it will do nothing.
5726     *
5727     * @return True if the cursor was actually moved, false otherwise.
5728     */
5729    public boolean moveCursorToVisibleOffset() {
5730        if (!(mText instanceof Spannable)) {
5731            return false;
5732        }
5733        int start = getSelectionStart();
5734        int end = getSelectionEnd();
5735        if (start != end) {
5736            return false;
5737        }
5738
5739        // First: make sure the line is visible on screen:
5740
5741        int line = mLayout.getLineForOffset(start);
5742
5743        final int top = mLayout.getLineTop(line);
5744        final int bottom = mLayout.getLineTop(line + 1);
5745        final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
5746        int vslack = (bottom - top) / 2;
5747        if (vslack > vspace / 4)
5748            vslack = vspace / 4;
5749        final int vs = mScrollY;
5750
5751        if (top < (vs+vslack)) {
5752            line = mLayout.getLineForVertical(vs+vslack+(bottom-top));
5753        } else if (bottom > (vspace+vs-vslack)) {
5754            line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top));
5755        }
5756
5757        // Next: make sure the character is visible on screen:
5758
5759        final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5760        final int hs = mScrollX;
5761        final int leftChar = mLayout.getOffsetForHorizontal(line, hs);
5762        final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs);
5763
5764        int newStart = start;
5765        if (newStart < leftChar) {
5766            newStart = leftChar;
5767        } else if (newStart > rightChar) {
5768            newStart = rightChar;
5769        }
5770
5771        if (newStart != start) {
5772            Selection.setSelection((Spannable)mText, newStart);
5773            return true;
5774        }
5775
5776        return false;
5777    }
5778
5779    @Override
5780    public void computeScroll() {
5781        if (mScroller != null) {
5782            if (mScroller.computeScrollOffset()) {
5783                mScrollX = mScroller.getCurrX();
5784                mScrollY = mScroller.getCurrY();
5785                postInvalidate();  // So we draw again
5786            }
5787        }
5788    }
5789
5790    private void getInterestingRect(Rect r, int line) {
5791        convertFromViewportToContentCoordinates(r);
5792
5793        // Rectangle can can be expanded on first and last line to take
5794        // padding into account.
5795        // TODO Take left/right padding into account too?
5796        if (line == 0) r.top -= getExtendedPaddingTop();
5797        if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom();
5798    }
5799
5800    private void convertFromViewportToContentCoordinates(Rect r) {
5801        final int horizontalOffset = viewportToContentHorizontalOffset();
5802        r.left += horizontalOffset;
5803        r.right += horizontalOffset;
5804
5805        final int verticalOffset = viewportToContentVerticalOffset();
5806        r.top += verticalOffset;
5807        r.bottom += verticalOffset;
5808    }
5809
5810    private int viewportToContentHorizontalOffset() {
5811        return getCompoundPaddingLeft() - mScrollX;
5812    }
5813
5814    private int viewportToContentVerticalOffset() {
5815        int offset = getExtendedPaddingTop() - mScrollY;
5816        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
5817            offset += getVerticalOffset(false);
5818        }
5819        return offset;
5820    }
5821
5822    @Override
5823    public void debug(int depth) {
5824        super.debug(depth);
5825
5826        String output = debugIndent(depth);
5827        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
5828                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
5829                + "} ";
5830
5831        if (mText != null) {
5832
5833            output += "mText=\"" + mText + "\" ";
5834            if (mLayout != null) {
5835                output += "mLayout width=" + mLayout.getWidth()
5836                        + " height=" + mLayout.getHeight();
5837            }
5838        } else {
5839            output += "mText=NULL";
5840        }
5841        Log.d(VIEW_LOG_TAG, output);
5842    }
5843
5844    /**
5845     * Convenience for {@link Selection#getSelectionStart}.
5846     */
5847    @ViewDebug.ExportedProperty(category = "text")
5848    public int getSelectionStart() {
5849        return Selection.getSelectionStart(getText());
5850    }
5851
5852    /**
5853     * Convenience for {@link Selection#getSelectionEnd}.
5854     */
5855    @ViewDebug.ExportedProperty(category = "text")
5856    public int getSelectionEnd() {
5857        return Selection.getSelectionEnd(getText());
5858    }
5859
5860    /**
5861     * Return true iff there is a selection inside this text view.
5862     */
5863    public boolean hasSelection() {
5864        final int selectionStart = getSelectionStart();
5865        final int selectionEnd = getSelectionEnd();
5866
5867        return selectionStart >= 0 && selectionStart != selectionEnd;
5868    }
5869
5870    /**
5871     * Sets the properties of this field (lines, horizontally scrolling,
5872     * transformation method) to be for a single-line input.
5873     *
5874     * @attr ref android.R.styleable#TextView_singleLine
5875     */
5876    public void setSingleLine() {
5877        setSingleLine(true);
5878    }
5879
5880    /**
5881     * If true, sets the properties of this field (lines, horizontally
5882     * scrolling, transformation method) to be for a single-line input;
5883     * if false, restores these to the default conditions.
5884     * Note that calling this with false restores default conditions,
5885     * not necessarily those that were in effect prior to calling
5886     * it with true.
5887     *
5888     * @attr ref android.R.styleable#TextView_singleLine
5889     */
5890    @android.view.RemotableViewMethod
5891    public void setSingleLine(boolean singleLine) {
5892        if ((mInputType&EditorInfo.TYPE_MASK_CLASS)
5893                == EditorInfo.TYPE_CLASS_TEXT) {
5894            if (singleLine) {
5895                mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
5896            } else {
5897                mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
5898            }
5899        }
5900        applySingleLine(singleLine, true);
5901    }
5902
5903    private void applySingleLine(boolean singleLine, boolean applyTransformation) {
5904        mSingleLine = singleLine;
5905        if (singleLine) {
5906            setLines(1);
5907            setHorizontallyScrolling(true);
5908            if (applyTransformation) {
5909                setTransformationMethod(SingleLineTransformationMethod.
5910                                        getInstance());
5911            }
5912        } else {
5913            setMaxLines(Integer.MAX_VALUE);
5914            setHorizontallyScrolling(false);
5915            if (applyTransformation) {
5916                setTransformationMethod(null);
5917            }
5918        }
5919    }
5920
5921    /**
5922     * Causes words in the text that are longer than the view is wide
5923     * to be ellipsized instead of broken in the middle.  You may also
5924     * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling}
5925     * to constrain the text to a single line.  Use <code>null</code>
5926     * to turn off ellipsizing.
5927     *
5928     * @attr ref android.R.styleable#TextView_ellipsize
5929     */
5930    public void setEllipsize(TextUtils.TruncateAt where) {
5931        mEllipsize = where;
5932
5933        if (mLayout != null) {
5934            nullLayouts();
5935            requestLayout();
5936            invalidate();
5937        }
5938    }
5939
5940    /**
5941     * Sets how many times to repeat the marquee animation. Only applied if the
5942     * TextView has marquee enabled. Set to -1 to repeat indefinitely.
5943     *
5944     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
5945     */
5946    public void setMarqueeRepeatLimit(int marqueeLimit) {
5947        mMarqueeRepeatLimit = marqueeLimit;
5948    }
5949
5950    /**
5951     * Returns where, if anywhere, words that are longer than the view
5952     * is wide should be ellipsized.
5953     */
5954    @ViewDebug.ExportedProperty
5955    public TextUtils.TruncateAt getEllipsize() {
5956        return mEllipsize;
5957    }
5958
5959    /**
5960     * Set the TextView so that when it takes focus, all the text is
5961     * selected.
5962     *
5963     * @attr ref android.R.styleable#TextView_selectAllOnFocus
5964     */
5965    @android.view.RemotableViewMethod
5966    public void setSelectAllOnFocus(boolean selectAllOnFocus) {
5967        mSelectAllOnFocus = selectAllOnFocus;
5968
5969        if (selectAllOnFocus && !(mText instanceof Spannable)) {
5970            setText(mText, BufferType.SPANNABLE);
5971        }
5972    }
5973
5974    /**
5975     * Set whether the cursor is visible.  The default is true.
5976     *
5977     * @attr ref android.R.styleable#TextView_cursorVisible
5978     */
5979    @android.view.RemotableViewMethod
5980    public void setCursorVisible(boolean visible) {
5981        mCursorVisible = visible;
5982        invalidate();
5983
5984        if (visible) {
5985            makeBlink();
5986        } else if (mBlink != null) {
5987            mBlink.removeCallbacks(mBlink);
5988        }
5989
5990        // InsertionPointCursorController depends on mCursorVisible
5991        prepareCursorControllers();
5992    }
5993
5994    private boolean canMarquee() {
5995        int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight());
5996        return width > 0 && mLayout.getLineWidth(0) > width;
5997    }
5998
5999    private void startMarquee() {
6000        // Do not ellipsize EditText
6001        if (mInput != null) return;
6002
6003        if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
6004            return;
6005        }
6006
6007        if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) &&
6008                getLineCount() == 1 && canMarquee()) {
6009
6010            if (mMarquee == null) mMarquee = new Marquee(this);
6011            mMarquee.start(mMarqueeRepeatLimit);
6012        }
6013    }
6014
6015    private void stopMarquee() {
6016        if (mMarquee != null && !mMarquee.isStopped()) {
6017            mMarquee.stop();
6018        }
6019    }
6020
6021    private void startStopMarquee(boolean start) {
6022        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6023            if (start) {
6024                startMarquee();
6025            } else {
6026                stopMarquee();
6027            }
6028        }
6029    }
6030
6031    private static final class Marquee extends Handler {
6032        // TODO: Add an option to configure this
6033        private static final float MARQUEE_DELTA_MAX = 0.07f;
6034        private static final int MARQUEE_DELAY = 1200;
6035        private static final int MARQUEE_RESTART_DELAY = 1200;
6036        private static final int MARQUEE_RESOLUTION = 1000 / 30;
6037        private static final int MARQUEE_PIXELS_PER_SECOND = 30;
6038
6039        private static final byte MARQUEE_STOPPED = 0x0;
6040        private static final byte MARQUEE_STARTING = 0x1;
6041        private static final byte MARQUEE_RUNNING = 0x2;
6042
6043        private static final int MESSAGE_START = 0x1;
6044        private static final int MESSAGE_TICK = 0x2;
6045        private static final int MESSAGE_RESTART = 0x3;
6046
6047        private final WeakReference<TextView> mView;
6048
6049        private byte mStatus = MARQUEE_STOPPED;
6050        private final float mScrollUnit;
6051        private float mMaxScroll;
6052        float mMaxFadeScroll;
6053        private float mGhostStart;
6054        private float mGhostOffset;
6055        private float mFadeStop;
6056        private int mRepeatLimit;
6057
6058        float mScroll;
6059
6060        Marquee(TextView v) {
6061            final float density = v.getContext().getResources().getDisplayMetrics().density;
6062            mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION;
6063            mView = new WeakReference<TextView>(v);
6064        }
6065
6066        @Override
6067        public void handleMessage(Message msg) {
6068            switch (msg.what) {
6069                case MESSAGE_START:
6070                    mStatus = MARQUEE_RUNNING;
6071                    tick();
6072                    break;
6073                case MESSAGE_TICK:
6074                    tick();
6075                    break;
6076                case MESSAGE_RESTART:
6077                    if (mStatus == MARQUEE_RUNNING) {
6078                        if (mRepeatLimit >= 0) {
6079                            mRepeatLimit--;
6080                        }
6081                        start(mRepeatLimit);
6082                    }
6083                    break;
6084            }
6085        }
6086
6087        void tick() {
6088            if (mStatus != MARQUEE_RUNNING) {
6089                return;
6090            }
6091
6092            removeMessages(MESSAGE_TICK);
6093
6094            final TextView textView = mView.get();
6095            if (textView != null && (textView.isFocused() || textView.isSelected())) {
6096                mScroll += mScrollUnit;
6097                if (mScroll > mMaxScroll) {
6098                    mScroll = mMaxScroll;
6099                    sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY);
6100                } else {
6101                    sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION);
6102                }
6103                textView.invalidate();
6104            }
6105        }
6106
6107        void stop() {
6108            mStatus = MARQUEE_STOPPED;
6109            removeMessages(MESSAGE_START);
6110            removeMessages(MESSAGE_RESTART);
6111            removeMessages(MESSAGE_TICK);
6112            resetScroll();
6113        }
6114
6115        private void resetScroll() {
6116            mScroll = 0.0f;
6117            final TextView textView = mView.get();
6118            if (textView != null) textView.invalidate();
6119        }
6120
6121        void start(int repeatLimit) {
6122            if (repeatLimit == 0) {
6123                stop();
6124                return;
6125            }
6126            mRepeatLimit = repeatLimit;
6127            final TextView textView = mView.get();
6128            if (textView != null && textView.mLayout != null) {
6129                mStatus = MARQUEE_STARTING;
6130                mScroll = 0.0f;
6131                final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() -
6132                        textView.getCompoundPaddingRight();
6133                final float lineWidth = textView.mLayout.getLineWidth(0);
6134                final float gap = textWidth / 3.0f;
6135                mGhostStart = lineWidth - textWidth + gap;
6136                mMaxScroll = mGhostStart + textWidth;
6137                mGhostOffset = lineWidth + gap;
6138                mFadeStop = lineWidth + textWidth / 6.0f;
6139                mMaxFadeScroll = mGhostStart + lineWidth + lineWidth;
6140
6141                textView.invalidate();
6142                sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY);
6143            }
6144        }
6145
6146        float getGhostOffset() {
6147            return mGhostOffset;
6148        }
6149
6150        boolean shouldDrawLeftFade() {
6151            return mScroll <= mFadeStop;
6152        }
6153
6154        boolean shouldDrawGhost() {
6155            return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart;
6156        }
6157
6158        boolean isRunning() {
6159            return mStatus == MARQUEE_RUNNING;
6160        }
6161
6162        boolean isStopped() {
6163            return mStatus == MARQUEE_STOPPED;
6164        }
6165    }
6166
6167    /**
6168     * This method is called when the text is changed, in case any
6169     * subclasses would like to know.
6170     *
6171     * @param text The text the TextView is displaying.
6172     * @param start The offset of the start of the range of the text
6173     *              that was modified.
6174     * @param before The offset of the former end of the range of the
6175     *               text that was modified.  If text was simply inserted,
6176     *               this will be the same as <code>start</code>.
6177     *               If text was replaced with new text or deleted, the
6178     *               length of the old text was <code>before-start</code>.
6179     * @param after The offset of the end of the range of the text
6180     *              that was modified.  If text was simply deleted,
6181     *              this will be the same as <code>start</code>.
6182     *              If text was replaced with new text or inserted,
6183     *              the length of the new text is <code>after-start</code>.
6184     */
6185    protected void onTextChanged(CharSequence text,
6186                                 int start, int before, int after) {
6187    }
6188
6189    /**
6190     * This method is called when the selection has changed, in case any
6191     * subclasses would like to know.
6192     *
6193     * @param selStart The new selection start location.
6194     * @param selEnd The new selection end location.
6195     */
6196    protected void onSelectionChanged(int selStart, int selEnd) {
6197    }
6198
6199    /**
6200     * Adds a TextWatcher to the list of those whose methods are called
6201     * whenever this TextView's text changes.
6202     * <p>
6203     * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
6204     * not called after {@link #setText} calls.  Now, doing {@link #setText}
6205     * if there are any text changed listeners forces the buffer type to
6206     * Editable if it would not otherwise be and does call this method.
6207     */
6208    public void addTextChangedListener(TextWatcher watcher) {
6209        if (mListeners == null) {
6210            mListeners = new ArrayList<TextWatcher>();
6211        }
6212
6213        mListeners.add(watcher);
6214    }
6215
6216    /**
6217     * Removes the specified TextWatcher from the list of those whose
6218     * methods are called
6219     * whenever this TextView's text changes.
6220     */
6221    public void removeTextChangedListener(TextWatcher watcher) {
6222        if (mListeners != null) {
6223            int i = mListeners.indexOf(watcher);
6224
6225            if (i >= 0) {
6226                mListeners.remove(i);
6227            }
6228        }
6229    }
6230
6231    private void sendBeforeTextChanged(CharSequence text, int start, int before,
6232                                   int after) {
6233        if (mListeners != null) {
6234            final ArrayList<TextWatcher> list = mListeners;
6235            final int count = list.size();
6236            for (int i = 0; i < count; i++) {
6237                list.get(i).beforeTextChanged(text, start, before, after);
6238            }
6239        }
6240    }
6241
6242    /**
6243     * Not private so it can be called from an inner class without going
6244     * through a thunk.
6245     */
6246    void sendOnTextChanged(CharSequence text, int start, int before,
6247                                   int after) {
6248        if (mListeners != null) {
6249            final ArrayList<TextWatcher> list = mListeners;
6250            final int count = list.size();
6251            for (int i = 0; i < count; i++) {
6252                list.get(i).onTextChanged(text, start, before, after);
6253            }
6254        }
6255    }
6256
6257    /**
6258     * Not private so it can be called from an inner class without going
6259     * through a thunk.
6260     */
6261    void sendAfterTextChanged(Editable text) {
6262        if (mListeners != null) {
6263            final ArrayList<TextWatcher> list = mListeners;
6264            final int count = list.size();
6265            for (int i = 0; i < count; i++) {
6266                list.get(i).afterTextChanged(text);
6267            }
6268        }
6269    }
6270
6271    /**
6272     * Not private so it can be called from an inner class without going
6273     * through a thunk.
6274     */
6275    void handleTextChanged(CharSequence buffer, int start,
6276            int before, int after) {
6277        final InputMethodState ims = mInputMethodState;
6278        if (ims == null || ims.mBatchEditNesting == 0) {
6279            updateAfterEdit();
6280        }
6281        if (ims != null) {
6282            ims.mContentChanged = true;
6283            if (ims.mChangedStart < 0) {
6284                ims.mChangedStart = start;
6285                ims.mChangedEnd = start+before;
6286            } else {
6287                if (ims.mChangedStart > start) ims.mChangedStart = start;
6288                if (ims.mChangedEnd < (start+before)) ims.mChangedEnd = start+before;
6289            }
6290            ims.mChangedDelta += after-before;
6291        }
6292
6293        sendOnTextChanged(buffer, start, before, after);
6294        onTextChanged(buffer, start, before, after);
6295
6296        // Hide the controller if the amount of content changed
6297        if (before != after) {
6298            hideControllers();
6299        }
6300    }
6301
6302    /**
6303     * Not private so it can be called from an inner class without going
6304     * through a thunk.
6305     */
6306    void spanChange(Spanned buf, Object what, int oldStart, int newStart,
6307            int oldEnd, int newEnd) {
6308        // XXX Make the start and end move together if this ends up
6309        // spending too much time invalidating.
6310
6311        boolean selChanged = false;
6312        int newSelStart=-1, newSelEnd=-1;
6313
6314        final InputMethodState ims = mInputMethodState;
6315
6316        if (what == Selection.SELECTION_END) {
6317            mHighlightPathBogus = true;
6318            selChanged = true;
6319            newSelEnd = newStart;
6320
6321            if (!isFocused()) {
6322                mSelectionMoved = true;
6323            }
6324
6325            if (oldStart >= 0 || newStart >= 0) {
6326                invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart);
6327                registerForPreDraw();
6328
6329                if (isFocused()) {
6330                    mShowCursor = SystemClock.uptimeMillis();
6331                    makeBlink();
6332                }
6333            }
6334        }
6335
6336        if (what == Selection.SELECTION_START) {
6337            mHighlightPathBogus = true;
6338            selChanged = true;
6339            newSelStart = newStart;
6340
6341            if (!isFocused()) {
6342                mSelectionMoved = true;
6343            }
6344
6345            if (oldStart >= 0 || newStart >= 0) {
6346                int end = Selection.getSelectionEnd(buf);
6347                invalidateCursor(end, oldStart, newStart);
6348            }
6349        }
6350
6351        if (selChanged) {
6352            if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) {
6353                if (newSelStart < 0) {
6354                    newSelStart = Selection.getSelectionStart(buf);
6355                }
6356                if (newSelEnd < 0) {
6357                    newSelEnd = Selection.getSelectionEnd(buf);
6358                }
6359                onSelectionChanged(newSelStart, newSelEnd);
6360            }
6361        }
6362
6363        if (what instanceof UpdateAppearance ||
6364            what instanceof ParagraphStyle) {
6365            if (ims == null || ims.mBatchEditNesting == 0) {
6366                invalidate();
6367                mHighlightPathBogus = true;
6368                checkForResize();
6369            } else {
6370                ims.mContentChanged = true;
6371            }
6372        }
6373
6374        if (MetaKeyKeyListener.isMetaTracker(buf, what)) {
6375            mHighlightPathBogus = true;
6376            if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) {
6377                ims.mSelectionModeChanged = true;
6378            }
6379
6380            if (Selection.getSelectionStart(buf) >= 0) {
6381                if (ims == null || ims.mBatchEditNesting == 0) {
6382                    invalidateCursor();
6383                } else {
6384                    ims.mCursorChanged = true;
6385                }
6386            }
6387        }
6388
6389        if (what instanceof ParcelableSpan) {
6390            // If this is a span that can be sent to a remote process,
6391            // the current extract editor would be interested in it.
6392            if (ims != null && ims.mExtracting != null) {
6393                if (ims.mBatchEditNesting != 0) {
6394                    if (oldStart >= 0) {
6395                        if (ims.mChangedStart > oldStart) {
6396                            ims.mChangedStart = oldStart;
6397                        }
6398                        if (ims.mChangedStart > oldEnd) {
6399                            ims.mChangedStart = oldEnd;
6400                        }
6401                    }
6402                    if (newStart >= 0) {
6403                        if (ims.mChangedStart > newStart) {
6404                            ims.mChangedStart = newStart;
6405                        }
6406                        if (ims.mChangedStart > newEnd) {
6407                            ims.mChangedStart = newEnd;
6408                        }
6409                    }
6410                } else {
6411                    if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: "
6412                            + oldStart + "-" + oldEnd + ","
6413                            + newStart + "-" + newEnd + what);
6414                    ims.mContentChanged = true;
6415                }
6416            }
6417        }
6418    }
6419
6420    private class ChangeWatcher
6421    implements TextWatcher, SpanWatcher {
6422
6423        private CharSequence mBeforeText;
6424
6425        public void beforeTextChanged(CharSequence buffer, int start,
6426                                      int before, int after) {
6427            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start
6428                    + " before=" + before + " after=" + after + ": " + buffer);
6429
6430            if (AccessibilityManager.getInstance(mContext).isEnabled()
6431                    && !isPasswordInputType(mInputType)) {
6432                mBeforeText = buffer.toString();
6433            }
6434
6435            TextView.this.sendBeforeTextChanged(buffer, start, before, after);
6436        }
6437
6438        public void onTextChanged(CharSequence buffer, int start,
6439                                  int before, int after) {
6440            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start
6441                    + " before=" + before + " after=" + after + ": " + buffer);
6442            TextView.this.handleTextChanged(buffer, start, before, after);
6443
6444            if (AccessibilityManager.getInstance(mContext).isEnabled() &&
6445                    (isFocused() || isSelected() &&
6446                    isShown())) {
6447                sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after);
6448                mBeforeText = null;
6449            }
6450        }
6451
6452        public void afterTextChanged(Editable buffer) {
6453            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer);
6454            TextView.this.sendAfterTextChanged(buffer);
6455
6456            if (MetaKeyKeyListener.getMetaState(buffer,
6457                                 MetaKeyKeyListener.META_SELECTING) != 0) {
6458                MetaKeyKeyListener.stopSelecting(TextView.this, buffer);
6459            }
6460        }
6461
6462        public void onSpanChanged(Spannable buf,
6463                                  Object what, int s, int e, int st, int en) {
6464            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e
6465                    + " st=" + st + " en=" + en + " what=" + what + ": " + buf);
6466            TextView.this.spanChange(buf, what, s, st, e, en);
6467        }
6468
6469        public void onSpanAdded(Spannable buf, Object what, int s, int e) {
6470            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e
6471                    + " what=" + what + ": " + buf);
6472            TextView.this.spanChange(buf, what, -1, s, -1, e);
6473        }
6474
6475        public void onSpanRemoved(Spannable buf, Object what, int s, int e) {
6476            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e
6477                    + " what=" + what + ": " + buf);
6478            TextView.this.spanChange(buf, what, s, -1, e, -1);
6479        }
6480    }
6481
6482    private void makeBlink() {
6483        if (!mCursorVisible) {
6484            if (mBlink != null) {
6485                mBlink.removeCallbacks(mBlink);
6486            }
6487
6488            return;
6489        }
6490
6491        if (mBlink == null)
6492            mBlink = new Blink(this);
6493
6494        mBlink.removeCallbacks(mBlink);
6495        mBlink.postAtTime(mBlink, mShowCursor + BLINK);
6496    }
6497
6498    /**
6499     * @hide
6500     */
6501    @Override
6502    public void dispatchFinishTemporaryDetach() {
6503        mDispatchTemporaryDetach = true;
6504        super.dispatchFinishTemporaryDetach();
6505        mDispatchTemporaryDetach = false;
6506    }
6507
6508    @Override
6509    public void onStartTemporaryDetach() {
6510        super.onStartTemporaryDetach();
6511        // Only track when onStartTemporaryDetach() is called directly,
6512        // usually because this instance is an editable field in a list
6513        if (!mDispatchTemporaryDetach) mTemporaryDetach = true;
6514    }
6515
6516    @Override
6517    public void onFinishTemporaryDetach() {
6518        super.onFinishTemporaryDetach();
6519        // Only track when onStartTemporaryDetach() is called directly,
6520        // usually because this instance is an editable field in a list
6521        if (!mDispatchTemporaryDetach) mTemporaryDetach = false;
6522    }
6523
6524    @Override
6525    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
6526        if (mTemporaryDetach) {
6527            // If we are temporarily in the detach state, then do nothing.
6528            super.onFocusChanged(focused, direction, previouslyFocusedRect);
6529            return;
6530        }
6531
6532        mShowCursor = SystemClock.uptimeMillis();
6533
6534        ensureEndedBatchEdit();
6535
6536        if (focused) {
6537            int selStart = getSelectionStart();
6538            int selEnd = getSelectionEnd();
6539
6540            if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
6541                // Has to be done before onTakeFocus, which can be overloaded.
6542                if (mLastTouchOffset >= 0) {
6543                    // Can happen when a TextView is displayed after its content has been deleted.
6544                    mLastTouchOffset = Math.min(mLastTouchOffset, mText.length());
6545                    Selection.setSelection((Spannable) mText, mLastTouchOffset);
6546                }
6547
6548                if (mMovement != null) {
6549                    mMovement.onTakeFocus(this, (Spannable) mText, direction);
6550                }
6551
6552                if (mSelectAllOnFocus) {
6553                    Selection.setSelection((Spannable) mText, 0, mText.length());
6554                }
6555
6556                // The DecorView does not have focus when the 'Done' ExtractEditText button is
6557                // pressed. Since it is the ViewRoot's mView, it requests focus before
6558                // ExtractEditText clears focus, which gives focus to the ExtractEditText.
6559                // This special case ensure that we keep current selection in that case.
6560                // It would be better to know why the DecorView does not have focus at that time.
6561                if (((this instanceof ExtractEditText) || mSelectionMoved) &&
6562                        selStart >= 0 && selEnd >= 0) {
6563                    /*
6564                     * Someone intentionally set the selection, so let them
6565                     * do whatever it is that they wanted to do instead of
6566                     * the default on-focus behavior.  We reset the selection
6567                     * here instead of just skipping the onTakeFocus() call
6568                     * because some movement methods do something other than
6569                     * just setting the selection in theirs and we still
6570                     * need to go through that path.
6571                     */
6572                    Selection.setSelection((Spannable) mText, selStart, selEnd);
6573                }
6574                mTouchFocusSelected = true;
6575            }
6576
6577            mFrozenWithFocus = false;
6578            mSelectionMoved = false;
6579
6580            if (mText instanceof Spannable) {
6581                Spannable sp = (Spannable) mText;
6582                MetaKeyKeyListener.resetMetaState(sp);
6583            }
6584
6585            makeBlink();
6586
6587            if (mError != null) {
6588                showError();
6589            }
6590        } else {
6591            if (mError != null) {
6592                hideError();
6593            }
6594            // Don't leave us in the middle of a batch edit.
6595            onEndBatchEdit();
6596
6597            hideInsertionPointCursorController();
6598            if (this instanceof ExtractEditText) {
6599                // terminateTextSelectionMode would remove selection, which we want to keep when
6600                // ExtractEditText goes out of focus.
6601                mIsInTextSelectionMode = false;
6602            } else {
6603                terminateTextSelectionMode();
6604            }
6605
6606            mLastTouchOffset = -1;
6607        }
6608
6609        startStopMarquee(focused);
6610
6611        if (mTransformation != null) {
6612            mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect);
6613        }
6614
6615        super.onFocusChanged(focused, direction, previouslyFocusedRect);
6616    }
6617
6618    @Override
6619    public void onWindowFocusChanged(boolean hasWindowFocus) {
6620        super.onWindowFocusChanged(hasWindowFocus);
6621
6622        if (hasWindowFocus) {
6623            if (mBlink != null) {
6624                mBlink.uncancel();
6625
6626                if (isFocused()) {
6627                    mShowCursor = SystemClock.uptimeMillis();
6628                    makeBlink();
6629                }
6630            }
6631        } else {
6632            if (mBlink != null) {
6633                mBlink.cancel();
6634            }
6635            // Don't leave us in the middle of a batch edit.
6636            onEndBatchEdit();
6637            if (mInputContentType != null) {
6638                mInputContentType.enterDown = false;
6639            }
6640            hideInsertionPointCursorController();
6641            if (mSelectionModifierCursorController != null) {
6642                mSelectionModifierCursorController.hide();
6643            }
6644        }
6645
6646        startStopMarquee(hasWindowFocus);
6647    }
6648
6649    @Override
6650    protected void onVisibilityChanged(View changedView, int visibility) {
6651        super.onVisibilityChanged(changedView, visibility);
6652        if (visibility != VISIBLE) {
6653            hideInsertionPointCursorController();
6654            if (mSelectionModifierCursorController != null) {
6655                mSelectionModifierCursorController.hide();
6656            }
6657        }
6658    }
6659
6660    /**
6661     * Use {@link BaseInputConnection#removeComposingSpans
6662     * BaseInputConnection.removeComposingSpans()} to remove any IME composing
6663     * state from this text view.
6664     */
6665    public void clearComposingText() {
6666        if (mText instanceof Spannable) {
6667            BaseInputConnection.removeComposingSpans((Spannable)mText);
6668        }
6669    }
6670
6671    @Override
6672    public void setSelected(boolean selected) {
6673        boolean wasSelected = isSelected();
6674
6675        super.setSelected(selected);
6676
6677        if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6678            if (selected) {
6679                startMarquee();
6680            } else {
6681                stopMarquee();
6682            }
6683        }
6684    }
6685
6686    private void onTapUpEvent(int prevStart, int prevEnd) {
6687        final int start = getSelectionStart();
6688        final int end = getSelectionEnd();
6689
6690        if (start == end) {
6691            if (start >= prevStart && start < prevEnd) {
6692                // Restore previous selection
6693                Selection.setSelection((Spannable)mText, prevStart, prevEnd);
6694
6695                if (mSelectionModifierCursorController != null &&
6696                        !mSelectionModifierCursorController.isShowing()) {
6697                    // If the anchors aren't showing, revive them.
6698                    mSelectionModifierCursorController.show();
6699                } else {
6700                    // Tapping inside the selection displays the cut/copy/paste context menu
6701                    // as long as the anchors are already showing.
6702                    showContextMenu();
6703                }
6704                return;
6705            } else {
6706                // Tapping outside stops selection mode, if any
6707                stopTextSelectionMode();
6708
6709                if (mInsertionPointCursorController != null) {
6710                    mInsertionPointCursorController.show();
6711                }
6712            }
6713        } else if (hasSelection() && mSelectionModifierCursorController != null) {
6714            mSelectionModifierCursorController.show();
6715        }
6716    }
6717
6718    class CommitSelectionReceiver extends ResultReceiver {
6719        private final int mPrevStart, mPrevEnd;
6720
6721        public CommitSelectionReceiver(int prevStart, int prevEnd) {
6722            super(getHandler());
6723            mPrevStart = prevStart;
6724            mPrevEnd = prevEnd;
6725        }
6726
6727        @Override
6728        protected void onReceiveResult(int resultCode, Bundle resultData) {
6729            // If this tap was actually used to show the IMM, leave cursor or selection unchanged
6730            // by restoring its previous position.
6731            if (resultCode == InputMethodManager.RESULT_SHOWN) {
6732                final int len = mText.length();
6733                int start = Math.min(len, mPrevStart);
6734                int end = Math.min(len, mPrevEnd);
6735                Selection.setSelection((Spannable)mText, start, end);
6736
6737                if (hasSelection()) {
6738                    startTextSelectionMode();
6739                }
6740            }
6741        }
6742    }
6743
6744    @Override
6745    public boolean onTouchEvent(MotionEvent event) {
6746        final int action = event.getActionMasked();
6747        if (action == MotionEvent.ACTION_DOWN) {
6748            if (mInsertionPointCursorController != null) {
6749                mInsertionPointCursorController.onTouchEvent(event);
6750            }
6751            if (mSelectionModifierCursorController != null) {
6752                mSelectionModifierCursorController.onTouchEvent(event);
6753            }
6754
6755            // Reset this state; it will be re-set if super.onTouchEvent
6756            // causes focus to move to the view.
6757            mTouchFocusSelected = false;
6758            mScrolled = false;
6759        }
6760
6761        final boolean superResult = super.onTouchEvent(event);
6762
6763        /*
6764         * Don't handle the release after a long press, because it will
6765         * move the selection away from whatever the menu action was
6766         * trying to affect.
6767         */
6768        if (mEatTouchRelease && action == MotionEvent.ACTION_UP) {
6769            mEatTouchRelease = false;
6770            return superResult;
6771        }
6772
6773        if ((mMovement != null || onCheckIsTextEditor()) && mText instanceof Spannable && mLayout != null) {
6774            if (mInsertionPointCursorController != null) {
6775                mInsertionPointCursorController.onTouchEvent(event);
6776            }
6777            if (mSelectionModifierCursorController != null) {
6778                mSelectionModifierCursorController.onTouchEvent(event);
6779            }
6780
6781            boolean handled = false;
6782
6783            // Save previous selection, in case this event is used to show the IME.
6784            int oldSelStart = getSelectionStart();
6785            int oldSelEnd = getSelectionEnd();
6786
6787            final int oldScrollX = mScrollX;
6788            final int oldScrollY = mScrollY;
6789
6790            if (mMovement != null) {
6791                handled |= mMovement.onTouchEvent(this, (Spannable) mText, event);
6792            }
6793
6794            if (isTextEditable()) {
6795                if (mScrollX != oldScrollX || mScrollY != oldScrollY) {
6796                    // Hide insertion anchor while scrolling. Leave selection.
6797                    hideInsertionPointCursorController();
6798                    if (mSelectionModifierCursorController != null &&
6799                            mSelectionModifierCursorController.isShowing()) {
6800                        mSelectionModifierCursorController.updatePosition();
6801                    }
6802                }
6803                if (action == MotionEvent.ACTION_UP && isFocused() && !mScrolled) {
6804                    InputMethodManager imm = (InputMethodManager)
6805                          getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
6806
6807                    CommitSelectionReceiver csr = null;
6808                    if (getSelectionStart() != oldSelStart || getSelectionEnd() != oldSelEnd ||
6809                            didTouchFocusSelect()) {
6810                        csr = new CommitSelectionReceiver(oldSelStart, oldSelEnd);
6811                    }
6812
6813                    handled |= imm.showSoftInput(this, 0, csr) && (csr != null);
6814
6815                    // Cannot be done by CommitSelectionReceiver, which might not always be called,
6816                    // for instance when dealing with an ExtractEditText.
6817                    onTapUpEvent(oldSelStart, oldSelEnd);
6818                }
6819            }
6820
6821            if (handled) {
6822                return true;
6823            }
6824        }
6825
6826        return superResult;
6827    }
6828
6829    private void prepareCursorControllers() {
6830        // TODO Add an extra android:cursorController flag to disable the controller?
6831        if (mCursorVisible && mLayout != null) {
6832            if (mInsertionPointCursorController == null) {
6833                mInsertionPointCursorController = new InsertionPointCursorController();
6834            }
6835        } else {
6836            mInsertionPointCursorController = null;
6837        }
6838
6839        if (textCanBeSelected() && mLayout != null) {
6840            if (mSelectionModifierCursorController == null) {
6841                mSelectionModifierCursorController = new SelectionModifierCursorController();
6842            }
6843        } else {
6844            // Stop selection mode if the controller becomes unavailable.
6845            stopTextSelectionMode();
6846            mSelectionModifierCursorController = null;
6847        }
6848    }
6849
6850    /**
6851     * @return True iff this TextView contains a text that can be edited.
6852     */
6853    private boolean isTextEditable() {
6854        return mText instanceof Editable && onCheckIsTextEditor();
6855    }
6856
6857    /**
6858     * Returns true, only while processing a touch gesture, if the initial
6859     * touch down event caused focus to move to the text view and as a result
6860     * its selection changed.  Only valid while processing the touch gesture
6861     * of interest.
6862     */
6863    public boolean didTouchFocusSelect() {
6864        return mTouchFocusSelected;
6865    }
6866
6867    @Override
6868    public void cancelLongPress() {
6869        super.cancelLongPress();
6870        mScrolled = true;
6871    }
6872
6873    @Override
6874    public boolean onTrackballEvent(MotionEvent event) {
6875        if (mMovement != null && mText instanceof Spannable &&
6876            mLayout != null) {
6877            if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) {
6878                return true;
6879            }
6880        }
6881
6882        return super.onTrackballEvent(event);
6883    }
6884
6885    public void setScroller(Scroller s) {
6886        mScroller = s;
6887    }
6888
6889    private static class Blink extends Handler implements Runnable {
6890        private final WeakReference<TextView> mView;
6891        private boolean mCancelled;
6892
6893        public Blink(TextView v) {
6894            mView = new WeakReference<TextView>(v);
6895        }
6896
6897        public void run() {
6898            if (mCancelled) {
6899                return;
6900            }
6901
6902            removeCallbacks(Blink.this);
6903
6904            TextView tv = mView.get();
6905
6906            if (tv != null && tv.isFocused()) {
6907                int st = tv.getSelectionStart();
6908                int en = tv.getSelectionEnd();
6909
6910                if (st == en && st >= 0 && en >= 0) {
6911                    if (tv.mLayout != null) {
6912                        tv.invalidateCursorPath();
6913                    }
6914
6915                    postAtTime(this, SystemClock.uptimeMillis() + BLINK);
6916                }
6917            }
6918        }
6919
6920        void cancel() {
6921            if (!mCancelled) {
6922                removeCallbacks(Blink.this);
6923                mCancelled = true;
6924            }
6925        }
6926
6927        void uncancel() {
6928            mCancelled = false;
6929        }
6930    }
6931
6932    @Override
6933    protected float getLeftFadingEdgeStrength() {
6934        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6935            if (mMarquee != null && !mMarquee.isStopped()) {
6936                final Marquee marquee = mMarquee;
6937                if (marquee.shouldDrawLeftFade()) {
6938                    return marquee.mScroll / getHorizontalFadingEdgeLength();
6939                } else {
6940                    return 0.0f;
6941                }
6942            } else if (getLineCount() == 1) {
6943                switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
6944                    case Gravity.LEFT:
6945                        return 0.0f;
6946                    case Gravity.RIGHT:
6947                        return (mLayout.getLineRight(0) - (mRight - mLeft) -
6948                                getCompoundPaddingLeft() - getCompoundPaddingRight() -
6949                                mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength();
6950                    case Gravity.CENTER_HORIZONTAL:
6951                        return 0.0f;
6952                }
6953            }
6954        }
6955        return super.getLeftFadingEdgeStrength();
6956    }
6957
6958    @Override
6959    protected float getRightFadingEdgeStrength() {
6960        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6961            if (mMarquee != null && !mMarquee.isStopped()) {
6962                final Marquee marquee = mMarquee;
6963                return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength();
6964            } else if (getLineCount() == 1) {
6965                switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
6966                    case Gravity.LEFT:
6967                        final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() -
6968                                getCompoundPaddingRight();
6969                        final float lineWidth = mLayout.getLineWidth(0);
6970                        return (lineWidth - textWidth) / getHorizontalFadingEdgeLength();
6971                    case Gravity.RIGHT:
6972                        return 0.0f;
6973                    case Gravity.CENTER_HORIZONTAL:
6974                        return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
6975                                getCompoundPaddingLeft() - getCompoundPaddingRight())) /
6976                                getHorizontalFadingEdgeLength();
6977                }
6978            }
6979        }
6980        return super.getRightFadingEdgeStrength();
6981    }
6982
6983    @Override
6984    protected int computeHorizontalScrollRange() {
6985        if (mLayout != null)
6986            return mLayout.getWidth();
6987
6988        return super.computeHorizontalScrollRange();
6989    }
6990
6991    @Override
6992    protected int computeVerticalScrollRange() {
6993        if (mLayout != null)
6994            return mLayout.getHeight();
6995
6996        return super.computeVerticalScrollRange();
6997    }
6998
6999    @Override
7000    protected int computeVerticalScrollExtent() {
7001        return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
7002    }
7003
7004    public enum BufferType {
7005        NORMAL, SPANNABLE, EDITABLE,
7006    }
7007
7008    /**
7009     * Returns the TextView_textColor attribute from the
7010     * Resources.StyledAttributes, if set, or the TextAppearance_textColor
7011     * from the TextView_textAppearance attribute, if TextView_textColor
7012     * was not set directly.
7013     */
7014    public static ColorStateList getTextColors(Context context, TypedArray attrs) {
7015        ColorStateList colors;
7016        colors = attrs.getColorStateList(com.android.internal.R.styleable.
7017                                         TextView_textColor);
7018
7019        if (colors == null) {
7020            int ap = attrs.getResourceId(com.android.internal.R.styleable.
7021                                         TextView_textAppearance, -1);
7022            if (ap != -1) {
7023                TypedArray appearance;
7024                appearance = context.obtainStyledAttributes(ap,
7025                                            com.android.internal.R.styleable.TextAppearance);
7026                colors = appearance.getColorStateList(com.android.internal.R.styleable.
7027                                                  TextAppearance_textColor);
7028                appearance.recycle();
7029            }
7030        }
7031
7032        return colors;
7033    }
7034
7035    /**
7036     * Returns the default color from the TextView_textColor attribute
7037     * from the AttributeSet, if set, or the default color from the
7038     * TextAppearance_textColor from the TextView_textAppearance attribute,
7039     * if TextView_textColor was not set directly.
7040     */
7041    public static int getTextColor(Context context,
7042                                   TypedArray attrs,
7043                                   int def) {
7044        ColorStateList colors = getTextColors(context, attrs);
7045
7046        if (colors == null) {
7047            return def;
7048        } else {
7049            return colors.getDefaultColor();
7050        }
7051    }
7052
7053    @Override
7054    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7055        switch (keyCode) {
7056        case KeyEvent.KEYCODE_A:
7057            if (canSelectText()) {
7058                return onTextContextMenuItem(ID_SELECT_ALL);
7059            }
7060
7061            break;
7062
7063        case KeyEvent.KEYCODE_X:
7064            if (canCut()) {
7065                return onTextContextMenuItem(ID_CUT);
7066            }
7067
7068            break;
7069
7070        case KeyEvent.KEYCODE_C:
7071            if (canCopy()) {
7072                return onTextContextMenuItem(ID_COPY);
7073            }
7074
7075            break;
7076
7077        case KeyEvent.KEYCODE_V:
7078            if (canPaste()) {
7079                return onTextContextMenuItem(ID_PASTE);
7080            }
7081
7082            break;
7083        }
7084
7085        return super.onKeyShortcut(keyCode, event);
7086    }
7087
7088    private boolean canSelectText() {
7089        return textCanBeSelected() && mText.length() != 0;
7090    }
7091
7092    private boolean textCanBeSelected() {
7093        // prepareCursorController() relies on this method.
7094        // If you change this condition, make sure prepareCursorController is called anywhere
7095        // the value of this condition might be changed.
7096        return (mText instanceof Spannable &&
7097                mMovement != null &&
7098                mMovement.canSelectArbitrarily());
7099    }
7100
7101    private boolean canCut() {
7102        if (mTransformation instanceof PasswordTransformationMethod) {
7103            return false;
7104        }
7105
7106        if (mText.length() > 0 && hasSelection()) {
7107            if (mText instanceof Editable && mInput != null) {
7108                return true;
7109            }
7110        }
7111
7112        return false;
7113    }
7114
7115    private boolean canCopy() {
7116        if (mTransformation instanceof PasswordTransformationMethod) {
7117            return false;
7118        }
7119
7120        if (mText.length() > 0 && hasSelection()) {
7121            return true;
7122        }
7123
7124        return false;
7125    }
7126
7127    private boolean canPaste() {
7128        return (mText instanceof Editable &&
7129                mInput != null &&
7130                getSelectionStart() >= 0 &&
7131                getSelectionEnd() >= 0 &&
7132                ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)).
7133                hasText());
7134    }
7135
7136    /**
7137     * Returns the offsets delimiting the 'word' located at position offset.
7138     *
7139     * @param offset An offset in the text.
7140     * @return The offsets for the start and end of the word located at <code>offset</code>.
7141     * The two ints offsets are packed in a long, with the starting offset shifted by 32 bits.
7142     * Returns a negative value if no valid word was found.
7143     */
7144    private long getWordLimitsAt(int offset) {
7145        /*
7146         * Quick return if the input type is one where adding words
7147         * to the dictionary doesn't make any sense.
7148         */
7149        int klass = mInputType & InputType.TYPE_MASK_CLASS;
7150        if (klass == InputType.TYPE_CLASS_NUMBER ||
7151            klass == InputType.TYPE_CLASS_PHONE ||
7152            klass == InputType.TYPE_CLASS_DATETIME) {
7153            return -1;
7154        }
7155
7156        int variation = mInputType & InputType.TYPE_MASK_VARIATION;
7157        if (variation == InputType.TYPE_TEXT_VARIATION_URI ||
7158            variation == InputType.TYPE_TEXT_VARIATION_PASSWORD ||
7159            variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ||
7160            variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
7161            variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
7162            return -1;
7163        }
7164
7165        int len = mText.length();
7166        int end = Math.min(offset, len);
7167
7168        if (end < 0) {
7169            return -1;
7170        }
7171
7172        int start = end;
7173
7174        for (; start > 0; start--) {
7175            char c = mTransformed.charAt(start - 1);
7176            int type = Character.getType(c);
7177
7178            if (c != '\'' &&
7179                type != Character.UPPERCASE_LETTER &&
7180                type != Character.LOWERCASE_LETTER &&
7181                type != Character.TITLECASE_LETTER &&
7182                type != Character.MODIFIER_LETTER &&
7183                type != Character.DECIMAL_DIGIT_NUMBER) {
7184                break;
7185            }
7186        }
7187
7188        for (; end < len; end++) {
7189            char c = mTransformed.charAt(end);
7190            int type = Character.getType(c);
7191
7192            if (c != '\'' &&
7193                type != Character.UPPERCASE_LETTER &&
7194                type != Character.LOWERCASE_LETTER &&
7195                type != Character.TITLECASE_LETTER &&
7196                type != Character.MODIFIER_LETTER &&
7197                type != Character.DECIMAL_DIGIT_NUMBER) {
7198                break;
7199            }
7200        }
7201
7202        if (start == end) {
7203            return -1;
7204        }
7205
7206        if (end - start > 48) {
7207            return -1;
7208        }
7209
7210        boolean hasLetter = false;
7211        for (int i = start; i < end; i++) {
7212            if (Character.isLetter(mTransformed.charAt(i))) {
7213                hasLetter = true;
7214                break;
7215            }
7216        }
7217
7218        if (!hasLetter) {
7219            return -1;
7220        }
7221
7222        // Two ints packed in a long
7223        return (((long) start) << 32) | end;
7224    }
7225
7226    private void selectCurrentWord() {
7227        // In case selection mode is started after an orientation change or after a select all,
7228        // use the current selection instead of creating one
7229        if (hasSelection()) {
7230            return;
7231        }
7232
7233        int selectionStart, selectionEnd;
7234
7235        // selectionModifierCursorController is not null at that point
7236        SelectionModifierCursorController selectionModifierCursorController =
7237            ((SelectionModifierCursorController) mSelectionModifierCursorController);
7238        int minOffset = selectionModifierCursorController.getMinTouchOffset();
7239        int maxOffset = selectionModifierCursorController.getMaxTouchOffset();
7240
7241        if (minOffset == maxOffset) {
7242            int offset = Math.max(0, Math.min(minOffset, mTransformed.length()));
7243
7244            // Tolerance, number of charaters around tapped position
7245            final int range = 1;
7246            final int max = mTransformed.length() - 1;
7247
7248            // 'Smart' word selection: detect position between words
7249            for (int i = -range; i <= range; i++) {
7250                int index = offset + i;
7251                if (index >= 0 && index <= max) {
7252                    if (Character.isSpaceChar(mTransformed.charAt(index))) {
7253                        // Select current space
7254                        selectionStart = index;
7255                        selectionEnd = selectionStart + 1;
7256
7257                        // Extend selection to maximum space range
7258                        while (selectionStart > 0 &&
7259                                Character.isSpaceChar(mTransformed.charAt(selectionStart - 1))) {
7260                            selectionStart--;
7261                        }
7262                        while (selectionEnd < max &&
7263                                Character.isSpaceChar(mTransformed.charAt(selectionEnd))) {
7264                            selectionEnd++;
7265                        }
7266
7267                        Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
7268                        return;
7269                    }
7270                }
7271            }
7272
7273            // 'Smart' word selection: detect position at beginning or end of text.
7274            if (offset <= range) {
7275                Selection.setSelection((Spannable) mText, 0, 0);
7276                return;
7277            }
7278            if (offset >= (max - range)) {
7279                Selection.setSelection((Spannable) mText, max + 1, max + 1);
7280                return;
7281            }
7282        }
7283
7284        long wordLimits = getWordLimitsAt(minOffset);
7285        if (wordLimits >= 0) {
7286            selectionStart = (int) (wordLimits >>> 32);
7287        } else {
7288            selectionStart = Math.max(minOffset - 5, 0);
7289        }
7290
7291        wordLimits = getWordLimitsAt(maxOffset);
7292        if (wordLimits >= 0) {
7293            selectionEnd = (int) (wordLimits & 0x00000000FFFFFFFFL);
7294        } else {
7295            selectionEnd = Math.min(maxOffset + 5, mText.length());
7296        }
7297
7298        Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
7299    }
7300
7301    private String getWordForDictionary() {
7302        if (mLastTouchOffset < 0) {
7303            return null;
7304        }
7305
7306        long wordLimits = getWordLimitsAt(mLastTouchOffset);
7307        if (wordLimits >= 0) {
7308            int start = (int) (wordLimits >>> 32);
7309            int end = (int) (wordLimits & 0x00000000FFFFFFFFL);
7310            return mTransformed.subSequence(start, end).toString();
7311        } else {
7312            return null;
7313        }
7314    }
7315
7316    @Override
7317    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
7318        if (!isShown()) {
7319            return false;
7320        }
7321
7322        final boolean isPassword = isPasswordInputType(mInputType);
7323
7324        if (!isPassword) {
7325            CharSequence text = getText();
7326            if (TextUtils.isEmpty(text)) {
7327                text = getHint();
7328            }
7329            if (!TextUtils.isEmpty(text)) {
7330                if (text.length() > AccessibilityEvent.MAX_TEXT_LENGTH) {
7331                    text = text.subSequence(0, AccessibilityEvent.MAX_TEXT_LENGTH + 1);
7332                }
7333                event.getText().add(text);
7334            }
7335        } else {
7336            event.setPassword(isPassword);
7337        }
7338        return false;
7339    }
7340
7341    void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText,
7342            int fromIndex, int removedCount, int addedCount) {
7343        AccessibilityEvent event =
7344            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
7345        event.setFromIndex(fromIndex);
7346        event.setRemovedCount(removedCount);
7347        event.setAddedCount(addedCount);
7348        event.setBeforeText(beforeText);
7349        sendAccessibilityEventUnchecked(event);
7350    }
7351
7352    @Override
7353    protected void onCreateContextMenu(ContextMenu menu) {
7354        super.onCreateContextMenu(menu);
7355        boolean added = false;
7356
7357        if (mIsInTextSelectionMode) {
7358            MenuHandler handler = new MenuHandler();
7359
7360            if (canCut()) {
7361                menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut).
7362                     setOnMenuItemClickListener(handler).
7363                     setAlphabeticShortcut('x');
7364                added = true;
7365            }
7366
7367            if (canCopy()) {
7368                menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy).
7369                     setOnMenuItemClickListener(handler).
7370                     setAlphabeticShortcut('c');
7371                added = true;
7372            }
7373
7374            if (canPaste()) {
7375                menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste).
7376                     setOnMenuItemClickListener(handler).
7377                     setAlphabeticShortcut('v');
7378                added = true;
7379            }
7380        } else {
7381            /*
7382            if (!isFocused()) {
7383                if (isFocusable() && mInput != null) {
7384                    if (canCopy()) {
7385                        MenuHandler handler = new MenuHandler();
7386                        menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy).
7387                             setOnMenuItemClickListener(handler).
7388                             setAlphabeticShortcut('c');
7389                        menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle);
7390                    }
7391                }
7392
7393                //return;
7394            }
7395             */
7396            MenuHandler handler = new MenuHandler();
7397
7398            if (canSelectText()) {
7399                menu.add(0, ID_START_SELECTING_TEXT, 0, com.android.internal.R.string.selectText).
7400                     setOnMenuItemClickListener(handler);
7401                menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll).
7402                     setOnMenuItemClickListener(handler).
7403                     setAlphabeticShortcut('a');
7404                added = true;
7405            }
7406
7407            if (mText instanceof Spanned) {
7408                int selStart = getSelectionStart();
7409                int selEnd = getSelectionEnd();
7410
7411                int min = Math.min(selStart, selEnd);
7412                int max = Math.max(selStart, selEnd);
7413
7414                URLSpan[] urls = ((Spanned) mText).getSpans(min, max,
7415                        URLSpan.class);
7416                if (urls.length == 1) {
7417                    menu.add(0, ID_COPY_URL, 0, com.android.internal.R.string.copyUrl).
7418                         setOnMenuItemClickListener(handler);
7419                    added = true;
7420                }
7421            }
7422
7423            if (canPaste()) {
7424                menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste).
7425                     setOnMenuItemClickListener(handler).
7426                     setAlphabeticShortcut('v');
7427                added = true;
7428            }
7429
7430            if (isInputMethodTarget()) {
7431                menu.add(1, ID_SWITCH_INPUT_METHOD, 0, com.android.internal.R.string.inputMethod).
7432                     setOnMenuItemClickListener(handler);
7433                added = true;
7434            }
7435
7436            String word = getWordForDictionary();
7437            if (word != null) {
7438                menu.add(1, ID_ADD_TO_DICTIONARY, 0,
7439                     getContext().getString(com.android.internal.R.string.addToDictionary, word)).
7440                     setOnMenuItemClickListener(handler);
7441                added = true;
7442
7443            }
7444        }
7445
7446        if (added) {
7447            menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle);
7448        }
7449    }
7450
7451    /**
7452     * Returns whether this text view is a current input method target.  The
7453     * default implementation just checks with {@link InputMethodManager}.
7454     */
7455    public boolean isInputMethodTarget() {
7456        InputMethodManager imm = InputMethodManager.peekInstance();
7457        return imm != null && imm.isActive(this);
7458    }
7459
7460    // Context menu entries
7461    private static final int ID_SELECT_ALL = android.R.id.selectAll;
7462    private static final int ID_START_SELECTING_TEXT = android.R.id.startSelectingText;
7463    private static final int ID_CUT = android.R.id.cut;
7464    private static final int ID_COPY = android.R.id.copy;
7465    private static final int ID_PASTE = android.R.id.paste;
7466    private static final int ID_COPY_URL = android.R.id.copyUrl;
7467    private static final int ID_SWITCH_INPUT_METHOD = android.R.id.switchInputMethod;
7468    private static final int ID_ADD_TO_DICTIONARY = android.R.id.addToDictionary;
7469
7470    private class MenuHandler implements MenuItem.OnMenuItemClickListener {
7471        public boolean onMenuItemClick(MenuItem item) {
7472            return onTextContextMenuItem(item.getItemId());
7473        }
7474    }
7475
7476    /**
7477     * Called when a context menu option for the text view is selected.  Currently
7478     * this will be one of: {@link android.R.id#selectAll},
7479     * {@link android.R.id#startSelectingText},
7480     * {@link android.R.id#cut}, {@link android.R.id#copy},
7481     * {@link android.R.id#paste}, {@link android.R.id#copyUrl},
7482     * or {@link android.R.id#switchInputMethod}.
7483     */
7484    public boolean onTextContextMenuItem(int id) {
7485        int min = 0;
7486        int max = mText.length();
7487
7488        if (isFocused()) {
7489            final int selStart = getSelectionStart();
7490            final int selEnd = getSelectionEnd();
7491
7492            min = Math.max(0, Math.min(selStart, selEnd));
7493            max = Math.max(0, Math.max(selStart, selEnd));
7494        }
7495
7496        ClipboardManager clip = (ClipboardManager)getContext()
7497                .getSystemService(Context.CLIPBOARD_SERVICE);
7498
7499        switch (id) {
7500            case ID_SELECT_ALL:
7501                Selection.setSelection((Spannable) mText, 0, mText.length());
7502                startTextSelectionMode();
7503                return true;
7504
7505            case ID_START_SELECTING_TEXT:
7506                startTextSelectionMode();
7507                return true;
7508
7509            case ID_CUT:
7510                clip.setText(mTransformed.subSequence(min, max));
7511                ((Editable) mText).delete(min, max);
7512                stopTextSelectionMode();
7513                return true;
7514
7515            case ID_COPY:
7516                clip.setText(mTransformed.subSequence(min, max));
7517                stopTextSelectionMode();
7518                return true;
7519
7520            case ID_PASTE:
7521                CharSequence paste = clip.getText();
7522
7523                if (paste != null && paste.length() > 0) {
7524                    // Paste adds/removes spaces before or after insertion as needed.
7525
7526                    if (Character.isSpaceChar(paste.charAt(0))) {
7527                        if (min > 0 && Character.isSpaceChar(mTransformed.charAt(min - 1))) {
7528                            // Two spaces at beginning of paste: remove one
7529                            ((Editable) mText).replace(min - 1, min, "");
7530                            min = min - 1;
7531                            max = max - 1;
7532                        }
7533                    } else {
7534                        if (min > 0 && !Character.isSpaceChar(mTransformed.charAt(min - 1))) {
7535                            // No space at beginning of paste: add one
7536                            ((Editable) mText).replace(min, min, " ");
7537                            min = min + 1;
7538                            max = max + 1;
7539                        }
7540                    }
7541
7542                    if (Character.isSpaceChar(paste.charAt(paste.length() - 1))) {
7543                        if (max < mText.length() && Character.isSpaceChar(mTransformed.charAt(max))) {
7544                            // Two spaces at end of paste: remove one
7545                            ((Editable) mText).replace(max, max + 1, "");
7546                        }
7547                    } else {
7548                        if (max < mText.length() && !Character.isSpaceChar(mTransformed.charAt(max))) {
7549                            // No space at end of paste: add one
7550                            ((Editable) mText).replace(max, max, " ");
7551                        }
7552                    }
7553
7554                    Selection.setSelection((Spannable) mText, max);
7555                    ((Editable) mText).replace(min, max, paste);
7556                    stopTextSelectionMode();
7557                }
7558                return true;
7559
7560            case ID_COPY_URL:
7561                URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class);
7562                if (urls.length == 1) {
7563                    clip.setText(urls[0].getURL());
7564                }
7565                return true;
7566
7567            case ID_SWITCH_INPUT_METHOD:
7568                InputMethodManager imm = InputMethodManager.peekInstance();
7569                if (imm != null) {
7570                    imm.showInputMethodPicker();
7571                }
7572                return true;
7573
7574            case ID_ADD_TO_DICTIONARY:
7575                String word = getWordForDictionary();
7576
7577                if (word != null) {
7578                    Intent i = new Intent("com.android.settings.USER_DICTIONARY_INSERT");
7579                    i.putExtra("word", word);
7580                    i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
7581                    getContext().startActivity(i);
7582                }
7583                return true;
7584            }
7585
7586        return false;
7587    }
7588
7589    @Override
7590    public boolean performLongClick() {
7591        if (super.performLongClick()) {
7592            mEatTouchRelease = true;
7593            return true;
7594        }
7595
7596        return false;
7597    }
7598
7599    private void startTextSelectionMode() {
7600        if (!mIsInTextSelectionMode) {
7601            if (mSelectionModifierCursorController == null) {
7602                Log.w(LOG_TAG, "TextView has no selection controller. Action mode cancelled.");
7603                return;
7604            }
7605
7606            if (!requestFocus()) {
7607                return;
7608            }
7609
7610            selectCurrentWord();
7611            mSelectionModifierCursorController.show();
7612            mIsInTextSelectionMode = true;
7613        }
7614    }
7615
7616    /**
7617     * Same as {@link #stopTextSelectionMode()}, except that there is no cursor controller
7618     * fade out animation. Needed since the drawable and their alpha values are shared by all
7619     * TextViews. Switching from one TextView to another would fade the cursor controllers in the
7620     * new one otherwise.
7621     */
7622    private void terminateTextSelectionMode() {
7623        stopTextSelectionMode();
7624        if (mSelectionModifierCursorController != null) {
7625            SelectionModifierCursorController selectionModifierCursorController =
7626                (SelectionModifierCursorController) mSelectionModifierCursorController;
7627            selectionModifierCursorController.cancelFadeOutAnimation();
7628        }
7629    }
7630
7631    private void stopTextSelectionMode() {
7632        if (mIsInTextSelectionMode) {
7633            Selection.setSelection((Spannable) mText, getSelectionEnd());
7634            if (mSelectionModifierCursorController != null) {
7635                mSelectionModifierCursorController.hide();
7636            }
7637
7638            mIsInTextSelectionMode = false;
7639        }
7640    }
7641
7642    /**
7643     * A CursorController instance can be used to control a cursor in the text.
7644     * It is not used outside of {@link TextView}.
7645     * @hide
7646     */
7647    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
7648        /**
7649         * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}.
7650         * See also {@link #hide()}.
7651         */
7652        public void show();
7653
7654        /**
7655         * Hide the cursor controller from screen.
7656         * See also {@link #show()}.
7657         */
7658        public void hide();
7659
7660        /**
7661         * @return true if the CursorController is currently visible
7662         */
7663        public boolean isShowing();
7664
7665        /**
7666         * Update the controller's position.
7667         */
7668        public void updatePosition(HandleView handle, int x, int y);
7669
7670        public void updatePosition();
7671
7672        /**
7673         * This method is called by {@link #onTouchEvent(MotionEvent)} and gives the controller
7674         * a chance to become active and/or visible.
7675         * @param event The touch event
7676         */
7677        public boolean onTouchEvent(MotionEvent event);
7678    }
7679
7680    private class HandleView extends View {
7681        private boolean mPositionOnTop = false;
7682        private Drawable mDrawable;
7683        private PopupWindow mContainer;
7684        private int mPositionX;
7685        private int mPositionY;
7686        private CursorController mController;
7687        private boolean mIsDragging;
7688        private float mOffsetX;
7689        private float mOffsetY;
7690        private float mHotspotX;
7691        private float mHotspotY;
7692
7693        public HandleView(CursorController controller, Drawable handle) {
7694            super(TextView.this.mContext);
7695            mController = controller;
7696            mDrawable = handle;
7697            mContainer = new PopupWindow(TextView.this.mContext, null,
7698                    com.android.internal.R.attr.textSelectHandleWindowStyle);
7699            mContainer.setSplitTouchEnabled(true);
7700            mContainer.setClippingEnabled(false);
7701            mHotspotX = mDrawable.getIntrinsicWidth() * 0.5f;
7702            mHotspotY = -mDrawable.getIntrinsicHeight() * 0.2f;
7703        }
7704
7705        @Override
7706        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
7707            setMeasuredDimension(mDrawable.getIntrinsicWidth(),
7708                    mDrawable.getIntrinsicHeight());
7709        }
7710
7711        public void show() {
7712            if (!isPositionInBounds()) {
7713                hide();
7714                return;
7715            }
7716            mContainer.setContentView(this);
7717            final int[] coords = mTempCoords;
7718            TextView.this.getLocationInWindow(coords);
7719            coords[0] += mPositionX;
7720            coords[1] += mPositionY;
7721            mContainer.showAtLocation(TextView.this, 0, coords[0], coords[1]);
7722        }
7723
7724        public void hide() {
7725            mIsDragging = false;
7726            mContainer.dismiss();
7727        }
7728
7729        public boolean isShowing() {
7730            return mContainer.isShowing();
7731        }
7732
7733        private boolean isPositionInBounds() {
7734            final int extendedPaddingTop = getExtendedPaddingTop();
7735            final int extendedPaddingBottom = getExtendedPaddingBottom();
7736            final int compoundPaddingLeft = getCompoundPaddingLeft();
7737            final int compoundPaddingRight = getCompoundPaddingRight();
7738
7739            final TextView hostView = TextView.this;
7740            final int left = 0;
7741            final int right = hostView.getWidth();
7742            final int top = 0;
7743            final int bottom = hostView.getHeight();
7744
7745            final int clipLeft = left + compoundPaddingLeft;
7746            final int clipTop = top + extendedPaddingTop;
7747            final int clipRight = right - compoundPaddingRight;
7748            final int clipBottom = bottom - extendedPaddingBottom;
7749
7750            return mPositionX + mHotspotX >= clipLeft && mPositionX + mHotspotX <= clipRight &&
7751                    mPositionY + mHotspotY >= clipTop && mPositionY + mHotspotY <= clipBottom;
7752        }
7753
7754        private void moveTo(int x, int y) {
7755            mPositionX = x - TextView.this.mScrollX;
7756            mPositionY = y - TextView.this.mScrollY;
7757            if (isPositionInBounds()) {
7758                if (mContainer.isShowing()){
7759                    final int[] coords = mTempCoords;
7760                    TextView.this.getLocationInWindow(coords);
7761                    coords[0] += mPositionX;
7762                    coords[1] += mPositionY;
7763                    mContainer.update(coords[0], coords[1], mRight - mLeft, mBottom - mTop);
7764                } else {
7765                    show();
7766                }
7767            } else {
7768                hide();
7769            }
7770        }
7771
7772        @Override
7773        public void onDraw(Canvas c) {
7774            mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
7775            if (mPositionOnTop) {
7776                c.save();
7777                c.rotate(180, (mRight - mLeft) / 2, (mBottom - mTop) / 2);
7778                mDrawable.draw(c);
7779                c.restore();
7780            } else {
7781                mDrawable.draw(c);
7782            }
7783        }
7784
7785        @Override
7786        public boolean onTouchEvent(MotionEvent ev) {
7787            switch (ev.getActionMasked()) {
7788            case MotionEvent.ACTION_DOWN: {
7789                final float rawX = ev.getRawX();
7790                final float rawY = ev.getRawY();
7791                mOffsetX = rawX - mPositionX;
7792                mOffsetY = rawY - mPositionY;
7793                mIsDragging = true;
7794                break;
7795            }
7796            case MotionEvent.ACTION_MOVE: {
7797                final float rawX = ev.getRawX();
7798                final float rawY = ev.getRawY();
7799                final float newPosX = rawX - mOffsetX + mHotspotX;
7800                final float newPosY = rawY - mOffsetY + mHotspotY;
7801
7802                mController.updatePosition(this, (int) Math.round(newPosX),
7803                        (int) Math.round(newPosY));
7804
7805                break;
7806            }
7807            case MotionEvent.ACTION_UP:
7808            case MotionEvent.ACTION_CANCEL:
7809                mIsDragging = false;
7810            }
7811            return true;
7812        }
7813
7814        public boolean isDragging() {
7815            return mIsDragging;
7816        }
7817
7818        void positionAtCursor(final int offset, boolean bottom) {
7819            final int width = mDrawable.getIntrinsicWidth();
7820            final int height = mDrawable.getIntrinsicHeight();
7821            final int line = mLayout.getLineForOffset(offset);
7822            final int lineTop = mLayout.getLineTop(line);
7823            final int lineBottom = mLayout.getLineBottom(line);
7824
7825            final Rect bounds = sCursorControllerTempRect;
7826            bounds.left = (int) (mLayout.getPrimaryHorizontal(offset) - width / 2.0)
7827                + TextView.this.mScrollX;
7828            bounds.top = (bottom ? lineBottom : lineTop) + TextView.this.mScrollY;
7829
7830            bounds.right = bounds.left + width;
7831            bounds.bottom = bounds.top + height;
7832
7833            convertFromViewportToContentCoordinates(bounds);
7834            moveTo(bounds.left, bounds.top);
7835        }
7836    }
7837
7838    private class InsertionPointCursorController implements CursorController {
7839        private static final int DELAY_BEFORE_FADE_OUT = 4100;
7840
7841        // The cursor controller image
7842        private final HandleView mHandle;
7843
7844        private final Runnable mHider = new Runnable() {
7845            public void run() {
7846                hide();
7847            }
7848        };
7849
7850        InsertionPointCursorController() {
7851            Resources res = mContext.getResources();
7852            mHandle = new HandleView(this, res.getDrawable(mTextSelectHandleRes));
7853        }
7854
7855        public void show() {
7856            updatePosition();
7857            mHandle.show();
7858            hideDelayed(DELAY_BEFORE_FADE_OUT);
7859        }
7860
7861        public void hide() {
7862            mHandle.hide();
7863            TextView.this.removeCallbacks(mHider);
7864        }
7865
7866        private void hideDelayed(int msec) {
7867            TextView.this.removeCallbacks(mHider);
7868            TextView.this.postDelayed(mHider, msec);
7869        }
7870
7871        public boolean isShowing() {
7872            return mHandle.isShowing();
7873        }
7874
7875        public void updatePosition(HandleView handle, int x, int y) {
7876            final int previousOffset = getSelectionStart();
7877            int offset = getHysteresisOffset(x, y, previousOffset);
7878
7879            if (offset != previousOffset) {
7880                Selection.setSelection((Spannable) mText, offset);
7881                updatePosition();
7882            }
7883            hideDelayed(DELAY_BEFORE_FADE_OUT);
7884        }
7885
7886        public void updatePosition() {
7887            final int offset = getSelectionStart();
7888
7889            if (offset < 0) {
7890                // Should never happen, safety check.
7891                Log.w(LOG_TAG, "Update cursor controller position called with no cursor");
7892                hide();
7893                return;
7894            }
7895
7896            mHandle.positionAtCursor(offset, true);
7897        }
7898
7899        public boolean onTouchEvent(MotionEvent ev) {
7900            return false;
7901        }
7902
7903        public void onTouchModeChanged(boolean isInTouchMode) {
7904            if (!isInTouchMode) {
7905                hide();
7906            }
7907        }
7908    }
7909
7910    private class SelectionModifierCursorController implements CursorController {
7911        // The cursor controller images
7912        private HandleView mStartHandle, mEndHandle;
7913        // The offsets of that last touch down event. Remembered to start selection there.
7914        private int mMinTouchOffset, mMaxTouchOffset;
7915        // Whether selection anchors are active
7916        private boolean mIsShowing;
7917
7918        private static final int DELAY_BEFORE_FADE_OUT = 4100;
7919
7920        private final Runnable mHider = new Runnable() {
7921            public void run() {
7922                hide();
7923            }
7924        };
7925
7926        SelectionModifierCursorController() {
7927            Resources res = mContext.getResources();
7928            mStartHandle = new HandleView(this, res.getDrawable(mTextSelectHandleLeftRes));
7929            mEndHandle = new HandleView(this, res.getDrawable(mTextSelectHandleRightRes));
7930        }
7931
7932        public void show() {
7933            mIsShowing = true;
7934            updatePosition();
7935            mStartHandle.show();
7936            mEndHandle.show();
7937            hideInsertionPointCursorController();
7938            hideDelayed(DELAY_BEFORE_FADE_OUT);
7939        }
7940
7941        public void hide() {
7942            mStartHandle.hide();
7943            mEndHandle.hide();
7944            mIsShowing = false;
7945            removeCallbacks(mHider);
7946        }
7947
7948        private void hideDelayed(int delay) {
7949            removeCallbacks(mHider);
7950            postDelayed(mHider, delay);
7951        }
7952
7953        public boolean isShowing() {
7954            return mIsShowing;
7955        }
7956
7957        public void cancelFadeOutAnimation() {
7958            hide();
7959        }
7960
7961        public void updatePosition(HandleView handle, int x, int y) {
7962            int selectionStart = getSelectionStart();
7963            int selectionEnd = getSelectionEnd();
7964
7965            final int previousOffset = handle == mStartHandle ? selectionStart : selectionEnd;
7966            int offset = getHysteresisOffset(x, y, previousOffset);
7967
7968            // Handle the case where start and end are swapped, making sure start <= end
7969            if (handle == mStartHandle) {
7970                if (offset <= selectionEnd) {
7971                    if (selectionStart == offset) {
7972                        return; // no change, no need to redraw;
7973                    }
7974                    selectionStart = offset;
7975                } else {
7976                    selectionStart = selectionEnd;
7977                    selectionEnd = offset;
7978                    HandleView temp = mStartHandle;
7979                    mStartHandle = mEndHandle;
7980                    mEndHandle = temp;
7981                }
7982            } else {
7983                if (offset >= selectionStart) {
7984                    if (selectionEnd == offset) {
7985                        return; // no change, no need to redraw;
7986                    }
7987                    selectionEnd = offset;
7988                } else {
7989                    selectionEnd = selectionStart;
7990                    selectionStart = offset;
7991                    HandleView temp = mStartHandle;
7992                    mStartHandle = mEndHandle;
7993                    mEndHandle = temp;
7994                }
7995            }
7996
7997            Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
7998            updatePosition();
7999        }
8000
8001        public void updatePosition() {
8002            final int selectionStart = getSelectionStart();
8003            final int selectionEnd = getSelectionEnd();
8004
8005            if ((selectionStart < 0) || (selectionEnd < 0)) {
8006                // Should never happen, safety check.
8007                Log.w(LOG_TAG, "Update selection controller position called with no cursor");
8008                hide();
8009                return;
8010            }
8011
8012            boolean oneLineSelection = mLayout.getLineForOffset(selectionStart) ==
8013                    mLayout.getLineForOffset(selectionEnd);
8014            mStartHandle.positionAtCursor(selectionStart, oneLineSelection);
8015            mEndHandle.positionAtCursor(selectionEnd, true);
8016            hideDelayed(DELAY_BEFORE_FADE_OUT);
8017        }
8018
8019        public boolean onTouchEvent(MotionEvent event) {
8020            if (isFocused() && isTextEditable()) {
8021                switch (event.getActionMasked()) {
8022                    case MotionEvent.ACTION_DOWN:
8023                        final int x = (int) event.getX();
8024                        final int y = (int) event.getY();
8025
8026                        // Remember finger down position, to be able to start selection from there
8027                        mMinTouchOffset = mMaxTouchOffset = mLastTouchOffset = getOffset(x, y);
8028
8029                        break;
8030
8031                    case MotionEvent.ACTION_POINTER_DOWN:
8032                    case MotionEvent.ACTION_POINTER_UP:
8033                        // Handle multi-point gestures. Keep min and max offset positions.
8034                        // Only activated for devices that correctly handle multi-touch.
8035                        if (mContext.getPackageManager().hasSystemFeature(
8036                                PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
8037                            updateMinAndMaxOffsets(event);
8038                        }
8039                        break;
8040                }
8041            }
8042            return false;
8043        }
8044
8045        /**
8046         * @param event
8047         */
8048        private void updateMinAndMaxOffsets(MotionEvent event) {
8049            int pointerCount = event.getPointerCount();
8050            for (int index = 0; index < pointerCount; index++) {
8051                final int x = (int) event.getX(index);
8052                final int y = (int) event.getY(index);
8053                int offset = getOffset(x, y);
8054                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
8055                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
8056            }
8057        }
8058
8059        public int getMinTouchOffset() {
8060            return mMinTouchOffset;
8061        }
8062
8063        public int getMaxTouchOffset() {
8064            return mMaxTouchOffset;
8065        }
8066
8067        /**
8068         * @return true iff this controller is currently used to move the selection start.
8069         */
8070        public boolean isSelectionStartDragged() {
8071            return mStartHandle.isDragging();
8072        }
8073
8074        public void onTouchModeChanged(boolean isInTouchMode) {
8075            if (!isInTouchMode) {
8076                hide();
8077            }
8078        }
8079    }
8080
8081    private void hideInsertionPointCursorController() {
8082        if (mInsertionPointCursorController != null) {
8083            mInsertionPointCursorController.hide();
8084        }
8085    }
8086
8087    private void hideControllers() {
8088        hideInsertionPointCursorController();
8089        stopTextSelectionMode();
8090    }
8091
8092    private int getOffsetForHorizontal(int line, int x) {
8093        x -= getTotalPaddingLeft();
8094        // Clamp the position to inside of the view.
8095        x = Math.max(0, x);
8096        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
8097        x += getScrollX();
8098        return getLayout().getOffsetForHorizontal(line, x);
8099    }
8100
8101    /**
8102     * Get the offset character closest to the specified absolute position.
8103     *
8104     * @param x The horizontal absolute position of a point on screen
8105     * @param y The vertical absolute position of a point on screen
8106     * @return the character offset for the character whose position is closest to the specified
8107     *  position. Returns -1 if there is no layout.
8108     *
8109     * @hide
8110     */
8111    public int getOffset(int x, int y) {
8112        if (getLayout() == null) return -1;
8113
8114        y -= getTotalPaddingTop();
8115        // Clamp the position to inside of the view.
8116        y = Math.max(0, y);
8117        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
8118        y += getScrollY();
8119
8120        final int line = getLayout().getLineForVertical(y);
8121        final int offset = getOffsetForHorizontal(line, x);
8122        return offset;
8123    }
8124
8125    int getHysteresisOffset(int x, int y, int previousOffset) {
8126        final Layout layout = getLayout();
8127        if (layout == null) return -1;
8128
8129        y -= getTotalPaddingTop();
8130        // Clamp the position to inside of the view.
8131        y = Math.max(0, y);
8132        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
8133        y += getScrollY();
8134
8135        int line = getLayout().getLineForVertical(y);
8136
8137        final int previousLine = layout.getLineForOffset(previousOffset);
8138        final int previousLineTop = layout.getLineTop(previousLine);
8139        final int previousLineBottom = layout.getLineBottom(previousLine);
8140        final int hysteresisThreshold = (previousLineBottom - previousLineTop) / 6;
8141
8142        // If new line is just before or after previous line and y position is less than
8143        // hysteresisThreshold away from previous line, keep cursor on previous line.
8144        if (((line == previousLine + 1) && ((y - previousLineBottom) < hysteresisThreshold)) ||
8145            ((line == previousLine - 1) && ((previousLineTop - y)    < hysteresisThreshold))) {
8146            line = previousLine;
8147        }
8148
8149        return getOffsetForHorizontal(line, x);
8150    }
8151
8152    @ViewDebug.ExportedProperty
8153    private CharSequence            mText;
8154    private CharSequence            mTransformed;
8155    private BufferType              mBufferType = BufferType.NORMAL;
8156
8157    private int                     mInputType = EditorInfo.TYPE_NULL;
8158    private CharSequence            mHint;
8159    private Layout                  mHintLayout;
8160
8161    private KeyListener             mInput;
8162
8163    private MovementMethod          mMovement;
8164    private TransformationMethod    mTransformation;
8165    private ChangeWatcher           mChangeWatcher;
8166
8167    private ArrayList<TextWatcher>  mListeners = null;
8168
8169    // display attributes
8170    private final TextPaint         mTextPaint;
8171    private boolean                 mUserSetTextScaleX;
8172    private final Paint             mHighlightPaint;
8173    private int                     mHighlightColor = 0xCC475925;
8174    private Layout                  mLayout;
8175
8176    private long                    mShowCursor;
8177    private Blink                   mBlink;
8178    private boolean                 mCursorVisible = true;
8179
8180    // Cursor Controllers. Null when disabled.
8181    private CursorController        mInsertionPointCursorController;
8182    private CursorController        mSelectionModifierCursorController;
8183    private boolean                 mIsInTextSelectionMode = false;
8184    private int                     mLastTouchOffset = -1;
8185    // Created once and shared by different CursorController helper methods.
8186    // Only one cursor controller is active at any time which prevent race conditions.
8187    private static Rect             sCursorControllerTempRect = new Rect();
8188
8189    private boolean                 mSelectAllOnFocus = false;
8190
8191    private int                     mGravity = Gravity.TOP | Gravity.LEFT;
8192    private boolean                 mHorizontallyScrolling;
8193
8194    private int                     mAutoLinkMask;
8195    private boolean                 mLinksClickable = true;
8196
8197    private float                   mSpacingMult = 1;
8198    private float                   mSpacingAdd = 0;
8199
8200    private static final int        LINES = 1;
8201    private static final int        EMS = LINES;
8202    private static final int        PIXELS = 2;
8203
8204    private int                     mMaximum = Integer.MAX_VALUE;
8205    private int                     mMaxMode = LINES;
8206    private int                     mMinimum = 0;
8207    private int                     mMinMode = LINES;
8208
8209    private int                     mMaxWidth = Integer.MAX_VALUE;
8210    private int                     mMaxWidthMode = PIXELS;
8211    private int                     mMinWidth = 0;
8212    private int                     mMinWidthMode = PIXELS;
8213
8214    private boolean                 mSingleLine;
8215    private int                     mDesiredHeightAtMeasure = -1;
8216    private boolean                 mIncludePad = true;
8217
8218    // tmp primitives, so we don't alloc them on each draw
8219    private Path                    mHighlightPath;
8220    private boolean                 mHighlightPathBogus = true;
8221    private static final RectF      sTempRect = new RectF();
8222
8223    // XXX should be much larger
8224    private static final int        VERY_WIDE = 16384;
8225
8226    private static final int        BLINK = 500;
8227
8228    private static final int ANIMATED_SCROLL_GAP = 250;
8229    private long mLastScroll;
8230    private Scroller mScroller = null;
8231
8232    private BoringLayout.Metrics mBoring;
8233    private BoringLayout.Metrics mHintBoring;
8234
8235    private BoringLayout mSavedLayout, mSavedHintLayout;
8236
8237    private static final InputFilter[] NO_FILTERS = new InputFilter[0];
8238    private InputFilter[] mFilters = NO_FILTERS;
8239    private static final Spanned EMPTY_SPANNED = new SpannedString("");
8240}
8241