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