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