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