TextView.java revision 60e2186c354c30b2f75ed0ef1ba75181bd32afda
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,
2984                                           ss.selEnd);
2985
2986                    if (ss.frozenWithFocus) {
2987                        createEditorIfNeeded("restore instance with focus");
2988                        getEditor().mFrozenWithFocus = true;
2989                    }
2990                }
2991            }
2992        }
2993
2994        if (ss.error != null) {
2995            final CharSequence error = ss.error;
2996            // Display the error later, after the first layout pass
2997            post(new Runnable() {
2998                public void run() {
2999                    setError(error);
3000                }
3001            });
3002        }
3003    }
3004
3005    /**
3006     * Control whether this text view saves its entire text contents when
3007     * freezing to an icicle, in addition to dynamic state such as cursor
3008     * position.  By default this is false, not saving the text.  Set to true
3009     * if the text in the text view is not being saved somewhere else in
3010     * persistent storage (such as in a content provider) so that if the
3011     * view is later thawed the user will not lose their data.
3012     *
3013     * @param freezesText Controls whether a frozen icicle should include the
3014     * entire text data: true to include it, false to not.
3015     *
3016     * @attr ref android.R.styleable#TextView_freezesText
3017     */
3018    @android.view.RemotableViewMethod
3019    public void setFreezesText(boolean freezesText) {
3020        mFreezesText = freezesText;
3021    }
3022
3023    /**
3024     * Return whether this text view is including its entire text contents
3025     * in frozen icicles.
3026     *
3027     * @return Returns true if text is included, false if it isn't.
3028     *
3029     * @see #setFreezesText
3030     */
3031    public boolean getFreezesText() {
3032        return mFreezesText;
3033    }
3034
3035    ///////////////////////////////////////////////////////////////////////////
3036
3037    /**
3038     * Sets the Factory used to create new Editables.
3039     */
3040    public final void setEditableFactory(Editable.Factory factory) {
3041        mEditableFactory = factory;
3042        setText(mText);
3043    }
3044
3045    /**
3046     * Sets the Factory used to create new Spannables.
3047     */
3048    public final void setSpannableFactory(Spannable.Factory factory) {
3049        mSpannableFactory = factory;
3050        setText(mText);
3051    }
3052
3053    /**
3054     * Sets the string value of the TextView. TextView <em>does not</em> accept
3055     * HTML-like formatting, which you can do with text strings in XML resource files.
3056     * To style your strings, attach android.text.style.* objects to a
3057     * {@link android.text.SpannableString SpannableString}, or see the
3058     * <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources">
3059     * Available Resource Types</a> documentation for an example of setting
3060     * formatted text in the XML resource file.
3061     *
3062     * @attr ref android.R.styleable#TextView_text
3063     */
3064    @android.view.RemotableViewMethod
3065    public final void setText(CharSequence text) {
3066        setText(text, mBufferType);
3067    }
3068
3069    /**
3070     * Like {@link #setText(CharSequence)},
3071     * except that the cursor position (if any) is retained in the new text.
3072     *
3073     * @param text The new text to place in the text view.
3074     *
3075     * @see #setText(CharSequence)
3076     */
3077    @android.view.RemotableViewMethod
3078    public final void setTextKeepState(CharSequence text) {
3079        setTextKeepState(text, mBufferType);
3080    }
3081
3082    /**
3083     * Sets the text that this TextView is to display (see
3084     * {@link #setText(CharSequence)}) and also sets whether it is stored
3085     * in a styleable/spannable buffer and whether it is editable.
3086     *
3087     * @attr ref android.R.styleable#TextView_text
3088     * @attr ref android.R.styleable#TextView_bufferType
3089     */
3090    public void setText(CharSequence text, BufferType type) {
3091        setText(text, type, true, 0);
3092
3093        if (mCharWrapper != null) {
3094            mCharWrapper.mChars = null;
3095        }
3096    }
3097
3098    private void setText(CharSequence text, BufferType type,
3099                         boolean notifyBefore, int oldlen) {
3100        if (text == null) {
3101            text = "";
3102        }
3103
3104        // If suggestions are not enabled, remove the suggestion spans from the text
3105        if (!isSuggestionsEnabled()) {
3106            text = removeSuggestionSpans(text);
3107        }
3108
3109        if (!mUserSetTextScaleX) mTextPaint.setTextScaleX(1.0f);
3110
3111        if (text instanceof Spanned &&
3112            ((Spanned) text).getSpanStart(TextUtils.TruncateAt.MARQUEE) >= 0) {
3113            if (ViewConfiguration.get(mContext).isFadingMarqueeEnabled()) {
3114                setHorizontalFadingEdgeEnabled(true);
3115                mMarqueeFadeMode = MARQUEE_FADE_NORMAL;
3116            } else {
3117                setHorizontalFadingEdgeEnabled(false);
3118                mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS;
3119            }
3120            setEllipsize(TextUtils.TruncateAt.MARQUEE);
3121        }
3122
3123        int n = mFilters.length;
3124        for (int i = 0; i < n; i++) {
3125            CharSequence out = mFilters[i].filter(text, 0, text.length(), EMPTY_SPANNED, 0, 0);
3126            if (out != null) {
3127                text = out;
3128            }
3129        }
3130
3131        if (notifyBefore) {
3132            if (mText != null) {
3133                oldlen = mText.length();
3134                sendBeforeTextChanged(mText, 0, oldlen, text.length());
3135            } else {
3136                sendBeforeTextChanged("", 0, 0, text.length());
3137            }
3138        }
3139
3140        boolean needEditableForNotification = false;
3141
3142        if (mListeners != null && mListeners.size() != 0) {
3143            needEditableForNotification = true;
3144        }
3145
3146        if (type == BufferType.EDITABLE || getKeyListener() != null || needEditableForNotification) {
3147            createEditorIfNeeded("setText with BufferType.EDITABLE or non null mInput");
3148            Editable t = mEditableFactory.newEditable(text);
3149            text = t;
3150            setFilters(t, mFilters);
3151            InputMethodManager imm = InputMethodManager.peekInstance();
3152            if (imm != null) imm.restartInput(this);
3153        } else if (type == BufferType.SPANNABLE || mMovement != null) {
3154            text = mSpannableFactory.newSpannable(text);
3155        } else if (!(text instanceof CharWrapper)) {
3156            text = TextUtils.stringOrSpannedString(text);
3157        }
3158
3159        if (mAutoLinkMask != 0) {
3160            Spannable s2;
3161
3162            if (type == BufferType.EDITABLE || text instanceof Spannable) {
3163                s2 = (Spannable) text;
3164            } else {
3165                s2 = mSpannableFactory.newSpannable(text);
3166            }
3167
3168            if (Linkify.addLinks(s2, mAutoLinkMask)) {
3169                text = s2;
3170                type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE;
3171
3172                /*
3173                 * We must go ahead and set the text before changing the
3174                 * movement method, because setMovementMethod() may call
3175                 * setText() again to try to upgrade the buffer type.
3176                 */
3177                mText = text;
3178
3179                // Do not change the movement method for text that support text selection as it
3180                // would prevent an arbitrary cursor displacement.
3181                if (mLinksClickable && !textCanBeSelected()) {
3182                    setMovementMethod(LinkMovementMethod.getInstance());
3183                }
3184            }
3185        }
3186
3187        mBufferType = type;
3188        mText = text;
3189
3190        if (mTransformation == null) {
3191            mTransformed = text;
3192        } else {
3193            mTransformed = mTransformation.getTransformation(text, this);
3194        }
3195
3196        final int textLength = text.length();
3197
3198        if (text instanceof Spannable && !mAllowTransformationLengthChange) {
3199            Spannable sp = (Spannable) text;
3200
3201            // Remove any ChangeWatchers that might have come
3202            // from other TextViews.
3203            final ChangeWatcher[] watchers = sp.getSpans(0, sp.length(), ChangeWatcher.class);
3204            final int count = watchers.length;
3205            for (int i = 0; i < count; i++)
3206                sp.removeSpan(watchers[i]);
3207
3208            if (mChangeWatcher == null)
3209                mChangeWatcher = new ChangeWatcher();
3210
3211            sp.setSpan(mChangeWatcher, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE |
3212                       (CHANGE_WATCHER_PRIORITY << Spanned.SPAN_PRIORITY_SHIFT));
3213
3214            if (mEditor != null && getEditor().mKeyListener != null) {
3215                sp.setSpan(getEditor().mKeyListener, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3216            }
3217
3218            if (mTransformation != null) {
3219                sp.setSpan(mTransformation, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3220            }
3221
3222            if (mMovement != null) {
3223                mMovement.initialize(this, (Spannable) text);
3224
3225                /*
3226                 * Initializing the movement method will have set the
3227                 * selection, so reset mSelectionMoved to keep that from
3228                 * interfering with the normal on-focus selection-setting.
3229                 */
3230                if (mEditor != null) getEditor().mSelectionMoved = false;
3231            }
3232        }
3233
3234        if (mLayout != null) {
3235            checkForRelayout();
3236        }
3237
3238        sendOnTextChanged(text, 0, oldlen, textLength);
3239        onTextChanged(text, 0, oldlen, textLength);
3240
3241        if (needEditableForNotification) {
3242            sendAfterTextChanged((Editable) text);
3243        }
3244
3245        // SelectionModifierCursorController depends on textCanBeSelected, which depends on text
3246        prepareCursorControllers();
3247    }
3248
3249    /**
3250     * Sets the TextView to display the specified slice of the specified
3251     * char array.  You must promise that you will not change the contents
3252     * of the array except for right before another call to setText(),
3253     * since the TextView has no way to know that the text
3254     * has changed and that it needs to invalidate and re-layout.
3255     */
3256    public final void setText(char[] text, int start, int len) {
3257        int oldlen = 0;
3258
3259        if (start < 0 || len < 0 || start + len > text.length) {
3260            throw new IndexOutOfBoundsException(start + ", " + len);
3261        }
3262
3263        /*
3264         * We must do the before-notification here ourselves because if
3265         * the old text is a CharWrapper we destroy it before calling
3266         * into the normal path.
3267         */
3268        if (mText != null) {
3269            oldlen = mText.length();
3270            sendBeforeTextChanged(mText, 0, oldlen, len);
3271        } else {
3272            sendBeforeTextChanged("", 0, 0, len);
3273        }
3274
3275        if (mCharWrapper == null) {
3276            mCharWrapper = new CharWrapper(text, start, len);
3277        } else {
3278            mCharWrapper.set(text, start, len);
3279        }
3280
3281        setText(mCharWrapper, mBufferType, false, oldlen);
3282    }
3283
3284    /**
3285     * Like {@link #setText(CharSequence, android.widget.TextView.BufferType)},
3286     * except that the cursor position (if any) is retained in the new text.
3287     *
3288     * @see #setText(CharSequence, android.widget.TextView.BufferType)
3289     */
3290    public final void setTextKeepState(CharSequence text, BufferType type) {
3291        int start = getSelectionStart();
3292        int end = getSelectionEnd();
3293        int len = text.length();
3294
3295        setText(text, type);
3296
3297        if (start >= 0 || end >= 0) {
3298            if (mText instanceof Spannable) {
3299                Selection.setSelection((Spannable) mText,
3300                                       Math.max(0, Math.min(start, len)),
3301                                       Math.max(0, Math.min(end, len)));
3302            }
3303        }
3304    }
3305
3306    @android.view.RemotableViewMethod
3307    public final void setText(int resid) {
3308        setText(getContext().getResources().getText(resid));
3309    }
3310
3311    public final void setText(int resid, BufferType type) {
3312        setText(getContext().getResources().getText(resid), type);
3313    }
3314
3315    /**
3316     * Sets the text to be displayed when the text of the TextView is empty.
3317     * Null means to use the normal empty text. The hint does not currently
3318     * participate in determining the size of the view.
3319     *
3320     * @attr ref android.R.styleable#TextView_hint
3321     */
3322    @android.view.RemotableViewMethod
3323    public final void setHint(CharSequence hint) {
3324        mHint = TextUtils.stringOrSpannedString(hint);
3325
3326        if (mLayout != null) {
3327            checkForRelayout();
3328        }
3329
3330        if (mText.length() == 0) {
3331            invalidate();
3332        }
3333
3334        // Invalidate display list if hint will be used
3335        if (mEditor != null && mText.length() == 0 && mHint != null) {
3336            getEditor().mTextDisplayListIsValid = false;
3337        }
3338    }
3339
3340    /**
3341     * Sets the text to be displayed when the text of the TextView is empty,
3342     * from a resource.
3343     *
3344     * @attr ref android.R.styleable#TextView_hint
3345     */
3346    @android.view.RemotableViewMethod
3347    public final void setHint(int resid) {
3348        setHint(getContext().getResources().getText(resid));
3349    }
3350
3351    /**
3352     * Returns the hint that is displayed when the text of the TextView
3353     * is empty.
3354     *
3355     * @attr ref android.R.styleable#TextView_hint
3356     */
3357    @ViewDebug.CapturedViewProperty
3358    public CharSequence getHint() {
3359        return mHint;
3360    }
3361
3362    private static boolean isMultilineInputType(int type) {
3363        return (type & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) ==
3364            (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
3365    }
3366
3367    /**
3368     * Set the type of the content with a constant as defined for {@link EditorInfo#inputType}. This
3369     * will take care of changing the key listener, by calling {@link #setKeyListener(KeyListener)},
3370     * to match the given content type.  If the given content type is {@link EditorInfo#TYPE_NULL}
3371     * then a soft keyboard will not be displayed for this text view.
3372     *
3373     * Note that the maximum number of displayed lines (see {@link #setMaxLines(int)}) will be
3374     * modified if you change the {@link EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE} flag of the input
3375     * type.
3376     *
3377     * @see #getInputType()
3378     * @see #setRawInputType(int)
3379     * @see android.text.InputType
3380     * @attr ref android.R.styleable#TextView_inputType
3381     */
3382    public void setInputType(int type) {
3383        final boolean wasPassword = isPasswordInputType(getInputType());
3384        final boolean wasVisiblePassword = isVisiblePasswordInputType(getInputType());
3385        setInputType(type, false);
3386        final boolean isPassword = isPasswordInputType(type);
3387        final boolean isVisiblePassword = isVisiblePasswordInputType(type);
3388        boolean forceUpdate = false;
3389        if (isPassword) {
3390            setTransformationMethod(PasswordTransformationMethod.getInstance());
3391            setTypefaceByIndex(MONOSPACE, 0);
3392        } else if (isVisiblePassword) {
3393            if (mTransformation == PasswordTransformationMethod.getInstance()) {
3394                forceUpdate = true;
3395            }
3396            setTypefaceByIndex(MONOSPACE, 0);
3397        } else if (wasPassword || wasVisiblePassword) {
3398            // not in password mode, clean up typeface and transformation
3399            setTypefaceByIndex(-1, -1);
3400            if (mTransformation == PasswordTransformationMethod.getInstance()) {
3401                forceUpdate = true;
3402            }
3403        }
3404
3405        boolean singleLine = !isMultilineInputType(type);
3406
3407        // We need to update the single line mode if it has changed or we
3408        // were previously in password mode.
3409        if (mSingleLine != singleLine || forceUpdate) {
3410            // Change single line mode, but only change the transformation if
3411            // we are not in password mode.
3412            applySingleLine(singleLine, !isPassword, true);
3413        }
3414
3415        if (!isSuggestionsEnabled()) {
3416            mText = removeSuggestionSpans(mText);
3417        }
3418
3419        InputMethodManager imm = InputMethodManager.peekInstance();
3420        if (imm != null) imm.restartInput(this);
3421    }
3422
3423    /**
3424     * It would be better to rely on the input type for everything. A password inputType should have
3425     * a password transformation. We should hence use isPasswordInputType instead of this method.
3426     *
3427     * We should:
3428     * - Call setInputType in setKeyListener instead of changing the input type directly (which
3429     * would install the correct transformation).
3430     * - Refuse the installation of a non-password transformation in setTransformation if the input
3431     * type is password.
3432     *
3433     * However, this is like this for legacy reasons and we cannot break existing apps. This method
3434     * is useful since it matches what the user can see (obfuscated text or not).
3435     *
3436     * @return true if the current transformation method is of the password type.
3437     */
3438    private boolean hasPasswordTransformationMethod() {
3439        return mTransformation instanceof PasswordTransformationMethod;
3440    }
3441
3442    private static boolean isPasswordInputType(int inputType) {
3443        final int variation =
3444                inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION);
3445        return variation
3446                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)
3447                || variation
3448                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD)
3449                || variation
3450                == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD);
3451    }
3452
3453    private static boolean isVisiblePasswordInputType(int inputType) {
3454        final int variation =
3455                inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION);
3456        return variation
3457                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
3458    }
3459
3460    /**
3461     * Directly change the content type integer of the text view, without
3462     * modifying any other state.
3463     * @see #setInputType(int)
3464     * @see android.text.InputType
3465     * @attr ref android.R.styleable#TextView_inputType
3466     */
3467    public void setRawInputType(int type) {
3468        if (type == InputType.TYPE_NULL && mEditor == null) return; //TYPE_NULL is the default value
3469        createEditorIfNeeded("non null input type");
3470        getEditor().mInputType = type;
3471    }
3472
3473    private void setInputType(int type, boolean direct) {
3474        final int cls = type & EditorInfo.TYPE_MASK_CLASS;
3475        KeyListener input;
3476        if (cls == EditorInfo.TYPE_CLASS_TEXT) {
3477            boolean autotext = (type & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) != 0;
3478            TextKeyListener.Capitalize cap;
3479            if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) {
3480                cap = TextKeyListener.Capitalize.CHARACTERS;
3481            } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS) != 0) {
3482                cap = TextKeyListener.Capitalize.WORDS;
3483            } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) {
3484                cap = TextKeyListener.Capitalize.SENTENCES;
3485            } else {
3486                cap = TextKeyListener.Capitalize.NONE;
3487            }
3488            input = TextKeyListener.getInstance(autotext, cap);
3489        } else if (cls == EditorInfo.TYPE_CLASS_NUMBER) {
3490            input = DigitsKeyListener.getInstance(
3491                    (type & EditorInfo.TYPE_NUMBER_FLAG_SIGNED) != 0,
3492                    (type & EditorInfo.TYPE_NUMBER_FLAG_DECIMAL) != 0);
3493        } else if (cls == EditorInfo.TYPE_CLASS_DATETIME) {
3494            switch (type & EditorInfo.TYPE_MASK_VARIATION) {
3495                case EditorInfo.TYPE_DATETIME_VARIATION_DATE:
3496                    input = DateKeyListener.getInstance();
3497                    break;
3498                case EditorInfo.TYPE_DATETIME_VARIATION_TIME:
3499                    input = TimeKeyListener.getInstance();
3500                    break;
3501                default:
3502                    input = DateTimeKeyListener.getInstance();
3503                    break;
3504            }
3505        } else if (cls == EditorInfo.TYPE_CLASS_PHONE) {
3506            input = DialerKeyListener.getInstance();
3507        } else {
3508            input = TextKeyListener.getInstance();
3509        }
3510        setRawInputType(type);
3511        if (direct) {
3512            createEditorIfNeeded("setInputType");
3513            getEditor().mKeyListener = input;
3514        } else {
3515            setKeyListenerOnly(input);
3516        }
3517    }
3518
3519    /**
3520     * Get the type of the editable content.
3521     *
3522     * @see #setInputType(int)
3523     * @see android.text.InputType
3524     */
3525    public int getInputType() {
3526        return mEditor == null ? EditorInfo.TYPE_NULL : getEditor().mInputType;
3527    }
3528
3529    /**
3530     * Change the editor type integer associated with the text view, which
3531     * will be reported to an IME with {@link EditorInfo#imeOptions} when it
3532     * has focus.
3533     * @see #getImeOptions
3534     * @see android.view.inputmethod.EditorInfo
3535     * @attr ref android.R.styleable#TextView_imeOptions
3536     */
3537    public void setImeOptions(int imeOptions) {
3538        createEditorIfNeeded("IME options specified");
3539        if (getEditor().mInputContentType == null) {
3540            getEditor().mInputContentType = new InputContentType();
3541        }
3542        getEditor().mInputContentType.imeOptions = imeOptions;
3543    }
3544
3545    /**
3546     * Get the type of the IME editor.
3547     *
3548     * @see #setImeOptions(int)
3549     * @see android.view.inputmethod.EditorInfo
3550     */
3551    public int getImeOptions() {
3552        return mEditor != null && getEditor().mInputContentType != null
3553                ? getEditor().mInputContentType.imeOptions : EditorInfo.IME_NULL;
3554    }
3555
3556    /**
3557     * Change the custom IME action associated with the text view, which
3558     * will be reported to an IME with {@link EditorInfo#actionLabel}
3559     * and {@link EditorInfo#actionId} when it has focus.
3560     * @see #getImeActionLabel
3561     * @see #getImeActionId
3562     * @see android.view.inputmethod.EditorInfo
3563     * @attr ref android.R.styleable#TextView_imeActionLabel
3564     * @attr ref android.R.styleable#TextView_imeActionId
3565     */
3566    public void setImeActionLabel(CharSequence label, int actionId) {
3567        createEditorIfNeeded("IME action label specified");
3568        if (getEditor().mInputContentType == null) {
3569            getEditor().mInputContentType = new InputContentType();
3570        }
3571        getEditor().mInputContentType.imeActionLabel = label;
3572        getEditor().mInputContentType.imeActionId = actionId;
3573    }
3574
3575    /**
3576     * Get the IME action label previous set with {@link #setImeActionLabel}.
3577     *
3578     * @see #setImeActionLabel
3579     * @see android.view.inputmethod.EditorInfo
3580     */
3581    public CharSequence getImeActionLabel() {
3582        return mEditor != null && getEditor().mInputContentType != null
3583                ? getEditor().mInputContentType.imeActionLabel : null;
3584    }
3585
3586    /**
3587     * Get the IME action ID previous set with {@link #setImeActionLabel}.
3588     *
3589     * @see #setImeActionLabel
3590     * @see android.view.inputmethod.EditorInfo
3591     */
3592    public int getImeActionId() {
3593        return mEditor != null && getEditor().mInputContentType != null
3594                ? getEditor().mInputContentType.imeActionId : 0;
3595    }
3596
3597    /**
3598     * Set a special listener to be called when an action is performed
3599     * on the text view.  This will be called when the enter key is pressed,
3600     * or when an action supplied to the IME is selected by the user.  Setting
3601     * this means that the normal hard key event will not insert a newline
3602     * into the text view, even if it is multi-line; holding down the ALT
3603     * modifier will, however, allow the user to insert a newline character.
3604     */
3605    public void setOnEditorActionListener(OnEditorActionListener l) {
3606        createEditorIfNeeded("Editor action listener set");
3607        if (getEditor().mInputContentType == null) {
3608            getEditor().mInputContentType = new InputContentType();
3609        }
3610        getEditor().mInputContentType.onEditorActionListener = l;
3611    }
3612
3613    /**
3614     * Called when an attached input method calls
3615     * {@link InputConnection#performEditorAction(int)
3616     * InputConnection.performEditorAction()}
3617     * for this text view.  The default implementation will call your action
3618     * listener supplied to {@link #setOnEditorActionListener}, or perform
3619     * a standard operation for {@link EditorInfo#IME_ACTION_NEXT
3620     * EditorInfo.IME_ACTION_NEXT}, {@link EditorInfo#IME_ACTION_PREVIOUS
3621     * EditorInfo.IME_ACTION_PREVIOUS}, or {@link EditorInfo#IME_ACTION_DONE
3622     * EditorInfo.IME_ACTION_DONE}.
3623     *
3624     * <p>For backwards compatibility, if no IME options have been set and the
3625     * text view would not normally advance focus on enter, then
3626     * the NEXT and DONE actions received here will be turned into an enter
3627     * key down/up pair to go through the normal key handling.
3628     *
3629     * @param actionCode The code of the action being performed.
3630     *
3631     * @see #setOnEditorActionListener
3632     */
3633    public void onEditorAction(int actionCode) {
3634        final InputContentType ict = mEditor == null ? null : getEditor().mInputContentType;
3635        if (ict != null) {
3636            if (ict.onEditorActionListener != null) {
3637                if (ict.onEditorActionListener.onEditorAction(this,
3638                        actionCode, null)) {
3639                    return;
3640                }
3641            }
3642
3643            // This is the handling for some default action.
3644            // Note that for backwards compatibility we don't do this
3645            // default handling if explicit ime options have not been given,
3646            // instead turning this into the normal enter key codes that an
3647            // app may be expecting.
3648            if (actionCode == EditorInfo.IME_ACTION_NEXT) {
3649                View v = focusSearch(FOCUS_FORWARD);
3650                if (v != null) {
3651                    if (!v.requestFocus(FOCUS_FORWARD)) {
3652                        throw new IllegalStateException("focus search returned a view " +
3653                                "that wasn't able to take focus!");
3654                    }
3655                }
3656                return;
3657
3658            } else if (actionCode == EditorInfo.IME_ACTION_PREVIOUS) {
3659                View v = focusSearch(FOCUS_BACKWARD);
3660                if (v != null) {
3661                    if (!v.requestFocus(FOCUS_BACKWARD)) {
3662                        throw new IllegalStateException("focus search returned a view " +
3663                                "that wasn't able to take focus!");
3664                    }
3665                }
3666                return;
3667
3668            } else if (actionCode == EditorInfo.IME_ACTION_DONE) {
3669                InputMethodManager imm = InputMethodManager.peekInstance();
3670                if (imm != null && imm.isActive(this)) {
3671                    imm.hideSoftInputFromWindow(getWindowToken(), 0);
3672                }
3673                return;
3674            }
3675        }
3676
3677        ViewRootImpl viewRootImpl = getViewRootImpl();
3678        if (viewRootImpl != null) {
3679            long eventTime = SystemClock.uptimeMillis();
3680            viewRootImpl.dispatchKeyFromIme(
3681                    new KeyEvent(eventTime, eventTime,
3682                    KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0,
3683                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
3684                    KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE
3685                    | KeyEvent.FLAG_EDITOR_ACTION));
3686            viewRootImpl.dispatchKeyFromIme(
3687                    new KeyEvent(SystemClock.uptimeMillis(), eventTime,
3688                    KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0,
3689                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
3690                    KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE
3691                    | KeyEvent.FLAG_EDITOR_ACTION));
3692        }
3693    }
3694
3695    /**
3696     * Set the private content type of the text, which is the
3697     * {@link EditorInfo#privateImeOptions EditorInfo.privateImeOptions}
3698     * field that will be filled in when creating an input connection.
3699     *
3700     * @see #getPrivateImeOptions()
3701     * @see EditorInfo#privateImeOptions
3702     * @attr ref android.R.styleable#TextView_privateImeOptions
3703     */
3704    public void setPrivateImeOptions(String type) {
3705        createEditorIfNeeded("Private IME option set");
3706        if (getEditor().mInputContentType == null)
3707            getEditor().mInputContentType = new InputContentType();
3708        getEditor().mInputContentType.privateImeOptions = type;
3709    }
3710
3711    /**
3712     * Get the private type of the content.
3713     *
3714     * @see #setPrivateImeOptions(String)
3715     * @see EditorInfo#privateImeOptions
3716     */
3717    public String getPrivateImeOptions() {
3718        return mEditor != null && getEditor().mInputContentType != null
3719                ? getEditor().mInputContentType.privateImeOptions : null;
3720    }
3721
3722    /**
3723     * Set the extra input data of the text, which is the
3724     * {@link EditorInfo#extras TextBoxAttribute.extras}
3725     * Bundle that will be filled in when creating an input connection.  The
3726     * given integer is the resource ID of an XML resource holding an
3727     * {@link android.R.styleable#InputExtras &lt;input-extras&gt;} XML tree.
3728     *
3729     * @see #getInputExtras(boolean)
3730     * @see EditorInfo#extras
3731     * @attr ref android.R.styleable#TextView_editorExtras
3732     */
3733    public void setInputExtras(int xmlResId) throws XmlPullParserException, IOException {
3734        createEditorIfNeeded("Input extra set");
3735        XmlResourceParser parser = getResources().getXml(xmlResId);
3736        if (getEditor().mInputContentType == null)
3737            getEditor().mInputContentType = new InputContentType();
3738        getEditor().mInputContentType.extras = new Bundle();
3739        getResources().parseBundleExtras(parser, getEditor().mInputContentType.extras);
3740    }
3741
3742    /**
3743     * Retrieve the input extras currently associated with the text view, which
3744     * can be viewed as well as modified.
3745     *
3746     * @param create If true, the extras will be created if they don't already
3747     * exist.  Otherwise, null will be returned if none have been created.
3748     * @see #setInputExtras(int)
3749     * @see EditorInfo#extras
3750     * @attr ref android.R.styleable#TextView_editorExtras
3751     */
3752    public Bundle getInputExtras(boolean create) {
3753        if (mEditor == null && !create) return null;
3754        createEditorIfNeeded("get Input extra");
3755        if (getEditor().mInputContentType == null) {
3756            if (!create) return null;
3757            getEditor().mInputContentType = new InputContentType();
3758        }
3759        if (getEditor().mInputContentType.extras == null) {
3760            if (!create) return null;
3761            getEditor().mInputContentType.extras = new Bundle();
3762        }
3763        return getEditor().mInputContentType.extras;
3764    }
3765
3766    /**
3767     * Returns the error message that was set to be displayed with
3768     * {@link #setError}, or <code>null</code> if no error was set
3769     * or if it the error was cleared by the widget after user input.
3770     */
3771    public CharSequence getError() {
3772        return mEditor == null ? null : getEditor().mError;
3773    }
3774
3775    /**
3776     * Sets the right-hand compound drawable of the TextView to the "error"
3777     * icon and sets an error message that will be displayed in a popup when
3778     * the TextView has focus.  The icon and error message will be reset to
3779     * null when any key events cause changes to the TextView's text.  If the
3780     * <code>error</code> is <code>null</code>, the error message and icon
3781     * will be cleared.
3782     */
3783    @android.view.RemotableViewMethod
3784    public void setError(CharSequence error) {
3785        if (error == null) {
3786            setError(null, null);
3787        } else {
3788            Drawable dr = getContext().getResources().
3789                getDrawable(com.android.internal.R.drawable.indicator_input_error);
3790
3791            dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());
3792            setError(error, dr);
3793        }
3794    }
3795
3796    /**
3797     * Sets the right-hand compound drawable of the TextView to the specified
3798     * icon and sets an error message that will be displayed in a popup when
3799     * the TextView has focus.  The icon and error message will be reset to
3800     * null when any key events cause changes to the TextView's text.  The
3801     * drawable must already have had {@link Drawable#setBounds} set on it.
3802     * If the <code>error</code> is <code>null</code>, the error message will
3803     * be cleared (and you should provide a <code>null</code> icon as well).
3804     */
3805    public void setError(CharSequence error, Drawable icon) {
3806        createEditorIfNeeded("setError");
3807        error = TextUtils.stringOrSpannedString(error);
3808
3809        getEditor().mError = error;
3810        getEditor().mErrorWasChanged = true;
3811        final Drawables dr = mDrawables;
3812        if (dr != null) {
3813            switch (getResolvedLayoutDirection()) {
3814                default:
3815                case LAYOUT_DIRECTION_LTR:
3816                    setCompoundDrawables(dr.mDrawableLeft, dr.mDrawableTop, icon,
3817                            dr.mDrawableBottom);
3818                    break;
3819                case LAYOUT_DIRECTION_RTL:
3820                    setCompoundDrawables(icon, dr.mDrawableTop, dr.mDrawableRight,
3821                            dr.mDrawableBottom);
3822                    break;
3823            }
3824        } else {
3825            setCompoundDrawables(null, null, icon, null);
3826        }
3827
3828        if (error == null) {
3829            if (getEditor().mErrorPopup != null) {
3830                if (getEditor().mErrorPopup.isShowing()) {
3831                    getEditor().mErrorPopup.dismiss();
3832                }
3833
3834                getEditor().mErrorPopup = null;
3835            }
3836        } else {
3837            if (isFocused()) {
3838                showError();
3839            }
3840        }
3841    }
3842
3843    private void showError() {
3844        if (getWindowToken() == null) {
3845            getEditor().mShowErrorAfterAttach = true;
3846            return;
3847        }
3848
3849        if (getEditor().mErrorPopup == null) {
3850            LayoutInflater inflater = LayoutInflater.from(getContext());
3851            final TextView err = (TextView) inflater.inflate(
3852                    com.android.internal.R.layout.textview_hint, null);
3853
3854            final float scale = getResources().getDisplayMetrics().density;
3855            getEditor().mErrorPopup = new ErrorPopup(err, (int) (200 * scale + 0.5f), (int) (50 * scale + 0.5f));
3856            getEditor().mErrorPopup.setFocusable(false);
3857            // The user is entering text, so the input method is needed.  We
3858            // don't want the popup to be displayed on top of it.
3859            getEditor().mErrorPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
3860        }
3861
3862        TextView tv = (TextView) getEditor().mErrorPopup.getContentView();
3863        chooseSize(getEditor().mErrorPopup, getEditor().mError, tv);
3864        tv.setText(getEditor().mError);
3865
3866        getEditor().mErrorPopup.showAsDropDown(this, getErrorX(), getErrorY());
3867        getEditor().mErrorPopup.fixDirection(getEditor().mErrorPopup.isAboveAnchor());
3868    }
3869
3870    /**
3871     * Returns the Y offset to make the pointy top of the error point
3872     * at the middle of the error icon.
3873     */
3874    private int getErrorX() {
3875        /*
3876         * The "25" is the distance between the point and the right edge
3877         * of the background
3878         */
3879        final float scale = getResources().getDisplayMetrics().density;
3880
3881        final Drawables dr = mDrawables;
3882        return getWidth() - getEditor().mErrorPopup.getWidth() - getPaddingRight() -
3883                (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f);
3884    }
3885
3886    /**
3887     * Returns the Y offset to make the pointy top of the error point
3888     * at the bottom of the error icon.
3889     */
3890    private int getErrorY() {
3891        /*
3892         * Compound, not extended, because the icon is not clipped
3893         * if the text height is smaller.
3894         */
3895        final int compoundPaddingTop = getCompoundPaddingTop();
3896        int vspace = mBottom - mTop - getCompoundPaddingBottom() - compoundPaddingTop;
3897
3898        final Drawables dr = mDrawables;
3899        int icontop = compoundPaddingTop +
3900                (vspace - (dr != null ? dr.mDrawableHeightRight : 0)) / 2;
3901
3902        /*
3903         * The "2" is the distance between the point and the top edge
3904         * of the background.
3905         */
3906        final float scale = getResources().getDisplayMetrics().density;
3907        return icontop + (dr != null ? dr.mDrawableHeightRight : 0) - getHeight() -
3908                (int) (2 * scale + 0.5f);
3909    }
3910
3911    private void hideError() {
3912        if (getEditor().mErrorPopup != null) {
3913            if (getEditor().mErrorPopup.isShowing()) {
3914                getEditor().mErrorPopup.dismiss();
3915            }
3916        }
3917
3918        getEditor().mShowErrorAfterAttach = false;
3919    }
3920
3921    private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) {
3922        int wid = tv.getPaddingLeft() + tv.getPaddingRight();
3923        int ht = tv.getPaddingTop() + tv.getPaddingBottom();
3924
3925        int defaultWidthInPixels = getResources().getDimensionPixelSize(
3926                com.android.internal.R.dimen.textview_error_popup_default_width);
3927        Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels,
3928                                    Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
3929        float max = 0;
3930        for (int i = 0; i < l.getLineCount(); i++) {
3931            max = Math.max(max, l.getLineWidth(i));
3932        }
3933
3934        /*
3935         * Now set the popup size to be big enough for the text plus the border capped
3936         * to DEFAULT_MAX_POPUP_WIDTH
3937         */
3938        pop.setWidth(wid + (int) Math.ceil(max));
3939        pop.setHeight(ht + l.getHeight());
3940    }
3941
3942
3943    @Override
3944    protected boolean setFrame(int l, int t, int r, int b) {
3945        boolean result = super.setFrame(l, t, r, b);
3946
3947        if (mEditor != null) getEditor().setFrame();
3948
3949        restartMarqueeIfNeeded();
3950
3951        return result;
3952    }
3953
3954    private void restartMarqueeIfNeeded() {
3955        if (mRestartMarquee && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
3956            mRestartMarquee = false;
3957            startMarquee();
3958        }
3959    }
3960
3961    /**
3962     * Sets the list of input filters that will be used if the buffer is
3963     * Editable. Has no effect otherwise.
3964     *
3965     * @attr ref android.R.styleable#TextView_maxLength
3966     */
3967    public void setFilters(InputFilter[] filters) {
3968        if (filters == null) {
3969            throw new IllegalArgumentException();
3970        }
3971
3972        mFilters = filters;
3973
3974        if (mText instanceof Editable) {
3975            setFilters((Editable) mText, filters);
3976        }
3977    }
3978
3979    /**
3980     * Sets the list of input filters on the specified Editable,
3981     * and includes mInput in the list if it is an InputFilter.
3982     */
3983    private void setFilters(Editable e, InputFilter[] filters) {
3984        if (mEditor != null && getEditor().mKeyListener instanceof InputFilter) {
3985            InputFilter[] nf = new InputFilter[filters.length + 1];
3986
3987            System.arraycopy(filters, 0, nf, 0, filters.length);
3988            nf[filters.length] = (InputFilter) getEditor().mKeyListener;
3989
3990            e.setFilters(nf);
3991        } else {
3992            e.setFilters(filters);
3993        }
3994    }
3995
3996    /**
3997     * Returns the current list of input filters.
3998     */
3999    public InputFilter[] getFilters() {
4000        return mFilters;
4001    }
4002
4003    /////////////////////////////////////////////////////////////////////////
4004
4005    private int getVerticalOffset(boolean forceNormal) {
4006        int voffset = 0;
4007        final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
4008
4009        Layout l = mLayout;
4010        if (!forceNormal && mText.length() == 0 && mHintLayout != null) {
4011            l = mHintLayout;
4012        }
4013
4014        if (gravity != Gravity.TOP) {
4015            int boxht;
4016
4017            if (l == mHintLayout) {
4018                boxht = getMeasuredHeight() - getCompoundPaddingTop() -
4019                        getCompoundPaddingBottom();
4020            } else {
4021                boxht = getMeasuredHeight() - getExtendedPaddingTop() -
4022                        getExtendedPaddingBottom();
4023            }
4024            int textht = l.getHeight();
4025
4026            if (textht < boxht) {
4027                if (gravity == Gravity.BOTTOM)
4028                    voffset = boxht - textht;
4029                else // (gravity == Gravity.CENTER_VERTICAL)
4030                    voffset = (boxht - textht) >> 1;
4031            }
4032        }
4033        return voffset;
4034    }
4035
4036    private int getBottomVerticalOffset(boolean forceNormal) {
4037        int voffset = 0;
4038        final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
4039
4040        Layout l = mLayout;
4041        if (!forceNormal && mText.length() == 0 && mHintLayout != null) {
4042            l = mHintLayout;
4043        }
4044
4045        if (gravity != Gravity.BOTTOM) {
4046            int boxht;
4047
4048            if (l == mHintLayout) {
4049                boxht = getMeasuredHeight() - getCompoundPaddingTop() -
4050                        getCompoundPaddingBottom();
4051            } else {
4052                boxht = getMeasuredHeight() - getExtendedPaddingTop() -
4053                        getExtendedPaddingBottom();
4054            }
4055            int textht = l.getHeight();
4056
4057            if (textht < boxht) {
4058                if (gravity == Gravity.TOP)
4059                    voffset = boxht - textht;
4060                else // (gravity == Gravity.CENTER_VERTICAL)
4061                    voffset = (boxht - textht) >> 1;
4062            }
4063        }
4064        return voffset;
4065    }
4066
4067    private void invalidateCursorPath() {
4068        if (getEditor().mHighlightPathBogus) {
4069            invalidateCursor();
4070        } else {
4071            final int horizontalPadding = getCompoundPaddingLeft();
4072            final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true);
4073
4074            if (getEditor().mCursorCount == 0) {
4075                synchronized (TEMP_RECTF) {
4076                    /*
4077                     * The reason for this concern about the thickness of the
4078                     * cursor and doing the floor/ceil on the coordinates is that
4079                     * some EditTexts (notably textfields in the Browser) have
4080                     * anti-aliased text where not all the characters are
4081                     * necessarily at integer-multiple locations.  This should
4082                     * make sure the entire cursor gets invalidated instead of
4083                     * sometimes missing half a pixel.
4084                     */
4085                    float thick = FloatMath.ceil(mTextPaint.getStrokeWidth());
4086                    if (thick < 1.0f) {
4087                        thick = 1.0f;
4088                    }
4089
4090                    thick /= 2.0f;
4091
4092                    getEditor().mHighlightPath.computeBounds(TEMP_RECTF, false);
4093
4094                    invalidate((int) FloatMath.floor(horizontalPadding + TEMP_RECTF.left - thick),
4095                            (int) FloatMath.floor(verticalPadding + TEMP_RECTF.top - thick),
4096                            (int) FloatMath.ceil(horizontalPadding + TEMP_RECTF.right + thick),
4097                            (int) FloatMath.ceil(verticalPadding + TEMP_RECTF.bottom + thick));
4098                }
4099            } else {
4100                for (int i = 0; i < getEditor().mCursorCount; i++) {
4101                    Rect bounds = getEditor().mCursorDrawable[i].getBounds();
4102                    invalidate(bounds.left + horizontalPadding, bounds.top + verticalPadding,
4103                            bounds.right + horizontalPadding, bounds.bottom + verticalPadding);
4104                }
4105            }
4106        }
4107    }
4108
4109    private void invalidateCursor() {
4110        int where = getSelectionEnd();
4111
4112        invalidateCursor(where, where, where);
4113    }
4114
4115    private void invalidateCursor(int a, int b, int c) {
4116        if (a >= 0 || b >= 0 || c >= 0) {
4117            int start = Math.min(Math.min(a, b), c);
4118            int end = Math.max(Math.max(a, b), c);
4119            invalidateRegion(start, end, true /* Also invalidates blinking cursor */);
4120        }
4121    }
4122
4123    /**
4124     * Invalidates the region of text enclosed between the start and end text offsets.
4125     *
4126     * @hide
4127     */
4128    void invalidateRegion(int start, int end, boolean invalidateCursor) {
4129        if (mLayout == null) {
4130            invalidate();
4131        } else {
4132                int lineStart = mLayout.getLineForOffset(start);
4133                int top = mLayout.getLineTop(lineStart);
4134
4135                // This is ridiculous, but the descent from the line above
4136                // can hang down into the line we really want to redraw,
4137                // so we have to invalidate part of the line above to make
4138                // sure everything that needs to be redrawn really is.
4139                // (But not the whole line above, because that would cause
4140                // the same problem with the descenders on the line above it!)
4141                if (lineStart > 0) {
4142                    top -= mLayout.getLineDescent(lineStart - 1);
4143                }
4144
4145                int lineEnd;
4146
4147                if (start == end)
4148                    lineEnd = lineStart;
4149                else
4150                    lineEnd = mLayout.getLineForOffset(end);
4151
4152                int bottom = mLayout.getLineBottom(lineEnd);
4153
4154                if (invalidateCursor) {
4155                    for (int i = 0; i < getEditor().mCursorCount; i++) {
4156                        Rect bounds = getEditor().mCursorDrawable[i].getBounds();
4157                        top = Math.min(top, bounds.top);
4158                        bottom = Math.max(bottom, bounds.bottom);
4159                    }
4160                }
4161
4162                final int compoundPaddingLeft = getCompoundPaddingLeft();
4163                final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true);
4164
4165                int left, right;
4166                if (lineStart == lineEnd && !invalidateCursor) {
4167                    left = (int) mLayout.getPrimaryHorizontal(start);
4168                    right = (int) (mLayout.getPrimaryHorizontal(end) + 1.0);
4169                    left += compoundPaddingLeft;
4170                    right += compoundPaddingLeft;
4171                } else {
4172                    // Rectangle bounding box when the region spans several lines
4173                    left = compoundPaddingLeft;
4174                    right = getWidth() - getCompoundPaddingRight();
4175                }
4176
4177                invalidate(mScrollX + left, verticalPadding + top,
4178                        mScrollX + right, verticalPadding + bottom);
4179        }
4180    }
4181
4182    private void registerForPreDraw() {
4183        if (!mPreDrawRegistered) {
4184            getViewTreeObserver().addOnPreDrawListener(this);
4185            mPreDrawRegistered = true;
4186        }
4187    }
4188
4189    /**
4190     * {@inheritDoc}
4191     */
4192    public boolean onPreDraw() {
4193        if (mLayout == null) {
4194            assumeLayout();
4195        }
4196
4197        boolean changed = false;
4198
4199        if (mMovement != null) {
4200            /* This code also provides auto-scrolling when a cursor is moved using a
4201             * CursorController (insertion point or selection limits).
4202             * For selection, ensure start or end is visible depending on controller's state.
4203             */
4204            int curs = getSelectionEnd();
4205            // Do not create the controller if it is not already created.
4206            if (mEditor != null && getEditor().mSelectionModifierCursorController != null &&
4207                    getEditor().mSelectionModifierCursorController.isSelectionStartDragged()) {
4208                curs = getSelectionStart();
4209            }
4210
4211            /*
4212             * TODO: This should really only keep the end in view if
4213             * it already was before the text changed.  I'm not sure
4214             * of a good way to tell from here if it was.
4215             */
4216            if (curs < 0 && (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
4217                curs = mText.length();
4218            }
4219
4220            if (curs >= 0) {
4221                changed = bringPointIntoView(curs);
4222            }
4223        } else {
4224            changed = bringTextIntoView();
4225        }
4226
4227        // This has to be checked here since:
4228        // - onFocusChanged cannot start it when focus is given to a view with selected text (after
4229        //   a screen rotation) since layout is not yet initialized at that point.
4230        if (mEditor != null && getEditor().mCreatedWithASelection) {
4231            startSelectionActionMode();
4232            getEditor().mCreatedWithASelection = false;
4233        }
4234
4235        // Phone specific code (there is no ExtractEditText on tablets).
4236        // ExtractEditText does not call onFocus when it is displayed, and mHasSelectionOnFocus can
4237        // not be set. Do the test here instead.
4238        if (this instanceof ExtractEditText && hasSelection()) {
4239            startSelectionActionMode();
4240        }
4241
4242        getViewTreeObserver().removeOnPreDrawListener(this);
4243        mPreDrawRegistered = false;
4244
4245        return !changed;
4246    }
4247
4248    @Override
4249    protected void onAttachedToWindow() {
4250        super.onAttachedToWindow();
4251
4252        mTemporaryDetach = false;
4253
4254        if (mEditor != null && getEditor().mShowErrorAfterAttach) {
4255            showError();
4256            getEditor().mShowErrorAfterAttach = false;
4257        }
4258
4259        // Resolve drawables as the layout direction has been resolved
4260        resolveDrawables();
4261
4262        if (mEditor != null) getEditor().onAttachedToWindow();
4263    }
4264
4265    @Override
4266    protected void onDetachedFromWindow() {
4267        super.onDetachedFromWindow();
4268
4269        if (mPreDrawRegistered) {
4270            getViewTreeObserver().removeOnPreDrawListener(this);
4271            mPreDrawRegistered = false;
4272        }
4273
4274        resetResolvedDrawables();
4275
4276        if (mEditor != null) getEditor().onDetachedFromWindow();
4277    }
4278
4279    @Override
4280    protected boolean isPaddingOffsetRequired() {
4281        return mShadowRadius != 0 || mDrawables != null;
4282    }
4283
4284    @Override
4285    protected int getLeftPaddingOffset() {
4286        return getCompoundPaddingLeft() - mPaddingLeft +
4287                (int) Math.min(0, mShadowDx - mShadowRadius);
4288    }
4289
4290    @Override
4291    protected int getTopPaddingOffset() {
4292        return (int) Math.min(0, mShadowDy - mShadowRadius);
4293    }
4294
4295    @Override
4296    protected int getBottomPaddingOffset() {
4297        return (int) Math.max(0, mShadowDy + mShadowRadius);
4298    }
4299
4300    @Override
4301    protected int getRightPaddingOffset() {
4302        return -(getCompoundPaddingRight() - mPaddingRight) +
4303                (int) Math.max(0, mShadowDx + mShadowRadius);
4304    }
4305
4306    @Override
4307    protected boolean verifyDrawable(Drawable who) {
4308        final boolean verified = super.verifyDrawable(who);
4309        if (!verified && mDrawables != null) {
4310            return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop ||
4311                    who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom ||
4312                    who == mDrawables.mDrawableStart || who == mDrawables.mDrawableEnd;
4313        }
4314        return verified;
4315    }
4316
4317    @Override
4318    public void jumpDrawablesToCurrentState() {
4319        super.jumpDrawablesToCurrentState();
4320        if (mDrawables != null) {
4321            if (mDrawables.mDrawableLeft != null) {
4322                mDrawables.mDrawableLeft.jumpToCurrentState();
4323            }
4324            if (mDrawables.mDrawableTop != null) {
4325                mDrawables.mDrawableTop.jumpToCurrentState();
4326            }
4327            if (mDrawables.mDrawableRight != null) {
4328                mDrawables.mDrawableRight.jumpToCurrentState();
4329            }
4330            if (mDrawables.mDrawableBottom != null) {
4331                mDrawables.mDrawableBottom.jumpToCurrentState();
4332            }
4333            if (mDrawables.mDrawableStart != null) {
4334                mDrawables.mDrawableStart.jumpToCurrentState();
4335            }
4336            if (mDrawables.mDrawableEnd != null) {
4337                mDrawables.mDrawableEnd.jumpToCurrentState();
4338            }
4339        }
4340    }
4341
4342    @Override
4343    public void invalidateDrawable(Drawable drawable) {
4344        if (verifyDrawable(drawable)) {
4345            final Rect dirty = drawable.getBounds();
4346            int scrollX = mScrollX;
4347            int scrollY = mScrollY;
4348
4349            // IMPORTANT: The coordinates below are based on the coordinates computed
4350            // for each compound drawable in onDraw(). Make sure to update each section
4351            // accordingly.
4352            final TextView.Drawables drawables = mDrawables;
4353            if (drawables != null) {
4354                if (drawable == drawables.mDrawableLeft) {
4355                    final int compoundPaddingTop = getCompoundPaddingTop();
4356                    final int compoundPaddingBottom = getCompoundPaddingBottom();
4357                    final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
4358
4359                    scrollX += mPaddingLeft;
4360                    scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2;
4361                } else if (drawable == drawables.mDrawableRight) {
4362                    final int compoundPaddingTop = getCompoundPaddingTop();
4363                    final int compoundPaddingBottom = getCompoundPaddingBottom();
4364                    final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
4365
4366                    scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight);
4367                    scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2;
4368                } else if (drawable == drawables.mDrawableTop) {
4369                    final int compoundPaddingLeft = getCompoundPaddingLeft();
4370                    final int compoundPaddingRight = getCompoundPaddingRight();
4371                    final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft;
4372
4373                    scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2;
4374                    scrollY += mPaddingTop;
4375                } else if (drawable == drawables.mDrawableBottom) {
4376                    final int compoundPaddingLeft = getCompoundPaddingLeft();
4377                    final int compoundPaddingRight = getCompoundPaddingRight();
4378                    final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft;
4379
4380                    scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2;
4381                    scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom);
4382                }
4383            }
4384
4385            invalidate(dirty.left + scrollX, dirty.top + scrollY,
4386                    dirty.right + scrollX, dirty.bottom + scrollY);
4387        }
4388    }
4389
4390    /**
4391     * @hide
4392     */
4393    @Override
4394    public int getResolvedLayoutDirection(Drawable who) {
4395        if (who == null) return View.LAYOUT_DIRECTION_LTR;
4396        if (mDrawables != null) {
4397            final Drawables drawables = mDrawables;
4398            if (who == drawables.mDrawableLeft || who == drawables.mDrawableRight ||
4399                who == drawables.mDrawableTop || who == drawables.mDrawableBottom ||
4400                who == drawables.mDrawableStart || who == drawables.mDrawableEnd) {
4401                return getResolvedLayoutDirection();
4402            }
4403        }
4404        return super.getResolvedLayoutDirection(who);
4405    }
4406
4407    @Override
4408    protected boolean onSetAlpha(int alpha) {
4409        // Alpha is supported if and only if the drawing can be done in one pass.
4410        // TODO text with spans with a background color currently do not respect this alpha.
4411        if (getBackground() == null) {
4412            if (mCurrentAlpha != alpha) {
4413                mCurrentAlpha = alpha;
4414                final Drawables dr = mDrawables;
4415                if (dr != null) {
4416                    if (dr.mDrawableLeft != null) dr.mDrawableLeft.mutate().setAlpha(alpha);
4417                    if (dr.mDrawableTop != null) dr.mDrawableTop.mutate().setAlpha(alpha);
4418                    if (dr.mDrawableRight != null) dr.mDrawableRight.mutate().setAlpha(alpha);
4419                    if (dr.mDrawableBottom != null) dr.mDrawableBottom.mutate().setAlpha(alpha);
4420                    if (dr.mDrawableStart != null) dr.mDrawableStart.mutate().setAlpha(alpha);
4421                    if (dr.mDrawableEnd != null) dr.mDrawableEnd.mutate().setAlpha(alpha);
4422                }
4423                if (mEditor != null) getEditor().mTextDisplayListIsValid = false;
4424            }
4425            return true;
4426        }
4427
4428        if (mCurrentAlpha != 255) {
4429            if (mEditor != null) getEditor().mTextDisplayListIsValid = false;
4430        }
4431        mCurrentAlpha = 255;
4432        return false;
4433    }
4434
4435    /**
4436     * When a TextView is used to display a useful piece of information to the user (such as a
4437     * contact's address), it should be made selectable, so that the user can select and copy this
4438     * content.
4439     *
4440     * Use {@link #setTextIsSelectable(boolean)} or the
4441     * {@link android.R.styleable#TextView_textIsSelectable} XML attribute to make this TextView
4442     * selectable (text is not selectable by default).
4443     *
4444     * Note that this method simply returns the state of this flag. Although this flag has to be set
4445     * in order to select text in non-editable TextView, the content of an {@link EditText} can
4446     * always be selected, independently of the value of this flag.
4447     *
4448     * @return True if the text displayed in this TextView can be selected by the user.
4449     *
4450     * @attr ref android.R.styleable#TextView_textIsSelectable
4451     */
4452    public boolean isTextSelectable() {
4453        return mEditor == null ? false : getEditor().mTextIsSelectable;
4454    }
4455
4456    /**
4457     * Sets whether or not (default) the content of this view is selectable by the user.
4458     *
4459     * Note that this methods affect the {@link #setFocusable(boolean)},
4460     * {@link #setFocusableInTouchMode(boolean)} {@link #setClickable(boolean)} and
4461     * {@link #setLongClickable(boolean)} states and you may want to restore these if they were
4462     * customized.
4463     *
4464     * See {@link #isTextSelectable} for details.
4465     *
4466     * @param selectable Whether or not the content of this TextView should be selectable.
4467     */
4468    public void setTextIsSelectable(boolean selectable) {
4469        if (!selectable && mEditor == null) return; // false is default value with no edit data
4470
4471        createEditorIfNeeded("setTextIsSelectable");
4472        if (getEditor().mTextIsSelectable == selectable) return;
4473
4474        getEditor().mTextIsSelectable = selectable;
4475        setFocusableInTouchMode(selectable);
4476        setFocusable(selectable);
4477        setClickable(selectable);
4478        setLongClickable(selectable);
4479
4480        // mInputType should already be EditorInfo.TYPE_NULL and mInput should be null
4481
4482        setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null);
4483        setText(getText(), selectable ? BufferType.SPANNABLE : BufferType.NORMAL);
4484
4485        // Called by setText above, but safer in case of future code changes
4486        prepareCursorControllers();
4487    }
4488
4489    @Override
4490    protected int[] onCreateDrawableState(int extraSpace) {
4491        final int[] drawableState;
4492
4493        if (mSingleLine) {
4494            drawableState = super.onCreateDrawableState(extraSpace);
4495        } else {
4496            drawableState = super.onCreateDrawableState(extraSpace + 1);
4497            mergeDrawableStates(drawableState, MULTILINE_STATE_SET);
4498        }
4499
4500        if (isTextSelectable()) {
4501            // Disable pressed state, which was introduced when TextView was made clickable.
4502            // Prevents text color change.
4503            // setClickable(false) would have a similar effect, but it also disables focus changes
4504            // and long press actions, which are both needed by text selection.
4505            final int length = drawableState.length;
4506            for (int i = 0; i < length; i++) {
4507                if (drawableState[i] == R.attr.state_pressed) {
4508                    final int[] nonPressedState = new int[length - 1];
4509                    System.arraycopy(drawableState, 0, nonPressedState, 0, i);
4510                    System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1);
4511                    return nonPressedState;
4512                }
4513            }
4514        }
4515
4516        return drawableState;
4517    }
4518
4519    @Override
4520    protected void onDraw(Canvas canvas) {
4521        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return;
4522
4523        restartMarqueeIfNeeded();
4524
4525        // Draw the background for this view
4526        super.onDraw(canvas);
4527
4528        final int compoundPaddingLeft = getCompoundPaddingLeft();
4529        final int compoundPaddingTop = getCompoundPaddingTop();
4530        final int compoundPaddingRight = getCompoundPaddingRight();
4531        final int compoundPaddingBottom = getCompoundPaddingBottom();
4532        final int scrollX = mScrollX;
4533        final int scrollY = mScrollY;
4534        final int right = mRight;
4535        final int left = mLeft;
4536        final int bottom = mBottom;
4537        final int top = mTop;
4538
4539        final Drawables dr = mDrawables;
4540        if (dr != null) {
4541            /*
4542             * Compound, not extended, because the icon is not clipped
4543             * if the text height is smaller.
4544             */
4545
4546            int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop;
4547            int hspace = right - left - compoundPaddingRight - compoundPaddingLeft;
4548
4549            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4550            // Make sure to update invalidateDrawable() when changing this code.
4551            if (dr.mDrawableLeft != null) {
4552                canvas.save();
4553                canvas.translate(scrollX + mPaddingLeft,
4554                                 scrollY + compoundPaddingTop +
4555                                 (vspace - dr.mDrawableHeightLeft) / 2);
4556                dr.mDrawableLeft.draw(canvas);
4557                canvas.restore();
4558            }
4559
4560            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4561            // Make sure to update invalidateDrawable() when changing this code.
4562            if (dr.mDrawableRight != null) {
4563                canvas.save();
4564                canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight,
4565                         scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2);
4566                dr.mDrawableRight.draw(canvas);
4567                canvas.restore();
4568            }
4569
4570            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4571            // Make sure to update invalidateDrawable() when changing this code.
4572            if (dr.mDrawableTop != null) {
4573                canvas.save();
4574                canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2,
4575                        scrollY + mPaddingTop);
4576                dr.mDrawableTop.draw(canvas);
4577                canvas.restore();
4578            }
4579
4580            // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
4581            // Make sure to update invalidateDrawable() when changing this code.
4582            if (dr.mDrawableBottom != null) {
4583                canvas.save();
4584                canvas.translate(scrollX + compoundPaddingLeft +
4585                        (hspace - dr.mDrawableWidthBottom) / 2,
4586                         scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom);
4587                dr.mDrawableBottom.draw(canvas);
4588                canvas.restore();
4589            }
4590        }
4591
4592        int color = mCurTextColor;
4593
4594        if (mLayout == null) {
4595            assumeLayout();
4596        }
4597
4598        Layout layout = mLayout;
4599
4600        if (mHint != null && mText.length() == 0) {
4601            if (mHintTextColor != null) {
4602                color = mCurHintTextColor;
4603            }
4604
4605            layout = mHintLayout;
4606        }
4607
4608        mTextPaint.setColor(color);
4609        if (mCurrentAlpha != 255) {
4610            // If set, the alpha will override the color's alpha. Multiply the alphas.
4611            mTextPaint.setAlpha((mCurrentAlpha * Color.alpha(color)) / 255);
4612        }
4613        mTextPaint.drawableState = getDrawableState();
4614
4615        canvas.save();
4616        /*  Would be faster if we didn't have to do this. Can we chop the
4617            (displayable) text so that we don't need to do this ever?
4618        */
4619
4620        int extendedPaddingTop = getExtendedPaddingTop();
4621        int extendedPaddingBottom = getExtendedPaddingBottom();
4622
4623        final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop;
4624        final int maxScrollY = mLayout.getHeight() - vspace;
4625
4626        float clipLeft = compoundPaddingLeft + scrollX;
4627        float clipTop = (scrollY == 0) ? 0 : extendedPaddingTop + scrollY;
4628        float clipRight = right - left - compoundPaddingRight + scrollX;
4629        float clipBottom = bottom - top + scrollY -
4630                ((scrollY == maxScrollY) ? 0 : extendedPaddingBottom);
4631
4632        if (mShadowRadius != 0) {
4633            clipLeft += Math.min(0, mShadowDx - mShadowRadius);
4634            clipRight += Math.max(0, mShadowDx + mShadowRadius);
4635
4636            clipTop += Math.min(0, mShadowDy - mShadowRadius);
4637            clipBottom += Math.max(0, mShadowDy + mShadowRadius);
4638        }
4639
4640        canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom);
4641
4642        int voffsetText = 0;
4643        int voffsetCursor = 0;
4644
4645        // translate in by our padding
4646        /* shortcircuit calling getVerticaOffset() */
4647        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4648            voffsetText = getVerticalOffset(false);
4649            voffsetCursor = getVerticalOffset(true);
4650        }
4651        canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText);
4652
4653        final int layoutDirection = getResolvedLayoutDirection();
4654        final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
4655        if (mEllipsize == TextUtils.TruncateAt.MARQUEE &&
4656                mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
4657            if (!mSingleLine && getLineCount() == 1 && canMarquee() &&
4658                    (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) {
4659                canvas.translate(mLayout.getLineRight(0) - (mRight - mLeft -
4660                        getCompoundPaddingLeft() - getCompoundPaddingRight()), 0.0f);
4661            }
4662
4663            if (mMarquee != null && mMarquee.isRunning()) {
4664                canvas.translate(-mMarquee.mScroll, 0.0f);
4665            }
4666        }
4667
4668        final int cursorOffsetVertical = voffsetCursor - voffsetText;
4669
4670        if (mEditor != null) {
4671            getEditor().onDraw(canvas, layout, cursorOffsetVertical);
4672        } else {
4673            layout.draw(canvas, null, null, cursorOffsetVertical);
4674
4675            if (mMarquee != null && mMarquee.shouldDrawGhost()) {
4676                canvas.translate((int) mMarquee.getGhostOffset(), 0.0f);
4677                layout.draw(canvas, null, null, cursorOffsetVertical);
4678            }
4679        }
4680
4681        canvas.restore();
4682    }
4683
4684    private void updateCursorsPositions() {
4685        if (mCursorDrawableRes == 0) {
4686            getEditor().mCursorCount = 0;
4687            return;
4688        }
4689
4690        final int offset = getSelectionStart();
4691        final int line = mLayout.getLineForOffset(offset);
4692        final int top = mLayout.getLineTop(line);
4693        final int bottom = mLayout.getLineTop(line + 1);
4694
4695        getEditor().mCursorCount = mLayout.isLevelBoundary(offset) ? 2 : 1;
4696
4697        int middle = bottom;
4698        if (getEditor().mCursorCount == 2) {
4699            // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)}
4700            middle = (top + bottom) >> 1;
4701        }
4702
4703        updateCursorPosition(0, top, middle, mLayout.getPrimaryHorizontal(offset));
4704
4705        if (getEditor().mCursorCount == 2) {
4706            updateCursorPosition(1, middle, bottom, mLayout.getSecondaryHorizontal(offset));
4707        }
4708    }
4709
4710    private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) {
4711        if (getEditor().mCursorDrawable[cursorIndex] == null)
4712            getEditor().mCursorDrawable[cursorIndex] = mContext.getResources().getDrawable(mCursorDrawableRes);
4713
4714        if (mTempRect == null) mTempRect = new Rect();
4715        getEditor().mCursorDrawable[cursorIndex].getPadding(mTempRect);
4716        final int width = getEditor().mCursorDrawable[cursorIndex].getIntrinsicWidth();
4717        horizontal = Math.max(0.5f, horizontal - 0.5f);
4718        final int left = (int) (horizontal) - mTempRect.left;
4719        getEditor().mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width,
4720                bottom + mTempRect.bottom);
4721    }
4722
4723    private void drawCursor(Canvas canvas, int cursorOffsetVertical) {
4724        final boolean translate = cursorOffsetVertical != 0;
4725        if (translate) canvas.translate(0, cursorOffsetVertical);
4726        for (int i = 0; i < getEditor().mCursorCount; i++) {
4727            getEditor().mCursorDrawable[i].draw(canvas);
4728        }
4729        if (translate) canvas.translate(0, -cursorOffsetVertical);
4730    }
4731
4732    @Override
4733    public void getFocusedRect(Rect r) {
4734        if (mLayout == null) {
4735            super.getFocusedRect(r);
4736            return;
4737        }
4738
4739        int selEnd = getSelectionEnd();
4740        if (selEnd < 0) {
4741            super.getFocusedRect(r);
4742            return;
4743        }
4744
4745        int selStart = getSelectionStart();
4746        if (selStart < 0 || selStart >= selEnd) {
4747            int line = mLayout.getLineForOffset(selEnd);
4748            r.top = mLayout.getLineTop(line);
4749            r.bottom = mLayout.getLineBottom(line);
4750            r.left = (int) mLayout.getPrimaryHorizontal(selEnd) - 2;
4751            r.right = r.left + 4;
4752        } else {
4753            int lineStart = mLayout.getLineForOffset(selStart);
4754            int lineEnd = mLayout.getLineForOffset(selEnd);
4755            r.top = mLayout.getLineTop(lineStart);
4756            r.bottom = mLayout.getLineBottom(lineEnd);
4757            if (lineStart == lineEnd) {
4758                r.left = (int) mLayout.getPrimaryHorizontal(selStart);
4759                r.right = (int) mLayout.getPrimaryHorizontal(selEnd);
4760            } else {
4761                // Selection extends across multiple lines -- make the focused
4762                // rect cover the entire width.
4763                if (mEditor != null) {
4764                    if (getEditor().mHighlightPath == null) getEditor().mHighlightPath = new Path();
4765                    if (getEditor().mHighlightPathBogus) {
4766                        getEditor().mHighlightPath.reset();
4767                        mLayout.getSelectionPath(selStart, selEnd, getEditor().mHighlightPath);
4768                        getEditor().mHighlightPathBogus = false;
4769                    }
4770                    synchronized (TEMP_RECTF) {
4771                        getEditor().mHighlightPath.computeBounds(TEMP_RECTF, true);
4772                        r.left = (int)TEMP_RECTF.left-1;
4773                        r.right = (int)TEMP_RECTF.right+1;
4774                    }
4775                } else {
4776                    r.left = 0;
4777                    r.right = getMeasuredWidth();
4778                }
4779            }
4780        }
4781
4782        // Adjust for padding and gravity.
4783        int paddingLeft = getCompoundPaddingLeft();
4784        int paddingTop = getExtendedPaddingTop();
4785        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4786            paddingTop += getVerticalOffset(false);
4787        }
4788        r.offset(paddingLeft, paddingTop);
4789    }
4790
4791    /**
4792     * Return the number of lines of text, or 0 if the internal Layout has not
4793     * been built.
4794     */
4795    public int getLineCount() {
4796        return mLayout != null ? mLayout.getLineCount() : 0;
4797    }
4798
4799    /**
4800     * Return the baseline for the specified line (0...getLineCount() - 1)
4801     * If bounds is not null, return the top, left, right, bottom extents
4802     * of the specified line in it. If the internal Layout has not been built,
4803     * return 0 and set bounds to (0, 0, 0, 0)
4804     * @param line which line to examine (0..getLineCount() - 1)
4805     * @param bounds Optional. If not null, it returns the extent of the line
4806     * @return the Y-coordinate of the baseline
4807     */
4808    public int getLineBounds(int line, Rect bounds) {
4809        if (mLayout == null) {
4810            if (bounds != null) {
4811                bounds.set(0, 0, 0, 0);
4812            }
4813            return 0;
4814        }
4815        else {
4816            int baseline = mLayout.getLineBounds(line, bounds);
4817
4818            int voffset = getExtendedPaddingTop();
4819            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4820                voffset += getVerticalOffset(true);
4821            }
4822            if (bounds != null) {
4823                bounds.offset(getCompoundPaddingLeft(), voffset);
4824            }
4825            return baseline + voffset;
4826        }
4827    }
4828
4829    @Override
4830    public int getBaseline() {
4831        if (mLayout == null) {
4832            return super.getBaseline();
4833        }
4834
4835        int voffset = 0;
4836        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4837            voffset = getVerticalOffset(true);
4838        }
4839
4840        return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0);
4841    }
4842
4843    /**
4844     * @hide
4845     * @param offsetRequired
4846     */
4847    @Override
4848    protected int getFadeTop(boolean offsetRequired) {
4849        if (mLayout == null) return 0;
4850
4851        int voffset = 0;
4852        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
4853            voffset = getVerticalOffset(true);
4854        }
4855
4856        if (offsetRequired) voffset += getTopPaddingOffset();
4857
4858        return getExtendedPaddingTop() + voffset;
4859    }
4860
4861    /**
4862     * @hide
4863     * @param offsetRequired
4864     */
4865    @Override
4866    protected int getFadeHeight(boolean offsetRequired) {
4867        return mLayout != null ? mLayout.getHeight() : 0;
4868    }
4869
4870    @Override
4871    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4872        if (keyCode == KeyEvent.KEYCODE_BACK) {
4873            boolean isInSelectionMode = mEditor != null && getEditor().mSelectionActionMode != null;
4874
4875            if (isInSelectionMode) {
4876                if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
4877                    KeyEvent.DispatcherState state = getKeyDispatcherState();
4878                    if (state != null) {
4879                        state.startTracking(event, this);
4880                    }
4881                    return true;
4882                } else if (event.getAction() == KeyEvent.ACTION_UP) {
4883                    KeyEvent.DispatcherState state = getKeyDispatcherState();
4884                    if (state != null) {
4885                        state.handleUpEvent(event);
4886                    }
4887                    if (event.isTracking() && !event.isCanceled()) {
4888                        stopSelectionActionMode();
4889                        return true;
4890                    }
4891                }
4892            }
4893        }
4894        return super.onKeyPreIme(keyCode, event);
4895    }
4896
4897    @Override
4898    public boolean onKeyDown(int keyCode, KeyEvent event) {
4899        int which = doKeyDown(keyCode, event, null);
4900        if (which == 0) {
4901            // Go through default dispatching.
4902            return super.onKeyDown(keyCode, event);
4903        }
4904
4905        return true;
4906    }
4907
4908    @Override
4909    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4910        KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN);
4911
4912        int which = doKeyDown(keyCode, down, event);
4913        if (which == 0) {
4914            // Go through default dispatching.
4915            return super.onKeyMultiple(keyCode, repeatCount, event);
4916        }
4917        if (which == -1) {
4918            // Consumed the whole thing.
4919            return true;
4920        }
4921
4922        repeatCount--;
4923
4924        // We are going to dispatch the remaining events to either the input
4925        // or movement method.  To do this, we will just send a repeated stream
4926        // of down and up events until we have done the complete repeatCount.
4927        // It would be nice if those interfaces had an onKeyMultiple() method,
4928        // but adding that is a more complicated change.
4929        KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP);
4930        if (which == 1) {
4931            // mEditor and getEditor().mInput are not null from doKeyDown
4932            getEditor().mKeyListener.onKeyUp(this, (Editable)mText, keyCode, up);
4933            while (--repeatCount > 0) {
4934                getEditor().mKeyListener.onKeyDown(this, (Editable)mText, keyCode, down);
4935                getEditor().mKeyListener.onKeyUp(this, (Editable)mText, keyCode, up);
4936            }
4937            hideErrorIfUnchanged();
4938
4939        } else if (which == 2) {
4940            // mMovement is not null from doKeyDown
4941            mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
4942            while (--repeatCount > 0) {
4943                mMovement.onKeyDown(this, (Spannable)mText, keyCode, down);
4944                mMovement.onKeyUp(this, (Spannable)mText, keyCode, up);
4945            }
4946        }
4947
4948        return true;
4949    }
4950
4951    /**
4952     * Returns true if pressing ENTER in this field advances focus instead
4953     * of inserting the character.  This is true mostly in single-line fields,
4954     * but also in mail addresses and subjects which will display on multiple
4955     * lines but where it doesn't make sense to insert newlines.
4956     */
4957    private boolean shouldAdvanceFocusOnEnter() {
4958        if (getKeyListener() == null) {
4959            return false;
4960        }
4961
4962        if (mSingleLine) {
4963            return true;
4964        }
4965
4966        if (mEditor != null && (getEditor().mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
4967            int variation = getEditor().mInputType & EditorInfo.TYPE_MASK_VARIATION;
4968            if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
4969                    || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) {
4970                return true;
4971            }
4972        }
4973
4974        return false;
4975    }
4976
4977    /**
4978     * Returns true if pressing TAB in this field advances focus instead
4979     * of inserting the character.  Insert tabs only in multi-line editors.
4980     */
4981    private boolean shouldAdvanceFocusOnTab() {
4982        if (getKeyListener() != null && !mSingleLine) {
4983            if (mEditor != null && (getEditor().mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
4984                int variation = getEditor().mInputType & EditorInfo.TYPE_MASK_VARIATION;
4985                if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE
4986                        || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) {
4987                    return false;
4988                }
4989            }
4990        }
4991        return true;
4992    }
4993
4994    private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) {
4995        if (!isEnabled()) {
4996            return 0;
4997        }
4998
4999        switch (keyCode) {
5000            case KeyEvent.KEYCODE_ENTER:
5001                if (event.hasNoModifiers()) {
5002                    // When mInputContentType is set, we know that we are
5003                    // running in a "modern" cupcake environment, so don't need
5004                    // to worry about the application trying to capture
5005                    // enter key events.
5006                    if (mEditor != null && getEditor().mInputContentType != null) {
5007                        // If there is an action listener, given them a
5008                        // chance to consume the event.
5009                        if (getEditor().mInputContentType.onEditorActionListener != null &&
5010                                getEditor().mInputContentType.onEditorActionListener.onEditorAction(
5011                                this, EditorInfo.IME_NULL, event)) {
5012                            getEditor().mInputContentType.enterDown = true;
5013                            // We are consuming the enter key for them.
5014                            return -1;
5015                        }
5016                    }
5017
5018                    // If our editor should move focus when enter is pressed, or
5019                    // this is a generated event from an IME action button, then
5020                    // don't let it be inserted into the text.
5021                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
5022                            || shouldAdvanceFocusOnEnter()) {
5023                        if (hasOnClickListeners()) {
5024                            return 0;
5025                        }
5026                        return -1;
5027                    }
5028                }
5029                break;
5030
5031            case KeyEvent.KEYCODE_DPAD_CENTER:
5032                if (event.hasNoModifiers()) {
5033                    if (shouldAdvanceFocusOnEnter()) {
5034                        return 0;
5035                    }
5036                }
5037                break;
5038
5039            case KeyEvent.KEYCODE_TAB:
5040                if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
5041                    if (shouldAdvanceFocusOnTab()) {
5042                        return 0;
5043                    }
5044                }
5045                break;
5046
5047                // Has to be done on key down (and not on key up) to correctly be intercepted.
5048            case KeyEvent.KEYCODE_BACK:
5049                if (mEditor != null && getEditor().mSelectionActionMode != null) {
5050                    stopSelectionActionMode();
5051                    return -1;
5052                }
5053                break;
5054        }
5055
5056        if (mEditor != null && getEditor().mKeyListener != null) {
5057            resetErrorChangedFlag();
5058
5059            boolean doDown = true;
5060            if (otherEvent != null) {
5061                try {
5062                    beginBatchEdit();
5063                    final boolean handled = getEditor().mKeyListener.onKeyOther(this, (Editable) mText, otherEvent);
5064                    hideErrorIfUnchanged();
5065                    doDown = false;
5066                    if (handled) {
5067                        return -1;
5068                    }
5069                } catch (AbstractMethodError e) {
5070                    // onKeyOther was added after 1.0, so if it isn't
5071                    // implemented we need to try to dispatch as a regular down.
5072                } finally {
5073                    endBatchEdit();
5074                }
5075            }
5076
5077            if (doDown) {
5078                beginBatchEdit();
5079                final boolean handled = getEditor().mKeyListener.onKeyDown(this, (Editable) mText, keyCode, event);
5080                endBatchEdit();
5081                hideErrorIfUnchanged();
5082                if (handled) return 1;
5083            }
5084        }
5085
5086        // bug 650865: sometimes we get a key event before a layout.
5087        // don't try to move around if we don't know the layout.
5088
5089        if (mMovement != null && mLayout != null) {
5090            boolean doDown = true;
5091            if (otherEvent != null) {
5092                try {
5093                    boolean handled = mMovement.onKeyOther(this, (Spannable) mText,
5094                            otherEvent);
5095                    doDown = false;
5096                    if (handled) {
5097                        return -1;
5098                    }
5099                } catch (AbstractMethodError e) {
5100                    // onKeyOther was added after 1.0, so if it isn't
5101                    // implemented we need to try to dispatch as a regular down.
5102                }
5103            }
5104            if (doDown) {
5105                if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event))
5106                    return 2;
5107            }
5108        }
5109
5110        return 0;
5111    }
5112
5113    /**
5114     * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)}
5115     * can be recorded.
5116     * @hide
5117     */
5118    public void resetErrorChangedFlag() {
5119        /*
5120         * Keep track of what the error was before doing the input
5121         * so that if an input filter changed the error, we leave
5122         * that error showing.  Otherwise, we take down whatever
5123         * error was showing when the user types something.
5124         */
5125        if (mEditor != null) getEditor().mErrorWasChanged = false;
5126    }
5127
5128    /**
5129     * @hide
5130     */
5131    public void hideErrorIfUnchanged() {
5132        if (mEditor != null && getEditor().mError != null && !getEditor().mErrorWasChanged) {
5133            setError(null, null);
5134        }
5135    }
5136
5137    @Override
5138    public boolean onKeyUp(int keyCode, KeyEvent event) {
5139        if (!isEnabled()) {
5140            return super.onKeyUp(keyCode, event);
5141        }
5142
5143        switch (keyCode) {
5144            case KeyEvent.KEYCODE_DPAD_CENTER:
5145                if (event.hasNoModifiers()) {
5146                    /*
5147                     * If there is a click listener, just call through to
5148                     * super, which will invoke it.
5149                     *
5150                     * If there isn't a click listener, try to show the soft
5151                     * input method.  (It will also
5152                     * call performClick(), but that won't do anything in
5153                     * this case.)
5154                     */
5155                    if (!hasOnClickListeners()) {
5156                        if (mMovement != null && mText instanceof Editable
5157                                && mLayout != null && onCheckIsTextEditor()) {
5158                            InputMethodManager imm = InputMethodManager.peekInstance();
5159                            viewClicked(imm);
5160                            if (imm != null) {
5161                                imm.showSoftInput(this, 0);
5162                            }
5163                        }
5164                    }
5165                }
5166                return super.onKeyUp(keyCode, event);
5167
5168            case KeyEvent.KEYCODE_ENTER:
5169                if (event.hasNoModifiers()) {
5170                    if (mEditor != null && getEditor().mInputContentType != null
5171                            && getEditor().mInputContentType.onEditorActionListener != null
5172                            && getEditor().mInputContentType.enterDown) {
5173                        getEditor().mInputContentType.enterDown = false;
5174                        if (getEditor().mInputContentType.onEditorActionListener.onEditorAction(
5175                                this, EditorInfo.IME_NULL, event)) {
5176                            return true;
5177                        }
5178                    }
5179
5180                    if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
5181                            || shouldAdvanceFocusOnEnter()) {
5182                        /*
5183                         * If there is a click listener, just call through to
5184                         * super, which will invoke it.
5185                         *
5186                         * If there isn't a click listener, try to advance focus,
5187                         * but still call through to super, which will reset the
5188                         * pressed state and longpress state.  (It will also
5189                         * call performClick(), but that won't do anything in
5190                         * this case.)
5191                         */
5192                        if (!hasOnClickListeners()) {
5193                            View v = focusSearch(FOCUS_DOWN);
5194
5195                            if (v != null) {
5196                                if (!v.requestFocus(FOCUS_DOWN)) {
5197                                    throw new IllegalStateException(
5198                                            "focus search returned a view " +
5199                                            "that wasn't able to take focus!");
5200                                }
5201
5202                                /*
5203                                 * Return true because we handled the key; super
5204                                 * will return false because there was no click
5205                                 * listener.
5206                                 */
5207                                super.onKeyUp(keyCode, event);
5208                                return true;
5209                            } else if ((event.getFlags()
5210                                    & KeyEvent.FLAG_EDITOR_ACTION) != 0) {
5211                                // No target for next focus, but make sure the IME
5212                                // if this came from it.
5213                                InputMethodManager imm = InputMethodManager.peekInstance();
5214                                if (imm != null && imm.isActive(this)) {
5215                                    imm.hideSoftInputFromWindow(getWindowToken(), 0);
5216                                }
5217                            }
5218                        }
5219                    }
5220                    return super.onKeyUp(keyCode, event);
5221                }
5222                break;
5223        }
5224
5225        if (mEditor != null && getEditor().mKeyListener != null)
5226            if (getEditor().mKeyListener.onKeyUp(this, (Editable) mText, keyCode, event))
5227                return true;
5228
5229        if (mMovement != null && mLayout != null)
5230            if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event))
5231                return true;
5232
5233        return super.onKeyUp(keyCode, event);
5234    }
5235
5236    @Override
5237    public boolean onCheckIsTextEditor() {
5238        return mEditor != null && getEditor().mInputType != EditorInfo.TYPE_NULL;
5239    }
5240
5241    @Override
5242    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
5243        createEditorIfNeeded("onCreateInputConnection");
5244        if (onCheckIsTextEditor() && isEnabled()) {
5245            if (getEditor().mInputMethodState == null) {
5246                getEditor().mInputMethodState = new InputMethodState();
5247            }
5248            outAttrs.inputType = getInputType();
5249            if (getEditor().mInputContentType != null) {
5250                outAttrs.imeOptions = getEditor().mInputContentType.imeOptions;
5251                outAttrs.privateImeOptions = getEditor().mInputContentType.privateImeOptions;
5252                outAttrs.actionLabel = getEditor().mInputContentType.imeActionLabel;
5253                outAttrs.actionId = getEditor().mInputContentType.imeActionId;
5254                outAttrs.extras = getEditor().mInputContentType.extras;
5255            } else {
5256                outAttrs.imeOptions = EditorInfo.IME_NULL;
5257            }
5258            if (focusSearch(FOCUS_DOWN) != null) {
5259                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT;
5260            }
5261            if (focusSearch(FOCUS_UP) != null) {
5262                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS;
5263            }
5264            if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION)
5265                    == EditorInfo.IME_ACTION_UNSPECIFIED) {
5266                if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) {
5267                    // An action has not been set, but the enter key will move to
5268                    // the next focus, so set the action to that.
5269                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT;
5270                } else {
5271                    // An action has not been set, and there is no focus to move
5272                    // to, so let's just supply a "done" action.
5273                    outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
5274                }
5275                if (!shouldAdvanceFocusOnEnter()) {
5276                    outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
5277                }
5278            }
5279            if (isMultilineInputType(outAttrs.inputType)) {
5280                // Multi-line text editors should always show an enter key.
5281                outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION;
5282            }
5283            outAttrs.hintText = mHint;
5284            if (mText instanceof Editable) {
5285                InputConnection ic = new EditableInputConnection(this);
5286                outAttrs.initialSelStart = getSelectionStart();
5287                outAttrs.initialSelEnd = getSelectionEnd();
5288                outAttrs.initialCapsMode = ic.getCursorCapsMode(getInputType());
5289                return ic;
5290            }
5291        }
5292        return null;
5293    }
5294
5295    /**
5296     * If this TextView contains editable content, extract a portion of it
5297     * based on the information in <var>request</var> in to <var>outText</var>.
5298     * @return Returns true if the text was successfully extracted, else false.
5299     */
5300    public boolean extractText(ExtractedTextRequest request,
5301            ExtractedText outText) {
5302        return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN,
5303                EXTRACT_UNKNOWN, outText);
5304    }
5305
5306    static final int EXTRACT_NOTHING = -2;
5307    static final int EXTRACT_UNKNOWN = -1;
5308
5309    boolean extractTextInternal(ExtractedTextRequest request,
5310            int partialStartOffset, int partialEndOffset, int delta,
5311            ExtractedText outText) {
5312        final CharSequence content = mText;
5313        if (content != null) {
5314            if (partialStartOffset != EXTRACT_NOTHING) {
5315                final int N = content.length();
5316                if (partialStartOffset < 0) {
5317                    outText.partialStartOffset = outText.partialEndOffset = -1;
5318                    partialStartOffset = 0;
5319                    partialEndOffset = N;
5320                } else {
5321                    // Now use the delta to determine the actual amount of text
5322                    // we need.
5323                    partialEndOffset += delta;
5324                    // Adjust offsets to ensure we contain full spans.
5325                    if (content instanceof Spanned) {
5326                        Spanned spanned = (Spanned)content;
5327                        Object[] spans = spanned.getSpans(partialStartOffset,
5328                                partialEndOffset, ParcelableSpan.class);
5329                        int i = spans.length;
5330                        while (i > 0) {
5331                            i--;
5332                            int j = spanned.getSpanStart(spans[i]);
5333                            if (j < partialStartOffset) partialStartOffset = j;
5334                            j = spanned.getSpanEnd(spans[i]);
5335                            if (j > partialEndOffset) partialEndOffset = j;
5336                        }
5337                    }
5338                    outText.partialStartOffset = partialStartOffset;
5339                    outText.partialEndOffset = partialEndOffset - delta;
5340
5341                    if (partialStartOffset > N) {
5342                        partialStartOffset = N;
5343                    } else if (partialStartOffset < 0) {
5344                        partialStartOffset = 0;
5345                    }
5346                    if (partialEndOffset > N) {
5347                        partialEndOffset = N;
5348                    } else if (partialEndOffset < 0) {
5349                        partialEndOffset = 0;
5350                    }
5351                }
5352                if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) {
5353                    outText.text = content.subSequence(partialStartOffset,
5354                            partialEndOffset);
5355                } else {
5356                    outText.text = TextUtils.substring(content, partialStartOffset,
5357                            partialEndOffset);
5358                }
5359            } else {
5360                outText.partialStartOffset = 0;
5361                outText.partialEndOffset = 0;
5362                outText.text = "";
5363            }
5364            outText.flags = 0;
5365            if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) {
5366                outText.flags |= ExtractedText.FLAG_SELECTING;
5367            }
5368            if (mSingleLine) {
5369                outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
5370            }
5371            outText.startOffset = 0;
5372            outText.selectionStart = getSelectionStart();
5373            outText.selectionEnd = getSelectionEnd();
5374            return true;
5375        }
5376        return false;
5377    }
5378
5379    boolean reportExtractedText() {
5380        final InputMethodState ims = getEditor().mInputMethodState;
5381        if (ims != null) {
5382            final boolean contentChanged = ims.mContentChanged;
5383            if (contentChanged || ims.mSelectionModeChanged) {
5384                ims.mContentChanged = false;
5385                ims.mSelectionModeChanged = false;
5386                final ExtractedTextRequest req = ims.mExtracting;
5387                if (req != null) {
5388                    InputMethodManager imm = InputMethodManager.peekInstance();
5389                    if (imm != null) {
5390                        if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start="
5391                                + ims.mChangedStart + " end=" + ims.mChangedEnd
5392                                + " delta=" + ims.mChangedDelta);
5393                        if (ims.mChangedStart < 0 && !contentChanged) {
5394                            ims.mChangedStart = EXTRACT_NOTHING;
5395                        }
5396                        if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd,
5397                                ims.mChangedDelta, ims.mTmpExtracted)) {
5398                            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start="
5399                                    + ims.mTmpExtracted.partialStartOffset
5400                                    + " end=" + ims.mTmpExtracted.partialEndOffset
5401                                    + ": " + ims.mTmpExtracted.text);
5402                            imm.updateExtractedText(this, req.token, ims.mTmpExtracted);
5403                            ims.mChangedStart = EXTRACT_UNKNOWN;
5404                            ims.mChangedEnd = EXTRACT_UNKNOWN;
5405                            ims.mChangedDelta = 0;
5406                            ims.mContentChanged = false;
5407                            return true;
5408                        }
5409                    }
5410                }
5411            }
5412        }
5413        return false;
5414    }
5415
5416    /**
5417     * This is used to remove all style-impacting spans from text before new
5418     * extracted text is being replaced into it, so that we don't have any
5419     * lingering spans applied during the replace.
5420     */
5421    static void removeParcelableSpans(Spannable spannable, int start, int end) {
5422        Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class);
5423        int i = spans.length;
5424        while (i > 0) {
5425            i--;
5426            spannable.removeSpan(spans[i]);
5427        }
5428    }
5429
5430    /**
5431     * Apply to this text view the given extracted text, as previously
5432     * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}.
5433     */
5434    public void setExtractedText(ExtractedText text) {
5435        Editable content = getEditableText();
5436        if (text.text != null) {
5437            if (content == null) {
5438                setText(text.text, TextView.BufferType.EDITABLE);
5439            } else if (text.partialStartOffset < 0) {
5440                removeParcelableSpans(content, 0, content.length());
5441                content.replace(0, content.length(), text.text);
5442            } else {
5443                final int N = content.length();
5444                int start = text.partialStartOffset;
5445                if (start > N) start = N;
5446                int end = text.partialEndOffset;
5447                if (end > N) end = N;
5448                removeParcelableSpans(content, start, end);
5449                content.replace(start, end, text.text);
5450            }
5451        }
5452
5453        // Now set the selection position...  make sure it is in range, to
5454        // avoid crashes.  If this is a partial update, it is possible that
5455        // the underlying text may have changed, causing us problems here.
5456        // Also we just don't want to trust clients to do the right thing.
5457        Spannable sp = (Spannable)getText();
5458        final int N = sp.length();
5459        int start = text.selectionStart;
5460        if (start < 0) start = 0;
5461        else if (start > N) start = N;
5462        int end = text.selectionEnd;
5463        if (end < 0) end = 0;
5464        else if (end > N) end = N;
5465        Selection.setSelection(sp, start, end);
5466
5467        // Finally, update the selection mode.
5468        if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) {
5469            MetaKeyKeyListener.startSelecting(this, sp);
5470        } else {
5471            MetaKeyKeyListener.stopSelecting(this, sp);
5472        }
5473    }
5474
5475    /**
5476     * @hide
5477     */
5478    public void setExtracting(ExtractedTextRequest req) {
5479        if (getEditor().mInputMethodState != null) {
5480            getEditor().mInputMethodState.mExtracting = req;
5481        }
5482        // This would stop a possible selection mode, but no such mode is started in case
5483        // extracted mode will start. Some text is selected though, and will trigger an action mode
5484        // in the extracted view.
5485        hideControllers();
5486    }
5487
5488    /**
5489     * Called by the framework in response to a text completion from
5490     * the current input method, provided by it calling
5491     * {@link InputConnection#commitCompletion
5492     * InputConnection.commitCompletion()}.  The default implementation does
5493     * nothing; text views that are supporting auto-completion should override
5494     * this to do their desired behavior.
5495     *
5496     * @param text The auto complete text the user has selected.
5497     */
5498    public void onCommitCompletion(CompletionInfo text) {
5499        // intentionally empty
5500    }
5501
5502    /**
5503     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
5504     * a dictionnary) from the current input method, provided by it calling
5505     * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
5506     * implementation flashes the background of the corrected word to provide feedback to the user.
5507     *
5508     * @param info The auto correct info about the text that was corrected.
5509     */
5510    public void onCommitCorrection(CorrectionInfo info) {
5511        if (mEditor == null) return;
5512        if (getEditor().mCorrectionHighlighter == null) {
5513            getEditor().mCorrectionHighlighter = new CorrectionHighlighter();
5514        } else {
5515            getEditor().mCorrectionHighlighter.invalidate(false);
5516        }
5517
5518        getEditor().mCorrectionHighlighter.highlight(info);
5519    }
5520
5521    public void beginBatchEdit() {
5522        if (mEditor == null) return;
5523        getEditor().mInBatchEditControllers = true;
5524        final InputMethodState ims = getEditor().mInputMethodState;
5525        if (ims != null) {
5526            int nesting = ++ims.mBatchEditNesting;
5527            if (nesting == 1) {
5528                ims.mCursorChanged = false;
5529                ims.mChangedDelta = 0;
5530                if (ims.mContentChanged) {
5531                    // We already have a pending change from somewhere else,
5532                    // so turn this into a full update.
5533                    ims.mChangedStart = 0;
5534                    ims.mChangedEnd = mText.length();
5535                } else {
5536                    ims.mChangedStart = EXTRACT_UNKNOWN;
5537                    ims.mChangedEnd = EXTRACT_UNKNOWN;
5538                    ims.mContentChanged = false;
5539                }
5540                onBeginBatchEdit();
5541            }
5542        }
5543    }
5544
5545    public void endBatchEdit() {
5546        if (mEditor == null) return;
5547        getEditor().mInBatchEditControllers = false;
5548        final InputMethodState ims = getEditor().mInputMethodState;
5549        if (ims != null) {
5550            int nesting = --ims.mBatchEditNesting;
5551            if (nesting == 0) {
5552                finishBatchEdit(ims);
5553            }
5554        }
5555    }
5556
5557    void ensureEndedBatchEdit() {
5558        final InputMethodState ims = getEditor().mInputMethodState;
5559        if (ims != null && ims.mBatchEditNesting != 0) {
5560            ims.mBatchEditNesting = 0;
5561            finishBatchEdit(ims);
5562        }
5563    }
5564
5565    void finishBatchEdit(final InputMethodState ims) {
5566        onEndBatchEdit();
5567
5568        if (ims.mContentChanged || ims.mSelectionModeChanged) {
5569            updateAfterEdit();
5570            reportExtractedText();
5571        } else if (ims.mCursorChanged) {
5572            // Cheezy way to get us to report the current cursor location.
5573            invalidateCursor();
5574        }
5575    }
5576
5577    void updateAfterEdit() {
5578        invalidate();
5579        int curs = getSelectionStart();
5580
5581        if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
5582            registerForPreDraw();
5583        }
5584
5585        if (curs >= 0) {
5586            getEditor().mHighlightPathBogus = true;
5587            makeBlink();
5588            bringPointIntoView(curs);
5589        }
5590
5591        checkForResize();
5592    }
5593
5594    /**
5595     * Called by the framework in response to a request to begin a batch
5596     * of edit operations through a call to link {@link #beginBatchEdit()}.
5597     */
5598    public void onBeginBatchEdit() {
5599        // intentionally empty
5600    }
5601
5602    /**
5603     * Called by the framework in response to a request to end a batch
5604     * of edit operations through a call to link {@link #endBatchEdit}.
5605     */
5606    public void onEndBatchEdit() {
5607        // intentionally empty
5608    }
5609
5610    /**
5611     * Called by the framework in response to a private command from the
5612     * current method, provided by it calling
5613     * {@link InputConnection#performPrivateCommand
5614     * InputConnection.performPrivateCommand()}.
5615     *
5616     * @param action The action name of the command.
5617     * @param data Any additional data for the command.  This may be null.
5618     * @return Return true if you handled the command, else false.
5619     */
5620    public boolean onPrivateIMECommand(String action, Bundle data) {
5621        return false;
5622    }
5623
5624    private void nullLayouts() {
5625        if (mLayout instanceof BoringLayout && mSavedLayout == null) {
5626            mSavedLayout = (BoringLayout) mLayout;
5627        }
5628        if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) {
5629            mSavedHintLayout = (BoringLayout) mHintLayout;
5630        }
5631
5632        mSavedMarqueeModeLayout = mLayout = mHintLayout = null;
5633
5634        mBoring = mHintBoring = null;
5635
5636        // Since it depends on the value of mLayout
5637        prepareCursorControllers();
5638    }
5639
5640    /**
5641     * Make a new Layout based on the already-measured size of the view,
5642     * on the assumption that it was measured correctly at some point.
5643     */
5644    private void assumeLayout() {
5645        int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
5646
5647        if (width < 1) {
5648            width = 0;
5649        }
5650
5651        int physicalWidth = width;
5652
5653        if (mHorizontallyScrolling) {
5654            width = VERY_WIDE;
5655        }
5656
5657        makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING,
5658                      physicalWidth, false);
5659    }
5660
5661    @Override
5662    protected void resetResolvedLayoutDirection() {
5663        super.resetResolvedLayoutDirection();
5664
5665        if (mLayoutAlignment != null &&
5666                (mTextAlign == TEXT_ALIGN.VIEW_START ||
5667                mTextAlign == TEXT_ALIGN.VIEW_END)) {
5668            mLayoutAlignment = null;
5669        }
5670    }
5671
5672    private Layout.Alignment getLayoutAlignment() {
5673        if (mLayoutAlignment == null) {
5674            Layout.Alignment alignment;
5675            TEXT_ALIGN textAlign = mTextAlign;
5676            switch (textAlign) {
5677                case INHERIT:
5678                    // fall through to gravity temporarily
5679                    // intention is to inherit value through view hierarchy.
5680                case GRAVITY:
5681                    switch (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) {
5682                        case Gravity.START:
5683                            alignment = Layout.Alignment.ALIGN_NORMAL;
5684                            break;
5685                        case Gravity.END:
5686                            alignment = Layout.Alignment.ALIGN_OPPOSITE;
5687                            break;
5688                        case Gravity.LEFT:
5689                            alignment = Layout.Alignment.ALIGN_LEFT;
5690                            break;
5691                        case Gravity.RIGHT:
5692                            alignment = Layout.Alignment.ALIGN_RIGHT;
5693                            break;
5694                        case Gravity.CENTER_HORIZONTAL:
5695                            alignment = Layout.Alignment.ALIGN_CENTER;
5696                            break;
5697                        default:
5698                            alignment = Layout.Alignment.ALIGN_NORMAL;
5699                            break;
5700                    }
5701                    break;
5702                case TEXT_START:
5703                    alignment = Layout.Alignment.ALIGN_NORMAL;
5704                    break;
5705                case TEXT_END:
5706                    alignment = Layout.Alignment.ALIGN_OPPOSITE;
5707                    break;
5708                case CENTER:
5709                    alignment = Layout.Alignment.ALIGN_CENTER;
5710                    break;
5711                case VIEW_START:
5712                    alignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
5713                            Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT;
5714                    break;
5715                case VIEW_END:
5716                    alignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
5717                            Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT;
5718                    break;
5719                default:
5720                    alignment = Layout.Alignment.ALIGN_NORMAL;
5721                    break;
5722            }
5723            mLayoutAlignment = alignment;
5724        }
5725        return mLayoutAlignment;
5726    }
5727
5728    /**
5729     * The width passed in is now the desired layout width,
5730     * not the full view width with padding.
5731     * {@hide}
5732     */
5733    protected void makeNewLayout(int wantWidth, int hintWidth,
5734                                 BoringLayout.Metrics boring,
5735                                 BoringLayout.Metrics hintBoring,
5736                                 int ellipsisWidth, boolean bringIntoView) {
5737        stopMarquee();
5738
5739        // Update "old" cached values
5740        mOldMaximum = mMaximum;
5741        mOldMaxMode = mMaxMode;
5742
5743        if (mEditor != null) getEditor().mHighlightPathBogus = true;
5744
5745        if (wantWidth < 0) {
5746            wantWidth = 0;
5747        }
5748        if (hintWidth < 0) {
5749            hintWidth = 0;
5750        }
5751
5752        Layout.Alignment alignment = getLayoutAlignment();
5753        boolean shouldEllipsize = mEllipsize != null && getKeyListener() == null;
5754        final boolean switchEllipsize = mEllipsize == TruncateAt.MARQUEE &&
5755                mMarqueeFadeMode != MARQUEE_FADE_NORMAL;
5756        TruncateAt effectiveEllipsize = mEllipsize;
5757        if (mEllipsize == TruncateAt.MARQUEE &&
5758                mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
5759            effectiveEllipsize = TruncateAt.END_SMALL;
5760        }
5761
5762        if (mTextDir == null) {
5763            resolveTextDirection();
5764        }
5765
5766        mLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize,
5767                effectiveEllipsize, effectiveEllipsize == mEllipsize);
5768        if (switchEllipsize) {
5769            TruncateAt oppositeEllipsize = effectiveEllipsize == TruncateAt.MARQUEE ?
5770                    TruncateAt.END : TruncateAt.MARQUEE;
5771            mSavedMarqueeModeLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment,
5772                    shouldEllipsize, oppositeEllipsize, effectiveEllipsize != mEllipsize);
5773        }
5774
5775        shouldEllipsize = mEllipsize != null;
5776        mHintLayout = null;
5777
5778        if (mHint != null) {
5779            if (shouldEllipsize) hintWidth = wantWidth;
5780
5781            if (hintBoring == UNKNOWN_BORING) {
5782                hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir,
5783                                                   mHintBoring);
5784                if (hintBoring != null) {
5785                    mHintBoring = hintBoring;
5786                }
5787            }
5788
5789            if (hintBoring != null) {
5790                if (hintBoring.width <= hintWidth &&
5791                    (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) {
5792                    if (mSavedHintLayout != null) {
5793                        mHintLayout = mSavedHintLayout.
5794                                replaceOrMake(mHint, mTextPaint,
5795                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5796                                hintBoring, mIncludePad);
5797                    } else {
5798                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5799                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5800                                hintBoring, mIncludePad);
5801                    }
5802
5803                    mSavedHintLayout = (BoringLayout) mHintLayout;
5804                } else if (shouldEllipsize && hintBoring.width <= hintWidth) {
5805                    if (mSavedHintLayout != null) {
5806                        mHintLayout = mSavedHintLayout.
5807                                replaceOrMake(mHint, mTextPaint,
5808                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5809                                hintBoring, mIncludePad, mEllipsize,
5810                                ellipsisWidth);
5811                    } else {
5812                        mHintLayout = BoringLayout.make(mHint, mTextPaint,
5813                                hintWidth, alignment, mSpacingMult, mSpacingAdd,
5814                                hintBoring, mIncludePad, mEllipsize,
5815                                ellipsisWidth);
5816                    }
5817                } else if (shouldEllipsize) {
5818                    mHintLayout = new StaticLayout(mHint,
5819                                0, mHint.length(),
5820                                mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult,
5821                                mSpacingAdd, mIncludePad, mEllipsize,
5822                                ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
5823                } else {
5824                    mHintLayout = new StaticLayout(mHint, mTextPaint,
5825                            hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd,
5826                            mIncludePad);
5827                }
5828            } else if (shouldEllipsize) {
5829                mHintLayout = new StaticLayout(mHint,
5830                            0, mHint.length(),
5831                            mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult,
5832                            mSpacingAdd, mIncludePad, mEllipsize,
5833                            ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
5834            } else {
5835                mHintLayout = new StaticLayout(mHint, mTextPaint,
5836                        hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd,
5837                        mIncludePad);
5838            }
5839        }
5840
5841        if (bringIntoView) {
5842            registerForPreDraw();
5843        }
5844
5845        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
5846            if (!compressText(ellipsisWidth)) {
5847                final int height = mLayoutParams.height;
5848                // If the size of the view does not depend on the size of the text, try to
5849                // start the marquee immediately
5850                if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) {
5851                    startMarquee();
5852                } else {
5853                    // Defer the start of the marquee until we know our width (see setFrame())
5854                    mRestartMarquee = true;
5855                }
5856            }
5857        }
5858
5859        // CursorControllers need a non-null mLayout
5860        prepareCursorControllers();
5861    }
5862
5863    private Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth,
5864            Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize,
5865            boolean useSaved) {
5866        Layout result = null;
5867        if (mText instanceof Spannable) {
5868            result = new DynamicLayout(mText, mTransformed, mTextPaint, wantWidth,
5869                    alignment, mTextDir, mSpacingMult,
5870                    mSpacingAdd, mIncludePad, getKeyListener() == null ? effectiveEllipsize : null,
5871                            ellipsisWidth);
5872        } else {
5873            if (boring == UNKNOWN_BORING) {
5874                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
5875                if (boring != null) {
5876                    mBoring = boring;
5877                }
5878            }
5879
5880            if (boring != null) {
5881                if (boring.width <= wantWidth &&
5882                        (effectiveEllipsize == null || boring.width <= ellipsisWidth)) {
5883                    if (useSaved && mSavedLayout != null) {
5884                        result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint,
5885                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
5886                                boring, mIncludePad);
5887                    } else {
5888                        result = BoringLayout.make(mTransformed, mTextPaint,
5889                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
5890                                boring, mIncludePad);
5891                    }
5892
5893                    if (useSaved) {
5894                        mSavedLayout = (BoringLayout) result;
5895                    }
5896                } else if (shouldEllipsize && boring.width <= wantWidth) {
5897                    if (useSaved && mSavedLayout != null) {
5898                        result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint,
5899                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
5900                                boring, mIncludePad, effectiveEllipsize,
5901                                ellipsisWidth);
5902                    } else {
5903                        result = BoringLayout.make(mTransformed, mTextPaint,
5904                                wantWidth, alignment, mSpacingMult, mSpacingAdd,
5905                                boring, mIncludePad, effectiveEllipsize,
5906                                ellipsisWidth);
5907                    }
5908                } else if (shouldEllipsize) {
5909                    result = new StaticLayout(mTransformed,
5910                            0, mTransformed.length(),
5911                            mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult,
5912                            mSpacingAdd, mIncludePad, effectiveEllipsize,
5913                            ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
5914                } else {
5915                    result = new StaticLayout(mTransformed, mTextPaint,
5916                            wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd,
5917                            mIncludePad);
5918                }
5919            } else if (shouldEllipsize) {
5920                result = new StaticLayout(mTransformed,
5921                        0, mTransformed.length(),
5922                        mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult,
5923                        mSpacingAdd, mIncludePad, effectiveEllipsize,
5924                        ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
5925            } else {
5926                result = new StaticLayout(mTransformed, mTextPaint,
5927                        wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd,
5928                        mIncludePad);
5929            }
5930        }
5931        return result;
5932    }
5933
5934    private boolean compressText(float width) {
5935        if (isHardwareAccelerated()) return false;
5936
5937        // Only compress the text if it hasn't been compressed by the previous pass
5938        if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX &&
5939                mTextPaint.getTextScaleX() == 1.0f) {
5940            final float textWidth = mLayout.getLineWidth(0);
5941            final float overflow = (textWidth + 1.0f - width) / width;
5942            if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) {
5943                mTextPaint.setTextScaleX(1.0f - overflow - 0.005f);
5944                post(new Runnable() {
5945                    public void run() {
5946                        requestLayout();
5947                    }
5948                });
5949                return true;
5950            }
5951        }
5952
5953        return false;
5954    }
5955
5956    private static int desired(Layout layout) {
5957        int n = layout.getLineCount();
5958        CharSequence text = layout.getText();
5959        float max = 0;
5960
5961        // if any line was wrapped, we can't use it.
5962        // but it's ok for the last line not to have a newline
5963
5964        for (int i = 0; i < n - 1; i++) {
5965            if (text.charAt(layout.getLineEnd(i) - 1) != '\n')
5966                return -1;
5967        }
5968
5969        for (int i = 0; i < n; i++) {
5970            max = Math.max(max, layout.getLineWidth(i));
5971        }
5972
5973        return (int) FloatMath.ceil(max);
5974    }
5975
5976    /**
5977     * Set whether the TextView includes extra top and bottom padding to make
5978     * room for accents that go above the normal ascent and descent.
5979     * The default is true.
5980     *
5981     * @attr ref android.R.styleable#TextView_includeFontPadding
5982     */
5983    public void setIncludeFontPadding(boolean includepad) {
5984        if (mIncludePad != includepad) {
5985            mIncludePad = includepad;
5986
5987            if (mLayout != null) {
5988                nullLayouts();
5989                requestLayout();
5990                invalidate();
5991            }
5992        }
5993    }
5994
5995    private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics();
5996
5997    @Override
5998    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
5999        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
6000        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
6001        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
6002        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
6003
6004        int width;
6005        int height;
6006
6007        BoringLayout.Metrics boring = UNKNOWN_BORING;
6008        BoringLayout.Metrics hintBoring = UNKNOWN_BORING;
6009
6010        if (mTextDir == null) {
6011            resolveTextDirection();
6012        }
6013
6014        int des = -1;
6015        boolean fromexisting = false;
6016
6017        if (widthMode == MeasureSpec.EXACTLY) {
6018            // Parent has told us how big to be. So be it.
6019            width = widthSize;
6020        } else {
6021            if (mLayout != null && mEllipsize == null) {
6022                des = desired(mLayout);
6023            }
6024
6025            if (des < 0) {
6026                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
6027                if (boring != null) {
6028                    mBoring = boring;
6029                }
6030            } else {
6031                fromexisting = true;
6032            }
6033
6034            if (boring == null || boring == UNKNOWN_BORING) {
6035                if (des < 0) {
6036                    des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint));
6037                }
6038
6039                width = des;
6040            } else {
6041                width = boring.width;
6042            }
6043
6044            final Drawables dr = mDrawables;
6045            if (dr != null) {
6046                width = Math.max(width, dr.mDrawableWidthTop);
6047                width = Math.max(width, dr.mDrawableWidthBottom);
6048            }
6049
6050            if (mHint != null) {
6051                int hintDes = -1;
6052                int hintWidth;
6053
6054                if (mHintLayout != null && mEllipsize == null) {
6055                    hintDes = desired(mHintLayout);
6056                }
6057
6058                if (hintDes < 0) {
6059                    hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring);
6060                    if (hintBoring != null) {
6061                        mHintBoring = hintBoring;
6062                    }
6063                }
6064
6065                if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
6066                    if (hintDes < 0) {
6067                        hintDes = (int) FloatMath.ceil(
6068                                Layout.getDesiredWidth(mHint, mTextPaint));
6069                    }
6070
6071                    hintWidth = hintDes;
6072                } else {
6073                    hintWidth = hintBoring.width;
6074                }
6075
6076                if (hintWidth > width) {
6077                    width = hintWidth;
6078                }
6079            }
6080
6081            width += getCompoundPaddingLeft() + getCompoundPaddingRight();
6082
6083            if (mMaxWidthMode == EMS) {
6084                width = Math.min(width, mMaxWidth * getLineHeight());
6085            } else {
6086                width = Math.min(width, mMaxWidth);
6087            }
6088
6089            if (mMinWidthMode == EMS) {
6090                width = Math.max(width, mMinWidth * getLineHeight());
6091            } else {
6092                width = Math.max(width, mMinWidth);
6093            }
6094
6095            // Check against our minimum width
6096            width = Math.max(width, getSuggestedMinimumWidth());
6097
6098            if (widthMode == MeasureSpec.AT_MOST) {
6099                width = Math.min(widthSize, width);
6100            }
6101        }
6102
6103        int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight();
6104        int unpaddedWidth = want;
6105
6106        if (mHorizontallyScrolling) want = VERY_WIDE;
6107
6108        int hintWant = want;
6109        int hintWidth = (mHintLayout == null) ? hintWant : mHintLayout.getWidth();
6110
6111        if (mLayout == null) {
6112            makeNewLayout(want, hintWant, boring, hintBoring,
6113                          width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
6114        } else {
6115            final boolean layoutChanged = (mLayout.getWidth() != want) ||
6116                    (hintWidth != hintWant) ||
6117                    (mLayout.getEllipsizedWidth() !=
6118                            width - getCompoundPaddingLeft() - getCompoundPaddingRight());
6119
6120            final boolean widthChanged = (mHint == null) &&
6121                    (mEllipsize == null) &&
6122                    (want > mLayout.getWidth()) &&
6123                    (mLayout instanceof BoringLayout || (fromexisting && des >= 0 && des <= want));
6124
6125            final boolean maximumChanged = (mMaxMode != mOldMaxMode) || (mMaximum != mOldMaximum);
6126
6127            if (layoutChanged || maximumChanged) {
6128                if (!maximumChanged && widthChanged) {
6129                    mLayout.increaseWidthTo(want);
6130                } else {
6131                    makeNewLayout(want, hintWant, boring, hintBoring,
6132                            width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
6133                }
6134            } else {
6135                // Nothing has changed
6136            }
6137        }
6138
6139        if (heightMode == MeasureSpec.EXACTLY) {
6140            // Parent has told us how big to be. So be it.
6141            height = heightSize;
6142            mDesiredHeightAtMeasure = -1;
6143        } else {
6144            int desired = getDesiredHeight();
6145
6146            height = desired;
6147            mDesiredHeightAtMeasure = desired;
6148
6149            if (heightMode == MeasureSpec.AT_MOST) {
6150                height = Math.min(desired, heightSize);
6151            }
6152        }
6153
6154        int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
6155        if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) {
6156            unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum));
6157        }
6158
6159        /*
6160         * We didn't let makeNewLayout() register to bring the cursor into view,
6161         * so do it here if there is any possibility that it is needed.
6162         */
6163        if (mMovement != null ||
6164            mLayout.getWidth() > unpaddedWidth ||
6165            mLayout.getHeight() > unpaddedHeight) {
6166            registerForPreDraw();
6167        } else {
6168            scrollTo(0, 0);
6169        }
6170
6171        setMeasuredDimension(width, height);
6172    }
6173
6174    private int getDesiredHeight() {
6175        return Math.max(
6176                getDesiredHeight(mLayout, true),
6177                getDesiredHeight(mHintLayout, mEllipsize != null));
6178    }
6179
6180    private int getDesiredHeight(Layout layout, boolean cap) {
6181        if (layout == null) {
6182            return 0;
6183        }
6184
6185        int linecount = layout.getLineCount();
6186        int pad = getCompoundPaddingTop() + getCompoundPaddingBottom();
6187        int desired = layout.getLineTop(linecount);
6188
6189        final Drawables dr = mDrawables;
6190        if (dr != null) {
6191            desired = Math.max(desired, dr.mDrawableHeightLeft);
6192            desired = Math.max(desired, dr.mDrawableHeightRight);
6193        }
6194
6195        desired += pad;
6196
6197        if (mMaxMode == LINES) {
6198            /*
6199             * Don't cap the hint to a certain number of lines.
6200             * (Do cap it, though, if we have a maximum pixel height.)
6201             */
6202            if (cap) {
6203                if (linecount > mMaximum) {
6204                    desired = layout.getLineTop(mMaximum);
6205
6206                    if (dr != null) {
6207                        desired = Math.max(desired, dr.mDrawableHeightLeft);
6208                        desired = Math.max(desired, dr.mDrawableHeightRight);
6209                    }
6210
6211                    desired += pad;
6212                    linecount = mMaximum;
6213                }
6214            }
6215        } else {
6216            desired = Math.min(desired, mMaximum);
6217        }
6218
6219        if (mMinMode == LINES) {
6220            if (linecount < mMinimum) {
6221                desired += getLineHeight() * (mMinimum - linecount);
6222            }
6223        } else {
6224            desired = Math.max(desired, mMinimum);
6225        }
6226
6227        // Check against our minimum height
6228        desired = Math.max(desired, getSuggestedMinimumHeight());
6229
6230        return desired;
6231    }
6232
6233    /**
6234     * Check whether a change to the existing text layout requires a
6235     * new view layout.
6236     */
6237    private void checkForResize() {
6238        boolean sizeChanged = false;
6239
6240        if (mLayout != null) {
6241            // Check if our width changed
6242            if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) {
6243                sizeChanged = true;
6244                invalidate();
6245            }
6246
6247            // Check if our height changed
6248            if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) {
6249                int desiredHeight = getDesiredHeight();
6250
6251                if (desiredHeight != this.getHeight()) {
6252                    sizeChanged = true;
6253                }
6254            } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) {
6255                if (mDesiredHeightAtMeasure >= 0) {
6256                    int desiredHeight = getDesiredHeight();
6257
6258                    if (desiredHeight != mDesiredHeightAtMeasure) {
6259                        sizeChanged = true;
6260                    }
6261                }
6262            }
6263        }
6264
6265        if (sizeChanged) {
6266            requestLayout();
6267            // caller will have already invalidated
6268        }
6269    }
6270
6271    /**
6272     * Check whether entirely new text requires a new view layout
6273     * or merely a new text layout.
6274     */
6275    private void checkForRelayout() {
6276        // If we have a fixed width, we can just swap in a new text layout
6277        // if the text height stays the same or if the view height is fixed.
6278
6279        if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT ||
6280                (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) &&
6281                (mHint == null || mHintLayout != null) &&
6282                (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) {
6283            // Static width, so try making a new text layout.
6284
6285            int oldht = mLayout.getHeight();
6286            int want = mLayout.getWidth();
6287            int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();
6288
6289            /*
6290             * No need to bring the text into view, since the size is not
6291             * changing (unless we do the requestLayout(), in which case it
6292             * will happen at measure).
6293             */
6294            makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
6295                          mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(),
6296                          false);
6297
6298            if (mEllipsize != TextUtils.TruncateAt.MARQUEE) {
6299                // In a fixed-height view, so use our new text layout.
6300                if (mLayoutParams.height != LayoutParams.WRAP_CONTENT &&
6301                    mLayoutParams.height != LayoutParams.MATCH_PARENT) {
6302                    invalidate();
6303                    return;
6304                }
6305
6306                // Dynamic height, but height has stayed the same,
6307                // so use our new text layout.
6308                if (mLayout.getHeight() == oldht &&
6309                    (mHintLayout == null || mHintLayout.getHeight() == oldht)) {
6310                    invalidate();
6311                    return;
6312                }
6313            }
6314
6315            // We lose: the height has changed and we have a dynamic height.
6316            // Request a new view layout using our new text layout.
6317            requestLayout();
6318            invalidate();
6319        } else {
6320            // Dynamic width, so we have no choice but to request a new
6321            // view layout with a new text layout.
6322            nullLayouts();
6323            requestLayout();
6324            invalidate();
6325        }
6326    }
6327
6328    @Override
6329    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
6330        super.onLayout(changed, left, top, right, bottom);
6331        if (changed && mEditor != null) getEditor().mTextDisplayListIsValid = false;
6332    }
6333
6334    /**
6335     * Returns true if anything changed.
6336     */
6337    private boolean bringTextIntoView() {
6338        int line = 0;
6339        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
6340            line = mLayout.getLineCount() - 1;
6341        }
6342
6343        Layout.Alignment a = mLayout.getParagraphAlignment(line);
6344        int dir = mLayout.getParagraphDirection(line);
6345        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6346        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6347        int ht = mLayout.getHeight();
6348
6349        int scrollx, scrolly;
6350
6351        // Convert to left, center, or right alignment.
6352        if (a == Layout.Alignment.ALIGN_NORMAL) {
6353            a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_LEFT :
6354                Layout.Alignment.ALIGN_RIGHT;
6355        } else if (a == Layout.Alignment.ALIGN_OPPOSITE){
6356            a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_RIGHT :
6357                Layout.Alignment.ALIGN_LEFT;
6358        }
6359
6360        if (a == Layout.Alignment.ALIGN_CENTER) {
6361            /*
6362             * Keep centered if possible, or, if it is too wide to fit,
6363             * keep leading edge in view.
6364             */
6365
6366            int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
6367            int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6368
6369            if (right - left < hspace) {
6370                scrollx = (right + left) / 2 - hspace / 2;
6371            } else {
6372                if (dir < 0) {
6373                    scrollx = right - hspace;
6374                } else {
6375                    scrollx = left;
6376                }
6377            }
6378        } else if (a == Layout.Alignment.ALIGN_RIGHT) {
6379            int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6380            scrollx = right - hspace;
6381        } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default)
6382            scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line));
6383        }
6384
6385        if (ht < vspace) {
6386            scrolly = 0;
6387        } else {
6388            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
6389                scrolly = ht - vspace;
6390            } else {
6391                scrolly = 0;
6392            }
6393        }
6394
6395        if (scrollx != mScrollX || scrolly != mScrollY) {
6396            scrollTo(scrollx, scrolly);
6397            return true;
6398        } else {
6399            return false;
6400        }
6401    }
6402
6403    /**
6404     * Move the point, specified by the offset, into the view if it is needed.
6405     * This has to be called after layout. Returns true if anything changed.
6406     */
6407    public boolean bringPointIntoView(int offset) {
6408        boolean changed = false;
6409
6410        if (mLayout == null) return changed;
6411
6412        int line = mLayout.getLineForOffset(offset);
6413
6414        // FIXME: Is it okay to truncate this, or should we round?
6415        final int x = (int)mLayout.getPrimaryHorizontal(offset);
6416        final int top = mLayout.getLineTop(line);
6417        final int bottom = mLayout.getLineTop(line + 1);
6418
6419        int left = (int) FloatMath.floor(mLayout.getLineLeft(line));
6420        int right = (int) FloatMath.ceil(mLayout.getLineRight(line));
6421        int ht = mLayout.getHeight();
6422
6423        int grav;
6424
6425        switch (mLayout.getParagraphAlignment(line)) {
6426            case ALIGN_LEFT:
6427                grav = 1;
6428                break;
6429            case ALIGN_RIGHT:
6430                grav = -1;
6431                break;
6432            case ALIGN_NORMAL:
6433                grav = mLayout.getParagraphDirection(line);
6434                break;
6435            case ALIGN_OPPOSITE:
6436                grav = -mLayout.getParagraphDirection(line);
6437                break;
6438            case ALIGN_CENTER:
6439            default:
6440                grav = 0;
6441                break;
6442        }
6443
6444        int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6445        int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6446
6447        int hslack = (bottom - top) / 2;
6448        int vslack = hslack;
6449
6450        if (vslack > vspace / 4)
6451            vslack = vspace / 4;
6452        if (hslack > hspace / 4)
6453            hslack = hspace / 4;
6454
6455        int hs = mScrollX;
6456        int vs = mScrollY;
6457
6458        if (top - vs < vslack)
6459            vs = top - vslack;
6460        if (bottom - vs > vspace - vslack)
6461            vs = bottom - (vspace - vslack);
6462        if (ht - vs < vspace)
6463            vs = ht - vspace;
6464        if (0 - vs > 0)
6465            vs = 0;
6466
6467        if (grav != 0) {
6468            if (x - hs < hslack) {
6469                hs = x - hslack;
6470            }
6471            if (x - hs > hspace - hslack) {
6472                hs = x - (hspace - hslack);
6473            }
6474        }
6475
6476        if (grav < 0) {
6477            if (left - hs > 0)
6478                hs = left;
6479            if (right - hs < hspace)
6480                hs = right - hspace;
6481        } else if (grav > 0) {
6482            if (right - hs < hspace)
6483                hs = right - hspace;
6484            if (left - hs > 0)
6485                hs = left;
6486        } else /* grav == 0 */ {
6487            if (right - left <= hspace) {
6488                /*
6489                 * If the entire text fits, center it exactly.
6490                 */
6491                hs = left - (hspace - (right - left)) / 2;
6492            } else if (x > right - hslack) {
6493                /*
6494                 * If we are near the right edge, keep the right edge
6495                 * at the edge of the view.
6496                 */
6497                hs = right - hspace;
6498            } else if (x < left + hslack) {
6499                /*
6500                 * If we are near the left edge, keep the left edge
6501                 * at the edge of the view.
6502                 */
6503                hs = left;
6504            } else if (left > hs) {
6505                /*
6506                 * Is there whitespace visible at the left?  Fix it if so.
6507                 */
6508                hs = left;
6509            } else if (right < hs + hspace) {
6510                /*
6511                 * Is there whitespace visible at the right?  Fix it if so.
6512                 */
6513                hs = right - hspace;
6514            } else {
6515                /*
6516                 * Otherwise, float as needed.
6517                 */
6518                if (x - hs < hslack) {
6519                    hs = x - hslack;
6520                }
6521                if (x - hs > hspace - hslack) {
6522                    hs = x - (hspace - hslack);
6523                }
6524            }
6525        }
6526
6527        if (hs != mScrollX || vs != mScrollY) {
6528            if (mScroller == null) {
6529                scrollTo(hs, vs);
6530            } else {
6531                long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
6532                int dx = hs - mScrollX;
6533                int dy = vs - mScrollY;
6534
6535                if (duration > ANIMATED_SCROLL_GAP) {
6536                    mScroller.startScroll(mScrollX, mScrollY, dx, dy);
6537                    awakenScrollBars(mScroller.getDuration());
6538                    invalidate();
6539                } else {
6540                    if (!mScroller.isFinished()) {
6541                        mScroller.abortAnimation();
6542                    }
6543
6544                    scrollBy(dx, dy);
6545                }
6546
6547                mLastScroll = AnimationUtils.currentAnimationTimeMillis();
6548            }
6549
6550            changed = true;
6551        }
6552
6553        if (isFocused()) {
6554            // This offsets because getInterestingRect() is in terms of viewport coordinates, but
6555            // requestRectangleOnScreen() is in terms of content coordinates.
6556
6557            // The offsets here are to ensure the rectangle we are using is
6558            // within our view bounds, in case the cursor is on the far left
6559            // or right.  If it isn't withing the bounds, then this request
6560            // will be ignored.
6561            if (mTempRect == null) mTempRect = new Rect();
6562            mTempRect.set(x - 2, top, x + 2, bottom);
6563            getInterestingRect(mTempRect, line);
6564            mTempRect.offset(mScrollX, mScrollY);
6565
6566            if (requestRectangleOnScreen(mTempRect)) {
6567                changed = true;
6568            }
6569        }
6570
6571        return changed;
6572    }
6573
6574    /**
6575     * Move the cursor, if needed, so that it is at an offset that is visible
6576     * to the user.  This will not move the cursor if it represents more than
6577     * one character (a selection range).  This will only work if the
6578     * TextView contains spannable text; otherwise it will do nothing.
6579     *
6580     * @return True if the cursor was actually moved, false otherwise.
6581     */
6582    public boolean moveCursorToVisibleOffset() {
6583        if (!(mText instanceof Spannable)) {
6584            return false;
6585        }
6586        int start = getSelectionStart();
6587        int end = getSelectionEnd();
6588        if (start != end) {
6589            return false;
6590        }
6591
6592        // First: make sure the line is visible on screen:
6593
6594        int line = mLayout.getLineForOffset(start);
6595
6596        final int top = mLayout.getLineTop(line);
6597        final int bottom = mLayout.getLineTop(line + 1);
6598        final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom();
6599        int vslack = (bottom - top) / 2;
6600        if (vslack > vspace / 4)
6601            vslack = vspace / 4;
6602        final int vs = mScrollY;
6603
6604        if (top < (vs+vslack)) {
6605            line = mLayout.getLineForVertical(vs+vslack+(bottom-top));
6606        } else if (bottom > (vspace+vs-vslack)) {
6607            line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top));
6608        }
6609
6610        // Next: make sure the character is visible on screen:
6611
6612        final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
6613        final int hs = mScrollX;
6614        final int leftChar = mLayout.getOffsetForHorizontal(line, hs);
6615        final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs);
6616
6617        // line might contain bidirectional text
6618        final int lowChar = leftChar < rightChar ? leftChar : rightChar;
6619        final int highChar = leftChar > rightChar ? leftChar : rightChar;
6620
6621        int newStart = start;
6622        if (newStart < lowChar) {
6623            newStart = lowChar;
6624        } else if (newStart > highChar) {
6625            newStart = highChar;
6626        }
6627
6628        if (newStart != start) {
6629            Selection.setSelection((Spannable)mText, newStart);
6630            return true;
6631        }
6632
6633        return false;
6634    }
6635
6636    @Override
6637    public void computeScroll() {
6638        if (mScroller != null) {
6639            if (mScroller.computeScrollOffset()) {
6640                mScrollX = mScroller.getCurrX();
6641                mScrollY = mScroller.getCurrY();
6642                invalidateParentCaches();
6643                postInvalidate();  // So we draw again
6644            }
6645        }
6646    }
6647
6648    private void getInterestingRect(Rect r, int line) {
6649        convertFromViewportToContentCoordinates(r);
6650
6651        // Rectangle can can be expanded on first and last line to take
6652        // padding into account.
6653        // TODO Take left/right padding into account too?
6654        if (line == 0) r.top -= getExtendedPaddingTop();
6655        if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom();
6656    }
6657
6658    private void convertFromViewportToContentCoordinates(Rect r) {
6659        final int horizontalOffset = viewportToContentHorizontalOffset();
6660        r.left += horizontalOffset;
6661        r.right += horizontalOffset;
6662
6663        final int verticalOffset = viewportToContentVerticalOffset();
6664        r.top += verticalOffset;
6665        r.bottom += verticalOffset;
6666    }
6667
6668    private int viewportToContentHorizontalOffset() {
6669        return getCompoundPaddingLeft() - mScrollX;
6670    }
6671
6672    private int viewportToContentVerticalOffset() {
6673        int offset = getExtendedPaddingTop() - mScrollY;
6674        if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) {
6675            offset += getVerticalOffset(false);
6676        }
6677        return offset;
6678    }
6679
6680    @Override
6681    public void debug(int depth) {
6682        super.debug(depth);
6683
6684        String output = debugIndent(depth);
6685        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
6686                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
6687                + "} ";
6688
6689        if (mText != null) {
6690
6691            output += "mText=\"" + mText + "\" ";
6692            if (mLayout != null) {
6693                output += "mLayout width=" + mLayout.getWidth()
6694                        + " height=" + mLayout.getHeight();
6695            }
6696        } else {
6697            output += "mText=NULL";
6698        }
6699        Log.d(VIEW_LOG_TAG, output);
6700    }
6701
6702    /**
6703     * Convenience for {@link Selection#getSelectionStart}.
6704     */
6705    @ViewDebug.ExportedProperty(category = "text")
6706    public int getSelectionStart() {
6707        return Selection.getSelectionStart(getText());
6708    }
6709
6710    /**
6711     * Convenience for {@link Selection#getSelectionEnd}.
6712     */
6713    @ViewDebug.ExportedProperty(category = "text")
6714    public int getSelectionEnd() {
6715        return Selection.getSelectionEnd(getText());
6716    }
6717
6718    /**
6719     * Return true iff there is a selection inside this text view.
6720     */
6721    public boolean hasSelection() {
6722        final int selectionStart = getSelectionStart();
6723        final int selectionEnd = getSelectionEnd();
6724
6725        return selectionStart >= 0 && selectionStart != selectionEnd;
6726    }
6727
6728    /**
6729     * Sets the properties of this field (lines, horizontally scrolling,
6730     * transformation method) to be for a single-line input.
6731     *
6732     * @attr ref android.R.styleable#TextView_singleLine
6733     */
6734    public void setSingleLine() {
6735        setSingleLine(true);
6736    }
6737
6738    /**
6739     * Sets the properties of this field to transform input to ALL CAPS
6740     * display. This may use a "small caps" formatting if available.
6741     * This setting will be ignored if this field is editable or selectable.
6742     *
6743     * This call replaces the current transformation method. Disabling this
6744     * will not necessarily restore the previous behavior from before this
6745     * was enabled.
6746     *
6747     * @see #setTransformationMethod(TransformationMethod)
6748     * @attr ref android.R.styleable#TextView_textAllCaps
6749     */
6750    public void setAllCaps(boolean allCaps) {
6751        if (allCaps) {
6752            setTransformationMethod(new AllCapsTransformationMethod(getContext()));
6753        } else {
6754            setTransformationMethod(null);
6755        }
6756    }
6757
6758    /**
6759     * If true, sets the properties of this field (number of lines, horizontally scrolling,
6760     * transformation method) to be for a single-line input; if false, restores these to the default
6761     * conditions.
6762     *
6763     * Note that the default conditions are not necessarily those that were in effect prior this
6764     * method, and you may want to reset these properties to your custom values.
6765     *
6766     * @attr ref android.R.styleable#TextView_singleLine
6767     */
6768    @android.view.RemotableViewMethod
6769    public void setSingleLine(boolean singleLine) {
6770        // Could be used, but may break backward compatibility.
6771        // if (mSingleLine == singleLine) return;
6772        setInputTypeSingleLine(singleLine);
6773        applySingleLine(singleLine, true, true);
6774    }
6775
6776    /**
6777     * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType.
6778     * @param singleLine
6779     */
6780    private void setInputTypeSingleLine(boolean singleLine) {
6781        if (mEditor != null && (getEditor().mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
6782            if (singleLine) {
6783                getEditor().mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
6784            } else {
6785                getEditor().mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
6786            }
6787        }
6788    }
6789
6790    private void applySingleLine(boolean singleLine, boolean applyTransformation,
6791            boolean changeMaxLines) {
6792        mSingleLine = singleLine;
6793        if (singleLine) {
6794            setLines(1);
6795            setHorizontallyScrolling(true);
6796            if (applyTransformation) {
6797                setTransformationMethod(SingleLineTransformationMethod.getInstance());
6798            }
6799        } else {
6800            if (changeMaxLines) {
6801                setMaxLines(Integer.MAX_VALUE);
6802            }
6803            setHorizontallyScrolling(false);
6804            if (applyTransformation) {
6805                setTransformationMethod(null);
6806            }
6807        }
6808    }
6809
6810    /**
6811     * Causes words in the text that are longer than the view is wide
6812     * to be ellipsized instead of broken in the middle.  You may also
6813     * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling}
6814     * to constrain the text to a single line.  Use <code>null</code>
6815     * to turn off ellipsizing.
6816     *
6817     * If {@link #setMaxLines} has been used to set two or more lines,
6818     * {@link android.text.TextUtils.TruncateAt#END} and
6819     * {@link android.text.TextUtils.TruncateAt#MARQUEE}* are only supported
6820     * (other ellipsizing types will not do anything).
6821     *
6822     * @attr ref android.R.styleable#TextView_ellipsize
6823     */
6824    public void setEllipsize(TextUtils.TruncateAt where) {
6825        // TruncateAt is an enum. != comparison is ok between these singleton objects.
6826        if (mEllipsize != where) {
6827            mEllipsize = where;
6828
6829            if (mLayout != null) {
6830                nullLayouts();
6831                requestLayout();
6832                invalidate();
6833            }
6834        }
6835    }
6836
6837    /**
6838     * Sets how many times to repeat the marquee animation. Only applied if the
6839     * TextView has marquee enabled. Set to -1 to repeat indefinitely.
6840     *
6841     * @attr ref android.R.styleable#TextView_marqueeRepeatLimit
6842     */
6843    public void setMarqueeRepeatLimit(int marqueeLimit) {
6844        mMarqueeRepeatLimit = marqueeLimit;
6845    }
6846
6847    /**
6848     * Returns where, if anywhere, words that are longer than the view
6849     * is wide should be ellipsized.
6850     */
6851    @ViewDebug.ExportedProperty
6852    public TextUtils.TruncateAt getEllipsize() {
6853        return mEllipsize;
6854    }
6855
6856    /**
6857     * Set the TextView so that when it takes focus, all the text is
6858     * selected.
6859     *
6860     * @attr ref android.R.styleable#TextView_selectAllOnFocus
6861     */
6862    @android.view.RemotableViewMethod
6863    public void setSelectAllOnFocus(boolean selectAllOnFocus) {
6864        createEditorIfNeeded("setSelectAllOnFocus");
6865        getEditor().mSelectAllOnFocus = selectAllOnFocus;
6866
6867        if (selectAllOnFocus && !(mText instanceof Spannable)) {
6868            setText(mText, BufferType.SPANNABLE);
6869        }
6870    }
6871
6872    /**
6873     * Set whether the cursor is visible.  The default is true.
6874     *
6875     * @attr ref android.R.styleable#TextView_cursorVisible
6876     */
6877    @android.view.RemotableViewMethod
6878    public void setCursorVisible(boolean visible) {
6879        if (visible && mEditor == null) return; // visible is the default value with no edit data
6880        createEditorIfNeeded("setCursorVisible");
6881        if (getEditor().mCursorVisible != visible) {
6882            getEditor().mCursorVisible = visible;
6883            invalidate();
6884
6885            makeBlink();
6886
6887            // InsertionPointCursorController depends on mCursorVisible
6888            prepareCursorControllers();
6889        }
6890    }
6891
6892    private boolean isCursorVisible() {
6893        // The default value is true, even when there is no associated Editor
6894        return mEditor == null ? true : (getEditor().mCursorVisible && isTextEditable());
6895    }
6896
6897    private boolean canMarquee() {
6898        int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight());
6899        return width > 0 && (mLayout.getLineWidth(0) > width ||
6900                (mMarqueeFadeMode != MARQUEE_FADE_NORMAL && mSavedMarqueeModeLayout != null &&
6901                        mSavedMarqueeModeLayout.getLineWidth(0) > width));
6902    }
6903
6904    private void startMarquee() {
6905        // Do not ellipsize EditText
6906        if (getKeyListener() != null) return;
6907
6908        if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
6909            return;
6910        }
6911
6912        if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) &&
6913                getLineCount() == 1 && canMarquee()) {
6914
6915            if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
6916                mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_FADE;
6917                final Layout tmp = mLayout;
6918                mLayout = mSavedMarqueeModeLayout;
6919                mSavedMarqueeModeLayout = tmp;
6920                setHorizontalFadingEdgeEnabled(true);
6921                requestLayout();
6922                invalidate();
6923            }
6924
6925            if (mMarquee == null) mMarquee = new Marquee(this);
6926            mMarquee.start(mMarqueeRepeatLimit);
6927        }
6928    }
6929
6930    private void stopMarquee() {
6931        if (mMarquee != null && !mMarquee.isStopped()) {
6932            mMarquee.stop();
6933        }
6934
6935        if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_FADE) {
6936            mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS;
6937            final Layout tmp = mSavedMarqueeModeLayout;
6938            mSavedMarqueeModeLayout = mLayout;
6939            mLayout = tmp;
6940            setHorizontalFadingEdgeEnabled(false);
6941            requestLayout();
6942            invalidate();
6943        }
6944    }
6945
6946    private void startStopMarquee(boolean start) {
6947        if (mEllipsize == TextUtils.TruncateAt.MARQUEE) {
6948            if (start) {
6949                startMarquee();
6950            } else {
6951                stopMarquee();
6952            }
6953        }
6954    }
6955
6956    /**
6957     * This method is called when the text is changed, in case any subclasses
6958     * would like to know.
6959     *
6960     * Within <code>text</code>, the <code>lengthAfter</code> characters
6961     * beginning at <code>start</code> have just replaced old text that had
6962     * length <code>lengthBefore</code>. It is an error to attempt to make
6963     * changes to <code>text</code> from this callback.
6964     *
6965     * @param text The text the TextView is displaying
6966     * @param start The offset of the start of the range of the text that was
6967     * modified
6968     * @param lengthBefore The length of the former text that has been replaced
6969     * @param lengthAfter The length of the replacement modified text
6970     */
6971    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
6972        // intentionally empty, template pattern method can be overridden by subclasses
6973    }
6974
6975    /**
6976     * This method is called when the selection has changed, in case any
6977     * subclasses would like to know.
6978     *
6979     * @param selStart The new selection start location.
6980     * @param selEnd The new selection end location.
6981     */
6982    protected void onSelectionChanged(int selStart, int selEnd) {
6983        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
6984        getEditor().mTextDisplayListIsValid = false;
6985    }
6986
6987    /**
6988     * Adds a TextWatcher to the list of those whose methods are called
6989     * whenever this TextView's text changes.
6990     * <p>
6991     * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
6992     * not called after {@link #setText} calls.  Now, doing {@link #setText}
6993     * if there are any text changed listeners forces the buffer type to
6994     * Editable if it would not otherwise be and does call this method.
6995     */
6996    public void addTextChangedListener(TextWatcher watcher) {
6997        if (mListeners == null) {
6998            mListeners = new ArrayList<TextWatcher>();
6999        }
7000
7001        mListeners.add(watcher);
7002    }
7003
7004    /**
7005     * Removes the specified TextWatcher from the list of those whose
7006     * methods are called
7007     * whenever this TextView's text changes.
7008     */
7009    public void removeTextChangedListener(TextWatcher watcher) {
7010        if (mListeners != null) {
7011            int i = mListeners.indexOf(watcher);
7012
7013            if (i >= 0) {
7014                mListeners.remove(i);
7015            }
7016        }
7017    }
7018
7019    private void sendBeforeTextChanged(CharSequence text, int start, int before, int after) {
7020        if (mListeners != null) {
7021            final ArrayList<TextWatcher> list = mListeners;
7022            final int count = list.size();
7023            for (int i = 0; i < count; i++) {
7024                list.get(i).beforeTextChanged(text, start, before, after);
7025            }
7026        }
7027
7028        // The spans that are inside or intersect the modified region no longer make sense
7029        removeIntersectingSpans(start, start + before, SpellCheckSpan.class);
7030        removeIntersectingSpans(start, start + before, SuggestionSpan.class);
7031    }
7032
7033    // Removes all spans that are inside or actually overlap the start..end range
7034    private <T> void removeIntersectingSpans(int start, int end, Class<T> type) {
7035        if (!(mText instanceof Editable)) return;
7036        Editable text = (Editable) mText;
7037
7038        T[] spans = text.getSpans(start, end, type);
7039        final int length = spans.length;
7040        for (int i = 0; i < length; i++) {
7041            final int s = text.getSpanStart(spans[i]);
7042            final int e = text.getSpanEnd(spans[i]);
7043            // Spans that are adjacent to the edited region will be handled in
7044            // updateSpellCheckSpans. Result depends on what will be added (space or text)
7045            if (e == start || s == end) break;
7046            text.removeSpan(spans[i]);
7047        }
7048    }
7049
7050    /**
7051     * Not private so it can be called from an inner class without going
7052     * through a thunk.
7053     */
7054    void sendOnTextChanged(CharSequence text, int start, int before, int after) {
7055        if (mListeners != null) {
7056            final ArrayList<TextWatcher> list = mListeners;
7057            final int count = list.size();
7058            for (int i = 0; i < count; i++) {
7059                list.get(i).onTextChanged(text, start, before, after);
7060            }
7061        }
7062
7063        if (mEditor != null) getEditor().sendOnTextChanged(start, after);
7064    }
7065
7066    /**
7067     * Not private so it can be called from an inner class without going
7068     * through a thunk.
7069     */
7070    void sendAfterTextChanged(Editable text) {
7071        if (mListeners != null) {
7072            final ArrayList<TextWatcher> list = mListeners;
7073            final int count = list.size();
7074            for (int i = 0; i < count; i++) {
7075                list.get(i).afterTextChanged(text);
7076            }
7077        }
7078    }
7079
7080    /**
7081     * Not private so it can be called from an inner class without going
7082     * through a thunk.
7083     */
7084    void handleTextChanged(CharSequence buffer, int start, int before, int after) {
7085        final InputMethodState ims = mEditor == null ? null : getEditor().mInputMethodState;
7086        if (ims == null || ims.mBatchEditNesting == 0) {
7087            updateAfterEdit();
7088        }
7089        if (ims != null) {
7090            ims.mContentChanged = true;
7091            if (ims.mChangedStart < 0) {
7092                ims.mChangedStart = start;
7093                ims.mChangedEnd = start+before;
7094            } else {
7095                ims.mChangedStart = Math.min(ims.mChangedStart, start);
7096                ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta);
7097            }
7098            ims.mChangedDelta += after-before;
7099        }
7100
7101        sendOnTextChanged(buffer, start, before, after);
7102        onTextChanged(buffer, start, before, after);
7103    }
7104
7105    /**
7106     * Not private so it can be called from an inner class without going
7107     * through a thunk.
7108     */
7109    void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) {
7110        // XXX Make the start and end move together if this ends up
7111        // spending too much time invalidating.
7112
7113        boolean selChanged = false;
7114        int newSelStart=-1, newSelEnd=-1;
7115
7116        final InputMethodState ims = mEditor == null ? null : getEditor().mInputMethodState;
7117
7118        if (what == Selection.SELECTION_END) {
7119            selChanged = true;
7120            newSelEnd = newStart;
7121
7122            if (oldStart >= 0 || newStart >= 0) {
7123                invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart);
7124                registerForPreDraw();
7125                makeBlink();
7126            }
7127        }
7128
7129        if (what == Selection.SELECTION_START) {
7130            selChanged = true;
7131            newSelStart = newStart;
7132
7133            if (oldStart >= 0 || newStart >= 0) {
7134                int end = Selection.getSelectionEnd(buf);
7135                invalidateCursor(end, oldStart, newStart);
7136            }
7137        }
7138
7139        if (selChanged) {
7140            if (mEditor != null) {
7141                getEditor().mHighlightPathBogus = true;
7142                if (!isFocused()) getEditor().mSelectionMoved = true;
7143            }
7144
7145            if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) {
7146                if (newSelStart < 0) {
7147                    newSelStart = Selection.getSelectionStart(buf);
7148                }
7149                if (newSelEnd < 0) {
7150                    newSelEnd = Selection.getSelectionEnd(buf);
7151                }
7152                onSelectionChanged(newSelStart, newSelEnd);
7153            }
7154        }
7155
7156        if (what instanceof UpdateAppearance || what instanceof ParagraphStyle ||
7157                what instanceof CharacterStyle) {
7158            if (ims == null || ims.mBatchEditNesting == 0) {
7159                invalidate();
7160                if (mEditor != null) getEditor().mHighlightPathBogus = true;
7161                checkForResize();
7162            } else {
7163                ims.mContentChanged = true;
7164            }
7165            if (mEditor != null) getEditor().mTextDisplayListIsValid = false;
7166        }
7167
7168        if (MetaKeyKeyListener.isMetaTracker(buf, what)) {
7169            if (mEditor != null) getEditor().mHighlightPathBogus = true;
7170            if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) {
7171                ims.mSelectionModeChanged = true;
7172            }
7173
7174            if (Selection.getSelectionStart(buf) >= 0) {
7175                if (ims == null || ims.mBatchEditNesting == 0) {
7176                    invalidateCursor();
7177                } else {
7178                    ims.mCursorChanged = true;
7179                }
7180            }
7181        }
7182
7183        if (what instanceof ParcelableSpan) {
7184            // If this is a span that can be sent to a remote process,
7185            // the current extract editor would be interested in it.
7186            if (ims != null && ims.mExtracting != null) {
7187                if (ims.mBatchEditNesting != 0) {
7188                    if (oldStart >= 0) {
7189                        if (ims.mChangedStart > oldStart) {
7190                            ims.mChangedStart = oldStart;
7191                        }
7192                        if (ims.mChangedStart > oldEnd) {
7193                            ims.mChangedStart = oldEnd;
7194                        }
7195                    }
7196                    if (newStart >= 0) {
7197                        if (ims.mChangedStart > newStart) {
7198                            ims.mChangedStart = newStart;
7199                        }
7200                        if (ims.mChangedStart > newEnd) {
7201                            ims.mChangedStart = newEnd;
7202                        }
7203                    }
7204                } else {
7205                    if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: "
7206                            + oldStart + "-" + oldEnd + ","
7207                            + newStart + "-" + newEnd + what);
7208                    ims.mContentChanged = true;
7209                }
7210            }
7211        }
7212
7213        if (mEditor != null && getEditor().mSpellChecker != null && newStart < 0 && what instanceof SpellCheckSpan) {
7214            getEditor().mSpellChecker.removeSpellCheckSpan((SpellCheckSpan) what);
7215        }
7216    }
7217
7218    /**
7219     * Create new SpellCheckSpans on the modified region.
7220     */
7221    private void updateSpellCheckSpans(int start, int end, boolean createSpellChecker) {
7222        if (isTextEditable() && isSuggestionsEnabled() && !(this instanceof ExtractEditText)) {
7223            if (getEditor().mSpellChecker == null && createSpellChecker) {
7224                getEditor().mSpellChecker = new SpellChecker(this);
7225            }
7226            if (getEditor().mSpellChecker != null) {
7227                getEditor().mSpellChecker.spellCheck(start, end);
7228            }
7229        }
7230    }
7231
7232    /**
7233     * @hide
7234     */
7235    @Override
7236    public void dispatchFinishTemporaryDetach() {
7237        mDispatchTemporaryDetach = true;
7238        super.dispatchFinishTemporaryDetach();
7239        mDispatchTemporaryDetach = false;
7240    }
7241
7242    @Override
7243    public void onStartTemporaryDetach() {
7244        super.onStartTemporaryDetach();
7245        // Only track when onStartTemporaryDetach() is called directly,
7246        // usually because this instance is an editable field in a list
7247        if (!mDispatchTemporaryDetach) mTemporaryDetach = true;
7248
7249        // Because of View recycling in ListView, there is no easy way to know when a TextView with
7250        // selection becomes visible again. Until a better solution is found, stop text selection
7251        // mode (if any) as soon as this TextView is recycled.
7252        if (mEditor != null) hideControllers();
7253    }
7254
7255    @Override
7256    public void onFinishTemporaryDetach() {
7257        super.onFinishTemporaryDetach();
7258        // Only track when onStartTemporaryDetach() is called directly,
7259        // usually because this instance is an editable field in a list
7260        if (!mDispatchTemporaryDetach) mTemporaryDetach = false;
7261    }
7262
7263    @Override
7264    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
7265        if (mTemporaryDetach) {
7266            // If we are temporarily in the detach state, then do nothing.
7267            super.onFocusChanged(focused, direction, previouslyFocusedRect);
7268            return;
7269        }
7270
7271        if (mEditor != null) getEditor().onFocusChanged(focused, direction);
7272
7273        if (focused) {
7274            if (mText instanceof Spannable) {
7275                Spannable sp = (Spannable) mText;
7276                MetaKeyKeyListener.resetMetaState(sp);
7277            }
7278        }
7279
7280        startStopMarquee(focused);
7281
7282        if (mTransformation != null) {
7283            mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect);
7284        }
7285
7286        super.onFocusChanged(focused, direction, previouslyFocusedRect);
7287    }
7288
7289    @Override
7290    public void onWindowFocusChanged(boolean hasWindowFocus) {
7291        super.onWindowFocusChanged(hasWindowFocus);
7292
7293        if (mEditor != null) getEditor().onWindowFocusChanged(hasWindowFocus);
7294
7295        startStopMarquee(hasWindowFocus);
7296    }
7297
7298    @Override
7299    protected void onVisibilityChanged(View changedView, int visibility) {
7300        super.onVisibilityChanged(changedView, visibility);
7301        if (mEditor != null && visibility != VISIBLE) {
7302            hideControllers();
7303        }
7304    }
7305
7306    /**
7307     * Use {@link BaseInputConnection#removeComposingSpans
7308     * BaseInputConnection.removeComposingSpans()} to remove any IME composing
7309     * state from this text view.
7310     */
7311    public void clearComposingText() {
7312        if (mText instanceof Spannable) {
7313            BaseInputConnection.removeComposingSpans((Spannable)mText);
7314        }
7315    }
7316
7317    @Override
7318    public void setSelected(boolean selected) {
7319        boolean wasSelected = isSelected();
7320
7321        super.setSelected(selected);
7322
7323        if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) {
7324            if (selected) {
7325                startMarquee();
7326            } else {
7327                stopMarquee();
7328            }
7329        }
7330    }
7331
7332    @Override
7333    public boolean onTouchEvent(MotionEvent event) {
7334        final int action = event.getActionMasked();
7335
7336        if (mEditor != null) getEditor().onTouchEvent(event);
7337
7338        final boolean superResult = super.onTouchEvent(event);
7339
7340        /*
7341         * Don't handle the release after a long press, because it will
7342         * move the selection away from whatever the menu action was
7343         * trying to affect.
7344         */
7345        if (mEditor != null && getEditor().mDiscardNextActionUp && action == MotionEvent.ACTION_UP) {
7346            getEditor().mDiscardNextActionUp = false;
7347            return superResult;
7348        }
7349
7350        final boolean touchIsFinished = (action == MotionEvent.ACTION_UP) &&
7351                (mEditor == null || !getEditor().mIgnoreActionUpEvent) && isFocused();
7352
7353         if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()
7354                && mText instanceof Spannable && mLayout != null) {
7355            boolean handled = false;
7356
7357            if (mMovement != null) {
7358                handled |= mMovement.onTouchEvent(this, (Spannable) mText, event);
7359            }
7360
7361            final boolean textIsSelectable = isTextSelectable();
7362            if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && textIsSelectable) {
7363                // The LinkMovementMethod which should handle taps on links has not been installed
7364                // on non editable text that support text selection.
7365                // We reproduce its behavior here to open links for these.
7366                ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(),
7367                        getSelectionEnd(), ClickableSpan.class);
7368
7369                if (links.length > 0) {
7370                    links[0].onClick(this);
7371                    handled = true;
7372                }
7373            }
7374
7375            if (touchIsFinished && (isTextEditable() || textIsSelectable)) {
7376                // Show the IME, except when selecting in read-only text.
7377                final InputMethodManager imm = InputMethodManager.peekInstance();
7378                viewClicked(imm);
7379                if (!textIsSelectable) {
7380                    handled |= imm != null && imm.showSoftInput(this, 0);
7381                }
7382
7383                boolean selectAllGotFocus = getEditor().mSelectAllOnFocus && didTouchFocusSelect();
7384                hideControllers();
7385                if (!selectAllGotFocus && mText.length() > 0) {
7386                    // Move cursor
7387                    final int offset = getOffsetForPosition(event.getX(), event.getY());
7388                    Selection.setSelection((Spannable) mText, offset);
7389                    if (getEditor().mSpellChecker != null) {
7390                        // When the cursor moves, the word that was typed may need spell check
7391                        getEditor().mSpellChecker.onSelectionChanged();
7392                    }
7393                    if (!extractedTextModeWillBeStarted()) {
7394                        if (isCursorInsideEasyCorrectionSpan()) {
7395                            getEditor().mShowSuggestionRunnable = new Runnable() {
7396                                public void run() {
7397                                    showSuggestions();
7398                                }
7399                            };
7400                            // removeCallbacks is performed on every touch
7401                            postDelayed(getEditor().mShowSuggestionRunnable,
7402                                    ViewConfiguration.getDoubleTapTimeout());
7403                        } else if (hasInsertionController()) {
7404                            getInsertionController().show();
7405                        }
7406                    }
7407                }
7408
7409                handled = true;
7410            }
7411
7412            if (handled) {
7413                return true;
7414            }
7415        }
7416
7417        return superResult;
7418    }
7419
7420    /**
7421     * @return <code>true</code> if the cursor/current selection overlaps a {@link SuggestionSpan}.
7422     */
7423    private boolean isCursorInsideSuggestionSpan() {
7424        if (!(mText instanceof Spannable)) return false;
7425
7426        SuggestionSpan[] suggestionSpans = ((Spannable) mText).getSpans(getSelectionStart(),
7427                getSelectionEnd(), SuggestionSpan.class);
7428        return (suggestionSpans.length > 0);
7429    }
7430
7431    /**
7432     * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with
7433     * {@link SuggestionSpan#FLAG_EASY_CORRECT} set.
7434     */
7435    private boolean isCursorInsideEasyCorrectionSpan() {
7436        Spannable spannable = (Spannable) mText;
7437        SuggestionSpan[] suggestionSpans = spannable.getSpans(getSelectionStart(),
7438                getSelectionEnd(), SuggestionSpan.class);
7439        for (int i = 0; i < suggestionSpans.length; i++) {
7440            if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) {
7441                return true;
7442            }
7443        }
7444        return false;
7445    }
7446
7447    /**
7448     * Downgrades to simple suggestions all the easy correction spans that are not a spell check
7449     * span.
7450     */
7451    private void downgradeEasyCorrectionSpans() {
7452        if (mText instanceof Spannable) {
7453            Spannable spannable = (Spannable) mText;
7454            SuggestionSpan[] suggestionSpans = spannable.getSpans(0,
7455                    spannable.length(), SuggestionSpan.class);
7456            for (int i = 0; i < suggestionSpans.length; i++) {
7457                int flags = suggestionSpans[i].getFlags();
7458                if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0
7459                        && (flags & SuggestionSpan.FLAG_MISSPELLED) == 0) {
7460                    flags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
7461                    suggestionSpans[i].setFlags(flags);
7462                }
7463            }
7464        }
7465    }
7466
7467    @Override
7468    public boolean onGenericMotionEvent(MotionEvent event) {
7469        if (mMovement != null && mText instanceof Spannable && mLayout != null) {
7470            try {
7471                if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) {
7472                    return true;
7473                }
7474            } catch (AbstractMethodError ex) {
7475                // onGenericMotionEvent was added to the MovementMethod interface in API 12.
7476                // Ignore its absence in case third party applications implemented the
7477                // interface directly.
7478            }
7479        }
7480        return super.onGenericMotionEvent(event);
7481    }
7482
7483    private void prepareCursorControllers() {
7484        if (mEditor == null) return;
7485
7486        boolean windowSupportsHandles = false;
7487
7488        ViewGroup.LayoutParams params = getRootView().getLayoutParams();
7489        if (params instanceof WindowManager.LayoutParams) {
7490            WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params;
7491            windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW
7492                    || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW;
7493        }
7494
7495        getEditor().mInsertionControllerEnabled = windowSupportsHandles && isCursorVisible() && mLayout != null;
7496        getEditor().mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() &&
7497                mLayout != null;
7498
7499        if (!getEditor().mInsertionControllerEnabled) {
7500            hideInsertionPointCursorController();
7501            if (getEditor().mInsertionPointCursorController != null) {
7502                getEditor().mInsertionPointCursorController.onDetached();
7503                getEditor().mInsertionPointCursorController = null;
7504            }
7505        }
7506
7507        if (!getEditor().mSelectionControllerEnabled) {
7508            stopSelectionActionMode();
7509            if (getEditor().mSelectionModifierCursorController != null) {
7510                getEditor().mSelectionModifierCursorController.onDetached();
7511                getEditor().mSelectionModifierCursorController = null;
7512            }
7513        }
7514    }
7515
7516    /**
7517     * @return True iff this TextView contains a text that can be edited, or if this is
7518     * a selectable TextView.
7519     */
7520    private boolean isTextEditable() {
7521        return mText instanceof Editable && onCheckIsTextEditor() && isEnabled();
7522    }
7523
7524    /**
7525     * Returns true, only while processing a touch gesture, if the initial
7526     * touch down event caused focus to move to the text view and as a result
7527     * its selection changed.  Only valid while processing the touch gesture
7528     * of interest.
7529     */
7530    public boolean didTouchFocusSelect() {
7531        return mEditor != null && getEditor().mTouchFocusSelected;
7532    }
7533
7534    @Override
7535    public void cancelLongPress() {
7536        super.cancelLongPress();
7537        if (mEditor != null) getEditor().mIgnoreActionUpEvent = true;
7538    }
7539
7540    @Override
7541    public boolean onTrackballEvent(MotionEvent event) {
7542        if (mMovement != null && mText instanceof Spannable && mLayout != null) {
7543            if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) {
7544                return true;
7545            }
7546        }
7547
7548        return super.onTrackballEvent(event);
7549    }
7550
7551    public void setScroller(Scroller s) {
7552        mScroller = s;
7553    }
7554
7555    /**
7556     * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
7557     */
7558    private boolean shouldBlink() {
7559        if (mEditor == null || !isCursorVisible() || !isFocused()) return false;
7560
7561        final int start = getSelectionStart();
7562        if (start < 0) return false;
7563
7564        final int end = getSelectionEnd();
7565        if (end < 0) return false;
7566
7567        return start == end;
7568    }
7569
7570    private void makeBlink() {
7571        if (shouldBlink()) {
7572            getEditor().mShowCursor = SystemClock.uptimeMillis();
7573            if (getEditor().mBlink == null) getEditor().mBlink = new Blink(this);
7574            getEditor().mBlink.removeCallbacks(getEditor().mBlink);
7575            getEditor().mBlink.postAtTime(getEditor().mBlink, getEditor().mShowCursor + BLINK);
7576        } else {
7577            if (mEditor != null && getEditor().mBlink != null) getEditor().mBlink.removeCallbacks(getEditor().mBlink);
7578        }
7579    }
7580
7581    @Override
7582    protected float getLeftFadingEdgeStrength() {
7583        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f;
7584        if (mEllipsize == TextUtils.TruncateAt.MARQUEE &&
7585                mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
7586            if (mMarquee != null && !mMarquee.isStopped()) {
7587                final Marquee marquee = mMarquee;
7588                if (marquee.shouldDrawLeftFade()) {
7589                    return marquee.mScroll / getHorizontalFadingEdgeLength();
7590                } else {
7591                    return 0.0f;
7592                }
7593            } else if (getLineCount() == 1) {
7594                final int layoutDirection = getResolvedLayoutDirection();
7595                final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
7596                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
7597                    case Gravity.LEFT:
7598                        return 0.0f;
7599                    case Gravity.RIGHT:
7600                        return (mLayout.getLineRight(0) - (mRight - mLeft) -
7601                                getCompoundPaddingLeft() - getCompoundPaddingRight() -
7602                                mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength();
7603                    case Gravity.CENTER_HORIZONTAL:
7604                        return 0.0f;
7605                }
7606            }
7607        }
7608        return super.getLeftFadingEdgeStrength();
7609    }
7610
7611    @Override
7612    protected float getRightFadingEdgeStrength() {
7613        if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f;
7614        if (mEllipsize == TextUtils.TruncateAt.MARQUEE &&
7615                mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
7616            if (mMarquee != null && !mMarquee.isStopped()) {
7617                final Marquee marquee = mMarquee;
7618                return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength();
7619            } else if (getLineCount() == 1) {
7620                final int layoutDirection = getResolvedLayoutDirection();
7621                final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection);
7622                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
7623                    case Gravity.LEFT:
7624                        final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() -
7625                                getCompoundPaddingRight();
7626                        final float lineWidth = mLayout.getLineWidth(0);
7627                        return (lineWidth - textWidth) / getHorizontalFadingEdgeLength();
7628                    case Gravity.RIGHT:
7629                        return 0.0f;
7630                    case Gravity.CENTER_HORIZONTAL:
7631                    case Gravity.FILL_HORIZONTAL:
7632                        return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
7633                                getCompoundPaddingLeft() - getCompoundPaddingRight())) /
7634                                getHorizontalFadingEdgeLength();
7635                }
7636            }
7637        }
7638        return super.getRightFadingEdgeStrength();
7639    }
7640
7641    @Override
7642    protected int computeHorizontalScrollRange() {
7643        if (mLayout != null) {
7644            return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ?
7645                    (int) mLayout.getLineWidth(0) : mLayout.getWidth();
7646        }
7647
7648        return super.computeHorizontalScrollRange();
7649    }
7650
7651    @Override
7652    protected int computeVerticalScrollRange() {
7653        if (mLayout != null)
7654            return mLayout.getHeight();
7655
7656        return super.computeVerticalScrollRange();
7657    }
7658
7659    @Override
7660    protected int computeVerticalScrollExtent() {
7661        return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
7662    }
7663
7664    @Override
7665    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
7666        super.findViewsWithText(outViews, searched, flags);
7667        if (!outViews.contains(this) && (flags & FIND_VIEWS_WITH_TEXT) != 0
7668                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mText)) {
7669            String searchedLowerCase = searched.toString().toLowerCase();
7670            String textLowerCase = mText.toString().toLowerCase();
7671            if (textLowerCase.contains(searchedLowerCase)) {
7672                outViews.add(this);
7673            }
7674        }
7675    }
7676
7677    public enum BufferType {
7678        NORMAL, SPANNABLE, EDITABLE,
7679    }
7680
7681    /**
7682     * Returns the TextView_textColor attribute from the
7683     * Resources.StyledAttributes, if set, or the TextAppearance_textColor
7684     * from the TextView_textAppearance attribute, if TextView_textColor
7685     * was not set directly.
7686     */
7687    public static ColorStateList getTextColors(Context context, TypedArray attrs) {
7688        ColorStateList colors;
7689        colors = attrs.getColorStateList(com.android.internal.R.styleable.
7690                                         TextView_textColor);
7691
7692        if (colors == null) {
7693            int ap = attrs.getResourceId(com.android.internal.R.styleable.
7694                                         TextView_textAppearance, -1);
7695            if (ap != -1) {
7696                TypedArray appearance;
7697                appearance = context.obtainStyledAttributes(ap,
7698                                            com.android.internal.R.styleable.TextAppearance);
7699                colors = appearance.getColorStateList(com.android.internal.R.styleable.
7700                                                  TextAppearance_textColor);
7701                appearance.recycle();
7702            }
7703        }
7704
7705        return colors;
7706    }
7707
7708    /**
7709     * Returns the default color from the TextView_textColor attribute
7710     * from the AttributeSet, if set, or the default color from the
7711     * TextAppearance_textColor from the TextView_textAppearance attribute,
7712     * if TextView_textColor was not set directly.
7713     */
7714    public static int getTextColor(Context context,
7715                                   TypedArray attrs,
7716                                   int def) {
7717        ColorStateList colors = getTextColors(context, attrs);
7718
7719        if (colors == null) {
7720            return def;
7721        } else {
7722            return colors.getDefaultColor();
7723        }
7724    }
7725
7726    @Override
7727    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7728        final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK;
7729        if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) {
7730            switch (keyCode) {
7731            case KeyEvent.KEYCODE_A:
7732                if (canSelectText()) {
7733                    return onTextContextMenuItem(ID_SELECT_ALL);
7734                }
7735                break;
7736            case KeyEvent.KEYCODE_X:
7737                if (canCut()) {
7738                    return onTextContextMenuItem(ID_CUT);
7739                }
7740                break;
7741            case KeyEvent.KEYCODE_C:
7742                if (canCopy()) {
7743                    return onTextContextMenuItem(ID_COPY);
7744                }
7745                break;
7746            case KeyEvent.KEYCODE_V:
7747                if (canPaste()) {
7748                    return onTextContextMenuItem(ID_PASTE);
7749                }
7750                break;
7751            }
7752        }
7753        return super.onKeyShortcut(keyCode, event);
7754    }
7755
7756    /**
7757     * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the
7758     * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have
7759     * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient.
7760     */
7761    private boolean canSelectText() {
7762        return hasSelectionController() && mText.length() != 0;
7763    }
7764
7765    /**
7766     * Test based on the <i>intrinsic</i> charateristics of the TextView.
7767     * The text must be spannable and the movement method must allow for arbitary selection.
7768     *
7769     * See also {@link #canSelectText()}.
7770     */
7771    private boolean textCanBeSelected() {
7772        // prepareCursorController() relies on this method.
7773        // If you change this condition, make sure prepareCursorController is called anywhere
7774        // the value of this condition might be changed.
7775        if (mMovement == null || !mMovement.canSelectArbitrarily()) return false;
7776        return isTextEditable() || (isTextSelectable() && mText instanceof Spannable && isEnabled());
7777    }
7778
7779    private boolean canCut() {
7780        if (hasPasswordTransformationMethod()) {
7781            return false;
7782        }
7783
7784        if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mEditor != null && getEditor().mKeyListener != null) {
7785            return true;
7786        }
7787
7788        return false;
7789    }
7790
7791    private boolean canCopy() {
7792        if (hasPasswordTransformationMethod()) {
7793            return false;
7794        }
7795
7796        if (mText.length() > 0 && hasSelection()) {
7797            return true;
7798        }
7799
7800        return false;
7801    }
7802
7803    private boolean canPaste() {
7804        return (mText instanceof Editable &&
7805                mEditor != null && getEditor().mKeyListener != null &&
7806                getSelectionStart() >= 0 &&
7807                getSelectionEnd() >= 0 &&
7808                ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)).
7809                hasPrimaryClip());
7810    }
7811
7812    private static long packRangeInLong(int start, int end) {
7813        return (((long) start) << 32) | end;
7814    }
7815
7816    private static int extractRangeStartFromLong(long range) {
7817        return (int) (range >>> 32);
7818    }
7819
7820    private static int extractRangeEndFromLong(long range) {
7821        return (int) (range & 0x00000000FFFFFFFFL);
7822    }
7823
7824    private boolean selectAll() {
7825        final int length = mText.length();
7826        Selection.setSelection((Spannable) mText, 0, length);
7827        return length > 0;
7828    }
7829
7830    /**
7831     * Adjusts selection to the word under last touch offset.
7832     * Return true if the operation was successfully performed.
7833     */
7834    private boolean selectCurrentWord() {
7835        if (!canSelectText()) {
7836            return false;
7837        }
7838
7839        if (hasPasswordTransformationMethod()) {
7840            // Always select all on a password field.
7841            // Cut/copy menu entries are not available for passwords, but being able to select all
7842            // is however useful to delete or paste to replace the entire content.
7843            return selectAll();
7844        }
7845
7846        int inputType = getInputType();
7847        int klass = inputType & InputType.TYPE_MASK_CLASS;
7848        int variation = inputType & InputType.TYPE_MASK_VARIATION;
7849
7850        // Specific text field types: select the entire text for these
7851        if (klass == InputType.TYPE_CLASS_NUMBER ||
7852                klass == InputType.TYPE_CLASS_PHONE ||
7853                klass == InputType.TYPE_CLASS_DATETIME ||
7854                variation == InputType.TYPE_TEXT_VARIATION_URI ||
7855                variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
7856                variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ||
7857                variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
7858            return selectAll();
7859        }
7860
7861        long lastTouchOffsets = getLastTouchOffsets();
7862        final int minOffset = extractRangeStartFromLong(lastTouchOffsets);
7863        final int maxOffset = extractRangeEndFromLong(lastTouchOffsets);
7864
7865        // Safety check in case standard touch event handling has been bypassed
7866        if (minOffset < 0 || minOffset >= mText.length()) return false;
7867        if (maxOffset < 0 || maxOffset >= mText.length()) return false;
7868
7869        int selectionStart, selectionEnd;
7870
7871        // If a URLSpan (web address, email, phone...) is found at that position, select it.
7872        URLSpan[] urlSpans = ((Spanned) mText).getSpans(minOffset, maxOffset, URLSpan.class);
7873        if (urlSpans.length >= 1) {
7874            URLSpan urlSpan = urlSpans[0];
7875            selectionStart = ((Spanned) mText).getSpanStart(urlSpan);
7876            selectionEnd = ((Spanned) mText).getSpanEnd(urlSpan);
7877        } else {
7878            final WordIterator wordIterator = getWordIterator();
7879            wordIterator.setCharSequence(mText, minOffset, maxOffset);
7880
7881            selectionStart = wordIterator.getBeginning(minOffset);
7882            selectionEnd = wordIterator.getEnd(maxOffset);
7883
7884            if (selectionStart == BreakIterator.DONE || selectionEnd == BreakIterator.DONE ||
7885                    selectionStart == selectionEnd) {
7886                // Possible when the word iterator does not properly handle the text's language
7887                long range = getCharRange(minOffset);
7888                selectionStart = extractRangeStartFromLong(range);
7889                selectionEnd = extractRangeEndFromLong(range);
7890            }
7891        }
7892
7893        Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
7894        return selectionEnd > selectionStart;
7895    }
7896
7897    /**
7898     * This is a temporary method. Future versions may support multi-locale text.
7899     *
7900     * @return The locale that should be used for a word iterator and a spell checker
7901     * in this TextView, based on the current spell checker settings,
7902     * the current IME's locale, or the system default locale.
7903     * @hide
7904     */
7905    public Locale getTextServicesLocale() {
7906        Locale locale = Locale.getDefault();
7907        final TextServicesManager textServicesManager = (TextServicesManager)
7908                mContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);
7909        final SpellCheckerSubtype subtype = textServicesManager.getCurrentSpellCheckerSubtype(true);
7910        if (subtype != null) {
7911            locale = new Locale(subtype.getLocale());
7912        }
7913        return locale;
7914    }
7915
7916    void onLocaleChanged() {
7917        // Will be re-created on demand in getWordIterator with the proper new locale
7918        getEditor().mWordIterator = null;
7919    }
7920
7921    /**
7922     * @hide
7923     */
7924    public WordIterator getWordIterator() {
7925        if (getEditor().mWordIterator == null) {
7926            getEditor().mWordIterator = new WordIterator(getTextServicesLocale());
7927        }
7928        return getEditor().mWordIterator;
7929    }
7930
7931    private long getCharRange(int offset) {
7932        final int textLength = mText.length();
7933        if (offset + 1 < textLength) {
7934            final char currentChar = mText.charAt(offset);
7935            final char nextChar = mText.charAt(offset + 1);
7936            if (Character.isSurrogatePair(currentChar, nextChar)) {
7937                return packRangeInLong(offset,  offset + 2);
7938            }
7939        }
7940        if (offset < textLength) {
7941            return packRangeInLong(offset,  offset + 1);
7942        }
7943        if (offset - 2 >= 0) {
7944            final char previousChar = mText.charAt(offset - 1);
7945            final char previousPreviousChar = mText.charAt(offset - 2);
7946            if (Character.isSurrogatePair(previousPreviousChar, previousChar)) {
7947                return packRangeInLong(offset - 2,  offset);
7948            }
7949        }
7950        if (offset - 1 >= 0) {
7951            return packRangeInLong(offset - 1,  offset);
7952        }
7953        return packRangeInLong(offset,  offset);
7954    }
7955
7956    private long getLastTouchOffsets() {
7957        SelectionModifierCursorController selectionController = getSelectionController();
7958        final int minOffset = selectionController.getMinTouchOffset();
7959        final int maxOffset = selectionController.getMaxTouchOffset();
7960        return packRangeInLong(minOffset, maxOffset);
7961    }
7962
7963    @Override
7964    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7965        super.onPopulateAccessibilityEvent(event);
7966
7967        final boolean isPassword = hasPasswordTransformationMethod();
7968        if (!isPassword) {
7969            CharSequence text = getTextForAccessibility();
7970            if (!TextUtils.isEmpty(text)) {
7971                event.getText().add(text);
7972            }
7973        }
7974    }
7975
7976    @Override
7977    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7978        super.onInitializeAccessibilityEvent(event);
7979
7980        event.setClassName(TextView.class.getName());
7981        final boolean isPassword = hasPasswordTransformationMethod();
7982        event.setPassword(isPassword);
7983
7984        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) {
7985            event.setFromIndex(Selection.getSelectionStart(mText));
7986            event.setToIndex(Selection.getSelectionEnd(mText));
7987            event.setItemCount(mText.length());
7988        }
7989    }
7990
7991    @Override
7992    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
7993        super.onInitializeAccessibilityNodeInfo(info);
7994
7995        info.setClassName(TextView.class.getName());
7996        final boolean isPassword = hasPasswordTransformationMethod();
7997        info.setPassword(isPassword);
7998
7999        if (!isPassword) {
8000            info.setText(getTextForAccessibility());
8001        }
8002    }
8003
8004    @Override
8005    public void sendAccessibilityEvent(int eventType) {
8006        // Do not send scroll events since first they are not interesting for
8007        // accessibility and second such events a generated too frequently.
8008        // For details see the implementation of bringTextIntoView().
8009        if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
8010            return;
8011        }
8012        super.sendAccessibilityEvent(eventType);
8013    }
8014
8015    /**
8016     * Gets the text reported for accessibility purposes. It is the
8017     * text if not empty or the hint.
8018     *
8019     * @return The accessibility text.
8020     */
8021    private CharSequence getTextForAccessibility() {
8022        CharSequence text = getText();
8023        if (TextUtils.isEmpty(text)) {
8024            text = getHint();
8025        }
8026        return text;
8027    }
8028
8029    void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText,
8030            int fromIndex, int removedCount, int addedCount) {
8031        AccessibilityEvent event =
8032            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
8033        event.setFromIndex(fromIndex);
8034        event.setRemovedCount(removedCount);
8035        event.setAddedCount(addedCount);
8036        event.setBeforeText(beforeText);
8037        sendAccessibilityEventUnchecked(event);
8038    }
8039
8040    /**
8041     * Returns whether this text view is a current input method target.  The
8042     * default implementation just checks with {@link InputMethodManager}.
8043     */
8044    public boolean isInputMethodTarget() {
8045        InputMethodManager imm = InputMethodManager.peekInstance();
8046        return imm != null && imm.isActive(this);
8047    }
8048
8049    // Selection context mode
8050    private static final int ID_SELECT_ALL = android.R.id.selectAll;
8051    private static final int ID_CUT = android.R.id.cut;
8052    private static final int ID_COPY = android.R.id.copy;
8053    private static final int ID_PASTE = android.R.id.paste;
8054
8055    /**
8056     * Called when a context menu option for the text view is selected.  Currently
8057     * this will be one of {@link android.R.id#selectAll}, {@link android.R.id#cut},
8058     * {@link android.R.id#copy} or {@link android.R.id#paste}.
8059     *
8060     * @return true if the context menu item action was performed.
8061     */
8062    public boolean onTextContextMenuItem(int id) {
8063        int min = 0;
8064        int max = mText.length();
8065
8066        if (isFocused()) {
8067            final int selStart = getSelectionStart();
8068            final int selEnd = getSelectionEnd();
8069
8070            min = Math.max(0, Math.min(selStart, selEnd));
8071            max = Math.max(0, Math.max(selStart, selEnd));
8072        }
8073
8074        switch (id) {
8075            case ID_SELECT_ALL:
8076                // This does not enter text selection mode. Text is highlighted, so that it can be
8077                // bulk edited, like selectAllOnFocus does. Returns true even if text is empty.
8078                selectAll();
8079                return true;
8080
8081            case ID_PASTE:
8082                paste(min, max);
8083                return true;
8084
8085            case ID_CUT:
8086                setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
8087                deleteText_internal(min, max);
8088                stopSelectionActionMode();
8089                return true;
8090
8091            case ID_COPY:
8092                setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
8093                stopSelectionActionMode();
8094                return true;
8095        }
8096        return false;
8097    }
8098
8099    private CharSequence getTransformedText(int start, int end) {
8100        return removeSuggestionSpans(mTransformed.subSequence(start, end));
8101    }
8102
8103    /**
8104     * Prepare text so that there are not zero or two spaces at beginning and end of region defined
8105     * by [min, max] when replacing this region by paste.
8106     * Note that if there were two spaces (or more) at that position before, they are kept. We just
8107     * make sure we do not add an extra one from the paste content.
8108     */
8109    private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) {
8110        if (paste.length() > 0) {
8111            if (min > 0) {
8112                final char charBefore = mTransformed.charAt(min - 1);
8113                final char charAfter = paste.charAt(0);
8114
8115                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
8116                    // Two spaces at beginning of paste: remove one
8117                    final int originalLength = mText.length();
8118                    deleteText_internal(min - 1, min);
8119                    // Due to filters, there is no guarantee that exactly one character was
8120                    // removed: count instead.
8121                    final int delta = mText.length() - originalLength;
8122                    min += delta;
8123                    max += delta;
8124                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
8125                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
8126                    // No space at beginning of paste: add one
8127                    final int originalLength = mText.length();
8128                    replaceText_internal(min, min, " ");
8129                    // Taking possible filters into account as above.
8130                    final int delta = mText.length() - originalLength;
8131                    min += delta;
8132                    max += delta;
8133                }
8134            }
8135
8136            if (max < mText.length()) {
8137                final char charBefore = paste.charAt(paste.length() - 1);
8138                final char charAfter = mTransformed.charAt(max);
8139
8140                if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) {
8141                    // Two spaces at end of paste: remove one
8142                    deleteText_internal(max, max + 1);
8143                } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' &&
8144                        !Character.isSpaceChar(charAfter) && charAfter != '\n') {
8145                    // No space at end of paste: add one
8146                    replaceText_internal(max, max, " ");
8147                }
8148            }
8149        }
8150
8151        return packRangeInLong(min, max);
8152    }
8153
8154    private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) {
8155        TextView shadowView = (TextView) inflate(mContext,
8156                com.android.internal.R.layout.text_drag_thumbnail, null);
8157
8158        if (shadowView == null) {
8159            throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
8160        }
8161
8162        if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) {
8163            text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH);
8164        }
8165        shadowView.setText(text);
8166        shadowView.setTextColor(getTextColors());
8167
8168        shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge);
8169        shadowView.setGravity(Gravity.CENTER);
8170
8171        shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
8172                ViewGroup.LayoutParams.WRAP_CONTENT));
8173
8174        final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
8175        shadowView.measure(size, size);
8176
8177        shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
8178        shadowView.invalidate();
8179        return new DragShadowBuilder(shadowView);
8180    }
8181
8182    @Override
8183    public boolean performLongClick() {
8184        boolean handled = false;
8185        boolean vibrate = true;
8186
8187        if (super.performLongClick()) {
8188            handled = true;
8189        }
8190
8191        // Long press in empty space moves cursor and shows the Paste affordance if available.
8192        if (!handled && mEditor != null && !isPositionOnText(getEditor().mLastDownPositionX, getEditor().mLastDownPositionY) &&
8193                getEditor().mInsertionControllerEnabled) {
8194            final int offset = getOffsetForPosition(getEditor().mLastDownPositionX, getEditor().mLastDownPositionY);
8195            stopSelectionActionMode();
8196            Selection.setSelection((Spannable) mText, offset);
8197            getInsertionController().showWithActionPopup();
8198            handled = true;
8199            vibrate = false;
8200        }
8201
8202        if (!handled && (mEditor == null || getEditor().mSelectionActionMode != null)) {
8203            if (touchPositionIsInSelection()) {
8204                // Start a drag
8205                final int start = getSelectionStart();
8206                final int end = getSelectionEnd();
8207                CharSequence selectedText = getTransformedText(start, end);
8208                ClipData data = ClipData.newPlainText(null, selectedText);
8209                DragLocalState localState = new DragLocalState(this, start, end);
8210                startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0);
8211                stopSelectionActionMode();
8212            } else {
8213                getSelectionController().hide();
8214                selectCurrentWord();
8215                getSelectionController().show();
8216            }
8217            handled = true;
8218        }
8219
8220        // Start a new selection
8221        if (!handled) {
8222            vibrate = handled = startSelectionActionMode();
8223        }
8224
8225        if (vibrate) {
8226            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
8227        }
8228
8229        if (handled && mEditor != null) {
8230            getEditor().mDiscardNextActionUp = true;
8231        }
8232
8233        return handled;
8234    }
8235
8236    private boolean touchPositionIsInSelection() {
8237        int selectionStart = getSelectionStart();
8238        int selectionEnd = getSelectionEnd();
8239
8240        if (selectionStart == selectionEnd) {
8241            return false;
8242        }
8243
8244        if (selectionStart > selectionEnd) {
8245            int tmp = selectionStart;
8246            selectionStart = selectionEnd;
8247            selectionEnd = tmp;
8248            Selection.setSelection((Spannable) mText, selectionStart, selectionEnd);
8249        }
8250
8251        SelectionModifierCursorController selectionController = getSelectionController();
8252        int minOffset = selectionController.getMinTouchOffset();
8253        int maxOffset = selectionController.getMaxTouchOffset();
8254
8255        return ((minOffset >= selectionStart) && (maxOffset < selectionEnd));
8256    }
8257
8258    private PositionListener getPositionListener() {
8259        if (getEditor().mPositionListener == null) {
8260            getEditor().mPositionListener = new PositionListener();
8261        }
8262        return getEditor().mPositionListener;
8263    }
8264
8265    private interface TextViewPositionListener {
8266        public void updatePosition(int parentPositionX, int parentPositionY,
8267                boolean parentPositionChanged, boolean parentScrolled);
8268    }
8269
8270    private boolean isPositionVisible(int positionX, int positionY) {
8271        synchronized (TEMP_POSITION) {
8272            final float[] position = TEMP_POSITION;
8273            position[0] = positionX;
8274            position[1] = positionY;
8275            View view = this;
8276
8277            while (view != null) {
8278                if (view != this) {
8279                    // Local scroll is already taken into account in positionX/Y
8280                    position[0] -= view.getScrollX();
8281                    position[1] -= view.getScrollY();
8282                }
8283
8284                if (position[0] < 0 || position[1] < 0 ||
8285                        position[0] > view.getWidth() || position[1] > view.getHeight()) {
8286                    return false;
8287                }
8288
8289                if (!view.getMatrix().isIdentity()) {
8290                    view.getMatrix().mapPoints(position);
8291                }
8292
8293                position[0] += view.getLeft();
8294                position[1] += view.getTop();
8295
8296                final ViewParent parent = view.getParent();
8297                if (parent instanceof View) {
8298                    view = (View) parent;
8299                } else {
8300                    // We've reached the ViewRoot, stop iterating
8301                    view = null;
8302                }
8303            }
8304        }
8305
8306        // We've been able to walk up the view hierarchy and the position was never clipped
8307        return true;
8308    }
8309
8310    private boolean isOffsetVisible(int offset) {
8311        final int line = mLayout.getLineForOffset(offset);
8312        final int lineBottom = mLayout.getLineBottom(line);
8313        final int primaryHorizontal = (int) mLayout.getPrimaryHorizontal(offset);
8314        return isPositionVisible(primaryHorizontal + viewportToContentHorizontalOffset(),
8315                lineBottom + viewportToContentVerticalOffset());
8316    }
8317
8318    @Override
8319    protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) {
8320        super.onScrollChanged(horiz, vert, oldHoriz, oldVert);
8321        if (mEditor != null && getEditor().mPositionListener != null) {
8322            getEditor().mPositionListener.onScrollChanged();
8323        }
8324    }
8325
8326    /**
8327     * Removes the suggestion spans.
8328     */
8329    CharSequence removeSuggestionSpans(CharSequence text) {
8330       if (text instanceof Spanned) {
8331           Spannable spannable;
8332           if (text instanceof Spannable) {
8333               spannable = (Spannable) text;
8334           } else {
8335               spannable = new SpannableString(text);
8336               text = spannable;
8337           }
8338
8339           SuggestionSpan[] spans = spannable.getSpans(0, text.length(), SuggestionSpan.class);
8340           for (int i = 0; i < spans.length; i++) {
8341               spannable.removeSpan(spans[i]);
8342           }
8343       }
8344       return text;
8345    }
8346
8347    void showSuggestions() {
8348        if (getEditor().mSuggestionsPopupWindow == null) {
8349            getEditor().mSuggestionsPopupWindow = new SuggestionsPopupWindow();
8350        }
8351        hideControllers();
8352        getEditor().mSuggestionsPopupWindow.show();
8353    }
8354
8355    boolean areSuggestionsShown() {
8356        return getEditor().mSuggestionsPopupWindow != null && getEditor().mSuggestionsPopupWindow.isShowing();
8357    }
8358
8359    /**
8360     * Return whether or not suggestions are enabled on this TextView. The suggestions are generated
8361     * by the IME or by the spell checker as the user types. This is done by adding
8362     * {@link SuggestionSpan}s to the text.
8363     *
8364     * When suggestions are enabled (default), this list of suggestions will be displayed when the
8365     * user asks for them on these parts of the text. This value depends on the inputType of this
8366     * TextView.
8367     *
8368     * The class of the input type must be {@link InputType#TYPE_CLASS_TEXT}.
8369     *
8370     * In addition, the type variation must be one of
8371     * {@link InputType#TYPE_TEXT_VARIATION_NORMAL},
8372     * {@link InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT},
8373     * {@link InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE},
8374     * {@link InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or
8375     * {@link InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}.
8376     *
8377     * And finally, the {@link InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS} flag must <i>not</i> be set.
8378     *
8379     * @return true if the suggestions popup window is enabled, based on the inputType.
8380     */
8381    public boolean isSuggestionsEnabled() {
8382        if (mEditor == null) return false;
8383        if ((getEditor().mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) return false;
8384        if ((getEditor().mInputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) > 0) return false;
8385
8386        final int variation = getEditor().mInputType & EditorInfo.TYPE_MASK_VARIATION;
8387        return (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL ||
8388                variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT ||
8389                variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE ||
8390                variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE ||
8391                variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT);
8392    }
8393
8394    /**
8395     * If provided, this ActionMode.Callback will be used to create the ActionMode when text
8396     * selection is initiated in this View.
8397     *
8398     * The standard implementation populates the menu with a subset of Select All, Cut, Copy and
8399     * Paste actions, depending on what this View supports.
8400     *
8401     * A custom implementation can add new entries in the default menu in its
8402     * {@link android.view.ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The
8403     * default actions can also be removed from the menu using {@link Menu#removeItem(int)} and
8404     * passing {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy}
8405     * or {@link android.R.id#paste} ids as parameters.
8406     *
8407     * Returning false from
8408     * {@link android.view.ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will prevent
8409     * the action mode from being started.
8410     *
8411     * Action click events should be handled by the custom implementation of
8412     * {@link android.view.ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}.
8413     *
8414     * Note that text selection mode is not started when a TextView receives focus and the
8415     * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in
8416     * that case, to allow for quick replacement.
8417     */
8418    public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) {
8419        createEditorIfNeeded("custom selection action mode set");
8420        getEditor().mCustomSelectionActionModeCallback = actionModeCallback;
8421    }
8422
8423    /**
8424     * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null.
8425     *
8426     * @return The current custom selection callback.
8427     */
8428    public ActionMode.Callback getCustomSelectionActionModeCallback() {
8429        return mEditor == null ? null : getEditor().mCustomSelectionActionModeCallback;
8430    }
8431
8432    /**
8433     *
8434     * @return true if the selection mode was actually started.
8435     */
8436    private boolean startSelectionActionMode() {
8437        if (getEditor().mSelectionActionMode != null) {
8438            // Selection action mode is already started
8439            return false;
8440        }
8441
8442        if (!canSelectText() || !requestFocus()) {
8443            Log.w(LOG_TAG, "TextView does not support text selection. Action mode cancelled.");
8444            return false;
8445        }
8446
8447        if (!hasSelection()) {
8448            // There may already be a selection on device rotation
8449            if (!selectCurrentWord()) {
8450                // No word found under cursor or text selection not permitted.
8451                return false;
8452            }
8453        }
8454
8455        boolean willExtract = extractedTextModeWillBeStarted();
8456
8457        // Do not start the action mode when extracted text will show up full screen, which would
8458        // immediately hide the newly created action bar and would be visually distracting.
8459        if (!willExtract) {
8460            ActionMode.Callback actionModeCallback = new SelectionActionModeCallback();
8461            getEditor().mSelectionActionMode = startActionMode(actionModeCallback);
8462        }
8463
8464        final boolean selectionStarted = getEditor().mSelectionActionMode != null || willExtract;
8465        if (selectionStarted && !isTextSelectable()) {
8466            // Show the IME to be able to replace text, except when selecting non editable text.
8467            final InputMethodManager imm = InputMethodManager.peekInstance();
8468            if (imm != null) {
8469                imm.showSoftInput(this, 0, null);
8470            }
8471        }
8472
8473        return selectionStarted;
8474    }
8475
8476    private boolean extractedTextModeWillBeStarted() {
8477        if (!(this instanceof ExtractEditText)) {
8478            final InputMethodManager imm = InputMethodManager.peekInstance();
8479            return  imm != null && imm.isFullscreenMode();
8480        }
8481        return false;
8482    }
8483
8484    /**
8485     * @hide
8486     */
8487    protected void stopSelectionActionMode() {
8488        if (getEditor().mSelectionActionMode != null) {
8489            // This will hide the mSelectionModifierCursorController
8490            getEditor().mSelectionActionMode.finish();
8491        }
8492    }
8493
8494    /**
8495     * Paste clipboard content between min and max positions.
8496     */
8497    private void paste(int min, int max) {
8498        ClipboardManager clipboard =
8499            (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
8500        ClipData clip = clipboard.getPrimaryClip();
8501        if (clip != null) {
8502            boolean didFirst = false;
8503            for (int i=0; i<clip.getItemCount(); i++) {
8504                CharSequence paste = clip.getItemAt(i).coerceToText(getContext());
8505                if (paste != null) {
8506                    if (!didFirst) {
8507                        long minMax = prepareSpacesAroundPaste(min, max, paste);
8508                        min = extractRangeStartFromLong(minMax);
8509                        max = extractRangeEndFromLong(minMax);
8510                        Selection.setSelection((Spannable) mText, max);
8511                        ((Editable) mText).replace(min, max, paste);
8512                        didFirst = true;
8513                    } else {
8514                        ((Editable) mText).insert(getSelectionEnd(), "\n");
8515                        ((Editable) mText).insert(getSelectionEnd(), paste);
8516                    }
8517                }
8518            }
8519            stopSelectionActionMode();
8520            LAST_CUT_OR_COPY_TIME = 0;
8521        }
8522    }
8523
8524    private void setPrimaryClip(ClipData clip) {
8525        ClipboardManager clipboard = (ClipboardManager) getContext().
8526                getSystemService(Context.CLIPBOARD_SERVICE);
8527        clipboard.setPrimaryClip(clip);
8528        LAST_CUT_OR_COPY_TIME = SystemClock.uptimeMillis();
8529    }
8530
8531    private void hideInsertionPointCursorController() {
8532        // No need to create the controller to hide it.
8533        if (getEditor().mInsertionPointCursorController != null) {
8534            getEditor().mInsertionPointCursorController.hide();
8535        }
8536    }
8537
8538    /**
8539     * Hides the insertion controller and stops text selection mode, hiding the selection controller
8540     */
8541    private void hideControllers() {
8542        hideCursorControllers();
8543        hideSpanControllers();
8544    }
8545
8546    private void hideSpanControllers() {
8547        if (mChangeWatcher != null) {
8548            mChangeWatcher.hideControllers();
8549        }
8550    }
8551
8552    private void hideCursorControllers() {
8553        if (getEditor().mSuggestionsPopupWindow != null && !getEditor().mSuggestionsPopupWindow.isShowingUp()) {
8554            // Should be done before hide insertion point controller since it triggers a show of it
8555            getEditor().mSuggestionsPopupWindow.hide();
8556        }
8557        hideInsertionPointCursorController();
8558        stopSelectionActionMode();
8559    }
8560
8561    /**
8562     * Get the character offset closest to the specified absolute position. A typical use case is to
8563     * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method.
8564     *
8565     * @param x The horizontal absolute position of a point on screen
8566     * @param y The vertical absolute position of a point on screen
8567     * @return the character offset for the character whose position is closest to the specified
8568     *  position. Returns -1 if there is no layout.
8569     */
8570    public int getOffsetForPosition(float x, float y) {
8571        if (getLayout() == null) return -1;
8572        final int line = getLineAtCoordinate(y);
8573        final int offset = getOffsetAtCoordinate(line, x);
8574        return offset;
8575    }
8576
8577    private float convertToLocalHorizontalCoordinate(float x) {
8578        x -= getTotalPaddingLeft();
8579        // Clamp the position to inside of the view.
8580        x = Math.max(0.0f, x);
8581        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
8582        x += getScrollX();
8583        return x;
8584    }
8585
8586    private int getLineAtCoordinate(float y) {
8587        y -= getTotalPaddingTop();
8588        // Clamp the position to inside of the view.
8589        y = Math.max(0.0f, y);
8590        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
8591        y += getScrollY();
8592        return getLayout().getLineForVertical((int) y);
8593    }
8594
8595    private int getOffsetAtCoordinate(int line, float x) {
8596        x = convertToLocalHorizontalCoordinate(x);
8597        return getLayout().getOffsetForHorizontal(line, x);
8598    }
8599
8600    /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed
8601     * in the view. Returns false when the position is in the empty space of left/right of text.
8602     */
8603    private boolean isPositionOnText(float x, float y) {
8604        if (getLayout() == null) return false;
8605
8606        final int line = getLineAtCoordinate(y);
8607        x = convertToLocalHorizontalCoordinate(x);
8608
8609        if (x < getLayout().getLineLeft(line)) return false;
8610        if (x > getLayout().getLineRight(line)) return false;
8611        return true;
8612    }
8613
8614    @Override
8615    public boolean onDragEvent(DragEvent event) {
8616        switch (event.getAction()) {
8617            case DragEvent.ACTION_DRAG_STARTED:
8618                return hasInsertionController();
8619
8620            case DragEvent.ACTION_DRAG_ENTERED:
8621                TextView.this.requestFocus();
8622                return true;
8623
8624            case DragEvent.ACTION_DRAG_LOCATION:
8625                final int offset = getOffsetForPosition(event.getX(), event.getY());
8626                Selection.setSelection((Spannable)mText, offset);
8627                return true;
8628
8629            case DragEvent.ACTION_DROP:
8630                onDrop(event);
8631                return true;
8632
8633            case DragEvent.ACTION_DRAG_ENDED:
8634            case DragEvent.ACTION_DRAG_EXITED:
8635            default:
8636                return true;
8637        }
8638    }
8639
8640    private void onDrop(DragEvent event) {
8641        StringBuilder content = new StringBuilder("");
8642        ClipData clipData = event.getClipData();
8643        final int itemCount = clipData.getItemCount();
8644        for (int i=0; i < itemCount; i++) {
8645            Item item = clipData.getItemAt(i);
8646            content.append(item.coerceToText(TextView.this.mContext));
8647        }
8648
8649        final int offset = getOffsetForPosition(event.getX(), event.getY());
8650
8651        Object localState = event.getLocalState();
8652        DragLocalState dragLocalState = null;
8653        if (localState instanceof DragLocalState) {
8654            dragLocalState = (DragLocalState) localState;
8655        }
8656        boolean dragDropIntoItself = dragLocalState != null &&
8657                dragLocalState.sourceTextView == this;
8658
8659        if (dragDropIntoItself) {
8660            if (offset >= dragLocalState.start && offset < dragLocalState.end) {
8661                // A drop inside the original selection discards the drop.
8662                return;
8663            }
8664        }
8665
8666        final int originalLength = mText.length();
8667        long minMax = prepareSpacesAroundPaste(offset, offset, content);
8668        int min = extractRangeStartFromLong(minMax);
8669        int max = extractRangeEndFromLong(minMax);
8670
8671        Selection.setSelection((Spannable) mText, max);
8672        replaceText_internal(min, max, content);
8673
8674        if (dragDropIntoItself) {
8675            int dragSourceStart = dragLocalState.start;
8676            int dragSourceEnd = dragLocalState.end;
8677            if (max <= dragSourceStart) {
8678                // Inserting text before selection has shifted positions
8679                final int shift = mText.length() - originalLength;
8680                dragSourceStart += shift;
8681                dragSourceEnd += shift;
8682            }
8683
8684            // Delete original selection
8685            deleteText_internal(dragSourceStart, dragSourceEnd);
8686
8687            // Make sure we do not leave two adjacent spaces.
8688            if ((dragSourceStart == 0 ||
8689                    Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) &&
8690                    (dragSourceStart == mText.length() ||
8691                    Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) {
8692                final int pos = dragSourceStart == mText.length() ?
8693                        dragSourceStart - 1 : dragSourceStart;
8694                deleteText_internal(pos, pos + 1);
8695            }
8696        }
8697    }
8698
8699    /**
8700     * @return True if this view supports insertion handles.
8701     */
8702    boolean hasInsertionController() {
8703        return getEditor().mInsertionControllerEnabled;
8704    }
8705
8706    /**
8707     * @return True if this view supports selection handles.
8708     */
8709    boolean hasSelectionController() {
8710        return getEditor().mSelectionControllerEnabled;
8711    }
8712
8713    InsertionPointCursorController getInsertionController() {
8714        if (!getEditor().mInsertionControllerEnabled) {
8715            return null;
8716        }
8717
8718        if (getEditor().mInsertionPointCursorController == null) {
8719            getEditor().mInsertionPointCursorController = new InsertionPointCursorController();
8720
8721            final ViewTreeObserver observer = getViewTreeObserver();
8722            observer.addOnTouchModeChangeListener(getEditor().mInsertionPointCursorController);
8723        }
8724
8725        return getEditor().mInsertionPointCursorController;
8726    }
8727
8728    SelectionModifierCursorController getSelectionController() {
8729        if (!getEditor().mSelectionControllerEnabled) {
8730            return null;
8731        }
8732
8733        if (getEditor().mSelectionModifierCursorController == null) {
8734            getEditor().mSelectionModifierCursorController = new SelectionModifierCursorController();
8735
8736            final ViewTreeObserver observer = getViewTreeObserver();
8737            observer.addOnTouchModeChangeListener(getEditor().mSelectionModifierCursorController);
8738        }
8739
8740        return getEditor().mSelectionModifierCursorController;
8741    }
8742
8743    boolean isInBatchEditMode() {
8744        if (mEditor == null) return false;
8745        final InputMethodState ims = getEditor().mInputMethodState;
8746        if (ims != null) {
8747            return ims.mBatchEditNesting > 0;
8748        }
8749        return getEditor().mInBatchEditControllers;
8750    }
8751
8752    @Override
8753    public void onResolveTextDirection() {
8754        if (hasPasswordTransformationMethod()) {
8755            mTextDir = TextDirectionHeuristics.LOCALE;
8756            return;
8757        }
8758
8759        // Always need to resolve layout direction first
8760        final boolean defaultIsRtl = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
8761
8762        // Now, we can select the heuristic
8763        int textDir = getResolvedTextDirection();
8764        switch (textDir) {
8765            default:
8766            case TEXT_DIRECTION_FIRST_STRONG:
8767                mTextDir = (defaultIsRtl ? TextDirectionHeuristics.FIRSTSTRONG_RTL :
8768                        TextDirectionHeuristics.FIRSTSTRONG_LTR);
8769                break;
8770            case TEXT_DIRECTION_ANY_RTL:
8771                mTextDir = TextDirectionHeuristics.ANYRTL_LTR;
8772                break;
8773            case TEXT_DIRECTION_LTR:
8774                mTextDir = TextDirectionHeuristics.LTR;
8775                break;
8776            case TEXT_DIRECTION_RTL:
8777                mTextDir = TextDirectionHeuristics.RTL;
8778                break;
8779            case TEXT_DIRECTION_LOCALE:
8780                mTextDir = TextDirectionHeuristics.LOCALE;
8781                break;
8782        }
8783    }
8784
8785    /**
8786     * Subclasses will need to override this method to implement their own way of resolving
8787     * drawables depending on the layout direction.
8788     *
8789     * A call to the super method will be required from the subclasses implementation.
8790     */
8791    protected void resolveDrawables() {
8792        // No need to resolve twice
8793        if (mResolvedDrawables) {
8794            return;
8795        }
8796        // No drawable to resolve
8797        if (mDrawables == null) {
8798            return;
8799        }
8800        // No relative drawable to resolve
8801        if (mDrawables.mDrawableStart == null && mDrawables.mDrawableEnd == null) {
8802            mResolvedDrawables = true;
8803            return;
8804        }
8805
8806        Drawables dr = mDrawables;
8807        switch(getResolvedLayoutDirection()) {
8808            case LAYOUT_DIRECTION_RTL:
8809                if (dr.mDrawableStart != null) {
8810                    dr.mDrawableRight = dr.mDrawableStart;
8811
8812                    dr.mDrawableSizeRight = dr.mDrawableSizeStart;
8813                    dr.mDrawableHeightRight = dr.mDrawableHeightStart;
8814                }
8815                if (dr.mDrawableEnd != null) {
8816                    dr.mDrawableLeft = dr.mDrawableEnd;
8817
8818                    dr.mDrawableSizeLeft = dr.mDrawableSizeEnd;
8819                    dr.mDrawableHeightLeft = dr.mDrawableHeightEnd;
8820                }
8821                break;
8822
8823            case LAYOUT_DIRECTION_LTR:
8824            default:
8825                if (dr.mDrawableStart != null) {
8826                    dr.mDrawableLeft = dr.mDrawableStart;
8827
8828                    dr.mDrawableSizeLeft = dr.mDrawableSizeStart;
8829                    dr.mDrawableHeightLeft = dr.mDrawableHeightStart;
8830                }
8831                if (dr.mDrawableEnd != null) {
8832                    dr.mDrawableRight = dr.mDrawableEnd;
8833
8834                    dr.mDrawableSizeRight = dr.mDrawableSizeEnd;
8835                    dr.mDrawableHeightRight = dr.mDrawableHeightEnd;
8836                }
8837                break;
8838        }
8839        mResolvedDrawables = true;
8840    }
8841
8842    protected void resetResolvedDrawables() {
8843        mResolvedDrawables = false;
8844    }
8845
8846    /**
8847     * @hide
8848     */
8849    protected void viewClicked(InputMethodManager imm) {
8850        if (imm != null) {
8851            imm.viewClicked(this);
8852        }
8853    }
8854
8855    /**
8856     * Deletes the range of text [start, end[.
8857     * @hide
8858     */
8859    protected void deleteText_internal(int start, int end) {
8860        ((Editable) mText).delete(start, end);
8861    }
8862
8863    /**
8864     * Replaces the range of text [start, end[ by replacement text
8865     * @hide
8866     */
8867    protected void replaceText_internal(int start, int end, CharSequence text) {
8868        ((Editable) mText).replace(start, end, text);
8869    }
8870
8871    /**
8872     * Sets a span on the specified range of text
8873     * @hide
8874     */
8875    protected void setSpan_internal(Object span, int start, int end, int flags) {
8876        ((Editable) mText).setSpan(span, start, end, flags);
8877    }
8878
8879    /**
8880     * Moves the cursor to the specified offset position in text
8881     * @hide
8882     */
8883    protected void setCursorPosition_internal(int start, int end) {
8884        Selection.setSelection(((Editable) mText), start, end);
8885    }
8886
8887    /**
8888     * An Editor should be created as soon as any of the editable-specific fields (grouped
8889     * inside the Editor object) is assigned to a non-default value.
8890     * This method will create the Editor if needed.
8891     *
8892     * A standard TextView (as well as buttons, checkboxes...) should not qualify and hence will
8893     * have a null Editor, unlike an EditText. Inconsistent in-between states will have an
8894     * Editor for backward compatibility, as soon as one of these fields is assigned.
8895     *
8896     * Also note that for performance reasons, the mEditor is created when needed, but not
8897     * reset when no more edit-specific fields are needed.
8898     */
8899    private void createEditorIfNeeded(String reason) {
8900        if (mEditor == null) {
8901            if (!(this instanceof EditText)) {
8902                Log.e(LOG_TAG + " EDITOR", "Creating Editor on TextView. " + reason);
8903            }
8904            mEditor = new Editor();
8905        } else {
8906            if (!(this instanceof EditText)) {
8907                Log.d(LOG_TAG + " EDITOR", "Redundant Editor creation. " + reason);
8908            }
8909        }
8910    }
8911
8912    private Editor getEditor() {
8913        if (mEditor == null) {
8914            //createEditorIfNeeded("Problem: mEditor is not initialized!");
8915            Log.e(LOG_TAG, "mEditor not initialized. Please send a bug report to debunne@");
8916        }
8917        return mEditor;
8918    }
8919
8920    /**
8921     * User interface state that is stored by TextView for implementing
8922     * {@link View#onSaveInstanceState}.
8923     */
8924    public static class SavedState extends BaseSavedState {
8925        int selStart;
8926        int selEnd;
8927        CharSequence text;
8928        boolean frozenWithFocus;
8929        CharSequence error;
8930
8931        SavedState(Parcelable superState) {
8932            super(superState);
8933        }
8934
8935        @Override
8936        public void writeToParcel(Parcel out, int flags) {
8937            super.writeToParcel(out, flags);
8938            out.writeInt(selStart);
8939            out.writeInt(selEnd);
8940            out.writeInt(frozenWithFocus ? 1 : 0);
8941            TextUtils.writeToParcel(text, out, flags);
8942
8943            if (error == null) {
8944                out.writeInt(0);
8945            } else {
8946                out.writeInt(1);
8947                TextUtils.writeToParcel(error, out, flags);
8948            }
8949        }
8950
8951        @Override
8952        public String toString() {
8953            String str = "TextView.SavedState{"
8954                    + Integer.toHexString(System.identityHashCode(this))
8955                    + " start=" + selStart + " end=" + selEnd;
8956            if (text != null) {
8957                str += " text=" + text;
8958            }
8959            return str + "}";
8960        }
8961
8962        @SuppressWarnings("hiding")
8963        public static final Parcelable.Creator<SavedState> CREATOR
8964                = new Parcelable.Creator<SavedState>() {
8965            public SavedState createFromParcel(Parcel in) {
8966                return new SavedState(in);
8967            }
8968
8969            public SavedState[] newArray(int size) {
8970                return new SavedState[size];
8971            }
8972        };
8973
8974        private SavedState(Parcel in) {
8975            super(in);
8976            selStart = in.readInt();
8977            selEnd = in.readInt();
8978            frozenWithFocus = (in.readInt() != 0);
8979            text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
8980
8981            if (in.readInt() != 0) {
8982                error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
8983            }
8984        }
8985    }
8986
8987    private static class CharWrapper implements CharSequence, GetChars, GraphicsOperations {
8988        private char[] mChars;
8989        private int mStart, mLength;
8990
8991        public CharWrapper(char[] chars, int start, int len) {
8992            mChars = chars;
8993            mStart = start;
8994            mLength = len;
8995        }
8996
8997        /* package */ void set(char[] chars, int start, int len) {
8998            mChars = chars;
8999            mStart = start;
9000            mLength = len;
9001        }
9002
9003        public int length() {
9004            return mLength;
9005        }
9006
9007        public char charAt(int off) {
9008            return mChars[off + mStart];
9009        }
9010
9011        @Override
9012        public String toString() {
9013            return new String(mChars, mStart, mLength);
9014        }
9015
9016        public CharSequence subSequence(int start, int end) {
9017            if (start < 0 || end < 0 || start > mLength || end > mLength) {
9018                throw new IndexOutOfBoundsException(start + ", " + end);
9019            }
9020
9021            return new String(mChars, start + mStart, end - start);
9022        }
9023
9024        public void getChars(int start, int end, char[] buf, int off) {
9025            if (start < 0 || end < 0 || start > mLength || end > mLength) {
9026                throw new IndexOutOfBoundsException(start + ", " + end);
9027            }
9028
9029            System.arraycopy(mChars, start + mStart, buf, off, end - start);
9030        }
9031
9032        public void drawText(Canvas c, int start, int end,
9033                             float x, float y, Paint p) {
9034            c.drawText(mChars, start + mStart, end - start, x, y, p);
9035        }
9036
9037        public void drawTextRun(Canvas c, int start, int end,
9038                int contextStart, int contextEnd, float x, float y, int flags, Paint p) {
9039            int count = end - start;
9040            int contextCount = contextEnd - contextStart;
9041            c.drawTextRun(mChars, start + mStart, count, contextStart + mStart,
9042                    contextCount, x, y, flags, p);
9043        }
9044
9045        public float measureText(int start, int end, Paint p) {
9046            return p.measureText(mChars, start + mStart, end - start);
9047        }
9048
9049        public int getTextWidths(int start, int end, float[] widths, Paint p) {
9050            return p.getTextWidths(mChars, start + mStart, end - start, widths);
9051        }
9052
9053        public float getTextRunAdvances(int start, int end, int contextStart,
9054                int contextEnd, int flags, float[] advances, int advancesIndex,
9055                Paint p) {
9056            int count = end - start;
9057            int contextCount = contextEnd - contextStart;
9058            return p.getTextRunAdvances(mChars, start + mStart, count,
9059                    contextStart + mStart, contextCount, flags, advances,
9060                    advancesIndex);
9061        }
9062
9063        public float getTextRunAdvances(int start, int end, int contextStart,
9064                int contextEnd, int flags, float[] advances, int advancesIndex,
9065                Paint p, int reserved) {
9066            int count = end - start;
9067            int contextCount = contextEnd - contextStart;
9068            return p.getTextRunAdvances(mChars, start + mStart, count,
9069                    contextStart + mStart, contextCount, flags, advances,
9070                    advancesIndex, reserved);
9071        }
9072
9073        public int getTextRunCursor(int contextStart, int contextEnd, int flags,
9074                int offset, int cursorOpt, Paint p) {
9075            int contextCount = contextEnd - contextStart;
9076            return p.getTextRunCursor(mChars, contextStart + mStart,
9077                    contextCount, flags, offset + mStart, cursorOpt);
9078        }
9079    }
9080
9081    private static class ErrorPopup extends PopupWindow {
9082        private boolean mAbove = false;
9083        private final TextView mView;
9084        private int mPopupInlineErrorBackgroundId = 0;
9085        private int mPopupInlineErrorAboveBackgroundId = 0;
9086
9087        ErrorPopup(TextView v, int width, int height) {
9088            super(v, width, height);
9089            mView = v;
9090            // Make sure the TextView has a background set as it will be used the first time it is
9091            // shown and positionned. Initialized with below background, which should have
9092            // dimensions identical to the above version for this to work (and is more likely).
9093            mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
9094                    com.android.internal.R.styleable.Theme_errorMessageBackground);
9095            mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
9096        }
9097
9098        void fixDirection(boolean above) {
9099            mAbove = above;
9100
9101            if (above) {
9102                mPopupInlineErrorAboveBackgroundId =
9103                    getResourceId(mPopupInlineErrorAboveBackgroundId,
9104                            com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
9105            } else {
9106                mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
9107                        com.android.internal.R.styleable.Theme_errorMessageBackground);
9108            }
9109
9110            mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId :
9111                mPopupInlineErrorBackgroundId);
9112        }
9113
9114        private int getResourceId(int currentId, int index) {
9115            if (currentId == 0) {
9116                TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
9117                        R.styleable.Theme);
9118                currentId = styledAttributes.getResourceId(index, 0);
9119                styledAttributes.recycle();
9120            }
9121            return currentId;
9122        }
9123
9124        @Override
9125        public void update(int x, int y, int w, int h, boolean force) {
9126            super.update(x, y, w, h, force);
9127
9128            boolean above = isAboveAnchor();
9129            if (above != mAbove) {
9130                fixDirection(above);
9131            }
9132        }
9133    }
9134
9135    private class CorrectionHighlighter {
9136        private final Path mPath = new Path();
9137        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
9138        private int mStart, mEnd;
9139        private long mFadingStartTime;
9140        private final static int FADE_OUT_DURATION = 400;
9141
9142        public CorrectionHighlighter() {
9143            mPaint.setCompatibilityScaling(getResources().getCompatibilityInfo().applicationScale);
9144            mPaint.setStyle(Paint.Style.FILL);
9145        }
9146
9147        public void highlight(CorrectionInfo info) {
9148            mStart = info.getOffset();
9149            mEnd = mStart + info.getNewText().length();
9150            mFadingStartTime = SystemClock.uptimeMillis();
9151
9152            if (mStart < 0 || mEnd < 0) {
9153                stopAnimation();
9154            }
9155        }
9156
9157        public void draw(Canvas canvas, int cursorOffsetVertical) {
9158            if (updatePath() && updatePaint()) {
9159                if (cursorOffsetVertical != 0) {
9160                    canvas.translate(0, cursorOffsetVertical);
9161                }
9162
9163                canvas.drawPath(mPath, mPaint);
9164
9165                if (cursorOffsetVertical != 0) {
9166                    canvas.translate(0, -cursorOffsetVertical);
9167                }
9168                invalidate(true); // TODO invalidate cursor region only
9169            } else {
9170                stopAnimation();
9171                invalidate(false); // TODO invalidate cursor region only
9172            }
9173        }
9174
9175        private boolean updatePaint() {
9176            final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
9177            if (duration > FADE_OUT_DURATION) return false;
9178
9179            final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
9180            final int highlightColorAlpha = Color.alpha(mHighlightColor);
9181            final int color = (mHighlightColor & 0x00FFFFFF) +
9182                    ((int) (highlightColorAlpha * coef) << 24);
9183            mPaint.setColor(color);
9184            return true;
9185        }
9186
9187        private boolean updatePath() {
9188            final Layout layout = TextView.this.mLayout;
9189            if (layout == null) return false;
9190
9191            // Update in case text is edited while the animation is run
9192            final int length = mText.length();
9193            int start = Math.min(length, mStart);
9194            int end = Math.min(length, mEnd);
9195
9196            mPath.reset();
9197            TextView.this.mLayout.getSelectionPath(start, end, mPath);
9198            return true;
9199        }
9200
9201        private void invalidate(boolean delayed) {
9202            if (TextView.this.mLayout == null) return;
9203
9204            synchronized (TEMP_RECTF) {
9205                mPath.computeBounds(TEMP_RECTF, false);
9206
9207                int left = getCompoundPaddingLeft();
9208                int top = getExtendedPaddingTop() + getVerticalOffset(true);
9209
9210                if (delayed) {
9211                    TextView.this.postInvalidateDelayed(16, // 60 Hz update
9212                            left + (int) TEMP_RECTF.left, top + (int) TEMP_RECTF.top,
9213                            left + (int) TEMP_RECTF.right, top + (int) TEMP_RECTF.bottom);
9214                } else {
9215                    TextView.this.postInvalidate((int) TEMP_RECTF.left, (int) TEMP_RECTF.top,
9216                            (int) TEMP_RECTF.right, (int) TEMP_RECTF.bottom);
9217                }
9218            }
9219        }
9220
9221        private void stopAnimation() {
9222            TextView.this.getEditor().mCorrectionHighlighter = null;
9223        }
9224    }
9225
9226    private static final class Marquee extends Handler {
9227        // TODO: Add an option to configure this
9228        private static final float MARQUEE_DELTA_MAX = 0.07f;
9229        private static final int MARQUEE_DELAY = 1200;
9230        private static final int MARQUEE_RESTART_DELAY = 1200;
9231        private static final int MARQUEE_RESOLUTION = 1000 / 30;
9232        private static final int MARQUEE_PIXELS_PER_SECOND = 30;
9233
9234        private static final byte MARQUEE_STOPPED = 0x0;
9235        private static final byte MARQUEE_STARTING = 0x1;
9236        private static final byte MARQUEE_RUNNING = 0x2;
9237
9238        private static final int MESSAGE_START = 0x1;
9239        private static final int MESSAGE_TICK = 0x2;
9240        private static final int MESSAGE_RESTART = 0x3;
9241
9242        private final WeakReference<TextView> mView;
9243
9244        private byte mStatus = MARQUEE_STOPPED;
9245        private final float mScrollUnit;
9246        private float mMaxScroll;
9247        float mMaxFadeScroll;
9248        private float mGhostStart;
9249        private float mGhostOffset;
9250        private float mFadeStop;
9251        private int mRepeatLimit;
9252
9253        float mScroll;
9254
9255        Marquee(TextView v) {
9256            final float density = v.getContext().getResources().getDisplayMetrics().density;
9257            mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION;
9258            mView = new WeakReference<TextView>(v);
9259        }
9260
9261        @Override
9262        public void handleMessage(Message msg) {
9263            switch (msg.what) {
9264                case MESSAGE_START:
9265                    mStatus = MARQUEE_RUNNING;
9266                    tick();
9267                    break;
9268                case MESSAGE_TICK:
9269                    tick();
9270                    break;
9271                case MESSAGE_RESTART:
9272                    if (mStatus == MARQUEE_RUNNING) {
9273                        if (mRepeatLimit >= 0) {
9274                            mRepeatLimit--;
9275                        }
9276                        start(mRepeatLimit);
9277                    }
9278                    break;
9279            }
9280        }
9281
9282        void tick() {
9283            if (mStatus != MARQUEE_RUNNING) {
9284                return;
9285            }
9286
9287            removeMessages(MESSAGE_TICK);
9288
9289            final TextView textView = mView.get();
9290            if (textView != null && (textView.isFocused() || textView.isSelected())) {
9291                mScroll += mScrollUnit;
9292                if (mScroll > mMaxScroll) {
9293                    mScroll = mMaxScroll;
9294                    sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY);
9295                } else {
9296                    sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION);
9297                }
9298                textView.invalidate();
9299            }
9300        }
9301
9302        void stop() {
9303            mStatus = MARQUEE_STOPPED;
9304            removeMessages(MESSAGE_START);
9305            removeMessages(MESSAGE_RESTART);
9306            removeMessages(MESSAGE_TICK);
9307            resetScroll();
9308        }
9309
9310        private void resetScroll() {
9311            mScroll = 0.0f;
9312            final TextView textView = mView.get();
9313            if (textView != null) textView.invalidate();
9314        }
9315
9316        void start(int repeatLimit) {
9317            if (repeatLimit == 0) {
9318                stop();
9319                return;
9320            }
9321            mRepeatLimit = repeatLimit;
9322            final TextView textView = mView.get();
9323            if (textView != null && textView.mLayout != null) {
9324                mStatus = MARQUEE_STARTING;
9325                mScroll = 0.0f;
9326                final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() -
9327                        textView.getCompoundPaddingRight();
9328                final float lineWidth = textView.mLayout.getLineWidth(0);
9329                final float gap = textWidth / 3.0f;
9330                mGhostStart = lineWidth - textWidth + gap;
9331                mMaxScroll = mGhostStart + textWidth;
9332                mGhostOffset = lineWidth + gap;
9333                mFadeStop = lineWidth + textWidth / 6.0f;
9334                mMaxFadeScroll = mGhostStart + lineWidth + lineWidth;
9335
9336                textView.invalidate();
9337                sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY);
9338            }
9339        }
9340
9341        float getGhostOffset() {
9342            return mGhostOffset;
9343        }
9344
9345        boolean shouldDrawLeftFade() {
9346            return mScroll <= mFadeStop;
9347        }
9348
9349        boolean shouldDrawGhost() {
9350            return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart;
9351        }
9352
9353        boolean isRunning() {
9354            return mStatus == MARQUEE_RUNNING;
9355        }
9356
9357        boolean isStopped() {
9358            return mStatus == MARQUEE_STOPPED;
9359        }
9360    }
9361
9362    /**
9363     * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related
9364     * pop-up should be displayed.
9365     */
9366    private class EasyEditSpanController {
9367
9368        private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs
9369
9370        private EasyEditPopupWindow mPopupWindow;
9371
9372        private EasyEditSpan mEasyEditSpan;
9373
9374        private Runnable mHidePopup;
9375
9376        private void hide() {
9377            if (mPopupWindow != null) {
9378                mPopupWindow.hide();
9379                TextView.this.removeCallbacks(mHidePopup);
9380            }
9381            removeSpans(mText);
9382            mEasyEditSpan = null;
9383        }
9384
9385        /**
9386         * Monitors the changes in the text.
9387         *
9388         * <p>{@link ChangeWatcher#onSpanAdded(Spannable, Object, int, int)} cannot be used,
9389         * as the notifications are not sent when a spannable (with spans) is inserted.
9390         */
9391        public void onTextChange(CharSequence buffer) {
9392            adjustSpans(mText);
9393
9394            if (getWindowVisibility() != View.VISIBLE) {
9395                // The window is not visible yet, ignore the text change.
9396                return;
9397            }
9398
9399            if (mLayout == null) {
9400                // The view has not been layout yet, ignore the text change
9401                return;
9402            }
9403
9404            InputMethodManager imm = InputMethodManager.peekInstance();
9405            if (!(TextView.this instanceof ExtractEditText)
9406                    && imm != null && imm.isFullscreenMode()) {
9407                // The input is in extract mode. We do not have to handle the easy edit in the
9408                // original TextView, as the ExtractEditText will do
9409                return;
9410            }
9411
9412            // Remove the current easy edit span, as the text changed, and remove the pop-up
9413            // (if any)
9414            if (mEasyEditSpan != null) {
9415                if (mText instanceof Spannable) {
9416                    ((Spannable) mText).removeSpan(mEasyEditSpan);
9417                }
9418                mEasyEditSpan = null;
9419            }
9420            if (mPopupWindow != null && mPopupWindow.isShowing()) {
9421                mPopupWindow.hide();
9422            }
9423
9424            // Display the new easy edit span (if any).
9425            if (buffer instanceof Spanned) {
9426                mEasyEditSpan = getSpan((Spanned) buffer);
9427                if (mEasyEditSpan != null) {
9428                    if (mPopupWindow == null) {
9429                        mPopupWindow = new EasyEditPopupWindow();
9430                        mHidePopup = new Runnable() {
9431                            @Override
9432                            public void run() {
9433                                hide();
9434                            }
9435                        };
9436                    }
9437                    mPopupWindow.show(mEasyEditSpan);
9438                    TextView.this.removeCallbacks(mHidePopup);
9439                    TextView.this.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS);
9440                }
9441            }
9442        }
9443
9444        /**
9445         * Adjusts the spans by removing all of them except the last one.
9446         */
9447        private void adjustSpans(CharSequence buffer) {
9448            // This method enforces that only one easy edit span is attached to the text.
9449            // A better way to enforce this would be to listen for onSpanAdded, but this method
9450            // cannot be used in this scenario as no notification is triggered when a text with
9451            // spans is inserted into a text.
9452            if (buffer instanceof Spannable) {
9453                Spannable spannable = (Spannable) buffer;
9454                EasyEditSpan[] spans = spannable.getSpans(0, spannable.length(),
9455                        EasyEditSpan.class);
9456                for (int i = 0; i < spans.length - 1; i++) {
9457                    spannable.removeSpan(spans[i]);
9458                }
9459            }
9460        }
9461
9462        /**
9463         * Removes all the {@link EasyEditSpan} currently attached.
9464         */
9465        private void removeSpans(CharSequence buffer) {
9466            if (buffer instanceof Spannable) {
9467                Spannable spannable = (Spannable) buffer;
9468                EasyEditSpan[] spans = spannable.getSpans(0, spannable.length(),
9469                        EasyEditSpan.class);
9470                for (int i = 0; i < spans.length; i++) {
9471                    spannable.removeSpan(spans[i]);
9472                }
9473            }
9474        }
9475
9476        private EasyEditSpan getSpan(Spanned spanned) {
9477            EasyEditSpan[] easyEditSpans = spanned.getSpans(0, spanned.length(),
9478                    EasyEditSpan.class);
9479            if (easyEditSpans.length == 0) {
9480                return null;
9481            } else {
9482                return easyEditSpans[0];
9483            }
9484        }
9485    }
9486
9487    /**
9488     * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled
9489     * by {@link EasyEditSpanController}.
9490     */
9491    private class EasyEditPopupWindow extends PinnedPopupWindow
9492            implements OnClickListener {
9493        private static final int POPUP_TEXT_LAYOUT =
9494                com.android.internal.R.layout.text_edit_action_popup_text;
9495        private TextView mDeleteTextView;
9496        private EasyEditSpan mEasyEditSpan;
9497
9498        @Override
9499        protected void createPopupWindow() {
9500            mPopupWindow = new PopupWindow(TextView.this.mContext, null,
9501                    com.android.internal.R.attr.textSelectHandleWindowStyle);
9502            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
9503            mPopupWindow.setClippingEnabled(true);
9504        }
9505
9506        @Override
9507        protected void initContentView() {
9508            LinearLayout linearLayout = new LinearLayout(TextView.this.getContext());
9509            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
9510            mContentView = linearLayout;
9511            mContentView.setBackgroundResource(
9512                    com.android.internal.R.drawable.text_edit_side_paste_window);
9513
9514            LayoutInflater inflater = (LayoutInflater)TextView.this.mContext.
9515                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
9516
9517            LayoutParams wrapContent = new LayoutParams(
9518                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
9519
9520            mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
9521            mDeleteTextView.setLayoutParams(wrapContent);
9522            mDeleteTextView.setText(com.android.internal.R.string.delete);
9523            mDeleteTextView.setOnClickListener(this);
9524            mContentView.addView(mDeleteTextView);
9525        }
9526
9527        public void show(EasyEditSpan easyEditSpan) {
9528            mEasyEditSpan = easyEditSpan;
9529            super.show();
9530        }
9531
9532        @Override
9533        public void onClick(View view) {
9534            if (view == mDeleteTextView) {
9535                Editable editable = (Editable) mText;
9536                int start = editable.getSpanStart(mEasyEditSpan);
9537                int end = editable.getSpanEnd(mEasyEditSpan);
9538                if (start >= 0 && end >= 0) {
9539                    deleteText_internal(start, end);
9540                }
9541            }
9542        }
9543
9544        @Override
9545        protected int getTextOffset() {
9546            // Place the pop-up at the end of the span
9547            Editable editable = (Editable) mText;
9548            return editable.getSpanEnd(mEasyEditSpan);
9549        }
9550
9551        @Override
9552        protected int getVerticalLocalPosition(int line) {
9553            return mLayout.getLineBottom(line);
9554        }
9555
9556        @Override
9557        protected int clipVertically(int positionY) {
9558            // As we display the pop-up below the span, no vertical clipping is required.
9559            return positionY;
9560        }
9561    }
9562
9563    private class ChangeWatcher implements TextWatcher, SpanWatcher {
9564
9565        private CharSequence mBeforeText;
9566
9567        private EasyEditSpanController mEasyEditSpanController;
9568
9569        private ChangeWatcher() {
9570            mEasyEditSpanController = new EasyEditSpanController();
9571        }
9572
9573        public void beforeTextChanged(CharSequence buffer, int start,
9574                                      int before, int after) {
9575            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start
9576                    + " before=" + before + " after=" + after + ": " + buffer);
9577
9578            if (AccessibilityManager.getInstance(mContext).isEnabled()
9579                    && !isPasswordInputType(getInputType())
9580                    && !hasPasswordTransformationMethod()) {
9581                mBeforeText = buffer.toString();
9582            }
9583
9584            TextView.this.sendBeforeTextChanged(buffer, start, before, after);
9585        }
9586
9587        public void onTextChanged(CharSequence buffer, int start,
9588                                  int before, int after) {
9589            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start
9590                    + " before=" + before + " after=" + after + ": " + buffer);
9591            TextView.this.handleTextChanged(buffer, start, before, after);
9592
9593            mEasyEditSpanController.onTextChange(buffer);
9594
9595            if (AccessibilityManager.getInstance(mContext).isEnabled() &&
9596                    (isFocused() || isSelected() && isShown())) {
9597                sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after);
9598                mBeforeText = null;
9599            }
9600        }
9601
9602        public void afterTextChanged(Editable buffer) {
9603            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer);
9604            TextView.this.sendAfterTextChanged(buffer);
9605
9606            if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) {
9607                MetaKeyKeyListener.stopSelecting(TextView.this, buffer);
9608            }
9609        }
9610
9611        public void onSpanChanged(Spannable buf,
9612                                  Object what, int s, int e, int st, int en) {
9613            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e
9614                    + " st=" + st + " en=" + en + " what=" + what + ": " + buf);
9615            TextView.this.spanChange(buf, what, s, st, e, en);
9616        }
9617
9618        public void onSpanAdded(Spannable buf, Object what, int s, int e) {
9619            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e
9620                    + " what=" + what + ": " + buf);
9621            TextView.this.spanChange(buf, what, -1, s, -1, e);
9622        }
9623
9624        public void onSpanRemoved(Spannable buf, Object what, int s, int e) {
9625            if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e
9626                    + " what=" + what + ": " + buf);
9627            TextView.this.spanChange(buf, what, s, -1, e, -1);
9628        }
9629
9630        private void hideControllers() {
9631            mEasyEditSpanController.hide();
9632        }
9633    }
9634
9635    private static class Blink extends Handler implements Runnable {
9636        private final WeakReference<TextView> mView;
9637        private boolean mCancelled;
9638
9639        public Blink(TextView v) {
9640            mView = new WeakReference<TextView>(v);
9641        }
9642
9643        public void run() {
9644            if (mCancelled) {
9645                return;
9646            }
9647
9648            removeCallbacks(Blink.this);
9649
9650            TextView tv = mView.get();
9651
9652            if (tv != null && tv.shouldBlink()) {
9653                if (tv.mLayout != null) {
9654                    tv.invalidateCursorPath();
9655                }
9656
9657                postAtTime(this, SystemClock.uptimeMillis() + BLINK);
9658            }
9659        }
9660
9661        void cancel() {
9662            if (!mCancelled) {
9663                removeCallbacks(Blink.this);
9664                mCancelled = true;
9665            }
9666        }
9667
9668        void uncancel() {
9669            mCancelled = false;
9670        }
9671    }
9672
9673    private static class DragLocalState {
9674        public TextView sourceTextView;
9675        public int start, end;
9676
9677        public DragLocalState(TextView sourceTextView, int start, int end) {
9678            this.sourceTextView = sourceTextView;
9679            this.start = start;
9680            this.end = end;
9681        }
9682    }
9683
9684    private class PositionListener implements ViewTreeObserver.OnPreDrawListener {
9685        // 3 handles
9686        // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others)
9687        private final int MAXIMUM_NUMBER_OF_LISTENERS = 6;
9688        private TextViewPositionListener[] mPositionListeners =
9689                new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS];
9690        private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS];
9691        private boolean mPositionHasChanged = true;
9692        // Absolute position of the TextView with respect to its parent window
9693        private int mPositionX, mPositionY;
9694        private int mNumberOfListeners;
9695        private boolean mScrollHasChanged;
9696        final int[] mTempCoords = new int[2];
9697
9698        public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) {
9699            if (mNumberOfListeners == 0) {
9700                updatePosition();
9701                ViewTreeObserver vto = TextView.this.getViewTreeObserver();
9702                vto.addOnPreDrawListener(this);
9703            }
9704
9705            int emptySlotIndex = -1;
9706            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
9707                TextViewPositionListener listener = mPositionListeners[i];
9708                if (listener == positionListener) {
9709                    return;
9710                } else if (emptySlotIndex < 0 && listener == null) {
9711                    emptySlotIndex = i;
9712                }
9713            }
9714
9715            mPositionListeners[emptySlotIndex] = positionListener;
9716            mCanMove[emptySlotIndex] = canMove;
9717            mNumberOfListeners++;
9718        }
9719
9720        public void removeSubscriber(TextViewPositionListener positionListener) {
9721            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
9722                if (mPositionListeners[i] == positionListener) {
9723                    mPositionListeners[i] = null;
9724                    mNumberOfListeners--;
9725                    break;
9726                }
9727            }
9728
9729            if (mNumberOfListeners == 0) {
9730                ViewTreeObserver vto = TextView.this.getViewTreeObserver();
9731                vto.removeOnPreDrawListener(this);
9732            }
9733        }
9734
9735        public int getPositionX() {
9736            return mPositionX;
9737        }
9738
9739        public int getPositionY() {
9740            return mPositionY;
9741        }
9742
9743        @Override
9744        public boolean onPreDraw() {
9745            updatePosition();
9746
9747            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
9748                if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) {
9749                    TextViewPositionListener positionListener = mPositionListeners[i];
9750                    if (positionListener != null) {
9751                        positionListener.updatePosition(mPositionX, mPositionY,
9752                                mPositionHasChanged, mScrollHasChanged);
9753                    }
9754                }
9755            }
9756
9757            mScrollHasChanged = false;
9758            return true;
9759        }
9760
9761        private void updatePosition() {
9762            TextView.this.getLocationInWindow(mTempCoords);
9763
9764            mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY;
9765
9766            mPositionX = mTempCoords[0];
9767            mPositionY = mTempCoords[1];
9768        }
9769
9770        public void onScrollChanged() {
9771            mScrollHasChanged = true;
9772        }
9773    }
9774
9775    private abstract class PinnedPopupWindow implements TextViewPositionListener {
9776        protected PopupWindow mPopupWindow;
9777        protected ViewGroup mContentView;
9778        int mPositionX, mPositionY;
9779
9780        protected abstract void createPopupWindow();
9781        protected abstract void initContentView();
9782        protected abstract int getTextOffset();
9783        protected abstract int getVerticalLocalPosition(int line);
9784        protected abstract int clipVertically(int positionY);
9785
9786        public PinnedPopupWindow() {
9787            createPopupWindow();
9788
9789            mPopupWindow.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
9790            mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
9791            mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
9792
9793            initContentView();
9794
9795            LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
9796                    ViewGroup.LayoutParams.WRAP_CONTENT);
9797            mContentView.setLayoutParams(wrapContent);
9798
9799            mPopupWindow.setContentView(mContentView);
9800        }
9801
9802        public void show() {
9803            TextView.this.getPositionListener().addSubscriber(this, false /* offset is fixed */);
9804
9805            computeLocalPosition();
9806
9807            final PositionListener positionListener = TextView.this.getPositionListener();
9808            updatePosition(positionListener.getPositionX(), positionListener.getPositionY());
9809        }
9810
9811        protected void measureContent() {
9812            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
9813            mContentView.measure(
9814                    View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels,
9815                            View.MeasureSpec.AT_MOST),
9816                    View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels,
9817                            View.MeasureSpec.AT_MOST));
9818        }
9819
9820        /* The popup window will be horizontally centered on the getTextOffset() and vertically
9821         * positioned according to viewportToContentHorizontalOffset.
9822         *
9823         * This method assumes that mContentView has properly been measured from its content. */
9824        private void computeLocalPosition() {
9825            measureContent();
9826            final int width = mContentView.getMeasuredWidth();
9827            final int offset = getTextOffset();
9828            mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - width / 2.0f);
9829            mPositionX += viewportToContentHorizontalOffset();
9830
9831            final int line = mLayout.getLineForOffset(offset);
9832            mPositionY = getVerticalLocalPosition(line);
9833            mPositionY += viewportToContentVerticalOffset();
9834        }
9835
9836        private void updatePosition(int parentPositionX, int parentPositionY) {
9837            int positionX = parentPositionX + mPositionX;
9838            int positionY = parentPositionY + mPositionY;
9839
9840            positionY = clipVertically(positionY);
9841
9842            // Horizontal clipping
9843            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
9844            final int width = mContentView.getMeasuredWidth();
9845            positionX = Math.min(displayMetrics.widthPixels - width, positionX);
9846            positionX = Math.max(0, positionX);
9847
9848            if (isShowing()) {
9849                mPopupWindow.update(positionX, positionY, -1, -1);
9850            } else {
9851                mPopupWindow.showAtLocation(TextView.this, Gravity.NO_GRAVITY,
9852                        positionX, positionY);
9853            }
9854        }
9855
9856        public void hide() {
9857            mPopupWindow.dismiss();
9858            TextView.this.getPositionListener().removeSubscriber(this);
9859        }
9860
9861        @Override
9862        public void updatePosition(int parentPositionX, int parentPositionY,
9863                boolean parentPositionChanged, boolean parentScrolled) {
9864            // Either parentPositionChanged or parentScrolled is true, check if still visible
9865            if (isShowing() && isOffsetVisible(getTextOffset())) {
9866                if (parentScrolled) computeLocalPosition();
9867                updatePosition(parentPositionX, parentPositionY);
9868            } else {
9869                hide();
9870            }
9871        }
9872
9873        public boolean isShowing() {
9874            return mPopupWindow.isShowing();
9875        }
9876    }
9877
9878    private class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener {
9879        private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE;
9880        private static final int ADD_TO_DICTIONARY = -1;
9881        private static final int DELETE_TEXT = -2;
9882        private SuggestionInfo[] mSuggestionInfos;
9883        private int mNumberOfSuggestions;
9884        private boolean mCursorWasVisibleBeforeSuggestions;
9885        private boolean mIsShowingUp = false;
9886        private SuggestionAdapter mSuggestionsAdapter;
9887        private final Comparator<SuggestionSpan> mSuggestionSpanComparator;
9888        private final HashMap<SuggestionSpan, Integer> mSpansLengths;
9889
9890        private class CustomPopupWindow extends PopupWindow {
9891            public CustomPopupWindow(Context context, int defStyle) {
9892                super(context, null, defStyle);
9893            }
9894
9895            @Override
9896            public void dismiss() {
9897                super.dismiss();
9898
9899                TextView.this.getPositionListener().removeSubscriber(SuggestionsPopupWindow.this);
9900
9901                // Safe cast since show() checks that mText is an Editable
9902                ((Spannable) mText).removeSpan(getEditor().mSuggestionRangeSpan);
9903
9904                setCursorVisible(mCursorWasVisibleBeforeSuggestions);
9905                if (hasInsertionController()) {
9906                    getInsertionController().show();
9907                }
9908            }
9909        }
9910
9911        public SuggestionsPopupWindow() {
9912            mCursorWasVisibleBeforeSuggestions = getEditor().mCursorVisible;
9913            mSuggestionSpanComparator = new SuggestionSpanComparator();
9914            mSpansLengths = new HashMap<SuggestionSpan, Integer>();
9915        }
9916
9917        @Override
9918        protected void createPopupWindow() {
9919            mPopupWindow = new CustomPopupWindow(TextView.this.mContext,
9920                com.android.internal.R.attr.textSuggestionsWindowStyle);
9921            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
9922            mPopupWindow.setFocusable(true);
9923            mPopupWindow.setClippingEnabled(false);
9924        }
9925
9926        @Override
9927        protected void initContentView() {
9928            ListView listView = new ListView(TextView.this.getContext());
9929            mSuggestionsAdapter = new SuggestionAdapter();
9930            listView.setAdapter(mSuggestionsAdapter);
9931            listView.setOnItemClickListener(this);
9932            mContentView = listView;
9933
9934            // Inflate the suggestion items once and for all. + 2 for add to dictionary and delete
9935            mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS + 2];
9936            for (int i = 0; i < mSuggestionInfos.length; i++) {
9937                mSuggestionInfos[i] = new SuggestionInfo();
9938            }
9939        }
9940
9941        public boolean isShowingUp() {
9942            return mIsShowingUp;
9943        }
9944
9945        public void onParentLostFocus() {
9946            mIsShowingUp = false;
9947        }
9948
9949        private class SuggestionInfo {
9950            int suggestionStart, suggestionEnd; // range of actual suggestion within text
9951            SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents
9952            int suggestionIndex; // the index of this suggestion inside suggestionSpan
9953            SpannableStringBuilder text = new SpannableStringBuilder();
9954            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mContext,
9955                    android.R.style.TextAppearance_SuggestionHighlight);
9956        }
9957
9958        private class SuggestionAdapter extends BaseAdapter {
9959            private LayoutInflater mInflater = (LayoutInflater) TextView.this.mContext.
9960                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
9961
9962            @Override
9963            public int getCount() {
9964                return mNumberOfSuggestions;
9965            }
9966
9967            @Override
9968            public Object getItem(int position) {
9969                return mSuggestionInfos[position];
9970            }
9971
9972            @Override
9973            public long getItemId(int position) {
9974                return position;
9975            }
9976
9977            @Override
9978            public View getView(int position, View convertView, ViewGroup parent) {
9979                TextView textView = (TextView) convertView;
9980
9981                if (textView == null) {
9982                    textView = (TextView) mInflater.inflate(mTextEditSuggestionItemLayout, parent,
9983                            false);
9984                }
9985
9986                final SuggestionInfo suggestionInfo = mSuggestionInfos[position];
9987                textView.setText(suggestionInfo.text);
9988
9989                if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) {
9990                    textView.setCompoundDrawablesWithIntrinsicBounds(
9991                            com.android.internal.R.drawable.ic_suggestions_add, 0, 0, 0);
9992                } else if (suggestionInfo.suggestionIndex == DELETE_TEXT) {
9993                    textView.setCompoundDrawablesWithIntrinsicBounds(
9994                            com.android.internal.R.drawable.ic_suggestions_delete, 0, 0, 0);
9995                } else {
9996                    textView.setCompoundDrawables(null, null, null, null);
9997                }
9998
9999                return textView;
10000            }
10001        }
10002
10003        private class SuggestionSpanComparator implements Comparator<SuggestionSpan> {
10004            public int compare(SuggestionSpan span1, SuggestionSpan span2) {
10005                final int flag1 = span1.getFlags();
10006                final int flag2 = span2.getFlags();
10007                if (flag1 != flag2) {
10008                    // The order here should match what is used in updateDrawState
10009                    final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
10010                    final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
10011                    final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0;
10012                    final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0;
10013                    if (easy1 && !misspelled1) return -1;
10014                    if (easy2 && !misspelled2) return 1;
10015                    if (misspelled1) return -1;
10016                    if (misspelled2) return 1;
10017                }
10018
10019                return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue();
10020            }
10021        }
10022
10023        /**
10024         * Returns the suggestion spans that cover the current cursor position. The suggestion
10025         * spans are sorted according to the length of text that they are attached to.
10026         */
10027        private SuggestionSpan[] getSuggestionSpans() {
10028            int pos = TextView.this.getSelectionStart();
10029            Spannable spannable = (Spannable) TextView.this.mText;
10030            SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class);
10031
10032            mSpansLengths.clear();
10033            for (SuggestionSpan suggestionSpan : suggestionSpans) {
10034                int start = spannable.getSpanStart(suggestionSpan);
10035                int end = spannable.getSpanEnd(suggestionSpan);
10036                mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start));
10037            }
10038
10039            // The suggestions are sorted according to their types (easy correction first, then
10040            // misspelled) and to the length of the text that they cover (shorter first).
10041            Arrays.sort(suggestionSpans, mSuggestionSpanComparator);
10042            return suggestionSpans;
10043        }
10044
10045        @Override
10046        public void show() {
10047            if (!(mText instanceof Editable)) return;
10048
10049            if (updateSuggestions()) {
10050                mCursorWasVisibleBeforeSuggestions = getEditor().mCursorVisible;
10051                setCursorVisible(false);
10052                mIsShowingUp = true;
10053                super.show();
10054            }
10055        }
10056
10057        @Override
10058        protected void measureContent() {
10059            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
10060            final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec(
10061                    displayMetrics.widthPixels, View.MeasureSpec.AT_MOST);
10062            final int verticalMeasure = View.MeasureSpec.makeMeasureSpec(
10063                    displayMetrics.heightPixels, View.MeasureSpec.AT_MOST);
10064
10065            int width = 0;
10066            View view = null;
10067            for (int i = 0; i < mNumberOfSuggestions; i++) {
10068                view = mSuggestionsAdapter.getView(i, view, mContentView);
10069                view.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
10070                view.measure(horizontalMeasure, verticalMeasure);
10071                width = Math.max(width, view.getMeasuredWidth());
10072            }
10073
10074            // Enforce the width based on actual text widths
10075            mContentView.measure(
10076                    View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
10077                    verticalMeasure);
10078
10079            Drawable popupBackground = mPopupWindow.getBackground();
10080            if (popupBackground != null) {
10081                if (mTempRect == null) mTempRect = new Rect();
10082                popupBackground.getPadding(mTempRect);
10083                width += mTempRect.left + mTempRect.right;
10084            }
10085            mPopupWindow.setWidth(width);
10086        }
10087
10088        @Override
10089        protected int getTextOffset() {
10090            return getSelectionStart();
10091        }
10092
10093        @Override
10094        protected int getVerticalLocalPosition(int line) {
10095            return mLayout.getLineBottom(line);
10096        }
10097
10098        @Override
10099        protected int clipVertically(int positionY) {
10100            final int height = mContentView.getMeasuredHeight();
10101            final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
10102            return Math.min(positionY, displayMetrics.heightPixels - height);
10103        }
10104
10105        @Override
10106        public void hide() {
10107            super.hide();
10108        }
10109
10110        private boolean updateSuggestions() {
10111            Spannable spannable = (Spannable) TextView.this.mText;
10112            SuggestionSpan[] suggestionSpans = getSuggestionSpans();
10113
10114            final int nbSpans = suggestionSpans.length;
10115            // Suggestions are shown after a delay: the underlying spans may have been removed
10116            if (nbSpans == 0) return false;
10117
10118            mNumberOfSuggestions = 0;
10119            int spanUnionStart = mText.length();
10120            int spanUnionEnd = 0;
10121
10122            SuggestionSpan misspelledSpan = null;
10123            int underlineColor = 0;
10124
10125            for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) {
10126                SuggestionSpan suggestionSpan = suggestionSpans[spanIndex];
10127                final int spanStart = spannable.getSpanStart(suggestionSpan);
10128                final int spanEnd = spannable.getSpanEnd(suggestionSpan);
10129                spanUnionStart = Math.min(spanStart, spanUnionStart);
10130                spanUnionEnd = Math.max(spanEnd, spanUnionEnd);
10131
10132                if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) {
10133                    misspelledSpan = suggestionSpan;
10134                }
10135
10136                // The first span dictates the background color of the highlighted text
10137                if (spanIndex == 0) underlineColor = suggestionSpan.getUnderlineColor();
10138
10139                String[] suggestions = suggestionSpan.getSuggestions();
10140                int nbSuggestions = suggestions.length;
10141                for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) {
10142                    String suggestion = suggestions[suggestionIndex];
10143
10144                    boolean suggestionIsDuplicate = false;
10145                    for (int i = 0; i < mNumberOfSuggestions; i++) {
10146                        if (mSuggestionInfos[i].text.toString().equals(suggestion)) {
10147                            SuggestionSpan otherSuggestionSpan = mSuggestionInfos[i].suggestionSpan;
10148                            final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan);
10149                            final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan);
10150                            if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) {
10151                                suggestionIsDuplicate = true;
10152                                break;
10153                            }
10154                        }
10155                    }
10156
10157                    if (!suggestionIsDuplicate) {
10158                        SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
10159                        suggestionInfo.suggestionSpan = suggestionSpan;
10160                        suggestionInfo.suggestionIndex = suggestionIndex;
10161                        suggestionInfo.text.replace(0, suggestionInfo.text.length(), suggestion);
10162
10163                        mNumberOfSuggestions++;
10164
10165                        if (mNumberOfSuggestions == MAX_NUMBER_SUGGESTIONS) {
10166                            // Also end outer for loop
10167                            spanIndex = nbSpans;
10168                            break;
10169                        }
10170                    }
10171                }
10172            }
10173
10174            for (int i = 0; i < mNumberOfSuggestions; i++) {
10175                highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd);
10176            }
10177
10178            // Add "Add to dictionary" item if there is a span with the misspelled flag
10179            if (misspelledSpan != null) {
10180                final int misspelledStart = spannable.getSpanStart(misspelledSpan);
10181                final int misspelledEnd = spannable.getSpanEnd(misspelledSpan);
10182                if (misspelledStart >= 0 && misspelledEnd > misspelledStart) {
10183                    SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
10184                    suggestionInfo.suggestionSpan = misspelledSpan;
10185                    suggestionInfo.suggestionIndex = ADD_TO_DICTIONARY;
10186                    suggestionInfo.text.replace(0, suggestionInfo.text.length(),
10187                            getContext().getString(com.android.internal.R.string.addToDictionary));
10188                    suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
10189                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
10190
10191                    mNumberOfSuggestions++;
10192                }
10193            }
10194
10195            // Delete item
10196            SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
10197            suggestionInfo.suggestionSpan = null;
10198            suggestionInfo.suggestionIndex = DELETE_TEXT;
10199            suggestionInfo.text.replace(0, suggestionInfo.text.length(),
10200                    getContext().getString(com.android.internal.R.string.deleteText));
10201            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
10202                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
10203            mNumberOfSuggestions++;
10204
10205            if (getEditor().mSuggestionRangeSpan == null) getEditor().mSuggestionRangeSpan = new SuggestionRangeSpan();
10206            if (underlineColor == 0) {
10207                // Fallback on the default highlight color when the first span does not provide one
10208                getEditor().mSuggestionRangeSpan.setBackgroundColor(mHighlightColor);
10209            } else {
10210                final float BACKGROUND_TRANSPARENCY = 0.4f;
10211                final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY);
10212                getEditor().mSuggestionRangeSpan.setBackgroundColor(
10213                        (underlineColor & 0x00FFFFFF) + (newAlpha << 24));
10214            }
10215            spannable.setSpan(getEditor().mSuggestionRangeSpan, spanUnionStart, spanUnionEnd,
10216                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
10217
10218            mSuggestionsAdapter.notifyDataSetChanged();
10219            return true;
10220        }
10221
10222        private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart,
10223                int unionEnd) {
10224            final Spannable text = (Spannable) mText;
10225            final int spanStart = text.getSpanStart(suggestionInfo.suggestionSpan);
10226            final int spanEnd = text.getSpanEnd(suggestionInfo.suggestionSpan);
10227
10228            // Adjust the start/end of the suggestion span
10229            suggestionInfo.suggestionStart = spanStart - unionStart;
10230            suggestionInfo.suggestionEnd = suggestionInfo.suggestionStart
10231                    + suggestionInfo.text.length();
10232
10233            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0,
10234                    suggestionInfo.text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
10235
10236            // Add the text before and after the span.
10237            final String textAsString = text.toString();
10238            suggestionInfo.text.insert(0, textAsString.substring(unionStart, spanStart));
10239            suggestionInfo.text.append(textAsString.substring(spanEnd, unionEnd));
10240        }
10241
10242        @Override
10243        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
10244            Editable editable = (Editable) mText;
10245            SuggestionInfo suggestionInfo = mSuggestionInfos[position];
10246
10247            if (suggestionInfo.suggestionIndex == DELETE_TEXT) {
10248                final int spanUnionStart = editable.getSpanStart(getEditor().mSuggestionRangeSpan);
10249                int spanUnionEnd = editable.getSpanEnd(getEditor().mSuggestionRangeSpan);
10250                if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) {
10251                    // Do not leave two adjacent spaces after deletion, or one at beginning of text
10252                    if (spanUnionEnd < editable.length() &&
10253                            Character.isSpaceChar(editable.charAt(spanUnionEnd)) &&
10254                            (spanUnionStart == 0 ||
10255                            Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) {
10256                        spanUnionEnd = spanUnionEnd + 1;
10257                    }
10258                    deleteText_internal(spanUnionStart, spanUnionEnd);
10259                }
10260                hide();
10261                return;
10262            }
10263
10264            final int spanStart = editable.getSpanStart(suggestionInfo.suggestionSpan);
10265            final int spanEnd = editable.getSpanEnd(suggestionInfo.suggestionSpan);
10266            if (spanStart < 0 || spanEnd <= spanStart) {
10267                // Span has been removed
10268                hide();
10269                return;
10270            }
10271            final String originalText = mText.toString().substring(spanStart, spanEnd);
10272
10273            if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) {
10274                Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT);
10275                intent.putExtra("word", originalText);
10276                intent.putExtra("locale", getTextServicesLocale().toString());
10277                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
10278                getContext().startActivity(intent);
10279                // There is no way to know if the word was indeed added. Re-check.
10280                // TODO The ExtractEditText should remove the span in the original text instead
10281                editable.removeSpan(suggestionInfo.suggestionSpan);
10282                updateSpellCheckSpans(spanStart, spanEnd, false);
10283            } else {
10284                // SuggestionSpans are removed by replace: save them before
10285                SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd,
10286                        SuggestionSpan.class);
10287                final int length = suggestionSpans.length;
10288                int[] suggestionSpansStarts = new int[length];
10289                int[] suggestionSpansEnds = new int[length];
10290                int[] suggestionSpansFlags = new int[length];
10291                for (int i = 0; i < length; i++) {
10292                    final SuggestionSpan suggestionSpan = suggestionSpans[i];
10293                    suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan);
10294                    suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan);
10295                    suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan);
10296
10297                    // Remove potential misspelled flags
10298                    int suggestionSpanFlags = suggestionSpan.getFlags();
10299                    if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) > 0) {
10300                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED;
10301                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
10302                        suggestionSpan.setFlags(suggestionSpanFlags);
10303                    }
10304                }
10305
10306                final int suggestionStart = suggestionInfo.suggestionStart;
10307                final int suggestionEnd = suggestionInfo.suggestionEnd;
10308                final String suggestion = suggestionInfo.text.subSequence(
10309                        suggestionStart, suggestionEnd).toString();
10310                replaceText_internal(spanStart, spanEnd, suggestion);
10311
10312                // Notify source IME of the suggestion pick. Do this before swaping texts.
10313                if (!TextUtils.isEmpty(
10314                        suggestionInfo.suggestionSpan.getNotificationTargetClassName())) {
10315                    InputMethodManager imm = InputMethodManager.peekInstance();
10316                    if (imm != null) {
10317                        imm.notifySuggestionPicked(suggestionInfo.suggestionSpan, originalText,
10318                                suggestionInfo.suggestionIndex);
10319                    }
10320                }
10321
10322                // Swap text content between actual text and Suggestion span
10323                String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions();
10324                suggestions[suggestionInfo.suggestionIndex] = originalText;
10325
10326                // Restore previous SuggestionSpans
10327                final int lengthDifference = suggestion.length() - (spanEnd - spanStart);
10328                for (int i = 0; i < length; i++) {
10329                    // Only spans that include the modified region make sense after replacement
10330                    // Spans partially included in the replaced region are removed, there is no
10331                    // way to assign them a valid range after replacement
10332                    if (suggestionSpansStarts[i] <= spanStart &&
10333                            suggestionSpansEnds[i] >= spanEnd) {
10334                        setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i],
10335                                suggestionSpansEnds[i] + lengthDifference, suggestionSpansFlags[i]);
10336                    }
10337                }
10338
10339                // Move cursor at the end of the replaced word
10340                final int newCursorPosition = spanEnd + lengthDifference;
10341                setCursorPosition_internal(newCursorPosition, newCursorPosition);
10342            }
10343
10344            hide();
10345        }
10346    }
10347
10348    /**
10349     * An ActionMode Callback class that is used to provide actions while in text selection mode.
10350     *
10351     * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending
10352     * on which of these this TextView supports.
10353     */
10354    private class SelectionActionModeCallback implements ActionMode.Callback {
10355
10356        @Override
10357        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
10358            TypedArray styledAttributes = mContext.obtainStyledAttributes(
10359                    com.android.internal.R.styleable.SelectionModeDrawables);
10360
10361            boolean allowText = getContext().getResources().getBoolean(
10362                    com.android.internal.R.bool.config_allowActionMenuItemTextWithIcon);
10363
10364            mode.setTitle(allowText ?
10365                    mContext.getString(com.android.internal.R.string.textSelectionCABTitle) : null);
10366            mode.setSubtitle(null);
10367
10368            int selectAllIconId = 0; // No icon by default
10369            if (!allowText) {
10370                // Provide an icon, text will not be displayed on smaller screens.
10371                selectAllIconId = styledAttributes.getResourceId(
10372                        R.styleable.SelectionModeDrawables_actionModeSelectAllDrawable, 0);
10373            }
10374
10375            menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll).
10376                    setIcon(selectAllIconId).
10377                    setAlphabeticShortcut('a').
10378                    setShowAsAction(
10379                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
10380
10381            if (canCut()) {
10382                menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut).
10383                    setIcon(styledAttributes.getResourceId(
10384                            R.styleable.SelectionModeDrawables_actionModeCutDrawable, 0)).
10385                    setAlphabeticShortcut('x').
10386                    setShowAsAction(
10387                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
10388            }
10389
10390            if (canCopy()) {
10391                menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy).
10392                    setIcon(styledAttributes.getResourceId(
10393                            R.styleable.SelectionModeDrawables_actionModeCopyDrawable, 0)).
10394                    setAlphabeticShortcut('c').
10395                    setShowAsAction(
10396                            MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
10397            }
10398
10399            if (canPaste()) {
10400                menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste).
10401                        setIcon(styledAttributes.getResourceId(
10402                                R.styleable.SelectionModeDrawables_actionModePasteDrawable, 0)).
10403                        setAlphabeticShortcut('v').
10404                        setShowAsAction(
10405                                MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
10406            }
10407
10408            styledAttributes.recycle();
10409
10410            if (getEditor().mCustomSelectionActionModeCallback != null) {
10411                if (!getEditor().mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) {
10412                    // The custom mode can choose to cancel the action mode
10413                    return false;
10414                }
10415            }
10416
10417            if (menu.hasVisibleItems() || mode.getCustomView() != null) {
10418                getSelectionController().show();
10419                return true;
10420            } else {
10421                return false;
10422            }
10423        }
10424
10425        @Override
10426        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
10427            if (getEditor().mCustomSelectionActionModeCallback != null) {
10428                return getEditor().mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu);
10429            }
10430            return true;
10431        }
10432
10433        @Override
10434        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
10435            if (getEditor().mCustomSelectionActionModeCallback != null &&
10436                 getEditor().mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) {
10437                return true;
10438            }
10439            return onTextContextMenuItem(item.getItemId());
10440        }
10441
10442        @Override
10443        public void onDestroyActionMode(ActionMode mode) {
10444            if (getEditor().mCustomSelectionActionModeCallback != null) {
10445                getEditor().mCustomSelectionActionModeCallback.onDestroyActionMode(mode);
10446            }
10447            Selection.setSelection((Spannable) mText, getSelectionEnd());
10448
10449            if (getEditor().mSelectionModifierCursorController != null) {
10450                getEditor().mSelectionModifierCursorController.hide();
10451            }
10452
10453            getEditor().mSelectionActionMode = null;
10454        }
10455    }
10456
10457    private class ActionPopupWindow extends PinnedPopupWindow implements OnClickListener {
10458        private static final int POPUP_TEXT_LAYOUT =
10459                com.android.internal.R.layout.text_edit_action_popup_text;
10460        private TextView mPasteTextView;
10461        private TextView mReplaceTextView;
10462
10463        @Override
10464        protected void createPopupWindow() {
10465            mPopupWindow = new PopupWindow(TextView.this.mContext, null,
10466                    com.android.internal.R.attr.textSelectHandleWindowStyle);
10467            mPopupWindow.setClippingEnabled(true);
10468        }
10469
10470        @Override
10471        protected void initContentView() {
10472            LinearLayout linearLayout = new LinearLayout(TextView.this.getContext());
10473            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
10474            mContentView = linearLayout;
10475            mContentView.setBackgroundResource(
10476                    com.android.internal.R.drawable.text_edit_paste_window);
10477
10478            LayoutInflater inflater = (LayoutInflater)TextView.this.mContext.
10479                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
10480
10481            LayoutParams wrapContent = new LayoutParams(
10482                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
10483
10484            mPasteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
10485            mPasteTextView.setLayoutParams(wrapContent);
10486            mContentView.addView(mPasteTextView);
10487            mPasteTextView.setText(com.android.internal.R.string.paste);
10488            mPasteTextView.setOnClickListener(this);
10489
10490            mReplaceTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
10491            mReplaceTextView.setLayoutParams(wrapContent);
10492            mContentView.addView(mReplaceTextView);
10493            mReplaceTextView.setText(com.android.internal.R.string.replace);
10494            mReplaceTextView.setOnClickListener(this);
10495        }
10496
10497        @Override
10498        public void show() {
10499            boolean canPaste = canPaste();
10500            boolean canSuggest = isSuggestionsEnabled() && isCursorInsideSuggestionSpan();
10501            mPasteTextView.setVisibility(canPaste ? View.VISIBLE : View.GONE);
10502            mReplaceTextView.setVisibility(canSuggest ? View.VISIBLE : View.GONE);
10503
10504            if (!canPaste && !canSuggest) return;
10505
10506            super.show();
10507        }
10508
10509        @Override
10510        public void onClick(View view) {
10511            if (view == mPasteTextView && canPaste()) {
10512                onTextContextMenuItem(ID_PASTE);
10513                hide();
10514            } else if (view == mReplaceTextView) {
10515                final int middle = (getSelectionStart() + getSelectionEnd()) / 2;
10516                stopSelectionActionMode();
10517                Selection.setSelection((Spannable) mText, middle);
10518                showSuggestions();
10519            }
10520        }
10521
10522        @Override
10523        protected int getTextOffset() {
10524            return (getSelectionStart() + getSelectionEnd()) / 2;
10525        }
10526
10527        @Override
10528        protected int getVerticalLocalPosition(int line) {
10529            return mLayout.getLineTop(line) - mContentView.getMeasuredHeight();
10530        }
10531
10532        @Override
10533        protected int clipVertically(int positionY) {
10534            if (positionY < 0) {
10535                final int offset = getTextOffset();
10536                final int line = mLayout.getLineForOffset(offset);
10537                positionY += mLayout.getLineBottom(line) - mLayout.getLineTop(line);
10538                positionY += mContentView.getMeasuredHeight();
10539
10540                // Assumes insertion and selection handles share the same height
10541                final Drawable handle = mContext.getResources().getDrawable(mTextSelectHandleRes);
10542                positionY += handle.getIntrinsicHeight();
10543            }
10544
10545            return positionY;
10546        }
10547    }
10548
10549    private abstract class HandleView extends View implements TextViewPositionListener {
10550        protected Drawable mDrawable;
10551        protected Drawable mDrawableLtr;
10552        protected Drawable mDrawableRtl;
10553        private final PopupWindow mContainer;
10554        // Position with respect to the parent TextView
10555        private int mPositionX, mPositionY;
10556        private boolean mIsDragging;
10557        // Offset from touch position to mPosition
10558        private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
10559        protected int mHotspotX;
10560        // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
10561        private float mTouchOffsetY;
10562        // Where the touch position should be on the handle to ensure a maximum cursor visibility
10563        private float mIdealVerticalOffset;
10564        // Parent's (TextView) previous position in window
10565        private int mLastParentX, mLastParentY;
10566        // Transient action popup window for Paste and Replace actions
10567        protected ActionPopupWindow mActionPopupWindow;
10568        // Previous text character offset
10569        private int mPreviousOffset = -1;
10570        // Previous text character offset
10571        private boolean mPositionHasChanged = true;
10572        // Used to delay the appearance of the action popup window
10573        private Runnable mActionPopupShower;
10574
10575        public HandleView(Drawable drawableLtr, Drawable drawableRtl) {
10576            super(TextView.this.mContext);
10577            mContainer = new PopupWindow(TextView.this.mContext, null,
10578                    com.android.internal.R.attr.textSelectHandleWindowStyle);
10579            mContainer.setSplitTouchEnabled(true);
10580            mContainer.setClippingEnabled(false);
10581            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
10582            mContainer.setContentView(this);
10583
10584            mDrawableLtr = drawableLtr;
10585            mDrawableRtl = drawableRtl;
10586
10587            updateDrawable();
10588
10589            final int handleHeight = mDrawable.getIntrinsicHeight();
10590            mTouchOffsetY = -0.3f * handleHeight;
10591            mIdealVerticalOffset = 0.7f * handleHeight;
10592        }
10593
10594        protected void updateDrawable() {
10595            final int offset = getCurrentCursorOffset();
10596            final boolean isRtlCharAtOffset = mLayout.isRtlCharAt(offset);
10597            mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
10598            mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
10599        }
10600
10601        protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
10602
10603        // Touch-up filter: number of previous positions remembered
10604        private static final int HISTORY_SIZE = 5;
10605        private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
10606        private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
10607        private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
10608        private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
10609        private int mPreviousOffsetIndex = 0;
10610        private int mNumberPreviousOffsets = 0;
10611
10612        private void startTouchUpFilter(int offset) {
10613            mNumberPreviousOffsets = 0;
10614            addPositionToTouchUpFilter(offset);
10615        }
10616
10617        private void addPositionToTouchUpFilter(int offset) {
10618            mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
10619            mPreviousOffsets[mPreviousOffsetIndex] = offset;
10620            mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
10621            mNumberPreviousOffsets++;
10622        }
10623
10624        private void filterOnTouchUp() {
10625            final long now = SystemClock.uptimeMillis();
10626            int i = 0;
10627            int index = mPreviousOffsetIndex;
10628            final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
10629            while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
10630                i++;
10631                index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
10632            }
10633
10634            if (i > 0 && i < iMax &&
10635                    (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
10636                positionAtCursorOffset(mPreviousOffsets[index], false);
10637            }
10638        }
10639
10640        public boolean offsetHasBeenChanged() {
10641            return mNumberPreviousOffsets > 1;
10642        }
10643
10644        @Override
10645        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10646            setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
10647        }
10648
10649        public void show() {
10650            if (isShowing()) return;
10651
10652            getPositionListener().addSubscriber(this, true /* local position may change */);
10653
10654            // Make sure the offset is always considered new, even when focusing at same position
10655            mPreviousOffset = -1;
10656            positionAtCursorOffset(getCurrentCursorOffset(), false);
10657
10658            hideActionPopupWindow();
10659        }
10660
10661        protected void dismiss() {
10662            mIsDragging = false;
10663            mContainer.dismiss();
10664            onDetached();
10665        }
10666
10667        public void hide() {
10668            dismiss();
10669
10670            TextView.this.getPositionListener().removeSubscriber(this);
10671        }
10672
10673        void showActionPopupWindow(int delay) {
10674            if (mActionPopupWindow == null) {
10675                mActionPopupWindow = new ActionPopupWindow();
10676            }
10677            if (mActionPopupShower == null) {
10678                mActionPopupShower = new Runnable() {
10679                    public void run() {
10680                        mActionPopupWindow.show();
10681                    }
10682                };
10683            } else {
10684                TextView.this.removeCallbacks(mActionPopupShower);
10685            }
10686            TextView.this.postDelayed(mActionPopupShower, delay);
10687        }
10688
10689        protected void hideActionPopupWindow() {
10690            if (mActionPopupShower != null) {
10691                TextView.this.removeCallbacks(mActionPopupShower);
10692            }
10693            if (mActionPopupWindow != null) {
10694                mActionPopupWindow.hide();
10695            }
10696        }
10697
10698        public boolean isShowing() {
10699            return mContainer.isShowing();
10700        }
10701
10702        private boolean isVisible() {
10703            // Always show a dragging handle.
10704            if (mIsDragging) {
10705                return true;
10706            }
10707
10708            if (isInBatchEditMode()) {
10709                return false;
10710            }
10711
10712            return TextView.this.isPositionVisible(mPositionX + mHotspotX, mPositionY);
10713        }
10714
10715        public abstract int getCurrentCursorOffset();
10716
10717        protected abstract void updateSelection(int offset);
10718
10719        public abstract void updatePosition(float x, float y);
10720
10721        protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
10722            // A HandleView relies on the layout, which may be nulled by external methods
10723            if (mLayout == null) {
10724                // Will update controllers' state, hiding them and stopping selection mode if needed
10725                prepareCursorControllers();
10726                return;
10727            }
10728
10729            if (offset != mPreviousOffset || parentScrolled) {
10730                updateSelection(offset);
10731                addPositionToTouchUpFilter(offset);
10732                final int line = mLayout.getLineForOffset(offset);
10733
10734                mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX);
10735                mPositionY = mLayout.getLineBottom(line);
10736
10737                // Take TextView's padding and scroll into account.
10738                mPositionX += viewportToContentHorizontalOffset();
10739                mPositionY += viewportToContentVerticalOffset();
10740
10741                mPreviousOffset = offset;
10742                mPositionHasChanged = true;
10743            }
10744        }
10745
10746        public void updatePosition(int parentPositionX, int parentPositionY,
10747                boolean parentPositionChanged, boolean parentScrolled) {
10748            positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled);
10749            if (parentPositionChanged || mPositionHasChanged) {
10750                if (mIsDragging) {
10751                    // Update touchToWindow offset in case of parent scrolling while dragging
10752                    if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
10753                        mTouchToWindowOffsetX += parentPositionX - mLastParentX;
10754                        mTouchToWindowOffsetY += parentPositionY - mLastParentY;
10755                        mLastParentX = parentPositionX;
10756                        mLastParentY = parentPositionY;
10757                    }
10758
10759                    onHandleMoved();
10760                }
10761
10762                if (isVisible()) {
10763                    final int positionX = parentPositionX + mPositionX;
10764                    final int positionY = parentPositionY + mPositionY;
10765                    if (isShowing()) {
10766                        mContainer.update(positionX, positionY, -1, -1);
10767                    } else {
10768                        mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY,
10769                                positionX, positionY);
10770                    }
10771                } else {
10772                    if (isShowing()) {
10773                        dismiss();
10774                    }
10775                }
10776
10777                mPositionHasChanged = false;
10778            }
10779        }
10780
10781        @Override
10782        protected void onDraw(Canvas c) {
10783            mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
10784            mDrawable.draw(c);
10785        }
10786
10787        @Override
10788        public boolean onTouchEvent(MotionEvent ev) {
10789            switch (ev.getActionMasked()) {
10790                case MotionEvent.ACTION_DOWN: {
10791                    startTouchUpFilter(getCurrentCursorOffset());
10792                    mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
10793                    mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
10794
10795                    final PositionListener positionListener = getPositionListener();
10796                    mLastParentX = positionListener.getPositionX();
10797                    mLastParentY = positionListener.getPositionY();
10798                    mIsDragging = true;
10799                    break;
10800                }
10801
10802                case MotionEvent.ACTION_MOVE: {
10803                    final float rawX = ev.getRawX();
10804                    final float rawY = ev.getRawY();
10805
10806                    // Vertical hysteresis: vertical down movement tends to snap to ideal offset
10807                    final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
10808                    final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
10809                    float newVerticalOffset;
10810                    if (previousVerticalOffset < mIdealVerticalOffset) {
10811                        newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
10812                        newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
10813                    } else {
10814                        newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
10815                        newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
10816                    }
10817                    mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
10818
10819                    final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX;
10820                    final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
10821
10822                    updatePosition(newPosX, newPosY);
10823                    break;
10824                }
10825
10826                case MotionEvent.ACTION_UP:
10827                    filterOnTouchUp();
10828                    mIsDragging = false;
10829                    break;
10830
10831                case MotionEvent.ACTION_CANCEL:
10832                    mIsDragging = false;
10833                    break;
10834            }
10835            return true;
10836        }
10837
10838        public boolean isDragging() {
10839            return mIsDragging;
10840        }
10841
10842        void onHandleMoved() {
10843            hideActionPopupWindow();
10844        }
10845
10846        public void onDetached() {
10847            hideActionPopupWindow();
10848        }
10849    }
10850
10851    private class InsertionHandleView extends HandleView {
10852        private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
10853        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
10854
10855        // Used to detect taps on the insertion handle, which will affect the ActionPopupWindow
10856        private float mDownPositionX, mDownPositionY;
10857        private Runnable mHider;
10858
10859        public InsertionHandleView(Drawable drawable) {
10860            super(drawable, drawable);
10861        }
10862
10863        @Override
10864        public void show() {
10865            super.show();
10866
10867            final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - LAST_CUT_OR_COPY_TIME;
10868            if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) {
10869                showActionPopupWindow(0);
10870            }
10871
10872            hideAfterDelay();
10873        }
10874
10875        public void showWithActionPopup() {
10876            show();
10877            showActionPopupWindow(0);
10878        }
10879
10880        private void hideAfterDelay() {
10881            if (mHider == null) {
10882                mHider = new Runnable() {
10883                    public void run() {
10884                        hide();
10885                    }
10886                };
10887            } else {
10888                removeHiderCallback();
10889            }
10890            TextView.this.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
10891        }
10892
10893        private void removeHiderCallback() {
10894            if (mHider != null) {
10895                TextView.this.removeCallbacks(mHider);
10896            }
10897        }
10898
10899        @Override
10900        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
10901            return drawable.getIntrinsicWidth() / 2;
10902        }
10903
10904        @Override
10905        public boolean onTouchEvent(MotionEvent ev) {
10906            final boolean result = super.onTouchEvent(ev);
10907
10908            switch (ev.getActionMasked()) {
10909                case MotionEvent.ACTION_DOWN:
10910                    mDownPositionX = ev.getRawX();
10911                    mDownPositionY = ev.getRawY();
10912                    break;
10913
10914                case MotionEvent.ACTION_UP:
10915                    if (!offsetHasBeenChanged()) {
10916                        final float deltaX = mDownPositionX - ev.getRawX();
10917                        final float deltaY = mDownPositionY - ev.getRawY();
10918                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
10919
10920                        final ViewConfiguration viewConfiguration = ViewConfiguration.get(
10921                                TextView.this.getContext());
10922                        final int touchSlop = viewConfiguration.getScaledTouchSlop();
10923
10924                        if (distanceSquared < touchSlop * touchSlop) {
10925                            if (mActionPopupWindow != null && mActionPopupWindow.isShowing()) {
10926                                // Tapping on the handle dismisses the displayed action popup
10927                                mActionPopupWindow.hide();
10928                            } else {
10929                                showWithActionPopup();
10930                            }
10931                        }
10932                    }
10933                    hideAfterDelay();
10934                    break;
10935
10936                case MotionEvent.ACTION_CANCEL:
10937                    hideAfterDelay();
10938                    break;
10939
10940                default:
10941                    break;
10942            }
10943
10944            return result;
10945        }
10946
10947        @Override
10948        public int getCurrentCursorOffset() {
10949            return TextView.this.getSelectionStart();
10950        }
10951
10952        @Override
10953        public void updateSelection(int offset) {
10954            Selection.setSelection((Spannable) mText, offset);
10955        }
10956
10957        @Override
10958        public void updatePosition(float x, float y) {
10959            positionAtCursorOffset(getOffsetForPosition(x, y), false);
10960        }
10961
10962        @Override
10963        void onHandleMoved() {
10964            super.onHandleMoved();
10965            removeHiderCallback();
10966        }
10967
10968        @Override
10969        public void onDetached() {
10970            super.onDetached();
10971            removeHiderCallback();
10972        }
10973    }
10974
10975    private class SelectionStartHandleView extends HandleView {
10976
10977        public SelectionStartHandleView(Drawable drawableLtr, Drawable drawableRtl) {
10978            super(drawableLtr, drawableRtl);
10979        }
10980
10981        @Override
10982        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
10983            if (isRtlRun) {
10984                return drawable.getIntrinsicWidth() / 4;
10985            } else {
10986                return (drawable.getIntrinsicWidth() * 3) / 4;
10987            }
10988        }
10989
10990        @Override
10991        public int getCurrentCursorOffset() {
10992            return TextView.this.getSelectionStart();
10993        }
10994
10995        @Override
10996        public void updateSelection(int offset) {
10997            Selection.setSelection((Spannable) mText, offset, getSelectionEnd());
10998            updateDrawable();
10999        }
11000
11001        @Override
11002        public void updatePosition(float x, float y) {
11003            int offset = getOffsetForPosition(x, y);
11004
11005            // Handles can not cross and selection is at least one character
11006            final int selectionEnd = getSelectionEnd();
11007            if (offset >= selectionEnd) offset = Math.max(0, selectionEnd - 1);
11008
11009            positionAtCursorOffset(offset, false);
11010        }
11011
11012        public ActionPopupWindow getActionPopupWindow() {
11013            return mActionPopupWindow;
11014        }
11015    }
11016
11017    private class SelectionEndHandleView extends HandleView {
11018
11019        public SelectionEndHandleView(Drawable drawableLtr, Drawable drawableRtl) {
11020            super(drawableLtr, drawableRtl);
11021        }
11022
11023        @Override
11024        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
11025            if (isRtlRun) {
11026                return (drawable.getIntrinsicWidth() * 3) / 4;
11027            } else {
11028                return drawable.getIntrinsicWidth() / 4;
11029            }
11030        }
11031
11032        @Override
11033        public int getCurrentCursorOffset() {
11034            return TextView.this.getSelectionEnd();
11035        }
11036
11037        @Override
11038        public void updateSelection(int offset) {
11039            Selection.setSelection((Spannable) mText, getSelectionStart(), offset);
11040            updateDrawable();
11041        }
11042
11043        @Override
11044        public void updatePosition(float x, float y) {
11045            int offset = getOffsetForPosition(x, y);
11046
11047            // Handles can not cross and selection is at least one character
11048            final int selectionStart = getSelectionStart();
11049            if (offset <= selectionStart) offset = Math.min(selectionStart + 1, mText.length());
11050
11051            positionAtCursorOffset(offset, false);
11052        }
11053
11054        public void setActionPopupWindow(ActionPopupWindow actionPopupWindow) {
11055            mActionPopupWindow = actionPopupWindow;
11056        }
11057    }
11058
11059    /**
11060     * A CursorController instance can be used to control a cursor in the text.
11061     * It is not used outside of {@link TextView}.
11062     * @hide
11063     */
11064    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
11065        /**
11066         * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}.
11067         * See also {@link #hide()}.
11068         */
11069        public void show();
11070
11071        /**
11072         * Hide the cursor controller from screen.
11073         * See also {@link #show()}.
11074         */
11075        public void hide();
11076
11077        /**
11078         * Called when the view is detached from window. Perform house keeping task, such as
11079         * stopping Runnable thread that would otherwise keep a reference on the context, thus
11080         * preventing the activity from being recycled.
11081         */
11082        public void onDetached();
11083    }
11084
11085    private class InsertionPointCursorController implements CursorController {
11086        private InsertionHandleView mHandle;
11087
11088        public void show() {
11089            getHandle().show();
11090        }
11091
11092        public void showWithActionPopup() {
11093            getHandle().showWithActionPopup();
11094        }
11095
11096        public void hide() {
11097            if (mHandle != null) {
11098                mHandle.hide();
11099            }
11100        }
11101
11102        public void onTouchModeChanged(boolean isInTouchMode) {
11103            if (!isInTouchMode) {
11104                hide();
11105            }
11106        }
11107
11108        private InsertionHandleView getHandle() {
11109            if (getEditor().mSelectHandleCenter == null) {
11110                getEditor().mSelectHandleCenter = mContext.getResources().getDrawable(
11111                        mTextSelectHandleRes);
11112            }
11113            if (mHandle == null) {
11114                mHandle = new InsertionHandleView(getEditor().mSelectHandleCenter);
11115            }
11116            return mHandle;
11117        }
11118
11119        @Override
11120        public void onDetached() {
11121            final ViewTreeObserver observer = getViewTreeObserver();
11122            observer.removeOnTouchModeChangeListener(this);
11123
11124            if (mHandle != null) mHandle.onDetached();
11125        }
11126    }
11127
11128    private class SelectionModifierCursorController implements CursorController {
11129        private static final int DELAY_BEFORE_REPLACE_ACTION = 200; // milliseconds
11130        // The cursor controller handles, lazily created when shown.
11131        private SelectionStartHandleView mStartHandle;
11132        private SelectionEndHandleView mEndHandle;
11133        // The offsets of that last touch down event. Remembered to start selection there.
11134        private int mMinTouchOffset, mMaxTouchOffset;
11135
11136        // Double tap detection
11137        private long mPreviousTapUpTime = 0;
11138        private float mDownPositionX, mDownPositionY;
11139        private boolean mGestureStayedInTapRegion;
11140
11141        SelectionModifierCursorController() {
11142            resetTouchOffsets();
11143        }
11144
11145        public void show() {
11146            if (isInBatchEditMode()) {
11147                return;
11148            }
11149            initDrawables();
11150            initHandles();
11151            hideInsertionPointCursorController();
11152        }
11153
11154        private void initDrawables() {
11155            if (getEditor().mSelectHandleLeft == null) {
11156                getEditor().mSelectHandleLeft = mContext.getResources().getDrawable(
11157                        mTextSelectHandleLeftRes);
11158            }
11159            if (getEditor().mSelectHandleRight == null) {
11160                getEditor().mSelectHandleRight = mContext.getResources().getDrawable(
11161                        mTextSelectHandleRightRes);
11162            }
11163        }
11164
11165        private void initHandles() {
11166            // Lazy object creation has to be done before updatePosition() is called.
11167            if (mStartHandle == null) {
11168                mStartHandle = new SelectionStartHandleView(getEditor().mSelectHandleLeft, getEditor().mSelectHandleRight);
11169            }
11170            if (mEndHandle == null) {
11171                mEndHandle = new SelectionEndHandleView(getEditor().mSelectHandleRight, getEditor().mSelectHandleLeft);
11172            }
11173
11174            mStartHandle.show();
11175            mEndHandle.show();
11176
11177            // Make sure both left and right handles share the same ActionPopupWindow (so that
11178            // moving any of the handles hides the action popup).
11179            mStartHandle.showActionPopupWindow(DELAY_BEFORE_REPLACE_ACTION);
11180            mEndHandle.setActionPopupWindow(mStartHandle.getActionPopupWindow());
11181
11182            hideInsertionPointCursorController();
11183        }
11184
11185        public void hide() {
11186            if (mStartHandle != null) mStartHandle.hide();
11187            if (mEndHandle != null) mEndHandle.hide();
11188        }
11189
11190        public void onTouchEvent(MotionEvent event) {
11191            // This is done even when the View does not have focus, so that long presses can start
11192            // selection and tap can move cursor from this tap position.
11193            switch (event.getActionMasked()) {
11194                case MotionEvent.ACTION_DOWN:
11195                    final float x = event.getX();
11196                    final float y = event.getY();
11197
11198                    // Remember finger down position, to be able to start selection from there
11199                    mMinTouchOffset = mMaxTouchOffset = getOffsetForPosition(x, y);
11200
11201                    // Double tap detection
11202                    if (mGestureStayedInTapRegion) {
11203                        long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime;
11204                        if (duration <= ViewConfiguration.getDoubleTapTimeout()) {
11205                            final float deltaX = x - mDownPositionX;
11206                            final float deltaY = y - mDownPositionY;
11207                            final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
11208
11209                            ViewConfiguration viewConfiguration = ViewConfiguration.get(
11210                                    TextView.this.getContext());
11211                            int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop();
11212                            boolean stayedInArea = distanceSquared < doubleTapSlop * doubleTapSlop;
11213
11214                            if (stayedInArea && isPositionOnText(x, y)) {
11215                                startSelectionActionMode();
11216                                getEditor().mDiscardNextActionUp = true;
11217                            }
11218                        }
11219                    }
11220
11221                    mDownPositionX = x;
11222                    mDownPositionY = y;
11223                    mGestureStayedInTapRegion = true;
11224                    break;
11225
11226                case MotionEvent.ACTION_POINTER_DOWN:
11227                case MotionEvent.ACTION_POINTER_UP:
11228                    // Handle multi-point gestures. Keep min and max offset positions.
11229                    // Only activated for devices that correctly handle multi-touch.
11230                    if (mContext.getPackageManager().hasSystemFeature(
11231                            PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
11232                        updateMinAndMaxOffsets(event);
11233                    }
11234                    break;
11235
11236                case MotionEvent.ACTION_MOVE:
11237                    if (mGestureStayedInTapRegion) {
11238                        final float deltaX = event.getX() - mDownPositionX;
11239                        final float deltaY = event.getY() - mDownPositionY;
11240                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
11241
11242                        final ViewConfiguration viewConfiguration = ViewConfiguration.get(
11243                                TextView.this.getContext());
11244                        int doubleTapTouchSlop = viewConfiguration.getScaledDoubleTapTouchSlop();
11245
11246                        if (distanceSquared > doubleTapTouchSlop * doubleTapTouchSlop) {
11247                            mGestureStayedInTapRegion = false;
11248                        }
11249                    }
11250                    break;
11251
11252                case MotionEvent.ACTION_UP:
11253                    mPreviousTapUpTime = SystemClock.uptimeMillis();
11254                    break;
11255            }
11256        }
11257
11258        /**
11259         * @param event
11260         */
11261        private void updateMinAndMaxOffsets(MotionEvent event) {
11262            int pointerCount = event.getPointerCount();
11263            for (int index = 0; index < pointerCount; index++) {
11264                int offset = getOffsetForPosition(event.getX(index), event.getY(index));
11265                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
11266                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
11267            }
11268        }
11269
11270        public int getMinTouchOffset() {
11271            return mMinTouchOffset;
11272        }
11273
11274        public int getMaxTouchOffset() {
11275            return mMaxTouchOffset;
11276        }
11277
11278        public void resetTouchOffsets() {
11279            mMinTouchOffset = mMaxTouchOffset = -1;
11280        }
11281
11282        /**
11283         * @return true iff this controller is currently used to move the selection start.
11284         */
11285        public boolean isSelectionStartDragged() {
11286            return mStartHandle != null && mStartHandle.isDragging();
11287        }
11288
11289        public void onTouchModeChanged(boolean isInTouchMode) {
11290            if (!isInTouchMode) {
11291                hide();
11292            }
11293        }
11294
11295        @Override
11296        public void onDetached() {
11297            final ViewTreeObserver observer = getViewTreeObserver();
11298            observer.removeOnTouchModeChangeListener(this);
11299
11300            if (mStartHandle != null) mStartHandle.onDetached();
11301            if (mEndHandle != null) mEndHandle.onDetached();
11302        }
11303    }
11304
11305    static class InputContentType {
11306        int imeOptions = EditorInfo.IME_NULL;
11307        String privateImeOptions;
11308        CharSequence imeActionLabel;
11309        int imeActionId;
11310        Bundle extras;
11311        OnEditorActionListener onEditorActionListener;
11312        boolean enterDown;
11313    }
11314
11315    static class InputMethodState {
11316        Rect mCursorRectInWindow = new Rect();
11317        RectF mTmpRectF = new RectF();
11318        float[] mTmpOffset = new float[2];
11319        ExtractedTextRequest mExtracting;
11320        final ExtractedText mTmpExtracted = new ExtractedText();
11321        int mBatchEditNesting;
11322        boolean mCursorChanged;
11323        boolean mSelectionModeChanged;
11324        boolean mContentChanged;
11325        int mChangedStart, mChangedEnd, mChangedDelta;
11326    }
11327
11328    private class Editor {
11329        Editor() {
11330            mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
11331            final CompatibilityInfo compat = TextView.this.getResources().getCompatibilityInfo();
11332            mHighlightPaint.setCompatibilityScaling(compat.applicationScale);
11333        }
11334
11335        // Cursor Controllers.
11336        InsertionPointCursorController mInsertionPointCursorController;
11337        SelectionModifierCursorController mSelectionModifierCursorController;
11338        ActionMode mSelectionActionMode;
11339        boolean mInsertionControllerEnabled;
11340        boolean mSelectionControllerEnabled;
11341
11342        // Used to highlight a word when it is corrected by the IME
11343        CorrectionHighlighter mCorrectionHighlighter;
11344
11345        InputContentType mInputContentType;
11346        InputMethodState mInputMethodState;
11347
11348        Path mHighlightPath;
11349        boolean mHighlightPathBogus = true;
11350        final Paint mHighlightPaint;
11351
11352        DisplayList mTextDisplayList;
11353        boolean mTextDisplayListIsValid;
11354
11355        boolean mFrozenWithFocus;
11356        boolean mSelectionMoved;
11357        boolean mTouchFocusSelected;
11358
11359        KeyListener mKeyListener;
11360        int mInputType = EditorInfo.TYPE_NULL;
11361
11362        boolean mDiscardNextActionUp;
11363        boolean mIgnoreActionUpEvent;
11364
11365        long mShowCursor;
11366        Blink mBlink;
11367
11368        boolean mCursorVisible = true;
11369        boolean mSelectAllOnFocus;
11370        boolean mTextIsSelectable;
11371
11372        CharSequence mError;
11373        boolean mErrorWasChanged;
11374        ErrorPopup mErrorPopup;
11375        /**
11376         * This flag is set if the TextView tries to display an error before it
11377         * is attached to the window (so its position is still unknown).
11378         * It causes the error to be shown later, when onAttachedToWindow()
11379         * is called.
11380         */
11381        boolean mShowErrorAfterAttach;
11382
11383        boolean mInBatchEditControllers;
11384
11385        SuggestionsPopupWindow mSuggestionsPopupWindow;
11386        SuggestionRangeSpan mSuggestionRangeSpan;
11387        Runnable mShowSuggestionRunnable;
11388
11389        final Drawable[] mCursorDrawable = new Drawable[2];
11390        int mCursorCount; // Actual current number of used mCursorDrawable: 0, 1 or 2 (split)
11391
11392        Drawable mSelectHandleLeft;
11393        Drawable mSelectHandleRight;
11394        Drawable mSelectHandleCenter;
11395
11396        // Global listener that detects changes in the global position of the TextView
11397        PositionListener mPositionListener;
11398
11399        float mLastDownPositionX, mLastDownPositionY;
11400        Callback mCustomSelectionActionModeCallback;
11401
11402        // Set when this TextView gained focus with some text selected. Will start selection mode.
11403        boolean mCreatedWithASelection;
11404
11405        WordIterator mWordIterator;
11406        SpellChecker mSpellChecker;
11407
11408        void onAttachedToWindow() {
11409            final ViewTreeObserver observer = getViewTreeObserver();
11410            // No need to create the controller.
11411            // The get method will add the listener on controller creation.
11412            if (mInsertionPointCursorController != null) {
11413                observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
11414            }
11415            if (mSelectionModifierCursorController != null) {
11416                observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
11417            }
11418            updateSpellCheckSpans(0, mText.length(), true /* create the spell checker if needed */);
11419        }
11420
11421        void onDetachedFromWindow() {
11422            if (mError != null) {
11423                hideError();
11424            }
11425
11426            if (mBlink != null) {
11427                mBlink.removeCallbacks(mBlink);
11428            }
11429
11430            if (mInsertionPointCursorController != null) {
11431                mInsertionPointCursorController.onDetached();
11432            }
11433
11434            if (mSelectionModifierCursorController != null) {
11435                mSelectionModifierCursorController.onDetached();
11436            }
11437
11438            if (mShowSuggestionRunnable != null) {
11439                removeCallbacks(mShowSuggestionRunnable);
11440            }
11441
11442            if (mTextDisplayList != null) {
11443                mTextDisplayList.invalidate();
11444            }
11445
11446            if (mSpellChecker != null) {
11447                mSpellChecker.closeSession();
11448                // Forces the creation of a new SpellChecker next time this window is created.
11449                // Will handle the cases where the settings has been changed in the meantime.
11450                mSpellChecker = null;
11451            }
11452
11453            hideControllers();
11454        }
11455
11456        void adjustInputType(boolean password, boolean passwordInputType,
11457                boolean webPasswordInputType, boolean numberPasswordInputType) {
11458            // mInputType has been set from inputType, possibly modified by mInputMethod.
11459            // Specialize mInputType to [web]password if we have a text class and the original input
11460            // type was a password.
11461            if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
11462                if (password || passwordInputType) {
11463                    mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
11464                            | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD;
11465                }
11466                if (webPasswordInputType) {
11467                    mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
11468                            | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD;
11469                }
11470            } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) {
11471                if (numberPasswordInputType) {
11472                    mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
11473                            | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD;
11474                }
11475            }
11476        }
11477
11478        void setFrame() {
11479            if (mErrorPopup != null) {
11480                TextView tv = (TextView) mErrorPopup.getContentView();
11481                chooseSize(mErrorPopup, mError, tv);
11482                mErrorPopup.update(TextView.this, getErrorX(), getErrorY(),
11483                        mErrorPopup.getWidth(), mErrorPopup.getHeight());
11484            }
11485        }
11486
11487        void onFocusChanged(boolean focused, int direction) {
11488            mShowCursor = SystemClock.uptimeMillis();
11489            ensureEndedBatchEdit();
11490
11491            if (focused) {
11492                int selStart = getSelectionStart();
11493                int selEnd = getSelectionEnd();
11494
11495                // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection
11496                // mode for these, unless there was a specific selection already started.
11497                final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 &&
11498                        selEnd == mText.length();
11499
11500                mCreatedWithASelection = mFrozenWithFocus && hasSelection() && !isFocusHighlighted;
11501
11502                if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
11503                    // If a tap was used to give focus to that view, move cursor at tap position.
11504                    // Has to be done before onTakeFocus, which can be overloaded.
11505                    final int lastTapPosition = getLastTapPosition();
11506                    if (lastTapPosition >= 0) {
11507                        Selection.setSelection((Spannable) mText, lastTapPosition);
11508                    }
11509
11510                    // Note this may have to be moved out of the Editor class
11511                    if (mMovement != null) {
11512                        mMovement.onTakeFocus(TextView.this, (Spannable) mText, direction);
11513                    }
11514
11515                    // The DecorView does not have focus when the 'Done' ExtractEditText button is
11516                    // pressed. Since it is the ViewAncestor's mView, it requests focus before
11517                    // ExtractEditText clears focus, which gives focus to the ExtractEditText.
11518                    // This special case ensure that we keep current selection in that case.
11519                    // It would be better to know why the DecorView does not have focus at that time.
11520                    if (((TextView.this instanceof ExtractEditText) || mSelectionMoved) &&
11521                            selStart >= 0 && selEnd >= 0) {
11522                        /*
11523                         * Someone intentionally set the selection, so let them
11524                         * do whatever it is that they wanted to do instead of
11525                         * the default on-focus behavior.  We reset the selection
11526                         * here instead of just skipping the onTakeFocus() call
11527                         * because some movement methods do something other than
11528                         * just setting the selection in theirs and we still
11529                         * need to go through that path.
11530                         */
11531                        Selection.setSelection((Spannable) mText, selStart, selEnd);
11532                    }
11533
11534                    if (mSelectAllOnFocus) {
11535                        selectAll();
11536                    }
11537
11538                    mTouchFocusSelected = true;
11539                }
11540
11541                mFrozenWithFocus = false;
11542                mSelectionMoved = false;
11543
11544                if (mError != null) {
11545                    showError();
11546                }
11547
11548                makeBlink();
11549            } else {
11550                if (mError != null) {
11551                    hideError();
11552                }
11553                // Don't leave us in the middle of a batch edit.
11554                onEndBatchEdit();
11555
11556                if (TextView.this instanceof ExtractEditText) {
11557                    // terminateTextSelectionMode removes selection, which we want to keep when
11558                    // ExtractEditText goes out of focus.
11559                    final int selStart = getSelectionStart();
11560                    final int selEnd = getSelectionEnd();
11561                    hideControllers();
11562                    Selection.setSelection((Spannable) mText, selStart, selEnd);
11563                } else {
11564                    hideControllers();
11565                    downgradeEasyCorrectionSpans();
11566                }
11567
11568                // No need to create the controller
11569                if (mSelectionModifierCursorController != null) {
11570                    mSelectionModifierCursorController.resetTouchOffsets();
11571                }
11572            }
11573        }
11574
11575        void sendOnTextChanged(int start, int after) {
11576            updateSpellCheckSpans(start, start + after, false);
11577            mTextDisplayListIsValid = false;
11578
11579            // Hide the controllers as soon as text is modified (typing, procedural...)
11580            // We do not hide the span controllers, since they can be added when a new text is
11581            // inserted into the text view (voice IME).
11582            hideCursorControllers();
11583        }
11584
11585        private int getLastTapPosition() {
11586            // No need to create the controller at that point, no last tap position saved
11587            if (mSelectionModifierCursorController != null) {
11588                int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset();
11589                if (lastTapPosition >= 0) {
11590                    // Safety check, should not be possible.
11591                    if (lastTapPosition > mText.length()) {
11592                        Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs "
11593                                + mText.length() + ")");
11594                        lastTapPosition = mText.length();
11595                    }
11596                    return lastTapPosition;
11597                }
11598            }
11599
11600            return -1;
11601        }
11602
11603        void onWindowFocusChanged(boolean hasWindowFocus) {
11604            if (hasWindowFocus) {
11605                if (mBlink != null) {
11606                    mBlink.uncancel();
11607                    makeBlink();
11608                }
11609            } else {
11610                if (mBlink != null) {
11611                    mBlink.cancel();
11612                }
11613                if (mInputContentType != null) {
11614                    mInputContentType.enterDown = false;
11615                }
11616                // Order matters! Must be done before onParentLostFocus to rely on isShowingUp
11617                hideControllers();
11618                if (mSuggestionsPopupWindow != null) {
11619                    mSuggestionsPopupWindow.onParentLostFocus();
11620                }
11621
11622                // Don't leave us in the middle of a batch edit.
11623                onEndBatchEdit();
11624            }
11625        }
11626
11627        void onTouchEvent(MotionEvent event) {
11628            if (hasSelectionController()) {
11629                getSelectionController().onTouchEvent(event);
11630            }
11631
11632            if (mShowSuggestionRunnable != null) {
11633                removeCallbacks(mShowSuggestionRunnable);
11634                mShowSuggestionRunnable = null;
11635            }
11636
11637            if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
11638                mLastDownPositionX = event.getX();
11639                mLastDownPositionY = event.getY();
11640
11641                // Reset this state; it will be re-set if super.onTouchEvent
11642                // causes focus to move to the view.
11643                mTouchFocusSelected = false;
11644                mIgnoreActionUpEvent = false;
11645            }
11646        }
11647
11648        void onDraw(Canvas canvas, Layout layout, int cursorOffsetVertical) {
11649            Path highlight = null;
11650            Paint highlightPaint = null;
11651
11652            int selStart = -1, selEnd = -1;
11653            boolean drawCursor = false;
11654
11655            highlightPaint = mHighlightPaint;
11656            //  If there is no movement method, then there can be no selection.
11657            //  Check that first and attempt to skip everything having to do with
11658            //  the cursor.
11659            //  XXX This is not strictly true -- a program could set the
11660            //  selection manually if it really wanted to.
11661            if (mMovement != null && (isFocused() || isPressed())) {
11662                selStart = getSelectionStart();
11663                selEnd = getSelectionEnd();
11664
11665                if (selStart >= 0) {
11666                    if (mHighlightPath == null) mHighlightPath = new Path();
11667
11668                    if (selStart == selEnd) {
11669                        if (isCursorVisible() &&
11670                                (SystemClock.uptimeMillis() - mShowCursor) % (2 * BLINK) < BLINK) {
11671                            if (mHighlightPathBogus) {
11672                                mHighlightPath.reset();
11673                                mLayout.getCursorPath(selStart, mHighlightPath, mText);
11674                                updateCursorsPositions();
11675                                mHighlightPathBogus = false;
11676                            }
11677
11678                            // XXX should pass to skin instead of drawing directly
11679                            highlightPaint.setColor(mCurTextColor);
11680                            if (mCurrentAlpha != 255) {
11681                                highlightPaint.setAlpha(
11682                                        (mCurrentAlpha * Color.alpha(mCurTextColor)) / 255);
11683                            }
11684                            highlightPaint.setStyle(Paint.Style.STROKE);
11685                            highlight = mHighlightPath;
11686                            drawCursor = mCursorCount > 0;
11687                        }
11688                    } else if (textCanBeSelected()) {
11689                        if (mHighlightPathBogus) {
11690                            mHighlightPath.reset();
11691                            mLayout.getSelectionPath(selStart, selEnd, mHighlightPath);
11692                            mHighlightPathBogus = false;
11693                        }
11694
11695                        // XXX should pass to skin instead of drawing directly
11696                        highlightPaint.setColor(mHighlightColor);
11697                        if (mCurrentAlpha != 255) {
11698                            highlightPaint.setAlpha(
11699                                    (mCurrentAlpha * Color.alpha(mHighlightColor)) / 255);
11700                        }
11701                        highlightPaint.setStyle(Paint.Style.FILL);
11702
11703                        highlight = mHighlightPath;
11704                    }
11705                }
11706            }
11707
11708            final InputMethodState ims = mInputMethodState;
11709            if (ims != null && ims.mBatchEditNesting == 0) {
11710                InputMethodManager imm = InputMethodManager.peekInstance();
11711                if (imm != null) {
11712                    if (imm.isActive(TextView.this)) {
11713                        boolean reported = false;
11714                        if (ims.mContentChanged || ims.mSelectionModeChanged) {
11715                            // We are in extract mode and the content has changed
11716                            // in some way... just report complete new text to the
11717                            // input method.
11718                            reported = reportExtractedText();
11719                        }
11720                        if (!reported && highlight != null) {
11721                            int candStart = -1;
11722                            int candEnd = -1;
11723                            if (mText instanceof Spannable) {
11724                                Spannable sp = (Spannable)mText;
11725                                candStart = EditableInputConnection.getComposingSpanStart(sp);
11726                                candEnd = EditableInputConnection.getComposingSpanEnd(sp);
11727                            }
11728                            imm.updateSelection(TextView.this, selStart, selEnd, candStart, candEnd);
11729                        }
11730                    }
11731
11732                    if (imm.isWatchingCursor(TextView.this) && highlight != null) {
11733                        highlight.computeBounds(ims.mTmpRectF, true);
11734                        ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0;
11735
11736                        canvas.getMatrix().mapPoints(ims.mTmpOffset);
11737                        ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]);
11738
11739                        ims.mTmpRectF.offset(0, cursorOffsetVertical);
11740
11741                        ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5),
11742                                (int)(ims.mTmpRectF.top + 0.5),
11743                                (int)(ims.mTmpRectF.right + 0.5),
11744                                (int)(ims.mTmpRectF.bottom + 0.5));
11745
11746                        imm.updateCursor(TextView.this,
11747                                ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top,
11748                                ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom);
11749                    }
11750                }
11751            }
11752
11753            if (mCorrectionHighlighter != null) {
11754                mCorrectionHighlighter.draw(canvas, cursorOffsetVertical);
11755            }
11756
11757            if (drawCursor) {
11758                drawCursor(canvas, cursorOffsetVertical);
11759                // Rely on the drawable entirely, do not draw the cursor line.
11760                // Has to be done after the IMM related code above which relies on the highlight.
11761                highlight = null;
11762            }
11763
11764            if (canHaveDisplayList() && canvas.isHardwareAccelerated()) {
11765                final int width = mRight - mLeft;
11766                final int height = mBottom - mTop;
11767
11768                if (mTextDisplayList == null || !mTextDisplayList.isValid() ||
11769                        !mTextDisplayListIsValid) {
11770                    if (mTextDisplayList == null) {
11771                        mTextDisplayList = getHardwareRenderer().createDisplayList("Text");
11772                    }
11773
11774                    final HardwareCanvas hardwareCanvas = mTextDisplayList.start();
11775                    try {
11776                        hardwareCanvas.setViewport(width, height);
11777                        // The dirty rect should always be null for a display list
11778                        hardwareCanvas.onPreDraw(null);
11779                        hardwareCanvas.translate(-mScrollX, -mScrollY);
11780                        layout.draw(hardwareCanvas, highlight, highlightPaint, cursorOffsetVertical);
11781                        hardwareCanvas.translate(mScrollX, mScrollY);
11782                    } finally {
11783                        hardwareCanvas.onPostDraw();
11784                        mTextDisplayList.end();
11785                        mTextDisplayListIsValid = true;
11786                    }
11787                }
11788                canvas.translate(mScrollX, mScrollY);
11789                ((HardwareCanvas) canvas).drawDisplayList(mTextDisplayList, width, height, null,
11790                        DisplayList.FLAG_CLIP_CHILDREN);
11791                canvas.translate(-mScrollX, -mScrollY);
11792            } else {
11793                layout.draw(canvas, highlight, highlightPaint, cursorOffsetVertical);
11794            }
11795
11796            if (mMarquee != null && mMarquee.shouldDrawGhost()) {
11797                canvas.translate((int) mMarquee.getGhostOffset(), 0.0f);
11798                layout.draw(canvas, highlight, highlightPaint, cursorOffsetVertical);
11799            }
11800        }
11801    }
11802}
11803