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