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