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