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