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