TextView.java revision fb81703ab11c653a587b652b90ec3b550f500ccf
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;
4139
4140        if (mSingleLine) {
4141            drawableState = super.onCreateDrawableState(extraSpace);
4142        } else {
4143            drawableState = super.onCreateDrawableState(extraSpace + 1);
4144            mergeDrawableStates(drawableState, MULTILINE_STATE_SET);
4145        }
4146
4147        if (mTextIsSelectable) {
4148            // Disable pressed state, which was introduced when TextView was made clickable.
4149            // Prevents text color change.
4150            // setClickable(false) would have a similar effect, but it also disables focus changes
4151            // and long press actions, which are both needed by text selection.
4152            final int length = drawableState.length;
4153            for (int i = 0; i < length; i++) {
4154                if (drawableState[i] == R.attr.state_pressed) {
4155                    final int[] nonPressedState = new int[length - 1];
4156                    System.arraycopy(drawableState, 0, nonPressedState, 0, i);
4157                    System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1);
4158                    return nonPressedState;
4159                }
4160            }
4161        }
4162
4163        return drawableState;
4164    }
4165
4166    @Override
4167    protected void onDraw(Canvas canvas) {
4168        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return;
4169
4170        restartMarqueeIfNeeded();
4171
4172        // Draw the background for this view
4173        super.onDraw(canvas);
4174
4175        final int compoundPaddingLeft = getCompoundPaddingLeft();
4176        final int compoundPaddingTop = getCompoundPaddingTop();
4177        final int compoundPaddingRight = getCompoundPaddingRight();
4178        final int compoundPaddingBottom = getCompoundPaddingBottom();
4179        final int scrollX = mScrollX;
4180        final int scrollY = mScrollY;
4181        final int right = mRight;
4182        final int left = mLeft;
4183        final int bottom = mBottom;
4184        final int top = mTop;
4185
4186        final Drawables dr = mDrawables;
4187        if (dr != null) {
4188            /*
4189             * Compound, not extended, because the icon is not clipped
4190             * if the text height is smaller.
4191             */
4192
4193            int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop;
4194            int hspace = right - left - compoundPaddingRight - compoundPaddingLeft;
4195
4196            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4197            // Make sure to update invalidateDrawable() when changing this code.
4198            if (dr.mDrawableLeft != null) {
4199                canvas.save();
4200                canvas.translate(scrollX + mPaddingLeft,
4201                                 scrollY + compoundPaddingTop +
4202                                 (vspace - dr.mDrawableHeightLeft) / 2);
4203                dr.mDrawableLeft.draw(canvas);
4204                canvas.restore();
4205            }
4206
4207            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4208            // Make sure to update invalidateDrawable() when changing this code.
4209            if (dr.mDrawableRight != null) {
4210                canvas.save();
4211                canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight,
4212                         scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2);
4213                dr.mDrawableRight.draw(canvas);
4214                canvas.restore();
4215            }
4216
4217            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4218            // Make sure to update invalidateDrawable() when changing this code.
4219            if (dr.mDrawableTop != null) {
4220                canvas.save();
4221                canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2,
4222                        scrollY + mPaddingTop);
4223                dr.mDrawableTop.draw(canvas);
4224                canvas.restore();
4225            }
4226
4227            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4228            // Make sure to update invalidateDrawable() when changing this code.
4229            if (dr.mDrawableBottom != null) {
4230                canvas.save();
4231                canvas.translate(scrollX + compoundPaddingLeft +
4232                        (hspace - dr.mDrawableWidthBottom) / 2,
4233                         scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom);
4234                dr.mDrawableBottom.draw(canvas);
4235                canvas.restore();
4236            }
4237        }
4238
4239        if (mPreDrawState == PREDRAW_DONE) {
4240            final ViewTreeObserver observer = getViewTreeObserver();
4241            if (observer != null) {
4242                observer.removeOnPreDrawListener(this);
4243                mPreDrawState = PREDRAW_NOT_REGISTERED;
4244            }
4245        }
4246
4247        int color = mCurTextColor;
4248
4249        if (mLayout == null) {
4250            assumeLayout();
4251        }
4252
4253        Layout layout = mLayout;
4254        int cursorcolor = color;
4255
4256        if (mHint != null && mText.length() == 0) {
4257            if (mHintTextColor != null) {
4258                color = mCurHintTextColor;
4259            }
4260
4261            layout = mHintLayout;
4262        }
4263
4264        mTextPaint.setColor(color);
4265        if (mCurrentAlpha != 255) {
4266            // If set, the alpha will override the color's alpha. Multiply the alphas.
4267            mTextPaint.setAlpha((mCurrentAlpha * Color.alpha(color)) / 255);
4268        }
4269        mTextPaint.drawableState = getDrawableState();
4270
4271        canvas.save();
4272        /*  Would be faster if we didn't have to do this. Can we chop the
4273            (displayable) text so that we don't need to do this ever?
4274        */
4275
4276        int extendedPaddingTop = getExtendedPaddingTop();
4277        int extendedPaddingBottom = getExtendedPaddingBottom();
4278
4279        float clipLeft = compoundPaddingLeft + scrollX;
4280        float clipTop = extendedPaddingTop + scrollY;
4281        float clipRight = right - left - compoundPaddingRight + scrollX;
4282        float clipBottom = bottom - top - extendedPaddingBottom + scrollY;
4283
4284        if (mShadowRadius != 0) {
4285            clipLeft += Math.min(0, mShadowDx - mShadowRadius);
4286            clipRight += Math.max(0, mShadowDx + mShadowRadius);
4287
4288            clipTop += Math.min(0, mShadowDy - mShadowRadius);
4289            clipBottom += Math.max(0, mShadowDy + mShadowRadius);
4290        }
4291
4292        canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom);
4293
4294        int voffsetText = 0;
4295        int voffsetCursor = 0;
4296
4297        // translate in by our padding
4298        {
4299            /* shortcircuit calling getVerticaOffset() */
4300            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4301                voffsetText = getVerticalOffset(false);
4302                voffsetCursor = getVerticalOffset(true);
4303            }
4304            canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText);
4305        }
4306
4307        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
4308            if (!mSingleLine && getLineCount() == 1 && canMarquee() &&
4309                    (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) {
4310                canvas.translate(mLayout.getLineRight(0) - (mRight - mLeft -
4311                        getCompoundPaddingLeft() - getCompoundPaddingRight()), 0.0f);
4312            }
4313
4314            if (mMarquee != null && mMarquee.isRunning()) {
4315                canvas.translate(-mMarquee.mScroll, 0.0f);
4316            }
4317        }
4318
4319        Path highlight = null;
4320        int selStart = -1, selEnd = -1;
4321
4322        //  If there is no movement method, then there can be no selection.
4323        //  Check that first and attempt to skip everything having to do with
4324        //  the cursor.
4325        //  XXX This is not strictly true -- a program could set the
4326        //  selection manually if it really wanted to.
4327        if (mMovement != null && (isFocused() || isPressed())) {
4328            selStart = getSelectionStart();
4329            selEnd = getSelectionEnd();
4330
4331            if ((mCursorVisible || mTextIsSelectable) && selStart >= 0 && isEnabled()) {
4332                if (mHighlightPath == null)
4333                    mHighlightPath = new Path();
4334
4335                if (selStart == selEnd) {
4336                    if (!mTextIsSelectable &&
4337                            (SystemClock.uptimeMillis() - mShowCursor) % (2 * BLINK) < BLINK) {
4338                        if (mHighlightPathBogus) {
4339                            mHighlightPath.reset();
4340                            mLayout.getCursorPath(selStart, mHighlightPath, mText);
4341                            mHighlightPathBogus = false;
4342                        }
4343
4344                        // XXX should pass to skin instead of drawing directly
4345                        mHighlightPaint.setColor(cursorcolor);
4346                        if (mCurrentAlpha != 255) {
4347                            mHighlightPaint.setAlpha(
4348                                    (mCurrentAlpha * Color.alpha(cursorcolor)) / 255);
4349                        }
4350                        mHighlightPaint.setStyle(Paint.Style.STROKE);
4351
4352                        highlight = mHighlightPath;
4353                    }
4354                } else {
4355                    if (mHighlightPathBogus) {
4356                        mHighlightPath.reset();
4357                        mLayout.getSelectionPath(selStart, selEnd, mHighlightPath);
4358                        mHighlightPathBogus = false;
4359                    }
4360
4361                    // XXX should pass to skin instead of drawing directly
4362                    mHighlightPaint.setColor(mHighlightColor);
4363                    if (mCurrentAlpha != 255) {
4364                        mHighlightPaint.setAlpha(
4365                                (mCurrentAlpha * Color.alpha(mHighlightColor)) / 255);
4366                    }
4367                    mHighlightPaint.setStyle(Paint.Style.FILL);
4368
4369                    highlight = mHighlightPath;
4370                }
4371            }
4372        }
4373
4374        /*  Comment out until we decide what to do about animations
4375        boolean isLinearTextOn = false;
4376        if (currentTransformation != null) {
4377            isLinearTextOn = mTextPaint.isLinearTextOn();
4378            Matrix m = currentTransformation.getMatrix();
4379            if (!m.isIdentity()) {
4380                // mTextPaint.setLinearTextOn(true);
4381            }
4382        }
4383        */
4384
4385        final InputMethodState ims = mInputMethodState;
4386        final int cursorOffsetVertical = voffsetCursor - voffsetText;
4387        if (ims != null && ims.mBatchEditNesting == 0) {
4388            InputMethodManager imm = InputMethodManager.peekInstance();
4389            if (imm != null) {
4390                if (imm.isActive(this)) {
4391                    boolean reported = false;
4392                    if (ims.mContentChanged || ims.mSelectionModeChanged) {
4393                        // We are in extract mode and the content has changed
4394                        // in some way... just report complete new text to the
4395                        // input method.
4396                        reported = reportExtractedText();
4397                    }
4398                    if (!reported && highlight != null) {
4399                        int candStart = -1;
4400                        int candEnd = -1;
4401                        if (mText instanceof Spannable) {
4402                            Spannable sp = (Spannable)mText;
4403                            candStart = EditableInputConnection.getComposingSpanStart(sp);
4404                            candEnd = EditableInputConnection.getComposingSpanEnd(sp);
4405                        }
4406                        imm.updateSelection(this, selStart, selEnd, candStart, candEnd);
4407                    }
4408                }
4409
4410                if (imm.isWatchingCursor(this) && highlight != null) {
4411                    highlight.computeBounds(ims.mTmpRectF, true);
4412                    ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0;
4413
4414                    canvas.getMatrix().mapPoints(ims.mTmpOffset);
4415                    ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]);
4416
4417                    ims.mTmpRectF.offset(0, cursorOffsetVertical);
4418
4419                    ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5),
4420                            (int)(ims.mTmpRectF.top + 0.5),
4421                            (int)(ims.mTmpRectF.right + 0.5),
4422                            (int)(ims.mTmpRectF.bottom + 0.5));
4423
4424                    imm.updateCursor(this,
4425                            ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top,
4426                            ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom);
4427                }
4428            }
4429        }
4430
4431        if (mCorrectionHighlighter != null) {
4432            mCorrectionHighlighter.draw(canvas, cursorOffsetVertical);
4433        }
4434
4435        layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
4436
4437        if (mMarquee != null && mMarquee.shouldDrawGhost()) {
4438            canvas.translate((int) mMarquee.getGhostOffset(), 0.0f);
4439            layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
4440        }
4441
4442        /*  Comment out until we decide what to do about animations
4443        if (currentTransformation != null) {
4444            mTextPaint.setLinearTextOn(isLinearTextOn);
4445        }
4446        */
4447
4448        canvas.restore();
4449
4450        updateCursorControllerPositions();
4451    }
4452
4453    /**
4454     * Update the positions of the CursorControllers.  Needed by WebTextView,
4455     * which does not draw.
4456     * @hide
4457     */
4458    protected void updateCursorControllerPositions() {
4459        // No need to create the controllers if they were not already
4460        if (mInsertionPointCursorController != null &&
4461                mInsertionPointCursorController.isShowing()) {
4462            mInsertionPointCursorController.updatePosition();
4463        }
4464        if (mSelectionModifierCursorController != null &&
4465                mSelectionModifierCursorController.isShowing()) {
4466            mSelectionModifierCursorController.updatePosition();
4467        }
4468    }
4469
4470    @Override
4471    public void getFocusedRect(Rect r) {
4472        if (mLayout == null) {
4473            super.getFocusedRect(r);
4474            return;
4475        }
4476
4477        int sel = getSelectionEnd();
4478        if (sel < 0) {
4479            super.getFocusedRect(r);
4480            return;
4481        }
4482
4483        int line = mLayout.getLineForOffset(sel);
4484        r.top = mLayout.getLineTop(line);
4485        r.bottom = mLayout.getLineBottom(line);
4486
4487        r.left = (int) mLayout.getPrimaryHorizontal(sel);
4488        r.right = r.left + 1;
4489
4490        // Adjust for padding and gravity.
4491        int paddingLeft = getCompoundPaddingLeft();
4492        int paddingTop = getExtendedPaddingTop();
4493        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4494            paddingTop += getVerticalOffset(false);
4495        }
4496        r.offset(paddingLeft, paddingTop);
4497    }
4498
4499    /**
4500     * Return the number of lines of text, or 0 if the internal Layout has not
4501     * been built.
4502     */
4503    public int getLineCount() {
4504        return mLayout != null ? mLayout.getLineCount() : 0;
4505    }
4506
4507    /**
4508     * Return the baseline for the specified line (0...getLineCount() - 1)
4509     * If bounds is not null, return the top, left, right, bottom extents
4510     * of the specified line in it. If the internal Layout has not been built,
4511     * return 0 and set bounds to (0, 0, 0, 0)
4512     * @param line which line to examine (0..getLineCount() - 1)
4513     * @param bounds Optional. If not null, it returns the extent of the line
4514     * @return the Y-coordinate of the baseline
4515     */
4516    public int getLineBounds(int line, Rect bounds) {
4517        if (mLayout == null) {
4518            if (bounds != null) {
4519                bounds.set(0, 0, 0, 0);
4520            }
4521            return 0;
4522        }
4523        else {
4524            int baseline = mLayout.getLineBounds(line, bounds);
4525
4526            int voffset = getExtendedPaddingTop();
4527            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4528                voffset += getVerticalOffset(true);
4529            }
4530            if (bounds != null) {
4531                bounds.offset(getCompoundPaddingLeft(), voffset);
4532            }
4533            return baseline + voffset;
4534        }
4535    }
4536
4537    @Override
4538    public int getBaseline() {
4539        if (mLayout == null) {
4540            return super.getBaseline();
4541        }
4542
4543        int voffset = 0;
4544        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4545            voffset = getVerticalOffset(true);
4546        }
4547
4548        return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0);
4549    }
4550
4551    @Override
4552    public boolean onKeyDown(int keyCode, KeyEvent event) {
4553        int which = doKeyDown(keyCode, event, null);
4554        if (which == 0) {
4555            // Go through default dispatching.
4556            return super.onKeyDown(keyCode, event);
4557        }
4558
4559        return true;
4560    }
4561
4562    @Override
4563    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4564        KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN);
4565
4566        int which = doKeyDown(keyCode, down, event);
4567        if (which == 0) {
4568            // Go through default dispatching.
4569            return super.onKeyMultiple(keyCode, repeatCount, event);
4570        }
4571        if (which == -1) {
4572            // Consumed the whole thing.
4573            return true;
4574        }
4575
4576        repeatCount--;
4577
4578        // We are going to dispatch the remaining events to either the input
4579        // or movement method.  To do this, we will just send a repeated stream
4580        // of down and up events until we have done the complete repeatCount.
4581        // It would be nice if those interfaces had an onKeyMultiple() method,
4582        // but adding that is a more complicated change.
4583        KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP);
4584        if (which == 1) {
4585            mInput.onKeyUp(this, (Editable)mText, keyCode, up);
4586            while (--repeatCount > 0) {
4587                mInput.onKeyDown(this, (Editable)mText, keyCode, down);
4588                mInput.onKeyUp(this, (Editable)mText, keyCode, up);
4589            }
4590            if (mError != null && !mErrorWasChanged) {
4591                setError(null, null);
4592            }
4593
4594        } else if (which == 2) {
4595            mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
4596            while (--repeatCount > 0) {
4597                mMovement.onKeyDown(this, (Spannable)mText, keyCode, down);
4598                mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
4599            }
4600        }
4601
4602        return true;
4603    }
4604
4605    /**
4606     * Returns true if pressing ENTER in this field advances focus instead
4607     * of inserting the character.  This is true mostly in single-line fields,
4608     * but also in mail addresses and subjects which will display on multiple
4609     * lines but where it doesn't make sense to insert newlines.
4610     */
4611    private boolean shouldAdvanceFocusOnEnter() {
4612        if (mInput == null) {
4613            return false;
4614        }
4615
4616        if (mSingleLine) {
4617            return true;
4618        }
4619
4620        if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
4621            int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION;
4622            if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
4623                    || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) {
4624                return true;
4625            }
4626        }
4627
4628        return false;
4629    }
4630
4631    /**
4632     * Returns true if pressing TAB in this field advances focus instead
4633     * of inserting the character.  Insert tabs only in multi-line editors.
4634     */
4635    private boolean shouldAdvanceFocusOnTab() {
4636        if (mInput != null && !mSingleLine) {
4637            if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
4638                int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION;
4639                if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE
4640                        || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) {
4641                    return false;
4642                }
4643            }
4644        }
4645        return true;
4646    }
4647
4648    private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) {
4649        if (!isEnabled()) {
4650            return 0;
4651        }
4652
4653        switch (keyCode) {
4654            case KeyEvent.KEYCODE_ENTER:
4655                mEnterKeyIsDown = true;
4656                if (event.hasNoModifiers()) {
4657                    // When mInputContentType is set, we know that we are
4658                    // running in a "modern" cupcake environment, so don't need
4659                    // to worry about the application trying to capture
4660                    // enter key events.
4661                    if (mInputContentType != null) {
4662                        // If there is an action listener, given them a
4663                        // chance to consume the event.
4664                        if (mInputContentType.onEditorActionListener != null &&
4665                                mInputContentType.onEditorActionListener.onEditorAction(
4666                                this, EditorInfo.IME_NULL, event)) {
4667                            mInputContentType.enterDown = true;
4668                            // We are consuming the enter key for them.
4669                            return -1;
4670                        }
4671                    }
4672
4673                    // If our editor should move focus when enter is pressed, or
4674                    // this is a generated event from an IME action button, then
4675                    // don't let it be inserted into the text.
4676                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
4677                            || shouldAdvanceFocusOnEnter()) {
4678                        if (mOnClickListener != null) {
4679                            return 0;
4680                        }
4681                        return -1;
4682                    }
4683                }
4684                break;
4685
4686            case KeyEvent.KEYCODE_DPAD_CENTER:
4687                mDPadCenterIsDown = true;
4688                if (event.hasNoModifiers()) {
4689                    if (shouldAdvanceFocusOnEnter()) {
4690                        return 0;
4691                    }
4692                }
4693                break;
4694
4695            case KeyEvent.KEYCODE_TAB:
4696                if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
4697                    if (shouldAdvanceFocusOnTab()) {
4698                        return 0;
4699                    }
4700                }
4701                break;
4702
4703                // Has to be done on key down (and not on key up) to correctly be intercepted.
4704            case KeyEvent.KEYCODE_BACK:
4705                if (mSelectionActionMode != null) {
4706                    stopSelectionActionMode();
4707                    return -1;
4708                }
4709                break;
4710        }
4711
4712        if (mInput != null) {
4713            /*
4714             * Keep track of what the error was before doing the input
4715             * so that if an input filter changed the error, we leave
4716             * that error showing.  Otherwise, we take down whatever
4717             * error was showing when the user types something.
4718             */
4719            mErrorWasChanged = false;
4720
4721            boolean doDown = true;
4722            if (otherEvent != null) {
4723                try {
4724                    beginBatchEdit();
4725                    boolean handled = mInput.onKeyOther(this, (Editable) mText,
4726                            otherEvent);
4727                    if (mError != null && !mErrorWasChanged) {
4728                        setError(null, null);
4729                    }
4730                    doDown = false;
4731                    if (handled) {
4732                        return -1;
4733                    }
4734                } catch (AbstractMethodError e) {
4735                    // onKeyOther was added after 1.0, so if it isn't
4736                    // implemented we need to try to dispatch as a regular down.
4737                } finally {
4738                    endBatchEdit();
4739                }
4740            }
4741
4742            if (doDown) {
4743                beginBatchEdit();
4744                if (mInput.onKeyDown(this, (Editable) mText, keyCode, event)) {
4745                    endBatchEdit();
4746                    if (mError != null && !mErrorWasChanged) {
4747                        setError(null, null);
4748                    }
4749                    return 1;
4750                }
4751                endBatchEdit();
4752            }
4753        }
4754
4755        // bug 650865: sometimes we get a key event before a layout.
4756        // don't try to move around if we don't know the layout.
4757
4758        if (mMovement != null && mLayout != null) {
4759            boolean doDown = true;
4760            if (otherEvent != null) {
4761                try {
4762                    boolean handled = mMovement.onKeyOther(this, (Spannable) mText,
4763                            otherEvent);
4764                    doDown = false;
4765                    if (handled) {
4766                        return -1;
4767                    }
4768                } catch (AbstractMethodError e) {
4769                    // onKeyOther was added after 1.0, so if it isn't
4770                    // implemented we need to try to dispatch as a regular down.
4771                }
4772            }
4773            if (doDown) {
4774                if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event))
4775                    return 2;
4776            }
4777        }
4778
4779        return 0;
4780    }
4781
4782    @Override
4783    public boolean onKeyUp(int keyCode, KeyEvent event) {
4784        if (!isEnabled()) {
4785            return super.onKeyUp(keyCode, event);
4786        }
4787
4788        hideControllers();
4789
4790        switch (keyCode) {
4791            case KeyEvent.KEYCODE_DPAD_CENTER:
4792                mDPadCenterIsDown = false;
4793                if (event.hasNoModifiers()) {
4794                    /*
4795                     * If there is a click listener, just call through to
4796                     * super, which will invoke it.
4797                     *
4798                     * If there isn't a click listener, try to show the soft
4799                     * input method.  (It will also
4800                     * call performClick(), but that won't do anything in
4801                     * this case.)
4802                     */
4803                    if (mOnClickListener == null) {
4804                        if (mMovement != null && mText instanceof Editable
4805                                && mLayout != null && onCheckIsTextEditor()) {
4806                            InputMethodManager imm = (InputMethodManager)
4807                                    getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
4808                            imm.showSoftInput(this, 0);
4809                        }
4810                    }
4811                }
4812                return super.onKeyUp(keyCode, event);
4813
4814            case KeyEvent.KEYCODE_ENTER:
4815                mEnterKeyIsDown = false;
4816                if (event.hasNoModifiers()) {
4817                    if (mInputContentType != null
4818                            && mInputContentType.onEditorActionListener != null
4819                            && mInputContentType.enterDown) {
4820                        mInputContentType.enterDown = false;
4821                        if (mInputContentType.onEditorActionListener.onEditorAction(
4822                                this, EditorInfo.IME_NULL, event)) {
4823                            return true;
4824                        }
4825                    }
4826
4827                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
4828                            || shouldAdvanceFocusOnEnter()) {
4829                        /*
4830                         * If there is a click listener, just call through to
4831                         * super, which will invoke it.
4832                         *
4833                         * If there isn't a click listener, try to advance focus,
4834                         * but still call through to super, which will reset the
4835                         * pressed state and longpress state.  (It will also
4836                         * call performClick(), but that won't do anything in
4837                         * this case.)
4838                         */
4839                        if (mOnClickListener == null) {
4840                            View v = focusSearch(FOCUS_DOWN);
4841
4842                            if (v != null) {
4843                                if (!v.requestFocus(FOCUS_DOWN)) {
4844                                    throw new IllegalStateException(
4845                                            "focus search returned a view " +
4846                                            "that wasn't able to take focus!");
4847                                }
4848
4849                                /*
4850                                 * Return true because we handled the key; super
4851                                 * will return false because there was no click
4852                                 * listener.
4853                                 */
4854                                super.onKeyUp(keyCode, event);
4855                                return true;
4856                            } else if ((event.getFlags()
4857                                    & KeyEvent.FLAG_EDITOR_ACTION) != 0) {
4858                                // No target for next focus, but make sure the IME
4859                                // if this came from it.
4860                                InputMethodManager imm = InputMethodManager.peekInstance();
4861                                if (imm != null) {
4862                                    imm.hideSoftInputFromWindow(getWindowToken(), 0);
4863                                }
4864                            }
4865                        }
4866                    }
4867                    return super.onKeyUp(keyCode, event);
4868                }
4869                break;
4870        }
4871
4872        if (mInput != null)
4873            if (mInput.onKeyUp(this, (Editable) mText, keyCode, event))
4874                return true;
4875
4876        if (mMovement != null && mLayout != null)
4877            if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event))
4878                return true;
4879
4880        return super.onKeyUp(keyCode, event);
4881    }
4882
4883    @Override public boolean onCheckIsTextEditor() {
4884        return mInputType != EditorInfo.TYPE_NULL;
4885    }
4886
4887    @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4888        if (onCheckIsTextEditor() && isEnabled()) {
4889            if (mInputMethodState == null) {
4890                mInputMethodState = new InputMethodState();
4891            }
4892            outAttrs.inputType = mInputType;
4893            if (mInputContentType != null) {
4894                outAttrs.imeOptions = mInputContentType.imeOptions;
4895                outAttrs.privateImeOptions = mInputContentType.privateImeOptions;
4896                outAttrs.actionLabel = mInputContentType.imeActionLabel;
4897                outAttrs.actionId = mInputContentType.imeActionId;
4898                outAttrs.extras = mInputContentType.extras;
4899            } else {
4900                outAttrs.imeOptions = EditorInfo.IME_NULL;
4901            }
4902            if (focusSearch(FOCUS_DOWN) != null) {
4903                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT;
4904            }
4905            if (focusSearch(FOCUS_UP) != null) {
4906                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS;
4907            }
4908            if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION)
4909                    == EditorInfo.IME_ACTION_UNSPECIFIED) {
4910                if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) {
4911                    // An action has not been set, but the enter key will move to
4912                    // the next focus, so set the action to that.
4913                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT;
4914                } else {
4915                    // An action has not been set, and there is no focus to move
4916                    // to, so let's just supply a "done" action.
4917                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
4918                }
4919                if (!shouldAdvanceFocusOnEnter()) {
4920                    outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
4921                }
4922            }
4923            if (isMultilineInputType(outAttrs.inputType)) {
4924                // Multi-line text editors should always show an enter key.
4925                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
4926            }
4927            outAttrs.hintText = mHint;
4928            if (mText instanceof Editable) {
4929                InputConnection ic = new EditableInputConnection(this);
4930                outAttrs.initialSelStart = getSelectionStart();
4931                outAttrs.initialSelEnd = getSelectionEnd();
4932                outAttrs.initialCapsMode = ic.getCursorCapsMode(mInputType);
4933                return ic;
4934            }
4935        }
4936        return null;
4937    }
4938
4939    /**
4940     * If this TextView contains editable content, extract a portion of it
4941     * based on the information in <var>request</var> in to <var>outText</var>.
4942     * @return Returns true if the text was successfully extracted, else false.
4943     */
4944    public boolean extractText(ExtractedTextRequest request,
4945            ExtractedText outText) {
4946        return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN,
4947                EXTRACT_UNKNOWN, outText);
4948    }
4949
4950    static final int EXTRACT_NOTHING = -2;
4951    static final int EXTRACT_UNKNOWN = -1;
4952
4953    boolean extractTextInternal(ExtractedTextRequest request,
4954            int partialStartOffset, int partialEndOffset, int delta,
4955            ExtractedText outText) {
4956        final CharSequence content = mText;
4957        if (content != null) {
4958            if (partialStartOffset != EXTRACT_NOTHING) {
4959                final int N = content.length();
4960                if (partialStartOffset < 0) {
4961                    outText.partialStartOffset = outText.partialEndOffset = -1;
4962                    partialStartOffset = 0;
4963                    partialEndOffset = N;
4964                } else {
4965                    // Now use the delta to determine the actual amount of text
4966                    // we need.
4967                    partialEndOffset += delta;
4968                    // Adjust offsets to ensure we contain full spans.
4969                    if (content instanceof Spanned) {
4970                        Spanned spanned = (Spanned)content;
4971                        Object[] spans = spanned.getSpans(partialStartOffset,
4972                                partialEndOffset, ParcelableSpan.class);
4973                        int i = spans.length;
4974                        while (i > 0) {
4975                            i--;
4976                            int j = spanned.getSpanStart(spans[i]);
4977                            if (j < partialStartOffset) partialStartOffset = j;
4978                            j = spanned.getSpanEnd(spans[i]);
4979                            if (j > partialEndOffset) partialEndOffset = j;
4980                        }
4981                    }
4982                    outText.partialStartOffset = partialStartOffset;
4983                    outText.partialEndOffset = partialEndOffset - delta;
4984
4985                    if (partialStartOffset > N) {
4986                        partialStartOffset = N;
4987                    } else if (partialStartOffset < 0) {
4988                        partialStartOffset = 0;
4989                    }
4990                    if (partialEndOffset > N) {
4991                        partialEndOffset = N;
4992                    } else if (partialEndOffset < 0) {
4993                        partialEndOffset = 0;
4994                    }
4995                }
4996                if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) {
4997                    outText.text = content.subSequence(partialStartOffset,
4998                            partialEndOffset);
4999                } else {
5000                    outText.text = TextUtils.substring(content, partialStartOffset,
5001                            partialEndOffset);
5002                }
5003            } else {
5004                outText.partialStartOffset = 0;
5005                outText.partialEndOffset = 0;
5006                outText.text = "";
5007            }
5008            outText.flags = 0;
5009            if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) {
5010                outText.flags |= ExtractedText.FLAG_SELECTING;
5011            }
5012            if (mSingleLine) {
5013                outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
5014            }
5015            outText.startOffset = 0;
5016            outText.selectionStart = getSelectionStart();
5017            outText.selectionEnd = getSelectionEnd();
5018            return true;
5019        }
5020        return false;
5021    }
5022
5023    boolean reportExtractedText() {
5024        final InputMethodState ims = mInputMethodState;
5025        if (ims != null) {
5026            final boolean contentChanged = ims.mContentChanged;
5027            if (contentChanged || ims.mSelectionModeChanged) {
5028                ims.mContentChanged = false;
5029                ims.mSelectionModeChanged = false;
5030                final ExtractedTextRequest req = mInputMethodState.mExtracting;
5031                if (req != null) {
5032                    InputMethodManager imm = InputMethodManager.peekInstance();
5033                    if (imm != null) {
5034                        if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start="
5035                                + ims.mChangedStart + " end=" + ims.mChangedEnd
5036                                + " delta=" + ims.mChangedDelta);
5037                        if (ims.mChangedStart < 0 && !contentChanged) {
5038                            ims.mChangedStart = EXTRACT_NOTHING;
5039                        }
5040                        if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd,
5041                                ims.mChangedDelta, ims.mTmpExtracted)) {
5042                            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start="
5043                                    + ims.mTmpExtracted.partialStartOffset
5044                                    + " end=" + ims.mTmpExtracted.partialEndOffset
5045                                    + ": " + ims.mTmpExtracted.text);
5046                            imm.updateExtractedText(this, req.token,
5047                                    mInputMethodState.mTmpExtracted);
5048                            ims.mChangedStart = EXTRACT_UNKNOWN;
5049                            ims.mChangedEnd = EXTRACT_UNKNOWN;
5050                            ims.mChangedDelta = 0;
5051                            ims.mContentChanged = false;
5052                            return true;
5053                        }
5054                    }
5055                }
5056            }
5057        }
5058        return false;
5059    }
5060
5061    /**
5062     * This is used to remove all style-impacting spans from text before new
5063     * extracted text is being replaced into it, so that we don't have any
5064     * lingering spans applied during the replace.
5065     */
5066    static void removeParcelableSpans(Spannable spannable, int start, int end) {
5067        Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class);
5068        int i = spans.length;
5069        while (i > 0) {
5070            i--;
5071            spannable.removeSpan(spans[i]);
5072        }
5073    }
5074
5075    /**
5076     * Apply to this text view the given extracted text, as previously
5077     * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}.
5078     */
5079    public void setExtractedText(ExtractedText text) {
5080        Editable content = getEditableText();
5081        if (text.text != null) {
5082            if (content == null) {
5083                setText(text.text, TextView.BufferType.EDITABLE);
5084            } else if (text.partialStartOffset < 0) {
5085                removeParcelableSpans(content, 0, content.length());
5086                content.replace(0, content.length(), text.text);
5087            } else {
5088                final int N = content.length();
5089                int start = text.partialStartOffset;
5090                if (start > N) start = N;
5091                int end = text.partialEndOffset;
5092                if (end > N) end = N;
5093                removeParcelableSpans(content, start, end);
5094                content.replace(start, end, text.text);
5095            }
5096        }
5097
5098        // Now set the selection position...  make sure it is in range, to
5099        // avoid crashes.  If this is a partial update, it is possible that
5100        // the underlying text may have changed, causing us problems here.
5101        // Also we just don't want to trust clients to do the right thing.
5102        Spannable sp = (Spannable)getText();
5103        final int N = sp.length();
5104        int start = text.selectionStart;
5105        if (start < 0) start = 0;
5106        else if (start > N) start = N;
5107        int end = text.selectionEnd;
5108        if (end < 0) end = 0;
5109        else if (end > N) end = N;
5110        Selection.setSelection(sp, start, end);
5111
5112        // Finally, update the selection mode.
5113        if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) {
5114            MetaKeyKeyListener.startSelecting(this, sp);
5115        } else {
5116            MetaKeyKeyListener.stopSelecting(this, sp);
5117        }
5118    }
5119
5120    /**
5121     * @hide
5122     */
5123    public void setExtracting(ExtractedTextRequest req) {
5124        if (mInputMethodState != null) {
5125            mInputMethodState.mExtracting = req;
5126        }
5127        // This stops a possible text selection mode. Maybe not intended.
5128        hideControllers();
5129    }
5130
5131    /**
5132     * Called by the framework in response to a text completion from
5133     * the current input method, provided by it calling
5134     * {@link InputConnection#commitCompletion
5135     * InputConnection.commitCompletion()}.  The default implementation does
5136     * nothing; text views that are supporting auto-completion should override
5137     * this to do their desired behavior.
5138     *
5139     * @param text The auto complete text the user has selected.
5140     */
5141    public void onCommitCompletion(CompletionInfo text) {
5142    }
5143
5144    /**
5145     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
5146     * a dictionnary) from the current input method, provided by it calling
5147     * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
5148     * implementation flashes the background of the corrected word to provide feedback to the user.
5149     *
5150     * @param info The auto correct info about the text that was corrected.
5151     */
5152    public void onCommitCorrection(CorrectionInfo info) {
5153        if (mCorrectionHighlighter == null) {
5154            mCorrectionHighlighter = new CorrectionHighlighter();
5155        } else {
5156            mCorrectionHighlighter.invalidate(false);
5157        }
5158
5159        mCorrectionHighlighter.highlight(info);
5160    }
5161
5162    private class CorrectionHighlighter {
5163        private final Path mPath = new Path();
5164        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
5165        private int mStart, mEnd;
5166        private long mFadingStartTime;
5167        private final static int FADE_OUT_DURATION = 400;
5168
5169        public CorrectionHighlighter() {
5170            mPaint.setCompatibilityScaling(getResources().getCompatibilityInfo().applicationScale);
5171            mPaint.setStyle(Paint.Style.FILL);
5172        }
5173
5174        public void highlight(CorrectionInfo info) {
5175            mStart = info.getOffset();
5176            mEnd = mStart + info.getNewText().length();
5177            mFadingStartTime = SystemClock.uptimeMillis();
5178
5179            if (mStart < 0 || mEnd < 0) {
5180                stopAnimation();
5181            }
5182        }
5183
5184        public void draw(Canvas canvas, int cursorOffsetVertical) {
5185            if (updatePath() && updatePaint()) {
5186                if (cursorOffsetVertical != 0) {
5187                    canvas.translate(0, cursorOffsetVertical);
5188                }
5189
5190                canvas.drawPath(mPath, mPaint);
5191
5192                if (cursorOffsetVertical != 0) {
5193                    canvas.translate(0, -cursorOffsetVertical);
5194                }
5195                invalidate(true);
5196            } else {
5197                stopAnimation();
5198                invalidate(false);
5199            }
5200        }
5201
5202        private boolean updatePaint() {
5203            final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
5204            if (duration > FADE_OUT_DURATION) return false;
5205
5206            final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
5207            final int highlightColorAlpha = Color.alpha(mHighlightColor);
5208            final int color = (mHighlightColor & 0x00FFFFFF) +
5209                    ((int) (highlightColorAlpha * coef) << 24);
5210            mPaint.setColor(color);
5211            return true;
5212        }
5213
5214        private boolean updatePath() {
5215            final Layout layout = TextView.this.mLayout;
5216            if (layout == null) return false;
5217
5218            // Update in case text is edited while the animation is run
5219            final int length = mText.length();
5220            int start = Math.min(length, mStart);
5221            int end = Math.min(length, mEnd);
5222
5223            mPath.reset();
5224            TextView.this.mLayout.getSelectionPath(start, end, mPath);
5225            return true;
5226        }
5227
5228        private void invalidate(boolean delayed) {
5229            if (TextView.this.mLayout == null) return;
5230
5231            synchronized (sTempRect) {
5232                mPath.computeBounds(sTempRect, false);
5233
5234                int left = getCompoundPaddingLeft();
5235                int top = getExtendedPaddingTop() + getVerticalOffset(true);
5236
5237                if (delayed) {
5238                    TextView.this.postInvalidateDelayed(16, // 60 Hz update
5239                            left + (int) sTempRect.left, top + (int) sTempRect.top,
5240                            left + (int) sTempRect.right, top + (int) sTempRect.bottom);
5241                } else {
5242                    TextView.this.postInvalidate((int) sTempRect.left, (int) sTempRect.top,
5243                            (int) sTempRect.right, (int) sTempRect.bottom);
5244                }
5245            }
5246        }
5247
5248        private void stopAnimation() {
5249            TextView.this.mCorrectionHighlighter = null;
5250        }
5251    }
5252
5253    public void beginBatchEdit() {
5254        mInBatchEditControllers = true;
5255        final InputMethodState ims = mInputMethodState;
5256        if (ims != null) {
5257            int nesting = ++ims.mBatchEditNesting;
5258            if (nesting == 1) {
5259                ims.mCursorChanged = false;
5260                ims.mChangedDelta = 0;
5261                if (ims.mContentChanged) {
5262                    // We already have a pending change from somewhere else,
5263                    // so turn this into a full update.
5264                    ims.mChangedStart = 0;
5265                    ims.mChangedEnd = mText.length();
5266                } else {
5267                    ims.mChangedStart = EXTRACT_UNKNOWN;
5268                    ims.mChangedEnd = EXTRACT_UNKNOWN;
5269                    ims.mContentChanged = false;
5270                }
5271                onBeginBatchEdit();
5272            }
5273        }
5274    }
5275
5276    public void endBatchEdit() {
5277        mInBatchEditControllers = false;
5278        final InputMethodState ims = mInputMethodState;
5279        if (ims != null) {
5280            int nesting = --ims.mBatchEditNesting;
5281            if (nesting == 0) {
5282                finishBatchEdit(ims);
5283            }
5284        }
5285    }
5286
5287    void ensureEndedBatchEdit() {
5288        final InputMethodState ims = mInputMethodState;
5289        if (ims != null && ims.mBatchEditNesting != 0) {
5290            ims.mBatchEditNesting = 0;
5291            finishBatchEdit(ims);
5292        }
5293    }
5294
5295    void finishBatchEdit(final InputMethodState ims) {
5296        onEndBatchEdit();
5297
5298        if (ims.mContentChanged || ims.mSelectionModeChanged) {
5299            updateAfterEdit();
5300            reportExtractedText();
5301        } else if (ims.mCursorChanged) {
5302            // Cheezy way to get us to report the current cursor location.
5303            invalidateCursor();
5304        }
5305    }
5306
5307    void updateAfterEdit() {
5308        invalidate();
5309        int curs = getSelectionStart();
5310
5311        if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) ==
5312                             Gravity.BOTTOM) {
5313            registerForPreDraw();
5314        }
5315
5316        if (curs >= 0) {
5317            mHighlightPathBogus = true;
5318
5319            if (isFocused()) {
5320                mShowCursor = SystemClock.uptimeMillis();
5321                makeBlink();
5322            }
5323        }
5324
5325        checkForResize();
5326    }
5327
5328    /**
5329     * Called by the framework in response to a request to begin a batch
5330     * of edit operations through a call to link {@link #beginBatchEdit()}.
5331     */
5332    public void onBeginBatchEdit() {
5333    }
5334
5335    /**
5336     * Called by the framework in response to a request to end a batch
5337     * of edit operations through a call to link {@link #endBatchEdit}.
5338     */
5339    public void onEndBatchEdit() {
5340    }
5341
5342    /**
5343     * Called by the framework in response to a private command from the
5344     * current method, provided by it calling
5345     * {@link InputConnection#performPrivateCommand
5346     * InputConnection.performPrivateCommand()}.
5347     *
5348     * @param action The action name of the command.
5349     * @param data Any additional data for the command.  This may be null.
5350     * @return Return true if you handled the command, else false.
5351     */
5352    public boolean onPrivateIMECommand(String action, Bundle data) {
5353        return false;
5354    }
5355
5356    private void nullLayouts() {
5357        if (mLayout instanceof BoringLayout && mSavedLayout == null) {
5358            mSavedLayout = (BoringLayout) mLayout;
5359        }
5360        if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) {
5361            mSavedHintLayout = (BoringLayout) mHintLayout;
5362        }
5363
5364        mLayout = mHintLayout = null;
5365
5366        // Since it depends on the value of mLayout
5367        prepareCursorControllers();
5368    }
5369
5370    /**
5371     * Make a new Layout based on the already-measured size of the view,
5372     * on the assumption that it was measured correctly at some point.
5373     */
5374    private void assumeLayout() {
5375        int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5376
5377        if (width < 1) {
5378            width = 0;
5379        }
5380
5381        int physicalWidth = width;
5382
5383        if (mHorizontallyScrolling) {
5384            width = VERY_WIDE;
5385        }
5386
5387        makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING,
5388                      physicalWidth, false);
5389    }
5390
5391    /**
5392     * The width passed in is now the desired layout width,
5393     * not the full view width with padding.
5394     * {@hide}
5395     */
5396    protected void makeNewLayout(int w, int hintWidth,
5397                                 BoringLayout.Metrics boring,
5398                                 BoringLayout.Metrics hintBoring,
5399                                 int ellipsisWidth, boolean bringIntoView) {
5400        stopMarquee();
5401
5402        mHighlightPathBogus = true;
5403
5404        if (w < 0) {
5405            w = 0;
5406        }
5407        if (hintWidth < 0) {
5408            hintWidth = 0;
5409        }
5410
5411        Layout.Alignment alignment;
5412        switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
5413            case Gravity.CENTER_HORIZONTAL:
5414                alignment = Layout.Alignment.ALIGN_CENTER;
5415                break;
5416
5417            case Gravity.RIGHT:
5418                // Note, Layout resolves ALIGN_OPPOSITE to left or
5419                // right based on the paragraph direction.
5420                alignment = Layout.Alignment.ALIGN_OPPOSITE;
5421                break;
5422
5423            default:
5424                alignment = Layout.Alignment.ALIGN_NORMAL;
5425        }
5426
5427        boolean shouldEllipsize = mEllipsize != null && mInput == null;
5428
5429        if (mText instanceof Spannable) {
5430            mLayout = new DynamicLayout(mText, mTransformed, mTextPaint, w,
5431                    alignment, mSpacingMult,
5432                    mSpacingAdd, mIncludePad, mInput == null ? mEllipsize : null,
5433                    ellipsisWidth);
5434        } else {
5435            if (boring == UNKNOWN_BORING) {
5436                boring = BoringLayout.isBoring(mTransformed, mTextPaint,
5437                                               mBoring);
5438                if (boring != null) {
5439                    mBoring = boring;
5440                }
5441            }
5442
5443            if (boring != null) {
5444                if (boring.width <= w &&
5445                    (mEllipsize == null || boring.width <= ellipsisWidth)) {
5446                    if (mSavedLayout != null) {
5447                        mLayout = mSavedLayout.
5448                                replaceOrMake(mTransformed, mTextPaint,
5449                                w, alignment, mSpacingMult, mSpacingAdd,
5450                                boring, mIncludePad);
5451                    } else {
5452                        mLayout = BoringLayout.make(mTransformed, mTextPaint,
5453                                w, alignment, mSpacingMult, mSpacingAdd,
5454                                boring, mIncludePad);
5455                    }
5456
5457                    mSavedLayout = (BoringLayout) mLayout;
5458                } else if (shouldEllipsize && boring.width <= w) {
5459                    if (mSavedLayout != null) {
5460                        mLayout = mSavedLayout.
5461                                replaceOrMake(mTransformed, mTextPaint,
5462                                w, alignment, mSpacingMult, mSpacingAdd,
5463                                boring, mIncludePad, mEllipsize,
5464                                ellipsisWidth);
5465                    } else {
5466                        mLayout = BoringLayout.make(mTransformed, mTextPaint,
5467                                w, alignment, mSpacingMult, mSpacingAdd,
5468                                boring, mIncludePad, mEllipsize,
5469                                ellipsisWidth);
5470                    }
5471                } else if (shouldEllipsize) {
5472                    mLayout = new StaticLayout(mTransformed,
5473                                0, mTransformed.length(),
5474                                mTextPaint, w, alignment, mSpacingMult,
5475                                mSpacingAdd, mIncludePad, mEllipsize,
5476                                ellipsisWidth);
5477                } else {
5478                    mLayout = new StaticLayout(mTransformed, mTextPaint,
5479                            w, alignment, mSpacingMult, mSpacingAdd,
5480                            mIncludePad);
5481                }
5482            } else if (shouldEllipsize) {
5483                mLayout = new StaticLayout(mTransformed,
5484                            0, mTransformed.length(),
5485                            mTextPaint, w, alignment, mSpacingMult,
5486                            mSpacingAdd, mIncludePad, mEllipsize,
5487                            ellipsisWidth);
5488            } else {
5489                mLayout = new StaticLayout(mTransformed, mTextPaint,
5490                        w, alignment, mSpacingMult, mSpacingAdd,
5491                        mIncludePad);
5492            }
5493        }
5494
5495        shouldEllipsize = mEllipsize != null;
5496        mHintLayout = null;
5497
5498        if (mHint != null) {
5499            if (shouldEllipsize) hintWidth = w;
5500
5501            if (hintBoring == UNKNOWN_BORING) {
5502                hintBoring = BoringLayout.isBoring(mHint, mTextPaint,
5503                                                   mHintBoring);
5504                if (hintBoring != null) {
5505                    mHintBoring = hintBoring;
5506                }
5507            }
5508
5509            if (hintBoring != null) {
5510                if (hintBoring.width <= hintWidth &&
5511                    (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) {
5512                    if (mSavedHintLayout != null) {
5513                        mHintLayout = mSavedHintLayout.
5514                                replaceOrMake(mHint, mTextPaint,
5515                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5516                                hintBoring, mIncludePad);
5517                    } else {
5518                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5519                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5520                                hintBoring, mIncludePad);
5521                    }
5522
5523                    mSavedHintLayout = (BoringLayout) mHintLayout;
5524                } else if (shouldEllipsize && hintBoring.width <= hintWidth) {
5525                    if (mSavedHintLayout != null) {
5526                        mHintLayout = mSavedHintLayout.
5527                                replaceOrMake(mHint, mTextPaint,
5528                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5529                                hintBoring, mIncludePad, mEllipsize,
5530                                ellipsisWidth);
5531                    } else {
5532                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5533                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5534                                hintBoring, mIncludePad, mEllipsize,
5535                                ellipsisWidth);
5536                    }
5537                } else if (shouldEllipsize) {
5538                    mHintLayout = new StaticLayout(mHint,
5539                                0, mHint.length(),
5540                                mTextPaint, hintWidth, alignment, mSpacingMult,
5541                                mSpacingAdd, mIncludePad, mEllipsize,
5542                                ellipsisWidth);
5543                } else {
5544                    mHintLayout = new StaticLayout(mHint, mTextPaint,
5545                            hintWidth, alignment, mSpacingMult, mSpacingAdd,
5546                            mIncludePad);
5547                }
5548            } else if (shouldEllipsize) {
5549                mHintLayout = new StaticLayout(mHint,
5550                            0, mHint.length(),
5551                            mTextPaint, hintWidth, alignment, mSpacingMult,
5552                            mSpacingAdd, mIncludePad, mEllipsize,
5553                            ellipsisWidth);
5554            } else {
5555                mHintLayout = new StaticLayout(mHint, mTextPaint,
5556                        hintWidth, alignment, mSpacingMult, mSpacingAdd,
5557                        mIncludePad);
5558            }
5559        }
5560
5561        if (bringIntoView) {
5562            registerForPreDraw();
5563        }
5564
5565        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
5566            if (!compressText(ellipsisWidth)) {
5567                final int height = mLayoutParams.height;
5568                // If the size of the view does not depend on the size of the text, try to
5569                // start the marquee immediately
5570                if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) {
5571                    startMarquee();
5572                } else {
5573                    // Defer the start of the marquee until we know our width (see setFrame())
5574                    mRestartMarquee = true;
5575                }
5576            }
5577        }
5578
5579        // CursorControllers need a non-null mLayout
5580        prepareCursorControllers();
5581    }
5582
5583    private boolean compressText(float width) {
5584        if (isHardwareAccelerated()) return false;
5585
5586        // Only compress the text if it hasn't been compressed by the previous pass
5587        if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX &&
5588                mTextPaint.getTextScaleX() == 1.0f) {
5589            final float textWidth = mLayout.getLineWidth(0);
5590            final float overflow = (textWidth + 1.0f - width) / width;
5591            if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) {
5592                mTextPaint.setTextScaleX(1.0f - overflow - 0.005f);
5593                post(new Runnable() {
5594                    public void run() {
5595                        requestLayout();
5596                    }
5597                });
5598                return true;
5599            }
5600        }
5601
5602        return false;
5603    }
5604
5605    private static int desired(Layout layout) {
5606        int n = layout.getLineCount();
5607        CharSequence text = layout.getText();
5608        float max = 0;
5609
5610        // if any line was wrapped, we can't use it.
5611        // but it's ok for the last line not to have a newline
5612
5613        for (int i = 0; i < n - 1; i++) {
5614            if (text.charAt(layout.getLineEnd(i) - 1) != '\n')
5615                return -1;
5616        }
5617
5618        for (int i = 0; i < n; i++) {
5619            max = Math.max(max, layout.getLineWidth(i));
5620        }
5621
5622        return (int) FloatMath.ceil(max);
5623    }
5624
5625    /**
5626     * Set whether the TextView includes extra top and bottom padding to make
5627     * room for accents that go above the normal ascent and descent.
5628     * The default is true.
5629     *
5630     * @attr ref android.R.styleable#TextView_includeFontPadding
5631     */
5632    public void setIncludeFontPadding(boolean includepad) {
5633        mIncludePad = includepad;
5634
5635        if (mLayout != null) {
5636            nullLayouts();
5637            requestLayout();
5638            invalidate();
5639        }
5640    }
5641
5642    private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics();
5643
5644    @Override
5645    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
5646        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
5647        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
5648        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
5649        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
5650
5651        int width;
5652        int height;
5653
5654        BoringLayout.Metrics boring = UNKNOWN_BORING;
5655        BoringLayout.Metrics hintBoring = UNKNOWN_BORING;
5656
5657        int des = -1;
5658        boolean fromexisting = false;
5659
5660        if (widthMode == MeasureSpec.EXACTLY) {
5661            // Parent has told us how big to be. So be it.
5662            width = widthSize;
5663        } else {
5664            if (mLayout != null && mEllipsize == null) {
5665                des = desired(mLayout);
5666            }
5667
5668            if (des < 0) {
5669                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mBoring);
5670                if (boring != null) {
5671                    mBoring = boring;
5672                }
5673            } else {
5674                fromexisting = true;
5675            }
5676
5677            if (boring == null || boring == UNKNOWN_BORING) {
5678                if (des < 0) {
5679                    des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint));
5680                }
5681
5682                width = des;
5683            } else {
5684                width = boring.width;
5685            }
5686
5687            final Drawables dr = mDrawables;
5688            if (dr != null) {
5689                width = Math.max(width, dr.mDrawableWidthTop);
5690                width = Math.max(width, dr.mDrawableWidthBottom);
5691            }
5692
5693            if (mHint != null) {
5694                int hintDes = -1;
5695                int hintWidth;
5696
5697                if (mHintLayout != null && mEllipsize == null) {
5698                    hintDes = desired(mHintLayout);
5699                }
5700
5701                if (hintDes < 0) {
5702                    hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring);
5703                    if (hintBoring != null) {
5704                        mHintBoring = hintBoring;
5705                    }
5706                }
5707
5708                if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
5709                    if (hintDes < 0) {
5710                        hintDes = (int) FloatMath.ceil(
5711                                Layout.getDesiredWidth(mHint, mTextPaint));
5712                    }
5713
5714                    hintWidth = hintDes;
5715                } else {
5716                    hintWidth = hintBoring.width;
5717                }
5718
5719                if (hintWidth > width) {
5720                    width = hintWidth;
5721                }
5722            }
5723
5724            width += getCompoundPaddingLeft() + getCompoundPaddingRight();
5725
5726            if (mMaxWidthMode == EMS) {
5727                width = Math.min(width, mMaxWidth * getLineHeight());
5728            } else {
5729                width = Math.min(width, mMaxWidth);
5730            }
5731
5732            if (mMinWidthMode == EMS) {
5733                width = Math.max(width, mMinWidth * getLineHeight());
5734            } else {
5735                width = Math.max(width, mMinWidth);
5736            }
5737
5738            // Check against our minimum width
5739            width = Math.max(width, getSuggestedMinimumWidth());
5740
5741            if (widthMode == MeasureSpec.AT_MOST) {
5742                width = Math.min(widthSize, width);
5743            }
5744        }
5745
5746        int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight();
5747        int unpaddedWidth = want;
5748        int hintWant = want;
5749
5750        if (mHorizontallyScrolling)
5751            want = VERY_WIDE;
5752
5753        int hintWidth = mHintLayout == null ? hintWant : mHintLayout.getWidth();
5754
5755        if (mLayout == null) {
5756            makeNewLayout(want, hintWant, boring, hintBoring,
5757                          width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
5758        } else if ((mLayout.getWidth() != want) || (hintWidth != hintWant) ||
5759                   (mLayout.getEllipsizedWidth() !=
5760                        width - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
5761            if (mHint == null && mEllipsize == null &&
5762                    want > mLayout.getWidth() &&
5763                    (mLayout instanceof BoringLayout ||
5764                            (fromexisting && des >= 0 && des <= want))) {
5765                mLayout.increaseWidthTo(want);
5766            } else {
5767                makeNewLayout(want, hintWant, boring, hintBoring,
5768                              width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
5769            }
5770        } else {
5771            // Width has not changed.
5772        }
5773
5774        if (heightMode == MeasureSpec.EXACTLY) {
5775            // Parent has told us how big to be. So be it.
5776            height = heightSize;
5777            mDesiredHeightAtMeasure = -1;
5778        } else {
5779            int desired = getDesiredHeight();
5780
5781            height = desired;
5782            mDesiredHeightAtMeasure = desired;
5783
5784            if (heightMode == MeasureSpec.AT_MOST) {
5785                height = Math.min(desired, heightSize);
5786            }
5787        }
5788
5789        int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
5790        if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) {
5791            unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum));
5792        }
5793
5794        /*
5795         * We didn't let makeNewLayout() register to bring the cursor into view,
5796         * so do it here if there is any possibility that it is needed.
5797         */
5798        if (mMovement != null ||
5799            mLayout.getWidth() > unpaddedWidth ||
5800            mLayout.getHeight() > unpaddedHeight) {
5801            registerForPreDraw();
5802        } else {
5803            scrollTo(0, 0);
5804        }
5805
5806        setMeasuredDimension(width, height);
5807    }
5808
5809    private int getDesiredHeight() {
5810        return Math.max(
5811                getDesiredHeight(mLayout, true),
5812                getDesiredHeight(mHintLayout, mEllipsize != null));
5813    }
5814
5815    private int getDesiredHeight(Layout layout, boolean cap) {
5816        if (layout == null) {
5817            return 0;
5818        }
5819
5820        int linecount = layout.getLineCount();
5821        int pad = getCompoundPaddingTop() + getCompoundPaddingBottom();
5822        int desired = layout.getLineTop(linecount);
5823
5824        final Drawables dr = mDrawables;
5825        if (dr != null) {
5826            desired = Math.max(desired, dr.mDrawableHeightLeft);
5827            desired = Math.max(desired, dr.mDrawableHeightRight);
5828        }
5829
5830        desired += pad;
5831
5832        if (mMaxMode == LINES) {
5833            /*
5834             * Don't cap the hint to a certain number of lines.
5835             * (Do cap it, though, if we have a maximum pixel height.)
5836             */
5837            if (cap) {
5838                if (linecount > mMaximum) {
5839                    desired = layout.getLineTop(mMaximum) +
5840                              layout.getBottomPadding();
5841
5842                    if (dr != null) {
5843                        desired = Math.max(desired, dr.mDrawableHeightLeft);
5844                        desired = Math.max(desired, dr.mDrawableHeightRight);
5845                    }
5846
5847                    desired += pad;
5848                    linecount = mMaximum;
5849                }
5850            }
5851        } else {
5852            desired = Math.min(desired, mMaximum);
5853        }
5854
5855        if (mMinMode == LINES) {
5856            if (linecount < mMinimum) {
5857                desired += getLineHeight() * (mMinimum - linecount);
5858            }
5859        } else {
5860            desired = Math.max(desired, mMinimum);
5861        }
5862
5863        // Check against our minimum height
5864        desired = Math.max(desired, getSuggestedMinimumHeight());
5865
5866        return desired;
5867    }
5868
5869    /**
5870     * Check whether a change to the existing text layout requires a
5871     * new view layout.
5872     */
5873    private void checkForResize() {
5874        boolean sizeChanged = false;
5875
5876        if (mLayout != null) {
5877            // Check if our width changed
5878            if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) {
5879                sizeChanged = true;
5880                invalidate();
5881            }
5882
5883            // Check if our height changed
5884            if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) {
5885                int desiredHeight = getDesiredHeight();
5886
5887                if (desiredHeight != this.getHeight()) {
5888                    sizeChanged = true;
5889                }
5890            } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) {
5891                if (mDesiredHeightAtMeasure >= 0) {
5892                    int desiredHeight = getDesiredHeight();
5893
5894                    if (desiredHeight != mDesiredHeightAtMeasure) {
5895                        sizeChanged = true;
5896                    }
5897                }
5898            }
5899        }
5900
5901        if (sizeChanged) {
5902            requestLayout();
5903            // caller will have already invalidated
5904        }
5905    }
5906
5907    /**
5908     * Check whether entirely new text requires a new view layout
5909     * or merely a new text layout.
5910     */
5911    private void checkForRelayout() {
5912        // If we have a fixed width, we can just swap in a new text layout
5913        // if the text height stays the same or if the view height is fixed.
5914
5915        if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT ||
5916                (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) &&
5917                (mHint == null || mHintLayout != null) &&
5918                (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) {
5919            // Static width, so try making a new text layout.
5920
5921            int oldht = mLayout.getHeight();
5922            int want = mLayout.getWidth();
5923            int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();
5924
5925            /*
5926             * No need to bring the text into view, since the size is not
5927             * changing (unless we do the requestLayout(), in which case it
5928             * will happen at measure).
5929             */
5930            makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
5931                          mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(),
5932                          false);
5933
5934            if (mEllipsize != TextUtils.TruncateAt.MARQUEE) {
5935                // In a fixed-height view, so use our new text layout.
5936                if (mLayoutParams.height != LayoutParams.WRAP_CONTENT &&
5937                    mLayoutParams.height != LayoutParams.MATCH_PARENT) {
5938                    invalidate();
5939                    return;
5940                }
5941
5942                // Dynamic height, but height has stayed the same,
5943                // so use our new text layout.
5944                if (mLayout.getHeight() == oldht &&
5945                    (mHintLayout == null || mHintLayout.getHeight() == oldht)) {
5946                    invalidate();
5947                    return;
5948                }
5949            }
5950
5951            // We lose: the height has changed and we have a dynamic height.
5952            // Request a new view layout using our new text layout.
5953            requestLayout();
5954            invalidate();
5955        } else {
5956            // Dynamic width, so we have no choice but to request a new
5957            // view layout with a new text layout.
5958
5959            nullLayouts();
5960            requestLayout();
5961            invalidate();
5962        }
5963    }
5964
5965    /**
5966     * Returns true if anything changed.
5967     */
5968    private boolean bringTextIntoView() {
5969        int line = 0;
5970        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
5971            line = mLayout.getLineCount() - 1;
5972        }
5973
5974        Layout.Alignment a = mLayout.getParagraphAlignment(line);
5975        int dir = mLayout.getParagraphDirection(line);
5976        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5977        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
5978        int ht = mLayout.getHeight();
5979
5980        int scrollx, scrolly;
5981
5982        if (a == Layout.Alignment.ALIGN_CENTER) {
5983            /*
5984             * Keep centered if possible, or, if it is too wide to fit,
5985             * keep leading edge in view.
5986             */
5987
5988            int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
5989            int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
5990
5991            if (right - left < hspace) {
5992                scrollx = (right + left) / 2 - hspace / 2;
5993            } else {
5994                if (dir < 0) {
5995                    scrollx = right - hspace;
5996                } else {
5997                    scrollx = left;
5998                }
5999            }
6000        } else if (a == Layout.Alignment.ALIGN_NORMAL) {
6001            /*
6002             * Keep leading edge in view.
6003             */
6004
6005            if (dir < 0) {
6006                int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6007                scrollx = right - hspace;
6008            } else {
6009                scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line));
6010            }
6011        } else /* a == Layout.Alignment.ALIGN_OPPOSITE */ {
6012            /*
6013             * Keep trailing edge in view.
6014             */
6015
6016            if (dir < 0) {
6017                scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line));
6018            } else {
6019                int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6020                scrollx = right - hspace;
6021            }
6022        }
6023
6024        if (ht < vspace) {
6025            scrolly = 0;
6026        } else {
6027            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
6028                scrolly = ht - vspace;
6029            } else {
6030                scrolly = 0;
6031            }
6032        }
6033
6034        if (scrollx != mScrollX || scrolly != mScrollY) {
6035            scrollTo(scrollx, scrolly);
6036            return true;
6037        } else {
6038            return false;
6039        }
6040    }
6041
6042    /**
6043     * Move the point, specified by the offset, into the view if it is needed.
6044     * This has to be called after layout. Returns true if anything changed.
6045     */
6046    public boolean bringPointIntoView(int offset) {
6047        boolean changed = false;
6048
6049        int line = mLayout.getLineForOffset(offset);
6050
6051        // FIXME: Is it okay to truncate this, or should we round?
6052        final int x = (int)mLayout.getPrimaryHorizontal(offset);
6053        final int top = mLayout.getLineTop(line);
6054        final int bottom = mLayout.getLineTop(line + 1);
6055
6056        int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
6057        int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6058        int ht = mLayout.getHeight();
6059
6060        int grav;
6061
6062        switch (mLayout.getParagraphAlignment(line)) {
6063            case ALIGN_NORMAL:
6064                grav = 1;
6065                break;
6066
6067            case ALIGN_OPPOSITE:
6068                grav = -1;
6069                break;
6070
6071            default:
6072                grav = 0;
6073        }
6074
6075        grav *= mLayout.getParagraphDirection(line);
6076
6077        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6078        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6079
6080        int hslack = (bottom - top) / 2;
6081        int vslack = hslack;
6082
6083        if (vslack > vspace / 4)
6084            vslack = vspace / 4;
6085        if (hslack > hspace / 4)
6086            hslack = hspace / 4;
6087
6088        int hs = mScrollX;
6089        int vs = mScrollY;
6090
6091        if (top - vs < vslack)
6092            vs = top - vslack;
6093        if (bottom - vs > vspace - vslack)
6094            vs = bottom - (vspace - vslack);
6095        if (ht - vs < vspace)
6096            vs = ht - vspace;
6097        if (0 - vs > 0)
6098            vs = 0;
6099
6100        if (grav != 0) {
6101            if (x - hs < hslack) {
6102                hs = x - hslack;
6103            }
6104            if (x - hs > hspace - hslack) {
6105                hs = x - (hspace - hslack);
6106            }
6107        }
6108
6109        if (grav < 0) {
6110            if (left - hs > 0)
6111                hs = left;
6112            if (right - hs < hspace)
6113                hs = right - hspace;
6114        } else if (grav > 0) {
6115            if (right - hs < hspace)
6116                hs = right - hspace;
6117            if (left - hs > 0)
6118                hs = left;
6119        } else /* grav == 0 */ {
6120            if (right - left <= hspace) {
6121                /*
6122                 * If the entire text fits, center it exactly.
6123                 */
6124                hs = left - (hspace - (right - left)) / 2;
6125            } else if (x > right - hslack) {
6126                /*
6127                 * If we are near the right edge, keep the right edge
6128                 * at the edge of the view.
6129                 */
6130                hs = right - hspace;
6131            } else if (x < left + hslack) {
6132                /*
6133                 * If we are near the left edge, keep the left edge
6134                 * at the edge of the view.
6135                 */
6136                hs = left;
6137            } else if (left > hs) {
6138                /*
6139                 * Is there whitespace visible at the left?  Fix it if so.
6140                 */
6141                hs = left;
6142            } else if (right < hs + hspace) {
6143                /*
6144                 * Is there whitespace visible at the right?  Fix it if so.
6145                 */
6146                hs = right - hspace;
6147            } else {
6148                /*
6149                 * Otherwise, float as needed.
6150                 */
6151                if (x - hs < hslack) {
6152                    hs = x - hslack;
6153                }
6154                if (x - hs > hspace - hslack) {
6155                    hs = x - (hspace - hslack);
6156                }
6157            }
6158        }
6159
6160        if (hs != mScrollX || vs != mScrollY) {
6161            if (mScroller == null) {
6162                scrollTo(hs, vs);
6163            } else {
6164                long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
6165                int dx = hs - mScrollX;
6166                int dy = vs - mScrollY;
6167
6168                if (duration > ANIMATED_SCROLL_GAP) {
6169                    mScroller.startScroll(mScrollX, mScrollY, dx, dy);
6170                    awakenScrollBars(mScroller.getDuration());
6171                    invalidate();
6172                } else {
6173                    if (!mScroller.isFinished()) {
6174                        mScroller.abortAnimation();
6175                    }
6176
6177                    scrollBy(dx, dy);
6178                }
6179
6180                mLastScroll = AnimationUtils.currentAnimationTimeMillis();
6181            }
6182
6183            changed = true;
6184        }
6185
6186        if (isFocused()) {
6187            // This offsets because getInterestingRect() is in terms of
6188            // viewport coordinates, but requestRectangleOnScreen()
6189            // is in terms of content coordinates.
6190
6191            Rect r = new Rect(x, top, x + 1, bottom);
6192            getInterestingRect(r, line);
6193            r.offset(mScrollX, mScrollY);
6194
6195            if (requestRectangleOnScreen(r)) {
6196                changed = true;
6197            }
6198        }
6199
6200        return changed;
6201    }
6202
6203    /**
6204     * Move the cursor, if needed, so that it is at an offset that is visible
6205     * to the user.  This will not move the cursor if it represents more than
6206     * one character (a selection range).  This will only work if the
6207     * TextView contains spannable text; otherwise it will do nothing.
6208     *
6209     * @return True if the cursor was actually moved, false otherwise.
6210     */
6211    public boolean moveCursorToVisibleOffset() {
6212        if (!(mText instanceof Spannable)) {
6213            return false;
6214        }
6215        int start = getSelectionStart();
6216        int end = getSelectionEnd();
6217        if (start != end) {
6218            return false;
6219        }
6220
6221        // First: make sure the line is visible on screen:
6222
6223        int line = mLayout.getLineForOffset(start);
6224
6225        final int top = mLayout.getLineTop(line);
6226        final int bottom = mLayout.getLineTop(line + 1);
6227        final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6228        int vslack = (bottom - top) / 2;
6229        if (vslack > vspace / 4)
6230            vslack = vspace / 4;
6231        final int vs = mScrollY;
6232
6233        if (top < (vs+vslack)) {
6234            line = mLayout.getLineForVertical(vs+vslack+(bottom-top));
6235        } else if (bottom > (vspace+vs-vslack)) {
6236            line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top));
6237        }
6238
6239        // Next: make sure the character is visible on screen:
6240
6241        final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6242        final int hs = mScrollX;
6243        final int leftChar = mLayout.getOffsetForHorizontal(line, hs);
6244        final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs);
6245
6246        // line might contain bidirectional text
6247        final int lowChar = leftChar < rightChar ? leftChar : rightChar;
6248        final int highChar = leftChar > rightChar ? leftChar : rightChar;
6249
6250        int newStart = start;
6251        if (newStart < lowChar) {
6252            newStart = lowChar;
6253        } else if (newStart > highChar) {
6254            newStart = highChar;
6255        }
6256
6257        if (newStart != start) {
6258            Selection.setSelection((Spannable)mText, newStart);
6259            return true;
6260        }
6261
6262        return false;
6263    }
6264
6265    @Override
6266    public void computeScroll() {
6267        if (mScroller != null) {
6268            if (mScroller.computeScrollOffset()) {
6269                mScrollX = mScroller.getCurrX();
6270                mScrollY = mScroller.getCurrY();
6271                postInvalidate();  // So we draw again
6272            }
6273        }
6274    }
6275
6276    private void getInterestingRect(Rect r, int line) {
6277        convertFromViewportToContentCoordinates(r);
6278
6279        // Rectangle can can be expanded on first and last line to take
6280        // padding into account.
6281        // TODO Take left/right padding into account too?
6282        if (line == 0) r.top -= getExtendedPaddingTop();
6283        if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom();
6284    }
6285
6286    private void convertFromViewportToContentCoordinates(Rect r) {
6287        final int horizontalOffset = viewportToContentHorizontalOffset();
6288        r.left += horizontalOffset;
6289        r.right += horizontalOffset;
6290
6291        final int verticalOffset = viewportToContentVerticalOffset();
6292        r.top += verticalOffset;
6293        r.bottom += verticalOffset;
6294    }
6295
6296    private int viewportToContentHorizontalOffset() {
6297        return getCompoundPaddingLeft() - mScrollX;
6298    }
6299
6300    private int viewportToContentVerticalOffset() {
6301        int offset = getExtendedPaddingTop() - mScrollY;
6302        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
6303            offset += getVerticalOffset(false);
6304        }
6305        return offset;
6306    }
6307
6308    @Override
6309    public void debug(int depth) {
6310        super.debug(depth);
6311
6312        String output = debugIndent(depth);
6313        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
6314                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
6315                + "} ";
6316
6317        if (mText != null) {
6318
6319            output += "mText=\"" + mText + "\" ";
6320            if (mLayout != null) {
6321                output += "mLayout width=" + mLayout.getWidth()
6322                        + " height=" + mLayout.getHeight();
6323            }
6324        } else {
6325            output += "mText=NULL";
6326        }
6327        Log.d(VIEW_LOG_TAG, output);
6328    }
6329
6330    /**
6331     * Convenience for {@link Selection#getSelectionStart}.
6332     */
6333    @ViewDebug.ExportedProperty(category = "text")
6334    public int getSelectionStart() {
6335        return Selection.getSelectionStart(getText());
6336    }
6337
6338    /**
6339     * Convenience for {@link Selection#getSelectionEnd}.
6340     */
6341    @ViewDebug.ExportedProperty(category = "text")
6342    public int getSelectionEnd() {
6343        return Selection.getSelectionEnd(getText());
6344    }
6345
6346    /**
6347     * Return true iff there is a selection inside this text view.
6348     */
6349    public boolean hasSelection() {
6350        final int selectionStart = getSelectionStart();
6351        final int selectionEnd = getSelectionEnd();
6352
6353        return selectionStart >= 0 && selectionStart != selectionEnd;
6354    }
6355
6356    /**
6357     * Sets the properties of this field (lines, horizontally scrolling,
6358     * transformation method) to be for a single-line input.
6359     *
6360     * @attr ref android.R.styleable#TextView_singleLine
6361     */
6362    public void setSingleLine() {
6363        setSingleLine(true);
6364    }
6365
6366    /**
6367     * If true, sets the properties of this field (number of lines, horizontally scrolling,
6368     * transformation method) to be for a single-line input; if false, restores these to the default
6369     * conditions.
6370     *
6371     * Note that the default conditions are not necessarily those that were in effect prior this
6372     * method, and you may want to reset these properties to your custom values.
6373     *
6374     * @attr ref android.R.styleable#TextView_singleLine
6375     */
6376    @android.view.RemotableViewMethod
6377    public void setSingleLine(boolean singleLine) {
6378        // Could be used, but may break backward compatibility.
6379        // if (mSingleLine == singleLine) return;
6380        setInputTypeSingleLine(singleLine);
6381        applySingleLine(singleLine, true, true);
6382    }
6383
6384    /**
6385     * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType.
6386     * @param singleLine
6387     */
6388    private void setInputTypeSingleLine(boolean singleLine) {
6389        if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
6390            if (singleLine) {
6391                mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
6392            } else {
6393                mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
6394            }
6395        }
6396    }
6397
6398    private void applySingleLine(boolean singleLine, boolean applyTransformation,
6399            boolean changeMaxLines) {
6400        mSingleLine = singleLine;
6401        if (singleLine) {
6402            setLines(1);
6403            setHorizontallyScrolling(true);
6404            if (applyTransformation) {
6405                setTransformationMethod(SingleLineTransformationMethod.getInstance());
6406            }
6407            // TODO setState
6408        } else {
6409            if (changeMaxLines) {
6410                setMaxLines(Integer.MAX_VALUE);
6411            }
6412            setHorizontallyScrolling(false);
6413            if (applyTransformation) {
6414                setTransformationMethod(null);
6415            }
6416            // TODO setState
6417        }
6418    }
6419
6420    /**
6421     * Causes words in the text that are longer than the view is wide
6422     * to be ellipsized instead of broken in the middle.  You may also
6423     * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling}
6424     * to constrain the text to a single line.  Use <code>null</code>
6425     * to turn off ellipsizing.
6426     *
6427     * @attr ref android.R.styleable#TextView_ellipsize
6428     */
6429    public void setEllipsize(TextUtils.TruncateAt where) {
6430        mEllipsize = where;
6431
6432        if (mLayout != null) {
6433            nullLayouts();
6434            requestLayout();
6435            invalidate();
6436        }
6437    }
6438
6439    /**
6440     * Sets how many times to repeat the marquee animation. Only applied if the
6441     * TextView has marquee enabled. Set to -1 to repeat indefinitely.
6442     *
6443     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
6444     */
6445    public void setMarqueeRepeatLimit(int marqueeLimit) {
6446        mMarqueeRepeatLimit = marqueeLimit;
6447    }
6448
6449    /**
6450     * Returns where, if anywhere, words that are longer than the view
6451     * is wide should be ellipsized.
6452     */
6453    @ViewDebug.ExportedProperty
6454    public TextUtils.TruncateAt getEllipsize() {
6455        return mEllipsize;
6456    }
6457
6458    /**
6459     * Set the TextView so that when it takes focus, all the text is
6460     * selected.
6461     *
6462     * @attr ref android.R.styleable#TextView_selectAllOnFocus
6463     */
6464    @android.view.RemotableViewMethod
6465    public void setSelectAllOnFocus(boolean selectAllOnFocus) {
6466        mSelectAllOnFocus = selectAllOnFocus;
6467
6468        if (selectAllOnFocus && !(mText instanceof Spannable)) {
6469            setText(mText, BufferType.SPANNABLE);
6470        }
6471    }
6472
6473    /**
6474     * Set whether the cursor is visible.  The default is true.
6475     *
6476     * @attr ref android.R.styleable#TextView_cursorVisible
6477     */
6478    @android.view.RemotableViewMethod
6479    public void setCursorVisible(boolean visible) {
6480        mCursorVisible = visible;
6481        invalidate();
6482
6483        makeBlink();
6484
6485        // InsertionPointCursorController depends on mCursorVisible
6486        prepareCursorControllers();
6487    }
6488
6489    private boolean canMarquee() {
6490        int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight());
6491        return width > 0 && mLayout.getLineWidth(0) > width;
6492    }
6493
6494    private void startMarquee() {
6495        // Do not ellipsize EditText
6496        if (mInput != null) return;
6497
6498        if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
6499            return;
6500        }
6501
6502        if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) &&
6503                getLineCount() == 1 && canMarquee()) {
6504
6505            if (mMarquee == null) mMarquee = new Marquee(this);
6506            mMarquee.start(mMarqueeRepeatLimit);
6507        }
6508    }
6509
6510    private void stopMarquee() {
6511        if (mMarquee != null && !mMarquee.isStopped()) {
6512            mMarquee.stop();
6513        }
6514    }
6515
6516    private void startStopMarquee(boolean start) {
6517        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6518            if (start) {
6519                startMarquee();
6520            } else {
6521                stopMarquee();
6522            }
6523        }
6524    }
6525
6526    private static final class Marquee extends Handler {
6527        // TODO: Add an option to configure this
6528        private static final float MARQUEE_DELTA_MAX = 0.07f;
6529        private static final int MARQUEE_DELAY = 1200;
6530        private static final int MARQUEE_RESTART_DELAY = 1200;
6531        private static final int MARQUEE_RESOLUTION = 1000 / 30;
6532        private static final int MARQUEE_PIXELS_PER_SECOND = 30;
6533
6534        private static final byte MARQUEE_STOPPED = 0x0;
6535        private static final byte MARQUEE_STARTING = 0x1;
6536        private static final byte MARQUEE_RUNNING = 0x2;
6537
6538        private static final int MESSAGE_START = 0x1;
6539        private static final int MESSAGE_TICK = 0x2;
6540        private static final int MESSAGE_RESTART = 0x3;
6541
6542        private final WeakReference<TextView> mView;
6543
6544        private byte mStatus = MARQUEE_STOPPED;
6545        private final float mScrollUnit;
6546        private float mMaxScroll;
6547        float mMaxFadeScroll;
6548        private float mGhostStart;
6549        private float mGhostOffset;
6550        private float mFadeStop;
6551        private int mRepeatLimit;
6552
6553        float mScroll;
6554
6555        Marquee(TextView v) {
6556            final float density = v.getContext().getResources().getDisplayMetrics().density;
6557            mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION;
6558            mView = new WeakReference<TextView>(v);
6559        }
6560
6561        @Override
6562        public void handleMessage(Message msg) {
6563            switch (msg.what) {
6564                case MESSAGE_START:
6565                    mStatus = MARQUEE_RUNNING;
6566                    tick();
6567                    break;
6568                case MESSAGE_TICK:
6569                    tick();
6570                    break;
6571                case MESSAGE_RESTART:
6572                    if (mStatus == MARQUEE_RUNNING) {
6573                        if (mRepeatLimit >= 0) {
6574                            mRepeatLimit--;
6575                        }
6576                        start(mRepeatLimit);
6577                    }
6578                    break;
6579            }
6580        }
6581
6582        void tick() {
6583            if (mStatus != MARQUEE_RUNNING) {
6584                return;
6585            }
6586
6587            removeMessages(MESSAGE_TICK);
6588
6589            final TextView textView = mView.get();
6590            if (textView != null && (textView.isFocused() || textView.isSelected())) {
6591                mScroll += mScrollUnit;
6592                if (mScroll > mMaxScroll) {
6593                    mScroll = mMaxScroll;
6594                    sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY);
6595                } else {
6596                    sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION);
6597                }
6598                textView.invalidate();
6599            }
6600        }
6601
6602        void stop() {
6603            mStatus = MARQUEE_STOPPED;
6604            removeMessages(MESSAGE_START);
6605            removeMessages(MESSAGE_RESTART);
6606            removeMessages(MESSAGE_TICK);
6607            resetScroll();
6608        }
6609
6610        private void resetScroll() {
6611            mScroll = 0.0f;
6612            final TextView textView = mView.get();
6613            if (textView != null) textView.invalidate();
6614        }
6615
6616        void start(int repeatLimit) {
6617            if (repeatLimit == 0) {
6618                stop();
6619                return;
6620            }
6621            mRepeatLimit = repeatLimit;
6622            final TextView textView = mView.get();
6623            if (textView != null && textView.mLayout != null) {
6624                mStatus = MARQUEE_STARTING;
6625                mScroll = 0.0f;
6626                final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() -
6627                        textView.getCompoundPaddingRight();
6628                final float lineWidth = textView.mLayout.getLineWidth(0);
6629                final float gap = textWidth / 3.0f;
6630                mGhostStart = lineWidth - textWidth + gap;
6631                mMaxScroll = mGhostStart + textWidth;
6632                mGhostOffset = lineWidth + gap;
6633                mFadeStop = lineWidth + textWidth / 6.0f;
6634                mMaxFadeScroll = mGhostStart + lineWidth + lineWidth;
6635
6636                textView.invalidate();
6637                sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY);
6638            }
6639        }
6640
6641        float getGhostOffset() {
6642            return mGhostOffset;
6643        }
6644
6645        boolean shouldDrawLeftFade() {
6646            return mScroll <= mFadeStop;
6647        }
6648
6649        boolean shouldDrawGhost() {
6650            return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart;
6651        }
6652
6653        boolean isRunning() {
6654            return mStatus == MARQUEE_RUNNING;
6655        }
6656
6657        boolean isStopped() {
6658            return mStatus == MARQUEE_STOPPED;
6659        }
6660    }
6661
6662    /**
6663     * This method is called when the text is changed, in case any
6664     * subclasses would like to know.
6665     *
6666     * @param text The text the TextView is displaying.
6667     * @param start The offset of the start of the range of the text
6668     *              that was modified.
6669     * @param before The offset of the former end of the range of the
6670     *               text that was modified.  If text was simply inserted,
6671     *               this will be the same as <code>start</code>.
6672     *               If text was replaced with new text or deleted, the
6673     *               length of the old text was <code>before-start</code>.
6674     * @param after The offset of the end of the range of the text
6675     *              that was modified.  If text was simply deleted,
6676     *              this will be the same as <code>start</code>.
6677     *              If text was replaced with new text or inserted,
6678     *              the length of the new text is <code>after-start</code>.
6679     */
6680    protected void onTextChanged(CharSequence text,
6681                                 int start, int before, int after) {
6682    }
6683
6684    /**
6685     * This method is called when the selection has changed, in case any
6686     * subclasses would like to know.
6687     *
6688     * @param selStart The new selection start location.
6689     * @param selEnd The new selection end location.
6690     */
6691    protected void onSelectionChanged(int selStart, int selEnd) {
6692    }
6693
6694    /**
6695     * Adds a TextWatcher to the list of those whose methods are called
6696     * whenever this TextView's text changes.
6697     * <p>
6698     * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
6699     * not called after {@link #setText} calls.  Now, doing {@link #setText}
6700     * if there are any text changed listeners forces the buffer type to
6701     * Editable if it would not otherwise be and does call this method.
6702     */
6703    public void addTextChangedListener(TextWatcher watcher) {
6704        if (mListeners == null) {
6705            mListeners = new ArrayList<TextWatcher>();
6706        }
6707
6708        mListeners.add(watcher);
6709    }
6710
6711    /**
6712     * Removes the specified TextWatcher from the list of those whose
6713     * methods are called
6714     * whenever this TextView's text changes.
6715     */
6716    public void removeTextChangedListener(TextWatcher watcher) {
6717        if (mListeners != null) {
6718            int i = mListeners.indexOf(watcher);
6719
6720            if (i >= 0) {
6721                mListeners.remove(i);
6722            }
6723        }
6724    }
6725
6726    private void sendBeforeTextChanged(CharSequence text, int start, int before,
6727                                   int after) {
6728        if (mListeners != null) {
6729            final ArrayList<TextWatcher> list = mListeners;
6730            final int count = list.size();
6731            for (int i = 0; i < count; i++) {
6732                list.get(i).beforeTextChanged(text, start, before, after);
6733            }
6734        }
6735    }
6736
6737    /**
6738     * Not private so it can be called from an inner class without going
6739     * through a thunk.
6740     */
6741    void sendOnTextChanged(CharSequence text, int start, int before,
6742                                   int after) {
6743        if (mListeners != null) {
6744            final ArrayList<TextWatcher> list = mListeners;
6745            final int count = list.size();
6746            for (int i = 0; i < count; i++) {
6747                list.get(i).onTextChanged(text, start, before, after);
6748            }
6749        }
6750    }
6751
6752    /**
6753     * Not private so it can be called from an inner class without going
6754     * through a thunk.
6755     */
6756    void sendAfterTextChanged(Editable text) {
6757        if (mListeners != null) {
6758            final ArrayList<TextWatcher> list = mListeners;
6759            final int count = list.size();
6760            for (int i = 0; i < count; i++) {
6761                list.get(i).afterTextChanged(text);
6762            }
6763        }
6764    }
6765
6766    /**
6767     * Not private so it can be called from an inner class without going
6768     * through a thunk.
6769     */
6770    void handleTextChanged(CharSequence buffer, int start, int before, int after) {
6771        final InputMethodState ims = mInputMethodState;
6772        if (ims == null || ims.mBatchEditNesting == 0) {
6773            updateAfterEdit();
6774        }
6775        if (ims != null) {
6776            ims.mContentChanged = true;
6777            if (ims.mChangedStart < 0) {
6778                ims.mChangedStart = start;
6779                ims.mChangedEnd = start+before;
6780            } else {
6781                ims.mChangedStart = Math.min(ims.mChangedStart, start);
6782                ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta);
6783            }
6784            ims.mChangedDelta += after-before;
6785        }
6786
6787        sendOnTextChanged(buffer, start, before, after);
6788        onTextChanged(buffer, start, before, after);
6789
6790        // Hide the controllers if the amount of content changed
6791        if (before != after) {
6792            hideControllers();
6793        }
6794    }
6795
6796    /**
6797     * Not private so it can be called from an inner class without going
6798     * through a thunk.
6799     */
6800    void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) {
6801        // XXX Make the start and end move together if this ends up
6802        // spending too much time invalidating.
6803
6804        boolean selChanged = false;
6805        int newSelStart=-1, newSelEnd=-1;
6806
6807        final InputMethodState ims = mInputMethodState;
6808
6809        if (what == Selection.SELECTION_END) {
6810            mHighlightPathBogus = true;
6811            selChanged = true;
6812            newSelEnd = newStart;
6813
6814            if (!isFocused()) {
6815                mSelectionMoved = true;
6816            }
6817
6818            if (oldStart >= 0 || newStart >= 0) {
6819                invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart);
6820                registerForPreDraw();
6821
6822                if (isFocused()) {
6823                    mShowCursor = SystemClock.uptimeMillis();
6824                    makeBlink();
6825                }
6826            }
6827        }
6828
6829        if (what == Selection.SELECTION_START) {
6830            mHighlightPathBogus = true;
6831            selChanged = true;
6832            newSelStart = newStart;
6833
6834            if (!isFocused()) {
6835                mSelectionMoved = true;
6836            }
6837
6838            if (oldStart >= 0 || newStart >= 0) {
6839                int end = Selection.getSelectionEnd(buf);
6840                invalidateCursor(end, oldStart, newStart);
6841            }
6842        }
6843
6844        if (selChanged) {
6845            if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) {
6846                if (newSelStart < 0) {
6847                    newSelStart = Selection.getSelectionStart(buf);
6848                }
6849                if (newSelEnd < 0) {
6850                    newSelEnd = Selection.getSelectionEnd(buf);
6851                }
6852                onSelectionChanged(newSelStart, newSelEnd);
6853            }
6854        }
6855
6856        if (what instanceof UpdateAppearance ||
6857            what instanceof ParagraphStyle) {
6858            if (ims == null || ims.mBatchEditNesting == 0) {
6859                invalidate();
6860                mHighlightPathBogus = true;
6861                checkForResize();
6862            } else {
6863                ims.mContentChanged = true;
6864            }
6865        }
6866
6867        if (MetaKeyKeyListener.isMetaTracker(buf, what)) {
6868            mHighlightPathBogus = true;
6869            if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) {
6870                ims.mSelectionModeChanged = true;
6871            }
6872
6873            if (Selection.getSelectionStart(buf) >= 0) {
6874                if (ims == null || ims.mBatchEditNesting == 0) {
6875                    invalidateCursor();
6876                } else {
6877                    ims.mCursorChanged = true;
6878                }
6879            }
6880        }
6881
6882        if (what instanceof ParcelableSpan) {
6883            // If this is a span that can be sent to a remote process,
6884            // the current extract editor would be interested in it.
6885            if (ims != null && ims.mExtracting != null) {
6886                if (ims.mBatchEditNesting != 0) {
6887                    if (oldStart >= 0) {
6888                        if (ims.mChangedStart > oldStart) {
6889                            ims.mChangedStart = oldStart;
6890                        }
6891                        if (ims.mChangedStart > oldEnd) {
6892                            ims.mChangedStart = oldEnd;
6893                        }
6894                    }
6895                    if (newStart >= 0) {
6896                        if (ims.mChangedStart > newStart) {
6897                            ims.mChangedStart = newStart;
6898                        }
6899                        if (ims.mChangedStart > newEnd) {
6900                            ims.mChangedStart = newEnd;
6901                        }
6902                    }
6903                } else {
6904                    if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: "
6905                            + oldStart + "-" + oldEnd + ","
6906                            + newStart + "-" + newEnd + what);
6907                    ims.mContentChanged = true;
6908                }
6909            }
6910        }
6911    }
6912
6913    private class ChangeWatcher
6914    implements TextWatcher, SpanWatcher {
6915
6916        private CharSequence mBeforeText;
6917
6918        public void beforeTextChanged(CharSequence buffer, int start,
6919                                      int before, int after) {
6920            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start
6921                    + " before=" + before + " after=" + after + ": " + buffer);
6922
6923            if (AccessibilityManager.getInstance(mContext).isEnabled()
6924                    && !isPasswordInputType(mInputType)
6925                    && !hasPasswordTransformationMethod()) {
6926                mBeforeText = buffer.toString();
6927            }
6928
6929            TextView.this.sendBeforeTextChanged(buffer, start, before, after);
6930        }
6931
6932        public void onTextChanged(CharSequence buffer, int start,
6933                                  int before, int after) {
6934            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start
6935                    + " before=" + before + " after=" + after + ": " + buffer);
6936            TextView.this.handleTextChanged(buffer, start, before, after);
6937
6938            if (AccessibilityManager.getInstance(mContext).isEnabled() &&
6939                    (isFocused() || isSelected() &&
6940                    isShown())) {
6941                sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after);
6942                mBeforeText = null;
6943            }
6944        }
6945
6946        public void afterTextChanged(Editable buffer) {
6947            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer);
6948            TextView.this.sendAfterTextChanged(buffer);
6949
6950            if (MetaKeyKeyListener.getMetaState(buffer,
6951                                 MetaKeyKeyListener.META_SELECTING) != 0) {
6952                MetaKeyKeyListener.stopSelecting(TextView.this, buffer);
6953            }
6954        }
6955
6956        public void onSpanChanged(Spannable buf,
6957                                  Object what, int s, int e, int st, int en) {
6958            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e
6959                    + " st=" + st + " en=" + en + " what=" + what + ": " + buf);
6960            TextView.this.spanChange(buf, what, s, st, e, en);
6961        }
6962
6963        public void onSpanAdded(Spannable buf, Object what, int s, int e) {
6964            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e
6965                    + " what=" + what + ": " + buf);
6966            TextView.this.spanChange(buf, what, -1, s, -1, e);
6967        }
6968
6969        public void onSpanRemoved(Spannable buf, Object what, int s, int e) {
6970            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e
6971                    + " what=" + what + ": " + buf);
6972            TextView.this.spanChange(buf, what, s, -1, e, -1);
6973        }
6974    }
6975
6976    private void makeBlink() {
6977        if (!mCursorVisible || !isTextEditable()) {
6978            if (mBlink != null) {
6979                mBlink.removeCallbacks(mBlink);
6980            }
6981
6982            return;
6983        }
6984
6985        if (mBlink == null)
6986            mBlink = new Blink(this);
6987
6988        mBlink.removeCallbacks(mBlink);
6989        mBlink.postAtTime(mBlink, mShowCursor + BLINK);
6990    }
6991
6992    /**
6993     * @hide
6994     */
6995    @Override
6996    public void dispatchFinishTemporaryDetach() {
6997        mDispatchTemporaryDetach = true;
6998        super.dispatchFinishTemporaryDetach();
6999        mDispatchTemporaryDetach = false;
7000    }
7001
7002    @Override
7003    public void onStartTemporaryDetach() {
7004        super.onStartTemporaryDetach();
7005        // Only track when onStartTemporaryDetach() is called directly,
7006        // usually because this instance is an editable field in a list
7007        if (!mDispatchTemporaryDetach) mTemporaryDetach = true;
7008    }
7009
7010    @Override
7011    public void onFinishTemporaryDetach() {
7012        super.onFinishTemporaryDetach();
7013        // Only track when onStartTemporaryDetach() is called directly,
7014        // usually because this instance is an editable field in a list
7015        if (!mDispatchTemporaryDetach) mTemporaryDetach = false;
7016    }
7017
7018    @Override
7019    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
7020        if (mTemporaryDetach) {
7021            // If we are temporarily in the detach state, then do nothing.
7022            super.onFocusChanged(focused, direction, previouslyFocusedRect);
7023            return;
7024        }
7025
7026        mShowCursor = SystemClock.uptimeMillis();
7027
7028        ensureEndedBatchEdit();
7029
7030        if (focused) {
7031            int selStart = getSelectionStart();
7032            int selEnd = getSelectionEnd();
7033
7034            // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection
7035            // mode for these, unless there was a specific selection already started.
7036            final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 &&
7037                    selEnd == mText.length();
7038            mCreatedWithASelection = mFrozenWithFocus && hasSelection() && !isFocusHighlighted;
7039
7040            if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
7041                // If a tap was used to give focus to that view, move cursor at tap position.
7042                // Has to be done before onTakeFocus, which can be overloaded.
7043                final int lastTapPosition = getLastTapPosition();
7044                if (lastTapPosition >= 0) {
7045                    Selection.setSelection((Spannable) mText, lastTapPosition);
7046                }
7047
7048                if (mMovement != null) {
7049                    mMovement.onTakeFocus(this, (Spannable) mText, direction);
7050                }
7051
7052                // The DecorView does not have focus when the 'Done' ExtractEditText button is
7053                // pressed. Since it is the ViewRoot's mView, it requests focus before
7054                // ExtractEditText clears focus, which gives focus to the ExtractEditText.
7055                // This special case ensure that we keep current selection in that case.
7056                // It would be better to know why the DecorView does not have focus at that time.
7057                if (((this instanceof ExtractEditText) || mSelectionMoved) &&
7058                        selStart >= 0 && selEnd >= 0) {
7059                    /*
7060                     * Someone intentionally set the selection, so let them
7061                     * do whatever it is that they wanted to do instead of
7062                     * the default on-focus behavior.  We reset the selection
7063                     * here instead of just skipping the onTakeFocus() call
7064                     * because some movement methods do something other than
7065                     * just setting the selection in theirs and we still
7066                     * need to go through that path.
7067                     */
7068                    Selection.setSelection((Spannable) mText, selStart, selEnd);
7069                }
7070
7071                if (mSelectAllOnFocus) {
7072                    selectAll();
7073                }
7074
7075                mTouchFocusSelected = true;
7076            }
7077
7078            mFrozenWithFocus = false;
7079            mSelectionMoved = false;
7080
7081            if (mText instanceof Spannable) {
7082                Spannable sp = (Spannable) mText;
7083                MetaKeyKeyListener.resetMetaState(sp);
7084            }
7085
7086            makeBlink();
7087
7088            if (mError != null) {
7089                showError();
7090            }
7091        } else {
7092            if (mError != null) {
7093                hideError();
7094            }
7095            // Don't leave us in the middle of a batch edit.
7096            onEndBatchEdit();
7097
7098            hideInsertionPointCursorController();
7099            if (this instanceof ExtractEditText) {
7100                // terminateTextSelectionMode removes selection, which we want to keep when
7101                // ExtractEditText goes out of focus.
7102                final int selStart = getSelectionStart();
7103                final int selEnd = getSelectionEnd();
7104                terminateSelectionActionMode();
7105                Selection.setSelection((Spannable) mText, selStart, selEnd);
7106            } else {
7107                terminateSelectionActionMode();
7108            }
7109
7110            // No need to create the controller
7111            if (mSelectionModifierCursorController != null) {
7112                mSelectionModifierCursorController.resetTouchOffsets();
7113            }
7114        }
7115
7116        startStopMarquee(focused);
7117
7118        if (mTransformation != null) {
7119            mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect);
7120        }
7121
7122        super.onFocusChanged(focused, direction, previouslyFocusedRect);
7123    }
7124
7125    private int getLastTapPosition() {
7126        // No need to create the controller at that point, no last tap position saved
7127        if (mSelectionModifierCursorController != null) {
7128            int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset();
7129            if (lastTapPosition >= 0) {
7130                // Safety check, should not be possible.
7131                if (lastTapPosition > mText.length()) {
7132                    Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs "
7133                            + mText.length() + ")");
7134                    lastTapPosition = mText.length();
7135                }
7136                return lastTapPosition;
7137            }
7138        }
7139
7140        return -1;
7141    }
7142
7143    @Override
7144    public void onWindowFocusChanged(boolean hasWindowFocus) {
7145        super.onWindowFocusChanged(hasWindowFocus);
7146
7147        if (hasWindowFocus) {
7148            if (mBlink != null) {
7149                mBlink.uncancel();
7150
7151                if (isFocused()) {
7152                    mShowCursor = SystemClock.uptimeMillis();
7153                    makeBlink();
7154                }
7155            }
7156        } else {
7157            if (mBlink != null) {
7158                mBlink.cancel();
7159            }
7160            // Don't leave us in the middle of a batch edit.
7161            onEndBatchEdit();
7162            if (mInputContentType != null) {
7163                mInputContentType.enterDown = false;
7164            }
7165            hideControllers();
7166        }
7167
7168        startStopMarquee(hasWindowFocus);
7169    }
7170
7171    @Override
7172    protected void onVisibilityChanged(View changedView, int visibility) {
7173        super.onVisibilityChanged(changedView, visibility);
7174        if (visibility != VISIBLE) {
7175            hideControllers();
7176        }
7177    }
7178
7179    /**
7180     * Use {@link BaseInputConnection#removeComposingSpans
7181     * BaseInputConnection.removeComposingSpans()} to remove any IME composing
7182     * state from this text view.
7183     */
7184    public void clearComposingText() {
7185        if (mText instanceof Spannable) {
7186            BaseInputConnection.removeComposingSpans((Spannable)mText);
7187        }
7188    }
7189
7190    @Override
7191    public void setSelected(boolean selected) {
7192        boolean wasSelected = isSelected();
7193
7194        super.setSelected(selected);
7195
7196        if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
7197            if (selected) {
7198                startMarquee();
7199            } else {
7200                stopMarquee();
7201            }
7202        }
7203    }
7204
7205    class CommitSelectionReceiver extends ResultReceiver {
7206        private final int mPrevStart, mPrevEnd;
7207
7208        public CommitSelectionReceiver(int prevStart, int prevEnd) {
7209            super(getHandler());
7210            mPrevStart = prevStart;
7211            mPrevEnd = prevEnd;
7212        }
7213
7214        @Override
7215        protected void onReceiveResult(int resultCode, Bundle resultData) {
7216            // If this tap was actually used to show the IMM, leave cursor or selection unchanged
7217            // by restoring its previous position.
7218            if (resultCode == InputMethodManager.RESULT_SHOWN) {
7219                final int len = mText.length();
7220                int start = Math.min(len, mPrevStart);
7221                int end = Math.min(len, mPrevEnd);
7222                Selection.setSelection((Spannable)mText, start, end);
7223
7224                boolean selectAllGotFocus = mSelectAllOnFocus && mTouchFocusSelected;
7225                if (hasSelection() && !selectAllGotFocus) {
7226                    startSelectionActionMode();
7227                }
7228            }
7229        }
7230    }
7231
7232    @Override
7233    public boolean onTouchEvent(MotionEvent event) {
7234        final int action = event.getActionMasked();
7235
7236        if (hasInsertionController()) {
7237            getInsertionController().onTouchEvent(event);
7238        }
7239        if (hasSelectionController()) {
7240            getSelectionController().onTouchEvent(event);
7241        }
7242
7243        if (action == MotionEvent.ACTION_DOWN) {
7244            mLastDownPositionX = (int) event.getX();
7245            mLastDownPositionY = (int) event.getY();
7246
7247            // Reset this state; it will be re-set if super.onTouchEvent
7248            // causes focus to move to the view.
7249            mTouchFocusSelected = false;
7250            mIgnoreActionUpEvent = false;
7251        }
7252
7253        final boolean superResult = super.onTouchEvent(event);
7254
7255        /*
7256         * Don't handle the release after a long press, because it will
7257         * move the selection away from whatever the menu action was
7258         * trying to affect.
7259         */
7260        if (mDiscardNextActionUp && action == MotionEvent.ACTION_UP) {
7261            mDiscardNextActionUp = false;
7262            return superResult;
7263        }
7264
7265        if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()
7266                && mText instanceof Spannable && mLayout != null) {
7267            boolean handled = false;
7268
7269            // Save previous selection, in case this event is used to show the IME.
7270            int oldSelStart = getSelectionStart();
7271            int oldSelEnd = getSelectionEnd();
7272
7273            final int oldScrollX = mScrollX;
7274            final int oldScrollY = mScrollY;
7275
7276            if (mMovement != null) {
7277                handled |= mMovement.onTouchEvent(this, (Spannable) mText, event);
7278            }
7279
7280            if (mLinksClickable && mAutoLinkMask != 0 && mTextIsSelectable &&
7281                    action == MotionEvent.ACTION_UP && !mIgnoreActionUpEvent && isFocused()) {
7282                // The LinkMovementMethod which should handle taps on links has not been installed
7283                // to support text selection. We reproduce its behavior here to open links.
7284                ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(),
7285                        getSelectionEnd(), ClickableSpan.class);
7286
7287                if (links.length != 0) {
7288                    links[0].onClick(this);
7289                    handled = true;
7290                }
7291            }
7292
7293            if (isTextEditable() || mTextIsSelectable) {
7294                if (mScrollX != oldScrollX || mScrollY != oldScrollY) {
7295                    // Hide insertion anchor while scrolling. Leave selection.
7296                    hideInsertionPointCursorController();
7297                    // No need to create the controller, since there is nothing to update.
7298                    if (mSelectionModifierCursorController != null &&
7299                            mSelectionModifierCursorController.isShowing()) {
7300                        mSelectionModifierCursorController.updatePosition();
7301                    }
7302                }
7303                if (action == MotionEvent.ACTION_UP && !mIgnoreActionUpEvent && isFocused()) {
7304                    InputMethodManager imm = (InputMethodManager)
7305                    getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
7306
7307                    CommitSelectionReceiver csr = null;
7308                    if (getSelectionStart() != oldSelStart || getSelectionEnd() != oldSelEnd ||
7309                            didTouchFocusSelect()) {
7310                        csr = new CommitSelectionReceiver(oldSelStart, oldSelEnd);
7311                    }
7312
7313                    if (!mTextIsSelectable) {
7314                        // Show the IME, except when selecting in read-only text.
7315                        handled |= imm.showSoftInput(this, 0, csr) && (csr != null);
7316                    }
7317
7318                    stopSelectionActionMode();
7319                    boolean selectAllGotFocus = mSelectAllOnFocus && mTouchFocusSelected;
7320                    if (hasInsertionController() && !selectAllGotFocus) {
7321                        getInsertionController().show();
7322                    }
7323                }
7324            }
7325
7326            if (handled) {
7327                return true;
7328            }
7329        }
7330
7331        return superResult;
7332    }
7333
7334    private void prepareCursorControllers() {
7335        boolean windowSupportsHandles = false;
7336
7337        ViewGroup.LayoutParams params = getRootView().getLayoutParams();
7338        if (params instanceof WindowManager.LayoutParams) {
7339            WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params;
7340            windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW
7341                    || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW;
7342        }
7343
7344        mInsertionControllerEnabled = windowSupportsHandles && isTextEditable() && mCursorVisible &&
7345                mLayout != null;
7346        mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() &&
7347                mLayout != null;
7348
7349        if (!mInsertionControllerEnabled) {
7350            hideInsertionPointCursorController();
7351            mInsertionPointCursorController = null;
7352        }
7353
7354        if (!mSelectionControllerEnabled) {
7355            stopSelectionActionMode();
7356            mSelectionModifierCursorController = null;
7357        }
7358    }
7359
7360    /**
7361     * @return True iff this TextView contains a text that can be edited, or if this is
7362     * a selectable TextView.
7363     */
7364    private boolean isTextEditable() {
7365        return mText instanceof Editable && onCheckIsTextEditor() && isEnabled();
7366    }
7367
7368    /**
7369     * Returns true, only while processing a touch gesture, if the initial
7370     * touch down event caused focus to move to the text view and as a result
7371     * its selection changed.  Only valid while processing the touch gesture
7372     * of interest.
7373     */
7374    public boolean didTouchFocusSelect() {
7375        return mTouchFocusSelected;
7376    }
7377
7378    @Override
7379    public void cancelLongPress() {
7380        super.cancelLongPress();
7381        mIgnoreActionUpEvent = true;
7382    }
7383
7384    @Override
7385    public boolean onTrackballEvent(MotionEvent event) {
7386        if (mMovement != null && mText instanceof Spannable &&
7387            mLayout != null) {
7388            if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) {
7389                return true;
7390            }
7391        }
7392
7393        return super.onTrackballEvent(event);
7394    }
7395
7396    public void setScroller(Scroller s) {
7397        mScroller = s;
7398    }
7399
7400    private static class Blink extends Handler implements Runnable {
7401        private final WeakReference<TextView> mView;
7402        private boolean mCancelled;
7403
7404        public Blink(TextView v) {
7405            mView = new WeakReference<TextView>(v);
7406        }
7407
7408        public void run() {
7409            if (mCancelled) {
7410                return;
7411            }
7412
7413            removeCallbacks(Blink.this);
7414
7415            TextView tv = mView.get();
7416
7417            if (tv != null && tv.isFocused()) {
7418                int st = tv.getSelectionStart();
7419                int en = tv.getSelectionEnd();
7420
7421                if (st == en && st >= 0 && en >= 0) {
7422                    if (tv.mLayout != null) {
7423                        tv.invalidateCursorPath();
7424                    }
7425
7426                    postAtTime(this, SystemClock.uptimeMillis() + BLINK);
7427                }
7428            }
7429        }
7430
7431        void cancel() {
7432            if (!mCancelled) {
7433                removeCallbacks(Blink.this);
7434                mCancelled = true;
7435            }
7436        }
7437
7438        void uncancel() {
7439            mCancelled = false;
7440        }
7441    }
7442
7443    @Override
7444    protected float getLeftFadingEdgeStrength() {
7445        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f;
7446        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
7447            if (mMarquee != null && !mMarquee.isStopped()) {
7448                final Marquee marquee = mMarquee;
7449                if (marquee.shouldDrawLeftFade()) {
7450                    return marquee.mScroll / getHorizontalFadingEdgeLength();
7451                } else {
7452                    return 0.0f;
7453                }
7454            } else if (getLineCount() == 1) {
7455                switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
7456                    case Gravity.LEFT:
7457                        return 0.0f;
7458                    case Gravity.RIGHT:
7459                        return (mLayout.getLineRight(0) - (mRight - mLeft) -
7460                                getCompoundPaddingLeft() - getCompoundPaddingRight() -
7461                                mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength();
7462                    case Gravity.CENTER_HORIZONTAL:
7463                        return 0.0f;
7464                }
7465            }
7466        }
7467        return super.getLeftFadingEdgeStrength();
7468    }
7469
7470    @Override
7471    protected float getRightFadingEdgeStrength() {
7472        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f;
7473        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
7474            if (mMarquee != null && !mMarquee.isStopped()) {
7475                final Marquee marquee = mMarquee;
7476                return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength();
7477            } else if (getLineCount() == 1) {
7478                switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
7479                    case Gravity.LEFT:
7480                        final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() -
7481                                getCompoundPaddingRight();
7482                        final float lineWidth = mLayout.getLineWidth(0);
7483                        return (lineWidth - textWidth) / getHorizontalFadingEdgeLength();
7484                    case Gravity.RIGHT:
7485                        return 0.0f;
7486                    case Gravity.CENTER_HORIZONTAL:
7487                    case Gravity.FILL_HORIZONTAL:
7488                        return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
7489                                getCompoundPaddingLeft() - getCompoundPaddingRight())) /
7490                                getHorizontalFadingEdgeLength();
7491                }
7492            }
7493        }
7494        return super.getRightFadingEdgeStrength();
7495    }
7496
7497    @Override
7498    protected int computeHorizontalScrollRange() {
7499        if (mLayout != null) {
7500            return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ?
7501                    (int) mLayout.getLineWidth(0) : mLayout.getWidth();
7502        }
7503
7504        return super.computeHorizontalScrollRange();
7505    }
7506
7507    @Override
7508    protected int computeVerticalScrollRange() {
7509        if (mLayout != null)
7510            return mLayout.getHeight();
7511
7512        return super.computeVerticalScrollRange();
7513    }
7514
7515    @Override
7516    protected int computeVerticalScrollExtent() {
7517        return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
7518    }
7519
7520    public enum BufferType {
7521        NORMAL, SPANNABLE, EDITABLE,
7522    }
7523
7524    /**
7525     * Returns the TextView_textColor attribute from the
7526     * Resources.StyledAttributes, if set, or the TextAppearance_textColor
7527     * from the TextView_textAppearance attribute, if TextView_textColor
7528     * was not set directly.
7529     */
7530    public static ColorStateList getTextColors(Context context, TypedArray attrs) {
7531        ColorStateList colors;
7532        colors = attrs.getColorStateList(com.android.internal.R.styleable.
7533                                         TextView_textColor);
7534
7535        if (colors == null) {
7536            int ap = attrs.getResourceId(com.android.internal.R.styleable.
7537                                         TextView_textAppearance, -1);
7538            if (ap != -1) {
7539                TypedArray appearance;
7540                appearance = context.obtainStyledAttributes(ap,
7541                                            com.android.internal.R.styleable.TextAppearance);
7542                colors = appearance.getColorStateList(com.android.internal.R.styleable.
7543                                                  TextAppearance_textColor);
7544                appearance.recycle();
7545            }
7546        }
7547
7548        return colors;
7549    }
7550
7551    /**
7552     * Returns the default color from the TextView_textColor attribute
7553     * from the AttributeSet, if set, or the default color from the
7554     * TextAppearance_textColor from the TextView_textAppearance attribute,
7555     * if TextView_textColor was not set directly.
7556     */
7557    public static int getTextColor(Context context,
7558                                   TypedArray attrs,
7559                                   int def) {
7560        ColorStateList colors = getTextColors(context, attrs);
7561
7562        if (colors == null) {
7563            return def;
7564        } else {
7565            return colors.getDefaultColor();
7566        }
7567    }
7568
7569    @Override
7570    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7571        final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK;
7572        if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) {
7573            switch (keyCode) {
7574            case KeyEvent.KEYCODE_A:
7575                if (canSelectText()) {
7576                    return onTextContextMenuItem(ID_SELECT_ALL);
7577                }
7578                break;
7579            case KeyEvent.KEYCODE_X:
7580                if (canCut()) {
7581                    return onTextContextMenuItem(ID_CUT);
7582                }
7583                break;
7584            case KeyEvent.KEYCODE_C:
7585                if (canCopy()) {
7586                    return onTextContextMenuItem(ID_COPY);
7587                }
7588                break;
7589            case KeyEvent.KEYCODE_V:
7590                if (canPaste()) {
7591                    return onTextContextMenuItem(ID_PASTE);
7592                }
7593                break;
7594            }
7595        }
7596        return super.onKeyShortcut(keyCode, event);
7597    }
7598
7599    /**
7600     * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the
7601     * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have
7602     * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient.
7603     */
7604    private boolean canSelectText() {
7605        return hasSelectionController() && mText.length() != 0;
7606    }
7607
7608    /**
7609     * Test based on the <i>intrinsic</i> charateristics of the TextView.
7610     * The text must be spannable and the movement method must allow for arbitary selection.
7611     *
7612     * See also {@link #canSelectText()}.
7613     */
7614    private boolean textCanBeSelected() {
7615        // prepareCursorController() relies on this method.
7616        // If you change this condition, make sure prepareCursorController is called anywhere
7617        // the value of this condition might be changed.
7618        return mText instanceof Spannable && mMovement != null && mMovement.canSelectArbitrarily();
7619    }
7620
7621    private boolean canCut() {
7622        if (hasPasswordTransformationMethod()) {
7623            return false;
7624        }
7625
7626        if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mInput != null) {
7627            return true;
7628        }
7629
7630        return false;
7631    }
7632
7633    private boolean canCopy() {
7634        if (hasPasswordTransformationMethod()) {
7635            return false;
7636        }
7637
7638        if (mText.length() > 0 && hasSelection()) {
7639            return true;
7640        }
7641
7642        return false;
7643    }
7644
7645    private boolean canPaste() {
7646        return (mText instanceof Editable &&
7647                mInput != null &&
7648                getSelectionStart() >= 0 &&
7649                getSelectionEnd() >= 0 &&
7650                ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)).
7651                hasPrimaryClip());
7652    }
7653
7654    private boolean isWordCharacter(int c, int type) {
7655        return (c == '\'' || c == '"' ||
7656                type == Character.UPPERCASE_LETTER ||
7657                type == Character.LOWERCASE_LETTER ||
7658                type == Character.TITLECASE_LETTER ||
7659                type == Character.MODIFIER_LETTER ||
7660                type == Character.OTHER_LETTER || // Should handle asian characters
7661                type == Character.DECIMAL_DIGIT_NUMBER);
7662    }
7663
7664    /**
7665     * Returns the offsets delimiting the 'word' located at position offset.
7666     *
7667     * @param offset An offset in the text.
7668     * @return The offsets for the start and end of the word located at <code>offset</code>.
7669     * The two ints offsets are packed in a long using {@link #packRangeInLong(int, int)}.
7670     * Returns -1 if no valid word was found.
7671     */
7672    private long getWordLimitsAt(int offset) {
7673        int klass = mInputType & InputType.TYPE_MASK_CLASS;
7674        int variation = mInputType & InputType.TYPE_MASK_VARIATION;
7675
7676        // Text selection is not permitted in password fields
7677        if (hasPasswordTransformationMethod()) {
7678            return -1;
7679        }
7680
7681        final int len = mText.length();
7682
7683        // Specific text fields: always select the entire text
7684        if (klass == InputType.TYPE_CLASS_NUMBER ||
7685                klass == InputType.TYPE_CLASS_PHONE ||
7686                klass == InputType.TYPE_CLASS_DATETIME ||
7687                variation == InputType.TYPE_TEXT_VARIATION_URI ||
7688                variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
7689                variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ||
7690                variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
7691            return len > 0 ? packRangeInLong(0, len) : -1;
7692        }
7693
7694        int end = Math.min(offset, len);
7695        if (end < 0) {
7696            return -1;
7697        }
7698
7699        final int MAX_LENGTH = 48;
7700        int start = end;
7701
7702        for (; start > 0; start--) {
7703            final char c = mTransformed.charAt(start - 1);
7704            final int type = Character.getType(c);
7705            if (start == end && type == Character.OTHER_PUNCTUATION) {
7706                // Cases where the text ends with a '.' and we select from the end of the line
7707                // (right after the dot), or when we select from the space character in "aaa, bbb".
7708                continue;
7709            }
7710            if (type == Character.SURROGATE) { // Two Character codepoint
7711                end = start - 1; // Recheck as a pair when scanning forward
7712                continue;
7713            }
7714            if (!isWordCharacter(c, type)) break;
7715            if ((end - start) > MAX_LENGTH) return -1;
7716        }
7717
7718        for (; end < len; end++) {
7719            final int c = Character.codePointAt(mTransformed, end);
7720            final int type = Character.getType(c);
7721            if (!isWordCharacter(c, type)) break;
7722            if ((end - start) > MAX_LENGTH) return -1;
7723            if (c > 0xFFFF) { // Two Character codepoint
7724                end++;
7725            }
7726        }
7727
7728        if (start == end) {
7729            return -1;
7730        }
7731
7732        // Two ints packed in a long
7733        return packRangeInLong(start, end);
7734    }
7735
7736    private static long packRangeInLong(int start, int end) {
7737        return (((long) start) << 32) | end;
7738    }
7739
7740    private static int extractRangeStartFromLong(long range) {
7741        return (int) (range >>> 32);
7742    }
7743
7744    private static int extractRangeEndFromLong(long range) {
7745        return (int) (range & 0x00000000FFFFFFFFL);
7746    }
7747
7748    private void selectAll() {
7749        Selection.setSelection((Spannable) mText, 0, mText.length());
7750    }
7751
7752    private void selectCurrentWord() {
7753        if (!canSelectText()) {
7754            return;
7755        }
7756
7757        if (hasPasswordTransformationMethod()) {
7758            // Always select all on a password field.
7759            // Cut/copy menu entries are not available for passwords, but being able to select all
7760            // is however useful to delete or paste to replace the entire content.
7761            selectAll();
7762            return;
7763        }
7764
7765        long lastTouchOffsets = getLastTouchOffsets();
7766        final int minOffset = extractRangeStartFromLong(lastTouchOffsets);
7767        final int maxOffset = extractRangeEndFromLong(lastTouchOffsets);
7768
7769        int selectionStart, selectionEnd;
7770
7771        // If a URLSpan (web address, email, phone...) is found at that position, select it.
7772        URLSpan[] urlSpans = ((Spanned) mText).getSpans(minOffset, maxOffset, URLSpan.class);
7773        if (urlSpans.length == 1) {
7774            URLSpan url = urlSpans[0];
7775            selectionStart = ((Spanned) mText).getSpanStart(url);
7776            selectionEnd = ((Spanned) mText).getSpanEnd(url);
7777        } else {
7778            long wordLimits = getWordLimitsAt(minOffset);
7779            if (wordLimits >= 0) {
7780                selectionStart = extractRangeStartFromLong(wordLimits);
7781            } else {
7782                selectionStart = Math.max(minOffset - 5, 0);
7783            }
7784
7785            wordLimits = getWordLimitsAt(maxOffset);
7786            if (wordLimits >= 0) {
7787                selectionEnd = extractRangeEndFromLong(wordLimits);
7788            } else {
7789                selectionEnd = Math.min(maxOffset + 5, mText.length());
7790            }
7791        }
7792
7793        Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
7794    }
7795
7796    private long getLastTouchOffsets() {
7797        int minOffset, maxOffset;
7798
7799        if (mContextMenuTriggeredByKey) {
7800            minOffset = getSelectionStart();
7801            maxOffset = getSelectionEnd();
7802        } else {
7803            SelectionModifierCursorController selectionController = getSelectionController();
7804            minOffset = selectionController.getMinTouchOffset();
7805            maxOffset = selectionController.getMaxTouchOffset();
7806        }
7807
7808        return packRangeInLong(minOffset, maxOffset);
7809    }
7810
7811    @Override
7812    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
7813        if (!isShown()) {
7814            return false;
7815        }
7816
7817        final boolean isPassword = hasPasswordTransformationMethod();
7818
7819        if (!isPassword) {
7820            CharSequence text = getText();
7821            if (TextUtils.isEmpty(text)) {
7822                text = getHint();
7823            }
7824            if (!TextUtils.isEmpty(text)) {
7825                if (text.length() > AccessibilityEvent.MAX_TEXT_LENGTH) {
7826                    text = text.subSequence(0, AccessibilityEvent.MAX_TEXT_LENGTH + 1);
7827                }
7828                event.getText().add(text);
7829            }
7830        } else {
7831            event.setPassword(isPassword);
7832        }
7833        return false;
7834    }
7835
7836    void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText,
7837            int fromIndex, int removedCount, int addedCount) {
7838        AccessibilityEvent event =
7839            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
7840        event.setFromIndex(fromIndex);
7841        event.setRemovedCount(removedCount);
7842        event.setAddedCount(addedCount);
7843        event.setBeforeText(beforeText);
7844        sendAccessibilityEventUnchecked(event);
7845    }
7846
7847    @Override
7848    protected void onCreateContextMenu(ContextMenu menu) {
7849        super.onCreateContextMenu(menu);
7850        boolean added = false;
7851        mContextMenuTriggeredByKey = mDPadCenterIsDown || mEnterKeyIsDown;
7852        // Problem with context menu on long press: the menu appears while the key in down and when
7853        // the key is released, the view does not receive the key_up event.
7854        // We need two layers of flags: mDPadCenterIsDown and mEnterKeyIsDown are set in key down/up
7855        // events. We cannot simply clear these flags in onTextContextMenuItem since
7856        // it may not be called (if the user/ discards the context menu with the back key).
7857        // We clear these flags here and mContextMenuTriggeredByKey saves that state so that it is
7858        // available in onTextContextMenuItem.
7859        mDPadCenterIsDown = mEnterKeyIsDown = false;
7860
7861        MenuHandler handler = new MenuHandler();
7862
7863        if (mText instanceof Spanned && hasSelectionController()) {
7864            long lastTouchOffset = getLastTouchOffsets();
7865            final int selStart = extractRangeStartFromLong(lastTouchOffset);
7866            final int selEnd = extractRangeEndFromLong(lastTouchOffset);
7867
7868            URLSpan[] urls = ((Spanned) mText).getSpans(selStart, selEnd, URLSpan.class);
7869            if (urls.length > 0) {
7870                menu.add(0, ID_COPY_URL, 0, com.android.internal.R.string.copyUrl).
7871                        setOnMenuItemClickListener(handler);
7872
7873                added = true;
7874            }
7875        }
7876
7877        // The context menu is not empty, which will prevent the selection mode from starting.
7878        // Add a entry to start it in the context menu.
7879        // TODO Does not handle the case where a subclass does not call super.thisMethod or
7880        // populates the menu AFTER this call.
7881        if (menu.size() > 0) {
7882            menu.add(0, ID_SELECTION_MODE, 0, com.android.internal.R.string.selectTextMode).
7883                    setOnMenuItemClickListener(handler);
7884            added = true;
7885        }
7886
7887        if (added) {
7888            menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle);
7889        }
7890    }
7891
7892    /**
7893     * Returns whether this text view is a current input method target.  The
7894     * default implementation just checks with {@link InputMethodManager}.
7895     */
7896    public boolean isInputMethodTarget() {
7897        InputMethodManager imm = InputMethodManager.peekInstance();
7898        return imm != null && imm.isActive(this);
7899    }
7900
7901    // Selection context mode
7902    private static final int ID_SELECT_ALL = android.R.id.selectAll;
7903    private static final int ID_CUT = android.R.id.cut;
7904    private static final int ID_COPY = android.R.id.copy;
7905    private static final int ID_PASTE = android.R.id.paste;
7906    // Context menu entries
7907    private static final int ID_COPY_URL = android.R.id.copyUrl;
7908    private static final int ID_SELECTION_MODE = android.R.id.selectTextMode;
7909
7910    private class MenuHandler implements MenuItem.OnMenuItemClickListener {
7911        public boolean onMenuItemClick(MenuItem item) {
7912            return onTextContextMenuItem(item.getItemId());
7913        }
7914    }
7915
7916    /**
7917     * Called when a context menu option for the text view is selected.  Currently
7918     * this will be {@link android.R.id#copyUrl}, {@link android.R.id#selectTextMode},
7919     * {@link android.R.id#selectAll}, {@link android.R.id#paste}, {@link android.R.id#cut}
7920     * or {@link android.R.id#copy}.
7921     */
7922    public boolean onTextContextMenuItem(int id) {
7923        int min = 0;
7924        int max = mText.length();
7925
7926        if (isFocused()) {
7927            final int selStart = getSelectionStart();
7928            final int selEnd = getSelectionEnd();
7929
7930            min = Math.max(0, Math.min(selStart, selEnd));
7931            max = Math.max(0, Math.max(selStart, selEnd));
7932        }
7933
7934        ClipboardManager clipboard = (ClipboardManager)getContext()
7935                .getSystemService(Context.CLIPBOARD_SERVICE);
7936
7937        switch (id) {
7938            case ID_COPY_URL:
7939                URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class);
7940                if (urls.length >= 1) {
7941                    ClipData clip = null;
7942                    for (int i=0; i<urls.length; i++) {
7943                        Uri uri = Uri.parse(urls[0].getURL());
7944                        if (clip == null) {
7945                            clip = ClipData.newRawUri(null, null, uri);
7946                        } else {
7947                            clip.addItem(new ClipData.Item(uri));
7948                        }
7949                    }
7950                    if (clip != null) {
7951                        setPrimaryClip(clip);
7952                    }
7953                }
7954                stopSelectionActionMode();
7955                return true;
7956
7957            case ID_SELECTION_MODE:
7958                if (mSelectionActionMode != null) {
7959                    // Selection mode is already started, simply change selected part.
7960                    updateSelectedRegion();
7961                } else {
7962                    startSelectionActionMode();
7963                }
7964                return true;
7965
7966            case ID_SELECT_ALL:
7967                selectAll();
7968                // Update controller positions after selection change.
7969                if (hasSelectionController()) {
7970                    getSelectionController().show();
7971                }
7972                return true;
7973
7974            case ID_PASTE:
7975                paste(min, max);
7976                return true;
7977
7978            case ID_CUT:
7979                setPrimaryClip(ClipData.newPlainText(null, null,
7980                        mTransformed.subSequence(min, max)));
7981                ((Editable) mText).delete(min, max);
7982                stopSelectionActionMode();
7983                return true;
7984
7985            case ID_COPY:
7986                setPrimaryClip(ClipData.newPlainText(null, null,
7987                        mTransformed.subSequence(min, max)));
7988                stopSelectionActionMode();
7989                return true;
7990        }
7991        return false;
7992    }
7993
7994    /**
7995     * Prepare text so that there are not zero or two spaces at beginning and end of region defined
7996     * by [min, max] when replacing this region by paste.
7997     * Note that if there were two spaces (or more) at that position before, they are kept. We just
7998     * make sure we do not add an extra one from the paste content.
7999     */
8000    private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) {
8001        if (paste.length() > 0) {
8002            if (min > 0) {
8003                final char charBefore = mTransformed.charAt(min - 1);
8004                final char charAfter = paste.charAt(0);
8005
8006                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
8007                    // Two spaces at beginning of paste: remove one
8008                    final int originalLength = mText.length();
8009                    ((Editable) mText).delete(min - 1, min);
8010                    // Due to filters, there is no guarantee that exactly one character was
8011                    // removed: count instead.
8012                    final int delta = mText.length() - originalLength;
8013                    min += delta;
8014                    max += delta;
8015                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
8016                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
8017                    // No space at beginning of paste: add one
8018                    final int originalLength = mText.length();
8019                    ((Editable) mText).replace(min, min, " ");
8020                    // Taking possible filters into account as above.
8021                    final int delta = mText.length() - originalLength;
8022                    min += delta;
8023                    max += delta;
8024                }
8025            }
8026
8027            if (max < mText.length()) {
8028                final char charBefore = paste.charAt(paste.length() - 1);
8029                final char charAfter = mTransformed.charAt(max);
8030
8031                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
8032                    // Two spaces at end of paste: remove one
8033                    ((Editable) mText).delete(max, max + 1);
8034                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
8035                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
8036                    // No space at end of paste: add one
8037                    ((Editable) mText).replace(max, max, " ");
8038                }
8039            }
8040        }
8041
8042        return packRangeInLong(min, max);
8043    }
8044
8045    private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) {
8046        TextView shadowView = (TextView) inflate(mContext,
8047                com.android.internal.R.layout.text_drag_thumbnail, null);
8048
8049        if (shadowView == null) {
8050            throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
8051        }
8052
8053        if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) {
8054            text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH);
8055        }
8056        shadowView.setText(text);
8057        shadowView.setTextColor(getTextColors());
8058
8059        shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge);
8060        shadowView.setGravity(Gravity.CENTER);
8061
8062        shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
8063                ViewGroup.LayoutParams.WRAP_CONTENT));
8064
8065        final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
8066        shadowView.measure(size, size);
8067
8068        shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
8069        shadowView.invalidate();
8070        return new DragShadowBuilder(shadowView);
8071    }
8072
8073    private static class DragLocalState {
8074        public TextView sourceTextView;
8075        public int start, end;
8076
8077        public DragLocalState(TextView sourceTextView, int start, int end) {
8078            this.sourceTextView = sourceTextView;
8079            this.start = start;
8080            this.end = end;
8081        }
8082    }
8083
8084    @Override
8085    public boolean performLongClick() {
8086        if (super.performLongClick()) {
8087            mDiscardNextActionUp = true;
8088            return true;
8089        }
8090
8091        // Long press in empty space moves cursor and shows the Paste affordance if available.
8092        if (!isPositionOnText(mLastDownPositionX, mLastDownPositionY) &&
8093                mInsertionControllerEnabled) {
8094            final int offset = getOffset(mLastDownPositionX, mLastDownPositionY);
8095            stopSelectionActionMode();
8096            Selection.setSelection((Spannable)mText, offset);
8097            getInsertionController().show(0);
8098            mDiscardNextActionUp = true;
8099            return true;
8100        }
8101
8102        if (mSelectionActionMode != null) {
8103            if (touchPositionIsInSelection()) {
8104                // Start a drag
8105                final int start = getSelectionStart();
8106                final int end = getSelectionEnd();
8107                CharSequence selectedText = mTransformed.subSequence(start, end);
8108                ClipData data = ClipData.newPlainText(null, null, selectedText);
8109                DragLocalState localState = new DragLocalState(this, start, end);
8110                startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0);
8111                stopSelectionActionMode();
8112            } else {
8113                updateSelectedRegion();
8114            }
8115            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
8116            mDiscardNextActionUp = true;
8117            return true;
8118        }
8119
8120        // Start a new selection
8121        if (startSelectionActionMode()) {
8122            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
8123            mDiscardNextActionUp = true;
8124            return true;
8125        }
8126
8127        return false;
8128    }
8129
8130    /**
8131     * When selection mode is already started, this method simply updates the selected part of text
8132     * to the text under the finger.
8133     */
8134    private void updateSelectedRegion() {
8135        // Start a new selection at current position, keep selectionAction mode on
8136        selectCurrentWord();
8137        // Updates handles' positions
8138        getSelectionController().show();
8139    }
8140
8141    private boolean touchPositionIsInSelection() {
8142        int selectionStart = getSelectionStart();
8143        int selectionEnd = getSelectionEnd();
8144
8145        if (selectionStart == selectionEnd) {
8146            return false;
8147        }
8148
8149        if (selectionStart > selectionEnd) {
8150            int tmp = selectionStart;
8151            selectionStart = selectionEnd;
8152            selectionEnd = tmp;
8153            Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
8154        }
8155
8156        SelectionModifierCursorController selectionController = getSelectionController();
8157        int minOffset = selectionController.getMinTouchOffset();
8158        int maxOffset = selectionController.getMaxTouchOffset();
8159
8160        return ((minOffset >= selectionStart) && (maxOffset < selectionEnd));
8161    }
8162
8163    /**
8164     * If provided, this ActionMode.Callback will be used to create the ActionMode when text
8165     * selection is initiated in this View.
8166     *
8167     * The standard implementation populates the menu with a subset of Select All, Cut, Copy and
8168     * Paste actions, depending on what this View supports.
8169     *
8170     * A custom implementation can add new entries in the default menu in its
8171     * {@link ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The default actions
8172     * can also be removed from the menu using {@link Menu#removeItem(int)} and passing
8173     * {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} or
8174     * {@link android.R.id#paste} ids as parameters.
8175     *
8176     * Action click events should be handled by the custom implementation of
8177     * {@link ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}.
8178     *
8179     * Note that text selection mode is not started when a TextView receives focus and the
8180     * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in
8181     * that case, to allow for quick replacement.
8182     */
8183    public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) {
8184        mCustomSelectionActionModeCallback = actionModeCallback;
8185    }
8186
8187    /**
8188     * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null.
8189     *
8190     * @return The current custom selection callback.
8191     */
8192    public ActionMode.Callback getCustomSelectionActionModeCallback() {
8193        return mCustomSelectionActionModeCallback;
8194    }
8195
8196    /**
8197     *
8198     * @return true if the selection mode was actually started.
8199     */
8200    private boolean startSelectionActionMode() {
8201        if (mSelectionActionMode != null) {
8202            // Selection action mode is already started
8203            return false;
8204        }
8205
8206        if (!canSelectText() || !requestFocus()) {
8207            Log.w(LOG_TAG, "TextView does not support text selection. Action mode cancelled.");
8208            return false;
8209        }
8210
8211        if (!hasSelection()) {
8212            // If selection mode is started after a device rotation, there is already a selection.
8213            selectCurrentWord();
8214        }
8215
8216        if (!mTextIsSelectable) {
8217            // Show the IME, except when selection non editable text.
8218            final InputMethodManager imm = (InputMethodManager)
8219                    getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
8220            imm.showSoftInput(this, 0, null);
8221        }
8222
8223        ActionMode.Callback actionModeCallback = new SelectionActionModeCallback();
8224        mSelectionActionMode = startActionMode(actionModeCallback);
8225        return mSelectionActionMode != null;
8226    }
8227
8228    /**
8229     * Same as {@link #stopSelectionActionMode()}, except that there is no cursor controller
8230     * fade out animation. Needed since the drawable and their alpha values are shared by all
8231     * TextViews. Switching from one TextView to another would fade the cursor controllers in the
8232     * new one otherwise.
8233     */
8234    private void terminateSelectionActionMode() {
8235        stopSelectionActionMode();
8236
8237        // No need to create the controller, nothing to cancel in that case.
8238        if (mSelectionModifierCursorController != null) {
8239            mSelectionModifierCursorController.cancelFadeOutAnimation();
8240        }
8241    }
8242
8243    private void stopSelectionActionMode() {
8244        if (mSelectionActionMode != null) {
8245            // This will hide the mSelectionModifierCursorController
8246            mSelectionActionMode.finish();
8247        }
8248    }
8249
8250    /**
8251     * Paste clipboard content between min and max positions.
8252     */
8253    private void paste(int min, int max) {
8254        ClipboardManager clipboard =
8255            (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
8256        ClipData clip = clipboard.getPrimaryClip();
8257        if (clip != null) {
8258            boolean didfirst = false;
8259            for (int i=0; i<clip.getItemCount(); i++) {
8260                CharSequence paste = clip.getItem(i).coerceToText(getContext());
8261                if (paste != null) {
8262                    if (!didfirst) {
8263                        long minMax = prepareSpacesAroundPaste(min, max, paste);
8264                        min = extractRangeStartFromLong(minMax);
8265                        max = extractRangeEndFromLong(minMax);
8266                        Selection.setSelection((Spannable) mText, max);
8267                        ((Editable) mText).replace(min, max, paste);
8268                    } else {
8269                        ((Editable) mText).insert(getSelectionEnd(), "\n");
8270                        ((Editable) mText).insert(getSelectionEnd(), paste);
8271                    }
8272                }
8273            }
8274            stopSelectionActionMode();
8275            sLastCutOrCopyTime = 0;
8276        }
8277    }
8278
8279    private void setPrimaryClip(ClipData clip) {
8280        ClipboardManager clipboard = (ClipboardManager) getContext().
8281                getSystemService(Context.CLIPBOARD_SERVICE);
8282        clipboard.setPrimaryClip(clip);
8283        sLastCutOrCopyTime = SystemClock.uptimeMillis();
8284    }
8285
8286    /**
8287     * An ActionMode Callback class that is used to provide actions while in text selection mode.
8288     *
8289     * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending
8290     * on which of these this TextView supports.
8291     */
8292    private class SelectionActionModeCallback implements ActionMode.Callback {
8293
8294        @Override
8295        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
8296            TypedArray styledAttributes = mContext.obtainStyledAttributes(R.styleable.Theme);
8297
8298            mode.setTitle(mContext.getString(com.android.internal.R.string.textSelectionCABTitle));
8299            mode.setSubtitle(null);
8300
8301            menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll).
8302                    setAlphabeticShortcut('a').
8303                    setShowAsAction(
8304                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
8305
8306            if (canCut()) {
8307                menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut).
8308                    setIcon(styledAttributes.getResourceId(
8309                            R.styleable.Theme_actionModeCutDrawable, 0)).
8310                    setAlphabeticShortcut('x').
8311                    setShowAsAction(
8312                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
8313            }
8314
8315            if (canCopy()) {
8316                menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy).
8317                    setIcon(styledAttributes.getResourceId(
8318                            R.styleable.Theme_actionModeCopyDrawable, 0)).
8319                    setAlphabeticShortcut('c').
8320                    setShowAsAction(
8321                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
8322            }
8323
8324            if (canPaste()) {
8325                menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste).
8326                        setIcon(styledAttributes.getResourceId(
8327                                R.styleable.Theme_actionModePasteDrawable, 0)).
8328                        setAlphabeticShortcut('v').
8329                        setShowAsAction(
8330                                MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
8331            }
8332
8333            styledAttributes.recycle();
8334
8335            if (mCustomSelectionActionModeCallback != null) {
8336                mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu);
8337            }
8338
8339            if (menu.hasVisibleItems() || mode.getCustomView() != null) {
8340                getSelectionController().show();
8341                return true;
8342            } else {
8343                return false;
8344            }
8345        }
8346
8347        @Override
8348        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
8349            if (mCustomSelectionActionModeCallback != null) {
8350                return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu);
8351            }
8352            return true;
8353        }
8354
8355        @Override
8356        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
8357            if (mCustomSelectionActionModeCallback != null &&
8358                 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) {
8359                return true;
8360            }
8361            return onTextContextMenuItem(item.getItemId());
8362        }
8363
8364        @Override
8365        public void onDestroyActionMode(ActionMode mode) {
8366            if (mCustomSelectionActionModeCallback != null) {
8367                mCustomSelectionActionModeCallback.onDestroyActionMode(mode);
8368            }
8369            Selection.setSelection((Spannable) mText, getSelectionEnd());
8370
8371            if (mSelectionModifierCursorController != null) {
8372                mSelectionModifierCursorController.hide();
8373            }
8374
8375            mSelectionActionMode = null;
8376        }
8377    }
8378
8379    /**
8380     * A CursorController instance can be used to control a cursor in the text.
8381     * It is not used outside of {@link TextView}.
8382     * @hide
8383     */
8384    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
8385        /**
8386         * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}.
8387         * See also {@link #hide()}.
8388         */
8389        public void show();
8390
8391        /**
8392         * Hide the cursor controller from screen.
8393         * See also {@link #show()}.
8394         */
8395        public void hide();
8396
8397        /**
8398         * @return true if the CursorController is currently visible
8399         */
8400        public boolean isShowing();
8401
8402        /**
8403         * Update the controller's position.
8404         */
8405        public void updatePosition(HandleView handle, int x, int y);
8406
8407        public void updatePosition();
8408
8409        /**
8410         * This method is called by {@link #onTouchEvent(MotionEvent)} and gives the controller
8411         * a chance to become active and/or visible.
8412         * @param event The touch event
8413         */
8414        public boolean onTouchEvent(MotionEvent event);
8415
8416        /**
8417         * Called when the view is detached from window. Perform house keeping task, such as
8418         * stopping Runnable thread that would otherwise keep a reference on the context, thus
8419         * preventing the activity to be recycled.
8420         */
8421        public void onDetached();
8422    }
8423
8424    private class PastePopupMenu implements OnClickListener {
8425        private PopupWindow mContainer;
8426        private int mPositionX;
8427        private int mPositionY;
8428        private View mPasteView, mNoPasteView;
8429
8430        public PastePopupMenu() {
8431            mContainer = new PopupWindow(TextView.this.mContext, null,
8432                    com.android.internal.R.attr.textSelectHandleWindowStyle);
8433            mContainer.setSplitTouchEnabled(true);
8434            mContainer.setClippingEnabled(false);
8435            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
8436
8437            mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
8438            mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
8439        }
8440
8441        private void updateContent() {
8442            View view = canPaste() ? mPasteView : mNoPasteView;
8443
8444            if (view == null) {
8445                final int layout = canPaste() ? mTextEditPasteWindowLayout :
8446                    mTextEditNoPasteWindowLayout;
8447                LayoutInflater inflater = (LayoutInflater)TextView.this.mContext.
8448                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
8449                if (inflater != null) {
8450                    view = inflater.inflate(layout, null);
8451                }
8452
8453                if (view == null) {
8454                    throw new IllegalArgumentException("Unable to inflate TextEdit paste window");
8455                }
8456
8457                final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
8458                view.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
8459                        ViewGroup.LayoutParams.WRAP_CONTENT));
8460                view.measure(size, size);
8461
8462                view.setOnClickListener(this);
8463
8464                if (canPaste()) mPasteView = view;
8465                else mNoPasteView = view;
8466            }
8467
8468            mContainer.setContentView(view);
8469        }
8470
8471        public void show() {
8472            updateContent();
8473            final int[] coords = mTempCoords;
8474            TextView.this.getLocationInWindow(coords);
8475            positionAtCursor();
8476            coords[0] += mPositionX;
8477            coords[1] += mPositionY;
8478            coords[0] = Math.max(0, coords[0]);
8479            final int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels;
8480            coords[0] = Math.min(screenWidth - mContainer.getContentView().getMeasuredWidth(),
8481                    coords[0]);
8482            mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]);
8483        }
8484
8485        public void hide() {
8486            mContainer.dismiss();
8487        }
8488
8489        public boolean isShowing() {
8490            return mContainer.isShowing();
8491        }
8492
8493        @Override
8494        public void onClick(View v) {
8495            if (canPaste()) {
8496                paste(getSelectionStart(), getSelectionEnd());
8497            }
8498            hide();
8499        }
8500
8501        void positionAtCursor() {
8502            final int offset = TextView.this.getSelectionStart();
8503            View contentView = mContainer.getContentView();
8504            final int width = contentView.getMeasuredWidth();
8505            final int height = contentView.getMeasuredHeight();
8506            final int line = mLayout.getLineForOffset(offset);
8507            final int lineTop = mLayout.getLineTop(line);
8508
8509            final Rect bounds = sCursorControllerTempRect;
8510            bounds.left = (int) (mLayout.getPrimaryHorizontal(offset) - width / 2.0f);
8511            bounds.top = lineTop - height;
8512
8513            bounds.right = bounds.left + width;
8514            bounds.bottom = bounds.top + height;
8515
8516            convertFromViewportToContentCoordinates(bounds);
8517
8518            mPositionX = bounds.left;
8519            mPositionY = bounds.top;
8520        }
8521    }
8522
8523    private class HandleView extends View {
8524        private boolean mPositionOnTop = false;
8525        private Drawable mDrawable;
8526        private PopupWindow mContainer;
8527        private int mPositionX;
8528        private int mPositionY;
8529        private CursorController mController;
8530        private boolean mIsDragging;
8531        private float mTouchToWindowOffsetX;
8532        private float mTouchToWindowOffsetY;
8533        private float mHotspotX;
8534        private float mHotspotY;
8535        private int mHeight;
8536        private float mTouchOffsetY;
8537        private int mLastParentX;
8538        private int mLastParentY;
8539        private float mDownPositionX, mDownPositionY;
8540        private int mContainerPositionX, mContainerPositionY;
8541        private long mTouchTimer;
8542        private boolean mIsInsertionHandle = false;
8543        private PastePopupMenu mPastePopupWindow;
8544        private Runnable mLongPressCallback;
8545
8546        public static final int LEFT = 0;
8547        public static final int CENTER = 1;
8548        public static final int RIGHT = 2;
8549
8550        public HandleView(CursorController controller, int pos) {
8551            super(TextView.this.mContext);
8552            mController = controller;
8553            mContainer = new PopupWindow(TextView.this.mContext, null,
8554                    com.android.internal.R.attr.textSelectHandleWindowStyle);
8555            mContainer.setSplitTouchEnabled(true);
8556            mContainer.setClippingEnabled(false);
8557            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
8558
8559            setOrientation(pos);
8560        }
8561
8562        public void setOrientation(int pos) {
8563            int handleWidth;
8564            switch (pos) {
8565            case LEFT: {
8566                if (mSelectHandleLeft == null) {
8567                    mSelectHandleLeft = mContext.getResources().getDrawable(
8568                            mTextSelectHandleLeftRes);
8569                }
8570                mDrawable = mSelectHandleLeft;
8571                handleWidth = mDrawable.getIntrinsicWidth();
8572                mHotspotX = (handleWidth * 3) / 4;
8573                break;
8574            }
8575
8576            case RIGHT: {
8577                if (mSelectHandleRight == null) {
8578                    mSelectHandleRight = mContext.getResources().getDrawable(
8579                            mTextSelectHandleRightRes);
8580                }
8581                mDrawable = mSelectHandleRight;
8582                handleWidth = mDrawable.getIntrinsicWidth();
8583                mHotspotX = handleWidth / 4;
8584                break;
8585            }
8586
8587            case CENTER:
8588            default: {
8589                if (mSelectHandleCenter == null) {
8590                    mSelectHandleCenter = mContext.getResources().getDrawable(
8591                            mTextSelectHandleRes);
8592                }
8593                mDrawable = mSelectHandleCenter;
8594                handleWidth = mDrawable.getIntrinsicWidth();
8595                mHotspotX = handleWidth / 2;
8596                mIsInsertionHandle = true;
8597                break;
8598            }
8599            }
8600
8601            final int handleHeight = mDrawable.getIntrinsicHeight();
8602
8603            mTouchOffsetY = -handleHeight * 0.3f;
8604            mHotspotY = 0;
8605            mHeight = handleHeight;
8606            invalidate();
8607        }
8608
8609        @Override
8610        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
8611            setMeasuredDimension(mDrawable.getIntrinsicWidth(),
8612                    mDrawable.getIntrinsicHeight());
8613        }
8614
8615        public void show() {
8616            if (!isPositionVisible()) {
8617                hide();
8618                return;
8619            }
8620            mContainer.setContentView(this);
8621            final int[] coords = mTempCoords;
8622            TextView.this.getLocationInWindow(coords);
8623            mContainerPositionX = coords[0] + mPositionX;
8624            mContainerPositionY = coords[1] + mPositionY;
8625            mContainer.showAtLocation(TextView.this, 0, mContainerPositionX, mContainerPositionY);
8626
8627            // Hide paste view when handle is moved on screen.
8628            if (mPastePopupWindow != null) {
8629                mPastePopupWindow.hide();
8630            }
8631        }
8632
8633        public void hide() {
8634            mIsDragging = false;
8635            mContainer.dismiss();
8636            if (mPastePopupWindow != null) {
8637                mPastePopupWindow.hide();
8638            }
8639        }
8640
8641        public boolean isShowing() {
8642            return mContainer.isShowing();
8643        }
8644
8645        private boolean isPositionVisible() {
8646            // Always show a dragging handle.
8647            if (mIsDragging) {
8648                return true;
8649            }
8650
8651            if (isInBatchEditMode()) {
8652                return false;
8653            }
8654
8655            final int extendedPaddingTop = getExtendedPaddingTop();
8656            final int extendedPaddingBottom = getExtendedPaddingBottom();
8657            final int compoundPaddingLeft = getCompoundPaddingLeft();
8658            final int compoundPaddingRight = getCompoundPaddingRight();
8659
8660            final TextView hostView = TextView.this;
8661            final int left = 0;
8662            final int right = hostView.getWidth();
8663            final int top = 0;
8664            final int bottom = hostView.getHeight();
8665
8666            if (mTempRect == null) {
8667                mTempRect = new Rect();
8668            }
8669            final Rect clip = mTempRect;
8670            clip.left = left + compoundPaddingLeft;
8671            clip.top = top + extendedPaddingTop;
8672            clip.right = right - compoundPaddingRight;
8673            clip.bottom = bottom - extendedPaddingBottom;
8674
8675            final ViewParent parent = hostView.getParent();
8676            if (parent == null || !parent.getChildVisibleRect(hostView, clip, null)) {
8677                return false;
8678            }
8679
8680            final int[] coords = mTempCoords;
8681            hostView.getLocationInWindow(coords);
8682            final int posX = coords[0] + mPositionX + (int) mHotspotX;
8683            final int posY = coords[1] + mPositionY + (int) mHotspotY;
8684
8685            return posX >= clip.left && posX <= clip.right &&
8686                    posY >= clip.top && posY <= clip.bottom;
8687        }
8688
8689        private void moveTo(int x, int y) {
8690            mPositionX = x - TextView.this.mScrollX;
8691            mPositionY = y - TextView.this.mScrollY;
8692            if (isPositionVisible()) {
8693                int[] coords = null;
8694                if (mContainer.isShowing()) {
8695                    coords = mTempCoords;
8696                    TextView.this.getLocationInWindow(coords);
8697                    final int containerPositionX = coords[0] + mPositionX;
8698                    final int containerPositionY = coords[1] + mPositionY;
8699
8700                    if (containerPositionX != mContainerPositionX ||
8701                        containerPositionY != mContainerPositionY) {
8702                        mContainerPositionX = containerPositionX;
8703                        mContainerPositionY = containerPositionY;
8704
8705                        mContainer.update(mContainerPositionX, mContainerPositionY,
8706                                mRight - mLeft, mBottom - mTop);
8707
8708                        // Hide paste popup window as soon as a scroll occurs.
8709                        if (mPastePopupWindow != null) {
8710                            mPastePopupWindow.hide();
8711                        }
8712                    }
8713                } else {
8714                    show();
8715                }
8716
8717                if (mIsDragging) {
8718                    if (coords == null) {
8719                        coords = mTempCoords;
8720                        TextView.this.getLocationInWindow(coords);
8721                    }
8722                    if (coords[0] != mLastParentX || coords[1] != mLastParentY) {
8723                        mTouchToWindowOffsetX += coords[0] - mLastParentX;
8724                        mTouchToWindowOffsetY += coords[1] - mLastParentY;
8725                        mLastParentX = coords[0];
8726                        mLastParentY = coords[1];
8727                    }
8728                    // Hide paste popup window as soon as the handle is dragged.
8729                    if (mPastePopupWindow != null) {
8730                        mPastePopupWindow.hide();
8731                    }
8732                }
8733            } else {
8734                hide();
8735            }
8736        }
8737
8738        @Override
8739        protected void onDraw(Canvas c) {
8740            mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
8741            if (mPositionOnTop) {
8742                c.save();
8743                c.rotate(180, (mRight - mLeft) / 2, (mBottom - mTop) / 2);
8744                mDrawable.draw(c);
8745                c.restore();
8746            } else {
8747                mDrawable.draw(c);
8748            }
8749        }
8750
8751        @Override
8752        public boolean onTouchEvent(MotionEvent ev) {
8753            switch (ev.getActionMasked()) {
8754            case MotionEvent.ACTION_DOWN: {
8755                mDownPositionX = ev.getRawX();
8756                mDownPositionY = ev.getRawY();
8757                mTouchToWindowOffsetX = mDownPositionX - mPositionX;
8758                mTouchToWindowOffsetY = mDownPositionY - mPositionY;
8759                final int[] coords = mTempCoords;
8760                TextView.this.getLocationInWindow(coords);
8761                mLastParentX = coords[0];
8762                mLastParentY = coords[1];
8763                mIsDragging = true;
8764                if (mIsInsertionHandle) {
8765                    mTouchTimer = SystemClock.uptimeMillis();
8766                    if (mLongPressCallback == null) {
8767                        mLongPressCallback = new Runnable() {
8768                            public void run() {
8769                                mController.hide();
8770                                startSelectionActionMode();
8771                            }
8772                        };
8773                    }
8774                    postDelayed(mLongPressCallback, ViewConfiguration.getLongPressTimeout());
8775                }
8776                break;
8777            }
8778
8779            case MotionEvent.ACTION_MOVE: {
8780                final float rawX = ev.getRawX();
8781                final float rawY = ev.getRawY();
8782                final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX;
8783                final float newPosY = rawY - mTouchToWindowOffsetY + mHotspotY + mTouchOffsetY;
8784
8785                mController.updatePosition(this, Math.round(newPosX), Math.round(newPosY));
8786
8787                if (mIsInsertionHandle) {
8788                    final float dx = rawX - mDownPositionX;
8789                    final float dy = rawY - mDownPositionY;
8790                    final float distanceSquared = dx * dx + dy * dy;
8791                    if (distanceSquared >= mSquaredTouchSlopDistance) {
8792                        removeLongPressCallback();
8793                    }
8794                }
8795                break;
8796            }
8797
8798            case MotionEvent.ACTION_UP:
8799                if (mIsInsertionHandle) {
8800                    removeLongPressCallback();
8801                    long delay = SystemClock.uptimeMillis() - mTouchTimer;
8802                    if (delay < ViewConfiguration.getTapTimeout()) {
8803                        if (mPastePopupWindow != null && mPastePopupWindow.isShowing()) {
8804                            // Tapping on the handle dismisses the displayed paste view,
8805                            mPastePopupWindow.hide();
8806                        } else {
8807                            ((InsertionPointCursorController) mController).show(0);
8808                        }
8809                    }
8810                }
8811                mIsDragging = false;
8812                break;
8813
8814            case MotionEvent.ACTION_CANCEL:
8815                if (mIsInsertionHandle) {
8816                    removeLongPressCallback();
8817                }
8818                mIsDragging = false;
8819            }
8820            return true;
8821        }
8822
8823        public boolean isDragging() {
8824            return mIsDragging;
8825        }
8826
8827        void positionAtCursor(final int offset, boolean bottom) {
8828            final int width = mDrawable.getIntrinsicWidth();
8829            final int height = mDrawable.getIntrinsicHeight();
8830            final int line = mLayout.getLineForOffset(offset);
8831            final int lineTop = mLayout.getLineTop(line);
8832            final int lineBottom = mLayout.getLineBottom(line);
8833
8834            final Rect bounds = sCursorControllerTempRect;
8835            bounds.left = (int) (mLayout.getPrimaryHorizontal(offset) - mHotspotX)
8836                + TextView.this.mScrollX;
8837            bounds.top = (bottom ? lineBottom : lineTop - mHeight) + TextView.this.mScrollY;
8838
8839            bounds.right = bounds.left + width;
8840            bounds.bottom = bounds.top + height;
8841
8842            convertFromViewportToContentCoordinates(bounds);
8843            moveTo(bounds.left, bounds.top);
8844        }
8845
8846        void showPastePopupWindow() {
8847            if (mIsInsertionHandle) {
8848                if (mPastePopupWindow == null) {
8849                    // Lazy initialisation: create when actually shown only.
8850                    mPastePopupWindow = new PastePopupMenu();
8851                }
8852                mPastePopupWindow.show();
8853            }
8854        }
8855
8856        private void removeLongPressCallback() {
8857            if (mLongPressCallback != null) {
8858                removeCallbacks(mLongPressCallback);
8859            }
8860        }
8861
8862        void onDetached() {
8863            removeLongPressCallback();
8864        }
8865    }
8866
8867    private class InsertionPointCursorController implements CursorController {
8868        private static final int DELAY_BEFORE_FADE_OUT = 4100;
8869        private static final int DELAY_BEFORE_PASTE = 2000;
8870        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000;
8871
8872        // The cursor controller image. Lazily created.
8873        private HandleView mHandle;
8874        private Runnable mHider;
8875        private Runnable mPastePopupShower;
8876
8877        public void show() {
8878            show(DELAY_BEFORE_PASTE);
8879        }
8880
8881        public void show(int delayBeforePaste) {
8882            updatePosition();
8883            hideDelayed();
8884            getHandle().show();
8885            removePastePopupCallback();
8886            if (canPaste()) {
8887                final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - sLastCutOrCopyTime;
8888                if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) {
8889                    delayBeforePaste = 0;
8890                }
8891                if (mPastePopupShower == null) {
8892                    mPastePopupShower = new Runnable() {
8893                        public void run() {
8894                            getHandle().showPastePopupWindow();
8895                        }
8896                    };
8897                }
8898                postDelayed(mPastePopupShower, delayBeforePaste);
8899            }
8900        }
8901
8902        private void removePastePopupCallback() {
8903            if (mPastePopupShower != null) {
8904                removeCallbacks(mPastePopupShower);
8905            }
8906        }
8907
8908        private void removeHiderCallback() {
8909            if (mHider != null) {
8910                removeCallbacks(mHider);
8911            }
8912        }
8913
8914        public void hide() {
8915            if (mHandle != null) {
8916                mHandle.hide();
8917            }
8918            removeHiderCallback();
8919            removePastePopupCallback();
8920        }
8921
8922        private void hideDelayed() {
8923            removeHiderCallback();
8924            if (mHider == null) {
8925                mHider = new Runnable() {
8926                    public void run() {
8927                        hide();
8928                    }
8929                };
8930            }
8931            postDelayed(mHider, DELAY_BEFORE_FADE_OUT);
8932        }
8933
8934        public boolean isShowing() {
8935            return mHandle != null && mHandle.isShowing();
8936        }
8937
8938        public void updatePosition(HandleView handle, int x, int y) {
8939            final int previousOffset = getSelectionStart();
8940            int offset = getHysteresisOffset(x, y, previousOffset);
8941
8942            if (offset != previousOffset) {
8943                Selection.setSelection((Spannable) mText, offset);
8944                updatePosition();
8945            }
8946            hideDelayed();
8947        }
8948
8949        public void updatePosition() {
8950            final int offset = getSelectionStart();
8951
8952            if (offset < 0) {
8953                // Should never happen, safety check.
8954                Log.w(LOG_TAG, "Update cursor controller position called with no cursor");
8955                hide();
8956                return;
8957            }
8958
8959            getHandle().positionAtCursor(offset, true);
8960        }
8961
8962        public boolean onTouchEvent(MotionEvent ev) {
8963            return false;
8964        }
8965
8966        public void onTouchModeChanged(boolean isInTouchMode) {
8967            if (!isInTouchMode) {
8968                hide();
8969            }
8970        }
8971
8972        private HandleView getHandle() {
8973            if (mHandle == null) {
8974                mHandle = new HandleView(this, HandleView.CENTER);
8975            }
8976            return mHandle;
8977        }
8978
8979        @Override
8980        public void onDetached() {
8981            removeHiderCallback();
8982            removePastePopupCallback();
8983            if (mHandle != null) {
8984                mHandle.onDetached();
8985            }
8986        }
8987    }
8988
8989    private class SelectionModifierCursorController implements CursorController {
8990        // The cursor controller images, lazily created when shown.
8991        private HandleView mStartHandle, mEndHandle;
8992        // The offsets of that last touch down event. Remembered to start selection there.
8993        private int mMinTouchOffset, mMaxTouchOffset;
8994        // Whether selection anchors are active
8995        private boolean mIsShowing;
8996
8997        // Double tap detection
8998        private long mPreviousTapUpTime = 0;
8999        private int mPreviousTapPositionX;
9000        private int mPreviousTapPositionY;
9001
9002        SelectionModifierCursorController() {
9003            resetTouchOffsets();
9004        }
9005
9006        public void show() {
9007            if (isInBatchEditMode()) {
9008                return;
9009            }
9010
9011            // Lazy object creation has to be done before updatePosition() is called.
9012            if (mStartHandle == null) mStartHandle = new HandleView(this, HandleView.LEFT);
9013            if (mEndHandle == null) mEndHandle = new HandleView(this, HandleView.RIGHT);
9014
9015            mIsShowing = true;
9016            updatePosition();
9017
9018            mStartHandle.show();
9019            mEndHandle.show();
9020
9021            hideInsertionPointCursorController();
9022        }
9023
9024        public void hide() {
9025            if (mStartHandle != null) mStartHandle.hide();
9026            if (mEndHandle != null) mEndHandle.hide();
9027            mIsShowing = false;
9028        }
9029
9030        public boolean isShowing() {
9031            return mIsShowing;
9032        }
9033
9034        public void cancelFadeOutAnimation() {
9035            hide();
9036        }
9037
9038        public void updatePosition(HandleView handle, int x, int y) {
9039            int selectionStart = getSelectionStart();
9040            int selectionEnd = getSelectionEnd();
9041
9042            final int previousOffset = handle == mStartHandle ? selectionStart : selectionEnd;
9043            int offset = getHysteresisOffset(x, y, previousOffset);
9044
9045            // Handle the case where start and end are swapped, making sure start <= end
9046            if (handle == mStartHandle) {
9047                if (selectionStart == offset || offset > selectionEnd) {
9048                    return; // no change, no need to redraw;
9049                }
9050                // If the user "closes" the selection entirely they were probably trying to
9051                // select a single character. Help them out.
9052                if (offset == selectionEnd) {
9053                    offset = selectionEnd - 1;
9054                }
9055                selectionStart = offset;
9056            } else {
9057                if (selectionEnd == offset || offset < selectionStart) {
9058                    return; // no change, no need to redraw;
9059                }
9060                // If the user "closes" the selection entirely they were probably trying to
9061                // select a single character. Help them out.
9062                if (offset == selectionStart) {
9063                    offset = selectionStart + 1;
9064                }
9065                selectionEnd = offset;
9066            }
9067
9068            Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
9069            updatePosition();
9070        }
9071
9072        public void updatePosition() {
9073            if (!isShowing()) {
9074                return;
9075            }
9076
9077            final int selectionStart = getSelectionStart();
9078            final int selectionEnd = getSelectionEnd();
9079
9080            if ((selectionStart < 0) || (selectionEnd < 0)) {
9081                // Should never happen, safety check.
9082                Log.w(LOG_TAG, "Update selection controller position called with no cursor");
9083                hide();
9084                return;
9085            }
9086
9087            // The handles have been created since the controller isShowing().
9088            mStartHandle.positionAtCursor(selectionStart, true);
9089            mEndHandle.positionAtCursor(selectionEnd, true);
9090        }
9091
9092        public boolean onTouchEvent(MotionEvent event) {
9093            // This is done even when the View does not have focus, so that long presses can start
9094            // selection and tap can move cursor from this tap position.
9095            if (isTextEditable() || mTextIsSelectable) {
9096                switch (event.getActionMasked()) {
9097                    case MotionEvent.ACTION_DOWN:
9098                        final int x = (int) event.getX();
9099                        final int y = (int) event.getY();
9100
9101                        // Remember finger down position, to be able to start selection from there
9102                        mMinTouchOffset = mMaxTouchOffset = getOffset(x, y);
9103
9104                        // Double tap detection
9105                        long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime;
9106                        if (duration <= ViewConfiguration.getDoubleTapTimeout() &&
9107                                isPositionOnText(x, y)) {
9108                            final int deltaX = x - mPreviousTapPositionX;
9109                            final int deltaY = y - mPreviousTapPositionY;
9110                            final int distanceSquared = deltaX * deltaX + deltaY * deltaY;
9111                            if (distanceSquared < mSquaredTouchSlopDistance) {
9112                                startSelectionActionMode();
9113                                mDiscardNextActionUp = true;
9114                            }
9115                        }
9116
9117                        mPreviousTapPositionX = x;
9118                        mPreviousTapPositionY = y;
9119
9120                        break;
9121
9122                    case MotionEvent.ACTION_POINTER_DOWN:
9123                    case MotionEvent.ACTION_POINTER_UP:
9124                        // Handle multi-point gestures. Keep min and max offset positions.
9125                        // Only activated for devices that correctly handle multi-touch.
9126                        if (mContext.getPackageManager().hasSystemFeature(
9127                                PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
9128                            updateMinAndMaxOffsets(event);
9129                        }
9130                        break;
9131
9132                    case MotionEvent.ACTION_UP:
9133                        mPreviousTapUpTime = SystemClock.uptimeMillis();
9134                        break;
9135                }
9136            }
9137            return false;
9138        }
9139
9140        /**
9141         * @param event
9142         */
9143        private void updateMinAndMaxOffsets(MotionEvent event) {
9144            int pointerCount = event.getPointerCount();
9145            for (int index = 0; index < pointerCount; index++) {
9146                final int x = (int) event.getX(index);
9147                final int y = (int) event.getY(index);
9148                int offset = getOffset(x, y);
9149                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
9150                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
9151            }
9152        }
9153
9154        public int getMinTouchOffset() {
9155            return mMinTouchOffset;
9156        }
9157
9158        public int getMaxTouchOffset() {
9159            return mMaxTouchOffset;
9160        }
9161
9162        public void resetTouchOffsets() {
9163            mMinTouchOffset = mMaxTouchOffset = -1;
9164        }
9165
9166        /**
9167         * @return true iff this controller is currently used to move the selection start.
9168         */
9169        public boolean isSelectionStartDragged() {
9170            return mStartHandle != null && mStartHandle.isDragging();
9171        }
9172
9173        public void onTouchModeChanged(boolean isInTouchMode) {
9174            if (!isInTouchMode) {
9175                hide();
9176            }
9177        }
9178
9179        @Override
9180        public void onDetached() {}
9181    }
9182
9183    private void hideInsertionPointCursorController() {
9184        // No need to create the controller to hide it.
9185        if (mInsertionPointCursorController != null) {
9186            mInsertionPointCursorController.hide();
9187        }
9188    }
9189
9190    /**
9191     * Hides the insertion controller and stops text selection mode, hiding the selection controller
9192     */
9193    private void hideControllers() {
9194        hideInsertionPointCursorController();
9195        stopSelectionActionMode();
9196    }
9197
9198    /**
9199     * Get the offset character closest to the specified absolute position.
9200     *
9201     * @param x The horizontal absolute position of a point on screen
9202     * @param y The vertical absolute position of a point on screen
9203     * @return the character offset for the character whose position is closest to the specified
9204     *  position. Returns -1 if there is no layout.
9205     *
9206     * @hide
9207     */
9208    public int getOffset(int x, int y) {
9209        if (getLayout() == null) return -1;
9210        final int line = getLineAtCoordinate(y);
9211        final int offset = getOffsetAtCoordinate(line, x);
9212        return offset;
9213    }
9214
9215    int getHysteresisOffset(int x, int y, int previousOffset) {
9216        final Layout layout = getLayout();
9217        if (layout == null) return -1;
9218
9219        int line = getLineAtCoordinate(y);
9220        final int previousLine = layout.getLineForOffset(previousOffset);
9221        final int previousLineTop = layout.getLineTop(previousLine);
9222        final int previousLineBottom = layout.getLineBottom(previousLine);
9223        final int hysteresisThreshold = (previousLineBottom - previousLineTop) / 8;
9224
9225        // If new line is just before or after previous line and y position is less than
9226        // hysteresisThreshold away from previous line, keep cursor on previous line.
9227        if (((line == previousLine + 1) && ((y - previousLineBottom) < hysteresisThreshold)) ||
9228            ((line == previousLine - 1) && ((previousLineTop - y)    < hysteresisThreshold))) {
9229            line = previousLine;
9230        }
9231
9232        return getOffsetAtCoordinate(line, x);
9233    }
9234
9235    private int convertToLocalHorizontalCoordinate(int x) {
9236        x -= getTotalPaddingLeft();
9237        // Clamp the position to inside of the view.
9238        x = Math.max(0, x);
9239        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
9240        x += getScrollX();
9241        return x;
9242    }
9243
9244    private int getLineAtCoordinate(int y) {
9245        y -= getTotalPaddingTop();
9246        // Clamp the position to inside of the view.
9247        y = Math.max(0, y);
9248        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
9249        y += getScrollY();
9250        return getLayout().getLineForVertical(y);
9251    }
9252
9253    private int getOffsetAtCoordinate(int line, int x) {
9254        x = convertToLocalHorizontalCoordinate(x);
9255        return getLayout().getOffsetForHorizontal(line, x);
9256    }
9257
9258    /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed
9259     * in the view. Returns false when the position is in the empty space of left/right of text.
9260     */
9261    private boolean isPositionOnText(int x, int y) {
9262        if (getLayout() == null) return false;
9263
9264        final int line = getLineAtCoordinate(y);
9265        x = convertToLocalHorizontalCoordinate(x);
9266
9267        if (x < getLayout().getLineLeft(line)) return false;
9268        if (x > getLayout().getLineRight(line)) return false;
9269        return true;
9270    }
9271
9272    @Override
9273    public boolean onDragEvent(DragEvent event) {
9274        switch (event.getAction()) {
9275            case DragEvent.ACTION_DRAG_STARTED:
9276                return hasInsertionController();
9277
9278            case DragEvent.ACTION_DRAG_ENTERED:
9279                TextView.this.requestFocus();
9280                return true;
9281
9282            case DragEvent.ACTION_DRAG_LOCATION:
9283                final int offset = getOffset((int) event.getX(), (int) event.getY());
9284                Selection.setSelection((Spannable)mText, offset);
9285                return true;
9286
9287            case DragEvent.ACTION_DROP:
9288                onDrop(event);
9289                return true;
9290
9291            case DragEvent.ACTION_DRAG_ENDED:
9292            case DragEvent.ACTION_DRAG_EXITED:
9293            default:
9294                return true;
9295        }
9296    }
9297
9298    private void onDrop(DragEvent event) {
9299        StringBuilder content = new StringBuilder("");
9300        ClipData clipData = event.getClipData();
9301        final int itemCount = clipData.getItemCount();
9302        for (int i=0; i < itemCount; i++) {
9303            Item item = clipData.getItem(i);
9304            content.append(item.coerceToText(TextView.this.mContext));
9305        }
9306
9307        final int offset = getOffset((int) event.getX(), (int) event.getY());
9308
9309        Object localState = event.getLocalState();
9310        DragLocalState dragLocalState = null;
9311        if (localState instanceof DragLocalState) {
9312            dragLocalState = (DragLocalState) localState;
9313        }
9314        boolean dragDropIntoItself = dragLocalState != null &&
9315                dragLocalState.sourceTextView == this;
9316
9317        if (dragDropIntoItself) {
9318            if (offset >= dragLocalState.start && offset < dragLocalState.end) {
9319                // A drop inside the original selection discards the drop.
9320                return;
9321            }
9322        }
9323
9324        final int originalLength = mText.length();
9325        long minMax = prepareSpacesAroundPaste(offset, offset, content);
9326        int min = extractRangeStartFromLong(minMax);
9327        int max = extractRangeEndFromLong(minMax);
9328
9329        Selection.setSelection((Spannable) mText, max);
9330        ((Editable) mText).replace(min, max, content);
9331
9332        if (dragDropIntoItself) {
9333            int dragSourceStart = dragLocalState.start;
9334            int dragSourceEnd = dragLocalState.end;
9335            if (max <= dragSourceStart) {
9336                // Inserting text before selection has shifted positions
9337                final int shift = mText.length() - originalLength;
9338                dragSourceStart += shift;
9339                dragSourceEnd += shift;
9340            }
9341
9342            // Delete original selection
9343            ((Editable) mText).delete(dragSourceStart, dragSourceEnd);
9344
9345            // Make sure we do not leave two adjacent spaces.
9346            if ((dragSourceStart == 0 ||
9347                    Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) &&
9348                    (dragSourceStart == mText.length() ||
9349                    Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) {
9350                final int pos = dragSourceStart == mText.length() ?
9351                        dragSourceStart - 1 : dragSourceStart;
9352                ((Editable) mText).delete(pos, pos + 1);
9353            }
9354        }
9355    }
9356
9357    /**
9358     * @return True if this view supports insertion handles.
9359     */
9360    boolean hasInsertionController() {
9361        return mInsertionControllerEnabled;
9362    }
9363
9364    /**
9365     * @return True if this view supports selection handles.
9366     */
9367    boolean hasSelectionController() {
9368        return mSelectionControllerEnabled;
9369    }
9370
9371    InsertionPointCursorController getInsertionController() {
9372        if (!mInsertionControllerEnabled) {
9373            return null;
9374        }
9375
9376        if (mInsertionPointCursorController == null) {
9377            mInsertionPointCursorController = new InsertionPointCursorController();
9378
9379            final ViewTreeObserver observer = getViewTreeObserver();
9380            if (observer != null) {
9381                observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
9382            }
9383        }
9384
9385        return mInsertionPointCursorController;
9386    }
9387
9388    SelectionModifierCursorController getSelectionController() {
9389        if (!mSelectionControllerEnabled) {
9390            return null;
9391        }
9392
9393        if (mSelectionModifierCursorController == null) {
9394            mSelectionModifierCursorController = new SelectionModifierCursorController();
9395
9396            final ViewTreeObserver observer = getViewTreeObserver();
9397            if (observer != null) {
9398                observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
9399            }
9400        }
9401
9402        return mSelectionModifierCursorController;
9403    }
9404
9405    boolean isInBatchEditMode() {
9406        final InputMethodState ims = mInputMethodState;
9407        if (ims != null) {
9408            return ims.mBatchEditNesting > 0;
9409        }
9410        return mInBatchEditControllers;
9411    }
9412
9413    @ViewDebug.ExportedProperty(category = "text")
9414    private CharSequence            mText;
9415    private CharSequence            mTransformed;
9416    private BufferType              mBufferType = BufferType.NORMAL;
9417
9418    private int                     mInputType = EditorInfo.TYPE_NULL;
9419    private CharSequence            mHint;
9420    private Layout                  mHintLayout;
9421
9422    private KeyListener             mInput;
9423
9424    private MovementMethod          mMovement;
9425    private TransformationMethod    mTransformation;
9426    private ChangeWatcher           mChangeWatcher;
9427
9428    private ArrayList<TextWatcher>  mListeners = null;
9429
9430    // display attributes
9431    private final TextPaint         mTextPaint;
9432    private boolean                 mUserSetTextScaleX;
9433    private final Paint             mHighlightPaint;
9434    private int                     mHighlightColor = 0xCC475925;
9435    /**
9436     * This is temporarily visible to fix bug 3085564 in webView. Do not rely on
9437     * this field being protected. Will be restored as private when lineHeight
9438     * feature request 3215097 is implemented
9439     * @hide
9440     */
9441    protected Layout                mLayout;
9442
9443    private long                    mShowCursor;
9444    private Blink                   mBlink;
9445    private boolean                 mCursorVisible = true;
9446
9447    // Cursor Controllers.
9448    private InsertionPointCursorController mInsertionPointCursorController;
9449    private SelectionModifierCursorController mSelectionModifierCursorController;
9450    private ActionMode              mSelectionActionMode;
9451    private boolean                 mInsertionControllerEnabled;
9452    private boolean                 mSelectionControllerEnabled;
9453    private boolean                 mInBatchEditControllers;
9454
9455    // These are needed to desambiguate a long click. If the long click comes from ones of these, we
9456    // select from the current cursor position. Otherwise, select from long pressed position.
9457    private boolean                 mDPadCenterIsDown = false;
9458    private boolean                 mEnterKeyIsDown = false;
9459    private boolean                 mContextMenuTriggeredByKey = false;
9460    // Created once and shared by different CursorController helper methods.
9461    // Only one cursor controller is active at any time which prevent race conditions.
9462    private static Rect             sCursorControllerTempRect = new Rect();
9463
9464    private boolean                 mSelectAllOnFocus = false;
9465
9466    private int                     mGravity = Gravity.TOP | Gravity.LEFT;
9467    private boolean                 mHorizontallyScrolling;
9468
9469    private int                     mAutoLinkMask;
9470    private boolean                 mLinksClickable = true;
9471
9472    private float                   mSpacingMult = 1;
9473    private float                   mSpacingAdd = 0;
9474    private boolean                 mTextIsSelectable = false;
9475
9476    private static final int        LINES = 1;
9477    private static final int        EMS = LINES;
9478    private static final int        PIXELS = 2;
9479
9480    private int                     mMaximum = Integer.MAX_VALUE;
9481    private int                     mMaxMode = LINES;
9482    private int                     mMinimum = 0;
9483    private int                     mMinMode = LINES;
9484
9485    private int                     mMaxWidth = Integer.MAX_VALUE;
9486    private int                     mMaxWidthMode = PIXELS;
9487    private int                     mMinWidth = 0;
9488    private int                     mMinWidthMode = PIXELS;
9489
9490    private boolean                 mSingleLine;
9491    private int                     mDesiredHeightAtMeasure = -1;
9492    private boolean                 mIncludePad = true;
9493
9494    // tmp primitives, so we don't alloc them on each draw
9495    private Path                    mHighlightPath;
9496    private boolean                 mHighlightPathBogus = true;
9497    private static final RectF      sTempRect = new RectF();
9498
9499    // XXX should be much larger
9500    private static final int        VERY_WIDE = 16384;
9501
9502    private static final int        BLINK = 500;
9503
9504    private static final int ANIMATED_SCROLL_GAP = 250;
9505    private long mLastScroll;
9506    private Scroller mScroller = null;
9507
9508    private BoringLayout.Metrics mBoring;
9509    private BoringLayout.Metrics mHintBoring;
9510
9511    private BoringLayout mSavedLayout, mSavedHintLayout;
9512
9513    private static final InputFilter[] NO_FILTERS = new InputFilter[0];
9514    private InputFilter[] mFilters = NO_FILTERS;
9515    private static final Spanned EMPTY_SPANNED = new SpannedString("");
9516    private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
9517    // System wide time for last cut or copy action.
9518    private static long sLastCutOrCopyTime;
9519    // Used to highlight a word when it is corrected by the IME
9520    private CorrectionHighlighter mCorrectionHighlighter;
9521    // New state used to change background based on whether this TextView is multiline.
9522    private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline };
9523}
9524