TextView.java revision 0500b3cfda5192efc09d6d4344b0c6c785c0a815
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    static class Drawables {
275        final Rect mCompoundRect = new Rect();
276        Drawable mDrawableTop, mDrawableBottom, mDrawableLeft, mDrawableRight,
277                mDrawableStart, mDrawableEnd;
278        int mDrawableSizeTop, mDrawableSizeBottom, mDrawableSizeLeft, mDrawableSizeRight,
279                mDrawableSizeStart, mDrawableSizeEnd;
280        int mDrawableWidthTop, mDrawableWidthBottom, mDrawableHeightLeft, mDrawableHeightRight,
281                mDrawableHeightStart, mDrawableHeightEnd;
282        int mDrawablePadding;
283    }
284    private Drawables mDrawables;
285
286    private CharSequence mError;
287    private boolean mErrorWasChanged;
288    private ErrorPopup mPopup;
289    /**
290     * This flag is set if the TextView tries to display an error before it
291     * is attached to the window (so its position is still unknown).
292     * It causes the error to be shown later, when onAttachedToWindow()
293     * is called.
294     */
295    private boolean mShowErrorAfterAttach;
296
297    private CharWrapper mCharWrapper = null;
298
299    private boolean mSelectionMoved = false;
300    private boolean mTouchFocusSelected = false;
301
302    private Marquee mMarquee;
303    private boolean mRestartMarquee;
304
305    private int mMarqueeRepeatLimit = 3;
306
307    static class InputContentType {
308        int imeOptions = EditorInfo.IME_NULL;
309        String privateImeOptions;
310        CharSequence imeActionLabel;
311        int imeActionId;
312        Bundle extras;
313        OnEditorActionListener onEditorActionListener;
314        boolean enterDown;
315    }
316    InputContentType mInputContentType;
317
318    static class InputMethodState {
319        Rect mCursorRectInWindow = new Rect();
320        RectF mTmpRectF = new RectF();
321        float[] mTmpOffset = new float[2];
322        ExtractedTextRequest mExtracting;
323        final ExtractedText mTmpExtracted = new ExtractedText();
324        int mBatchEditNesting;
325        boolean mCursorChanged;
326        boolean mSelectionModeChanged;
327        boolean mContentChanged;
328        int mChangedStart, mChangedEnd, mChangedDelta;
329    }
330    InputMethodState mInputMethodState;
331
332    private int mTextSelectHandleLeftRes;
333    private int mTextSelectHandleRightRes;
334    private int mTextSelectHandleRes;
335
336    private int mTextEditSuggestionItemLayout;
337    private SuggestionsPopupWindow mSuggestionsPopupWindow;
338    private SuggestionRangeSpan mSuggestionRangeSpan;
339
340    private int mCursorDrawableRes;
341    private final Drawable[] mCursorDrawable = new Drawable[2];
342    private int mCursorCount; // Actual current number of used mCursorDrawable: 0, 1 or 2
343
344    private Drawable mSelectHandleLeft;
345    private Drawable mSelectHandleRight;
346    private Drawable mSelectHandleCenter;
347
348    // Global listener that detects changes in the global position of the TextView
349    private PositionListener mPositionListener;
350
351    private float mLastDownPositionX, mLastDownPositionY;
352    private Callback mCustomSelectionActionModeCallback;
353
354    private final int mSquaredTouchSlopDistance;
355    // Set when this TextView gained focus with some text selected. Will start selection mode.
356    private boolean mCreatedWithASelection = false;
357
358    private WordIterator mWordIterator;
359
360    private SpellChecker mSpellChecker;
361
362    private boolean mSoftInputShownOnFocus = true;
363
364    // The alignment to pass to Layout, or null if not resolved.
365    private Layout.Alignment mLayoutAlignment;
366
367    // The default value for mTextAlign.
368    private TextAlign mTextAlign = TextAlign.INHERIT;
369
370    private static enum TextAlign {
371        INHERIT, GRAVITY, TEXT_START, TEXT_END, CENTER, VIEW_START, VIEW_END;
372    }
373
374    private boolean mResolvedDrawables = false;
375
376    /**
377     * On some devices the fading edges add a performance penalty if used
378     * extensively in the same layout. This mode indicates how the marquee
379     * is currently being shown, if applicable. (mEllipsize will == MARQUEE)
380     */
381    private int mMarqueeFadeMode = MARQUEE_FADE_NORMAL;
382
383    /**
384     * When mMarqueeFadeMode is not MARQUEE_FADE_NORMAL, this stores
385     * the layout that should be used when the mode switches.
386     */
387    private Layout mSavedMarqueeModeLayout;
388
389    /**
390     * Draw marquee text with fading edges as usual
391     */
392    private static final int MARQUEE_FADE_NORMAL = 0;
393
394    /**
395     * Draw marquee text as ellipsize end while inactive instead of with the fade.
396     * (Useful for devices where the fade can be expensive if overdone)
397     */
398    private static final int MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS = 1;
399
400    /**
401     * Draw marquee text with fading edges because it is currently active/animating.
402     */
403    private static final int MARQUEE_FADE_SWITCH_SHOW_FADE = 2;
404
405    /*
406     * Kick-start the font cache for the zygote process (to pay the cost of
407     * initializing freetype for our default font only once).
408     */
409    static {
410        Paint p = new Paint();
411        p.setAntiAlias(true);
412        // We don't care about the result, just the side-effect of measuring.
413        p.measureText("H");
414    }
415
416    /**
417     * Interface definition for a callback to be invoked when an action is
418     * performed on the editor.
419     */
420    public interface OnEditorActionListener {
421        /**
422         * Called when an action is being performed.
423         *
424         * @param v The view that was clicked.
425         * @param actionId Identifier of the action.  This will be either the
426         * identifier you supplied, or {@link EditorInfo#IME_NULL
427         * EditorInfo.IME_NULL} if being called due to the enter key
428         * being pressed.
429         * @param event If triggered by an enter key, this is the event;
430         * otherwise, this is null.
431         * @return Return true if you have consumed the action, else false.
432         */
433        boolean onEditorAction(TextView v, int actionId, KeyEvent event);
434    }
435
436    public TextView(Context context) {
437        this(context, null);
438    }
439
440    public TextView(Context context,
441                    AttributeSet attrs) {
442        this(context, attrs, com.android.internal.R.attr.textViewStyle);
443    }
444
445    @SuppressWarnings("deprecation")
446    public TextView(Context context,
447                    AttributeSet attrs,
448                    int defStyle) {
449        super(context, attrs, defStyle);
450        mText = "";
451
452        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_softInputShownOnFocus
2385     * @hide
2386     */
2387    @android.view.RemotableViewMethod
2388    public final void setSoftInputShownOnFocus(boolean show) {
2389        mSoftInputShownOnFocus = 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_softInputShownOnFocus
2397     * @hide
2398     */
2399    public final boolean getSoftInputShownOnFocus() {
2400        return mSoftInputShownOnFocus;
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 (hasOnClickListeners()) {
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 (hasOnClickListeners()) {
5501                        if (mMovement != null && mText instanceof Editable
5502                                && mLayout != null && onCheckIsTextEditor()) {
5503                            InputMethodManager imm = InputMethodManager.peekInstance();
5504                            viewClicked(imm);
5505                            if (imm != null && mSoftInputShownOnFocus) {
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 (hasOnClickListeners()) {
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 || what instanceof ParagraphStyle
7724                || (what instanceof SuggestionSpan && (((SuggestionSpan)what).getFlags()
7725                        & SuggestionSpan.FLAG_AUTO_CORRECTION) != 0)) {
7726            if (ims == null || ims.mBatchEditNesting == 0) {
7727                invalidate();
7728                mHighlightPathBogus = true;
7729                checkForResize();
7730            } else {
7731                ims.mContentChanged = true;
7732            }
7733        }
7734
7735        if (MetaKeyKeyListener.isMetaTracker(buf, what)) {
7736            mHighlightPathBogus = true;
7737            if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) {
7738                ims.mSelectionModeChanged = true;
7739            }
7740
7741            if (Selection.getSelectionStart(buf) >= 0) {
7742                if (ims == null || ims.mBatchEditNesting == 0) {
7743                    invalidateCursor();
7744                } else {
7745                    ims.mCursorChanged = true;
7746                }
7747            }
7748        }
7749
7750        if (what instanceof ParcelableSpan) {
7751            // If this is a span that can be sent to a remote process,
7752            // the current extract editor would be interested in it.
7753            if (ims != null && ims.mExtracting != null) {
7754                if (ims.mBatchEditNesting != 0) {
7755                    if (oldStart >= 0) {
7756                        if (ims.mChangedStart > oldStart) {
7757                            ims.mChangedStart = oldStart;
7758                        }
7759                        if (ims.mChangedStart > oldEnd) {
7760                            ims.mChangedStart = oldEnd;
7761                        }
7762                    }
7763                    if (newStart >= 0) {
7764                        if (ims.mChangedStart > newStart) {
7765                            ims.mChangedStart = newStart;
7766                        }
7767                        if (ims.mChangedStart > newEnd) {
7768                            ims.mChangedStart = newEnd;
7769                        }
7770                    }
7771                } else {
7772                    if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: "
7773                            + oldStart + "-" + oldEnd + ","
7774                            + newStart + "-" + newEnd + what);
7775                    ims.mContentChanged = true;
7776                }
7777            }
7778        }
7779
7780        if (newStart < 0 && what instanceof SpellCheckSpan) {
7781            getSpellChecker().removeSpellCheckSpan((SpellCheckSpan) what);
7782        }
7783    }
7784
7785    /**
7786     * Create new SpellCheckSpans on the modified region.
7787     */
7788    private void updateSpellCheckSpans(int start, int end) {
7789        if (isTextEditable() && isSuggestionsEnabled()) {
7790            getSpellChecker().spellCheck(start, end);
7791        }
7792    }
7793
7794    /**
7795     * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related
7796     * pop-up should be displayed.
7797     */
7798    private class EasyEditSpanController {
7799
7800        private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs
7801
7802        private EasyEditPopupWindow mPopupWindow;
7803
7804        private EasyEditSpan mEasyEditSpan;
7805
7806        private Runnable mHidePopup;
7807
7808        private void hide() {
7809            if (mPopupWindow != null) {
7810                mPopupWindow.hide();
7811                TextView.this.removeCallbacks(mHidePopup);
7812            }
7813            removeSpans(mText);
7814            mEasyEditSpan = null;
7815        }
7816
7817        /**
7818         * Monitors the changes in the text.
7819         *
7820         * <p>{@link ChangeWatcher#onSpanAdded(Spannable, Object, int, int)} cannot be used,
7821         * as the notifications are not sent when a spannable (with spans) is inserted.
7822         */
7823        public void onTextChange(CharSequence buffer) {
7824            adjustSpans(mText);
7825
7826            if (getWindowVisibility() != View.VISIBLE) {
7827                // The window is not visible yet, ignore the text change.
7828                return;
7829            }
7830
7831            if (mLayout == null) {
7832                // The view has not been layout yet, ignore the text change
7833                return;
7834            }
7835
7836            InputMethodManager imm = InputMethodManager.peekInstance();
7837            if (!(TextView.this instanceof ExtractEditText)
7838                    && imm != null && imm.isFullscreenMode()) {
7839                // The input is in extract mode. We do not have to handle the easy edit in the
7840                // original TextView, as the ExtractEditText will do
7841                return;
7842            }
7843
7844            // Remove the current easy edit span, as the text changed, and remove the pop-up
7845            // (if any)
7846            if (mEasyEditSpan != null) {
7847                if (mText instanceof Spannable) {
7848                    ((Spannable) mText).removeSpan(mEasyEditSpan);
7849                }
7850                mEasyEditSpan = null;
7851            }
7852            if (mPopupWindow != null && mPopupWindow.isShowing()) {
7853                mPopupWindow.hide();
7854            }
7855
7856            // Display the new easy edit span (if any).
7857            if (buffer instanceof Spanned) {
7858                mEasyEditSpan = getSpan((Spanned) buffer);
7859                if (mEasyEditSpan != null) {
7860                    if (mPopupWindow == null) {
7861                        mPopupWindow = new EasyEditPopupWindow();
7862                        mHidePopup = new Runnable() {
7863                            @Override
7864                            public void run() {
7865                                hide();
7866                            }
7867                        };
7868                    }
7869                    mPopupWindow.show(mEasyEditSpan);
7870                    TextView.this.removeCallbacks(mHidePopup);
7871                    TextView.this.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS);
7872                }
7873            }
7874        }
7875
7876        /**
7877         * Adjusts the spans by removing all of them except the last one.
7878         */
7879        private void adjustSpans(CharSequence buffer) {
7880            // This method enforces that only one easy edit span is attached to the text.
7881            // A better way to enforce this would be to listen for onSpanAdded, but this method
7882            // cannot be used in this scenario as no notification is triggered when a text with
7883            // spans is inserted into a text.
7884            if (buffer instanceof Spannable) {
7885                Spannable spannable = (Spannable) buffer;
7886                EasyEditSpan[] spans = spannable.getSpans(0, spannable.length(),
7887                        EasyEditSpan.class);
7888                for (int i = 0; i < spans.length - 1; i++) {
7889                    spannable.removeSpan(spans[i]);
7890                }
7891            }
7892        }
7893
7894        /**
7895         * Removes all the {@link EasyEditSpan} currently attached.
7896         */
7897        private void removeSpans(CharSequence buffer) {
7898            if (buffer instanceof Spannable) {
7899                Spannable spannable = (Spannable) buffer;
7900                EasyEditSpan[] spans = spannable.getSpans(0, spannable.length(),
7901                        EasyEditSpan.class);
7902                for (int i = 0; i < spans.length; i++) {
7903                    spannable.removeSpan(spans[i]);
7904                }
7905            }
7906        }
7907
7908        private EasyEditSpan getSpan(Spanned spanned) {
7909            EasyEditSpan[] easyEditSpans = spanned.getSpans(0, spanned.length(),
7910                    EasyEditSpan.class);
7911            if (easyEditSpans.length == 0) {
7912                return null;
7913            } else {
7914                return easyEditSpans[0];
7915            }
7916        }
7917    }
7918
7919    /**
7920     * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled
7921     * by {@link EasyEditSpanController}.
7922     */
7923    private class EasyEditPopupWindow extends PinnedPopupWindow
7924            implements OnClickListener {
7925        private static final int POPUP_TEXT_LAYOUT =
7926                com.android.internal.R.layout.text_edit_action_popup_text;
7927        private TextView mDeleteTextView;
7928        private EasyEditSpan mEasyEditSpan;
7929
7930        @Override
7931        protected void createPopupWindow() {
7932            mPopupWindow = new PopupWindow(TextView.this.mContext, null,
7933                    com.android.internal.R.attr.textSelectHandleWindowStyle);
7934            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
7935            mPopupWindow.setClippingEnabled(true);
7936        }
7937
7938        @Override
7939        protected void initContentView() {
7940            LinearLayout linearLayout = new LinearLayout(TextView.this.getContext());
7941            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
7942            mContentView = linearLayout;
7943            mContentView.setBackgroundResource(
7944                    com.android.internal.R.drawable.text_edit_side_paste_window);
7945
7946            LayoutInflater inflater = (LayoutInflater)TextView.this.mContext.
7947                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
7948
7949            LayoutParams wrapContent = new LayoutParams(
7950                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
7951
7952            mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
7953            mDeleteTextView.setLayoutParams(wrapContent);
7954            mDeleteTextView.setText(com.android.internal.R.string.delete);
7955            mDeleteTextView.setOnClickListener(this);
7956            mContentView.addView(mDeleteTextView);
7957        }
7958
7959        public void show(EasyEditSpan easyEditSpan) {
7960            mEasyEditSpan = easyEditSpan;
7961            super.show();
7962        }
7963
7964        @Override
7965        public void onClick(View view) {
7966            if (view == mDeleteTextView) {
7967                deleteText();
7968            }
7969        }
7970
7971        private void deleteText() {
7972            Editable editable = (Editable) mText;
7973            int start = editable.getSpanStart(mEasyEditSpan);
7974            int end = editable.getSpanEnd(mEasyEditSpan);
7975            if (start >= 0 && end >= 0) {
7976                editable.delete(start, end);
7977            }
7978        }
7979
7980        @Override
7981        protected int getTextOffset() {
7982            // Place the pop-up at the end of the span
7983            Editable editable = (Editable) mText;
7984            return editable.getSpanEnd(mEasyEditSpan);
7985        }
7986
7987        @Override
7988        protected int getVerticalLocalPosition(int line) {
7989            return mLayout.getLineBottom(line);
7990        }
7991
7992        @Override
7993        protected int clipVertically(int positionY) {
7994            // As we display the pop-up below the span, no vertical clipping is required.
7995            return positionY;
7996        }
7997    }
7998
7999    private class ChangeWatcher implements TextWatcher, SpanWatcher {
8000
8001        private CharSequence mBeforeText;
8002
8003        private EasyEditSpanController mEasyEditSpanController;
8004
8005        private ChangeWatcher() {
8006            mEasyEditSpanController = new EasyEditSpanController();
8007        }
8008
8009        public void beforeTextChanged(CharSequence buffer, int start,
8010                                      int before, int after) {
8011            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start
8012                    + " before=" + before + " after=" + after + ": " + buffer);
8013
8014            if (AccessibilityManager.getInstance(mContext).isEnabled()
8015                    && !isPasswordInputType(mInputType)
8016                    && !hasPasswordTransformationMethod()) {
8017                mBeforeText = buffer.toString();
8018            }
8019
8020            TextView.this.sendBeforeTextChanged(buffer, start, before, after);
8021        }
8022
8023        public void onTextChanged(CharSequence buffer, int start,
8024                                  int before, int after) {
8025            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start
8026                    + " before=" + before + " after=" + after + ": " + buffer);
8027            TextView.this.handleTextChanged(buffer, start, before, after);
8028
8029            mEasyEditSpanController.onTextChange(buffer);
8030
8031            if (AccessibilityManager.getInstance(mContext).isEnabled() &&
8032                    (isFocused() || isSelected() && isShown())) {
8033                sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after);
8034                mBeforeText = null;
8035            }
8036        }
8037
8038        public void afterTextChanged(Editable buffer) {
8039            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer);
8040            TextView.this.sendAfterTextChanged(buffer);
8041
8042            if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) {
8043                MetaKeyKeyListener.stopSelecting(TextView.this, buffer);
8044            }
8045        }
8046
8047        public void onSpanChanged(Spannable buf,
8048                                  Object what, int s, int e, int st, int en) {
8049            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e
8050                    + " st=" + st + " en=" + en + " what=" + what + ": " + buf);
8051            TextView.this.spanChange(buf, what, s, st, e, en);
8052        }
8053
8054        public void onSpanAdded(Spannable buf, Object what, int s, int e) {
8055            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e
8056                    + " what=" + what + ": " + buf);
8057            TextView.this.spanChange(buf, what, -1, s, -1, e);
8058        }
8059
8060        public void onSpanRemoved(Spannable buf, Object what, int s, int e) {
8061            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e
8062                    + " what=" + what + ": " + buf);
8063            TextView.this.spanChange(buf, what, s, -1, e, -1);
8064        }
8065
8066        private void hideControllers() {
8067            mEasyEditSpanController.hide();
8068        }
8069    }
8070
8071    /**
8072     * @hide
8073     */
8074    @Override
8075    public void dispatchFinishTemporaryDetach() {
8076        mDispatchTemporaryDetach = true;
8077        super.dispatchFinishTemporaryDetach();
8078        mDispatchTemporaryDetach = false;
8079    }
8080
8081    @Override
8082    public void onStartTemporaryDetach() {
8083        super.onStartTemporaryDetach();
8084        // Only track when onStartTemporaryDetach() is called directly,
8085        // usually because this instance is an editable field in a list
8086        if (!mDispatchTemporaryDetach) mTemporaryDetach = true;
8087
8088        // Because of View recycling in ListView, there is no easy way to know when a TextView with
8089        // selection becomes visible again. Until a better solution is found, stop text selection
8090        // mode (if any) as soon as this TextView is recycled.
8091        hideControllers();
8092    }
8093
8094    @Override
8095    public void onFinishTemporaryDetach() {
8096        super.onFinishTemporaryDetach();
8097        // Only track when onStartTemporaryDetach() is called directly,
8098        // usually because this instance is an editable field in a list
8099        if (!mDispatchTemporaryDetach) mTemporaryDetach = false;
8100    }
8101
8102    @Override
8103    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
8104        if (mTemporaryDetach) {
8105            // If we are temporarily in the detach state, then do nothing.
8106            super.onFocusChanged(focused, direction, previouslyFocusedRect);
8107            return;
8108        }
8109
8110        mShowCursor = SystemClock.uptimeMillis();
8111
8112        ensureEndedBatchEdit();
8113
8114        if (focused) {
8115            int selStart = getSelectionStart();
8116            int selEnd = getSelectionEnd();
8117
8118            // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection
8119            // mode for these, unless there was a specific selection already started.
8120            final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 &&
8121                    selEnd == mText.length();
8122            mCreatedWithASelection = mFrozenWithFocus && hasSelection() && !isFocusHighlighted;
8123
8124            if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
8125                // If a tap was used to give focus to that view, move cursor at tap position.
8126                // Has to be done before onTakeFocus, which can be overloaded.
8127                final int lastTapPosition = getLastTapPosition();
8128                if (lastTapPosition >= 0) {
8129                    Selection.setSelection((Spannable) mText, lastTapPosition);
8130                }
8131
8132                if (mMovement != null) {
8133                    mMovement.onTakeFocus(this, (Spannable) mText, direction);
8134                }
8135
8136                // The DecorView does not have focus when the 'Done' ExtractEditText button is
8137                // pressed. Since it is the ViewAncestor's mView, it requests focus before
8138                // ExtractEditText clears focus, which gives focus to the ExtractEditText.
8139                // This special case ensure that we keep current selection in that case.
8140                // It would be better to know why the DecorView does not have focus at that time.
8141                if (((this instanceof ExtractEditText) || mSelectionMoved) &&
8142                        selStart >= 0 && selEnd >= 0) {
8143                    /*
8144                     * Someone intentionally set the selection, so let them
8145                     * do whatever it is that they wanted to do instead of
8146                     * the default on-focus behavior.  We reset the selection
8147                     * here instead of just skipping the onTakeFocus() call
8148                     * because some movement methods do something other than
8149                     * just setting the selection in theirs and we still
8150                     * need to go through that path.
8151                     */
8152                    Selection.setSelection((Spannable) mText, selStart, selEnd);
8153                }
8154
8155                if (mSelectAllOnFocus) {
8156                    selectAll();
8157                }
8158
8159                mTouchFocusSelected = true;
8160            }
8161
8162            mFrozenWithFocus = false;
8163            mSelectionMoved = false;
8164
8165            if (mText instanceof Spannable) {
8166                Spannable sp = (Spannable) mText;
8167                MetaKeyKeyListener.resetMetaState(sp);
8168            }
8169
8170            makeBlink();
8171
8172            if (mError != null) {
8173                showError();
8174            }
8175        } else {
8176            if (mError != null) {
8177                hideError();
8178            }
8179            // Don't leave us in the middle of a batch edit.
8180            onEndBatchEdit();
8181
8182            if (this instanceof ExtractEditText) {
8183                // terminateTextSelectionMode removes selection, which we want to keep when
8184                // ExtractEditText goes out of focus.
8185                final int selStart = getSelectionStart();
8186                final int selEnd = getSelectionEnd();
8187                hideControllers();
8188                Selection.setSelection((Spannable) mText, selStart, selEnd);
8189            } else {
8190                hideControllers();
8191                downgradeEasyCorrectionSpans();
8192            }
8193
8194            // No need to create the controller
8195            if (mSelectionModifierCursorController != null) {
8196                mSelectionModifierCursorController.resetTouchOffsets();
8197            }
8198        }
8199
8200        startStopMarquee(focused);
8201
8202        if (mTransformation != null) {
8203            mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect);
8204        }
8205
8206        super.onFocusChanged(focused, direction, previouslyFocusedRect);
8207    }
8208
8209    private int getLastTapPosition() {
8210        // No need to create the controller at that point, no last tap position saved
8211        if (mSelectionModifierCursorController != null) {
8212            int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset();
8213            if (lastTapPosition >= 0) {
8214                // Safety check, should not be possible.
8215                if (lastTapPosition > mText.length()) {
8216                    Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs "
8217                            + mText.length() + ")");
8218                    lastTapPosition = mText.length();
8219                }
8220                return lastTapPosition;
8221            }
8222        }
8223
8224        return -1;
8225    }
8226
8227    @Override
8228    public void onWindowFocusChanged(boolean hasWindowFocus) {
8229        super.onWindowFocusChanged(hasWindowFocus);
8230
8231        if (hasWindowFocus) {
8232            if (mBlink != null) {
8233                mBlink.uncancel();
8234                makeBlink();
8235            }
8236        } else {
8237            if (mBlink != null) {
8238                mBlink.cancel();
8239            }
8240            // Don't leave us in the middle of a batch edit.
8241            onEndBatchEdit();
8242            if (mInputContentType != null) {
8243                mInputContentType.enterDown = false;
8244            }
8245
8246            hideControllers();
8247            if (mSuggestionsPopupWindow != null) {
8248                mSuggestionsPopupWindow.onParentLostFocus();
8249            }
8250        }
8251
8252        startStopMarquee(hasWindowFocus);
8253    }
8254
8255    @Override
8256    protected void onVisibilityChanged(View changedView, int visibility) {
8257        super.onVisibilityChanged(changedView, visibility);
8258        if (visibility != VISIBLE) {
8259            hideControllers();
8260        }
8261    }
8262
8263    /**
8264     * Use {@link BaseInputConnection#removeComposingSpans
8265     * BaseInputConnection.removeComposingSpans()} to remove any IME composing
8266     * state from this text view.
8267     */
8268    public void clearComposingText() {
8269        if (mText instanceof Spannable) {
8270            BaseInputConnection.removeComposingSpans((Spannable)mText);
8271        }
8272    }
8273
8274    @Override
8275    public void setSelected(boolean selected) {
8276        boolean wasSelected = isSelected();
8277
8278        super.setSelected(selected);
8279
8280        if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
8281            if (selected) {
8282                startMarquee();
8283            } else {
8284                stopMarquee();
8285            }
8286        }
8287    }
8288
8289    @Override
8290    public boolean onTouchEvent(MotionEvent event) {
8291        final int action = event.getActionMasked();
8292
8293        if (hasSelectionController()) {
8294            getSelectionController().onTouchEvent(event);
8295        }
8296
8297        if (action == MotionEvent.ACTION_DOWN) {
8298            mLastDownPositionX = event.getX();
8299            mLastDownPositionY = event.getY();
8300
8301            // Reset this state; it will be re-set if super.onTouchEvent
8302            // causes focus to move to the view.
8303            mTouchFocusSelected = false;
8304            mIgnoreActionUpEvent = false;
8305        }
8306
8307        final boolean superResult = super.onTouchEvent(event);
8308
8309        /*
8310         * Don't handle the release after a long press, because it will
8311         * move the selection away from whatever the menu action was
8312         * trying to affect.
8313         */
8314        if (mDiscardNextActionUp && action == MotionEvent.ACTION_UP) {
8315            mDiscardNextActionUp = false;
8316            return superResult;
8317        }
8318
8319        final boolean touchIsFinished = (action == MotionEvent.ACTION_UP) &&
8320                !shouldIgnoreActionUpEvent() && isFocused();
8321
8322         if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()
8323                && mText instanceof Spannable && mLayout != null) {
8324            boolean handled = false;
8325
8326            if (mMovement != null) {
8327                handled |= mMovement.onTouchEvent(this, (Spannable) mText, event);
8328            }
8329
8330            if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && mTextIsSelectable) {
8331                // The LinkMovementMethod which should handle taps on links has not been installed
8332                // on non editable text that support text selection.
8333                // We reproduce its behavior here to open links for these.
8334                ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(),
8335                        getSelectionEnd(), ClickableSpan.class);
8336
8337                if (links.length != 0) {
8338                    links[0].onClick(this);
8339                    handled = true;
8340                }
8341            }
8342
8343            if (touchIsFinished && (isTextEditable() || mTextIsSelectable)) {
8344                // Show the IME, except when selecting in read-only text.
8345                final InputMethodManager imm = InputMethodManager.peekInstance();
8346                viewClicked(imm);
8347                if (!mTextIsSelectable && mSoftInputShownOnFocus) {
8348                    handled |= imm != null && imm.showSoftInput(this, 0);
8349                }
8350
8351                boolean selectAllGotFocus = mSelectAllOnFocus && didTouchFocusSelect();
8352                hideControllers();
8353                if (!selectAllGotFocus && mText.length() > 0) {
8354                    if (mSpellChecker != null) {
8355                        // When the cursor moves, the word that was typed may need spell check
8356                        mSpellChecker.onSelectionChanged();
8357                    }
8358                    if (isCursorInsideEasyCorrectionSpan()) {
8359                        showSuggestions();
8360                    } else if (hasInsertionController()) {
8361                        getInsertionController().show();
8362                    }
8363                }
8364
8365                handled = true;
8366            }
8367
8368            if (handled) {
8369                return true;
8370            }
8371        }
8372
8373        return superResult;
8374    }
8375
8376    /**
8377     * @return <code>true</code> if the cursor/current selection overlaps a {@link SuggestionSpan}.
8378     */
8379    private boolean isCursorInsideSuggestionSpan() {
8380        if (!(mText instanceof Spannable)) return false;
8381
8382        SuggestionSpan[] suggestionSpans = ((Spannable) mText).getSpans(getSelectionStart(),
8383                getSelectionEnd(), SuggestionSpan.class);
8384        return (suggestionSpans.length > 0);
8385    }
8386
8387    /**
8388     * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with
8389     * {@link SuggestionSpan#FLAG_EASY_CORRECT} set.
8390     */
8391    private boolean isCursorInsideEasyCorrectionSpan() {
8392        Spannable spannable = (Spannable) mText;
8393        SuggestionSpan[] suggestionSpans = spannable.getSpans(getSelectionStart(),
8394                getSelectionEnd(), SuggestionSpan.class);
8395        for (int i = 0; i < suggestionSpans.length; i++) {
8396            if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) {
8397                return true;
8398            }
8399        }
8400        return false;
8401    }
8402
8403    /**
8404     * Downgrades to simple suggestions all the easy correction spans that are not a spell check
8405     * span.
8406     */
8407    private void downgradeEasyCorrectionSpans() {
8408        if (mText instanceof Spannable) {
8409            Spannable spannable = (Spannable) mText;
8410            SuggestionSpan[] suggestionSpans = spannable.getSpans(0,
8411                    spannable.length(), SuggestionSpan.class);
8412            for (int i = 0; i < suggestionSpans.length; i++) {
8413                int flags = suggestionSpans[i].getFlags();
8414                if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0
8415                        && (flags & SuggestionSpan.FLAG_MISSPELLED) == 0) {
8416                    flags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
8417                    suggestionSpans[i].setFlags(flags);
8418                }
8419            }
8420        }
8421    }
8422
8423    @Override
8424    public boolean onGenericMotionEvent(MotionEvent event) {
8425        if (mMovement != null && mText instanceof Spannable && mLayout != null) {
8426            try {
8427                if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) {
8428                    return true;
8429                }
8430            } catch (AbstractMethodError ex) {
8431                // onGenericMotionEvent was added to the MovementMethod interface in API 12.
8432                // Ignore its absence in case third party applications implemented the
8433                // interface directly.
8434            }
8435        }
8436        return super.onGenericMotionEvent(event);
8437    }
8438
8439    private void prepareCursorControllers() {
8440        boolean windowSupportsHandles = false;
8441
8442        ViewGroup.LayoutParams params = getRootView().getLayoutParams();
8443        if (params instanceof WindowManager.LayoutParams) {
8444            WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params;
8445            windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW
8446                    || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW;
8447        }
8448
8449        mInsertionControllerEnabled = windowSupportsHandles && isCursorVisible() && mLayout != null;
8450        mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() &&
8451                mLayout != null;
8452
8453        if (!mInsertionControllerEnabled) {
8454            hideInsertionPointCursorController();
8455            if (mInsertionPointCursorController != null) {
8456                mInsertionPointCursorController.onDetached();
8457                mInsertionPointCursorController = null;
8458            }
8459        }
8460
8461        if (!mSelectionControllerEnabled) {
8462            stopSelectionActionMode();
8463            if (mSelectionModifierCursorController != null) {
8464                mSelectionModifierCursorController.onDetached();
8465                mSelectionModifierCursorController = null;
8466            }
8467        }
8468    }
8469
8470    /**
8471     * @return True iff this TextView contains a text that can be edited, or if this is
8472     * a selectable TextView.
8473     */
8474    private boolean isTextEditable() {
8475        return mText instanceof Editable && onCheckIsTextEditor() && isEnabled();
8476    }
8477
8478    /**
8479     * Returns true, only while processing a touch gesture, if the initial
8480     * touch down event caused focus to move to the text view and as a result
8481     * its selection changed.  Only valid while processing the touch gesture
8482     * of interest.
8483     */
8484    public boolean didTouchFocusSelect() {
8485        return mTouchFocusSelected;
8486    }
8487
8488    @Override
8489    public void cancelLongPress() {
8490        super.cancelLongPress();
8491        mIgnoreActionUpEvent = true;
8492    }
8493
8494    /**
8495     * This method is only valid during a touch event.
8496     *
8497     * @return true when the ACTION_UP event should be ignored, false otherwise.
8498     *
8499     * @hide
8500     */
8501    public boolean shouldIgnoreActionUpEvent() {
8502        return mIgnoreActionUpEvent;
8503    }
8504
8505    @Override
8506    public boolean onTrackballEvent(MotionEvent event) {
8507        if (mMovement != null && mText instanceof Spannable &&
8508            mLayout != null) {
8509            if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) {
8510                return true;
8511            }
8512        }
8513
8514        return super.onTrackballEvent(event);
8515    }
8516
8517    public void setScroller(Scroller s) {
8518        mScroller = s;
8519    }
8520
8521    private static class Blink extends Handler implements Runnable {
8522        private final WeakReference<TextView> mView;
8523        private boolean mCancelled;
8524
8525        public Blink(TextView v) {
8526            mView = new WeakReference<TextView>(v);
8527        }
8528
8529        public void run() {
8530            if (mCancelled) {
8531                return;
8532            }
8533
8534            removeCallbacks(Blink.this);
8535
8536            TextView tv = mView.get();
8537
8538            if (tv != null && tv.shouldBlink()) {
8539                if (tv.mLayout != null) {
8540                    tv.invalidateCursorPath();
8541                }
8542
8543                postAtTime(this, SystemClock.uptimeMillis() + BLINK);
8544            }
8545        }
8546
8547        void cancel() {
8548            if (!mCancelled) {
8549                removeCallbacks(Blink.this);
8550                mCancelled = true;
8551            }
8552        }
8553
8554        void uncancel() {
8555            mCancelled = false;
8556        }
8557    }
8558
8559    /**
8560     * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
8561     */
8562    private boolean shouldBlink() {
8563        if (!isFocused()) return false;
8564
8565        final int start = getSelectionStart();
8566        if (start < 0) return false;
8567
8568        final int end = getSelectionEnd();
8569        if (end < 0) return false;
8570
8571        return start == end;
8572    }
8573
8574    private void makeBlink() {
8575        if (isCursorVisible()) {
8576            if (shouldBlink()) {
8577                mShowCursor = SystemClock.uptimeMillis();
8578                if (mBlink == null) mBlink = new Blink(this);
8579                mBlink.removeCallbacks(mBlink);
8580                mBlink.postAtTime(mBlink, mShowCursor + BLINK);
8581            }
8582        } else {
8583            if (mBlink != null) mBlink.removeCallbacks(mBlink);
8584        }
8585    }
8586
8587    @Override
8588    protected float getLeftFadingEdgeStrength() {
8589        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f;
8590        if (mEllipsize == TextUtils.TruncateAt.MARQUEE &&
8591                mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
8592            if (mMarquee != null && !mMarquee.isStopped()) {
8593                final Marquee marquee = mMarquee;
8594                if (marquee.shouldDrawLeftFade()) {
8595                    return marquee.mScroll / getHorizontalFadingEdgeLength();
8596                } else {
8597                    return 0.0f;
8598                }
8599            } else if (getLineCount() == 1) {
8600                final int layoutDirection = getResolvedLayoutDirection();
8601                final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
8602                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
8603                    case Gravity.LEFT:
8604                        return 0.0f;
8605                    case Gravity.RIGHT:
8606                        return (mLayout.getLineRight(0) - (mRight - mLeft) -
8607                                getCompoundPaddingLeft() - getCompoundPaddingRight() -
8608                                mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength();
8609                    case Gravity.CENTER_HORIZONTAL:
8610                        return 0.0f;
8611                }
8612            }
8613        }
8614        return super.getLeftFadingEdgeStrength();
8615    }
8616
8617    @Override
8618    protected float getRightFadingEdgeStrength() {
8619        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f;
8620        if (mEllipsize == TextUtils.TruncateAt.MARQUEE &&
8621                mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
8622            if (mMarquee != null && !mMarquee.isStopped()) {
8623                final Marquee marquee = mMarquee;
8624                return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength();
8625            } else if (getLineCount() == 1) {
8626                final int layoutDirection = getResolvedLayoutDirection();
8627                final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
8628                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
8629                    case Gravity.LEFT:
8630                        final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() -
8631                                getCompoundPaddingRight();
8632                        final float lineWidth = mLayout.getLineWidth(0);
8633                        return (lineWidth - textWidth) / getHorizontalFadingEdgeLength();
8634                    case Gravity.RIGHT:
8635                        return 0.0f;
8636                    case Gravity.CENTER_HORIZONTAL:
8637                    case Gravity.FILL_HORIZONTAL:
8638                        return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
8639                                getCompoundPaddingLeft() - getCompoundPaddingRight())) /
8640                                getHorizontalFadingEdgeLength();
8641                }
8642            }
8643        }
8644        return super.getRightFadingEdgeStrength();
8645    }
8646
8647    @Override
8648    protected int computeHorizontalScrollRange() {
8649        if (mLayout != null) {
8650            return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ?
8651                    (int) mLayout.getLineWidth(0) : mLayout.getWidth();
8652        }
8653
8654        return super.computeHorizontalScrollRange();
8655    }
8656
8657    @Override
8658    protected int computeVerticalScrollRange() {
8659        if (mLayout != null)
8660            return mLayout.getHeight();
8661
8662        return super.computeVerticalScrollRange();
8663    }
8664
8665    @Override
8666    protected int computeVerticalScrollExtent() {
8667        return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
8668    }
8669
8670    @Override
8671    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
8672        super.findViewsWithText(outViews, searched, flags);
8673        if (!outViews.contains(this) && (flags & FIND_VIEWS_WITH_TEXT) != 0
8674                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mText)) {
8675            String searchedLowerCase = searched.toString().toLowerCase();
8676            String textLowerCase = mText.toString().toLowerCase();
8677            if (textLowerCase.contains(searchedLowerCase)) {
8678                outViews.add(this);
8679            }
8680        }
8681    }
8682
8683    public enum BufferType {
8684        NORMAL, SPANNABLE, EDITABLE,
8685    }
8686
8687    /**
8688     * Returns the TextView_textColor attribute from the
8689     * Resources.StyledAttributes, if set, or the TextAppearance_textColor
8690     * from the TextView_textAppearance attribute, if TextView_textColor
8691     * was not set directly.
8692     */
8693    public static ColorStateList getTextColors(Context context, TypedArray attrs) {
8694        ColorStateList colors;
8695        colors = attrs.getColorStateList(com.android.internal.R.styleable.
8696                                         TextView_textColor);
8697
8698        if (colors == null) {
8699            int ap = attrs.getResourceId(com.android.internal.R.styleable.
8700                                         TextView_textAppearance, -1);
8701            if (ap != -1) {
8702                TypedArray appearance;
8703                appearance = context.obtainStyledAttributes(ap,
8704                                            com.android.internal.R.styleable.TextAppearance);
8705                colors = appearance.getColorStateList(com.android.internal.R.styleable.
8706                                                  TextAppearance_textColor);
8707                appearance.recycle();
8708            }
8709        }
8710
8711        return colors;
8712    }
8713
8714    /**
8715     * Returns the default color from the TextView_textColor attribute
8716     * from the AttributeSet, if set, or the default color from the
8717     * TextAppearance_textColor from the TextView_textAppearance attribute,
8718     * if TextView_textColor was not set directly.
8719     */
8720    public static int getTextColor(Context context,
8721                                   TypedArray attrs,
8722                                   int def) {
8723        ColorStateList colors = getTextColors(context, attrs);
8724
8725        if (colors == null) {
8726            return def;
8727        } else {
8728            return colors.getDefaultColor();
8729        }
8730    }
8731
8732    @Override
8733    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8734        final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK;
8735        if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) {
8736            switch (keyCode) {
8737            case KeyEvent.KEYCODE_A:
8738                if (canSelectText()) {
8739                    return onTextContextMenuItem(ID_SELECT_ALL);
8740                }
8741                break;
8742            case KeyEvent.KEYCODE_X:
8743                if (canCut()) {
8744                    return onTextContextMenuItem(ID_CUT);
8745                }
8746                break;
8747            case KeyEvent.KEYCODE_C:
8748                if (canCopy()) {
8749                    return onTextContextMenuItem(ID_COPY);
8750                }
8751                break;
8752            case KeyEvent.KEYCODE_V:
8753                if (canPaste()) {
8754                    return onTextContextMenuItem(ID_PASTE);
8755                }
8756                break;
8757            }
8758        }
8759        return super.onKeyShortcut(keyCode, event);
8760    }
8761
8762    /**
8763     * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the
8764     * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have
8765     * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient.
8766     */
8767    private boolean canSelectText() {
8768        return hasSelectionController() && mText.length() != 0;
8769    }
8770
8771    /**
8772     * Test based on the <i>intrinsic</i> charateristics of the TextView.
8773     * The text must be spannable and the movement method must allow for arbitary selection.
8774     *
8775     * See also {@link #canSelectText()}.
8776     */
8777    private boolean textCanBeSelected() {
8778        // prepareCursorController() relies on this method.
8779        // If you change this condition, make sure prepareCursorController is called anywhere
8780        // the value of this condition might be changed.
8781        if (mMovement == null || !mMovement.canSelectArbitrarily()) return false;
8782        return isTextEditable() || (mTextIsSelectable && mText instanceof Spannable && isEnabled());
8783    }
8784
8785    private boolean canCut() {
8786        if (hasPasswordTransformationMethod()) {
8787            return false;
8788        }
8789
8790        if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mInput != null) {
8791            return true;
8792        }
8793
8794        return false;
8795    }
8796
8797    private boolean canCopy() {
8798        if (hasPasswordTransformationMethod()) {
8799            return false;
8800        }
8801
8802        if (mText.length() > 0 && hasSelection()) {
8803            return true;
8804        }
8805
8806        return false;
8807    }
8808
8809    private boolean canPaste() {
8810        return (mText instanceof Editable &&
8811                mInput != null &&
8812                getSelectionStart() >= 0 &&
8813                getSelectionEnd() >= 0 &&
8814                ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)).
8815                hasPrimaryClip());
8816    }
8817
8818    private static long packRangeInLong(int start, int end) {
8819        return (((long) start) << 32) | end;
8820    }
8821
8822    private static int extractRangeStartFromLong(long range) {
8823        return (int) (range >>> 32);
8824    }
8825
8826    private static int extractRangeEndFromLong(long range) {
8827        return (int) (range & 0x00000000FFFFFFFFL);
8828    }
8829
8830    private boolean selectAll() {
8831        final int length = mText.length();
8832        Selection.setSelection((Spannable) mText, 0, length);
8833        return length > 0;
8834    }
8835
8836    /**
8837     * Adjusts selection to the word under last touch offset.
8838     * Return true if the operation was successfully performed.
8839     */
8840    private boolean selectCurrentWord() {
8841        if (!canSelectText()) {
8842            return false;
8843        }
8844
8845        if (hasPasswordTransformationMethod()) {
8846            // Always select all on a password field.
8847            // Cut/copy menu entries are not available for passwords, but being able to select all
8848            // is however useful to delete or paste to replace the entire content.
8849            return selectAll();
8850        }
8851
8852        int klass = mInputType & InputType.TYPE_MASK_CLASS;
8853        int variation = mInputType & InputType.TYPE_MASK_VARIATION;
8854
8855        // Specific text field types: select the entire text for these
8856        if (klass == InputType.TYPE_CLASS_NUMBER ||
8857                klass == InputType.TYPE_CLASS_PHONE ||
8858                klass == InputType.TYPE_CLASS_DATETIME ||
8859                variation == InputType.TYPE_TEXT_VARIATION_URI ||
8860                variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
8861                variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ||
8862                variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
8863            return selectAll();
8864        }
8865
8866        long lastTouchOffsets = getLastTouchOffsets();
8867        final int minOffset = extractRangeStartFromLong(lastTouchOffsets);
8868        final int maxOffset = extractRangeEndFromLong(lastTouchOffsets);
8869
8870        // Safety check in case standard touch event handling has been bypassed
8871        if (minOffset < 0 || minOffset >= mText.length()) return false;
8872        if (maxOffset < 0 || maxOffset >= mText.length()) return false;
8873
8874        int selectionStart, selectionEnd;
8875
8876        // If a URLSpan (web address, email, phone...) is found at that position, select it.
8877        URLSpan[] urlSpans = ((Spanned) mText).getSpans(minOffset, maxOffset, URLSpan.class);
8878        if (urlSpans.length >= 1) {
8879            URLSpan urlSpan = urlSpans[0];
8880            selectionStart = ((Spanned) mText).getSpanStart(urlSpan);
8881            selectionEnd = ((Spanned) mText).getSpanEnd(urlSpan);
8882        } else {
8883            final WordIterator wordIterator = getWordIterator();
8884            wordIterator.setCharSequence(mText, minOffset, maxOffset);
8885
8886            selectionStart = wordIterator.getBeginning(minOffset);
8887            if (selectionStart == BreakIterator.DONE) return false;
8888
8889            selectionEnd = wordIterator.getEnd(maxOffset);
8890            if (selectionEnd == BreakIterator.DONE) return false;
8891
8892            if (selectionStart == selectionEnd) {
8893                // Possible when the word iterator does not properly handle the text's language
8894                long range = getCharRange(selectionStart);
8895                selectionStart = extractRangeStartFromLong(range);
8896                selectionEnd = extractRangeEndFromLong(range);
8897            }
8898        }
8899
8900        Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
8901        return selectionEnd > selectionStart;
8902    }
8903
8904    /**
8905     * This is a temporary method. Future versions may support multi-locale text.
8906     *
8907     * @return The current locale used in this TextView, based on the current IME's locale,
8908     * or the system default locale if this is not defined.
8909     * @hide
8910     */
8911    public Locale getLocale() {
8912        Locale locale = Locale.getDefault();
8913        final InputMethodManager imm = InputMethodManager.peekInstance();
8914        if (imm != null) {
8915            final InputMethodSubtype currentInputMethodSubtype = imm.getCurrentInputMethodSubtype();
8916            if (currentInputMethodSubtype != null) {
8917                String localeString = currentInputMethodSubtype.getLocale();
8918                if (!TextUtils.isEmpty(localeString)) {
8919                    locale = new Locale(localeString);
8920                }
8921            }
8922        }
8923        return locale;
8924    }
8925
8926    void onLocaleChanged() {
8927        // Will be re-created on demand in getWordIterator with the proper new locale
8928        mWordIterator = null;
8929    }
8930
8931    /**
8932     * @hide
8933     */
8934    public WordIterator getWordIterator() {
8935        if (mWordIterator == null) {
8936            mWordIterator = new WordIterator(getLocale());
8937        }
8938        return mWordIterator;
8939    }
8940
8941    private long getCharRange(int offset) {
8942        final int textLength = mText.length();
8943        if (offset + 1 < textLength) {
8944            final char currentChar = mText.charAt(offset);
8945            final char nextChar = mText.charAt(offset + 1);
8946            if (Character.isSurrogatePair(currentChar, nextChar)) {
8947                return packRangeInLong(offset,  offset + 2);
8948            }
8949        }
8950        if (offset < textLength) {
8951            return packRangeInLong(offset,  offset + 1);
8952        }
8953        if (offset - 2 >= 0) {
8954            final char previousChar = mText.charAt(offset - 1);
8955            final char previousPreviousChar = mText.charAt(offset - 2);
8956            if (Character.isSurrogatePair(previousPreviousChar, previousChar)) {
8957                return packRangeInLong(offset - 2,  offset);
8958            }
8959        }
8960        if (offset - 1 >= 0) {
8961            return packRangeInLong(offset - 1,  offset);
8962        }
8963        return packRangeInLong(offset,  offset);
8964    }
8965
8966    private SpellChecker getSpellChecker() {
8967        if (mSpellChecker == null) {
8968            mSpellChecker = new SpellChecker(this);
8969        }
8970        return mSpellChecker;
8971    }
8972
8973    private long getLastTouchOffsets() {
8974        int minOffset, maxOffset;
8975
8976        if (mContextMenuTriggeredByKey) {
8977            minOffset = getSelectionStart();
8978            maxOffset = getSelectionEnd();
8979        } else {
8980            SelectionModifierCursorController selectionController = getSelectionController();
8981            minOffset = selectionController.getMinTouchOffset();
8982            maxOffset = selectionController.getMaxTouchOffset();
8983        }
8984
8985        return packRangeInLong(minOffset, maxOffset);
8986    }
8987
8988    @Override
8989    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
8990        super.onPopulateAccessibilityEvent(event);
8991
8992        final boolean isPassword = hasPasswordTransformationMethod();
8993        if (!isPassword) {
8994            CharSequence text = getTextForAccessibility();
8995            if (!TextUtils.isEmpty(text)) {
8996                event.getText().add(text);
8997            }
8998        }
8999    }
9000
9001    @Override
9002    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
9003        super.onInitializeAccessibilityEvent(event);
9004
9005        final boolean isPassword = hasPasswordTransformationMethod();
9006        event.setPassword(isPassword);
9007
9008        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) {
9009            event.setFromIndex(Selection.getSelectionStart(mText));
9010            event.setToIndex(Selection.getSelectionEnd(mText));
9011            event.setItemCount(mText.length());
9012        }
9013    }
9014
9015    @Override
9016    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
9017        super.onInitializeAccessibilityNodeInfo(info);
9018
9019        final boolean isPassword = hasPasswordTransformationMethod();
9020        if (!isPassword) {
9021            info.setText(getTextForAccessibility());
9022        }
9023        info.setPassword(isPassword);
9024    }
9025
9026    @Override
9027    public void sendAccessibilityEvent(int eventType) {
9028        // Do not send scroll events since first they are not interesting for
9029        // accessibility and second such events a generated too frequently.
9030        // For details see the implementation of bringTextIntoView().
9031        if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
9032            return;
9033        }
9034        super.sendAccessibilityEvent(eventType);
9035    }
9036
9037    /**
9038     * Gets the text reported for accessibility purposes. It is the
9039     * text if not empty or the hint.
9040     *
9041     * @return The accessibility text.
9042     */
9043    private CharSequence getTextForAccessibility() {
9044        CharSequence text = getText();
9045        if (TextUtils.isEmpty(text)) {
9046            text = getHint();
9047        }
9048        return text;
9049    }
9050
9051    void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText,
9052            int fromIndex, int removedCount, int addedCount) {
9053        AccessibilityEvent event =
9054            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
9055        event.setFromIndex(fromIndex);
9056        event.setRemovedCount(removedCount);
9057        event.setAddedCount(addedCount);
9058        event.setBeforeText(beforeText);
9059        sendAccessibilityEventUnchecked(event);
9060    }
9061
9062    @Override
9063    protected void onCreateContextMenu(ContextMenu menu) {
9064        super.onCreateContextMenu(menu);
9065        boolean added = false;
9066        mContextMenuTriggeredByKey = mDPadCenterIsDown || mEnterKeyIsDown;
9067        // Problem with context menu on long press: the menu appears while the key in down and when
9068        // the key is released, the view does not receive the key_up event.
9069        // We need two layers of flags: mDPadCenterIsDown and mEnterKeyIsDown are set in key down/up
9070        // events. We cannot simply clear these flags in onTextContextMenuItem since
9071        // it may not be called (if the user/ discards the context menu with the back key).
9072        // We clear these flags here and mContextMenuTriggeredByKey saves that state so that it is
9073        // available in onTextContextMenuItem.
9074        mDPadCenterIsDown = mEnterKeyIsDown = false;
9075
9076        MenuHandler handler = new MenuHandler();
9077
9078        if (mText instanceof Spanned && hasSelectionController()) {
9079            long lastTouchOffset = getLastTouchOffsets();
9080            final int selStart = extractRangeStartFromLong(lastTouchOffset);
9081            final int selEnd = extractRangeEndFromLong(lastTouchOffset);
9082
9083            URLSpan[] urls = ((Spanned) mText).getSpans(selStart, selEnd, URLSpan.class);
9084            if (urls.length > 0) {
9085                menu.add(0, ID_COPY_URL, 0, com.android.internal.R.string.copyUrl).
9086                        setOnMenuItemClickListener(handler);
9087
9088                added = true;
9089            }
9090        }
9091
9092        // The context menu is not empty, which will prevent the selection mode from starting.
9093        // Add a entry to start it in the context menu.
9094        // TODO Does not handle the case where a subclass does not call super.thisMethod or
9095        // populates the menu AFTER this call.
9096        if (menu.size() > 0) {
9097            menu.add(0, ID_SELECTION_MODE, 0, com.android.internal.R.string.selectTextMode).
9098                    setOnMenuItemClickListener(handler);
9099            added = true;
9100        }
9101
9102        if (added) {
9103            menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle);
9104        }
9105    }
9106
9107    /**
9108     * Returns whether this text view is a current input method target.  The
9109     * default implementation just checks with {@link InputMethodManager}.
9110     */
9111    public boolean isInputMethodTarget() {
9112        InputMethodManager imm = InputMethodManager.peekInstance();
9113        return imm != null && imm.isActive(this);
9114    }
9115
9116    // Selection context mode
9117    private static final int ID_SELECT_ALL = android.R.id.selectAll;
9118    private static final int ID_CUT = android.R.id.cut;
9119    private static final int ID_COPY = android.R.id.copy;
9120    private static final int ID_PASTE = android.R.id.paste;
9121    // Context menu entries
9122    private static final int ID_COPY_URL = android.R.id.copyUrl;
9123    private static final int ID_SELECTION_MODE = android.R.id.selectTextMode;
9124
9125    private class MenuHandler implements MenuItem.OnMenuItemClickListener {
9126        public boolean onMenuItemClick(MenuItem item) {
9127            return onTextContextMenuItem(item.getItemId());
9128        }
9129    }
9130
9131    /**
9132     * Called when a context menu option for the text view is selected.  Currently
9133     * this will be {@link android.R.id#copyUrl}, {@link android.R.id#selectTextMode},
9134     * {@link android.R.id#selectAll}, {@link android.R.id#paste}, {@link android.R.id#cut}
9135     * or {@link android.R.id#copy}.
9136     *
9137     * @return true if the context menu item action was performed.
9138     */
9139    public boolean onTextContextMenuItem(int id) {
9140        int min = 0;
9141        int max = mText.length();
9142
9143        if (isFocused()) {
9144            final int selStart = getSelectionStart();
9145            final int selEnd = getSelectionEnd();
9146
9147            min = Math.max(0, Math.min(selStart, selEnd));
9148            max = Math.max(0, Math.max(selStart, selEnd));
9149        }
9150
9151        switch (id) {
9152            case ID_COPY_URL:
9153                URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class);
9154                if (urls.length >= 1) {
9155                    ClipData clip = null;
9156                    for (int i=0; i<urls.length; i++) {
9157                        Uri uri = Uri.parse(urls[0].getURL());
9158                        if (clip == null) {
9159                            clip = ClipData.newRawUri(null, uri);
9160                        } else {
9161                            clip.addItem(new ClipData.Item(uri));
9162                        }
9163                    }
9164                    if (clip != null) {
9165                        setPrimaryClip(clip);
9166                    }
9167                }
9168                stopSelectionActionMode();
9169                return true;
9170
9171            case ID_SELECTION_MODE:
9172                if (mSelectionActionMode != null) {
9173                    // Selection mode is already started, simply change selected part.
9174                    selectCurrentWord();
9175                } else {
9176                    startSelectionActionMode();
9177                }
9178                return true;
9179
9180            case ID_SELECT_ALL:
9181                // This does not enter text selection mode. Text is highlighted, so that it can be
9182                // bulk edited, like selectAllOnFocus does. Returns true even if text is empty.
9183                selectAll();
9184                return true;
9185
9186            case ID_PASTE:
9187                paste(min, max);
9188                return true;
9189
9190            case ID_CUT:
9191                setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
9192                ((Editable) mText).delete(min, max);
9193                stopSelectionActionMode();
9194                return true;
9195
9196            case ID_COPY:
9197                setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
9198                stopSelectionActionMode();
9199                return true;
9200        }
9201        return false;
9202    }
9203
9204    private CharSequence getTransformedText(int start, int end) {
9205        return removeSuggestionSpans(mTransformed.subSequence(start, end));
9206    }
9207
9208    /**
9209     * Prepare text so that there are not zero or two spaces at beginning and end of region defined
9210     * by [min, max] when replacing this region by paste.
9211     * Note that if there were two spaces (or more) at that position before, they are kept. We just
9212     * make sure we do not add an extra one from the paste content.
9213     */
9214    private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) {
9215        if (paste.length() > 0) {
9216            if (min > 0) {
9217                final char charBefore = mTransformed.charAt(min - 1);
9218                final char charAfter = paste.charAt(0);
9219
9220                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
9221                    // Two spaces at beginning of paste: remove one
9222                    final int originalLength = mText.length();
9223                    ((Editable) mText).delete(min - 1, min);
9224                    // Due to filters, there is no guarantee that exactly one character was
9225                    // removed: count instead.
9226                    final int delta = mText.length() - originalLength;
9227                    min += delta;
9228                    max += delta;
9229                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
9230                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
9231                    // No space at beginning of paste: add one
9232                    final int originalLength = mText.length();
9233                    ((Editable) mText).replace(min, min, " ");
9234                    // Taking possible filters into account as above.
9235                    final int delta = mText.length() - originalLength;
9236                    min += delta;
9237                    max += delta;
9238                }
9239            }
9240
9241            if (max < mText.length()) {
9242                final char charBefore = paste.charAt(paste.length() - 1);
9243                final char charAfter = mTransformed.charAt(max);
9244
9245                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
9246                    // Two spaces at end of paste: remove one
9247                    ((Editable) mText).delete(max, max + 1);
9248                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
9249                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
9250                    // No space at end of paste: add one
9251                    ((Editable) mText).replace(max, max, " ");
9252                }
9253            }
9254        }
9255
9256        return packRangeInLong(min, max);
9257    }
9258
9259    private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) {
9260        TextView shadowView = (TextView) inflate(mContext,
9261                com.android.internal.R.layout.text_drag_thumbnail, null);
9262
9263        if (shadowView == null) {
9264            throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
9265        }
9266
9267        if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) {
9268            text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH);
9269        }
9270        shadowView.setText(text);
9271        shadowView.setTextColor(getTextColors());
9272
9273        shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge);
9274        shadowView.setGravity(Gravity.CENTER);
9275
9276        shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
9277                ViewGroup.LayoutParams.WRAP_CONTENT));
9278
9279        final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
9280        shadowView.measure(size, size);
9281
9282        shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
9283        shadowView.invalidate();
9284        return new DragShadowBuilder(shadowView);
9285    }
9286
9287    private static class DragLocalState {
9288        public TextView sourceTextView;
9289        public int start, end;
9290
9291        public DragLocalState(TextView sourceTextView, int start, int end) {
9292            this.sourceTextView = sourceTextView;
9293            this.start = start;
9294            this.end = end;
9295        }
9296    }
9297
9298    @Override
9299    public boolean performLongClick() {
9300        boolean handled = false;
9301        boolean vibrate = true;
9302
9303        if (super.performLongClick()) {
9304            mDiscardNextActionUp = true;
9305            handled = true;
9306        }
9307
9308        // Long press in empty space moves cursor and shows the Paste affordance if available.
9309        if (!handled && !isPositionOnText(mLastDownPositionX, mLastDownPositionY) &&
9310                mInsertionControllerEnabled) {
9311            final int offset = getOffsetForPosition(mLastDownPositionX, mLastDownPositionY);
9312            stopSelectionActionMode();
9313            Selection.setSelection((Spannable) mText, offset);
9314            getInsertionController().showWithActionPopup();
9315            handled = true;
9316            vibrate = false;
9317        }
9318
9319        if (!handled && mSelectionActionMode != null) {
9320            if (touchPositionIsInSelection()) {
9321                // Start a drag
9322                final int start = getSelectionStart();
9323                final int end = getSelectionEnd();
9324                CharSequence selectedText = getTransformedText(start, end);
9325                ClipData data = ClipData.newPlainText(null, selectedText);
9326                DragLocalState localState = new DragLocalState(this, start, end);
9327                startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0);
9328                stopSelectionActionMode();
9329            } else {
9330                getSelectionController().hide();
9331                selectCurrentWord();
9332                getSelectionController().show();
9333            }
9334            handled = true;
9335        }
9336
9337        // Start a new selection
9338        if (!handled) {
9339            vibrate = handled = startSelectionActionMode();
9340        }
9341
9342        if (vibrate) {
9343            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
9344        }
9345
9346        if (handled) {
9347            mDiscardNextActionUp = true;
9348        }
9349
9350        return handled;
9351    }
9352
9353    private boolean touchPositionIsInSelection() {
9354        int selectionStart = getSelectionStart();
9355        int selectionEnd = getSelectionEnd();
9356
9357        if (selectionStart == selectionEnd) {
9358            return false;
9359        }
9360
9361        if (selectionStart > selectionEnd) {
9362            int tmp = selectionStart;
9363            selectionStart = selectionEnd;
9364            selectionEnd = tmp;
9365            Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
9366        }
9367
9368        SelectionModifierCursorController selectionController = getSelectionController();
9369        int minOffset = selectionController.getMinTouchOffset();
9370        int maxOffset = selectionController.getMaxTouchOffset();
9371
9372        return ((minOffset >= selectionStart) && (maxOffset < selectionEnd));
9373    }
9374
9375    private PositionListener getPositionListener() {
9376        if (mPositionListener == null) {
9377            mPositionListener = new PositionListener();
9378        }
9379        return mPositionListener;
9380    }
9381
9382    private interface TextViewPositionListener {
9383        public void updatePosition(int parentPositionX, int parentPositionY,
9384                boolean parentPositionChanged, boolean parentScrolled);
9385    }
9386
9387    private class PositionListener implements ViewTreeObserver.OnPreDrawListener {
9388        // 3 handles
9389        // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others)
9390        private final int MAXIMUM_NUMBER_OF_LISTENERS = 6;
9391        private TextViewPositionListener[] mPositionListeners =
9392                new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS];
9393        private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS];
9394        private boolean mPositionHasChanged = true;
9395        // Absolute position of the TextView with respect to its parent window
9396        private int mPositionX, mPositionY;
9397        private int mNumberOfListeners;
9398        private boolean mScrollHasChanged;
9399
9400        public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) {
9401            if (mNumberOfListeners == 0) {
9402                updatePosition();
9403                ViewTreeObserver vto = TextView.this.getViewTreeObserver();
9404                vto.addOnPreDrawListener(this);
9405            }
9406
9407            int emptySlotIndex = -1;
9408            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
9409                TextViewPositionListener listener = mPositionListeners[i];
9410                if (listener == positionListener) {
9411                    return;
9412                } else if (emptySlotIndex < 0 && listener == null) {
9413                    emptySlotIndex = i;
9414                }
9415            }
9416
9417            mPositionListeners[emptySlotIndex] = positionListener;
9418            mCanMove[emptySlotIndex] = canMove;
9419            mNumberOfListeners++;
9420        }
9421
9422        public void removeSubscriber(TextViewPositionListener positionListener) {
9423            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
9424                if (mPositionListeners[i] == positionListener) {
9425                    mPositionListeners[i] = null;
9426                    mNumberOfListeners--;
9427                    break;
9428                }
9429            }
9430
9431            if (mNumberOfListeners == 0) {
9432                ViewTreeObserver vto = TextView.this.getViewTreeObserver();
9433                vto.removeOnPreDrawListener(this);
9434            }
9435        }
9436
9437        public int getPositionX() {
9438            return mPositionX;
9439        }
9440
9441        public int getPositionY() {
9442            return mPositionY;
9443        }
9444
9445        @Override
9446        public boolean onPreDraw() {
9447            updatePosition();
9448
9449            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
9450                if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) {
9451                    TextViewPositionListener positionListener = mPositionListeners[i];
9452                    if (positionListener != null) {
9453                        positionListener.updatePosition(mPositionX, mPositionY,
9454                                mPositionHasChanged, mScrollHasChanged);
9455                    }
9456                }
9457            }
9458
9459            mScrollHasChanged = false;
9460            return true;
9461        }
9462
9463        private void updatePosition() {
9464            TextView.this.getLocationInWindow(mTempCoords);
9465
9466            mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY;
9467
9468            mPositionX = mTempCoords[0];
9469            mPositionY = mTempCoords[1];
9470        }
9471
9472        public boolean isVisible(int positionX, int positionY) {
9473            final TextView textView = TextView.this;
9474
9475            if (mTempRect == null) mTempRect = new Rect();
9476            final Rect clip = mTempRect;
9477            clip.left = getCompoundPaddingLeft();
9478            clip.top = getExtendedPaddingTop();
9479            clip.right = textView.getWidth() - getCompoundPaddingRight();
9480            clip.bottom = textView.getHeight() - getExtendedPaddingBottom();
9481
9482            final ViewParent parent = textView.getParent();
9483            if (parent == null || !parent.getChildVisibleRect(textView, clip, null)) {
9484                return false;
9485            }
9486
9487            int posX = mPositionX + positionX;
9488            int posY = mPositionY + positionY;
9489
9490            // Offset by 1 to take into account 0.5 and int rounding around getPrimaryHorizontal.
9491            return posX >= clip.left - 1 && posX <= clip.right + 1 &&
9492                    posY >= clip.top && posY <= clip.bottom;
9493        }
9494
9495        public boolean isOffsetVisible(int offset) {
9496            final int line = mLayout.getLineForOffset(offset);
9497            final int lineBottom = mLayout.getLineBottom(line);
9498            final int primaryHorizontal = (int) mLayout.getPrimaryHorizontal(offset);
9499            return isVisible(primaryHorizontal + viewportToContentHorizontalOffset(),
9500                    lineBottom + viewportToContentVerticalOffset());
9501        }
9502
9503        public void onScrollChanged() {
9504            mScrollHasChanged = true;
9505        }
9506    }
9507
9508    @Override
9509    protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) {
9510        super.onScrollChanged(horiz, vert, oldHoriz, oldVert);
9511        if (mPositionListener != null) {
9512            mPositionListener.onScrollChanged();
9513        }
9514    }
9515
9516    private abstract class PinnedPopupWindow implements TextViewPositionListener {
9517        protected PopupWindow mPopupWindow;
9518        protected ViewGroup mContentView;
9519        int mPositionX, mPositionY;
9520
9521        protected abstract void createPopupWindow();
9522        protected abstract void initContentView();
9523        protected abstract int getTextOffset();
9524        protected abstract int getVerticalLocalPosition(int line);
9525        protected abstract int clipVertically(int positionY);
9526
9527        public PinnedPopupWindow() {
9528            createPopupWindow();
9529
9530            mPopupWindow.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
9531            mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
9532            mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
9533
9534            initContentView();
9535
9536            LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
9537                    ViewGroup.LayoutParams.WRAP_CONTENT);
9538            mContentView.setLayoutParams(wrapContent);
9539
9540            mPopupWindow.setContentView(mContentView);
9541        }
9542
9543        public void show() {
9544            TextView.this.getPositionListener().addSubscriber(this, false /* offset is fixed */);
9545
9546            computeLocalPosition();
9547
9548            final PositionListener positionListener = TextView.this.getPositionListener();
9549            updatePosition(positionListener.getPositionX(), positionListener.getPositionY());
9550        }
9551
9552        protected void measureContent() {
9553            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
9554            mContentView.measure(
9555                    View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels,
9556                            View.MeasureSpec.AT_MOST),
9557                    View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels,
9558                            View.MeasureSpec.AT_MOST));
9559        }
9560
9561        /* The popup window will be horizontally centered on the getTextOffset() and vertically
9562         * positioned according to viewportToContentHorizontalOffset.
9563         *
9564         * This method assumes that mContentView has properly been measured from its content. */
9565        private void computeLocalPosition() {
9566            measureContent();
9567            final int width = mContentView.getMeasuredWidth();
9568            final int offset = getTextOffset();
9569            mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - width / 2.0f);
9570            mPositionX += viewportToContentHorizontalOffset();
9571
9572            final int line = mLayout.getLineForOffset(offset);
9573            mPositionY = getVerticalLocalPosition(line);
9574            mPositionY += viewportToContentVerticalOffset();
9575        }
9576
9577        private void updatePosition(int parentPositionX, int parentPositionY) {
9578            int positionX = parentPositionX + mPositionX;
9579            int positionY = parentPositionY + mPositionY;
9580
9581            positionY = clipVertically(positionY);
9582
9583            // Horizontal clipping
9584            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
9585            final int width = mContentView.getMeasuredWidth();
9586            positionX = Math.min(displayMetrics.widthPixels - width, positionX);
9587            positionX = Math.max(0, positionX);
9588
9589            if (isShowing()) {
9590                mPopupWindow.update(positionX, positionY, -1, -1);
9591            } else {
9592                mPopupWindow.showAtLocation(TextView.this, Gravity.NO_GRAVITY,
9593                        positionX, positionY);
9594            }
9595        }
9596
9597        public void hide() {
9598            mPopupWindow.dismiss();
9599            TextView.this.getPositionListener().removeSubscriber(this);
9600        }
9601
9602        @Override
9603        public void updatePosition(int parentPositionX, int parentPositionY,
9604                boolean parentPositionChanged, boolean parentScrolled) {
9605            // Either parentPositionChanged or parentScrolled is true, check if still visible
9606            if (isShowing() && getPositionListener().isOffsetVisible(getTextOffset())) {
9607                if (parentScrolled) computeLocalPosition();
9608                updatePosition(parentPositionX, parentPositionY);
9609            } else {
9610                hide();
9611            }
9612        }
9613
9614        public boolean isShowing() {
9615            return mPopupWindow.isShowing();
9616        }
9617    }
9618
9619    private class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener {
9620        private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE;
9621        private static final int ADD_TO_DICTIONARY = -1;
9622        private static final int DELETE_TEXT = -2;
9623        private SuggestionInfo[] mSuggestionInfos;
9624        private int mNumberOfSuggestions;
9625        private boolean mCursorWasVisibleBeforeSuggestions;
9626        private boolean mIsShowingUp = false;
9627        private SuggestionAdapter mSuggestionsAdapter;
9628        private final Comparator<SuggestionSpan> mSuggestionSpanComparator;
9629        private final HashMap<SuggestionSpan, Integer> mSpansLengths;
9630
9631        private class CustomPopupWindow extends PopupWindow {
9632            public CustomPopupWindow(Context context, int defStyle) {
9633                super(context, null, defStyle);
9634            }
9635
9636            @Override
9637            public void dismiss() {
9638                super.dismiss();
9639
9640                TextView.this.getPositionListener().removeSubscriber(SuggestionsPopupWindow.this);
9641
9642                // Safe cast since show() checks that mText is an Editable
9643                ((Spannable) mText).removeSpan(mSuggestionRangeSpan);
9644
9645                setCursorVisible(mCursorWasVisibleBeforeSuggestions);
9646                if (hasInsertionController()) {
9647                    getInsertionController().show();
9648                }
9649            }
9650        }
9651
9652        public SuggestionsPopupWindow() {
9653            mCursorWasVisibleBeforeSuggestions = mCursorVisible;
9654            mSuggestionSpanComparator = new SuggestionSpanComparator();
9655            mSpansLengths = new HashMap<SuggestionSpan, Integer>();
9656        }
9657
9658        @Override
9659        protected void createPopupWindow() {
9660            mPopupWindow = new CustomPopupWindow(TextView.this.mContext,
9661                com.android.internal.R.attr.textSuggestionsWindowStyle);
9662            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
9663            mPopupWindow.setFocusable(true);
9664            mPopupWindow.setClippingEnabled(false);
9665        }
9666
9667        @Override
9668        protected void initContentView() {
9669            ListView listView = new ListView(TextView.this.getContext());
9670            mSuggestionsAdapter = new SuggestionAdapter();
9671            listView.setAdapter(mSuggestionsAdapter);
9672            listView.setOnItemClickListener(this);
9673            mContentView = listView;
9674
9675            // Inflate the suggestion items once and for all. + 2 for add to dictionary and delete
9676            mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS + 2];
9677            for (int i = 0; i < mSuggestionInfos.length; i++) {
9678                mSuggestionInfos[i] = new SuggestionInfo();
9679            }
9680        }
9681
9682        public boolean isShowingUp() {
9683            return mIsShowingUp;
9684        }
9685
9686        public void onParentLostFocus() {
9687            mIsShowingUp = false;
9688        }
9689
9690        private class SuggestionInfo {
9691            int suggestionStart, suggestionEnd; // range of actual suggestion within text
9692            SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents
9693            int suggestionIndex; // the index of this suggestion inside suggestionSpan
9694            SpannableStringBuilder text = new SpannableStringBuilder();
9695            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mContext,
9696                    android.R.style.TextAppearance_SuggestionHighlight);
9697        }
9698
9699        private class SuggestionAdapter extends BaseAdapter {
9700            private LayoutInflater mInflater = (LayoutInflater) TextView.this.mContext.
9701                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
9702
9703            @Override
9704            public int getCount() {
9705                return mNumberOfSuggestions;
9706            }
9707
9708            @Override
9709            public Object getItem(int position) {
9710                return mSuggestionInfos[position];
9711            }
9712
9713            @Override
9714            public long getItemId(int position) {
9715                return position;
9716            }
9717
9718            @Override
9719            public View getView(int position, View convertView, ViewGroup parent) {
9720                TextView textView = (TextView) convertView;
9721
9722                if (textView == null) {
9723                    textView = (TextView) mInflater.inflate(mTextEditSuggestionItemLayout, parent,
9724                            false);
9725                }
9726
9727                final SuggestionInfo suggestionInfo = mSuggestionInfos[position];
9728                textView.setText(suggestionInfo.text);
9729
9730                if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) {
9731                    textView.setCompoundDrawablesWithIntrinsicBounds(
9732                            com.android.internal.R.drawable.ic_suggestions_add, 0, 0, 0);
9733                } else if (suggestionInfo.suggestionIndex == DELETE_TEXT) {
9734                    textView.setCompoundDrawablesWithIntrinsicBounds(
9735                            com.android.internal.R.drawable.ic_suggestions_delete, 0, 0, 0);
9736                } else {
9737                    textView.setCompoundDrawables(null, null, null, null);
9738                }
9739
9740                return textView;
9741            }
9742        }
9743
9744        private class SuggestionSpanComparator implements Comparator<SuggestionSpan> {
9745            public int compare(SuggestionSpan span1, SuggestionSpan span2) {
9746                final int flag1 = span1.getFlags();
9747                final int flag2 = span2.getFlags();
9748                if (flag1 != flag2) {
9749                    // The order here should match what is used in updateDrawState
9750                    final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
9751                    final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
9752                    final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0;
9753                    final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0;
9754                    if (easy1 && !misspelled1) return -1;
9755                    if (easy2 && !misspelled2) return 1;
9756                    if (misspelled1) return -1;
9757                    if (misspelled2) return 1;
9758                }
9759
9760                return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue();
9761            }
9762        }
9763
9764        /**
9765         * Returns the suggestion spans that cover the current cursor position. The suggestion
9766         * spans are sorted according to the length of text that they are attached to.
9767         */
9768        private SuggestionSpan[] getSuggestionSpans() {
9769            int pos = TextView.this.getSelectionStart();
9770            Spannable spannable = (Spannable) TextView.this.mText;
9771            SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class);
9772
9773            mSpansLengths.clear();
9774            for (SuggestionSpan suggestionSpan : suggestionSpans) {
9775                int start = spannable.getSpanStart(suggestionSpan);
9776                int end = spannable.getSpanEnd(suggestionSpan);
9777                mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start));
9778            }
9779
9780            // The suggestions are sorted according to their types (easy correction first, then
9781            // misspelled) and to the length of the text that they cover (shorter first).
9782            Arrays.sort(suggestionSpans, mSuggestionSpanComparator);
9783            return suggestionSpans;
9784        }
9785
9786        @Override
9787        public void show() {
9788            if (!(mText instanceof Editable)) return;
9789
9790            updateSuggestions();
9791            mCursorWasVisibleBeforeSuggestions = mCursorVisible;
9792            setCursorVisible(false);
9793            mIsShowingUp = true;
9794            super.show();
9795        }
9796
9797        @Override
9798        protected void measureContent() {
9799            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
9800            final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec(
9801                    displayMetrics.widthPixels, View.MeasureSpec.AT_MOST);
9802            final int verticalMeasure = View.MeasureSpec.makeMeasureSpec(
9803                    displayMetrics.heightPixels, View.MeasureSpec.AT_MOST);
9804
9805            int width = 0;
9806            View view = null;
9807            for (int i = 0; i < mNumberOfSuggestions; i++) {
9808                view = mSuggestionsAdapter.getView(i, view, mContentView);
9809                view.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
9810                view.measure(horizontalMeasure, verticalMeasure);
9811                width = Math.max(width, view.getMeasuredWidth());
9812            }
9813
9814            // Enforce the width based on actual text widths
9815            mContentView.measure(
9816                    View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
9817                    verticalMeasure);
9818
9819            Drawable popupBackground = mPopupWindow.getBackground();
9820            if (popupBackground != null) {
9821                if (mTempRect == null) mTempRect = new Rect();
9822                popupBackground.getPadding(mTempRect);
9823                width += mTempRect.left + mTempRect.right;
9824            }
9825            mPopupWindow.setWidth(width);
9826        }
9827
9828        @Override
9829        protected int getTextOffset() {
9830            return getSelectionStart();
9831        }
9832
9833        @Override
9834        protected int getVerticalLocalPosition(int line) {
9835            return mLayout.getLineBottom(line);
9836        }
9837
9838        @Override
9839        protected int clipVertically(int positionY) {
9840            final int height = mContentView.getMeasuredHeight();
9841            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
9842            return Math.min(positionY, displayMetrics.heightPixels - height);
9843        }
9844
9845        @Override
9846        public void hide() {
9847            super.hide();
9848        }
9849
9850        private void updateSuggestions() {
9851            Spannable spannable = (Spannable) TextView.this.mText;
9852            SuggestionSpan[] suggestionSpans = getSuggestionSpans();
9853
9854            final int nbSpans = suggestionSpans.length;
9855
9856            mNumberOfSuggestions = 0;
9857            int spanUnionStart = mText.length();
9858            int spanUnionEnd = 0;
9859
9860            SuggestionSpan misspelledSpan = null;
9861            int underlineColor = 0;
9862
9863            for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) {
9864                SuggestionSpan suggestionSpan = suggestionSpans[spanIndex];
9865                final int spanStart = spannable.getSpanStart(suggestionSpan);
9866                final int spanEnd = spannable.getSpanEnd(suggestionSpan);
9867                spanUnionStart = Math.min(spanStart, spanUnionStart);
9868                spanUnionEnd = Math.max(spanEnd, spanUnionEnd);
9869
9870                if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) {
9871                    misspelledSpan = suggestionSpan;
9872                }
9873
9874                // The first span dictates the background color of the highlighted text
9875                if (spanIndex == 0) underlineColor = suggestionSpan.getUnderlineColor();
9876
9877                String[] suggestions = suggestionSpan.getSuggestions();
9878                int nbSuggestions = suggestions.length;
9879                for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) {
9880                    SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
9881                    suggestionInfo.suggestionSpan = suggestionSpan;
9882                    suggestionInfo.suggestionIndex = suggestionIndex;
9883                    suggestionInfo.text.replace(0, suggestionInfo.text.length(),
9884                            suggestions[suggestionIndex]);
9885
9886                    mNumberOfSuggestions++;
9887                    if (mNumberOfSuggestions == MAX_NUMBER_SUGGESTIONS) {
9888                        // Also end outer for loop
9889                        spanIndex = nbSpans;
9890                        break;
9891                    }
9892                }
9893            }
9894
9895            for (int i = 0; i < mNumberOfSuggestions; i++) {
9896                highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd);
9897            }
9898
9899            // Add to dictionary item is there a span with the misspelled flag
9900            if (misspelledSpan != null) {
9901                final int misspelledStart = spannable.getSpanStart(misspelledSpan);
9902                final int misspelledEnd = spannable.getSpanEnd(misspelledSpan);
9903                if (misspelledStart >= 0 && misspelledEnd > misspelledStart) {
9904                    SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
9905                    suggestionInfo.suggestionSpan = misspelledSpan;
9906                    suggestionInfo.suggestionIndex = ADD_TO_DICTIONARY;
9907                    suggestionInfo.text.replace(0, suggestionInfo.text.length(),
9908                            getContext().getString(com.android.internal.R.string.addToDictionary));
9909                    suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
9910                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
9911
9912                    mNumberOfSuggestions++;
9913                }
9914            }
9915
9916            // Delete item
9917            SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
9918            suggestionInfo.suggestionSpan = null;
9919            suggestionInfo.suggestionIndex = DELETE_TEXT;
9920            suggestionInfo.text.replace(0, suggestionInfo.text.length(),
9921                    getContext().getString(com.android.internal.R.string.deleteText));
9922            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
9923                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
9924            mNumberOfSuggestions++;
9925
9926            if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan();
9927            if (underlineColor == 0) {
9928                // Fallback on the default highlight color when the first span does not provide one
9929                mSuggestionRangeSpan.setBackgroundColor(mHighlightColor);
9930            } else {
9931                final float BACKGROUND_TRANSPARENCY = 0.4f;
9932                final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY);
9933                mSuggestionRangeSpan.setBackgroundColor(
9934                        (underlineColor & 0x00FFFFFF) + (newAlpha << 24));
9935            }
9936            spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd,
9937                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
9938
9939            mSuggestionsAdapter.notifyDataSetChanged();
9940        }
9941
9942        private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart,
9943                int unionEnd) {
9944            final Spannable text = (Spannable) mText;
9945            final int spanStart = text.getSpanStart(suggestionInfo.suggestionSpan);
9946            final int spanEnd = text.getSpanEnd(suggestionInfo.suggestionSpan);
9947
9948            // Adjust the start/end of the suggestion span
9949            suggestionInfo.suggestionStart = spanStart - unionStart;
9950            suggestionInfo.suggestionEnd = suggestionInfo.suggestionStart
9951                    + suggestionInfo.text.length();
9952
9953            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0,
9954                    suggestionInfo.text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
9955
9956            // Add the text before and after the span.
9957            suggestionInfo.text.insert(0, mText.toString().substring(unionStart, spanStart));
9958            suggestionInfo.text.append(mText.toString().substring(spanEnd, unionEnd));
9959        }
9960
9961        @Override
9962        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
9963            TextView textView = (TextView) view;
9964            Editable editable = (Editable) mText;
9965
9966            SuggestionInfo suggestionInfo = mSuggestionInfos[position];
9967
9968            if (suggestionInfo.suggestionIndex == DELETE_TEXT) {
9969                final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan);
9970                int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan);
9971                if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) {
9972                    // Do not leave two adjacent spaces after deletion, or one at beginning of text
9973                    if (spanUnionEnd < editable.length() &&
9974                            Character.isSpaceChar(editable.charAt(spanUnionEnd)) &&
9975                            (spanUnionStart == 0 ||
9976                            Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) {
9977                        spanUnionEnd = spanUnionEnd + 1;
9978                    }
9979                    editable.replace(spanUnionStart, spanUnionEnd, "");
9980                }
9981                hide();
9982                return;
9983            }
9984
9985            final int spanStart = editable.getSpanStart(suggestionInfo.suggestionSpan);
9986            final int spanEnd = editable.getSpanEnd(suggestionInfo.suggestionSpan);
9987            if (spanStart < 0 || spanEnd < 0) {
9988                // Span has been removed
9989                hide();
9990                return;
9991            }
9992            final String originalText = mText.toString().substring(spanStart, spanEnd);
9993
9994            if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) {
9995                Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT);
9996                intent.putExtra("word", originalText);
9997                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
9998                getContext().startActivity(intent);
9999                // There is no way to know if the word was indeed added. Re-check.
10000                editable.removeSpan(suggestionInfo.suggestionSpan);
10001                updateSpellCheckSpans(spanStart, spanEnd);
10002            } else {
10003                // SuggestionSpans are removed by replace: save them before
10004                SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd,
10005                        SuggestionSpan.class);
10006                final int length = suggestionSpans.length;
10007                int[] suggestionSpansStarts = new int[length];
10008                int[] suggestionSpansEnds = new int[length];
10009                int[] suggestionSpansFlags = new int[length];
10010                for (int i = 0; i < length; i++) {
10011                    final SuggestionSpan suggestionSpan = suggestionSpans[i];
10012                    suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan);
10013                    suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan);
10014                    suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan);
10015
10016                    // Remove potential misspelled flags
10017                    int suggestionSpanFlags = suggestionSpan.getFlags();
10018                    if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) > 0) {
10019                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED;
10020                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
10021                        suggestionSpan.setFlags(suggestionSpanFlags);
10022                    }
10023                }
10024
10025                final int suggestionStart = suggestionInfo.suggestionStart;
10026                final int suggestionEnd = suggestionInfo.suggestionEnd;
10027                final String suggestion = textView.getText().subSequence(
10028                        suggestionStart, suggestionEnd).toString();
10029                editable.replace(spanStart, spanEnd, suggestion);
10030
10031                // Notify source IME of the suggestion pick. Do this before swaping texts.
10032                if (!TextUtils.isEmpty(
10033                        suggestionInfo.suggestionSpan.getNotificationTargetClassName())) {
10034                    InputMethodManager imm = InputMethodManager.peekInstance();
10035                    if (imm != null) {
10036                        imm.notifySuggestionPicked(suggestionInfo.suggestionSpan, originalText,
10037                                suggestionInfo.suggestionIndex);
10038                    }
10039                }
10040
10041                // Swap text content between actual text and Suggestion span
10042                String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions();
10043                suggestions[suggestionInfo.suggestionIndex] = originalText;
10044
10045                // Restore previous SuggestionSpans
10046                final int lengthDifference = suggestion.length() - (spanEnd - spanStart);
10047                for (int i = 0; i < length; i++) {
10048                    // Only spans that include the modified region make sense after replacement
10049                    // Spans partially included in the replaced region are removed, there is no
10050                    // way to assign them a valid range after replacement
10051                    if (suggestionSpansStarts[i] <= spanStart &&
10052                            suggestionSpansEnds[i] >= spanEnd) {
10053                        editable.setSpan(suggestionSpans[i], suggestionSpansStarts[i],
10054                                suggestionSpansEnds[i] + lengthDifference, suggestionSpansFlags[i]);
10055                    }
10056                }
10057
10058                // Move cursor at the end of the replaced word
10059                Selection.setSelection(editable, spanEnd + lengthDifference);
10060            }
10061
10062            hide();
10063        }
10064    }
10065
10066    /**
10067     * Removes the suggestion spans.
10068     */
10069    CharSequence removeSuggestionSpans(CharSequence text) {
10070       if (text instanceof Spanned) {
10071           Spannable spannable;
10072           if (text instanceof Spannable) {
10073               spannable = (Spannable) text;
10074           } else {
10075               spannable = new SpannableString(text);
10076               text = spannable;
10077           }
10078
10079           SuggestionSpan[] spans = spannable.getSpans(0, text.length(), SuggestionSpan.class);
10080           for (int i = 0; i < spans.length; i++) {
10081               spannable.removeSpan(spans[i]);
10082           }
10083       }
10084       return text;
10085    }
10086
10087    void showSuggestions() {
10088        if (mSuggestionsPopupWindow == null) {
10089            mSuggestionsPopupWindow = new SuggestionsPopupWindow();
10090        }
10091        hideControllers();
10092        mSuggestionsPopupWindow.show();
10093    }
10094
10095    boolean areSuggestionsShown() {
10096        return mSuggestionsPopupWindow != null && mSuggestionsPopupWindow.isShowing();
10097    }
10098
10099    /**
10100     * Return whether or not suggestions are enabled on this TextView. The suggestions are generated
10101     * by the IME or by the spell checker as the user types. This is done by adding
10102     * {@link SuggestionSpan}s to the text.
10103     *
10104     * When suggestions are enabled (default), this list of suggestions will be displayed when the
10105     * user asks for them on these parts of the text. This value depends on the inputType of this
10106     * TextView.
10107     *
10108     * The class of the input type must be {@link InputType#TYPE_CLASS_TEXT}.
10109     *
10110     * In addition, the type variation must be one of
10111     * {@link InputType#TYPE_TEXT_VARIATION_NORMAL},
10112     * {@link InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT},
10113     * {@link InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE},
10114     * {@link InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or
10115     * {@link InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}.
10116     *
10117     * And finally, the {@link InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS} flag must <i>not</i> be set.
10118     *
10119     * @return true if the suggestions popup window is enabled, based on the inputType.
10120     */
10121    public boolean isSuggestionsEnabled() {
10122        if ((mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) return false;
10123        if ((mInputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) > 0) return false;
10124
10125        final int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION;
10126        return (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL ||
10127                variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT ||
10128                variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE ||
10129                variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE ||
10130                variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT);
10131    }
10132
10133    /**
10134     * If provided, this ActionMode.Callback will be used to create the ActionMode when text
10135     * selection is initiated in this View.
10136     *
10137     * The standard implementation populates the menu with a subset of Select All, Cut, Copy and
10138     * Paste actions, depending on what this View supports.
10139     *
10140     * A custom implementation can add new entries in the default menu in its
10141     * {@link android.view.ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The
10142     * default actions can also be removed from the menu using {@link Menu#removeItem(int)} and
10143     * passing {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy}
10144     * or {@link android.R.id#paste} ids as parameters.
10145     *
10146     * Returning false from
10147     * {@link android.view.ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will prevent
10148     * the action mode from being started.
10149     *
10150     * Action click events should be handled by the custom implementation of
10151     * {@link android.view.ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}.
10152     *
10153     * Note that text selection mode is not started when a TextView receives focus and the
10154     * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in
10155     * that case, to allow for quick replacement.
10156     */
10157    public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) {
10158        mCustomSelectionActionModeCallback = actionModeCallback;
10159    }
10160
10161    /**
10162     * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null.
10163     *
10164     * @return The current custom selection callback.
10165     */
10166    public ActionMode.Callback getCustomSelectionActionModeCallback() {
10167        return mCustomSelectionActionModeCallback;
10168    }
10169
10170    /**
10171     *
10172     * @return true if the selection mode was actually started.
10173     */
10174    private boolean startSelectionActionMode() {
10175        if (mSelectionActionMode != null) {
10176            // Selection action mode is already started
10177            return false;
10178        }
10179
10180        if (!canSelectText() || !requestFocus()) {
10181            Log.w(LOG_TAG, "TextView does not support text selection. Action mode cancelled.");
10182            return false;
10183        }
10184
10185        if (!hasSelection()) {
10186            // There may already be a selection on device rotation
10187            if (!selectCurrentWord()) {
10188                // No word found under cursor or text selection not permitted.
10189                return false;
10190            }
10191        }
10192
10193        final InputMethodManager imm = InputMethodManager.peekInstance();
10194        boolean extractedTextModeWillBeStartedFullScreen = !(this instanceof ExtractEditText) &&
10195                imm != null && imm.isFullscreenMode();
10196
10197        // Do not start the action mode when extracted text will show up full screen, thus
10198        // immediately hiding the newly created action bar, which would be visually distracting.
10199        if (!extractedTextModeWillBeStartedFullScreen) {
10200            ActionMode.Callback actionModeCallback = new SelectionActionModeCallback();
10201            mSelectionActionMode = startActionMode(actionModeCallback);
10202        }
10203        final boolean selectionStarted = mSelectionActionMode != null ||
10204                extractedTextModeWillBeStartedFullScreen;
10205
10206        if (selectionStarted && !mTextIsSelectable && imm != null && mSoftInputShownOnFocus) {
10207            // Show the IME to be able to replace text, except when selecting non editable text.
10208            imm.showSoftInput(this, 0, null);
10209        }
10210
10211        return selectionStarted;
10212    }
10213
10214    private void stopSelectionActionMode() {
10215        if (mSelectionActionMode != null) {
10216            // This will hide the mSelectionModifierCursorController
10217            mSelectionActionMode.finish();
10218        }
10219    }
10220
10221    /**
10222     * Paste clipboard content between min and max positions.
10223     */
10224    private void paste(int min, int max) {
10225        ClipboardManager clipboard =
10226            (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
10227        ClipData clip = clipboard.getPrimaryClip();
10228        if (clip != null) {
10229            boolean didFirst = false;
10230            for (int i=0; i<clip.getItemCount(); i++) {
10231                CharSequence paste = clip.getItemAt(i).coerceToText(getContext());
10232                if (paste != null) {
10233                    if (!didFirst) {
10234                        long minMax = prepareSpacesAroundPaste(min, max, paste);
10235                        min = extractRangeStartFromLong(minMax);
10236                        max = extractRangeEndFromLong(minMax);
10237                        Selection.setSelection((Spannable) mText, max);
10238                        ((Editable) mText).replace(min, max, paste);
10239                        didFirst = true;
10240                    } else {
10241                        ((Editable) mText).insert(getSelectionEnd(), "\n");
10242                        ((Editable) mText).insert(getSelectionEnd(), paste);
10243                    }
10244                }
10245            }
10246            stopSelectionActionMode();
10247            sLastCutOrCopyTime = 0;
10248        }
10249    }
10250
10251    private void setPrimaryClip(ClipData clip) {
10252        ClipboardManager clipboard = (ClipboardManager) getContext().
10253                getSystemService(Context.CLIPBOARD_SERVICE);
10254        clipboard.setPrimaryClip(clip);
10255        sLastCutOrCopyTime = SystemClock.uptimeMillis();
10256    }
10257
10258    /**
10259     * An ActionMode Callback class that is used to provide actions while in text selection mode.
10260     *
10261     * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending
10262     * on which of these this TextView supports.
10263     */
10264    private class SelectionActionModeCallback implements ActionMode.Callback {
10265
10266        @Override
10267        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
10268            TypedArray styledAttributes = mContext.obtainStyledAttributes(
10269                    com.android.internal.R.styleable.SelectionModeDrawables);
10270
10271            boolean allowText = getContext().getResources().getBoolean(
10272                    com.android.internal.R.bool.config_allowActionMenuItemTextWithIcon);
10273
10274            mode.setTitle(allowText ?
10275                    mContext.getString(com.android.internal.R.string.textSelectionCABTitle) : null);
10276            mode.setSubtitle(null);
10277
10278            int selectAllIconId = 0; // No icon by default
10279            if (!allowText) {
10280                // Provide an icon, text will not be displayed on smaller screens.
10281                selectAllIconId = styledAttributes.getResourceId(
10282                        R.styleable.SelectionModeDrawables_actionModeSelectAllDrawable, 0);
10283            }
10284
10285            menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll).
10286                    setIcon(selectAllIconId).
10287                    setAlphabeticShortcut('a').
10288                    setShowAsAction(
10289                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
10290
10291            if (canCut()) {
10292                menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut).
10293                    setIcon(styledAttributes.getResourceId(
10294                            R.styleable.SelectionModeDrawables_actionModeCutDrawable, 0)).
10295                    setAlphabeticShortcut('x').
10296                    setShowAsAction(
10297                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
10298            }
10299
10300            if (canCopy()) {
10301                menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy).
10302                    setIcon(styledAttributes.getResourceId(
10303                            R.styleable.SelectionModeDrawables_actionModeCopyDrawable, 0)).
10304                    setAlphabeticShortcut('c').
10305                    setShowAsAction(
10306                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
10307            }
10308
10309            if (canPaste()) {
10310                menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste).
10311                        setIcon(styledAttributes.getResourceId(
10312                                R.styleable.SelectionModeDrawables_actionModePasteDrawable, 0)).
10313                        setAlphabeticShortcut('v').
10314                        setShowAsAction(
10315                                MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
10316            }
10317
10318            styledAttributes.recycle();
10319
10320            if (mCustomSelectionActionModeCallback != null) {
10321                if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) {
10322                    // The custom mode can choose to cancel the action mode
10323                    return false;
10324                }
10325            }
10326
10327            if (menu.hasVisibleItems() || mode.getCustomView() != null) {
10328                getSelectionController().show();
10329                return true;
10330            } else {
10331                return false;
10332            }
10333        }
10334
10335        @Override
10336        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
10337            if (mCustomSelectionActionModeCallback != null) {
10338                return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu);
10339            }
10340            return true;
10341        }
10342
10343        @Override
10344        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
10345            if (mCustomSelectionActionModeCallback != null &&
10346                 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) {
10347                return true;
10348            }
10349            return onTextContextMenuItem(item.getItemId());
10350        }
10351
10352        @Override
10353        public void onDestroyActionMode(ActionMode mode) {
10354            if (mCustomSelectionActionModeCallback != null) {
10355                mCustomSelectionActionModeCallback.onDestroyActionMode(mode);
10356            }
10357            Selection.setSelection((Spannable) mText, getSelectionEnd());
10358
10359            if (mSelectionModifierCursorController != null) {
10360                mSelectionModifierCursorController.hide();
10361            }
10362
10363            mSelectionActionMode = null;
10364        }
10365    }
10366
10367    private class ActionPopupWindow extends PinnedPopupWindow implements OnClickListener {
10368        private static final int POPUP_TEXT_LAYOUT =
10369                com.android.internal.R.layout.text_edit_action_popup_text;
10370        private TextView mPasteTextView;
10371        private TextView mReplaceTextView;
10372
10373        @Override
10374        protected void createPopupWindow() {
10375            mPopupWindow = new PopupWindow(TextView.this.mContext, null,
10376                    com.android.internal.R.attr.textSelectHandleWindowStyle);
10377            mPopupWindow.setClippingEnabled(true);
10378        }
10379
10380        @Override
10381        protected void initContentView() {
10382            LinearLayout linearLayout = new LinearLayout(TextView.this.getContext());
10383            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
10384            mContentView = linearLayout;
10385            mContentView.setBackgroundResource(
10386                    com.android.internal.R.drawable.text_edit_paste_window);
10387
10388            LayoutInflater inflater = (LayoutInflater)TextView.this.mContext.
10389                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
10390
10391            LayoutParams wrapContent = new LayoutParams(
10392                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
10393
10394            mPasteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
10395            mPasteTextView.setLayoutParams(wrapContent);
10396            mContentView.addView(mPasteTextView);
10397            mPasteTextView.setText(com.android.internal.R.string.paste);
10398            mPasteTextView.setOnClickListener(this);
10399
10400            mReplaceTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
10401            mReplaceTextView.setLayoutParams(wrapContent);
10402            mContentView.addView(mReplaceTextView);
10403            mReplaceTextView.setText(com.android.internal.R.string.replace);
10404            mReplaceTextView.setOnClickListener(this);
10405        }
10406
10407        @Override
10408        public void show() {
10409            boolean canPaste = canPaste();
10410            boolean canSuggest = isSuggestionsEnabled() && isCursorInsideSuggestionSpan();
10411            mPasteTextView.setVisibility(canPaste ? View.VISIBLE : View.GONE);
10412            mReplaceTextView.setVisibility(canSuggest ? View.VISIBLE : View.GONE);
10413
10414            if (!canPaste && !canSuggest) return;
10415
10416            super.show();
10417        }
10418
10419        @Override
10420        public void onClick(View view) {
10421            if (view == mPasteTextView && canPaste()) {
10422                onTextContextMenuItem(ID_PASTE);
10423                hide();
10424            } else if (view == mReplaceTextView) {
10425                final int middle = (getSelectionStart() + getSelectionEnd()) / 2;
10426                stopSelectionActionMode();
10427                Selection.setSelection((Spannable) mText, middle);
10428                showSuggestions();
10429            }
10430        }
10431
10432        @Override
10433        protected int getTextOffset() {
10434            return (getSelectionStart() + getSelectionEnd()) / 2;
10435        }
10436
10437        @Override
10438        protected int getVerticalLocalPosition(int line) {
10439            return mLayout.getLineTop(line) - mContentView.getMeasuredHeight();
10440        }
10441
10442        @Override
10443        protected int clipVertically(int positionY) {
10444            if (positionY < 0) {
10445                final int offset = getTextOffset();
10446                final int line = mLayout.getLineForOffset(offset);
10447                positionY += mLayout.getLineBottom(line) - mLayout.getLineTop(line);
10448                positionY += mContentView.getMeasuredHeight();
10449
10450                // Assumes insertion and selection handles share the same height
10451                final Drawable handle = mContext.getResources().getDrawable(mTextSelectHandleRes);
10452                positionY += handle.getIntrinsicHeight();
10453            }
10454
10455            return positionY;
10456        }
10457    }
10458
10459    private abstract class HandleView extends View implements TextViewPositionListener {
10460        protected Drawable mDrawable;
10461        protected Drawable mDrawableLtr;
10462        protected Drawable mDrawableRtl;
10463        private final PopupWindow mContainer;
10464        // Position with respect to the parent TextView
10465        private int mPositionX, mPositionY;
10466        private boolean mIsDragging;
10467        // Offset from touch position to mPosition
10468        private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
10469        protected int mHotspotX;
10470        // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
10471        private float mTouchOffsetY;
10472        // Where the touch position should be on the handle to ensure a maximum cursor visibility
10473        private float mIdealVerticalOffset;
10474        // Parent's (TextView) previous position in window
10475        private int mLastParentX, mLastParentY;
10476        // Transient action popup window for Paste and Replace actions
10477        protected ActionPopupWindow mActionPopupWindow;
10478        // Previous text character offset
10479        private int mPreviousOffset = -1;
10480        // Previous text character offset
10481        private boolean mPositionHasChanged = true;
10482        // Used to delay the appearance of the action popup window
10483        private Runnable mActionPopupShower;
10484
10485        public HandleView(Drawable drawableLtr, Drawable drawableRtl) {
10486            super(TextView.this.mContext);
10487            mContainer = new PopupWindow(TextView.this.mContext, null,
10488                    com.android.internal.R.attr.textSelectHandleWindowStyle);
10489            mContainer.setSplitTouchEnabled(true);
10490            mContainer.setClippingEnabled(false);
10491            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
10492            mContainer.setContentView(this);
10493
10494            mDrawableLtr = drawableLtr;
10495            mDrawableRtl = drawableRtl;
10496
10497            updateDrawable();
10498
10499            final int handleHeight = mDrawable.getIntrinsicHeight();
10500            mTouchOffsetY = -0.3f * handleHeight;
10501            mIdealVerticalOffset = 0.7f * handleHeight;
10502        }
10503
10504        protected void updateDrawable() {
10505            final int offset = getCurrentCursorOffset();
10506            final boolean isRtlCharAtOffset = mLayout.isRtlCharAt(offset);
10507            mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
10508            mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
10509        }
10510
10511        protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
10512
10513        // Touch-up filter: number of previous positions remembered
10514        private static final int HISTORY_SIZE = 5;
10515        private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
10516        private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
10517        private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
10518        private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
10519        private int mPreviousOffsetIndex = 0;
10520        private int mNumberPreviousOffsets = 0;
10521
10522        private void startTouchUpFilter(int offset) {
10523            mNumberPreviousOffsets = 0;
10524            addPositionToTouchUpFilter(offset);
10525        }
10526
10527        private void addPositionToTouchUpFilter(int offset) {
10528            mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
10529            mPreviousOffsets[mPreviousOffsetIndex] = offset;
10530            mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
10531            mNumberPreviousOffsets++;
10532        }
10533
10534        private void filterOnTouchUp() {
10535            final long now = SystemClock.uptimeMillis();
10536            int i = 0;
10537            int index = mPreviousOffsetIndex;
10538            final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
10539            while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
10540                i++;
10541                index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
10542            }
10543
10544            if (i > 0 && i < iMax &&
10545                    (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
10546                positionAtCursorOffset(mPreviousOffsets[index], false);
10547            }
10548        }
10549
10550        public boolean offsetHasBeenChanged() {
10551            return mNumberPreviousOffsets > 1;
10552        }
10553
10554        @Override
10555        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10556            setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
10557        }
10558
10559        public void show() {
10560            if (isShowing()) return;
10561
10562            getPositionListener().addSubscriber(this, true /* local position may change */);
10563
10564            // Make sure the offset is always considered new, even when focusing at same position
10565            mPreviousOffset = -1;
10566            positionAtCursorOffset(getCurrentCursorOffset(), false);
10567
10568            hideActionPopupWindow();
10569        }
10570
10571        protected void dismiss() {
10572            mIsDragging = false;
10573            mContainer.dismiss();
10574            onDetached();
10575        }
10576
10577        public void hide() {
10578            dismiss();
10579
10580            TextView.this.getPositionListener().removeSubscriber(this);
10581        }
10582
10583        void showActionPopupWindow(int delay) {
10584            if (mActionPopupWindow == null) {
10585                mActionPopupWindow = new ActionPopupWindow();
10586            }
10587            if (mActionPopupShower == null) {
10588                mActionPopupShower = new Runnable() {
10589                    public void run() {
10590                        mActionPopupWindow.show();
10591                    }
10592                };
10593            } else {
10594                TextView.this.removeCallbacks(mActionPopupShower);
10595            }
10596            TextView.this.postDelayed(mActionPopupShower, delay);
10597        }
10598
10599        protected void hideActionPopupWindow() {
10600            if (mActionPopupShower != null) {
10601                TextView.this.removeCallbacks(mActionPopupShower);
10602            }
10603            if (mActionPopupWindow != null) {
10604                mActionPopupWindow.hide();
10605            }
10606        }
10607
10608        public boolean isShowing() {
10609            return mContainer.isShowing();
10610        }
10611
10612        private boolean isVisible() {
10613            // Always show a dragging handle.
10614            if (mIsDragging) {
10615                return true;
10616            }
10617
10618            if (isInBatchEditMode()) {
10619                return false;
10620            }
10621
10622            return getPositionListener().isVisible(mPositionX + mHotspotX, mPositionY);
10623        }
10624
10625        public abstract int getCurrentCursorOffset();
10626
10627        protected abstract void updateSelection(int offset);
10628
10629        public abstract void updatePosition(float x, float y);
10630
10631        protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
10632            // A HandleView relies on the layout, which may be nulled by external methods
10633            if (mLayout == null) {
10634                // Will update controllers' state, hiding them and stopping selection mode if needed
10635                prepareCursorControllers();
10636                return;
10637            }
10638
10639            if (offset != mPreviousOffset || parentScrolled) {
10640                updateSelection(offset);
10641                addPositionToTouchUpFilter(offset);
10642                final int line = mLayout.getLineForOffset(offset);
10643
10644                mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX);
10645                mPositionY = mLayout.getLineBottom(line);
10646
10647                // Take TextView's padding and scroll into account.
10648                mPositionX += viewportToContentHorizontalOffset();
10649                mPositionY += viewportToContentVerticalOffset();
10650
10651                mPreviousOffset = offset;
10652                mPositionHasChanged = true;
10653            }
10654        }
10655
10656        public void updatePosition(int parentPositionX, int parentPositionY,
10657                boolean parentPositionChanged, boolean parentScrolled) {
10658            positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled);
10659            if (parentPositionChanged || mPositionHasChanged) {
10660                if (mIsDragging) {
10661                    // Update touchToWindow offset in case of parent scrolling while dragging
10662                    if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
10663                        mTouchToWindowOffsetX += parentPositionX - mLastParentX;
10664                        mTouchToWindowOffsetY += parentPositionY - mLastParentY;
10665                        mLastParentX = parentPositionX;
10666                        mLastParentY = parentPositionY;
10667                    }
10668
10669                    onHandleMoved();
10670                }
10671
10672                if (isVisible()) {
10673                    final int positionX = parentPositionX + mPositionX;
10674                    final int positionY = parentPositionY + mPositionY;
10675                    if (isShowing()) {
10676                        mContainer.update(positionX, positionY, -1, -1);
10677                    } else {
10678                        mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY,
10679                                positionX, positionY);
10680                    }
10681                } else {
10682                    if (isShowing()) {
10683                        dismiss();
10684                    }
10685                }
10686
10687                mPositionHasChanged = false;
10688            }
10689        }
10690
10691        @Override
10692        protected void onDraw(Canvas c) {
10693            mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
10694            mDrawable.draw(c);
10695        }
10696
10697        @Override
10698        public boolean onTouchEvent(MotionEvent ev) {
10699            switch (ev.getActionMasked()) {
10700                case MotionEvent.ACTION_DOWN: {
10701                    startTouchUpFilter(getCurrentCursorOffset());
10702                    mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
10703                    mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
10704
10705                    final PositionListener positionListener = getPositionListener();
10706                    mLastParentX = positionListener.getPositionX();
10707                    mLastParentY = positionListener.getPositionY();
10708                    mIsDragging = true;
10709                    break;
10710                }
10711
10712                case MotionEvent.ACTION_MOVE: {
10713                    final float rawX = ev.getRawX();
10714                    final float rawY = ev.getRawY();
10715
10716                    // Vertical hysteresis: vertical down movement tends to snap to ideal offset
10717                    final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
10718                    final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
10719                    float newVerticalOffset;
10720                    if (previousVerticalOffset < mIdealVerticalOffset) {
10721                        newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
10722                        newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
10723                    } else {
10724                        newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
10725                        newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
10726                    }
10727                    mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
10728
10729                    final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX;
10730                    final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
10731
10732                    updatePosition(newPosX, newPosY);
10733                    break;
10734                }
10735
10736                case MotionEvent.ACTION_UP:
10737                    filterOnTouchUp();
10738                    mIsDragging = false;
10739                    break;
10740
10741                case MotionEvent.ACTION_CANCEL:
10742                    mIsDragging = false;
10743                    break;
10744            }
10745            return true;
10746        }
10747
10748        public boolean isDragging() {
10749            return mIsDragging;
10750        }
10751
10752        void onHandleMoved() {
10753            hideActionPopupWindow();
10754        }
10755
10756        public void onDetached() {
10757            hideActionPopupWindow();
10758        }
10759    }
10760
10761    private class InsertionHandleView extends HandleView {
10762        private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
10763        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
10764
10765        // Used to detect taps on the insertion handle, which will affect the ActionPopupWindow
10766        private float mDownPositionX, mDownPositionY;
10767        private Runnable mHider;
10768
10769        public InsertionHandleView(Drawable drawable) {
10770            super(drawable, drawable);
10771        }
10772
10773        @Override
10774        public void show() {
10775            super.show();
10776
10777            final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - sLastCutOrCopyTime;
10778            if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) {
10779                showActionPopupWindow(0);
10780            }
10781
10782            hideAfterDelay();
10783        }
10784
10785        public void showWithActionPopup() {
10786            show();
10787            showActionPopupWindow(0);
10788        }
10789
10790        private void hideAfterDelay() {
10791            removeHiderCallback();
10792            if (mHider == null) {
10793                mHider = new Runnable() {
10794                    public void run() {
10795                        hide();
10796                    }
10797                };
10798            }
10799            TextView.this.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
10800        }
10801
10802        private void removeHiderCallback() {
10803            if (mHider != null) {
10804                TextView.this.removeCallbacks(mHider);
10805            }
10806        }
10807
10808        @Override
10809        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
10810            return drawable.getIntrinsicWidth() / 2;
10811        }
10812
10813        @Override
10814        public boolean onTouchEvent(MotionEvent ev) {
10815            final boolean result = super.onTouchEvent(ev);
10816
10817            switch (ev.getActionMasked()) {
10818                case MotionEvent.ACTION_DOWN:
10819                    mDownPositionX = ev.getRawX();
10820                    mDownPositionY = ev.getRawY();
10821                    break;
10822
10823                case MotionEvent.ACTION_UP:
10824                    if (!offsetHasBeenChanged()) {
10825                        final float deltaX = mDownPositionX - ev.getRawX();
10826                        final float deltaY = mDownPositionY - ev.getRawY();
10827                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
10828                        if (distanceSquared < mSquaredTouchSlopDistance) {
10829                            if (mActionPopupWindow != null && mActionPopupWindow.isShowing()) {
10830                                // Tapping on the handle dismisses the displayed action popup
10831                                mActionPopupWindow.hide();
10832                            } else {
10833                                showWithActionPopup();
10834                            }
10835                        }
10836                    }
10837                    hideAfterDelay();
10838                    break;
10839
10840                case MotionEvent.ACTION_CANCEL:
10841                    hideAfterDelay();
10842                    break;
10843
10844                default:
10845                    break;
10846            }
10847
10848            return result;
10849        }
10850
10851        @Override
10852        public int getCurrentCursorOffset() {
10853            return TextView.this.getSelectionStart();
10854        }
10855
10856        @Override
10857        public void updateSelection(int offset) {
10858            Selection.setSelection((Spannable) mText, offset);
10859        }
10860
10861        @Override
10862        public void updatePosition(float x, float y) {
10863            positionAtCursorOffset(getOffsetForPosition(x, y), false);
10864        }
10865
10866        @Override
10867        void onHandleMoved() {
10868            super.onHandleMoved();
10869            removeHiderCallback();
10870        }
10871
10872        @Override
10873        public void onDetached() {
10874            super.onDetached();
10875            removeHiderCallback();
10876        }
10877    }
10878
10879    private class SelectionStartHandleView extends HandleView {
10880
10881        public SelectionStartHandleView(Drawable drawableLtr, Drawable drawableRtl) {
10882            super(drawableLtr, drawableRtl);
10883        }
10884
10885        @Override
10886        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
10887            if (isRtlRun) {
10888                return drawable.getIntrinsicWidth() / 4;
10889            } else {
10890                return (drawable.getIntrinsicWidth() * 3) / 4;
10891            }
10892        }
10893
10894        @Override
10895        public int getCurrentCursorOffset() {
10896            return TextView.this.getSelectionStart();
10897        }
10898
10899        @Override
10900        public void updateSelection(int offset) {
10901            Selection.setSelection((Spannable) mText, offset, getSelectionEnd());
10902            updateDrawable();
10903        }
10904
10905        @Override
10906        public void updatePosition(float x, float y) {
10907            int offset = getOffsetForPosition(x, y);
10908
10909            // Handles can not cross and selection is at least one character
10910            final int selectionEnd = getSelectionEnd();
10911            if (offset >= selectionEnd) offset = selectionEnd - 1;
10912
10913            positionAtCursorOffset(offset, false);
10914        }
10915
10916        public ActionPopupWindow getActionPopupWindow() {
10917            return mActionPopupWindow;
10918        }
10919    }
10920
10921    private class SelectionEndHandleView extends HandleView {
10922
10923        public SelectionEndHandleView(Drawable drawableLtr, Drawable drawableRtl) {
10924            super(drawableLtr, drawableRtl);
10925        }
10926
10927        @Override
10928        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
10929            if (isRtlRun) {
10930                return (drawable.getIntrinsicWidth() * 3) / 4;
10931            } else {
10932                return drawable.getIntrinsicWidth() / 4;
10933            }
10934        }
10935
10936        @Override
10937        public int getCurrentCursorOffset() {
10938            return TextView.this.getSelectionEnd();
10939        }
10940
10941        @Override
10942        public void updateSelection(int offset) {
10943            Selection.setSelection((Spannable) mText, getSelectionStart(), offset);
10944            updateDrawable();
10945        }
10946
10947        @Override
10948        public void updatePosition(float x, float y) {
10949            int offset = getOffsetForPosition(x, y);
10950
10951            // Handles can not cross and selection is at least one character
10952            final int selectionStart = getSelectionStart();
10953            if (offset <= selectionStart) offset = selectionStart + 1;
10954
10955            positionAtCursorOffset(offset, false);
10956        }
10957
10958        public void setActionPopupWindow(ActionPopupWindow actionPopupWindow) {
10959            mActionPopupWindow = actionPopupWindow;
10960        }
10961    }
10962
10963    /**
10964     * A CursorController instance can be used to control a cursor in the text.
10965     * It is not used outside of {@link TextView}.
10966     * @hide
10967     */
10968    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
10969        /**
10970         * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}.
10971         * See also {@link #hide()}.
10972         */
10973        public void show();
10974
10975        /**
10976         * Hide the cursor controller from screen.
10977         * See also {@link #show()}.
10978         */
10979        public void hide();
10980
10981        /**
10982         * Called when the view is detached from window. Perform house keeping task, such as
10983         * stopping Runnable thread that would otherwise keep a reference on the context, thus
10984         * preventing the activity from being recycled.
10985         */
10986        public void onDetached();
10987    }
10988
10989    private class InsertionPointCursorController implements CursorController {
10990        private InsertionHandleView mHandle;
10991
10992        public void show() {
10993            getHandle().show();
10994        }
10995
10996        public void showWithActionPopup() {
10997            getHandle().showWithActionPopup();
10998        }
10999
11000        public void hide() {
11001            if (mHandle != null) {
11002                mHandle.hide();
11003            }
11004        }
11005
11006        public void onTouchModeChanged(boolean isInTouchMode) {
11007            if (!isInTouchMode) {
11008                hide();
11009            }
11010        }
11011
11012        private InsertionHandleView getHandle() {
11013            if (mSelectHandleCenter == null) {
11014                mSelectHandleCenter = mContext.getResources().getDrawable(
11015                        mTextSelectHandleRes);
11016            }
11017            if (mHandle == null) {
11018                mHandle = new InsertionHandleView(mSelectHandleCenter);
11019            }
11020            return mHandle;
11021        }
11022
11023        @Override
11024        public void onDetached() {
11025            final ViewTreeObserver observer = getViewTreeObserver();
11026            observer.removeOnTouchModeChangeListener(this);
11027
11028            if (mHandle != null) mHandle.onDetached();
11029        }
11030    }
11031
11032    private class SelectionModifierCursorController implements CursorController {
11033        private static final int DELAY_BEFORE_REPLACE_ACTION = 200; // milliseconds
11034        // The cursor controller handles, lazily created when shown.
11035        private SelectionStartHandleView mStartHandle;
11036        private SelectionEndHandleView mEndHandle;
11037        // The offsets of that last touch down event. Remembered to start selection there.
11038        private int mMinTouchOffset, mMaxTouchOffset;
11039
11040        // Double tap detection
11041        private long mPreviousTapUpTime = 0;
11042        private float mPreviousTapPositionX, mPreviousTapPositionY;
11043
11044        SelectionModifierCursorController() {
11045            resetTouchOffsets();
11046        }
11047
11048        public void show() {
11049            if (isInBatchEditMode()) {
11050                return;
11051            }
11052            initDrawables();
11053            initHandles();
11054            hideInsertionPointCursorController();
11055        }
11056
11057        private void initDrawables() {
11058            if (mSelectHandleLeft == null) {
11059                mSelectHandleLeft = mContext.getResources().getDrawable(
11060                        mTextSelectHandleLeftRes);
11061            }
11062            if (mSelectHandleRight == null) {
11063                mSelectHandleRight = mContext.getResources().getDrawable(
11064                        mTextSelectHandleRightRes);
11065            }
11066        }
11067
11068        private void initHandles() {
11069            // Lazy object creation has to be done before updatePosition() is called.
11070            if (mStartHandle == null) {
11071                mStartHandle = new SelectionStartHandleView(mSelectHandleLeft, mSelectHandleRight);
11072            }
11073            if (mEndHandle == null) {
11074                mEndHandle = new SelectionEndHandleView(mSelectHandleRight, mSelectHandleLeft);
11075            }
11076
11077            mStartHandle.show();
11078            mEndHandle.show();
11079
11080            // Make sure both left and right handles share the same ActionPopupWindow (so that
11081            // moving any of the handles hides the action popup).
11082            mStartHandle.showActionPopupWindow(DELAY_BEFORE_REPLACE_ACTION);
11083            mEndHandle.setActionPopupWindow(mStartHandle.getActionPopupWindow());
11084
11085            hideInsertionPointCursorController();
11086        }
11087
11088        public void hide() {
11089            if (mStartHandle != null) mStartHandle.hide();
11090            if (mEndHandle != null) mEndHandle.hide();
11091        }
11092
11093        public void onTouchEvent(MotionEvent event) {
11094            // This is done even when the View does not have focus, so that long presses can start
11095            // selection and tap can move cursor from this tap position.
11096            switch (event.getActionMasked()) {
11097                case MotionEvent.ACTION_DOWN:
11098                    final float x = event.getX();
11099                    final float y = event.getY();
11100
11101                    // Remember finger down position, to be able to start selection from there
11102                    mMinTouchOffset = mMaxTouchOffset = getOffsetForPosition(x, y);
11103
11104                    // Double tap detection
11105                    long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime;
11106                    if (duration <= ViewConfiguration.getDoubleTapTimeout() &&
11107                            isPositionOnText(x, y)) {
11108                        final float deltaX = x - mPreviousTapPositionX;
11109                        final float deltaY = y - mPreviousTapPositionY;
11110                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
11111                        if (distanceSquared < mSquaredTouchSlopDistance) {
11112                            startSelectionActionMode();
11113                            mDiscardNextActionUp = true;
11114                        }
11115                    }
11116
11117                    mPreviousTapPositionX = x;
11118                    mPreviousTapPositionY = y;
11119                    break;
11120
11121                case MotionEvent.ACTION_POINTER_DOWN:
11122                case MotionEvent.ACTION_POINTER_UP:
11123                    // Handle multi-point gestures. Keep min and max offset positions.
11124                    // Only activated for devices that correctly handle multi-touch.
11125                    if (mContext.getPackageManager().hasSystemFeature(
11126                            PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
11127                        updateMinAndMaxOffsets(event);
11128                    }
11129                    break;
11130
11131                case MotionEvent.ACTION_UP:
11132                    mPreviousTapUpTime = SystemClock.uptimeMillis();
11133                    break;
11134            }
11135        }
11136
11137        /**
11138         * @param event
11139         */
11140        private void updateMinAndMaxOffsets(MotionEvent event) {
11141            int pointerCount = event.getPointerCount();
11142            for (int index = 0; index < pointerCount; index++) {
11143                int offset = getOffsetForPosition(event.getX(index), event.getY(index));
11144                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
11145                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
11146            }
11147        }
11148
11149        public int getMinTouchOffset() {
11150            return mMinTouchOffset;
11151        }
11152
11153        public int getMaxTouchOffset() {
11154            return mMaxTouchOffset;
11155        }
11156
11157        public void resetTouchOffsets() {
11158            mMinTouchOffset = mMaxTouchOffset = -1;
11159        }
11160
11161        /**
11162         * @return true iff this controller is currently used to move the selection start.
11163         */
11164        public boolean isSelectionStartDragged() {
11165            return mStartHandle != null && mStartHandle.isDragging();
11166        }
11167
11168        public void onTouchModeChanged(boolean isInTouchMode) {
11169            if (!isInTouchMode) {
11170                hide();
11171            }
11172        }
11173
11174        @Override
11175        public void onDetached() {
11176            final ViewTreeObserver observer = getViewTreeObserver();
11177            observer.removeOnTouchModeChangeListener(this);
11178
11179            if (mStartHandle != null) mStartHandle.onDetached();
11180            if (mEndHandle != null) mEndHandle.onDetached();
11181        }
11182    }
11183
11184    private void hideInsertionPointCursorController() {
11185        // No need to create the controller to hide it.
11186        if (mInsertionPointCursorController != null) {
11187            mInsertionPointCursorController.hide();
11188        }
11189    }
11190
11191    /**
11192     * Hides the insertion controller and stops text selection mode, hiding the selection controller
11193     */
11194    private void hideControllers() {
11195        hideCursorControllers();
11196        hideSpanControllers();
11197    }
11198
11199    private void hideSpanControllers() {
11200        if (mChangeWatcher != null) {
11201            mChangeWatcher.hideControllers();
11202        }
11203    }
11204
11205    private void hideCursorControllers() {
11206        if (mSuggestionsPopupWindow != null && !mSuggestionsPopupWindow.isShowingUp()) {
11207            // Should be done before hide insertion point controller since it triggers a show of it
11208            mSuggestionsPopupWindow.hide();
11209        }
11210        hideInsertionPointCursorController();
11211        stopSelectionActionMode();
11212    }
11213
11214    /**
11215     * Get the character offset closest to the specified absolute position. A typical use case is to
11216     * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method.
11217     *
11218     * @param x The horizontal absolute position of a point on screen
11219     * @param y The vertical absolute position of a point on screen
11220     * @return the character offset for the character whose position is closest to the specified
11221     *  position. Returns -1 if there is no layout.
11222     */
11223    public int getOffsetForPosition(float x, float y) {
11224        if (getLayout() == null) return -1;
11225        final int line = getLineAtCoordinate(y);
11226        final int offset = getOffsetAtCoordinate(line, x);
11227        return offset;
11228    }
11229
11230    private float convertToLocalHorizontalCoordinate(float x) {
11231        x -= getTotalPaddingLeft();
11232        // Clamp the position to inside of the view.
11233        x = Math.max(0.0f, x);
11234        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
11235        x += getScrollX();
11236        return x;
11237    }
11238
11239    private int getLineAtCoordinate(float y) {
11240        y -= getTotalPaddingTop();
11241        // Clamp the position to inside of the view.
11242        y = Math.max(0.0f, y);
11243        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
11244        y += getScrollY();
11245        return getLayout().getLineForVertical((int) y);
11246    }
11247
11248    private int getOffsetAtCoordinate(int line, float x) {
11249        x = convertToLocalHorizontalCoordinate(x);
11250        return getLayout().getOffsetForHorizontal(line, x);
11251    }
11252
11253    /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed
11254     * in the view. Returns false when the position is in the empty space of left/right of text.
11255     */
11256    private boolean isPositionOnText(float x, float y) {
11257        if (getLayout() == null) return false;
11258
11259        final int line = getLineAtCoordinate(y);
11260        x = convertToLocalHorizontalCoordinate(x);
11261
11262        if (x < getLayout().getLineLeft(line)) return false;
11263        if (x > getLayout().getLineRight(line)) return false;
11264        return true;
11265    }
11266
11267    @Override
11268    public boolean onDragEvent(DragEvent event) {
11269        switch (event.getAction()) {
11270            case DragEvent.ACTION_DRAG_STARTED:
11271                return hasInsertionController();
11272
11273            case DragEvent.ACTION_DRAG_ENTERED:
11274                TextView.this.requestFocus();
11275                return true;
11276
11277            case DragEvent.ACTION_DRAG_LOCATION:
11278                final int offset = getOffsetForPosition(event.getX(), event.getY());
11279                Selection.setSelection((Spannable)mText, offset);
11280                return true;
11281
11282            case DragEvent.ACTION_DROP:
11283                onDrop(event);
11284                return true;
11285
11286            case DragEvent.ACTION_DRAG_ENDED:
11287            case DragEvent.ACTION_DRAG_EXITED:
11288            default:
11289                return true;
11290        }
11291    }
11292
11293    private void onDrop(DragEvent event) {
11294        StringBuilder content = new StringBuilder("");
11295        ClipData clipData = event.getClipData();
11296        final int itemCount = clipData.getItemCount();
11297        for (int i=0; i < itemCount; i++) {
11298            Item item = clipData.getItemAt(i);
11299            content.append(item.coerceToText(TextView.this.mContext));
11300        }
11301
11302        final int offset = getOffsetForPosition(event.getX(), event.getY());
11303
11304        Object localState = event.getLocalState();
11305        DragLocalState dragLocalState = null;
11306        if (localState instanceof DragLocalState) {
11307            dragLocalState = (DragLocalState) localState;
11308        }
11309        boolean dragDropIntoItself = dragLocalState != null &&
11310                dragLocalState.sourceTextView == this;
11311
11312        if (dragDropIntoItself) {
11313            if (offset >= dragLocalState.start && offset < dragLocalState.end) {
11314                // A drop inside the original selection discards the drop.
11315                return;
11316            }
11317        }
11318
11319        final int originalLength = mText.length();
11320        long minMax = prepareSpacesAroundPaste(offset, offset, content);
11321        int min = extractRangeStartFromLong(minMax);
11322        int max = extractRangeEndFromLong(minMax);
11323
11324        Selection.setSelection((Spannable) mText, max);
11325        ((Editable) mText).replace(min, max, content);
11326
11327        if (dragDropIntoItself) {
11328            int dragSourceStart = dragLocalState.start;
11329            int dragSourceEnd = dragLocalState.end;
11330            if (max <= dragSourceStart) {
11331                // Inserting text before selection has shifted positions
11332                final int shift = mText.length() - originalLength;
11333                dragSourceStart += shift;
11334                dragSourceEnd += shift;
11335            }
11336
11337            // Delete original selection
11338            ((Editable) mText).delete(dragSourceStart, dragSourceEnd);
11339
11340            // Make sure we do not leave two adjacent spaces.
11341            if ((dragSourceStart == 0 ||
11342                    Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) &&
11343                    (dragSourceStart == mText.length() ||
11344                    Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) {
11345                final int pos = dragSourceStart == mText.length() ?
11346                        dragSourceStart - 1 : dragSourceStart;
11347                ((Editable) mText).delete(pos, pos + 1);
11348            }
11349        }
11350    }
11351
11352    /**
11353     * @return True if this view supports insertion handles.
11354     */
11355    boolean hasInsertionController() {
11356        return mInsertionControllerEnabled;
11357    }
11358
11359    /**
11360     * @return True if this view supports selection handles.
11361     */
11362    boolean hasSelectionController() {
11363        return mSelectionControllerEnabled;
11364    }
11365
11366    InsertionPointCursorController getInsertionController() {
11367        if (!mInsertionControllerEnabled) {
11368            return null;
11369        }
11370
11371        if (mInsertionPointCursorController == null) {
11372            mInsertionPointCursorController = new InsertionPointCursorController();
11373
11374            final ViewTreeObserver observer = getViewTreeObserver();
11375            observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
11376        }
11377
11378        return mInsertionPointCursorController;
11379    }
11380
11381    SelectionModifierCursorController getSelectionController() {
11382        if (!mSelectionControllerEnabled) {
11383            return null;
11384        }
11385
11386        if (mSelectionModifierCursorController == null) {
11387            mSelectionModifierCursorController = new SelectionModifierCursorController();
11388
11389            final ViewTreeObserver observer = getViewTreeObserver();
11390            observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
11391        }
11392
11393        return mSelectionModifierCursorController;
11394    }
11395
11396    boolean isInBatchEditMode() {
11397        final InputMethodState ims = mInputMethodState;
11398        if (ims != null) {
11399            return ims.mBatchEditNesting > 0;
11400        }
11401        return mInBatchEditControllers;
11402    }
11403
11404    @Override
11405    protected void resolveTextDirection() {
11406        if (hasPasswordTransformationMethod()) {
11407            mTextDir = TextDirectionHeuristics.LOCALE;
11408            return;
11409        }
11410
11411        // Always need to resolve layout direction first
11412        final boolean defaultIsRtl = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
11413
11414        // Then resolve text direction on the parent
11415        super.resolveTextDirection();
11416
11417        // Now, we can select the heuristic
11418        int textDir = getResolvedTextDirection();
11419        switch (textDir) {
11420            default:
11421            case TEXT_DIRECTION_FIRST_STRONG:
11422                mTextDir = (defaultIsRtl ? TextDirectionHeuristics.FIRSTSTRONG_RTL :
11423                        TextDirectionHeuristics.FIRSTSTRONG_LTR);
11424                break;
11425            case TEXT_DIRECTION_ANY_RTL:
11426                mTextDir = TextDirectionHeuristics.ANYRTL_LTR;
11427                break;
11428            case TEXT_DIRECTION_LTR:
11429                mTextDir = TextDirectionHeuristics.LTR;
11430                break;
11431            case TEXT_DIRECTION_RTL:
11432                mTextDir = TextDirectionHeuristics.RTL;
11433                break;
11434        }
11435    }
11436
11437    /**
11438     * Subclasses will need to override this method to implement their own way of resolving
11439     * drawables depending on the layout direction.
11440     *
11441     * A call to the super method will be required from the subclasses implementation.
11442     *
11443     */
11444    protected void resolveDrawables() {
11445        // No need to resolve twice
11446        if (mResolvedDrawables) {
11447            return;
11448        }
11449        // No drawable to resolve
11450        if (mDrawables == null) {
11451            return;
11452        }
11453        // No relative drawable to resolve
11454        if (mDrawables.mDrawableStart == null && mDrawables.mDrawableEnd == null) {
11455            mResolvedDrawables = true;
11456            return;
11457        }
11458
11459        Drawables dr = mDrawables;
11460        switch(getResolvedLayoutDirection()) {
11461            case LAYOUT_DIRECTION_RTL:
11462                if (dr.mDrawableStart != null) {
11463                    dr.mDrawableRight = dr.mDrawableStart;
11464
11465                    dr.mDrawableSizeRight = dr.mDrawableSizeStart;
11466                    dr.mDrawableHeightRight = dr.mDrawableHeightStart;
11467                }
11468                if (dr.mDrawableEnd != null) {
11469                    dr.mDrawableLeft = dr.mDrawableEnd;
11470
11471                    dr.mDrawableSizeLeft = dr.mDrawableSizeEnd;
11472                    dr.mDrawableHeightLeft = dr.mDrawableHeightEnd;
11473                }
11474                break;
11475
11476            case LAYOUT_DIRECTION_LTR:
11477            default:
11478                if (dr.mDrawableStart != null) {
11479                    dr.mDrawableLeft = dr.mDrawableStart;
11480
11481                    dr.mDrawableSizeLeft = dr.mDrawableSizeStart;
11482                    dr.mDrawableHeightLeft = dr.mDrawableHeightStart;
11483                }
11484                if (dr.mDrawableEnd != null) {
11485                    dr.mDrawableRight = dr.mDrawableEnd;
11486
11487                    dr.mDrawableSizeRight = dr.mDrawableSizeEnd;
11488                    dr.mDrawableHeightRight = dr.mDrawableHeightEnd;
11489                }
11490                break;
11491        }
11492        mResolvedDrawables = true;
11493    }
11494
11495    protected void resetResolvedDrawables() {
11496        mResolvedDrawables = false;
11497    }
11498
11499    /**
11500     * @hide
11501     */
11502    protected void viewClicked(InputMethodManager imm) {
11503        if (imm != null) {
11504            imm.viewClicked(this);
11505        }
11506    }
11507
11508    @ViewDebug.ExportedProperty(category = "text")
11509    private CharSequence            mText;
11510    private CharSequence            mTransformed;
11511    private BufferType              mBufferType = BufferType.NORMAL;
11512
11513    private int                     mInputType = EditorInfo.TYPE_NULL;
11514    private CharSequence            mHint;
11515    private Layout                  mHintLayout;
11516
11517    private KeyListener             mInput;
11518
11519    private MovementMethod          mMovement;
11520    private TransformationMethod    mTransformation;
11521    private boolean                 mAllowTransformationLengthChange;
11522    private ChangeWatcher           mChangeWatcher;
11523
11524    private ArrayList<TextWatcher>  mListeners = null;
11525
11526    // display attributes
11527    private final TextPaint         mTextPaint;
11528    private boolean                 mUserSetTextScaleX;
11529    private final Paint             mHighlightPaint;
11530    private int                     mHighlightColor = 0x6633B5E5;
11531    /**
11532     * This is temporarily visible to fix bug 3085564 in webView. Do not rely on
11533     * this field being protected. Will be restored as private when lineHeight
11534     * feature request 3215097 is implemented
11535     * @hide
11536     */
11537    protected Layout                mLayout;
11538
11539    private long                    mShowCursor;
11540    private Blink                   mBlink;
11541    private boolean                 mCursorVisible = true;
11542
11543    // Cursor Controllers.
11544    private InsertionPointCursorController mInsertionPointCursorController;
11545    private SelectionModifierCursorController mSelectionModifierCursorController;
11546    private ActionMode              mSelectionActionMode;
11547    private boolean                 mInsertionControllerEnabled;
11548    private boolean                 mSelectionControllerEnabled;
11549    private boolean                 mInBatchEditControllers;
11550
11551    // These are needed to desambiguate a long click. If the long click comes from ones of these, we
11552    // select from the current cursor position. Otherwise, select from long pressed position.
11553    private boolean                 mDPadCenterIsDown = false;
11554    private boolean                 mEnterKeyIsDown = false;
11555    private boolean                 mContextMenuTriggeredByKey = false;
11556
11557    private boolean                 mSelectAllOnFocus = false;
11558
11559    private int                     mGravity = Gravity.TOP | Gravity.START;
11560    private boolean                 mHorizontallyScrolling;
11561
11562    private int                     mAutoLinkMask;
11563    private boolean                 mLinksClickable = true;
11564
11565    private float                   mSpacingMult = 1.0f;
11566    private float                   mSpacingAdd = 0.0f;
11567    private boolean                 mTextIsSelectable = false;
11568
11569    private static final int        LINES = 1;
11570    private static final int        EMS = LINES;
11571    private static final int        PIXELS = 2;
11572
11573    private int                     mMaximum = Integer.MAX_VALUE;
11574    private int                     mMaxMode = LINES;
11575    private int                     mMinimum = 0;
11576    private int                     mMinMode = LINES;
11577
11578    private int                     mOldMaximum = mMaximum;
11579    private int                     mOldMaxMode = mMaxMode;
11580
11581    private int                     mMaxWidth = Integer.MAX_VALUE;
11582    private int                     mMaxWidthMode = PIXELS;
11583    private int                     mMinWidth = 0;
11584    private int                     mMinWidthMode = PIXELS;
11585
11586    private boolean                 mSingleLine;
11587    private int                     mDesiredHeightAtMeasure = -1;
11588    private boolean                 mIncludePad = true;
11589
11590    // tmp primitives, so we don't alloc them on each draw
11591    private Path                    mHighlightPath;
11592    private boolean                 mHighlightPathBogus = true;
11593    private static final RectF      sTempRect = new RectF();
11594
11595    // XXX should be much larger
11596    private static final int        VERY_WIDE = 1024*1024;
11597
11598    private static final int        BLINK = 500;
11599
11600    private static final int ANIMATED_SCROLL_GAP = 250;
11601    private long mLastScroll;
11602    private Scroller mScroller = null;
11603
11604    private BoringLayout.Metrics mBoring;
11605    private BoringLayout.Metrics mHintBoring;
11606
11607    private BoringLayout mSavedLayout, mSavedHintLayout;
11608
11609    private TextDirectionHeuristic mTextDir = null;
11610
11611    private static final InputFilter[] NO_FILTERS = new InputFilter[0];
11612    private InputFilter[] mFilters = NO_FILTERS;
11613    private static final Spanned EMPTY_SPANNED = new SpannedString("");
11614    private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
11615    // System wide time for last cut or copy action.
11616    private static long sLastCutOrCopyTime;
11617    // Used to highlight a word when it is corrected by the IME
11618    private CorrectionHighlighter mCorrectionHighlighter;
11619    // New state used to change background based on whether this TextView is multiline.
11620    private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline };
11621}
11622