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