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