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