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