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