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