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