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