TextView.java revision 6dd005b48138708762bfade0081d031a2a4a3822
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 bResolvedDrawables = 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    @Override
5066    public boolean onKeyDown(int keyCode, KeyEvent event) {
5067        int which = doKeyDown(keyCode, event, null);
5068        if (which == 0) {
5069            // Go through default dispatching.
5070            return super.onKeyDown(keyCode, event);
5071        }
5072
5073        return true;
5074    }
5075
5076    @Override
5077    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
5078        KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN);
5079
5080        int which = doKeyDown(keyCode, down, event);
5081        if (which == 0) {
5082            // Go through default dispatching.
5083            return super.onKeyMultiple(keyCode, repeatCount, event);
5084        }
5085        if (which == -1) {
5086            // Consumed the whole thing.
5087            return true;
5088        }
5089
5090        repeatCount--;
5091
5092        // We are going to dispatch the remaining events to either the input
5093        // or movement method.  To do this, we will just send a repeated stream
5094        // of down and up events until we have done the complete repeatCount.
5095        // It would be nice if those interfaces had an onKeyMultiple() method,
5096        // but adding that is a more complicated change.
5097        KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP);
5098        if (which == 1) {
5099            mInput.onKeyUp(this, (Editable)mText, keyCode, up);
5100            while (--repeatCount > 0) {
5101                mInput.onKeyDown(this, (Editable)mText, keyCode, down);
5102                mInput.onKeyUp(this, (Editable)mText, keyCode, up);
5103            }
5104            hideErrorIfUnchanged();
5105
5106        } else if (which == 2) {
5107            mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
5108            while (--repeatCount > 0) {
5109                mMovement.onKeyDown(this, (Spannable)mText, keyCode, down);
5110                mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
5111            }
5112        }
5113
5114        return true;
5115    }
5116
5117    /**
5118     * Returns true if pressing ENTER in this field advances focus instead
5119     * of inserting the character.  This is true mostly in single-line fields,
5120     * but also in mail addresses and subjects which will display on multiple
5121     * lines but where it doesn't make sense to insert newlines.
5122     */
5123    private boolean shouldAdvanceFocusOnEnter() {
5124        if (mInput == null) {
5125            return false;
5126        }
5127
5128        if (mSingleLine) {
5129            return true;
5130        }
5131
5132        if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
5133            int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION;
5134            if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
5135                    || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) {
5136                return true;
5137            }
5138        }
5139
5140        return false;
5141    }
5142
5143    /**
5144     * Returns true if pressing TAB in this field advances focus instead
5145     * of inserting the character.  Insert tabs only in multi-line editors.
5146     */
5147    private boolean shouldAdvanceFocusOnTab() {
5148        if (mInput != null && !mSingleLine) {
5149            if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
5150                int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION;
5151                if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE
5152                        || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) {
5153                    return false;
5154                }
5155            }
5156        }
5157        return true;
5158    }
5159
5160    private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) {
5161        if (!isEnabled()) {
5162            return 0;
5163        }
5164
5165        switch (keyCode) {
5166            case KeyEvent.KEYCODE_ENTER:
5167                mEnterKeyIsDown = true;
5168                if (event.hasNoModifiers()) {
5169                    // When mInputContentType is set, we know that we are
5170                    // running in a "modern" cupcake environment, so don't need
5171                    // to worry about the application trying to capture
5172                    // enter key events.
5173                    if (mInputContentType != null) {
5174                        // If there is an action listener, given them a
5175                        // chance to consume the event.
5176                        if (mInputContentType.onEditorActionListener != null &&
5177                                mInputContentType.onEditorActionListener.onEditorAction(
5178                                this, EditorInfo.IME_NULL, event)) {
5179                            mInputContentType.enterDown = true;
5180                            // We are consuming the enter key for them.
5181                            return -1;
5182                        }
5183                    }
5184
5185                    // If our editor should move focus when enter is pressed, or
5186                    // this is a generated event from an IME action button, then
5187                    // don't let it be inserted into the text.
5188                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
5189                            || shouldAdvanceFocusOnEnter()) {
5190                        if (mOnClickListener != null) {
5191                            return 0;
5192                        }
5193                        return -1;
5194                    }
5195                }
5196                break;
5197
5198            case KeyEvent.KEYCODE_DPAD_CENTER:
5199                mDPadCenterIsDown = true;
5200                if (event.hasNoModifiers()) {
5201                    if (shouldAdvanceFocusOnEnter()) {
5202                        return 0;
5203                    }
5204                }
5205                break;
5206
5207            case KeyEvent.KEYCODE_TAB:
5208                if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
5209                    if (shouldAdvanceFocusOnTab()) {
5210                        return 0;
5211                    }
5212                }
5213                break;
5214
5215                // Has to be done on key down (and not on key up) to correctly be intercepted.
5216            case KeyEvent.KEYCODE_BACK:
5217                if (mSelectionActionMode != null) {
5218                    stopSelectionActionMode();
5219                    return -1;
5220                }
5221                break;
5222        }
5223
5224        if (mInput != null) {
5225            resetErrorChangedFlag();
5226
5227            boolean doDown = true;
5228            if (otherEvent != null) {
5229                try {
5230                    beginBatchEdit();
5231                    final boolean handled = mInput.onKeyOther(this, (Editable) mText, otherEvent);
5232                    hideErrorIfUnchanged();
5233                    doDown = false;
5234                    if (handled) {
5235                        return -1;
5236                    }
5237                } catch (AbstractMethodError e) {
5238                    // onKeyOther was added after 1.0, so if it isn't
5239                    // implemented we need to try to dispatch as a regular down.
5240                } finally {
5241                    endBatchEdit();
5242                }
5243            }
5244
5245            if (doDown) {
5246                beginBatchEdit();
5247                final boolean handled = mInput.onKeyDown(this, (Editable) mText, keyCode, event);
5248                endBatchEdit();
5249                hideErrorIfUnchanged();
5250                if (handled) return 1;
5251            }
5252        }
5253
5254        // bug 650865: sometimes we get a key event before a layout.
5255        // don't try to move around if we don't know the layout.
5256
5257        if (mMovement != null && mLayout != null) {
5258            boolean doDown = true;
5259            if (otherEvent != null) {
5260                try {
5261                    boolean handled = mMovement.onKeyOther(this, (Spannable) mText,
5262                            otherEvent);
5263                    doDown = false;
5264                    if (handled) {
5265                        return -1;
5266                    }
5267                } catch (AbstractMethodError e) {
5268                    // onKeyOther was added after 1.0, so if it isn't
5269                    // implemented we need to try to dispatch as a regular down.
5270                }
5271            }
5272            if (doDown) {
5273                if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event))
5274                    return 2;
5275            }
5276        }
5277
5278        return 0;
5279    }
5280
5281    /**
5282     * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)}
5283     * can be recorded.
5284     * @hide
5285     */
5286    public void resetErrorChangedFlag() {
5287        /*
5288         * Keep track of what the error was before doing the input
5289         * so that if an input filter changed the error, we leave
5290         * that error showing.  Otherwise, we take down whatever
5291         * error was showing when the user types something.
5292         */
5293        mErrorWasChanged = false;
5294    }
5295
5296    /**
5297     * @hide
5298     */
5299    public void hideErrorIfUnchanged() {
5300        if (mError != null && !mErrorWasChanged) {
5301            setError(null, null);
5302        }
5303    }
5304
5305    @Override
5306    public boolean onKeyUp(int keyCode, KeyEvent event) {
5307        if (!isEnabled()) {
5308            return super.onKeyUp(keyCode, event);
5309        }
5310
5311        switch (keyCode) {
5312            case KeyEvent.KEYCODE_DPAD_CENTER:
5313                mDPadCenterIsDown = false;
5314                if (event.hasNoModifiers()) {
5315                    /*
5316                     * If there is a click listener, just call through to
5317                     * super, which will invoke it.
5318                     *
5319                     * If there isn't a click listener, try to show the soft
5320                     * input method.  (It will also
5321                     * call performClick(), but that won't do anything in
5322                     * this case.)
5323                     */
5324                    if (mOnClickListener == null) {
5325                        if (mMovement != null && mText instanceof Editable
5326                                && mLayout != null && onCheckIsTextEditor()) {
5327                            InputMethodManager imm = InputMethodManager.peekInstance();
5328                            if (imm != null) {
5329                                imm.viewClicked(this);
5330                                imm.showSoftInput(this, 0);
5331                            }
5332                        }
5333                    }
5334                }
5335                return super.onKeyUp(keyCode, event);
5336
5337            case KeyEvent.KEYCODE_ENTER:
5338                mEnterKeyIsDown = false;
5339                if (event.hasNoModifiers()) {
5340                    if (mInputContentType != null
5341                            && mInputContentType.onEditorActionListener != null
5342                            && mInputContentType.enterDown) {
5343                        mInputContentType.enterDown = false;
5344                        if (mInputContentType.onEditorActionListener.onEditorAction(
5345                                this, EditorInfo.IME_NULL, event)) {
5346                            return true;
5347                        }
5348                    }
5349
5350                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
5351                            || shouldAdvanceFocusOnEnter()) {
5352                        /*
5353                         * If there is a click listener, just call through to
5354                         * super, which will invoke it.
5355                         *
5356                         * If there isn't a click listener, try to advance focus,
5357                         * but still call through to super, which will reset the
5358                         * pressed state and longpress state.  (It will also
5359                         * call performClick(), but that won't do anything in
5360                         * this case.)
5361                         */
5362                        if (mOnClickListener == null) {
5363                            View v = focusSearch(FOCUS_DOWN);
5364
5365                            if (v != null) {
5366                                if (!v.requestFocus(FOCUS_DOWN)) {
5367                                    throw new IllegalStateException(
5368                                            "focus search returned a view " +
5369                                            "that wasn't able to take focus!");
5370                                }
5371
5372                                /*
5373                                 * Return true because we handled the key; super
5374                                 * will return false because there was no click
5375                                 * listener.
5376                                 */
5377                                super.onKeyUp(keyCode, event);
5378                                return true;
5379                            } else if ((event.getFlags()
5380                                    & KeyEvent.FLAG_EDITOR_ACTION) != 0) {
5381                                // No target for next focus, but make sure the IME
5382                                // if this came from it.
5383                                InputMethodManager imm = InputMethodManager.peekInstance();
5384                                if (imm != null && imm.isActive(this)) {
5385                                    imm.hideSoftInputFromWindow(getWindowToken(), 0);
5386                                }
5387                            }
5388                        }
5389                    }
5390                    return super.onKeyUp(keyCode, event);
5391                }
5392                break;
5393        }
5394
5395        if (mInput != null)
5396            if (mInput.onKeyUp(this, (Editable) mText, keyCode, event))
5397                return true;
5398
5399        if (mMovement != null && mLayout != null)
5400            if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event))
5401                return true;
5402
5403        return super.onKeyUp(keyCode, event);
5404    }
5405
5406    @Override public boolean onCheckIsTextEditor() {
5407        return mInputType != EditorInfo.TYPE_NULL;
5408    }
5409
5410    @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
5411        if (onCheckIsTextEditor() && isEnabled()) {
5412            if (mInputMethodState == null) {
5413                mInputMethodState = new InputMethodState();
5414            }
5415            outAttrs.inputType = mInputType;
5416            if (mInputContentType != null) {
5417                outAttrs.imeOptions = mInputContentType.imeOptions;
5418                outAttrs.privateImeOptions = mInputContentType.privateImeOptions;
5419                outAttrs.actionLabel = mInputContentType.imeActionLabel;
5420                outAttrs.actionId = mInputContentType.imeActionId;
5421                outAttrs.extras = mInputContentType.extras;
5422            } else {
5423                outAttrs.imeOptions = EditorInfo.IME_NULL;
5424            }
5425            if (focusSearch(FOCUS_DOWN) != null) {
5426                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT;
5427            }
5428            if (focusSearch(FOCUS_UP) != null) {
5429                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS;
5430            }
5431            if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION)
5432                    == EditorInfo.IME_ACTION_UNSPECIFIED) {
5433                if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) {
5434                    // An action has not been set, but the enter key will move to
5435                    // the next focus, so set the action to that.
5436                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT;
5437                } else {
5438                    // An action has not been set, and there is no focus to move
5439                    // to, so let's just supply a "done" action.
5440                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
5441                }
5442                if (!shouldAdvanceFocusOnEnter()) {
5443                    outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
5444                }
5445            }
5446            if (isMultilineInputType(outAttrs.inputType)) {
5447                // Multi-line text editors should always show an enter key.
5448                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
5449            }
5450            outAttrs.hintText = mHint;
5451            if (mText instanceof Editable) {
5452                InputConnection ic = new EditableInputConnection(this);
5453                outAttrs.initialSelStart = getSelectionStart();
5454                outAttrs.initialSelEnd = getSelectionEnd();
5455                outAttrs.initialCapsMode = ic.getCursorCapsMode(mInputType);
5456                return ic;
5457            }
5458        }
5459        return null;
5460    }
5461
5462    /**
5463     * If this TextView contains editable content, extract a portion of it
5464     * based on the information in <var>request</var> in to <var>outText</var>.
5465     * @return Returns true if the text was successfully extracted, else false.
5466     */
5467    public boolean extractText(ExtractedTextRequest request,
5468            ExtractedText outText) {
5469        return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN,
5470                EXTRACT_UNKNOWN, outText);
5471    }
5472
5473    static final int EXTRACT_NOTHING = -2;
5474    static final int EXTRACT_UNKNOWN = -1;
5475
5476    boolean extractTextInternal(ExtractedTextRequest request,
5477            int partialStartOffset, int partialEndOffset, int delta,
5478            ExtractedText outText) {
5479        final CharSequence content = mText;
5480        if (content != null) {
5481            if (partialStartOffset != EXTRACT_NOTHING) {
5482                final int N = content.length();
5483                if (partialStartOffset < 0) {
5484                    outText.partialStartOffset = outText.partialEndOffset = -1;
5485                    partialStartOffset = 0;
5486                    partialEndOffset = N;
5487                } else {
5488                    // Now use the delta to determine the actual amount of text
5489                    // we need.
5490                    partialEndOffset += delta;
5491                    // Adjust offsets to ensure we contain full spans.
5492                    if (content instanceof Spanned) {
5493                        Spanned spanned = (Spanned)content;
5494                        Object[] spans = spanned.getSpans(partialStartOffset,
5495                                partialEndOffset, ParcelableSpan.class);
5496                        int i = spans.length;
5497                        while (i > 0) {
5498                            i--;
5499                            int j = spanned.getSpanStart(spans[i]);
5500                            if (j < partialStartOffset) partialStartOffset = j;
5501                            j = spanned.getSpanEnd(spans[i]);
5502                            if (j > partialEndOffset) partialEndOffset = j;
5503                        }
5504                    }
5505                    outText.partialStartOffset = partialStartOffset;
5506                    outText.partialEndOffset = partialEndOffset - delta;
5507
5508                    if (partialStartOffset > N) {
5509                        partialStartOffset = N;
5510                    } else if (partialStartOffset < 0) {
5511                        partialStartOffset = 0;
5512                    }
5513                    if (partialEndOffset > N) {
5514                        partialEndOffset = N;
5515                    } else if (partialEndOffset < 0) {
5516                        partialEndOffset = 0;
5517                    }
5518                }
5519                if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) {
5520                    outText.text = content.subSequence(partialStartOffset,
5521                            partialEndOffset);
5522                } else {
5523                    outText.text = TextUtils.substring(content, partialStartOffset,
5524                            partialEndOffset);
5525                }
5526            } else {
5527                outText.partialStartOffset = 0;
5528                outText.partialEndOffset = 0;
5529                outText.text = "";
5530            }
5531            outText.flags = 0;
5532            if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) {
5533                outText.flags |= ExtractedText.FLAG_SELECTING;
5534            }
5535            if (mSingleLine) {
5536                outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
5537            }
5538            outText.startOffset = 0;
5539            outText.selectionStart = getSelectionStart();
5540            outText.selectionEnd = getSelectionEnd();
5541            return true;
5542        }
5543        return false;
5544    }
5545
5546    boolean reportExtractedText() {
5547        final InputMethodState ims = mInputMethodState;
5548        if (ims != null) {
5549            final boolean contentChanged = ims.mContentChanged;
5550            if (contentChanged || ims.mSelectionModeChanged) {
5551                ims.mContentChanged = false;
5552                ims.mSelectionModeChanged = false;
5553                final ExtractedTextRequest req = mInputMethodState.mExtracting;
5554                if (req != null) {
5555                    InputMethodManager imm = InputMethodManager.peekInstance();
5556                    if (imm != null) {
5557                        if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start="
5558                                + ims.mChangedStart + " end=" + ims.mChangedEnd
5559                                + " delta=" + ims.mChangedDelta);
5560                        if (ims.mChangedStart < 0 && !contentChanged) {
5561                            ims.mChangedStart = EXTRACT_NOTHING;
5562                        }
5563                        if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd,
5564                                ims.mChangedDelta, ims.mTmpExtracted)) {
5565                            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start="
5566                                    + ims.mTmpExtracted.partialStartOffset
5567                                    + " end=" + ims.mTmpExtracted.partialEndOffset
5568                                    + ": " + ims.mTmpExtracted.text);
5569                            imm.updateExtractedText(this, req.token,
5570                                    mInputMethodState.mTmpExtracted);
5571                            ims.mChangedStart = EXTRACT_UNKNOWN;
5572                            ims.mChangedEnd = EXTRACT_UNKNOWN;
5573                            ims.mChangedDelta = 0;
5574                            ims.mContentChanged = false;
5575                            return true;
5576                        }
5577                    }
5578                }
5579            }
5580        }
5581        return false;
5582    }
5583
5584    /**
5585     * This is used to remove all style-impacting spans from text before new
5586     * extracted text is being replaced into it, so that we don't have any
5587     * lingering spans applied during the replace.
5588     */
5589    static void removeParcelableSpans(Spannable spannable, int start, int end) {
5590        Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class);
5591        int i = spans.length;
5592        while (i > 0) {
5593            i--;
5594            spannable.removeSpan(spans[i]);
5595        }
5596    }
5597
5598    /**
5599     * Apply to this text view the given extracted text, as previously
5600     * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}.
5601     */
5602    public void setExtractedText(ExtractedText text) {
5603        Editable content = getEditableText();
5604        if (text.text != null) {
5605            if (content == null) {
5606                setText(text.text, TextView.BufferType.EDITABLE);
5607            } else if (text.partialStartOffset < 0) {
5608                removeParcelableSpans(content, 0, content.length());
5609                content.replace(0, content.length(), text.text);
5610            } else {
5611                final int N = content.length();
5612                int start = text.partialStartOffset;
5613                if (start > N) start = N;
5614                int end = text.partialEndOffset;
5615                if (end > N) end = N;
5616                removeParcelableSpans(content, start, end);
5617                content.replace(start, end, text.text);
5618            }
5619        }
5620
5621        // Now set the selection position...  make sure it is in range, to
5622        // avoid crashes.  If this is a partial update, it is possible that
5623        // the underlying text may have changed, causing us problems here.
5624        // Also we just don't want to trust clients to do the right thing.
5625        Spannable sp = (Spannable)getText();
5626        final int N = sp.length();
5627        int start = text.selectionStart;
5628        if (start < 0) start = 0;
5629        else if (start > N) start = N;
5630        int end = text.selectionEnd;
5631        if (end < 0) end = 0;
5632        else if (end > N) end = N;
5633        Selection.setSelection(sp, start, end);
5634
5635        // Finally, update the selection mode.
5636        if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) {
5637            MetaKeyKeyListener.startSelecting(this, sp);
5638        } else {
5639            MetaKeyKeyListener.stopSelecting(this, sp);
5640        }
5641    }
5642
5643    /**
5644     * @hide
5645     */
5646    public void setExtracting(ExtractedTextRequest req) {
5647        if (mInputMethodState != null) {
5648            mInputMethodState.mExtracting = req;
5649        }
5650        // This stops a possible text selection mode. Maybe not intended.
5651        hideControllers();
5652    }
5653
5654    /**
5655     * Called by the framework in response to a text completion from
5656     * the current input method, provided by it calling
5657     * {@link InputConnection#commitCompletion
5658     * InputConnection.commitCompletion()}.  The default implementation does
5659     * nothing; text views that are supporting auto-completion should override
5660     * this to do their desired behavior.
5661     *
5662     * @param text The auto complete text the user has selected.
5663     */
5664    public void onCommitCompletion(CompletionInfo text) {
5665        // intentionally empty
5666    }
5667
5668    /**
5669     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
5670     * a dictionnary) from the current input method, provided by it calling
5671     * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
5672     * implementation flashes the background of the corrected word to provide feedback to the user.
5673     *
5674     * @param info The auto correct info about the text that was corrected.
5675     */
5676    public void onCommitCorrection(CorrectionInfo info) {
5677        if (mCorrectionHighlighter == null) {
5678            mCorrectionHighlighter = new CorrectionHighlighter();
5679        } else {
5680            mCorrectionHighlighter.invalidate(false);
5681        }
5682
5683        mCorrectionHighlighter.highlight(info);
5684    }
5685
5686    private class CorrectionHighlighter {
5687        private final Path mPath = new Path();
5688        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
5689        private int mStart, mEnd;
5690        private long mFadingStartTime;
5691        private final static int FADE_OUT_DURATION = 400;
5692
5693        public CorrectionHighlighter() {
5694            mPaint.setCompatibilityScaling(getResources().getCompatibilityInfo().applicationScale);
5695            mPaint.setStyle(Paint.Style.FILL);
5696        }
5697
5698        public void highlight(CorrectionInfo info) {
5699            mStart = info.getOffset();
5700            mEnd = mStart + info.getNewText().length();
5701            mFadingStartTime = SystemClock.uptimeMillis();
5702
5703            if (mStart < 0 || mEnd < 0) {
5704                stopAnimation();
5705            }
5706        }
5707
5708        public void draw(Canvas canvas, int cursorOffsetVertical) {
5709            if (updatePath() && updatePaint()) {
5710                if (cursorOffsetVertical != 0) {
5711                    canvas.translate(0, cursorOffsetVertical);
5712                }
5713
5714                canvas.drawPath(mPath, mPaint);
5715
5716                if (cursorOffsetVertical != 0) {
5717                    canvas.translate(0, -cursorOffsetVertical);
5718                }
5719                invalidate(true);
5720            } else {
5721                stopAnimation();
5722                invalidate(false);
5723            }
5724        }
5725
5726        private boolean updatePaint() {
5727            final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
5728            if (duration > FADE_OUT_DURATION) return false;
5729
5730            final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
5731            final int highlightColorAlpha = Color.alpha(mHighlightColor);
5732            final int color = (mHighlightColor & 0x00FFFFFF) +
5733                    ((int) (highlightColorAlpha * coef) << 24);
5734            mPaint.setColor(color);
5735            return true;
5736        }
5737
5738        private boolean updatePath() {
5739            final Layout layout = TextView.this.mLayout;
5740            if (layout == null) return false;
5741
5742            // Update in case text is edited while the animation is run
5743            final int length = mText.length();
5744            int start = Math.min(length, mStart);
5745            int end = Math.min(length, mEnd);
5746
5747            mPath.reset();
5748            TextView.this.mLayout.getSelectionPath(start, end, mPath);
5749            return true;
5750        }
5751
5752        private void invalidate(boolean delayed) {
5753            if (TextView.this.mLayout == null) return;
5754
5755            synchronized (sTempRect) {
5756                mPath.computeBounds(sTempRect, false);
5757
5758                int left = getCompoundPaddingLeft();
5759                int top = getExtendedPaddingTop() + getVerticalOffset(true);
5760
5761                if (delayed) {
5762                    TextView.this.postInvalidateDelayed(16, // 60 Hz update
5763                            left + (int) sTempRect.left, top + (int) sTempRect.top,
5764                            left + (int) sTempRect.right, top + (int) sTempRect.bottom);
5765                } else {
5766                    TextView.this.postInvalidate((int) sTempRect.left, (int) sTempRect.top,
5767                            (int) sTempRect.right, (int) sTempRect.bottom);
5768                }
5769            }
5770        }
5771
5772        private void stopAnimation() {
5773            TextView.this.mCorrectionHighlighter = null;
5774        }
5775    }
5776
5777    public void beginBatchEdit() {
5778        mInBatchEditControllers = true;
5779        final InputMethodState ims = mInputMethodState;
5780        if (ims != null) {
5781            int nesting = ++ims.mBatchEditNesting;
5782            if (nesting == 1) {
5783                ims.mCursorChanged = false;
5784                ims.mChangedDelta = 0;
5785                if (ims.mContentChanged) {
5786                    // We already have a pending change from somewhere else,
5787                    // so turn this into a full update.
5788                    ims.mChangedStart = 0;
5789                    ims.mChangedEnd = mText.length();
5790                } else {
5791                    ims.mChangedStart = EXTRACT_UNKNOWN;
5792                    ims.mChangedEnd = EXTRACT_UNKNOWN;
5793                    ims.mContentChanged = false;
5794                }
5795                onBeginBatchEdit();
5796            }
5797        }
5798    }
5799
5800    public void endBatchEdit() {
5801        mInBatchEditControllers = false;
5802        final InputMethodState ims = mInputMethodState;
5803        if (ims != null) {
5804            int nesting = --ims.mBatchEditNesting;
5805            if (nesting == 0) {
5806                finishBatchEdit(ims);
5807            }
5808        }
5809    }
5810
5811    void ensureEndedBatchEdit() {
5812        final InputMethodState ims = mInputMethodState;
5813        if (ims != null && ims.mBatchEditNesting != 0) {
5814            ims.mBatchEditNesting = 0;
5815            finishBatchEdit(ims);
5816        }
5817    }
5818
5819    void finishBatchEdit(final InputMethodState ims) {
5820        onEndBatchEdit();
5821
5822        if (ims.mContentChanged || ims.mSelectionModeChanged) {
5823            updateAfterEdit();
5824            reportExtractedText();
5825        } else if (ims.mCursorChanged) {
5826            // Cheezy way to get us to report the current cursor location.
5827            invalidateCursor();
5828        }
5829    }
5830
5831    void updateAfterEdit() {
5832        invalidate();
5833        int curs = getSelectionStart();
5834
5835        if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
5836            registerForPreDraw();
5837        }
5838
5839        if (curs >= 0) {
5840            mHighlightPathBogus = true;
5841            makeBlink();
5842            bringPointIntoView(curs);
5843        }
5844
5845        checkForResize();
5846    }
5847
5848    /**
5849     * Called by the framework in response to a request to begin a batch
5850     * of edit operations through a call to link {@link #beginBatchEdit()}.
5851     */
5852    public void onBeginBatchEdit() {
5853        // intentionally empty
5854    }
5855
5856    /**
5857     * Called by the framework in response to a request to end a batch
5858     * of edit operations through a call to link {@link #endBatchEdit}.
5859     */
5860    public void onEndBatchEdit() {
5861        // intentionally empty
5862    }
5863
5864    /**
5865     * Called by the framework in response to a private command from the
5866     * current method, provided by it calling
5867     * {@link InputConnection#performPrivateCommand
5868     * InputConnection.performPrivateCommand()}.
5869     *
5870     * @param action The action name of the command.
5871     * @param data Any additional data for the command.  This may be null.
5872     * @return Return true if you handled the command, else false.
5873     */
5874    public boolean onPrivateIMECommand(String action, Bundle data) {
5875        return false;
5876    }
5877
5878    private void nullLayouts() {
5879        if (mLayout instanceof BoringLayout && mSavedLayout == null) {
5880            mSavedLayout = (BoringLayout) mLayout;
5881        }
5882        if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) {
5883            mSavedHintLayout = (BoringLayout) mHintLayout;
5884        }
5885
5886        mLayout = mHintLayout = null;
5887
5888        // Since it depends on the value of mLayout
5889        prepareCursorControllers();
5890    }
5891
5892    /**
5893     * Make a new Layout based on the already-measured size of the view,
5894     * on the assumption that it was measured correctly at some point.
5895     */
5896    private void assumeLayout() {
5897        int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5898
5899        if (width < 1) {
5900            width = 0;
5901        }
5902
5903        int physicalWidth = width;
5904
5905        if (mHorizontallyScrolling) {
5906            width = VERY_WIDE;
5907        }
5908
5909        makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING,
5910                      physicalWidth, false);
5911    }
5912
5913    @Override
5914    protected void resetResolvedLayoutDirection() {
5915        super.resetResolvedLayoutDirection();
5916
5917        if (mLayoutAlignment != null &&
5918                (mTextAlign == TextAlign.VIEW_START ||
5919                mTextAlign == TextAlign.VIEW_END)) {
5920            mLayoutAlignment = null;
5921        }
5922    }
5923
5924    private Layout.Alignment getLayoutAlignment() {
5925        if (mLayoutAlignment == null) {
5926            Layout.Alignment alignment;
5927            TextAlign textAlign = mTextAlign;
5928            switch (textAlign) {
5929                case INHERIT:
5930                    // fall through to gravity temporarily
5931                    // intention is to inherit value through view hierarchy.
5932                case GRAVITY:
5933                    switch (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) {
5934                        case Gravity.START:
5935                            alignment = Layout.Alignment.ALIGN_NORMAL;
5936                            break;
5937                        case Gravity.END:
5938                            alignment = Layout.Alignment.ALIGN_OPPOSITE;
5939                            break;
5940                        case Gravity.LEFT:
5941                            alignment = Layout.Alignment.ALIGN_LEFT;
5942                            break;
5943                        case Gravity.RIGHT:
5944                            alignment = Layout.Alignment.ALIGN_RIGHT;
5945                            break;
5946                        case Gravity.CENTER_HORIZONTAL:
5947                            alignment = Layout.Alignment.ALIGN_CENTER;
5948                            break;
5949                        default:
5950                            alignment = Layout.Alignment.ALIGN_NORMAL;
5951                            break;
5952                    }
5953                    break;
5954                case TEXT_START:
5955                    alignment = Layout.Alignment.ALIGN_NORMAL;
5956                    break;
5957                case TEXT_END:
5958                    alignment = Layout.Alignment.ALIGN_OPPOSITE;
5959                    break;
5960                case CENTER:
5961                    alignment = Layout.Alignment.ALIGN_CENTER;
5962                    break;
5963                case VIEW_START:
5964                    alignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
5965                            Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT;
5966                    break;
5967                case VIEW_END:
5968                    alignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
5969                            Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT;
5970                    break;
5971                default:
5972                    alignment = Layout.Alignment.ALIGN_NORMAL;
5973                    break;
5974            }
5975            mLayoutAlignment = alignment;
5976        }
5977        return mLayoutAlignment;
5978    }
5979
5980    /**
5981     * The width passed in is now the desired layout width,
5982     * not the full view width with padding.
5983     * {@hide}
5984     */
5985    protected void makeNewLayout(int w, int hintWidth,
5986                                 BoringLayout.Metrics boring,
5987                                 BoringLayout.Metrics hintBoring,
5988                                 int ellipsisWidth, boolean bringIntoView) {
5989        stopMarquee();
5990
5991        mHighlightPathBogus = true;
5992
5993        if (w < 0) {
5994            w = 0;
5995        }
5996        if (hintWidth < 0) {
5997            hintWidth = 0;
5998        }
5999
6000        Layout.Alignment alignment = getLayoutAlignment();
6001        boolean shouldEllipsize = mEllipsize != null && mInput == null;
6002
6003        if (mTextDir == null) {
6004            resolveTextDirection();
6005        }
6006        if (mText instanceof Spannable) {
6007            mLayout = new DynamicLayout(mText, mTransformed, mTextPaint, w,
6008                    alignment, mTextDir, mSpacingMult,
6009                    mSpacingAdd, mIncludePad, mInput == null ? mEllipsize : null,
6010                    ellipsisWidth);
6011        } else {
6012            if (boring == UNKNOWN_BORING) {
6013                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
6014                if (boring != null) {
6015                    mBoring = boring;
6016                }
6017            }
6018
6019            if (boring != null) {
6020                if (boring.width <= w &&
6021                    (mEllipsize == null || boring.width <= ellipsisWidth)) {
6022                    if (mSavedLayout != null) {
6023                        mLayout = mSavedLayout.
6024                                replaceOrMake(mTransformed, mTextPaint,
6025                                w, alignment, mSpacingMult, mSpacingAdd,
6026                                boring, mIncludePad);
6027                    } else {
6028                        mLayout = BoringLayout.make(mTransformed, mTextPaint,
6029                                w, alignment, mSpacingMult, mSpacingAdd,
6030                                boring, mIncludePad);
6031                    }
6032
6033                    mSavedLayout = (BoringLayout) mLayout;
6034                } else if (shouldEllipsize && boring.width <= w) {
6035                    if (mSavedLayout != null) {
6036                        mLayout = mSavedLayout.
6037                                replaceOrMake(mTransformed, mTextPaint,
6038                                w, alignment, mSpacingMult, mSpacingAdd,
6039                                boring, mIncludePad, mEllipsize,
6040                                ellipsisWidth);
6041                    } else {
6042                        mLayout = BoringLayout.make(mTransformed, mTextPaint,
6043                                w, alignment, mSpacingMult, mSpacingAdd,
6044                                boring, mIncludePad, mEllipsize,
6045                                ellipsisWidth);
6046                    }
6047                } else if (shouldEllipsize) {
6048                    mLayout = new StaticLayout(mTransformed,
6049                                0, mTransformed.length(),
6050                                mTextPaint, w, alignment, mTextDir, mSpacingMult,
6051                                mSpacingAdd, mIncludePad, mEllipsize,
6052                                ellipsisWidth);
6053                } else {
6054                    mLayout = new StaticLayout(mTransformed, mTextPaint,
6055                            w, alignment, mTextDir, mSpacingMult, mSpacingAdd,
6056                            mIncludePad);
6057                }
6058            } else if (shouldEllipsize) {
6059                mLayout = new StaticLayout(mTransformed,
6060                            0, mTransformed.length(),
6061                            mTextPaint, w, alignment, mTextDir, mSpacingMult,
6062                            mSpacingAdd, mIncludePad, mEllipsize,
6063                            ellipsisWidth);
6064            } else {
6065                mLayout = new StaticLayout(mTransformed, mTextPaint,
6066                        w, alignment, mTextDir, mSpacingMult, mSpacingAdd,
6067                        mIncludePad);
6068            }
6069        }
6070
6071        shouldEllipsize = mEllipsize != null;
6072        mHintLayout = null;
6073
6074        if (mHint != null) {
6075            if (shouldEllipsize) hintWidth = w;
6076
6077            if (hintBoring == UNKNOWN_BORING) {
6078                hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir,
6079                                                   mHintBoring);
6080                if (hintBoring != null) {
6081                    mHintBoring = hintBoring;
6082                }
6083            }
6084
6085            if (hintBoring != null) {
6086                if (hintBoring.width <= hintWidth &&
6087                    (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) {
6088                    if (mSavedHintLayout != null) {
6089                        mHintLayout = mSavedHintLayout.
6090                                replaceOrMake(mHint, mTextPaint,
6091                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6092                                hintBoring, mIncludePad);
6093                    } else {
6094                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
6095                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6096                                hintBoring, mIncludePad);
6097                    }
6098
6099                    mSavedHintLayout = (BoringLayout) mHintLayout;
6100                } else if (shouldEllipsize && hintBoring.width <= hintWidth) {
6101                    if (mSavedHintLayout != null) {
6102                        mHintLayout = mSavedHintLayout.
6103                                replaceOrMake(mHint, mTextPaint,
6104                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6105                                hintBoring, mIncludePad, mEllipsize,
6106                                ellipsisWidth);
6107                    } else {
6108                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
6109                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
6110                                hintBoring, mIncludePad, mEllipsize,
6111                                ellipsisWidth);
6112                    }
6113                } else if (shouldEllipsize) {
6114                    mHintLayout = new StaticLayout(mHint,
6115                                0, mHint.length(),
6116                                mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult,
6117                                mSpacingAdd, mIncludePad, mEllipsize,
6118                                ellipsisWidth);
6119                } else {
6120                    mHintLayout = new StaticLayout(mHint, mTextPaint,
6121                            hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd,
6122                            mIncludePad);
6123                }
6124            } else if (shouldEllipsize) {
6125                mHintLayout = new StaticLayout(mHint,
6126                            0, mHint.length(),
6127                            mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult,
6128                            mSpacingAdd, mIncludePad, mEllipsize,
6129                            ellipsisWidth);
6130            } else {
6131                mHintLayout = new StaticLayout(mHint, mTextPaint,
6132                        hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd,
6133                        mIncludePad);
6134            }
6135        }
6136
6137        if (bringIntoView) {
6138            registerForPreDraw();
6139        }
6140
6141        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6142            if (!compressText(ellipsisWidth)) {
6143                final int height = mLayoutParams.height;
6144                // If the size of the view does not depend on the size of the text, try to
6145                // start the marquee immediately
6146                if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) {
6147                    startMarquee();
6148                } else {
6149                    // Defer the start of the marquee until we know our width (see setFrame())
6150                    mRestartMarquee = true;
6151                }
6152            }
6153        }
6154
6155        // CursorControllers need a non-null mLayout
6156        prepareCursorControllers();
6157    }
6158
6159    private boolean compressText(float width) {
6160        if (isHardwareAccelerated()) return false;
6161
6162        // Only compress the text if it hasn't been compressed by the previous pass
6163        if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX &&
6164                mTextPaint.getTextScaleX() == 1.0f) {
6165            final float textWidth = mLayout.getLineWidth(0);
6166            final float overflow = (textWidth + 1.0f - width) / width;
6167            if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) {
6168                mTextPaint.setTextScaleX(1.0f - overflow - 0.005f);
6169                post(new Runnable() {
6170                    public void run() {
6171                        requestLayout();
6172                    }
6173                });
6174                return true;
6175            }
6176        }
6177
6178        return false;
6179    }
6180
6181    private static int desired(Layout layout) {
6182        int n = layout.getLineCount();
6183        CharSequence text = layout.getText();
6184        float max = 0;
6185
6186        // if any line was wrapped, we can't use it.
6187        // but it's ok for the last line not to have a newline
6188
6189        for (int i = 0; i < n - 1; i++) {
6190            if (text.charAt(layout.getLineEnd(i) - 1) != '\n')
6191                return -1;
6192        }
6193
6194        for (int i = 0; i < n; i++) {
6195            max = Math.max(max, layout.getLineWidth(i));
6196        }
6197
6198        return (int) FloatMath.ceil(max);
6199    }
6200
6201    /**
6202     * Set whether the TextView includes extra top and bottom padding to make
6203     * room for accents that go above the normal ascent and descent.
6204     * The default is true.
6205     *
6206     * @attr ref android.R.styleable#TextView_includeFontPadding
6207     */
6208    public void setIncludeFontPadding(boolean includepad) {
6209        mIncludePad = includepad;
6210
6211        if (mLayout != null) {
6212            nullLayouts();
6213            requestLayout();
6214            invalidate();
6215        }
6216    }
6217
6218    private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics();
6219
6220    @Override
6221    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
6222        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
6223        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
6224        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
6225        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
6226
6227        int width;
6228        int height;
6229
6230        BoringLayout.Metrics boring = UNKNOWN_BORING;
6231        BoringLayout.Metrics hintBoring = UNKNOWN_BORING;
6232
6233        if (mTextDir == null) {
6234            resolveTextDirection();
6235        }
6236
6237        int des = -1;
6238        boolean fromexisting = false;
6239
6240        if (widthMode == MeasureSpec.EXACTLY) {
6241            // Parent has told us how big to be. So be it.
6242            width = widthSize;
6243        } else {
6244            if (mLayout != null && mEllipsize == null) {
6245                des = desired(mLayout);
6246            }
6247
6248            if (des < 0) {
6249                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
6250                if (boring != null) {
6251                    mBoring = boring;
6252                }
6253            } else {
6254                fromexisting = true;
6255            }
6256
6257            if (boring == null || boring == UNKNOWN_BORING) {
6258                if (des < 0) {
6259                    des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint));
6260                }
6261
6262                width = des;
6263            } else {
6264                width = boring.width;
6265            }
6266
6267            final Drawables dr = mDrawables;
6268            if (dr != null) {
6269                width = Math.max(width, dr.mDrawableWidthTop);
6270                width = Math.max(width, dr.mDrawableWidthBottom);
6271            }
6272
6273            if (mHint != null) {
6274                int hintDes = -1;
6275                int hintWidth;
6276
6277                if (mHintLayout != null && mEllipsize == null) {
6278                    hintDes = desired(mHintLayout);
6279                }
6280
6281                if (hintDes < 0) {
6282                    hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring);
6283                    if (hintBoring != null) {
6284                        mHintBoring = hintBoring;
6285                    }
6286                }
6287
6288                if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
6289                    if (hintDes < 0) {
6290                        hintDes = (int) FloatMath.ceil(
6291                                Layout.getDesiredWidth(mHint, mTextPaint));
6292                    }
6293
6294                    hintWidth = hintDes;
6295                } else {
6296                    hintWidth = hintBoring.width;
6297                }
6298
6299                if (hintWidth > width) {
6300                    width = hintWidth;
6301                }
6302            }
6303
6304            width += getCompoundPaddingLeft() + getCompoundPaddingRight();
6305
6306            if (mMaxWidthMode == EMS) {
6307                width = Math.min(width, mMaxWidth * getLineHeight());
6308            } else {
6309                width = Math.min(width, mMaxWidth);
6310            }
6311
6312            if (mMinWidthMode == EMS) {
6313                width = Math.max(width, mMinWidth * getLineHeight());
6314            } else {
6315                width = Math.max(width, mMinWidth);
6316            }
6317
6318            // Check against our minimum width
6319            width = Math.max(width, getSuggestedMinimumWidth());
6320
6321            if (widthMode == MeasureSpec.AT_MOST) {
6322                width = Math.min(widthSize, width);
6323            }
6324        }
6325
6326        int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight();
6327        int unpaddedWidth = want;
6328
6329        if (mHorizontallyScrolling) want = VERY_WIDE;
6330
6331        int hintWant = want;
6332        int hintWidth = mHintLayout == null ? hintWant : mHintLayout.getWidth();
6333
6334        if (mLayout == null) {
6335            makeNewLayout(want, hintWant, boring, hintBoring,
6336                          width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
6337        } else if ((mLayout.getWidth() != want) || (hintWidth != hintWant) ||
6338                   (mLayout.getEllipsizedWidth() !=
6339                        width - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
6340            if (mHint == null && mEllipsize == null &&
6341                    want > mLayout.getWidth() &&
6342                    (mLayout instanceof BoringLayout ||
6343                            (fromexisting && des >= 0 && des <= want))) {
6344                mLayout.increaseWidthTo(want);
6345            } else {
6346                makeNewLayout(want, hintWant, boring, hintBoring,
6347                              width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
6348            }
6349        } else {
6350            // Width has not changed.
6351        }
6352
6353        if (heightMode == MeasureSpec.EXACTLY) {
6354            // Parent has told us how big to be. So be it.
6355            height = heightSize;
6356            mDesiredHeightAtMeasure = -1;
6357        } else {
6358            int desired = getDesiredHeight();
6359
6360            height = desired;
6361            mDesiredHeightAtMeasure = desired;
6362
6363            if (heightMode == MeasureSpec.AT_MOST) {
6364                height = Math.min(desired, heightSize);
6365            }
6366        }
6367
6368        int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
6369        if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) {
6370            unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum));
6371        }
6372
6373        /*
6374         * We didn't let makeNewLayout() register to bring the cursor into view,
6375         * so do it here if there is any possibility that it is needed.
6376         */
6377        if (mMovement != null ||
6378            mLayout.getWidth() > unpaddedWidth ||
6379            mLayout.getHeight() > unpaddedHeight) {
6380            registerForPreDraw();
6381        } else {
6382            scrollTo(0, 0);
6383        }
6384
6385        setMeasuredDimension(width, height);
6386    }
6387
6388    private int getDesiredHeight() {
6389        return Math.max(
6390                getDesiredHeight(mLayout, true),
6391                getDesiredHeight(mHintLayout, mEllipsize != null));
6392    }
6393
6394    private int getDesiredHeight(Layout layout, boolean cap) {
6395        if (layout == null) {
6396            return 0;
6397        }
6398
6399        int linecount = layout.getLineCount();
6400        int pad = getCompoundPaddingTop() + getCompoundPaddingBottom();
6401        int desired = layout.getLineTop(linecount);
6402
6403        final Drawables dr = mDrawables;
6404        if (dr != null) {
6405            desired = Math.max(desired, dr.mDrawableHeightLeft);
6406            desired = Math.max(desired, dr.mDrawableHeightRight);
6407        }
6408
6409        desired += pad;
6410        layout.setMaximumVisibleLineCount(0);
6411
6412        if (mMaxMode == LINES) {
6413            /*
6414             * Don't cap the hint to a certain number of lines.
6415             * (Do cap it, though, if we have a maximum pixel height.)
6416             */
6417            if (cap) {
6418                if (linecount > mMaximum) {
6419                    layout.setMaximumVisibleLineCount(mMaximum);
6420                    desired = layout.getLineTop(mMaximum);
6421
6422                    if (dr != null) {
6423                        desired = Math.max(desired, dr.mDrawableHeightLeft);
6424                        desired = Math.max(desired, dr.mDrawableHeightRight);
6425                    }
6426
6427                    desired += pad;
6428                    linecount = mMaximum;
6429                }
6430            }
6431        } else {
6432            desired = Math.min(desired, mMaximum);
6433        }
6434
6435        if (mMinMode == LINES) {
6436            if (linecount < mMinimum) {
6437                desired += getLineHeight() * (mMinimum - linecount);
6438            }
6439        } else {
6440            desired = Math.max(desired, mMinimum);
6441        }
6442
6443        // Check against our minimum height
6444        desired = Math.max(desired, getSuggestedMinimumHeight());
6445
6446        return desired;
6447    }
6448
6449    /**
6450     * Check whether a change to the existing text layout requires a
6451     * new view layout.
6452     */
6453    private void checkForResize() {
6454        boolean sizeChanged = false;
6455
6456        if (mLayout != null) {
6457            // Check if our width changed
6458            if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) {
6459                sizeChanged = true;
6460                invalidate();
6461            }
6462
6463            // Check if our height changed
6464            if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) {
6465                int desiredHeight = getDesiredHeight();
6466
6467                if (desiredHeight != this.getHeight()) {
6468                    sizeChanged = true;
6469                }
6470            } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) {
6471                if (mDesiredHeightAtMeasure >= 0) {
6472                    int desiredHeight = getDesiredHeight();
6473
6474                    if (desiredHeight != mDesiredHeightAtMeasure) {
6475                        sizeChanged = true;
6476                    }
6477                }
6478            }
6479        }
6480
6481        if (sizeChanged) {
6482            requestLayout();
6483            // caller will have already invalidated
6484        }
6485    }
6486
6487    /**
6488     * Check whether entirely new text requires a new view layout
6489     * or merely a new text layout.
6490     */
6491    private void checkForRelayout() {
6492        // If we have a fixed width, we can just swap in a new text layout
6493        // if the text height stays the same or if the view height is fixed.
6494
6495        if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT ||
6496                (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) &&
6497                (mHint == null || mHintLayout != null) &&
6498                (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) {
6499            // Static width, so try making a new text layout.
6500
6501            int oldht = mLayout.getHeight();
6502            int want = mLayout.getWidth();
6503            int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();
6504
6505            /*
6506             * No need to bring the text into view, since the size is not
6507             * changing (unless we do the requestLayout(), in which case it
6508             * will happen at measure).
6509             */
6510            makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
6511                          mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(),
6512                          false);
6513
6514            if (mEllipsize != TextUtils.TruncateAt.MARQUEE) {
6515                // In a fixed-height view, so use our new text layout.
6516                if (mLayoutParams.height != LayoutParams.WRAP_CONTENT &&
6517                    mLayoutParams.height != LayoutParams.MATCH_PARENT) {
6518                    invalidate();
6519                    return;
6520                }
6521
6522                // Dynamic height, but height has stayed the same,
6523                // so use our new text layout.
6524                if (mLayout.getHeight() == oldht &&
6525                    (mHintLayout == null || mHintLayout.getHeight() == oldht)) {
6526                    invalidate();
6527                    return;
6528                }
6529            }
6530
6531            // We lose: the height has changed and we have a dynamic height.
6532            // Request a new view layout using our new text layout.
6533            requestLayout();
6534            invalidate();
6535        } else {
6536            // Dynamic width, so we have no choice but to request a new
6537            // view layout with a new text layout.
6538
6539            nullLayouts();
6540            requestLayout();
6541            invalidate();
6542        }
6543    }
6544
6545    /**
6546     * Returns true if anything changed.
6547     */
6548    private boolean bringTextIntoView() {
6549        int line = 0;
6550        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
6551            line = mLayout.getLineCount() - 1;
6552        }
6553
6554        Layout.Alignment a = mLayout.getParagraphAlignment(line);
6555        int dir = mLayout.getParagraphDirection(line);
6556        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6557        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6558        int ht = mLayout.getHeight();
6559
6560        int scrollx, scrolly;
6561
6562        // Convert to left, center, or right alignment.
6563        if (a == Layout.Alignment.ALIGN_NORMAL) {
6564            a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_LEFT :
6565                Layout.Alignment.ALIGN_RIGHT;
6566        } else if (a == Layout.Alignment.ALIGN_OPPOSITE){
6567            a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_RIGHT :
6568                Layout.Alignment.ALIGN_LEFT;
6569        }
6570
6571        if (a == Layout.Alignment.ALIGN_CENTER) {
6572            /*
6573             * Keep centered if possible, or, if it is too wide to fit,
6574             * keep leading edge in view.
6575             */
6576
6577            int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
6578            int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6579
6580            if (right - left < hspace) {
6581                scrollx = (right + left) / 2 - hspace / 2;
6582            } else {
6583                if (dir < 0) {
6584                    scrollx = right - hspace;
6585                } else {
6586                    scrollx = left;
6587                }
6588            }
6589        } else if (a == Layout.Alignment.ALIGN_RIGHT) {
6590            int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6591            scrollx = right - hspace;
6592        } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default)
6593            scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line));
6594        }
6595
6596        if (ht < vspace) {
6597            scrolly = 0;
6598        } else {
6599            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
6600                scrolly = ht - vspace;
6601            } else {
6602                scrolly = 0;
6603            }
6604        }
6605
6606        if (scrollx != mScrollX || scrolly != mScrollY) {
6607            scrollTo(scrollx, scrolly);
6608            return true;
6609        } else {
6610            return false;
6611        }
6612    }
6613
6614    /**
6615     * Move the point, specified by the offset, into the view if it is needed.
6616     * This has to be called after layout. Returns true if anything changed.
6617     */
6618    public boolean bringPointIntoView(int offset) {
6619        boolean changed = false;
6620
6621        if (mLayout == null) return changed;
6622
6623        int line = mLayout.getLineForOffset(offset);
6624
6625        // FIXME: Is it okay to truncate this, or should we round?
6626        final int x = (int)mLayout.getPrimaryHorizontal(offset);
6627        final int top = mLayout.getLineTop(line);
6628        final int bottom = mLayout.getLineTop(line + 1);
6629
6630        int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
6631        int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6632        int ht = mLayout.getHeight();
6633
6634        int grav;
6635
6636        switch (mLayout.getParagraphAlignment(line)) {
6637            case ALIGN_LEFT:
6638                grav = 1;
6639                break;
6640            case ALIGN_RIGHT:
6641                grav = -1;
6642                break;
6643            case ALIGN_NORMAL:
6644                grav = mLayout.getParagraphDirection(line);
6645                break;
6646            case ALIGN_OPPOSITE:
6647                grav = -mLayout.getParagraphDirection(line);
6648                break;
6649            case ALIGN_CENTER:
6650            default:
6651                grav = 0;
6652                break;
6653        }
6654
6655        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6656        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6657
6658        int hslack = (bottom - top) / 2;
6659        int vslack = hslack;
6660
6661        if (vslack > vspace / 4)
6662            vslack = vspace / 4;
6663        if (hslack > hspace / 4)
6664            hslack = hspace / 4;
6665
6666        int hs = mScrollX;
6667        int vs = mScrollY;
6668
6669        if (top - vs < vslack)
6670            vs = top - vslack;
6671        if (bottom - vs > vspace - vslack)
6672            vs = bottom - (vspace - vslack);
6673        if (ht - vs < vspace)
6674            vs = ht - vspace;
6675        if (0 - vs > 0)
6676            vs = 0;
6677
6678        if (grav != 0) {
6679            if (x - hs < hslack) {
6680                hs = x - hslack;
6681            }
6682            if (x - hs > hspace - hslack) {
6683                hs = x - (hspace - hslack);
6684            }
6685        }
6686
6687        if (grav < 0) {
6688            if (left - hs > 0)
6689                hs = left;
6690            if (right - hs < hspace)
6691                hs = right - hspace;
6692        } else if (grav > 0) {
6693            if (right - hs < hspace)
6694                hs = right - hspace;
6695            if (left - hs > 0)
6696                hs = left;
6697        } else /* grav == 0 */ {
6698            if (right - left <= hspace) {
6699                /*
6700                 * If the entire text fits, center it exactly.
6701                 */
6702                hs = left - (hspace - (right - left)) / 2;
6703            } else if (x > right - hslack) {
6704                /*
6705                 * If we are near the right edge, keep the right edge
6706                 * at the edge of the view.
6707                 */
6708                hs = right - hspace;
6709            } else if (x < left + hslack) {
6710                /*
6711                 * If we are near the left edge, keep the left edge
6712                 * at the edge of the view.
6713                 */
6714                hs = left;
6715            } else if (left > hs) {
6716                /*
6717                 * Is there whitespace visible at the left?  Fix it if so.
6718                 */
6719                hs = left;
6720            } else if (right < hs + hspace) {
6721                /*
6722                 * Is there whitespace visible at the right?  Fix it if so.
6723                 */
6724                hs = right - hspace;
6725            } else {
6726                /*
6727                 * Otherwise, float as needed.
6728                 */
6729                if (x - hs < hslack) {
6730                    hs = x - hslack;
6731                }
6732                if (x - hs > hspace - hslack) {
6733                    hs = x - (hspace - hslack);
6734                }
6735            }
6736        }
6737
6738        if (hs != mScrollX || vs != mScrollY) {
6739            if (mScroller == null) {
6740                scrollTo(hs, vs);
6741            } else {
6742                long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
6743                int dx = hs - mScrollX;
6744                int dy = vs - mScrollY;
6745
6746                if (duration > ANIMATED_SCROLL_GAP) {
6747                    mScroller.startScroll(mScrollX, mScrollY, dx, dy);
6748                    awakenScrollBars(mScroller.getDuration());
6749                    invalidate();
6750                } else {
6751                    if (!mScroller.isFinished()) {
6752                        mScroller.abortAnimation();
6753                    }
6754
6755                    scrollBy(dx, dy);
6756                }
6757
6758                mLastScroll = AnimationUtils.currentAnimationTimeMillis();
6759            }
6760
6761            changed = true;
6762        }
6763
6764        if (isFocused()) {
6765            // This offsets because getInterestingRect() is in terms of viewport coordinates, but
6766            // requestRectangleOnScreen() is in terms of content coordinates.
6767
6768            if (mTempRect == null) mTempRect = new Rect();
6769            mTempRect.set(x, top, x + 1, bottom);
6770            getInterestingRect(mTempRect, line);
6771            mTempRect.offset(mScrollX, mScrollY);
6772
6773            if (requestRectangleOnScreen(mTempRect)) {
6774                changed = true;
6775            }
6776        }
6777
6778        return changed;
6779    }
6780
6781    /**
6782     * Move the cursor, if needed, so that it is at an offset that is visible
6783     * to the user.  This will not move the cursor if it represents more than
6784     * one character (a selection range).  This will only work if the
6785     * TextView contains spannable text; otherwise it will do nothing.
6786     *
6787     * @return True if the cursor was actually moved, false otherwise.
6788     */
6789    public boolean moveCursorToVisibleOffset() {
6790        if (!(mText instanceof Spannable)) {
6791            return false;
6792        }
6793        int start = getSelectionStart();
6794        int end = getSelectionEnd();
6795        if (start != end) {
6796            return false;
6797        }
6798
6799        // First: make sure the line is visible on screen:
6800
6801        int line = mLayout.getLineForOffset(start);
6802
6803        final int top = mLayout.getLineTop(line);
6804        final int bottom = mLayout.getLineTop(line + 1);
6805        final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6806        int vslack = (bottom - top) / 2;
6807        if (vslack > vspace / 4)
6808            vslack = vspace / 4;
6809        final int vs = mScrollY;
6810
6811        if (top < (vs+vslack)) {
6812            line = mLayout.getLineForVertical(vs+vslack+(bottom-top));
6813        } else if (bottom > (vspace+vs-vslack)) {
6814            line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top));
6815        }
6816
6817        // Next: make sure the character is visible on screen:
6818
6819        final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6820        final int hs = mScrollX;
6821        final int leftChar = mLayout.getOffsetForHorizontal(line, hs);
6822        final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs);
6823
6824        // line might contain bidirectional text
6825        final int lowChar = leftChar < rightChar ? leftChar : rightChar;
6826        final int highChar = leftChar > rightChar ? leftChar : rightChar;
6827
6828        int newStart = start;
6829        if (newStart < lowChar) {
6830            newStart = lowChar;
6831        } else if (newStart > highChar) {
6832            newStart = highChar;
6833        }
6834
6835        if (newStart != start) {
6836            Selection.setSelection((Spannable)mText, newStart);
6837            return true;
6838        }
6839
6840        return false;
6841    }
6842
6843    @Override
6844    public void computeScroll() {
6845        if (mScroller != null) {
6846            if (mScroller.computeScrollOffset()) {
6847                mScrollX = mScroller.getCurrX();
6848                mScrollY = mScroller.getCurrY();
6849                invalidateParentCaches();
6850                postInvalidate();  // So we draw again
6851            }
6852        }
6853    }
6854
6855    private void getInterestingRect(Rect r, int line) {
6856        convertFromViewportToContentCoordinates(r);
6857
6858        // Rectangle can can be expanded on first and last line to take
6859        // padding into account.
6860        // TODO Take left/right padding into account too?
6861        if (line == 0) r.top -= getExtendedPaddingTop();
6862        if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom();
6863    }
6864
6865    private void convertFromViewportToContentCoordinates(Rect r) {
6866        final int horizontalOffset = viewportToContentHorizontalOffset();
6867        r.left += horizontalOffset;
6868        r.right += horizontalOffset;
6869
6870        final int verticalOffset = viewportToContentVerticalOffset();
6871        r.top += verticalOffset;
6872        r.bottom += verticalOffset;
6873    }
6874
6875    private int viewportToContentHorizontalOffset() {
6876        return getCompoundPaddingLeft() - mScrollX;
6877    }
6878
6879    private int viewportToContentVerticalOffset() {
6880        int offset = getExtendedPaddingTop() - mScrollY;
6881        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
6882            offset += getVerticalOffset(false);
6883        }
6884        return offset;
6885    }
6886
6887    @Override
6888    public void debug(int depth) {
6889        super.debug(depth);
6890
6891        String output = debugIndent(depth);
6892        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
6893                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
6894                + "} ";
6895
6896        if (mText != null) {
6897
6898            output += "mText=\"" + mText + "\" ";
6899            if (mLayout != null) {
6900                output += "mLayout width=" + mLayout.getWidth()
6901                        + " height=" + mLayout.getHeight();
6902            }
6903        } else {
6904            output += "mText=NULL";
6905        }
6906        Log.d(VIEW_LOG_TAG, output);
6907    }
6908
6909    /**
6910     * Convenience for {@link Selection#getSelectionStart}.
6911     */
6912    @ViewDebug.ExportedProperty(category = "text")
6913    public int getSelectionStart() {
6914        return Selection.getSelectionStart(getText());
6915    }
6916
6917    /**
6918     * Convenience for {@link Selection#getSelectionEnd}.
6919     */
6920    @ViewDebug.ExportedProperty(category = "text")
6921    public int getSelectionEnd() {
6922        return Selection.getSelectionEnd(getText());
6923    }
6924
6925    /**
6926     * Return true iff there is a selection inside this text view.
6927     */
6928    public boolean hasSelection() {
6929        final int selectionStart = getSelectionStart();
6930        final int selectionEnd = getSelectionEnd();
6931
6932        return selectionStart >= 0 && selectionStart != selectionEnd;
6933    }
6934
6935    /**
6936     * Sets the properties of this field (lines, horizontally scrolling,
6937     * transformation method) to be for a single-line input.
6938     *
6939     * @attr ref android.R.styleable#TextView_singleLine
6940     */
6941    public void setSingleLine() {
6942        setSingleLine(true);
6943    }
6944
6945    /**
6946     * Sets the properties of this field to transform input to ALL CAPS
6947     * display. This may use a "small caps" formatting if available.
6948     * This setting will be ignored if this field is editable or selectable.
6949     *
6950     * This call replaces the current transformation method. Disabling this
6951     * will not necessarily restore the previous behavior from before this
6952     * was enabled.
6953     *
6954     * @see #setTransformationMethod(TransformationMethod)
6955     * @attr ref android.R.styleable#TextView_textAllCaps
6956     */
6957    public void setAllCaps(boolean allCaps) {
6958        if (allCaps) {
6959            setTransformationMethod(new AllCapsTransformationMethod(getContext()));
6960        } else {
6961            setTransformationMethod(null);
6962        }
6963    }
6964
6965    /**
6966     * If true, sets the properties of this field (number of lines, horizontally scrolling,
6967     * transformation method) to be for a single-line input; if false, restores these to the default
6968     * conditions.
6969     *
6970     * Note that the default conditions are not necessarily those that were in effect prior this
6971     * method, and you may want to reset these properties to your custom values.
6972     *
6973     * @attr ref android.R.styleable#TextView_singleLine
6974     */
6975    @android.view.RemotableViewMethod
6976    public void setSingleLine(boolean singleLine) {
6977        // Could be used, but may break backward compatibility.
6978        // if (mSingleLine == singleLine) return;
6979        setInputTypeSingleLine(singleLine);
6980        applySingleLine(singleLine, true, true);
6981    }
6982
6983    /**
6984     * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType.
6985     * @param singleLine
6986     */
6987    private void setInputTypeSingleLine(boolean singleLine) {
6988        if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
6989            if (singleLine) {
6990                mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
6991            } else {
6992                mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
6993            }
6994        }
6995    }
6996
6997    private void applySingleLine(boolean singleLine, boolean applyTransformation,
6998            boolean changeMaxLines) {
6999        mSingleLine = singleLine;
7000        if (singleLine) {
7001            setLines(1);
7002            setHorizontallyScrolling(true);
7003            if (applyTransformation) {
7004                setTransformationMethod(SingleLineTransformationMethod.getInstance());
7005            }
7006        } else {
7007            if (changeMaxLines) {
7008                setMaxLines(Integer.MAX_VALUE);
7009            }
7010            setHorizontallyScrolling(false);
7011            if (applyTransformation) {
7012                setTransformationMethod(null);
7013            }
7014        }
7015    }
7016
7017    /**
7018     * Causes words in the text that are longer than the view is wide
7019     * to be ellipsized instead of broken in the middle.  You may also
7020     * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling}
7021     * to constrain the text to a single line.  Use <code>null</code>
7022     * to turn off ellipsizing.
7023     *
7024     * @attr ref android.R.styleable#TextView_ellipsize
7025     */
7026    public void setEllipsize(TextUtils.TruncateAt where) {
7027        mEllipsize = where;
7028
7029        if (mLayout != null) {
7030            nullLayouts();
7031            requestLayout();
7032            invalidate();
7033        }
7034    }
7035
7036    /**
7037     * Sets how many times to repeat the marquee animation. Only applied if the
7038     * TextView has marquee enabled. Set to -1 to repeat indefinitely.
7039     *
7040     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
7041     */
7042    public void setMarqueeRepeatLimit(int marqueeLimit) {
7043        mMarqueeRepeatLimit = marqueeLimit;
7044    }
7045
7046    /**
7047     * Returns where, if anywhere, words that are longer than the view
7048     * is wide should be ellipsized.
7049     */
7050    @ViewDebug.ExportedProperty
7051    public TextUtils.TruncateAt getEllipsize() {
7052        return mEllipsize;
7053    }
7054
7055    /**
7056     * Set the TextView so that when it takes focus, all the text is
7057     * selected.
7058     *
7059     * @attr ref android.R.styleable#TextView_selectAllOnFocus
7060     */
7061    @android.view.RemotableViewMethod
7062    public void setSelectAllOnFocus(boolean selectAllOnFocus) {
7063        mSelectAllOnFocus = selectAllOnFocus;
7064
7065        if (selectAllOnFocus && !(mText instanceof Spannable)) {
7066            setText(mText, BufferType.SPANNABLE);
7067        }
7068    }
7069
7070    /**
7071     * Set whether the cursor is visible.  The default is true.
7072     *
7073     * @attr ref android.R.styleable#TextView_cursorVisible
7074     */
7075    @android.view.RemotableViewMethod
7076    public void setCursorVisible(boolean visible) {
7077        if (mCursorVisible != visible) {
7078            mCursorVisible = visible;
7079            invalidate();
7080
7081            makeBlink();
7082
7083            // InsertionPointCursorController depends on mCursorVisible
7084            prepareCursorControllers();
7085        }
7086    }
7087
7088    private boolean isCursorVisible() {
7089        return mCursorVisible && isTextEditable();
7090    }
7091
7092    private boolean canMarquee() {
7093        int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight());
7094        return width > 0 && mLayout.getLineWidth(0) > width;
7095    }
7096
7097    private void startMarquee() {
7098        // Do not ellipsize EditText
7099        if (mInput != null) return;
7100
7101        if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
7102            return;
7103        }
7104
7105        if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) &&
7106                getLineCount() == 1 && canMarquee()) {
7107
7108            if (mMarquee == null) mMarquee = new Marquee(this);
7109            mMarquee.start(mMarqueeRepeatLimit);
7110        }
7111    }
7112
7113    private void stopMarquee() {
7114        if (mMarquee != null && !mMarquee.isStopped()) {
7115            mMarquee.stop();
7116        }
7117    }
7118
7119    private void startStopMarquee(boolean start) {
7120        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
7121            if (start) {
7122                startMarquee();
7123            } else {
7124                stopMarquee();
7125            }
7126        }
7127    }
7128
7129    private static final class Marquee extends Handler {
7130        // TODO: Add an option to configure this
7131        private static final float MARQUEE_DELTA_MAX = 0.07f;
7132        private static final int MARQUEE_DELAY = 1200;
7133        private static final int MARQUEE_RESTART_DELAY = 1200;
7134        private static final int MARQUEE_RESOLUTION = 1000 / 30;
7135        private static final int MARQUEE_PIXELS_PER_SECOND = 30;
7136
7137        private static final byte MARQUEE_STOPPED = 0x0;
7138        private static final byte MARQUEE_STARTING = 0x1;
7139        private static final byte MARQUEE_RUNNING = 0x2;
7140
7141        private static final int MESSAGE_START = 0x1;
7142        private static final int MESSAGE_TICK = 0x2;
7143        private static final int MESSAGE_RESTART = 0x3;
7144
7145        private final WeakReference<TextView> mView;
7146
7147        private byte mStatus = MARQUEE_STOPPED;
7148        private final float mScrollUnit;
7149        private float mMaxScroll;
7150        float mMaxFadeScroll;
7151        private float mGhostStart;
7152        private float mGhostOffset;
7153        private float mFadeStop;
7154        private int mRepeatLimit;
7155
7156        float mScroll;
7157
7158        Marquee(TextView v) {
7159            final float density = v.getContext().getResources().getDisplayMetrics().density;
7160            mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION;
7161            mView = new WeakReference<TextView>(v);
7162        }
7163
7164        @Override
7165        public void handleMessage(Message msg) {
7166            switch (msg.what) {
7167                case MESSAGE_START:
7168                    mStatus = MARQUEE_RUNNING;
7169                    tick();
7170                    break;
7171                case MESSAGE_TICK:
7172                    tick();
7173                    break;
7174                case MESSAGE_RESTART:
7175                    if (mStatus == MARQUEE_RUNNING) {
7176                        if (mRepeatLimit >= 0) {
7177                            mRepeatLimit--;
7178                        }
7179                        start(mRepeatLimit);
7180                    }
7181                    break;
7182            }
7183        }
7184
7185        void tick() {
7186            if (mStatus != MARQUEE_RUNNING) {
7187                return;
7188            }
7189
7190            removeMessages(MESSAGE_TICK);
7191
7192            final TextView textView = mView.get();
7193            if (textView != null && (textView.isFocused() || textView.isSelected())) {
7194                mScroll += mScrollUnit;
7195                if (mScroll > mMaxScroll) {
7196                    mScroll = mMaxScroll;
7197                    sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY);
7198                } else {
7199                    sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION);
7200                }
7201                textView.invalidate();
7202            }
7203        }
7204
7205        void stop() {
7206            mStatus = MARQUEE_STOPPED;
7207            removeMessages(MESSAGE_START);
7208            removeMessages(MESSAGE_RESTART);
7209            removeMessages(MESSAGE_TICK);
7210            resetScroll();
7211        }
7212
7213        private void resetScroll() {
7214            mScroll = 0.0f;
7215            final TextView textView = mView.get();
7216            if (textView != null) textView.invalidate();
7217        }
7218
7219        void start(int repeatLimit) {
7220            if (repeatLimit == 0) {
7221                stop();
7222                return;
7223            }
7224            mRepeatLimit = repeatLimit;
7225            final TextView textView = mView.get();
7226            if (textView != null && textView.mLayout != null) {
7227                mStatus = MARQUEE_STARTING;
7228                mScroll = 0.0f;
7229                final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() -
7230                        textView.getCompoundPaddingRight();
7231                final float lineWidth = textView.mLayout.getLineWidth(0);
7232                final float gap = textWidth / 3.0f;
7233                mGhostStart = lineWidth - textWidth + gap;
7234                mMaxScroll = mGhostStart + textWidth;
7235                mGhostOffset = lineWidth + gap;
7236                mFadeStop = lineWidth + textWidth / 6.0f;
7237                mMaxFadeScroll = mGhostStart + lineWidth + lineWidth;
7238
7239                textView.invalidate();
7240                sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY);
7241            }
7242        }
7243
7244        float getGhostOffset() {
7245            return mGhostOffset;
7246        }
7247
7248        boolean shouldDrawLeftFade() {
7249            return mScroll <= mFadeStop;
7250        }
7251
7252        boolean shouldDrawGhost() {
7253            return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart;
7254        }
7255
7256        boolean isRunning() {
7257            return mStatus == MARQUEE_RUNNING;
7258        }
7259
7260        boolean isStopped() {
7261            return mStatus == MARQUEE_STOPPED;
7262        }
7263    }
7264
7265    /**
7266     * This method is called when the text is changed, in case any subclasses
7267     * would like to know.
7268     *
7269     * Within <code>text</code>, the <code>lengthAfter</code> characters
7270     * beginning at <code>start</code> have just replaced old text that had
7271     * length <code>lengthBefore</code>. It is an error to attempt to make
7272     * changes to <code>text</code> from this callback.
7273     *
7274     * @param text The text the TextView is displaying
7275     * @param start The offset of the start of the range of the text that was
7276     * modified
7277     * @param lengthBefore The length of the former text that has been replaced
7278     * @param lengthAfter The length of the replacement modified text
7279     */
7280    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
7281        // intentionally empty
7282    }
7283
7284    /**
7285     * This method is called when the selection has changed, in case any
7286     * subclasses would like to know.
7287     *
7288     * @param selStart The new selection start location.
7289     * @param selEnd The new selection end location.
7290     */
7291    protected void onSelectionChanged(int selStart, int selEnd) {
7292        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7293    }
7294
7295    /**
7296     * Adds a TextWatcher to the list of those whose methods are called
7297     * whenever this TextView's text changes.
7298     * <p>
7299     * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
7300     * not called after {@link #setText} calls.  Now, doing {@link #setText}
7301     * if there are any text changed listeners forces the buffer type to
7302     * Editable if it would not otherwise be and does call this method.
7303     */
7304    public void addTextChangedListener(TextWatcher watcher) {
7305        if (mListeners == null) {
7306            mListeners = new ArrayList<TextWatcher>();
7307        }
7308
7309        mListeners.add(watcher);
7310    }
7311
7312    /**
7313     * Removes the specified TextWatcher from the list of those whose
7314     * methods are called
7315     * whenever this TextView's text changes.
7316     */
7317    public void removeTextChangedListener(TextWatcher watcher) {
7318        if (mListeners != null) {
7319            int i = mListeners.indexOf(watcher);
7320
7321            if (i >= 0) {
7322                mListeners.remove(i);
7323            }
7324        }
7325    }
7326
7327    private void sendBeforeTextChanged(CharSequence text, int start, int before,
7328                                   int after) {
7329        if (mListeners != null) {
7330            final ArrayList<TextWatcher> list = mListeners;
7331            final int count = list.size();
7332            for (int i = 0; i < count; i++) {
7333                list.get(i).beforeTextChanged(text, start, before, after);
7334            }
7335        }
7336    }
7337
7338    /**
7339     * Not private so it can be called from an inner class without going
7340     * through a thunk.
7341     */
7342    void sendOnTextChanged(CharSequence text, int start, int before,
7343                                   int after) {
7344        if (mListeners != null) {
7345            final ArrayList<TextWatcher> list = mListeners;
7346            final int count = list.size();
7347            for (int i = 0; i < count; i++) {
7348                list.get(i).onTextChanged(text, start, before, after);
7349            }
7350        }
7351    }
7352
7353    /**
7354     * Not private so it can be called from an inner class without going
7355     * through a thunk.
7356     */
7357    void sendAfterTextChanged(Editable text) {
7358        if (mListeners != null) {
7359            final ArrayList<TextWatcher> list = mListeners;
7360            final int count = list.size();
7361            for (int i = 0; i < count; i++) {
7362                list.get(i).afterTextChanged(text);
7363            }
7364        }
7365    }
7366
7367    /**
7368     * Not private so it can be called from an inner class without going
7369     * through a thunk.
7370     */
7371    void handleTextChanged(CharSequence buffer, int start, int before, int after) {
7372        final InputMethodState ims = mInputMethodState;
7373        if (ims == null || ims.mBatchEditNesting == 0) {
7374            updateAfterEdit();
7375        }
7376        if (ims != null) {
7377            ims.mContentChanged = true;
7378            if (ims.mChangedStart < 0) {
7379                ims.mChangedStart = start;
7380                ims.mChangedEnd = start+before;
7381            } else {
7382                ims.mChangedStart = Math.min(ims.mChangedStart, start);
7383                ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta);
7384            }
7385            ims.mChangedDelta += after-before;
7386        }
7387
7388        sendOnTextChanged(buffer, start, before, after);
7389        onTextChanged(buffer, start, before, after);
7390
7391        // Hide the controllers if the amount of content changed
7392        if (before != after) {
7393            hideControllers();
7394        }
7395    }
7396
7397    /**
7398     * Not private so it can be called from an inner class without going
7399     * through a thunk.
7400     */
7401    void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) {
7402        // XXX Make the start and end move together if this ends up
7403        // spending too much time invalidating.
7404
7405        boolean selChanged = false;
7406        int newSelStart=-1, newSelEnd=-1;
7407
7408        final InputMethodState ims = mInputMethodState;
7409
7410        if (what == Selection.SELECTION_END) {
7411            mHighlightPathBogus = true;
7412            selChanged = true;
7413            newSelEnd = newStart;
7414
7415            if (!isFocused()) {
7416                mSelectionMoved = true;
7417            }
7418
7419            if (oldStart >= 0 || newStart >= 0) {
7420                invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart);
7421                registerForPreDraw();
7422                makeBlink();
7423            }
7424        }
7425
7426        if (what == Selection.SELECTION_START) {
7427            mHighlightPathBogus = true;
7428            selChanged = true;
7429            newSelStart = newStart;
7430
7431            if (!isFocused()) {
7432                mSelectionMoved = true;
7433            }
7434
7435            if (oldStart >= 0 || newStart >= 0) {
7436                int end = Selection.getSelectionEnd(buf);
7437                invalidateCursor(end, oldStart, newStart);
7438            }
7439        }
7440
7441        if (selChanged) {
7442            if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) {
7443                if (newSelStart < 0) {
7444                    newSelStart = Selection.getSelectionStart(buf);
7445                }
7446                if (newSelEnd < 0) {
7447                    newSelEnd = Selection.getSelectionEnd(buf);
7448                }
7449                onSelectionChanged(newSelStart, newSelEnd);
7450            }
7451        }
7452
7453        if (what instanceof UpdateAppearance ||
7454            what instanceof ParagraphStyle) {
7455            if (ims == null || ims.mBatchEditNesting == 0) {
7456                invalidate();
7457                mHighlightPathBogus = true;
7458                checkForResize();
7459            } else {
7460                ims.mContentChanged = true;
7461            }
7462        }
7463
7464        if (MetaKeyKeyListener.isMetaTracker(buf, what)) {
7465            mHighlightPathBogus = true;
7466            if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) {
7467                ims.mSelectionModeChanged = true;
7468            }
7469
7470            if (Selection.getSelectionStart(buf) >= 0) {
7471                if (ims == null || ims.mBatchEditNesting == 0) {
7472                    invalidateCursor();
7473                } else {
7474                    ims.mCursorChanged = true;
7475                }
7476            }
7477        }
7478
7479        if (what instanceof ParcelableSpan) {
7480            // If this is a span that can be sent to a remote process,
7481            // the current extract editor would be interested in it.
7482            if (ims != null && ims.mExtracting != null) {
7483                if (ims.mBatchEditNesting != 0) {
7484                    if (oldStart >= 0) {
7485                        if (ims.mChangedStart > oldStart) {
7486                            ims.mChangedStart = oldStart;
7487                        }
7488                        if (ims.mChangedStart > oldEnd) {
7489                            ims.mChangedStart = oldEnd;
7490                        }
7491                    }
7492                    if (newStart >= 0) {
7493                        if (ims.mChangedStart > newStart) {
7494                            ims.mChangedStart = newStart;
7495                        }
7496                        if (ims.mChangedStart > newEnd) {
7497                            ims.mChangedStart = newEnd;
7498                        }
7499                    }
7500                } else {
7501                    if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: "
7502                            + oldStart + "-" + oldEnd + ","
7503                            + newStart + "-" + newEnd + what);
7504                    ims.mContentChanged = true;
7505                }
7506            }
7507        }
7508    }
7509
7510    private class ChangeWatcher
7511    implements TextWatcher, SpanWatcher {
7512
7513        private CharSequence mBeforeText;
7514
7515        public void beforeTextChanged(CharSequence buffer, int start,
7516                                      int before, int after) {
7517            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start
7518                    + " before=" + before + " after=" + after + ": " + buffer);
7519
7520            if (AccessibilityManager.getInstance(mContext).isEnabled()
7521                    && !isPasswordInputType(mInputType)
7522                    && !hasPasswordTransformationMethod()) {
7523                mBeforeText = buffer.toString();
7524            }
7525
7526            TextView.this.sendBeforeTextChanged(buffer, start, before, after);
7527        }
7528
7529        public void onTextChanged(CharSequence buffer, int start,
7530                                  int before, int after) {
7531            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start
7532                    + " before=" + before + " after=" + after + ": " + buffer);
7533            TextView.this.handleTextChanged(buffer, start, before, after);
7534
7535            if (AccessibilityManager.getInstance(mContext).isEnabled() &&
7536                    (isFocused() || isSelected() &&
7537                    isShown())) {
7538                sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after);
7539                mBeforeText = null;
7540            }
7541        }
7542
7543        public void afterTextChanged(Editable buffer) {
7544            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer);
7545            TextView.this.sendAfterTextChanged(buffer);
7546
7547            if (MetaKeyKeyListener.getMetaState(buffer,
7548                                 MetaKeyKeyListener.META_SELECTING) != 0) {
7549                MetaKeyKeyListener.stopSelecting(TextView.this, buffer);
7550            }
7551        }
7552
7553        public void onSpanChanged(Spannable buf,
7554                                  Object what, int s, int e, int st, int en) {
7555            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e
7556                    + " st=" + st + " en=" + en + " what=" + what + ": " + buf);
7557            TextView.this.spanChange(buf, what, s, st, e, en);
7558        }
7559
7560        public void onSpanAdded(Spannable buf, Object what, int s, int e) {
7561            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e
7562                    + " what=" + what + ": " + buf);
7563            TextView.this.spanChange(buf, what, -1, s, -1, e);
7564        }
7565
7566        public void onSpanRemoved(Spannable buf, Object what, int s, int e) {
7567            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e
7568                    + " what=" + what + ": " + buf);
7569            TextView.this.spanChange(buf, what, s, -1, e, -1);
7570        }
7571    }
7572
7573    /**
7574     * @hide
7575     */
7576    @Override
7577    public void dispatchFinishTemporaryDetach() {
7578        mDispatchTemporaryDetach = true;
7579        super.dispatchFinishTemporaryDetach();
7580        mDispatchTemporaryDetach = false;
7581    }
7582
7583    @Override
7584    public void onStartTemporaryDetach() {
7585        super.onStartTemporaryDetach();
7586        // Only track when onStartTemporaryDetach() is called directly,
7587        // usually because this instance is an editable field in a list
7588        if (!mDispatchTemporaryDetach) mTemporaryDetach = true;
7589
7590        // Because of View recycling in ListView, there is no easy way to know when a TextView with
7591        // selection becomes visible again. Until a better solution is found, stop text selection
7592        // mode (if any) as soon as this TextView is recycled.
7593        stopSelectionActionMode();
7594    }
7595
7596    @Override
7597    public void onFinishTemporaryDetach() {
7598        super.onFinishTemporaryDetach();
7599        // Only track when onStartTemporaryDetach() is called directly,
7600        // usually because this instance is an editable field in a list
7601        if (!mDispatchTemporaryDetach) mTemporaryDetach = false;
7602    }
7603
7604    @Override
7605    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
7606        if (mTemporaryDetach) {
7607            // If we are temporarily in the detach state, then do nothing.
7608            super.onFocusChanged(focused, direction, previouslyFocusedRect);
7609            return;
7610        }
7611
7612        mShowCursor = SystemClock.uptimeMillis();
7613
7614        ensureEndedBatchEdit();
7615
7616        if (focused) {
7617            int selStart = getSelectionStart();
7618            int selEnd = getSelectionEnd();
7619
7620            // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection
7621            // mode for these, unless there was a specific selection already started.
7622            final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 &&
7623                    selEnd == mText.length();
7624            mCreatedWithASelection = mFrozenWithFocus && hasSelection() && !isFocusHighlighted;
7625
7626            if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
7627                // If a tap was used to give focus to that view, move cursor at tap position.
7628                // Has to be done before onTakeFocus, which can be overloaded.
7629                final int lastTapPosition = getLastTapPosition();
7630                if (lastTapPosition >= 0) {
7631                    Selection.setSelection((Spannable) mText, lastTapPosition);
7632                }
7633
7634                if (mMovement != null) {
7635                    mMovement.onTakeFocus(this, (Spannable) mText, direction);
7636                }
7637
7638                // The DecorView does not have focus when the 'Done' ExtractEditText button is
7639                // pressed. Since it is the ViewAncestor's mView, it requests focus before
7640                // ExtractEditText clears focus, which gives focus to the ExtractEditText.
7641                // This special case ensure that we keep current selection in that case.
7642                // It would be better to know why the DecorView does not have focus at that time.
7643                if (((this instanceof ExtractEditText) || mSelectionMoved) &&
7644                        selStart >= 0 && selEnd >= 0) {
7645                    /*
7646                     * Someone intentionally set the selection, so let them
7647                     * do whatever it is that they wanted to do instead of
7648                     * the default on-focus behavior.  We reset the selection
7649                     * here instead of just skipping the onTakeFocus() call
7650                     * because some movement methods do something other than
7651                     * just setting the selection in theirs and we still
7652                     * need to go through that path.
7653                     */
7654                    Selection.setSelection((Spannable) mText, selStart, selEnd);
7655                }
7656
7657                if (mSelectAllOnFocus) {
7658                    selectAll();
7659                }
7660
7661                mTouchFocusSelected = true;
7662            }
7663
7664            mFrozenWithFocus = false;
7665            mSelectionMoved = false;
7666
7667            if (mText instanceof Spannable) {
7668                Spannable sp = (Spannable) mText;
7669                MetaKeyKeyListener.resetMetaState(sp);
7670            }
7671
7672            makeBlink();
7673
7674            if (mError != null) {
7675                showError();
7676            }
7677        } else {
7678            if (mError != null) {
7679                hideError();
7680            }
7681            // Don't leave us in the middle of a batch edit.
7682            onEndBatchEdit();
7683
7684            if (this instanceof ExtractEditText) {
7685                // terminateTextSelectionMode removes selection, which we want to keep when
7686                // ExtractEditText goes out of focus.
7687                final int selStart = getSelectionStart();
7688                final int selEnd = getSelectionEnd();
7689                hideControllers();
7690                Selection.setSelection((Spannable) mText, selStart, selEnd);
7691            } else {
7692                hideControllers();
7693            }
7694
7695            // No need to create the controller
7696            if (mSelectionModifierCursorController != null) {
7697                mSelectionModifierCursorController.resetTouchOffsets();
7698            }
7699        }
7700
7701        startStopMarquee(focused);
7702
7703        if (mTransformation != null) {
7704            mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect);
7705        }
7706
7707        super.onFocusChanged(focused, direction, previouslyFocusedRect);
7708    }
7709
7710    private int getLastTapPosition() {
7711        // No need to create the controller at that point, no last tap position saved
7712        if (mSelectionModifierCursorController != null) {
7713            int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset();
7714            if (lastTapPosition >= 0) {
7715                // Safety check, should not be possible.
7716                if (lastTapPosition > mText.length()) {
7717                    Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs "
7718                            + mText.length() + ")");
7719                    lastTapPosition = mText.length();
7720                }
7721                return lastTapPosition;
7722            }
7723        }
7724
7725        return -1;
7726    }
7727
7728    @Override
7729    public void onWindowFocusChanged(boolean hasWindowFocus) {
7730        super.onWindowFocusChanged(hasWindowFocus);
7731
7732        if (hasWindowFocus) {
7733            if (mBlink != null) {
7734                mBlink.uncancel();
7735                makeBlink();
7736            }
7737        } else {
7738            if (mBlink != null) {
7739                mBlink.cancel();
7740            }
7741            // Don't leave us in the middle of a batch edit.
7742            onEndBatchEdit();
7743            if (mInputContentType != null) {
7744                mInputContentType.enterDown = false;
7745            }
7746            hideControllers();
7747            removeAllSuggestionSpans();
7748        }
7749
7750        startStopMarquee(hasWindowFocus);
7751    }
7752
7753    private void removeAllSuggestionSpans() {
7754        if (mText instanceof Editable) {
7755            Editable editable = ((Editable) mText);
7756            SuggestionSpan[] spans = editable.getSpans(0, mText.length(), SuggestionSpan.class);
7757            final int length = spans.length;
7758            for (int i = 0; i < length; i++) {
7759                editable.removeSpan(spans[i]);
7760            }
7761        }
7762    }
7763
7764    @Override
7765    protected void onVisibilityChanged(View changedView, int visibility) {
7766        super.onVisibilityChanged(changedView, visibility);
7767        if (visibility != VISIBLE) {
7768            hideControllers();
7769        }
7770    }
7771
7772    /**
7773     * Use {@link BaseInputConnection#removeComposingSpans
7774     * BaseInputConnection.removeComposingSpans()} to remove any IME composing
7775     * state from this text view.
7776     */
7777    public void clearComposingText() {
7778        if (mText instanceof Spannable) {
7779            BaseInputConnection.removeComposingSpans((Spannable)mText);
7780        }
7781    }
7782
7783    @Override
7784    public void setSelected(boolean selected) {
7785        boolean wasSelected = isSelected();
7786
7787        super.setSelected(selected);
7788
7789        if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
7790            if (selected) {
7791                startMarquee();
7792            } else {
7793                stopMarquee();
7794            }
7795        }
7796    }
7797
7798    @Override
7799    public boolean onTouchEvent(MotionEvent event) {
7800        final int action = event.getActionMasked();
7801
7802        if (hasSelectionController()) {
7803            getSelectionController().onTouchEvent(event);
7804        }
7805
7806        if (action == MotionEvent.ACTION_DOWN) {
7807            mLastDownPositionX = event.getX();
7808            mLastDownPositionY = event.getY();
7809
7810            // Reset this state; it will be re-set if super.onTouchEvent
7811            // causes focus to move to the view.
7812            mTouchFocusSelected = false;
7813            mIgnoreActionUpEvent = false;
7814        }
7815
7816        final boolean superResult = super.onTouchEvent(event);
7817
7818        /*
7819         * Don't handle the release after a long press, because it will
7820         * move the selection away from whatever the menu action was
7821         * trying to affect.
7822         */
7823        if (mDiscardNextActionUp && action == MotionEvent.ACTION_UP) {
7824            mDiscardNextActionUp = false;
7825            return superResult;
7826        }
7827
7828        final boolean touchIsFinished = action == MotionEvent.ACTION_UP && !mIgnoreActionUpEvent &&
7829                isFocused();
7830
7831        if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()
7832                && mText instanceof Spannable && mLayout != null) {
7833            boolean handled = false;
7834
7835            if (mMovement != null) {
7836                handled |= mMovement.onTouchEvent(this, (Spannable) mText, event);
7837            }
7838
7839            if (mLinksClickable && mAutoLinkMask != 0 && mTextIsSelectable && touchIsFinished) {
7840                // The LinkMovementMethod which should handle taps on links has not been installed
7841                // to support text selection. We reproduce its behavior here to open links.
7842                ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(),
7843                        getSelectionEnd(), ClickableSpan.class);
7844
7845                if (links.length != 0) {
7846                    links[0].onClick(this);
7847                    handled = true;
7848                }
7849            }
7850
7851            if ((isTextEditable() || mTextIsSelectable) && touchIsFinished) {
7852                // Show the IME, except when selecting in read-only text.
7853                final InputMethodManager imm = InputMethodManager.peekInstance();
7854                if (imm != null) {
7855                    imm.viewClicked(this);
7856                }
7857                if (!mTextIsSelectable) {
7858                    handled |= imm != null && imm.showSoftInput(this, 0);
7859                }
7860
7861                boolean selectAllGotFocus = mSelectAllOnFocus && didTouchFocusSelect();
7862                if (!selectAllGotFocus && hasSelection()) {
7863                    startSelectionActionMode();
7864                } else {
7865                    stopSelectionActionMode();
7866                    hideSuggestions();
7867                    if (hasInsertionController() && !selectAllGotFocus && mText.length() > 0) {
7868                        getInsertionController().show();
7869                    }
7870                }
7871            }
7872
7873            if (handled) {
7874                return true;
7875            }
7876        }
7877
7878        return superResult;
7879    }
7880
7881    @Override
7882    public boolean onGenericMotionEvent(MotionEvent event) {
7883        if (mMovement != null && mText instanceof Spannable && mLayout != null) {
7884            try {
7885                if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) {
7886                    return true;
7887                }
7888            } catch (AbstractMethodError ex) {
7889                // onGenericMotionEvent was added to the MovementMethod interface in API 12.
7890                // Ignore its absence in case third party applications implemented the
7891                // interface directly.
7892            }
7893        }
7894        return super.onGenericMotionEvent(event);
7895    }
7896
7897    private void prepareCursorControllers() {
7898        boolean windowSupportsHandles = false;
7899
7900        ViewGroup.LayoutParams params = getRootView().getLayoutParams();
7901        if (params instanceof WindowManager.LayoutParams) {
7902            WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params;
7903            windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW
7904                    || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW;
7905        }
7906
7907        mInsertionControllerEnabled = windowSupportsHandles && isCursorVisible() && mLayout != null;
7908        mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() &&
7909                mLayout != null;
7910
7911        if (!mInsertionControllerEnabled) {
7912            hideInsertionPointCursorController();
7913            if (mInsertionPointCursorController != null) {
7914                mInsertionPointCursorController.onDetached();
7915                mInsertionPointCursorController = null;
7916            }
7917        }
7918
7919        if (!mSelectionControllerEnabled) {
7920            stopSelectionActionMode();
7921            if (mSelectionModifierCursorController != null) {
7922                mSelectionModifierCursorController.onDetached();
7923                mSelectionModifierCursorController = null;
7924            }
7925        }
7926    }
7927
7928    /**
7929     * @return True iff this TextView contains a text that can be edited, or if this is
7930     * a selectable TextView.
7931     */
7932    private boolean isTextEditable() {
7933        return mText instanceof Editable && onCheckIsTextEditor() && isEnabled();
7934    }
7935
7936    /**
7937     * Returns true, only while processing a touch gesture, if the initial
7938     * touch down event caused focus to move to the text view and as a result
7939     * its selection changed.  Only valid while processing the touch gesture
7940     * of interest.
7941     */
7942    public boolean didTouchFocusSelect() {
7943        return mTouchFocusSelected;
7944    }
7945
7946    @Override
7947    public void cancelLongPress() {
7948        super.cancelLongPress();
7949        mIgnoreActionUpEvent = true;
7950    }
7951
7952    @Override
7953    public boolean onTrackballEvent(MotionEvent event) {
7954        if (mMovement != null && mText instanceof Spannable &&
7955            mLayout != null) {
7956            if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) {
7957                return true;
7958            }
7959        }
7960
7961        return super.onTrackballEvent(event);
7962    }
7963
7964    public void setScroller(Scroller s) {
7965        mScroller = s;
7966    }
7967
7968    private static class Blink extends Handler implements Runnable {
7969        private final WeakReference<TextView> mView;
7970        private boolean mCancelled;
7971
7972        public Blink(TextView v) {
7973            mView = new WeakReference<TextView>(v);
7974        }
7975
7976        public void run() {
7977            if (mCancelled) {
7978                return;
7979            }
7980
7981            removeCallbacks(Blink.this);
7982
7983            TextView tv = mView.get();
7984
7985            if (tv != null && tv.shouldBlink()) {
7986                if (tv.mLayout != null) {
7987                    tv.invalidateCursorPath();
7988                }
7989
7990                postAtTime(this, SystemClock.uptimeMillis() + BLINK);
7991            }
7992        }
7993
7994        void cancel() {
7995            if (!mCancelled) {
7996                removeCallbacks(Blink.this);
7997                mCancelled = true;
7998            }
7999        }
8000
8001        void uncancel() {
8002            mCancelled = false;
8003        }
8004    }
8005
8006    /**
8007     * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
8008     */
8009    private boolean shouldBlink() {
8010        if (!isFocused()) return false;
8011
8012        final int start = getSelectionStart();
8013        if (start < 0) return false;
8014
8015        final int end = getSelectionEnd();
8016        if (end < 0) return false;
8017
8018        return start == end;
8019    }
8020
8021    private void makeBlink() {
8022        if (isCursorVisible()) {
8023            if (shouldBlink()) {
8024                mShowCursor = SystemClock.uptimeMillis();
8025                if (mBlink == null) mBlink = new Blink(this);
8026                mBlink.removeCallbacks(mBlink);
8027                mBlink.postAtTime(mBlink, mShowCursor + BLINK);
8028            }
8029        } else {
8030            if (mBlink != null) mBlink.removeCallbacks(mBlink);
8031        }
8032    }
8033
8034    @Override
8035    protected float getLeftFadingEdgeStrength() {
8036        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f;
8037        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
8038            if (mMarquee != null && !mMarquee.isStopped()) {
8039                final Marquee marquee = mMarquee;
8040                if (marquee.shouldDrawLeftFade()) {
8041                    return marquee.mScroll / getHorizontalFadingEdgeLength();
8042                } else {
8043                    return 0.0f;
8044                }
8045            } else if (getLineCount() == 1) {
8046                final int layoutDirection = getResolvedLayoutDirection();
8047                final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
8048                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
8049                    case Gravity.LEFT:
8050                        return 0.0f;
8051                    case Gravity.RIGHT:
8052                        return (mLayout.getLineRight(0) - (mRight - mLeft) -
8053                                getCompoundPaddingLeft() - getCompoundPaddingRight() -
8054                                mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength();
8055                    case Gravity.CENTER_HORIZONTAL:
8056                        return 0.0f;
8057                }
8058            }
8059        }
8060        return super.getLeftFadingEdgeStrength();
8061    }
8062
8063    @Override
8064    protected float getRightFadingEdgeStrength() {
8065        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f;
8066        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
8067            if (mMarquee != null && !mMarquee.isStopped()) {
8068                final Marquee marquee = mMarquee;
8069                return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength();
8070            } else if (getLineCount() == 1) {
8071                final int layoutDirection = getResolvedLayoutDirection();
8072                final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
8073                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
8074                    case Gravity.LEFT:
8075                        final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() -
8076                                getCompoundPaddingRight();
8077                        final float lineWidth = mLayout.getLineWidth(0);
8078                        return (lineWidth - textWidth) / getHorizontalFadingEdgeLength();
8079                    case Gravity.RIGHT:
8080                        return 0.0f;
8081                    case Gravity.CENTER_HORIZONTAL:
8082                    case Gravity.FILL_HORIZONTAL:
8083                        return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
8084                                getCompoundPaddingLeft() - getCompoundPaddingRight())) /
8085                                getHorizontalFadingEdgeLength();
8086                }
8087            }
8088        }
8089        return super.getRightFadingEdgeStrength();
8090    }
8091
8092    @Override
8093    protected int computeHorizontalScrollRange() {
8094        if (mLayout != null) {
8095            return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ?
8096                    (int) mLayout.getLineWidth(0) : mLayout.getWidth();
8097        }
8098
8099        return super.computeHorizontalScrollRange();
8100    }
8101
8102    @Override
8103    protected int computeVerticalScrollRange() {
8104        if (mLayout != null)
8105            return mLayout.getHeight();
8106
8107        return super.computeVerticalScrollRange();
8108    }
8109
8110    @Override
8111    protected int computeVerticalScrollExtent() {
8112        return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
8113    }
8114
8115    @Override
8116    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched) {
8117        if (TextUtils.isEmpty(searched)) {
8118            return;
8119        }
8120        CharSequence thisText = getText();
8121        if (TextUtils.isEmpty(thisText)) {
8122            return;
8123        }
8124        String searchedLowerCase = searched.toString().toLowerCase();
8125        String thisTextLowerCase = thisText.toString().toLowerCase();
8126        if (thisTextLowerCase.contains(searchedLowerCase)) {
8127            outViews.add(this);
8128        }
8129    }
8130
8131    public enum BufferType {
8132        NORMAL, SPANNABLE, EDITABLE,
8133    }
8134
8135    /**
8136     * Returns the TextView_textColor attribute from the
8137     * Resources.StyledAttributes, if set, or the TextAppearance_textColor
8138     * from the TextView_textAppearance attribute, if TextView_textColor
8139     * was not set directly.
8140     */
8141    public static ColorStateList getTextColors(Context context, TypedArray attrs) {
8142        ColorStateList colors;
8143        colors = attrs.getColorStateList(com.android.internal.R.styleable.
8144                                         TextView_textColor);
8145
8146        if (colors == null) {
8147            int ap = attrs.getResourceId(com.android.internal.R.styleable.
8148                                         TextView_textAppearance, -1);
8149            if (ap != -1) {
8150                TypedArray appearance;
8151                appearance = context.obtainStyledAttributes(ap,
8152                                            com.android.internal.R.styleable.TextAppearance);
8153                colors = appearance.getColorStateList(com.android.internal.R.styleable.
8154                                                  TextAppearance_textColor);
8155                appearance.recycle();
8156            }
8157        }
8158
8159        return colors;
8160    }
8161
8162    /**
8163     * Returns the default color from the TextView_textColor attribute
8164     * from the AttributeSet, if set, or the default color from the
8165     * TextAppearance_textColor from the TextView_textAppearance attribute,
8166     * if TextView_textColor was not set directly.
8167     */
8168    public static int getTextColor(Context context,
8169                                   TypedArray attrs,
8170                                   int def) {
8171        ColorStateList colors = getTextColors(context, attrs);
8172
8173        if (colors == null) {
8174            return def;
8175        } else {
8176            return colors.getDefaultColor();
8177        }
8178    }
8179
8180    @Override
8181    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8182        final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK;
8183        if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) {
8184            switch (keyCode) {
8185            case KeyEvent.KEYCODE_A:
8186                if (canSelectText()) {
8187                    return onTextContextMenuItem(ID_SELECT_ALL);
8188                }
8189                break;
8190            case KeyEvent.KEYCODE_X:
8191                if (canCut()) {
8192                    return onTextContextMenuItem(ID_CUT);
8193                }
8194                break;
8195            case KeyEvent.KEYCODE_C:
8196                if (canCopy()) {
8197                    return onTextContextMenuItem(ID_COPY);
8198                }
8199                break;
8200            case KeyEvent.KEYCODE_V:
8201                if (canPaste()) {
8202                    return onTextContextMenuItem(ID_PASTE);
8203                }
8204                break;
8205            }
8206        }
8207        return super.onKeyShortcut(keyCode, event);
8208    }
8209
8210    /**
8211     * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the
8212     * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have
8213     * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient.
8214     */
8215    private boolean canSelectText() {
8216        return hasSelectionController() && mText.length() != 0;
8217    }
8218
8219    /**
8220     * Test based on the <i>intrinsic</i> charateristics of the TextView.
8221     * The text must be spannable and the movement method must allow for arbitary selection.
8222     *
8223     * See also {@link #canSelectText()}.
8224     */
8225    private boolean textCanBeSelected() {
8226        // prepareCursorController() relies on this method.
8227        // If you change this condition, make sure prepareCursorController is called anywhere
8228        // the value of this condition might be changed.
8229        if (mMovement == null || !mMovement.canSelectArbitrarily()) return false;
8230        return isTextEditable() || (mTextIsSelectable && mText instanceof Spannable && isEnabled());
8231    }
8232
8233    private boolean canCut() {
8234        if (hasPasswordTransformationMethod()) {
8235            return false;
8236        }
8237
8238        if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mInput != null) {
8239            return true;
8240        }
8241
8242        return false;
8243    }
8244
8245    private boolean canCopy() {
8246        if (hasPasswordTransformationMethod()) {
8247            return false;
8248        }
8249
8250        if (mText.length() > 0 && hasSelection()) {
8251            return true;
8252        }
8253
8254        return false;
8255    }
8256
8257    private boolean canPaste() {
8258        return (mText instanceof Editable &&
8259                mInput != null &&
8260                getSelectionStart() >= 0 &&
8261                getSelectionEnd() >= 0 &&
8262                ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)).
8263                hasPrimaryClip());
8264    }
8265
8266    private static long packRangeInLong(int start, int end) {
8267        return (((long) start) << 32) | end;
8268    }
8269
8270    private static int extractRangeStartFromLong(long range) {
8271        return (int) (range >>> 32);
8272    }
8273
8274    private static int extractRangeEndFromLong(long range) {
8275        return (int) (range & 0x00000000FFFFFFFFL);
8276    }
8277
8278    private boolean selectAll() {
8279        final int length = mText.length();
8280        Selection.setSelection((Spannable) mText, 0, length);
8281        return length > 0;
8282    }
8283
8284    /**
8285     * Adjusts selection to the word under last touch offset.
8286     * Return true if the operation was successfully performed.
8287     */
8288    private boolean selectCurrentWord() {
8289        if (!canSelectText()) {
8290            return false;
8291        }
8292
8293        if (hasPasswordTransformationMethod()) {
8294            // Always select all on a password field.
8295            // Cut/copy menu entries are not available for passwords, but being able to select all
8296            // is however useful to delete or paste to replace the entire content.
8297            return selectAll();
8298        }
8299
8300        int klass = mInputType & InputType.TYPE_MASK_CLASS;
8301        int variation = mInputType & InputType.TYPE_MASK_VARIATION;
8302
8303        // Specific text field types: select the entire text for these
8304        if (klass == InputType.TYPE_CLASS_NUMBER ||
8305                klass == InputType.TYPE_CLASS_PHONE ||
8306                klass == InputType.TYPE_CLASS_DATETIME ||
8307                variation == InputType.TYPE_TEXT_VARIATION_URI ||
8308                variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
8309                variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ||
8310                variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
8311            return selectAll();
8312        }
8313
8314        long lastTouchOffsets = getLastTouchOffsets();
8315        final int minOffset = extractRangeStartFromLong(lastTouchOffsets);
8316        final int maxOffset = extractRangeEndFromLong(lastTouchOffsets);
8317
8318        // Safety check in case standard touch event handling has been bypassed
8319        if (minOffset < 0 || minOffset >= mText.length()) return false;
8320        if (maxOffset < 0 || maxOffset >= mText.length()) return false;
8321
8322        int selectionStart, selectionEnd;
8323
8324        // If a URLSpan (web address, email, phone...) is found at that position, select it.
8325        URLSpan[] urlSpans = ((Spanned) mText).getSpans(minOffset, maxOffset, URLSpan.class);
8326        if (urlSpans.length == 1) {
8327            URLSpan url = urlSpans[0];
8328            selectionStart = ((Spanned) mText).getSpanStart(url);
8329            selectionEnd = ((Spanned) mText).getSpanEnd(url);
8330        } else {
8331            if (mWordIterator == null) {
8332                mWordIterator = new WordIterator();
8333            }
8334            // WordIerator handles text changes, this is a no-op if text in unchanged.
8335            mWordIterator.setCharSequence(mText);
8336
8337            selectionStart = mWordIterator.getBeginning(minOffset);
8338            if (selectionStart == BreakIterator.DONE) return false;
8339
8340            selectionEnd = mWordIterator.getEnd(maxOffset);
8341            if (selectionEnd == BreakIterator.DONE) return false;
8342        }
8343
8344        Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
8345        return true;
8346    }
8347
8348    private long getLastTouchOffsets() {
8349        int minOffset, maxOffset;
8350
8351        if (mContextMenuTriggeredByKey) {
8352            minOffset = getSelectionStart();
8353            maxOffset = getSelectionEnd();
8354        } else {
8355            SelectionModifierCursorController selectionController = getSelectionController();
8356            minOffset = selectionController.getMinTouchOffset();
8357            maxOffset = selectionController.getMaxTouchOffset();
8358        }
8359
8360        return packRangeInLong(minOffset, maxOffset);
8361    }
8362
8363    @Override
8364    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
8365        super.onPopulateAccessibilityEvent(event);
8366
8367        final boolean isPassword = hasPasswordTransformationMethod();
8368        if (!isPassword) {
8369            CharSequence text = getText();
8370            if (TextUtils.isEmpty(text)) {
8371                text = getHint();
8372            }
8373            if (!TextUtils.isEmpty(text)) {
8374                event.getText().add(text);
8375            }
8376        }
8377    }
8378
8379    @Override
8380    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
8381        super.onInitializeAccessibilityEvent(event);
8382
8383        final boolean isPassword = hasPasswordTransformationMethod();
8384        event.setPassword(isPassword);
8385
8386        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) {
8387            event.setFromIndex(Selection.getSelectionStart(mText));
8388            event.setToIndex(Selection.getSelectionEnd(mText));
8389            event.setItemCount(mText.length());
8390        }
8391    }
8392
8393    @Override
8394    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
8395        super.onInitializeAccessibilityNodeInfo(info);
8396
8397        final boolean isPassword = hasPasswordTransformationMethod();
8398        if (!isPassword) {
8399            info.setText(getText());
8400        }
8401        info.setPassword(isPassword);
8402    }
8403
8404    void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText,
8405            int fromIndex, int removedCount, int addedCount) {
8406        AccessibilityEvent event =
8407            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
8408        event.setFromIndex(fromIndex);
8409        event.setRemovedCount(removedCount);
8410        event.setAddedCount(addedCount);
8411        event.setBeforeText(beforeText);
8412        sendAccessibilityEventUnchecked(event);
8413    }
8414
8415    @Override
8416    protected void onCreateContextMenu(ContextMenu menu) {
8417        super.onCreateContextMenu(menu);
8418        boolean added = false;
8419        mContextMenuTriggeredByKey = mDPadCenterIsDown || mEnterKeyIsDown;
8420        // Problem with context menu on long press: the menu appears while the key in down and when
8421        // the key is released, the view does not receive the key_up event.
8422        // We need two layers of flags: mDPadCenterIsDown and mEnterKeyIsDown are set in key down/up
8423        // events. We cannot simply clear these flags in onTextContextMenuItem since
8424        // it may not be called (if the user/ discards the context menu with the back key).
8425        // We clear these flags here and mContextMenuTriggeredByKey saves that state so that it is
8426        // available in onTextContextMenuItem.
8427        mDPadCenterIsDown = mEnterKeyIsDown = false;
8428
8429        MenuHandler handler = new MenuHandler();
8430
8431        if (mText instanceof Spanned && hasSelectionController()) {
8432            long lastTouchOffset = getLastTouchOffsets();
8433            final int selStart = extractRangeStartFromLong(lastTouchOffset);
8434            final int selEnd = extractRangeEndFromLong(lastTouchOffset);
8435
8436            URLSpan[] urls = ((Spanned) mText).getSpans(selStart, selEnd, URLSpan.class);
8437            if (urls.length > 0) {
8438                menu.add(0, ID_COPY_URL, 0, com.android.internal.R.string.copyUrl).
8439                        setOnMenuItemClickListener(handler);
8440
8441                added = true;
8442            }
8443        }
8444
8445        // The context menu is not empty, which will prevent the selection mode from starting.
8446        // Add a entry to start it in the context menu.
8447        // TODO Does not handle the case where a subclass does not call super.thisMethod or
8448        // populates the menu AFTER this call.
8449        if (menu.size() > 0) {
8450            menu.add(0, ID_SELECTION_MODE, 0, com.android.internal.R.string.selectTextMode).
8451                    setOnMenuItemClickListener(handler);
8452            added = true;
8453        }
8454
8455        if (added) {
8456            menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle);
8457        }
8458    }
8459
8460    /**
8461     * Returns whether this text view is a current input method target.  The
8462     * default implementation just checks with {@link InputMethodManager}.
8463     */
8464    public boolean isInputMethodTarget() {
8465        InputMethodManager imm = InputMethodManager.peekInstance();
8466        return imm != null && imm.isActive(this);
8467    }
8468
8469    // Selection context mode
8470    private static final int ID_SELECT_ALL = android.R.id.selectAll;
8471    private static final int ID_CUT = android.R.id.cut;
8472    private static final int ID_COPY = android.R.id.copy;
8473    private static final int ID_PASTE = android.R.id.paste;
8474    // Context menu entries
8475    private static final int ID_COPY_URL = android.R.id.copyUrl;
8476    private static final int ID_SELECTION_MODE = android.R.id.selectTextMode;
8477
8478    private class MenuHandler implements MenuItem.OnMenuItemClickListener {
8479        public boolean onMenuItemClick(MenuItem item) {
8480            return onTextContextMenuItem(item.getItemId());
8481        }
8482    }
8483
8484    /**
8485     * Called when a context menu option for the text view is selected.  Currently
8486     * this will be {@link android.R.id#copyUrl}, {@link android.R.id#selectTextMode},
8487     * {@link android.R.id#selectAll}, {@link android.R.id#paste}, {@link android.R.id#cut}
8488     * or {@link android.R.id#copy}.
8489     *
8490     * @return true if the context menu item action was performed.
8491     */
8492    public boolean onTextContextMenuItem(int id) {
8493        int min = 0;
8494        int max = mText.length();
8495
8496        if (isFocused()) {
8497            final int selStart = getSelectionStart();
8498            final int selEnd = getSelectionEnd();
8499
8500            min = Math.max(0, Math.min(selStart, selEnd));
8501            max = Math.max(0, Math.max(selStart, selEnd));
8502        }
8503
8504        switch (id) {
8505            case ID_COPY_URL:
8506                URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class);
8507                if (urls.length >= 1) {
8508                    ClipData clip = null;
8509                    for (int i=0; i<urls.length; i++) {
8510                        Uri uri = Uri.parse(urls[0].getURL());
8511                        if (clip == null) {
8512                            clip = ClipData.newRawUri(null, uri);
8513                        } else {
8514                            clip.addItem(new ClipData.Item(uri));
8515                        }
8516                    }
8517                    if (clip != null) {
8518                        setPrimaryClip(clip);
8519                    }
8520                }
8521                stopSelectionActionMode();
8522                return true;
8523
8524            case ID_SELECTION_MODE:
8525                if (mSelectionActionMode != null) {
8526                    // Selection mode is already started, simply change selected part.
8527                    selectCurrentWord();
8528                } else {
8529                    startSelectionActionMode();
8530                }
8531                return true;
8532
8533            case ID_SELECT_ALL:
8534                // This does not enter text selection mode. Text is highlighted, so that it can be
8535                // bulk edited, like selectAllOnFocus does. Returns true even if text is empty.
8536                selectAll();
8537                return true;
8538
8539            case ID_PASTE:
8540                paste(min, max);
8541                return true;
8542
8543            case ID_CUT:
8544                setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max)));
8545                ((Editable) mText).delete(min, max);
8546                stopSelectionActionMode();
8547                return true;
8548
8549            case ID_COPY:
8550                setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max)));
8551                stopSelectionActionMode();
8552                return true;
8553        }
8554        return false;
8555    }
8556
8557    /**
8558     * Prepare text so that there are not zero or two spaces at beginning and end of region defined
8559     * by [min, max] when replacing this region by paste.
8560     * Note that if there were two spaces (or more) at that position before, they are kept. We just
8561     * make sure we do not add an extra one from the paste content.
8562     */
8563    private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) {
8564        if (paste.length() > 0) {
8565            if (min > 0) {
8566                final char charBefore = mTransformed.charAt(min - 1);
8567                final char charAfter = paste.charAt(0);
8568
8569                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
8570                    // Two spaces at beginning of paste: remove one
8571                    final int originalLength = mText.length();
8572                    ((Editable) mText).delete(min - 1, min);
8573                    // Due to filters, there is no guarantee that exactly one character was
8574                    // removed: count instead.
8575                    final int delta = mText.length() - originalLength;
8576                    min += delta;
8577                    max += delta;
8578                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
8579                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
8580                    // No space at beginning of paste: add one
8581                    final int originalLength = mText.length();
8582                    ((Editable) mText).replace(min, min, " ");
8583                    // Taking possible filters into account as above.
8584                    final int delta = mText.length() - originalLength;
8585                    min += delta;
8586                    max += delta;
8587                }
8588            }
8589
8590            if (max < mText.length()) {
8591                final char charBefore = paste.charAt(paste.length() - 1);
8592                final char charAfter = mTransformed.charAt(max);
8593
8594                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
8595                    // Two spaces at end of paste: remove one
8596                    ((Editable) mText).delete(max, max + 1);
8597                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
8598                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
8599                    // No space at end of paste: add one
8600                    ((Editable) mText).replace(max, max, " ");
8601                }
8602            }
8603        }
8604
8605        return packRangeInLong(min, max);
8606    }
8607
8608    private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) {
8609        TextView shadowView = (TextView) inflate(mContext,
8610                com.android.internal.R.layout.text_drag_thumbnail, null);
8611
8612        if (shadowView == null) {
8613            throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
8614        }
8615
8616        if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) {
8617            text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH);
8618        }
8619        shadowView.setText(text);
8620        shadowView.setTextColor(getTextColors());
8621
8622        shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge);
8623        shadowView.setGravity(Gravity.CENTER);
8624
8625        shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
8626                ViewGroup.LayoutParams.WRAP_CONTENT));
8627
8628        final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
8629        shadowView.measure(size, size);
8630
8631        shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
8632        shadowView.invalidate();
8633        return new DragShadowBuilder(shadowView);
8634    }
8635
8636    private static class DragLocalState {
8637        public TextView sourceTextView;
8638        public int start, end;
8639
8640        public DragLocalState(TextView sourceTextView, int start, int end) {
8641            this.sourceTextView = sourceTextView;
8642            this.start = start;
8643            this.end = end;
8644        }
8645    }
8646
8647    @Override
8648    public boolean performLongClick() {
8649        if (super.performLongClick()) {
8650            mDiscardNextActionUp = true;
8651            return true;
8652        }
8653
8654        boolean handled = false;
8655
8656        // Long press in empty space moves cursor and shows the Paste affordance if available.
8657        if (!isPositionOnText(mLastDownPositionX, mLastDownPositionY) &&
8658                mInsertionControllerEnabled) {
8659            final int offset = getOffsetForPosition(mLastDownPositionX, mLastDownPositionY);
8660            stopSelectionActionMode();
8661            Selection.setSelection((Spannable) mText, offset);
8662            getInsertionController().showWithPaste();
8663            handled = true;
8664        }
8665
8666        if (!handled && mSelectionActionMode != null) {
8667            if (touchPositionIsInSelection()) {
8668                // Start a drag
8669                final int start = getSelectionStart();
8670                final int end = getSelectionEnd();
8671                CharSequence selectedText = mTransformed.subSequence(start, end);
8672                ClipData data = ClipData.newPlainText(null, selectedText);
8673                DragLocalState localState = new DragLocalState(this, start, end);
8674                startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0);
8675                stopSelectionActionMode();
8676            } else {
8677                selectCurrentWord();
8678            }
8679            handled = true;
8680        }
8681
8682        // Start a new selection
8683        handled |= !handled && startSelectionActionMode();
8684
8685        if (handled) {
8686            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
8687            mDiscardNextActionUp = true;
8688        }
8689
8690        return handled;
8691    }
8692
8693    private boolean touchPositionIsInSelection() {
8694        int selectionStart = getSelectionStart();
8695        int selectionEnd = getSelectionEnd();
8696
8697        if (selectionStart == selectionEnd) {
8698            return false;
8699        }
8700
8701        if (selectionStart > selectionEnd) {
8702            int tmp = selectionStart;
8703            selectionStart = selectionEnd;
8704            selectionEnd = tmp;
8705            Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
8706        }
8707
8708        SelectionModifierCursorController selectionController = getSelectionController();
8709        int minOffset = selectionController.getMinTouchOffset();
8710        int maxOffset = selectionController.getMaxTouchOffset();
8711
8712        return ((minOffset >= selectionStart) && (maxOffset < selectionEnd));
8713    }
8714
8715    private static class SuggestionRangeSpan extends UnderlineSpan {
8716        // TODO themable, would be nice to make it a child class of TextAppearanceSpan, but
8717        // there is no way to have underline and TextAppearanceSpan.
8718    }
8719
8720    private class SuggestionsPopupWindow implements OnClickListener {
8721        private static final int MAX_NUMBER_SUGGESTIONS = 5;
8722        private static final int NO_SUGGESTIONS = -1;
8723        private final PopupWindow mContainer;
8724        private final ViewGroup[] mSuggestionViews = new ViewGroup[2];
8725        private final int[] mSuggestionViewLayouts = new int[] {
8726                mTextEditSuggestionsBottomWindowLayout, mTextEditSuggestionsTopWindowLayout};
8727        private WordIterator mSuggestionWordIterator;
8728        private TextAppearanceSpan[] mHighlightSpans = new TextAppearanceSpan[0];
8729
8730        public SuggestionsPopupWindow() {
8731            mContainer = new PopupWindow(TextView.this.mContext, null,
8732                    com.android.internal.R.attr.textSuggestionsWindowStyle);
8733            mContainer.setSplitTouchEnabled(true);
8734            mContainer.setClippingEnabled(false);
8735            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
8736
8737            mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
8738            mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
8739        }
8740
8741        private class SuggestionInfo {
8742            int suggestionStart, suggestionEnd; // range of suggestion item with replacement text
8743            int spanStart, spanEnd; // range in TextView where text should be inserted
8744            SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents
8745            int suggestionIndex; // the index of the suggestion inside suggestionSpan
8746        }
8747
8748        private ViewGroup getViewGroup(boolean under) {
8749            final int viewIndex = under ? 0 : 1;
8750            ViewGroup viewGroup = mSuggestionViews[viewIndex];
8751
8752            if (viewGroup == null) {
8753                final int layout = mSuggestionViewLayouts[viewIndex];
8754                LayoutInflater inflater = (LayoutInflater) TextView.this.mContext.
8755                        getSystemService(Context.LAYOUT_INFLATER_SERVICE);
8756
8757                if (inflater == null) {
8758                    throw new IllegalArgumentException(
8759                            "Unable to create TextEdit suggestion window inflater");
8760                }
8761
8762                View view = inflater.inflate(layout, null);
8763
8764                if (! (view instanceof ViewGroup)) {
8765                    throw new IllegalArgumentException(
8766                            "Inflated TextEdit suggestion window is not a ViewGroup: " + view);
8767                }
8768
8769                viewGroup = (ViewGroup) view;
8770
8771                // Inflate the suggestion items once and for all.
8772                for (int i = 0; i < MAX_NUMBER_SUGGESTIONS; i++) {
8773                    View childView = inflater.inflate(mTextEditSuggestionItemLayout, viewGroup,
8774                            false);
8775
8776                    if (! (childView instanceof TextView)) {
8777                        throw new IllegalArgumentException(
8778                               "Inflated TextEdit suggestion item is not a TextView: " + childView);
8779                    }
8780
8781                    childView.setTag(new SuggestionInfo());
8782                    viewGroup.addView(childView);
8783                    childView.setOnClickListener(this);
8784                }
8785
8786                mSuggestionViews[viewIndex] = viewGroup;
8787            }
8788
8789            return viewGroup;
8790        }
8791
8792        public void show() {
8793            if (!(mText instanceof Editable)) return;
8794
8795            final int pos = TextView.this.getSelectionStart();
8796            Spannable spannable = (Spannable)TextView.this.mText;
8797            SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class);
8798            final int nbSpans = suggestionSpans.length;
8799
8800            ViewGroup viewGroup = getViewGroup(true);
8801            mContainer.setContentView(viewGroup);
8802
8803            int totalNbSuggestions = 0;
8804            int spanUnionStart = mText.length();
8805            int spanUnionEnd = 0;
8806
8807            for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) {
8808                SuggestionSpan suggestionSpan = suggestionSpans[spanIndex];
8809                final int spanStart = spannable.getSpanStart(suggestionSpan);
8810                final int spanEnd = spannable.getSpanEnd(suggestionSpan);
8811                spanUnionStart = Math.min(spanStart, spanUnionStart);
8812                spanUnionEnd = Math.max(spanEnd, spanUnionEnd);
8813
8814                String[] suggestions = suggestionSpan.getSuggestions();
8815                int nbSuggestions = suggestions.length;
8816                for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) {
8817                    TextView textView = (TextView) viewGroup.getChildAt(totalNbSuggestions);
8818                    textView.setText(suggestions[suggestionIndex]);
8819                    SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag();
8820                    suggestionInfo.spanStart = spanStart;
8821                    suggestionInfo.spanEnd = spanEnd;
8822                    suggestionInfo.suggestionSpan = suggestionSpan;
8823                    suggestionInfo.suggestionIndex = suggestionIndex;
8824
8825                    totalNbSuggestions++;
8826                    if (totalNbSuggestions == MAX_NUMBER_SUGGESTIONS) {
8827                        // Also end outer for loop
8828                        spanIndex = nbSpans;
8829                        break;
8830                    }
8831                }
8832            }
8833
8834            if (totalNbSuggestions == 0) {
8835                // TODO Replace by final text, use a dedicated layout, add a fade out timer...
8836                TextView textView = (TextView) viewGroup.getChildAt(0);
8837                textView.setText("No suggestions available");
8838                SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag();
8839                suggestionInfo.spanStart = NO_SUGGESTIONS;
8840                totalNbSuggestions++;
8841            } else {
8842                if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan();
8843                ((Editable) mText).setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd,
8844                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
8845
8846                for (int i = 0; i < totalNbSuggestions; i++) {
8847                    final TextView textView = (TextView) viewGroup.getChildAt(i);
8848                    highlightTextDifferences(textView, spanUnionStart, spanUnionEnd);
8849                }
8850            }
8851
8852            for (int i = 0; i < MAX_NUMBER_SUGGESTIONS; i++) {
8853                viewGroup.getChildAt(i).setVisibility(i < totalNbSuggestions ? VISIBLE : GONE);
8854            }
8855
8856            final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
8857            viewGroup.measure(size, size);
8858
8859            positionAtCursor();
8860        }
8861
8862        private long[] getWordLimits(CharSequence text) {
8863            // TODO locale for mSuggestionWordIterator
8864            if (mSuggestionWordIterator == null) mSuggestionWordIterator = new WordIterator();
8865            mSuggestionWordIterator.setCharSequence(text);
8866
8867            // First pass will simply count the number of words to be able to create an array
8868            // Not too expensive since previous break positions are cached by the BreakIterator
8869            int nbWords = 0;
8870            int position = mSuggestionWordIterator.following(0);
8871            while (position != BreakIterator.DONE) {
8872                nbWords++;
8873                position = mSuggestionWordIterator.following(position);
8874            }
8875
8876            int index = 0;
8877            long[] result = new long[nbWords];
8878
8879            position = mSuggestionWordIterator.following(0);
8880            while (position != BreakIterator.DONE) {
8881                int wordStart = mSuggestionWordIterator.getBeginning(position);
8882                result[index++] = packRangeInLong(wordStart, position);
8883                position = mSuggestionWordIterator.following(position);
8884            }
8885
8886            return result;
8887        }
8888
8889        private TextAppearanceSpan highlightSpan(int index) {
8890            final int length = mHighlightSpans.length;
8891            if (index < length) {
8892                return mHighlightSpans[index];
8893            }
8894
8895            // Assumes indexes are requested in sequence: simply append one more item
8896            TextAppearanceSpan[] newArray = new TextAppearanceSpan[length + 1];
8897            System.arraycopy(mHighlightSpans, 0, newArray, 0, length);
8898            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mContext,
8899                    android.R.style.TextAppearance_SuggestionHighlight);
8900            newArray[length] = highlightSpan;
8901            mHighlightSpans = newArray;
8902            return highlightSpan;
8903        }
8904
8905        private void highlightTextDifferences(TextView textView, int unionStart, int unionEnd) {
8906            SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag();
8907            final int spanStart = suggestionInfo.spanStart;
8908            final int spanEnd = suggestionInfo.spanEnd;
8909
8910            // Remove all text formating by converting to Strings
8911            final String text = textView.getText().toString();
8912            final String sourceText = mText.subSequence(spanStart, spanEnd).toString();
8913
8914            long[] sourceWordLimits = getWordLimits(sourceText);
8915            long[] wordLimits = getWordLimits(text);
8916
8917            SpannableStringBuilder ssb = new SpannableStringBuilder();
8918            // span [spanStart, spanEnd] is included in union [spanUnionStart, int spanUnionEnd]
8919            // The final result is made of 3 parts: the text before, between and after the span
8920            // This is the text before, provided for context
8921            ssb.append(mText.subSequence(unionStart, spanStart).toString());
8922
8923            // shift is used to offset spans positions wrt span's beginning
8924            final int shift = spanStart - unionStart;
8925            suggestionInfo.suggestionStart = shift;
8926            suggestionInfo.suggestionEnd = shift + text.length();
8927
8928            // This is the actual suggestion text, which will be highlighted by the following code
8929            ssb.append(text);
8930
8931            String[] words = new String[wordLimits.length];
8932            for (int i = 0; i < wordLimits.length; i++) {
8933                int wordStart = extractRangeStartFromLong(wordLimits[i]);
8934                int wordEnd = extractRangeEndFromLong(wordLimits[i]);
8935                words[i] = text.substring(wordStart, wordEnd);
8936            }
8937
8938            // Highlighted word algorithm is based on word matching between source and text
8939            // Matching words are found from left to right. TODO: change for RTL languages
8940            // Characters between matching words are highlighted
8941            int previousCommonWordIndex = -1;
8942            int nbHighlightSpans = 0;
8943            for (int i = 0; i < sourceWordLimits.length; i++) {
8944                int wordStart = extractRangeStartFromLong(sourceWordLimits[i]);
8945                int wordEnd = extractRangeEndFromLong(sourceWordLimits[i]);
8946                String sourceWord = sourceText.substring(wordStart, wordEnd);
8947
8948                for (int j = previousCommonWordIndex + 1; j < words.length; j++) {
8949                    if (sourceWord.equals(words[j])) {
8950                        if (j != previousCommonWordIndex + 1) {
8951                            int firstDifferentPosition = previousCommonWordIndex < 0 ? 0 :
8952                                extractRangeEndFromLong(wordLimits[previousCommonWordIndex]);
8953                            int lastDifferentPosition = extractRangeStartFromLong(wordLimits[j]);
8954                            ssb.setSpan(highlightSpan(nbHighlightSpans++),
8955                                    shift + firstDifferentPosition, shift + lastDifferentPosition,
8956                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
8957                        } else {
8958                            // Compare characters between words
8959                            int previousSourceWordEnd = i == 0 ? 0 :
8960                                extractRangeEndFromLong(sourceWordLimits[i - 1]);
8961                            int sourceWordStart = extractRangeStartFromLong(sourceWordLimits[i]);
8962                            String sourceSpaces = sourceText.substring(previousSourceWordEnd,
8963                                    sourceWordStart);
8964
8965                            int previousWordEnd = j == 0 ? 0 :
8966                                extractRangeEndFromLong(wordLimits[j - 1]);
8967                            int currentWordStart = extractRangeStartFromLong(wordLimits[j]);
8968                            String textSpaces = text.substring(previousWordEnd, currentWordStart);
8969
8970                            if (!sourceSpaces.equals(textSpaces)) {
8971                                ssb.setSpan(highlightSpan(nbHighlightSpans++),
8972                                        shift + previousWordEnd, shift + currentWordStart,
8973                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
8974                            }
8975                        }
8976                        previousCommonWordIndex = j;
8977                        break;
8978                    }
8979                }
8980            }
8981
8982            // Finally, compare ends of Strings
8983            if (previousCommonWordIndex < words.length - 1) {
8984                int firstDifferentPosition = previousCommonWordIndex < 0 ? 0 :
8985                    extractRangeEndFromLong(wordLimits[previousCommonWordIndex]);
8986                int lastDifferentPosition = textView.length();
8987                ssb.setSpan(highlightSpan(nbHighlightSpans++),
8988                        shift + firstDifferentPosition, shift + lastDifferentPosition,
8989                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
8990            } else {
8991                int lastSourceWordEnd = sourceWordLimits.length == 0 ? 0 :
8992                    extractRangeEndFromLong(sourceWordLimits[sourceWordLimits.length - 1]);
8993                String sourceSpaces = sourceText.substring(lastSourceWordEnd, sourceText.length());
8994
8995                int lastCommonTextWordEnd = previousCommonWordIndex < 0 ? 0 :
8996                    extractRangeEndFromLong(wordLimits[previousCommonWordIndex]);
8997                String textSpaces = text.substring(lastCommonTextWordEnd, textView.length());
8998
8999                if (!sourceSpaces.equals(textSpaces) && textSpaces.length() > 0) {
9000                    ssb.setSpan(highlightSpan(nbHighlightSpans++),
9001                            shift + lastCommonTextWordEnd, shift + textView.length(),
9002                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
9003                }
9004            }
9005
9006            // Final part, text after the current suggestion range.
9007            ssb.append(mText.subSequence(spanEnd, unionEnd).toString());
9008            textView.setText(ssb);
9009        }
9010
9011        public void hide() {
9012            if ((mText instanceof Editable) && mSuggestionRangeSpan != null) {
9013                ((Editable) mText).removeSpan(mSuggestionRangeSpan);
9014            }
9015            mContainer.dismiss();
9016        }
9017
9018        @Override
9019        public void onClick(View view) {
9020            if (view instanceof TextView) {
9021                TextView textView = (TextView) view;
9022                SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag();
9023                final int spanStart = suggestionInfo.spanStart;
9024                final int spanEnd = suggestionInfo.spanEnd;
9025                if (spanStart != NO_SUGGESTIONS) {
9026                    // SuggestionSpans are removed by replace: save them before
9027                    Editable editable = ((Editable) mText);
9028                    SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd,
9029                            SuggestionSpan.class);
9030                    final int length = suggestionSpans.length;
9031                    int[] suggestionSpansStarts = new int[length];
9032                    int[] suggestionSpansEnds = new int[length];
9033                    int[] suggestionSpansFlags = new int[length];
9034                    for (int i = 0; i < length; i++) {
9035                        final SuggestionSpan suggestionSpan = suggestionSpans[i];
9036                        suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan);
9037                        suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan);
9038                        suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan);
9039                    }
9040
9041                    final int suggestionStart = suggestionInfo.suggestionStart;
9042                    final int suggestionEnd = suggestionInfo.suggestionEnd;
9043                    final String suggestion = textView.getText().subSequence(
9044                            suggestionStart, suggestionEnd).toString();
9045                    final String originalText = mText.subSequence(spanStart, spanEnd).toString();
9046                    ((Editable) mText).replace(spanStart, spanEnd, suggestion);
9047
9048                    // Notify source IME of the suggestion pick. Do this before swaping texts.
9049                    if (!TextUtils.isEmpty(
9050                            suggestionInfo.suggestionSpan.getNotificationTargetClassName())) {
9051                        InputMethodManager imm = InputMethodManager.peekInstance();
9052                        imm.notifySuggestionPicked(suggestionInfo.suggestionSpan, originalText,
9053                                suggestionInfo.suggestionIndex);
9054                    }
9055
9056                    // Swap text content between actual text and Suggestion span
9057                    String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions();
9058                    suggestions[suggestionInfo.suggestionIndex] = originalText;
9059
9060                    // Restore previous SuggestionSpans
9061                    final int lengthDifference = suggestion.length() - (spanEnd - spanStart);
9062                    for (int i = 0; i < length; i++) {
9063                        // Only spans that include the modified region make sense after replacement
9064                        // Spans partially included in the replaced region are removed, there is no
9065                        // way to assign them a valid range after replacement
9066                        if (suggestionSpansStarts[i] <= spanStart &&
9067                                suggestionSpansEnds[i] >= spanEnd) {
9068                            editable.setSpan(suggestionSpans[i], suggestionSpansStarts[i],
9069                                    suggestionSpansEnds[i] + lengthDifference,
9070                                    suggestionSpansFlags[i]);
9071                        }
9072                    }
9073                }
9074            }
9075            hide();
9076        }
9077
9078        void positionAtCursor() {
9079            View contentView = mContainer.getContentView();
9080            int width = contentView.getMeasuredWidth();
9081            int height = contentView.getMeasuredHeight();
9082            final int offset = TextView.this.getSelectionStart();
9083            final int line = mLayout.getLineForOffset(offset);
9084            final int lineBottom = mLayout.getLineBottom(line);
9085            float primaryHorizontal = mLayout.getPrimaryHorizontal(offset);
9086
9087            final Rect bounds = sCursorControllerTempRect;
9088            bounds.left = (int) (primaryHorizontal - width / 2.0f);
9089            bounds.top = lineBottom;
9090
9091            bounds.right = bounds.left + width;
9092            bounds.bottom = bounds.top + height;
9093
9094            convertFromViewportToContentCoordinates(bounds);
9095
9096            final int[] coords = mTempCoords;
9097            TextView.this.getLocationInWindow(coords);
9098            coords[0] += bounds.left;
9099            coords[1] += bounds.top;
9100
9101            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
9102            final int screenHeight = displayMetrics.heightPixels;
9103
9104            // Vertical clipping
9105            if (coords[1] + height > screenHeight) {
9106                // Try to position above current line instead
9107                // TODO use top layout instead, reverse suggestion order,
9108                // try full screen vertical down if it still does not fit. TBD with designers.
9109
9110                // Update dimensions from new view
9111                contentView = mContainer.getContentView();
9112                width = contentView.getMeasuredWidth();
9113                height = contentView.getMeasuredHeight();
9114
9115                final int lineTop = mLayout.getLineTop(line);
9116                final int lineHeight = lineBottom - lineTop;
9117                coords[1] -= height + lineHeight;
9118            }
9119
9120            // Horizontal clipping
9121            coords[0] = Math.max(0, coords[0]);
9122            coords[0] = Math.min(displayMetrics.widthPixels - width, coords[0]);
9123
9124            mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]);
9125        }
9126    }
9127
9128    void showSuggestions() {
9129        if (!mSuggestionsEnabled || !isTextEditable()) return;
9130
9131        if (mSuggestionsPopupWindow == null) {
9132            mSuggestionsPopupWindow = new SuggestionsPopupWindow();
9133        }
9134        hideControllers();
9135        mSuggestionsPopupWindow.show();
9136    }
9137
9138    void hideSuggestions() {
9139        if (mSuggestionsPopupWindow != null) {
9140            mSuggestionsPopupWindow.hide();
9141        }
9142    }
9143
9144    /**
9145     * Some parts of the text can have alternate suggestion text attached. This is typically done by
9146     * the IME by adding {@link SuggestionSpan}s to the text.
9147     *
9148     * When suggestions are enabled (default), this list of suggestions will be displayed when the
9149     * user double taps on these parts of the text. No suggestions are displayed when this value is
9150     * false. Use {@link #setSuggestionsEnabled(boolean)} to change this value.
9151     *
9152     * @return true if the suggestions popup window is enabled.
9153     *
9154     * @attr ref android.R.styleable#TextView_suggestionsEnabled
9155     */
9156    public boolean isSuggestionsEnabled() {
9157        return mSuggestionsEnabled;
9158    }
9159
9160    /**
9161     * Enables or disables the suggestion popup. See {@link #isSuggestionsEnabled()}.
9162     *
9163     * @param enabled Whether or not suggestions are enabled.
9164     */
9165    public void setSuggestionsEnabled(boolean enabled) {
9166        mSuggestionsEnabled = enabled;
9167    }
9168
9169    /**
9170     * If provided, this ActionMode.Callback will be used to create the ActionMode when text
9171     * selection is initiated in this View.
9172     *
9173     * The standard implementation populates the menu with a subset of Select All, Cut, Copy and
9174     * Paste actions, depending on what this View supports.
9175     *
9176     * A custom implementation can add new entries in the default menu in its
9177     * {@link ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The default actions
9178     * can also be removed from the menu using {@link Menu#removeItem(int)} and passing
9179     * {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} or
9180     * {@link android.R.id#paste} ids as parameters.
9181     *
9182     * Returning false from {@link ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will
9183     * prevent the action mode from being started.
9184     *
9185     * Action click events should be handled by the custom implementation of
9186     * {@link ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}.
9187     *
9188     * Note that text selection mode is not started when a TextView receives focus and the
9189     * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in
9190     * that case, to allow for quick replacement.
9191     */
9192    public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) {
9193        mCustomSelectionActionModeCallback = actionModeCallback;
9194    }
9195
9196    /**
9197     * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null.
9198     *
9199     * @return The current custom selection callback.
9200     */
9201    public ActionMode.Callback getCustomSelectionActionModeCallback() {
9202        return mCustomSelectionActionModeCallback;
9203    }
9204
9205    /**
9206     *
9207     * @return true if the selection mode was actually started.
9208     */
9209    private boolean startSelectionActionMode() {
9210        if (mSelectionActionMode != null) {
9211            // Selection action mode is already started
9212            return false;
9213        }
9214
9215        if (!canSelectText() || !requestFocus()) {
9216            Log.w(LOG_TAG, "TextView does not support text selection. Action mode cancelled.");
9217            return false;
9218        }
9219
9220        if (!hasSelection()) {
9221            // There may already be a selection on device rotation
9222            boolean currentWordSelected = selectCurrentWord();
9223            if (!currentWordSelected) {
9224                // No word found under cursor or text selection not permitted.
9225                return false;
9226            }
9227        }
9228
9229        ActionMode.Callback actionModeCallback = new SelectionActionModeCallback();
9230        mSelectionActionMode = startActionMode(actionModeCallback);
9231        final boolean selectionStarted = mSelectionActionMode != null;
9232
9233        if (selectionStarted && !mTextIsSelectable) {
9234            // Show the IME to be able to replace text, except when selecting non editable text.
9235            final InputMethodManager imm = InputMethodManager.peekInstance();
9236            if (imm != null) imm.showSoftInput(this, 0, null);
9237        }
9238
9239        return selectionStarted;
9240    }
9241
9242    private void stopSelectionActionMode() {
9243        if (mSelectionActionMode != null) {
9244            // This will hide the mSelectionModifierCursorController
9245            mSelectionActionMode.finish();
9246        }
9247    }
9248
9249    /**
9250     * Paste clipboard content between min and max positions.
9251     */
9252    private void paste(int min, int max) {
9253        ClipboardManager clipboard =
9254            (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
9255        ClipData clip = clipboard.getPrimaryClip();
9256        if (clip != null) {
9257            boolean didFirst = false;
9258            for (int i=0; i<clip.getItemCount(); i++) {
9259                CharSequence paste = clip.getItemAt(i).coerceToText(getContext());
9260                if (paste != null) {
9261                    if (!didFirst) {
9262                        long minMax = prepareSpacesAroundPaste(min, max, paste);
9263                        min = extractRangeStartFromLong(minMax);
9264                        max = extractRangeEndFromLong(minMax);
9265                        Selection.setSelection((Spannable) mText, max);
9266                        ((Editable) mText).replace(min, max, paste);
9267                        didFirst = true;
9268                    } else {
9269                        ((Editable) mText).insert(getSelectionEnd(), "\n");
9270                        ((Editable) mText).insert(getSelectionEnd(), paste);
9271                    }
9272                }
9273            }
9274            stopSelectionActionMode();
9275            sLastCutOrCopyTime = 0;
9276        }
9277    }
9278
9279    private void setPrimaryClip(ClipData clip) {
9280        ClipboardManager clipboard = (ClipboardManager) getContext().
9281                getSystemService(Context.CLIPBOARD_SERVICE);
9282        clipboard.setPrimaryClip(clip);
9283        sLastCutOrCopyTime = SystemClock.uptimeMillis();
9284    }
9285
9286    /**
9287     * An ActionMode Callback class that is used to provide actions while in text selection mode.
9288     *
9289     * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending
9290     * on which of these this TextView supports.
9291     */
9292    private class SelectionActionModeCallback implements ActionMode.Callback {
9293
9294        @Override
9295        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
9296            TypedArray styledAttributes = mContext.obtainStyledAttributes(R.styleable.Theme);
9297
9298            boolean allowText = getContext().getResources().getBoolean(
9299                    com.android.internal.R.bool.config_allowActionMenuItemTextWithIcon);
9300
9301            mode.setTitle(allowText ?
9302                    mContext.getString(com.android.internal.R.string.textSelectionCABTitle) : null);
9303            mode.setSubtitle(null);
9304
9305            int selectAllIconId = 0; // No icon by default
9306            if (!allowText) {
9307                // Provide an icon, text will not be displayed on smaller screens.
9308                selectAllIconId = styledAttributes.getResourceId(
9309                        R.styleable.Theme_actionModeSelectAllDrawable, 0);
9310            }
9311
9312            menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll).
9313                    setIcon(selectAllIconId).
9314                    setAlphabeticShortcut('a').
9315                    setShowAsAction(
9316                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
9317
9318            if (canCut()) {
9319                menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut).
9320                    setIcon(styledAttributes.getResourceId(
9321                            R.styleable.Theme_actionModeCutDrawable, 0)).
9322                    setAlphabeticShortcut('x').
9323                    setShowAsAction(
9324                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
9325            }
9326
9327            if (canCopy()) {
9328                menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy).
9329                    setIcon(styledAttributes.getResourceId(
9330                            R.styleable.Theme_actionModeCopyDrawable, 0)).
9331                    setAlphabeticShortcut('c').
9332                    setShowAsAction(
9333                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
9334            }
9335
9336            if (canPaste()) {
9337                menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste).
9338                        setIcon(styledAttributes.getResourceId(
9339                                R.styleable.Theme_actionModePasteDrawable, 0)).
9340                        setAlphabeticShortcut('v').
9341                        setShowAsAction(
9342                                MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
9343            }
9344
9345            styledAttributes.recycle();
9346
9347            if (mCustomSelectionActionModeCallback != null) {
9348                if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) {
9349                    // The custom mode can choose to cancel the action mode
9350                    return false;
9351                }
9352            }
9353
9354            if (menu.hasVisibleItems() || mode.getCustomView() != null) {
9355                getSelectionController().show();
9356                return true;
9357            } else {
9358                return false;
9359            }
9360        }
9361
9362        @Override
9363        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
9364            if (mCustomSelectionActionModeCallback != null) {
9365                return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu);
9366            }
9367            return true;
9368        }
9369
9370        @Override
9371        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
9372            if (mCustomSelectionActionModeCallback != null &&
9373                 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) {
9374                return true;
9375            }
9376            return onTextContextMenuItem(item.getItemId());
9377        }
9378
9379        @Override
9380        public void onDestroyActionMode(ActionMode mode) {
9381            if (mCustomSelectionActionModeCallback != null) {
9382                mCustomSelectionActionModeCallback.onDestroyActionMode(mode);
9383            }
9384            Selection.setSelection((Spannable) mText, getSelectionEnd());
9385
9386            if (mSelectionModifierCursorController != null) {
9387                mSelectionModifierCursorController.hide();
9388            }
9389
9390            mSelectionActionMode = null;
9391        }
9392    }
9393
9394    private class PastePopupWindow implements OnClickListener {
9395        private final PopupWindow mContainer;
9396        private final View[] mPasteViews = new View[4];
9397        private final int[] mPasteViewLayouts = new int[] {
9398                mTextEditPasteWindowLayout,  mTextEditNoPasteWindowLayout,
9399                mTextEditSidePasteWindowLayout, mTextEditSideNoPasteWindowLayout };
9400
9401        public PastePopupWindow() {
9402            mContainer = new PopupWindow(TextView.this.mContext, null,
9403                    com.android.internal.R.attr.textSelectHandleWindowStyle);
9404            mContainer.setSplitTouchEnabled(true);
9405            mContainer.setClippingEnabled(false);
9406            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
9407
9408            mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
9409            mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
9410        }
9411
9412        private int viewIndex(boolean onTop) {
9413            return (onTop ? 0 : 1<<1) + (canPaste() ? 0 : 1<<0);
9414        }
9415
9416        private void updateContent(boolean onTop) {
9417            final int viewIndex = viewIndex(onTop);
9418            View view = mPasteViews[viewIndex];
9419
9420            if (view == null) {
9421                final int layout = mPasteViewLayouts[viewIndex];
9422                LayoutInflater inflater = (LayoutInflater)TextView.this.mContext.
9423                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
9424                if (inflater != null) {
9425                    view = inflater.inflate(layout, null);
9426                }
9427
9428                if (view == null) {
9429                    throw new IllegalArgumentException("Unable to inflate TextEdit paste window");
9430                }
9431
9432                final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
9433                view.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
9434                        ViewGroup.LayoutParams.WRAP_CONTENT));
9435                view.measure(size, size);
9436
9437                view.setOnClickListener(this);
9438
9439                mPasteViews[viewIndex] = view;
9440            }
9441
9442            mContainer.setContentView(view);
9443        }
9444
9445        public void show() {
9446            updateContent(true);
9447            positionAtCursor();
9448        }
9449
9450        public void hide() {
9451            mContainer.dismiss();
9452        }
9453
9454        public boolean isShowing() {
9455            return mContainer.isShowing();
9456        }
9457
9458        @Override
9459        public void onClick(View v) {
9460            if (canPaste()) {
9461                onTextContextMenuItem(ID_PASTE);
9462            }
9463            hide();
9464        }
9465
9466        void positionAtCursor() {
9467            View contentView = mContainer.getContentView();
9468            int width = contentView.getMeasuredWidth();
9469            int height = contentView.getMeasuredHeight();
9470            final int offset = TextView.this.getSelectionStart();
9471            final int line = mLayout.getLineForOffset(offset);
9472            final int lineTop = mLayout.getLineTop(line);
9473            float primaryHorizontal = mLayout.getPrimaryHorizontal(offset);
9474
9475            final Rect bounds = sCursorControllerTempRect;
9476            bounds.left = (int) (primaryHorizontal - width / 2.0f);
9477            bounds.top = lineTop - height;
9478
9479            bounds.right = bounds.left + width;
9480            bounds.bottom = bounds.top + height;
9481
9482            convertFromViewportToContentCoordinates(bounds);
9483
9484            final int[] coords = mTempCoords;
9485            TextView.this.getLocationInWindow(coords);
9486            coords[0] += bounds.left;
9487            coords[1] += bounds.top;
9488
9489            final int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels;
9490            if (coords[1] < 0) {
9491                updateContent(false);
9492                // Update dimensions from new view
9493                contentView = mContainer.getContentView();
9494                width = contentView.getMeasuredWidth();
9495                height = contentView.getMeasuredHeight();
9496
9497                // Vertical clipping, move under edited line and to the side of insertion cursor
9498                // TODO bottom clipping in case there is no system bar
9499                coords[1] += height;
9500                final int lineBottom = mLayout.getLineBottom(line);
9501                final int lineHeight = lineBottom - lineTop;
9502                coords[1] += lineHeight;
9503
9504                // Move to right hand side of insertion cursor by default. TODO RTL text.
9505                final Drawable handle = mContext.getResources().getDrawable(mTextSelectHandleRes);
9506                final int handleHalfWidth = handle.getIntrinsicWidth() / 2;
9507
9508                if (primaryHorizontal + handleHalfWidth + width < screenWidth) {
9509                    coords[0] += handleHalfWidth + width / 2;
9510                } else {
9511                    coords[0] -= handleHalfWidth + width / 2;
9512                }
9513            } else {
9514                // Horizontal clipping
9515                coords[0] = Math.max(0, coords[0]);
9516                coords[0] = Math.min(screenWidth - width, coords[0]);
9517            }
9518
9519            mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]);
9520        }
9521    }
9522
9523    private abstract class HandleView extends View implements ViewTreeObserver.OnPreDrawListener {
9524        protected Drawable mDrawable;
9525        private final PopupWindow mContainer;
9526        // Position with respect to the parent TextView
9527        private int mPositionX, mPositionY;
9528        private boolean mIsDragging;
9529        // Offset from touch position to mPosition
9530        private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
9531        protected float mHotspotX;
9532        // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
9533        private float mTouchOffsetY;
9534        // Where the touch position should be on the handle to ensure a maximum cursor visibility
9535        private float mIdealVerticalOffset;
9536        // Parent's (TextView) previous position in window
9537        private int mLastParentX, mLastParentY;
9538        // PopupWindow container absolute position with respect to the enclosing window
9539        private int mContainerPositionX, mContainerPositionY;
9540        // Visible or not (scrolled off screen), whether or not this handle should be visible
9541        private boolean mIsActive = false;
9542        // Used to detect that setFrame was called
9543        private boolean mNeedsUpdate = true;
9544
9545        public HandleView() {
9546            super(TextView.this.mContext);
9547            mContainer = new PopupWindow(TextView.this.mContext, null,
9548                    com.android.internal.R.attr.textSelectHandleWindowStyle);
9549            mContainer.setSplitTouchEnabled(true);
9550            mContainer.setClippingEnabled(false);
9551            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
9552            mContainer.setContentView(this);
9553
9554            initDrawable();
9555
9556            final int handleHeight = mDrawable.getIntrinsicHeight();
9557            mTouchOffsetY = -0.3f * handleHeight;
9558            mIdealVerticalOffset = 0.7f * handleHeight;
9559        }
9560
9561        @Override
9562        protected boolean setFrame(int left, int top, int right, int bottom) {
9563            boolean changed = super.setFrame(left, top, right, bottom);
9564            // onPreDraw is called for PhoneWindow before the layout of this view is
9565            // performed. Make sure to update position, even if container didn't move.
9566            if (changed) mNeedsUpdate  = true;
9567            return changed;
9568        }
9569
9570        protected abstract void initDrawable();
9571
9572        // Touch-up filter: number of previous positions remembered
9573        private static final int HISTORY_SIZE = 5;
9574        private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
9575        private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
9576        private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
9577        private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
9578        private int mPreviousOffsetIndex = 0;
9579        private int mNumberPreviousOffsets = 0;
9580
9581        private void startTouchUpFilter(int offset) {
9582            mNumberPreviousOffsets = 0;
9583            addPositionToTouchUpFilter(offset);
9584        }
9585
9586        private void addPositionToTouchUpFilter(int offset) {
9587            if (mNumberPreviousOffsets > 0 &&
9588                    mPreviousOffsets[mPreviousOffsetIndex] == offset) {
9589                // Make sure only actual changes of position are recorded.
9590                return;
9591            }
9592
9593            mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
9594            mPreviousOffsets[mPreviousOffsetIndex] = offset;
9595            mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
9596            mNumberPreviousOffsets++;
9597        }
9598
9599        private void filterOnTouchUp() {
9600            final long now = SystemClock.uptimeMillis();
9601            int i = 0;
9602            int index = mPreviousOffsetIndex;
9603            final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
9604            while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
9605                i++;
9606                index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
9607            }
9608
9609            if (i > 0 && i < iMax &&
9610                    (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
9611                updateOffset(mPreviousOffsets[index]);
9612            }
9613        }
9614
9615        @Override
9616        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
9617            setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
9618        }
9619
9620        public void show() {
9621            if (isShowing()) {
9622                mContainer.update(mContainerPositionX, mContainerPositionY,
9623                        mRight - mLeft, mBottom - mTop);
9624            } else {
9625                mContainer.showAtLocation(TextView.this, 0,
9626                        mContainerPositionX, mContainerPositionY);
9627
9628                mIsActive = true;
9629
9630                ViewTreeObserver vto = TextView.this.getViewTreeObserver();
9631                vto.addOnPreDrawListener(this);
9632            }
9633        }
9634
9635        protected void dismiss() {
9636            mIsDragging = false;
9637            mContainer.dismiss();
9638        }
9639
9640        public void hide() {
9641            dismiss();
9642
9643            mIsActive = false;
9644
9645            ViewTreeObserver vto = TextView.this.getViewTreeObserver();
9646            vto.removeOnPreDrawListener(this);
9647        }
9648
9649        public boolean isShowing() {
9650            return mContainer.isShowing();
9651        }
9652
9653        private boolean isPositionVisible() {
9654            // Always show a dragging handle.
9655            if (mIsDragging) {
9656                return true;
9657            }
9658
9659            if (isInBatchEditMode()) {
9660                return false;
9661            }
9662
9663            final int extendedPaddingTop = getExtendedPaddingTop();
9664            final int extendedPaddingBottom = getExtendedPaddingBottom();
9665            final int compoundPaddingLeft = getCompoundPaddingLeft();
9666            final int compoundPaddingRight = getCompoundPaddingRight();
9667
9668            final TextView textView = TextView.this;
9669
9670            if (mTempRect == null) mTempRect = new Rect();
9671            final Rect clip = mTempRect;
9672            clip.left = compoundPaddingLeft;
9673            clip.top = extendedPaddingTop;
9674            clip.right = textView.getWidth() - compoundPaddingRight;
9675            clip.bottom = textView.getHeight() - extendedPaddingBottom;
9676
9677            final ViewParent parent = textView.getParent();
9678            if (parent == null || !parent.getChildVisibleRect(textView, clip, null)) {
9679                return false;
9680            }
9681
9682            final int[] coords = mTempCoords;
9683            textView.getLocationInWindow(coords);
9684            final int posX = coords[0] + mPositionX + (int) mHotspotX;
9685            final int posY = coords[1] + mPositionY;
9686
9687            // Offset by 1 to take into account 0.5 and int rounding around getPrimaryHorizontal.
9688            return posX >= clip.left - 1 && posX <= clip.right + 1 &&
9689                    posY >= clip.top && posY <= clip.bottom;
9690        }
9691
9692        public abstract int getCurrentCursorOffset();
9693
9694        public abstract void updateOffset(int offset);
9695
9696        public abstract void updatePosition(float x, float y);
9697
9698        protected void positionAtCursorOffset(int offset) {
9699            // A HandleView relies on the layout, which may be nulled by external methods.
9700            if (mLayout == null) {
9701                // Will update controllers' state, hiding them and stopping selection mode if needed
9702                prepareCursorControllers();
9703                return;
9704            }
9705
9706            addPositionToTouchUpFilter(offset);
9707            final int line = mLayout.getLineForOffset(offset);
9708            final int lineBottom = mLayout.getLineBottom(line);
9709
9710            mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX);
9711            mPositionY = lineBottom;
9712
9713            // Take TextView's padding into account.
9714            mPositionX += viewportToContentHorizontalOffset();
9715            mPositionY += viewportToContentVerticalOffset();
9716        }
9717
9718        private void checkForContainerPositionChange() {
9719            positionAtCursorOffset(getCurrentCursorOffset());
9720
9721            final int previousContainerPositionX = mContainerPositionX;
9722            final int previousContainerPositionY = mContainerPositionY;
9723
9724            TextView.this.getLocationInWindow(mTempCoords);
9725            mContainerPositionX = mTempCoords[0] + mPositionX;
9726            mContainerPositionY = mTempCoords[1] + mPositionY;
9727
9728            mNeedsUpdate |= previousContainerPositionX != mContainerPositionX;
9729            mNeedsUpdate |= previousContainerPositionY != mContainerPositionY;
9730        }
9731
9732        public boolean onPreDraw() {
9733            checkForContainerPositionChange();
9734            if (mNeedsUpdate) {
9735                if (mIsDragging) {
9736                    if (mTempCoords[0] != mLastParentX || mTempCoords[1] != mLastParentY) {
9737                        mTouchToWindowOffsetX += mTempCoords[0] - mLastParentX;
9738                        mTouchToWindowOffsetY += mTempCoords[1] - mLastParentY;
9739                        mLastParentX = mTempCoords[0];
9740                        mLastParentY = mTempCoords[1];
9741                    }
9742                }
9743
9744                onHandleMoved();
9745
9746                if (isPositionVisible()) {
9747                    mContainer.update(mContainerPositionX, mContainerPositionY,
9748                            mRight - mLeft, mBottom - mTop);
9749
9750                    if (mIsActive && !isShowing()) {
9751                        show();
9752                    }
9753                } else {
9754                    if (isShowing()) {
9755                        dismiss();
9756                    }
9757                }
9758                mNeedsUpdate = false;
9759            }
9760            return true;
9761        }
9762
9763        @Override
9764        protected void onDraw(Canvas c) {
9765            mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
9766            mDrawable.draw(c);
9767        }
9768
9769        @Override
9770        public boolean onTouchEvent(MotionEvent ev) {
9771            switch (ev.getActionMasked()) {
9772                case MotionEvent.ACTION_DOWN: {
9773                    startTouchUpFilter(getCurrentCursorOffset());
9774                    mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
9775                    mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
9776
9777                    final int[] coords = mTempCoords;
9778                    TextView.this.getLocationInWindow(coords);
9779                    mLastParentX = coords[0];
9780                    mLastParentY = coords[1];
9781                    mIsDragging = true;
9782                    break;
9783                }
9784
9785                case MotionEvent.ACTION_MOVE: {
9786                    final float rawX = ev.getRawX();
9787                    final float rawY = ev.getRawY();
9788
9789                    // Vertical hysteresis: vertical down movement tends to snap to ideal offset
9790                    final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
9791                    final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
9792                    float newVerticalOffset;
9793                    if (previousVerticalOffset < mIdealVerticalOffset) {
9794                        newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
9795                        newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
9796                    } else {
9797                        newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
9798                        newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
9799                    }
9800                    mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
9801
9802                    final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX;
9803                    final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
9804
9805                    updatePosition(newPosX, newPosY);
9806                    break;
9807                }
9808
9809                case MotionEvent.ACTION_UP:
9810                    filterOnTouchUp();
9811                    mIsDragging = false;
9812                    break;
9813
9814                case MotionEvent.ACTION_CANCEL:
9815                    mIsDragging = false;
9816                    break;
9817            }
9818            return true;
9819        }
9820
9821        public boolean isDragging() {
9822            return mIsDragging;
9823        }
9824
9825        void onHandleMoved() {
9826            // Does nothing by default
9827        }
9828
9829        public void onDetached() {
9830            // Should be overriden to clean possible Runnable
9831        }
9832    }
9833
9834    private class InsertionHandleView extends HandleView {
9835        private static final int DELAY_BEFORE_FADE_OUT = 4000;
9836        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
9837
9838        // Used to detect taps on the insertion handle, which will affect the PastePopupWindow
9839        private float mDownPositionX, mDownPositionY;
9840        private PastePopupWindow mPastePopupWindow;
9841        private Runnable mHider;
9842        private Runnable mPastePopupShower;
9843
9844        @Override
9845        public void show() {
9846            super.show();
9847            hideDelayed();
9848            hidePastePopupWindow();
9849        }
9850
9851        public void show(int delayBeforePaste) {
9852            show();
9853
9854            final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - sLastCutOrCopyTime;
9855            if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) {
9856                delayBeforePaste = 0;
9857            }
9858            if (delayBeforePaste == 0 || canPaste()) {
9859                if (mPastePopupShower == null) {
9860                    mPastePopupShower = new Runnable() {
9861                        public void run() {
9862                            showPastePopupWindow();
9863                        }
9864                    };
9865                }
9866                TextView.this.postDelayed(mPastePopupShower, delayBeforePaste);
9867            }
9868        }
9869
9870        @Override
9871        protected void dismiss() {
9872            super.dismiss();
9873            onDetached();
9874        }
9875
9876        private void hideDelayed() {
9877            removeHiderCallback();
9878            if (mHider == null) {
9879                mHider = new Runnable() {
9880                    public void run() {
9881                        hide();
9882                    }
9883                };
9884            }
9885            TextView.this.postDelayed(mHider, DELAY_BEFORE_FADE_OUT);
9886        }
9887
9888        private void removeHiderCallback() {
9889            if (mHider != null) {
9890                TextView.this.removeCallbacks(mHider);
9891            }
9892        }
9893
9894        @Override
9895        protected void initDrawable() {
9896            if (mSelectHandleCenter == null) {
9897                mSelectHandleCenter = mContext.getResources().getDrawable(
9898                        mTextSelectHandleRes);
9899            }
9900            mDrawable = mSelectHandleCenter;
9901            mHotspotX = mDrawable.getIntrinsicWidth() / 2.0f;
9902        }
9903
9904        @Override
9905        public boolean onTouchEvent(MotionEvent ev) {
9906            final boolean result = super.onTouchEvent(ev);
9907
9908            switch (ev.getActionMasked()) {
9909                case MotionEvent.ACTION_DOWN:
9910                    mDownPositionX = ev.getRawX();
9911                    mDownPositionY = ev.getRawY();
9912                    break;
9913
9914                case MotionEvent.ACTION_UP:
9915                    final float deltaX = mDownPositionX - ev.getRawX();
9916                    final float deltaY = mDownPositionY - ev.getRawY();
9917                    final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
9918                    if (distanceSquared < mSquaredTouchSlopDistance) {
9919                        if (mPastePopupWindow != null && mPastePopupWindow.isShowing()) {
9920                            // Tapping on the handle dismisses the displayed paste view,
9921                            mPastePopupWindow.hide();
9922                        } else {
9923                            show(0);
9924                        }
9925                    }
9926                    hideDelayed();
9927                    break;
9928
9929                case MotionEvent.ACTION_CANCEL:
9930                    hideDelayed();
9931                    break;
9932
9933                default:
9934                    break;
9935            }
9936
9937            return result;
9938        }
9939
9940        @Override
9941        public int getCurrentCursorOffset() {
9942            return TextView.this.getSelectionStart();
9943        }
9944
9945        @Override
9946        public void updateOffset(int offset) {
9947            Selection.setSelection((Spannable) mText, offset);
9948        }
9949
9950        @Override
9951        public void updatePosition(float x, float y) {
9952            updateOffset(getOffsetForPosition(x, y));
9953        }
9954
9955        void showPastePopupWindow() {
9956            if (mPastePopupWindow == null) {
9957                mPastePopupWindow = new PastePopupWindow();
9958            }
9959            mPastePopupWindow.show();
9960        }
9961
9962        @Override
9963        void onHandleMoved() {
9964            removeHiderCallback();
9965            hidePastePopupWindow();
9966        }
9967
9968        void hidePastePopupWindow() {
9969            if (mPastePopupShower != null) {
9970                TextView.this.removeCallbacks(mPastePopupShower);
9971            }
9972            if (mPastePopupWindow != null) {
9973                mPastePopupWindow.hide();
9974            }
9975        }
9976
9977        @Override
9978        public void onDetached() {
9979            removeHiderCallback();
9980            hidePastePopupWindow();
9981        }
9982    }
9983
9984    private class SelectionStartHandleView extends HandleView {
9985        @Override
9986        protected void initDrawable() {
9987            if (mSelectHandleLeft == null) {
9988                mSelectHandleLeft = mContext.getResources().getDrawable(
9989                        mTextSelectHandleLeftRes);
9990            }
9991            mDrawable = mSelectHandleLeft;
9992            mHotspotX = mDrawable.getIntrinsicWidth() * 3.0f / 4.0f;
9993        }
9994
9995        @Override
9996        public int getCurrentCursorOffset() {
9997            return TextView.this.getSelectionStart();
9998        }
9999
10000        @Override
10001        public void updateOffset(int offset) {
10002            Selection.setSelection((Spannable) mText, offset, getSelectionEnd());
10003        }
10004
10005        @Override
10006        public void updatePosition(float x, float y) {
10007            final int selectionStart = getSelectionStart();
10008            final int selectionEnd = getSelectionEnd();
10009
10010            int offset = getOffsetForPosition(x, y);
10011
10012            // No need to redraw when the offset is unchanged
10013            if (offset == selectionStart) return;
10014            // Handles can not cross and selection is at least one character
10015            if (offset >= selectionEnd) offset = selectionEnd - 1;
10016
10017            Selection.setSelection((Spannable) mText, offset, selectionEnd);
10018        }
10019    }
10020
10021    private class SelectionEndHandleView extends HandleView {
10022        @Override
10023        protected void initDrawable() {
10024            if (mSelectHandleRight == null) {
10025                mSelectHandleRight = mContext.getResources().getDrawable(
10026                        mTextSelectHandleRightRes);
10027            }
10028            mDrawable = mSelectHandleRight;
10029            mHotspotX = mDrawable.getIntrinsicWidth() / 4.0f;
10030        }
10031
10032        @Override
10033        public int getCurrentCursorOffset() {
10034            return TextView.this.getSelectionEnd();
10035        }
10036
10037        @Override
10038        public void updateOffset(int offset) {
10039            Selection.setSelection((Spannable) mText, getSelectionStart(), offset);
10040        }
10041
10042        @Override
10043        public void updatePosition(float x, float y) {
10044            final int selectionStart = getSelectionStart();
10045            final int selectionEnd = getSelectionEnd();
10046
10047            int offset = getOffsetForPosition(x, y);
10048
10049            // No need to redraw when the offset is unchanged
10050            if (offset == selectionEnd) return;
10051            // Handles can not cross and selection is at least one character
10052            if (offset <= selectionStart) offset = selectionStart + 1;
10053
10054            Selection.setSelection((Spannable) mText, selectionStart, offset);
10055        }
10056    }
10057
10058    /**
10059     * A CursorController instance can be used to control a cursor in the text.
10060     * It is not used outside of {@link TextView}.
10061     * @hide
10062     */
10063    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
10064        /**
10065         * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}.
10066         * See also {@link #hide()}.
10067         */
10068        public void show();
10069
10070        /**
10071         * Hide the cursor controller from screen.
10072         * See also {@link #show()}.
10073         */
10074        public void hide();
10075
10076        /**
10077         * Called when the view is detached from window. Perform house keeping task, such as
10078         * stopping Runnable thread that would otherwise keep a reference on the context, thus
10079         * preventing the activity from being recycled.
10080         */
10081        public void onDetached();
10082    }
10083
10084    private class InsertionPointCursorController implements CursorController {
10085        private static final int DELAY_BEFORE_PASTE = 2000;
10086
10087        private InsertionHandleView mHandle;
10088
10089        public void show() {
10090            ((InsertionHandleView) getHandle()).show(DELAY_BEFORE_PASTE);
10091        }
10092
10093        public void showWithPaste() {
10094            ((InsertionHandleView) getHandle()).show(0);
10095        }
10096
10097        public void hide() {
10098            if (mHandle != null) {
10099                mHandle.hide();
10100            }
10101        }
10102
10103        public void onTouchModeChanged(boolean isInTouchMode) {
10104            if (!isInTouchMode) {
10105                hide();
10106            }
10107        }
10108
10109        private HandleView getHandle() {
10110            if (mHandle == null) {
10111                mHandle = new InsertionHandleView();
10112            }
10113            return mHandle;
10114        }
10115
10116        @Override
10117        public void onDetached() {
10118            final ViewTreeObserver observer = getViewTreeObserver();
10119            observer.removeOnTouchModeChangeListener(this);
10120
10121            if (mHandle != null) mHandle.onDetached();
10122        }
10123    }
10124
10125    private class SelectionModifierCursorController implements CursorController {
10126        // The cursor controller handles, lazily created when shown.
10127        private SelectionStartHandleView mStartHandle;
10128        private SelectionEndHandleView mEndHandle;
10129        // The offsets of that last touch down event. Remembered to start selection there.
10130        private int mMinTouchOffset, mMaxTouchOffset;
10131
10132        // Double tap detection
10133        private long mPreviousTapUpTime = 0;
10134        private float mPreviousTapPositionX, mPreviousTapPositionY;
10135
10136        SelectionModifierCursorController() {
10137            resetTouchOffsets();
10138        }
10139
10140        public void show() {
10141            if (isInBatchEditMode()) {
10142                return;
10143            }
10144
10145            // Lazy object creation has to be done before updatePosition() is called.
10146            if (mStartHandle == null) mStartHandle = new SelectionStartHandleView();
10147            if (mEndHandle == null) mEndHandle = new SelectionEndHandleView();
10148
10149            mStartHandle.show();
10150            mEndHandle.show();
10151
10152            hideInsertionPointCursorController();
10153            hideSuggestions();
10154        }
10155
10156        public void hide() {
10157            if (mStartHandle != null) mStartHandle.hide();
10158            if (mEndHandle != null) mEndHandle.hide();
10159        }
10160
10161        public void onTouchEvent(MotionEvent event) {
10162            // This is done even when the View does not have focus, so that long presses can start
10163            // selection and tap can move cursor from this tap position.
10164            switch (event.getActionMasked()) {
10165                case MotionEvent.ACTION_DOWN:
10166                    final float x = event.getX();
10167                    final float y = event.getY();
10168
10169                    // Remember finger down position, to be able to start selection from there
10170                    mMinTouchOffset = mMaxTouchOffset = getOffsetForPosition(x, y);
10171
10172                    // Double tap detection
10173                    long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime;
10174                    if (duration <= ViewConfiguration.getDoubleTapTimeout() &&
10175                            isPositionOnText(x, y)) {
10176                        final float deltaX = x - mPreviousTapPositionX;
10177                        final float deltaY = y - mPreviousTapPositionY;
10178                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
10179                        if (distanceSquared < mSquaredTouchSlopDistance) {
10180                            showSuggestions();
10181                            mDiscardNextActionUp = true;
10182                        }
10183                    }
10184
10185                    mPreviousTapPositionX = x;
10186                    mPreviousTapPositionY = y;
10187
10188                    break;
10189
10190                case MotionEvent.ACTION_POINTER_DOWN:
10191                case MotionEvent.ACTION_POINTER_UP:
10192                    // Handle multi-point gestures. Keep min and max offset positions.
10193                    // Only activated for devices that correctly handle multi-touch.
10194                    if (mContext.getPackageManager().hasSystemFeature(
10195                            PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
10196                        updateMinAndMaxOffsets(event);
10197                    }
10198                    break;
10199
10200                case MotionEvent.ACTION_UP:
10201                    mPreviousTapUpTime = SystemClock.uptimeMillis();
10202                    break;
10203            }
10204        }
10205
10206        /**
10207         * @param event
10208         */
10209        private void updateMinAndMaxOffsets(MotionEvent event) {
10210            int pointerCount = event.getPointerCount();
10211            for (int index = 0; index < pointerCount; index++) {
10212                int offset = getOffsetForPosition(event.getX(index), event.getY(index));
10213                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
10214                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
10215            }
10216        }
10217
10218        public int getMinTouchOffset() {
10219            return mMinTouchOffset;
10220        }
10221
10222        public int getMaxTouchOffset() {
10223            return mMaxTouchOffset;
10224        }
10225
10226        public void resetTouchOffsets() {
10227            mMinTouchOffset = mMaxTouchOffset = -1;
10228        }
10229
10230        /**
10231         * @return true iff this controller is currently used to move the selection start.
10232         */
10233        public boolean isSelectionStartDragged() {
10234            return mStartHandle != null && mStartHandle.isDragging();
10235        }
10236
10237        public void onTouchModeChanged(boolean isInTouchMode) {
10238            if (!isInTouchMode) {
10239                hide();
10240            }
10241        }
10242
10243        @Override
10244        public void onDetached() {
10245            final ViewTreeObserver observer = getViewTreeObserver();
10246            observer.removeOnTouchModeChangeListener(this);
10247
10248            if (mStartHandle != null) mStartHandle.onDetached();
10249            if (mEndHandle != null) mEndHandle.onDetached();
10250        }
10251    }
10252
10253    private void hideInsertionPointCursorController() {
10254        // No need to create the controller to hide it.
10255        if (mInsertionPointCursorController != null) {
10256            mInsertionPointCursorController.hide();
10257        }
10258    }
10259
10260    /**
10261     * Hides the insertion controller and stops text selection mode, hiding the selection controller
10262     */
10263    private void hideControllers() {
10264        hideInsertionPointCursorController();
10265        stopSelectionActionMode();
10266        hideSuggestions();
10267    }
10268
10269    /**
10270     * Get the character offset closest to the specified absolute position. A typical use case is to
10271     * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method.
10272     *
10273     * @param x The horizontal absolute position of a point on screen
10274     * @param y The vertical absolute position of a point on screen
10275     * @return the character offset for the character whose position is closest to the specified
10276     *  position. Returns -1 if there is no layout.
10277     */
10278    public int getOffsetForPosition(float x, float y) {
10279        if (getLayout() == null) return -1;
10280        final int line = getLineAtCoordinate(y);
10281        final int offset = getOffsetAtCoordinate(line, x);
10282        return offset;
10283    }
10284
10285    private float convertToLocalHorizontalCoordinate(float x) {
10286        x -= getTotalPaddingLeft();
10287        // Clamp the position to inside of the view.
10288        x = Math.max(0.0f, x);
10289        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
10290        x += getScrollX();
10291        return x;
10292    }
10293
10294    private int getLineAtCoordinate(float y) {
10295        y -= getTotalPaddingTop();
10296        // Clamp the position to inside of the view.
10297        y = Math.max(0.0f, y);
10298        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
10299        y += getScrollY();
10300        return getLayout().getLineForVertical((int) y);
10301    }
10302
10303    private int getOffsetAtCoordinate(int line, float x) {
10304        x = convertToLocalHorizontalCoordinate(x);
10305        return getLayout().getOffsetForHorizontal(line, x);
10306    }
10307
10308    /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed
10309     * in the view. Returns false when the position is in the empty space of left/right of text.
10310     */
10311    private boolean isPositionOnText(float x, float y) {
10312        if (getLayout() == null) return false;
10313
10314        final int line = getLineAtCoordinate(y);
10315        x = convertToLocalHorizontalCoordinate(x);
10316
10317        if (x < getLayout().getLineLeft(line)) return false;
10318        if (x > getLayout().getLineRight(line)) return false;
10319        return true;
10320    }
10321
10322    @Override
10323    public boolean onDragEvent(DragEvent event) {
10324        switch (event.getAction()) {
10325            case DragEvent.ACTION_DRAG_STARTED:
10326                return hasInsertionController();
10327
10328            case DragEvent.ACTION_DRAG_ENTERED:
10329                TextView.this.requestFocus();
10330                return true;
10331
10332            case DragEvent.ACTION_DRAG_LOCATION:
10333                final int offset = getOffsetForPosition(event.getX(), event.getY());
10334                Selection.setSelection((Spannable)mText, offset);
10335                return true;
10336
10337            case DragEvent.ACTION_DROP:
10338                onDrop(event);
10339                return true;
10340
10341            case DragEvent.ACTION_DRAG_ENDED:
10342            case DragEvent.ACTION_DRAG_EXITED:
10343            default:
10344                return true;
10345        }
10346    }
10347
10348    private void onDrop(DragEvent event) {
10349        StringBuilder content = new StringBuilder("");
10350        ClipData clipData = event.getClipData();
10351        final int itemCount = clipData.getItemCount();
10352        for (int i=0; i < itemCount; i++) {
10353            Item item = clipData.getItemAt(i);
10354            content.append(item.coerceToText(TextView.this.mContext));
10355        }
10356
10357        final int offset = getOffsetForPosition(event.getX(), event.getY());
10358
10359        Object localState = event.getLocalState();
10360        DragLocalState dragLocalState = null;
10361        if (localState instanceof DragLocalState) {
10362            dragLocalState = (DragLocalState) localState;
10363        }
10364        boolean dragDropIntoItself = dragLocalState != null &&
10365                dragLocalState.sourceTextView == this;
10366
10367        if (dragDropIntoItself) {
10368            if (offset >= dragLocalState.start && offset < dragLocalState.end) {
10369                // A drop inside the original selection discards the drop.
10370                return;
10371            }
10372        }
10373
10374        final int originalLength = mText.length();
10375        long minMax = prepareSpacesAroundPaste(offset, offset, content);
10376        int min = extractRangeStartFromLong(minMax);
10377        int max = extractRangeEndFromLong(minMax);
10378
10379        Selection.setSelection((Spannable) mText, max);
10380        ((Editable) mText).replace(min, max, content);
10381
10382        if (dragDropIntoItself) {
10383            int dragSourceStart = dragLocalState.start;
10384            int dragSourceEnd = dragLocalState.end;
10385            if (max <= dragSourceStart) {
10386                // Inserting text before selection has shifted positions
10387                final int shift = mText.length() - originalLength;
10388                dragSourceStart += shift;
10389                dragSourceEnd += shift;
10390            }
10391
10392            // Delete original selection
10393            ((Editable) mText).delete(dragSourceStart, dragSourceEnd);
10394
10395            // Make sure we do not leave two adjacent spaces.
10396            if ((dragSourceStart == 0 ||
10397                    Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) &&
10398                    (dragSourceStart == mText.length() ||
10399                    Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) {
10400                final int pos = dragSourceStart == mText.length() ?
10401                        dragSourceStart - 1 : dragSourceStart;
10402                ((Editable) mText).delete(pos, pos + 1);
10403            }
10404        }
10405    }
10406
10407    /**
10408     * @return True if this view supports insertion handles.
10409     */
10410    boolean hasInsertionController() {
10411        return mInsertionControllerEnabled;
10412    }
10413
10414    /**
10415     * @return True if this view supports selection handles.
10416     */
10417    boolean hasSelectionController() {
10418        return mSelectionControllerEnabled;
10419    }
10420
10421    InsertionPointCursorController getInsertionController() {
10422        if (!mInsertionControllerEnabled) {
10423            return null;
10424        }
10425
10426        if (mInsertionPointCursorController == null) {
10427            mInsertionPointCursorController = new InsertionPointCursorController();
10428
10429            final ViewTreeObserver observer = getViewTreeObserver();
10430            observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
10431        }
10432
10433        return mInsertionPointCursorController;
10434    }
10435
10436    SelectionModifierCursorController getSelectionController() {
10437        if (!mSelectionControllerEnabled) {
10438            return null;
10439        }
10440
10441        if (mSelectionModifierCursorController == null) {
10442            mSelectionModifierCursorController = new SelectionModifierCursorController();
10443
10444            final ViewTreeObserver observer = getViewTreeObserver();
10445            observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
10446        }
10447
10448        return mSelectionModifierCursorController;
10449    }
10450
10451    boolean isInBatchEditMode() {
10452        final InputMethodState ims = mInputMethodState;
10453        if (ims != null) {
10454            return ims.mBatchEditNesting > 0;
10455        }
10456        return mInBatchEditControllers;
10457    }
10458
10459    private class TextViewDirectionHeuristic extends TextDirectionHeuristicImpl {
10460        private TextViewDirectionHeuristic(TextDirectionAlgorithm algorithm) {
10461            super(algorithm);
10462        }
10463        @Override
10464        protected boolean defaultIsRtl() {
10465            return getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL;
10466        }
10467    }
10468
10469    /**
10470     * Resolve the text direction.
10471     *
10472     * Text direction of paragraphs in a TextView is determined using a heuristic. If the correct
10473     * text direction cannot be determined by the heuristic, the view's resolved layout direction
10474     * determines the direction.
10475     *
10476     * This heuristic and result is applied individually to each paragraph in a TextView, based on
10477     * the text and style content of that paragraph. Paragraph text styles can also be used to force
10478     * a particular direction.
10479     */
10480    @Override
10481    protected void resolveTextDirection() {
10482        super.resolveTextDirection();
10483
10484        int textDir = getResolvedTextDirection();
10485        switch (textDir) {
10486            default:
10487            case TEXT_DIRECTION_FIRST_STRONG:
10488                mTextDir = new TextViewDirectionHeuristic(FirstStrong.INSTANCE);
10489                break;
10490            case TEXT_DIRECTION_ANY_RTL:
10491                mTextDir = new TextViewDirectionHeuristic(AnyStrong.INSTANCE_RTL);
10492                break;
10493            case TEXT_DIRECTION_CHAR_COUNT:
10494                mTextDir = new TextViewDirectionHeuristic(CharCount.INSTANCE_DEFAULT);
10495                break;
10496            case TEXT_DIRECTION_LTR:
10497                mTextDir = TextDirectionHeuristics.LTR;
10498                break;
10499            case TEXT_DIRECTION_RTL:
10500                mTextDir = TextDirectionHeuristics.RTL;
10501                break;
10502        }
10503    }
10504
10505    /**
10506     * Subclasses will need to override this method to implement their own way of resolving
10507     * drawables depending on the layout direction.
10508     *
10509     * A call to the super method will be required from the subclasses implementation.
10510     *
10511     */
10512    protected void resolveDrawables() {
10513        // No need to resolve twice
10514        if (bResolvedDrawables) {
10515            return;
10516        }
10517        // No drawable to resolve
10518        if (mDrawables == null) {
10519            return;
10520        }
10521        // No relative drawable to resolve
10522        if (mDrawables.mDrawableStart == null && mDrawables.mDrawableEnd == null) {
10523            bResolvedDrawables = true;
10524            return;
10525        }
10526
10527        Drawables dr = mDrawables;
10528        switch(getResolvedLayoutDirection()) {
10529            case LAYOUT_DIRECTION_RTL:
10530                if (dr.mDrawableStart != null) {
10531                    dr.mDrawableRight = dr.mDrawableStart;
10532
10533                    dr.mDrawableSizeRight = dr.mDrawableSizeStart;
10534                    dr.mDrawableHeightRight = dr.mDrawableHeightStart;
10535                }
10536                if (dr.mDrawableEnd != null) {
10537                    dr.mDrawableLeft = dr.mDrawableEnd;
10538
10539                    dr.mDrawableSizeLeft = dr.mDrawableSizeEnd;
10540                    dr.mDrawableHeightLeft = dr.mDrawableHeightEnd;
10541                }
10542                break;
10543
10544            case LAYOUT_DIRECTION_LTR:
10545            default:
10546                if (dr.mDrawableStart != null) {
10547                    dr.mDrawableLeft = dr.mDrawableStart;
10548
10549                    dr.mDrawableSizeLeft = dr.mDrawableSizeStart;
10550                    dr.mDrawableHeightLeft = dr.mDrawableHeightStart;
10551                }
10552                if (dr.mDrawableEnd != null) {
10553                    dr.mDrawableRight = dr.mDrawableEnd;
10554
10555                    dr.mDrawableSizeRight = dr.mDrawableSizeEnd;
10556                    dr.mDrawableHeightRight = dr.mDrawableHeightEnd;
10557                }
10558                break;
10559        }
10560        bResolvedDrawables = true;
10561    }
10562
10563    protected void resetResolvedDrawables() {
10564        bResolvedDrawables = false;
10565    }
10566
10567    @ViewDebug.ExportedProperty(category = "text")
10568    private CharSequence            mText;
10569    private CharSequence            mTransformed;
10570    private BufferType              mBufferType = BufferType.NORMAL;
10571
10572    private int                     mInputType = EditorInfo.TYPE_NULL;
10573    private CharSequence            mHint;
10574    private Layout                  mHintLayout;
10575
10576    private KeyListener             mInput;
10577
10578    private MovementMethod          mMovement;
10579    private TransformationMethod    mTransformation;
10580    private boolean                 mAllowTransformationLengthChange;
10581    private ChangeWatcher           mChangeWatcher;
10582
10583    private ArrayList<TextWatcher>  mListeners = null;
10584
10585    // display attributes
10586    private final TextPaint         mTextPaint;
10587    private boolean                 mUserSetTextScaleX;
10588    private final Paint             mHighlightPaint;
10589    private int                     mHighlightColor = 0xCC475925;
10590    /**
10591     * This is temporarily visible to fix bug 3085564 in webView. Do not rely on
10592     * this field being protected. Will be restored as private when lineHeight
10593     * feature request 3215097 is implemented
10594     * @hide
10595     */
10596    protected Layout                mLayout;
10597
10598    private long                    mShowCursor;
10599    private Blink                   mBlink;
10600    private boolean                 mCursorVisible = true;
10601
10602    // Cursor Controllers.
10603    private InsertionPointCursorController mInsertionPointCursorController;
10604    private SelectionModifierCursorController mSelectionModifierCursorController;
10605    private ActionMode              mSelectionActionMode;
10606    private boolean                 mInsertionControllerEnabled;
10607    private boolean                 mSelectionControllerEnabled;
10608    private boolean                 mInBatchEditControllers;
10609
10610    // These are needed to desambiguate a long click. If the long click comes from ones of these, we
10611    // select from the current cursor position. Otherwise, select from long pressed position.
10612    private boolean                 mDPadCenterIsDown = false;
10613    private boolean                 mEnterKeyIsDown = false;
10614    private boolean                 mContextMenuTriggeredByKey = false;
10615    // Created once and shared by different CursorController helper methods.
10616    // Only one cursor controller is active at any time which prevent race conditions.
10617    private static Rect             sCursorControllerTempRect = new Rect();
10618
10619    private boolean                 mSelectAllOnFocus = false;
10620
10621    private int                     mGravity = Gravity.TOP | Gravity.START;
10622    private boolean                 mHorizontallyScrolling;
10623
10624    private int                     mAutoLinkMask;
10625    private boolean                 mLinksClickable = true;
10626
10627    private float                   mSpacingMult = 1;
10628    private float                   mSpacingAdd = 0;
10629    private boolean                 mTextIsSelectable = false;
10630
10631    private static final int        LINES = 1;
10632    private static final int        EMS = LINES;
10633    private static final int        PIXELS = 2;
10634
10635    private int                     mMaximum = Integer.MAX_VALUE;
10636    private int                     mMaxMode = LINES;
10637    private int                     mMinimum = 0;
10638    private int                     mMinMode = LINES;
10639
10640    private int                     mMaxWidth = Integer.MAX_VALUE;
10641    private int                     mMaxWidthMode = PIXELS;
10642    private int                     mMinWidth = 0;
10643    private int                     mMinWidthMode = PIXELS;
10644
10645    private boolean                 mSingleLine;
10646    private int                     mDesiredHeightAtMeasure = -1;
10647    private boolean                 mIncludePad = true;
10648
10649    // tmp primitives, so we don't alloc them on each draw
10650    private Path                    mHighlightPath;
10651    private boolean                 mHighlightPathBogus = true;
10652    private static final RectF      sTempRect = new RectF();
10653
10654    // XXX should be much larger
10655    private static final int        VERY_WIDE = 16384;
10656
10657    private static final int        BLINK = 500;
10658
10659    private static final int ANIMATED_SCROLL_GAP = 250;
10660    private long mLastScroll;
10661    private Scroller mScroller = null;
10662
10663    private BoringLayout.Metrics mBoring;
10664    private BoringLayout.Metrics mHintBoring;
10665
10666    private BoringLayout mSavedLayout, mSavedHintLayout;
10667
10668    private TextDirectionHeuristic mTextDir = null;
10669
10670    private static final InputFilter[] NO_FILTERS = new InputFilter[0];
10671    private InputFilter[] mFilters = NO_FILTERS;
10672    private static final Spanned EMPTY_SPANNED = new SpannedString("");
10673    private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
10674    // System wide time for last cut or copy action.
10675    private static long sLastCutOrCopyTime;
10676    // Used to highlight a word when it is corrected by the IME
10677    private CorrectionHighlighter mCorrectionHighlighter;
10678    // New state used to change background based on whether this TextView is multiline.
10679    private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline };
10680}
10681