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