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