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