RecipientEditTextView.java revision cb76b4d2bcb7b72b9505a620ca71f753506e48b9
1/* 2 * Copyright (C) 2011 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 com.android.ex.chips; 18 19import android.app.Dialog; 20import android.content.ClipData; 21import android.content.ClipDescription; 22import android.content.ClipboardManager; 23import android.content.Context; 24import android.content.DialogInterface; 25import android.content.DialogInterface.OnDismissListener; 26import android.content.res.Resources; 27import android.content.res.TypedArray; 28import android.graphics.Bitmap; 29import android.graphics.BitmapFactory; 30import android.graphics.Canvas; 31import android.graphics.Matrix; 32import android.graphics.Point; 33import android.graphics.Rect; 34import android.graphics.RectF; 35import android.graphics.drawable.BitmapDrawable; 36import android.graphics.drawable.Drawable; 37import android.os.AsyncTask; 38import android.os.Handler; 39import android.os.Message; 40import android.os.Parcelable; 41import android.text.Editable; 42import android.text.InputType; 43import android.text.Layout; 44import android.text.Spannable; 45import android.text.SpannableString; 46import android.text.SpannableStringBuilder; 47import android.text.Spanned; 48import android.text.TextPaint; 49import android.text.TextUtils; 50import android.text.TextWatcher; 51import android.text.method.QwertyKeyListener; 52import android.text.style.ImageSpan; 53import android.text.util.Rfc822Token; 54import android.text.util.Rfc822Tokenizer; 55import android.util.AttributeSet; 56import android.util.Log; 57import android.util.Patterns; 58import android.view.ActionMode; 59import android.view.ActionMode.Callback; 60import android.view.DragEvent; 61import android.view.GestureDetector; 62import android.view.KeyEvent; 63import android.view.LayoutInflater; 64import android.view.Menu; 65import android.view.MenuItem; 66import android.view.MotionEvent; 67import android.view.View; 68import android.view.View.OnClickListener; 69import android.view.ViewParent; 70import android.view.inputmethod.EditorInfo; 71import android.view.inputmethod.InputConnection; 72import android.widget.AdapterView; 73import android.widget.AdapterView.OnItemClickListener; 74import android.widget.Button; 75import android.widget.ListAdapter; 76import android.widget.ListPopupWindow; 77import android.widget.ListView; 78import android.widget.MultiAutoCompleteTextView; 79import android.widget.ScrollView; 80import android.widget.TextView; 81 82import java.util.ArrayList; 83import java.util.Arrays; 84import java.util.Collection; 85import java.util.Collections; 86import java.util.Comparator; 87import java.util.HashMap; 88import java.util.HashSet; 89import java.util.Set; 90import java.util.regex.Matcher; 91 92/** 93 * RecipientEditTextView is an auto complete text view for use with applications 94 * that use the new Chips UI for addressing a message to recipients. 95 */ 96public class RecipientEditTextView extends MultiAutoCompleteTextView implements 97 OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener, 98 GestureDetector.OnGestureListener, OnDismissListener, OnClickListener, 99 TextView.OnEditorActionListener { 100 101 private static final char COMMIT_CHAR_COMMA = ','; 102 103 private static final char NAME_WRAPPER_CHAR = '"'; 104 105 private static final char COMMIT_CHAR_SEMICOLON = ';'; 106 107 private static final char COMMIT_CHAR_SPACE = ' '; 108 109 private static final String TAG = "RecipientEditTextView"; 110 111 private static int DISMISS = "dismiss".hashCode(); 112 113 private static final long DISMISS_DELAY = 300; 114 115 // TODO: get correct number/ algorithm from with UX. 116 // Visible for testing. 117 /*package*/ static final int CHIP_LIMIT = 2; 118 119 private static final int MAX_CHIPS_PARSED = 50; 120 121 private static int sSelectedTextColor = -1; 122 123 // Resources for displaying chips. 124 private Drawable mChipBackground = null; 125 126 private Drawable mChipDelete = null; 127 128 private Drawable mInvalidChipBackground; 129 130 private Drawable mChipBackgroundPressed; 131 132 private float mChipHeight; 133 134 private float mChipFontSize; 135 136 private float mLineSpacingExtra; 137 138 private int mChipPadding; 139 140 private Tokenizer mTokenizer; 141 142 private Validator mValidator; 143 144 private RecipientChip mSelectedChip; 145 146 private int mAlternatesLayout; 147 148 private Bitmap mDefaultContactPhoto; 149 150 private ImageSpan mMoreChip; 151 152 private TextView mMoreItem; 153 154 private final ArrayList<String> mPendingChips = new ArrayList<String>(); 155 156 private Handler mHandler; 157 158 private int mPendingChipsCount = 0; 159 160 private boolean mNoChips = false; 161 162 private ListPopupWindow mAlternatesPopup; 163 164 private ListPopupWindow mAddressPopup; 165 166 private ArrayList<RecipientChip> mTemporaryRecipients; 167 168 private ArrayList<RecipientChip> mRemovedSpans; 169 170 private boolean mShouldShrink = true; 171 172 // Chip copy fields. 173 private GestureDetector mGestureDetector; 174 175 private Dialog mCopyDialog; 176 177 private String mCopyAddress; 178 179 /** 180 * Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a 181 * selected chip. 182 */ 183 private OnItemClickListener mAlternatesListener; 184 185 private int mCheckedItem; 186 187 private TextWatcher mTextWatcher; 188 189 // Obtain the enclosing scroll view, if it exists, so that the view can be 190 // scrolled to show the last line of chips content. 191 private ScrollView mScrollView; 192 193 private boolean mTriedGettingScrollView; 194 195 private boolean mDragEnabled = false; 196 197 private final Runnable mAddTextWatcher = new Runnable() { 198 @Override 199 public void run() { 200 if (mTextWatcher == null) { 201 mTextWatcher = new RecipientTextWatcher(); 202 addTextChangedListener(mTextWatcher); 203 } 204 } 205 }; 206 207 private IndividualReplacementTask mIndividualReplacements; 208 209 private Runnable mHandlePendingChips = new Runnable() { 210 211 @Override 212 public void run() { 213 handlePendingChips(); 214 } 215 216 }; 217 218 private Runnable mDelayedShrink = new Runnable() { 219 220 @Override 221 public void run() { 222 shrink(); 223 } 224 225 }; 226 227 private int mMaxLines; 228 229 public RecipientEditTextView(Context context, AttributeSet attrs) { 230 super(context, attrs); 231 setChipDimensions(context, attrs); 232 if (sSelectedTextColor == -1) { 233 sSelectedTextColor = context.getResources().getColor(android.R.color.white); 234 } 235 mAlternatesPopup = new ListPopupWindow(context); 236 mAddressPopup = new ListPopupWindow(context); 237 mCopyDialog = new Dialog(context); 238 mAlternatesListener = new OnItemClickListener() { 239 @Override 240 public void onItemClick(AdapterView<?> adapterView,View view, int position, 241 long rowId) { 242 mAlternatesPopup.setOnItemClickListener(null); 243 replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter()) 244 .getRecipientEntry(position)); 245 Message delayed = Message.obtain(mHandler, DISMISS); 246 delayed.obj = mAlternatesPopup; 247 mHandler.sendMessageDelayed(delayed, DISMISS_DELAY); 248 clearComposingText(); 249 } 250 }; 251 setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); 252 setOnItemClickListener(this); 253 setCustomSelectionActionModeCallback(this); 254 mHandler = new Handler() { 255 @Override 256 public void handleMessage(Message msg) { 257 if (msg.what == DISMISS) { 258 ((ListPopupWindow) msg.obj).dismiss(); 259 return; 260 } 261 super.handleMessage(msg); 262 } 263 }; 264 mTextWatcher = new RecipientTextWatcher(); 265 addTextChangedListener(mTextWatcher); 266 mGestureDetector = new GestureDetector(context, this); 267 setOnEditorActionListener(this); 268 mMaxLines = getLineCount(); 269 } 270 271 @Override 272 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) { 273 if (action == EditorInfo.IME_ACTION_DONE) { 274 if (commitDefault()) { 275 return true; 276 } 277 if (mSelectedChip != null) { 278 clearSelectedChip(); 279 return true; 280 } else if (focusNext()) { 281 return true; 282 } 283 } 284 return false; 285 } 286 287 @Override 288 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 289 InputConnection connection = super.onCreateInputConnection(outAttrs); 290 int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION; 291 if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) { 292 // clear the existing action 293 outAttrs.imeOptions ^= imeActions; 294 // set the DONE action 295 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; 296 } 297 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) { 298 outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION; 299 } 300 outAttrs.actionLabel = getContext().getString(R.string.done); 301 return connection; 302 } 303 304 /*package*/ RecipientChip getLastChip() { 305 RecipientChip last = null; 306 RecipientChip[] chips = getSortedRecipients(); 307 if (chips != null && chips.length > 0) { 308 last = chips[chips.length - 1]; 309 } 310 return last; 311 } 312 313 @Override 314 public void onSelectionChanged(int start, int end) { 315 // When selection changes, see if it is inside the chips area. 316 // If so, move the cursor back after the chips again. 317 RecipientChip last = getLastChip(); 318 if (last != null && start < getSpannable().getSpanEnd(last)) { 319 // Grab the last chip and set the cursor to after it. 320 setSelection(Math.min(getSpannable().getSpanEnd(last) + 1, getText().length())); 321 } 322 super.onSelectionChanged(start, end); 323 } 324 325 @Override 326 public void onRestoreInstanceState(Parcelable state) { 327 if (!TextUtils.isEmpty(getText())) { 328 super.onRestoreInstanceState(null); 329 } else { 330 super.onRestoreInstanceState(state); 331 } 332 } 333 334 @Override 335 public Parcelable onSaveInstanceState() { 336 // If the user changes orientation while they are editing, just roll back the selection. 337 clearSelectedChip(); 338 return super.onSaveInstanceState(); 339 } 340 341 /** 342 * Convenience method: Append the specified text slice to the TextView's 343 * display buffer, upgrading it to BufferType.EDITABLE if it was 344 * not already editable. Commas are excluded as they are added automatically 345 * by the view. 346 */ 347 @Override 348 public void append(CharSequence text, int start, int end) { 349 // We don't care about watching text changes while appending. 350 if (mTextWatcher != null) { 351 removeTextChangedListener(mTextWatcher); 352 } 353 super.append(text, start, end); 354 if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) { 355 String displayString = text.toString(); 356 int separatorPos = displayString.lastIndexOf(COMMIT_CHAR_COMMA); 357 // Verify that the separator pos is not within ""; if it is, look 358 // past the closing quote. If there is no comma past ", this string 359 // will resolve to an error chip. 360 if (separatorPos > -1) { 361 String parseDisplayString = displayString.substring(separatorPos); 362 int endQuotedTextPos = parseDisplayString.indexOf(NAME_WRAPPER_CHAR); 363 if (endQuotedTextPos > separatorPos) { 364 separatorPos = parseDisplayString.lastIndexOf(COMMIT_CHAR_COMMA, 365 endQuotedTextPos); 366 } 367 } 368 if (!TextUtils.isEmpty(displayString) 369 && TextUtils.getTrimmedLength(displayString) > 0) { 370 mPendingChipsCount++; 371 mPendingChips.add(text.toString()); 372 } 373 } 374 // Put a message on the queue to make sure we ALWAYS handle pending 375 // chips. 376 if (mPendingChipsCount > 0) { 377 postHandlePendingChips(); 378 } 379 mHandler.post(mAddTextWatcher); 380 } 381 382 @Override 383 public void onFocusChanged(boolean hasFocus, int direction, Rect previous) { 384 super.onFocusChanged(hasFocus, direction, previous); 385 if (!hasFocus) { 386 shrink(); 387 } else { 388 expand(); 389 } 390 } 391 392 @Override 393 public void performValidation() { 394 // Do nothing. Chips handles its own validation. 395 } 396 397 private void shrink() { 398 if (mTokenizer == null) { 399 return; 400 } 401 long contactId = mSelectedChip != null ? mSelectedChip.getEntry().getContactId() : -1; 402 if (mSelectedChip != null && contactId != RecipientEntry.INVALID_CONTACT 403 && (!isPhoneQuery() && contactId != RecipientEntry.GENERATED_CONTACT)) { 404 clearSelectedChip(); 405 } else { 406 if (getWidth() <= 0) { 407 // We don't have the width yet which means the view hasn't been drawn yet 408 // and there is no reason to attempt to commit chips yet. 409 // This focus lost must be the result of an orientation change 410 // or an initial rendering. 411 // Re-post the shrink for later. 412 mHandler.removeCallbacks(mDelayedShrink); 413 mHandler.post(mDelayedShrink); 414 return; 415 } 416 // Reset any pending chips as they would have been handled 417 // when the field lost focus. 418 if (mPendingChipsCount > 0) { 419 postHandlePendingChips(); 420 } else { 421 Editable editable = getText(); 422 int end = getSelectionEnd(); 423 int start = mTokenizer.findTokenStart(editable, end); 424 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); 425 if ((chips == null || chips.length == 0)) { 426 Editable text = getText(); 427 int whatEnd = mTokenizer.findTokenEnd(text, start); 428 // This token was already tokenized, so skip past the ending token. 429 if (whatEnd < text.length() && text.charAt(whatEnd) == ',') { 430 whatEnd = movePastTerminators(whatEnd); 431 } 432 // In the middle of chip; treat this as an edit 433 // and commit the whole token. 434 int selEnd = getSelectionEnd(); 435 if (whatEnd != selEnd) { 436 handleEdit(start, whatEnd); 437 } else { 438 commitChip(start, end, editable); 439 } 440 } 441 } 442 mHandler.post(mAddTextWatcher); 443 } 444 createMoreChip(); 445 } 446 447 private void expand() { 448 if (mShouldShrink) { 449 setMaxLines(Integer.MAX_VALUE); 450 } 451 removeMoreChip(); 452 setCursorVisible(true); 453 Editable text = getText(); 454 setSelection(text != null && text.length() > 0 ? text.length() : 0); 455 // If there are any temporary chips, try replacing them now that the user 456 // has expanded the field. 457 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) { 458 new RecipientReplacementTask().execute(); 459 mTemporaryRecipients = null; 460 } 461 } 462 463 private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) { 464 paint.setTextSize(mChipFontSize); 465 if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) { 466 Log.d(TAG, "Max width is negative: " + maxWidth); 467 } 468 return TextUtils.ellipsize(text, paint, maxWidth, 469 TextUtils.TruncateAt.END); 470 } 471 472 private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) { 473 // Ellipsize the text so that it takes AT MOST the entire width of the 474 // autocomplete text entry area. Make sure to leave space for padding 475 // on the sides. 476 int height = (int) mChipHeight; 477 int deleteWidth = height; 478 float[] widths = new float[1]; 479 paint.getTextWidths(" ", widths); 480 CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint, 481 calculateAvailableWidth(true) - deleteWidth - widths[0]); 482 483 // Make sure there is a minimum chip width so the user can ALWAYS 484 // tap a chip without difficulty. 485 int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, 486 ellipsizedText.length())) 487 + (mChipPadding * 2) + deleteWidth); 488 489 // Create the background of the chip. 490 Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 491 Canvas canvas = new Canvas(tmpBitmap); 492 if (mChipBackgroundPressed != null) { 493 mChipBackgroundPressed.setBounds(0, 0, width, height); 494 mChipBackgroundPressed.draw(canvas); 495 paint.setColor(sSelectedTextColor); 496 // Vertically center the text in the chip. 497 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, 498 getTextYOffset((String) ellipsizedText, paint, height), paint); 499 // Make the delete a square. 500 Rect backgroundPadding = new Rect(); 501 mChipBackgroundPressed.getPadding(backgroundPadding); 502 mChipDelete.setBounds(width - deleteWidth + backgroundPadding.left, 503 0 + backgroundPadding.top, 504 width - backgroundPadding.right, 505 height - backgroundPadding.bottom); 506 mChipDelete.draw(canvas); 507 } else { 508 Log.w(TAG, "Unable to draw a background for the chips as it was never set"); 509 } 510 return tmpBitmap; 511 } 512 513 514 private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout, 515 boolean leaveBlankIconSpacer) { 516 // Ellipsize the text so that it takes AT MOST the entire width of the 517 // autocomplete text entry area. Make sure to leave space for padding 518 // on the sides. 519 int height = (int) mChipHeight; 520 int iconWidth = height; 521 float[] widths = new float[1]; 522 paint.getTextWidths(" ", widths); 523 CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint, 524 calculateAvailableWidth(false) - iconWidth - widths[0]); 525 // Make sure there is a minimum chip width so the user can ALWAYS 526 // tap a chip without difficulty. 527 int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, 528 ellipsizedText.length())) 529 + (mChipPadding * 2) + iconWidth); 530 531 // Create the background of the chip. 532 Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 533 Canvas canvas = new Canvas(tmpBitmap); 534 Drawable background = getChipBackground(contact); 535 if (background != null) { 536 background.setBounds(0, 0, width, height); 537 background.draw(canvas); 538 539 // Don't draw photos for recipients that have been typed in OR generated on the fly. 540 long contactId = contact.getContactId(); 541 boolean drawPhotos = isPhoneQuery() ? 542 contactId != RecipientEntry.INVALID_CONTACT 543 : (contactId != RecipientEntry.INVALID_CONTACT 544 && (contactId != RecipientEntry.GENERATED_CONTACT && 545 !TextUtils.isEmpty(contact.getDisplayName()))); 546 if (drawPhotos) { 547 byte[] photoBytes = contact.getPhotoBytes(); 548 // There may not be a photo yet if anything but the first contact address 549 // was selected. 550 if (photoBytes == null && contact.getPhotoThumbnailUri() != null) { 551 // TODO: cache this in the recipient entry? 552 ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact 553 .getPhotoThumbnailUri()); 554 photoBytes = contact.getPhotoBytes(); 555 } 556 557 Bitmap photo; 558 if (photoBytes != null) { 559 photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length); 560 } else { 561 // TODO: can the scaled down default photo be cached? 562 photo = mDefaultContactPhoto; 563 } 564 // Draw the photo on the left side. 565 if (photo != null) { 566 RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight()); 567 Rect backgroundPadding = new Rect(); 568 mChipBackground.getPadding(backgroundPadding); 569 RectF dst = new RectF(width - iconWidth + backgroundPadding.left, 570 0 + backgroundPadding.top, 571 width - backgroundPadding.right, 572 height - backgroundPadding.bottom); 573 Matrix matrix = new Matrix(); 574 matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL); 575 canvas.drawBitmap(photo, matrix, paint); 576 } 577 } else if (!leaveBlankIconSpacer || isPhoneQuery()) { 578 iconWidth = 0; 579 } 580 paint.setColor(getContext().getResources().getColor(android.R.color.black)); 581 // Vertically center the text in the chip. 582 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, 583 getTextYOffset((String)ellipsizedText, paint, height), paint); 584 } else { 585 Log.w(TAG, "Unable to draw a background for the chips as it was never set"); 586 } 587 return tmpBitmap; 588 } 589 590 /** 591 * Get the background drawable for a RecipientChip. 592 */ 593 // Visible for testing. 594 /*package*/ Drawable getChipBackground(RecipientEntry contact) { 595 return (mValidator != null && mValidator.isValid(contact.getDestination())) ? 596 mChipBackground : mInvalidChipBackground; 597 } 598 599 private float getTextYOffset(String text, TextPaint paint, int height) { 600 Rect bounds = new Rect(); 601 paint.getTextBounds(text, 0, text.length(), bounds); 602 int textHeight = bounds.bottom - bounds.top ; 603 return height - ((height - textHeight) / 2) - (int)paint.descent(); 604 } 605 606 private RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed, 607 boolean leaveIconSpace) throws NullPointerException { 608 if (mChipBackground == null) { 609 throw new NullPointerException( 610 "Unable to render any chips as setChipDimensions was not called."); 611 } 612 Layout layout = getLayout(); 613 614 TextPaint paint = getPaint(); 615 float defaultSize = paint.getTextSize(); 616 int defaultColor = paint.getColor(); 617 618 Bitmap tmpBitmap; 619 if (pressed) { 620 tmpBitmap = createSelectedChip(contact, paint, layout); 621 622 } else { 623 tmpBitmap = createUnselectedChip(contact, paint, layout, leaveIconSpace); 624 } 625 626 // Pass the full text, un-ellipsized, to the chip. 627 Drawable result = new BitmapDrawable(getResources(), tmpBitmap); 628 result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight()); 629 RecipientChip recipientChip = new RecipientChip(result, contact, offset); 630 // Return text to the original size. 631 paint.setTextSize(defaultSize); 632 paint.setColor(defaultColor); 633 return recipientChip; 634 } 635 636 /** 637 * Calculate the bottom of the line the chip will be located on using: 638 * 1) which line the chip appears on 639 * 2) the height of a chip 640 * 3) padding built into the edit text view 641 */ 642 private int calculateOffsetFromBottom(int line) { 643 // Line offsets start at zero. 644 int actualLine = getLineCount() - (line + 1); 645 return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop()) 646 + getDropDownVerticalOffset(); 647 } 648 649 /** 650 * Get the max amount of space a chip can take up. The formula takes into 651 * account the width of the EditTextView, any view padding, and padding 652 * that will be added to the chip. 653 */ 654 private float calculateAvailableWidth(boolean pressed) { 655 return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2); 656 } 657 658 659 private void setChipDimensions(Context context, AttributeSet attrs) { 660 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0, 661 0); 662 Resources r = getContext().getResources(); 663 mChipBackground = a.getDrawable(R.styleable.RecipientEditTextView_chipBackground); 664 if (mChipBackground == null) { 665 mChipBackground = r.getDrawable(R.drawable.chip_background); 666 } 667 mChipBackgroundPressed = a 668 .getDrawable(R.styleable.RecipientEditTextView_chipBackgroundPressed); 669 if (mChipBackgroundPressed == null) { 670 mChipBackgroundPressed = r.getDrawable(R.drawable.chip_background_selected); 671 } 672 mChipDelete = a.getDrawable(R.styleable.RecipientEditTextView_chipDelete); 673 if (mChipDelete == null) { 674 mChipDelete = r.getDrawable(R.drawable.chip_delete); 675 } 676 mChipPadding = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipPadding, -1); 677 if (mChipPadding == -1) { 678 mChipPadding = (int) r.getDimension(R.dimen.chip_padding); 679 } 680 mAlternatesLayout = a.getResourceId(R.styleable.RecipientEditTextView_chipAlternatesLayout, 681 -1); 682 if (mAlternatesLayout == -1) { 683 mAlternatesLayout = R.layout.chips_alternate_item; 684 } 685 686 mDefaultContactPhoto = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture); 687 688 mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.more_item, null); 689 690 mChipHeight = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipHeight, -1); 691 if (mChipHeight == -1) { 692 mChipHeight = r.getDimension(R.dimen.chip_height); 693 } 694 mChipFontSize = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipFontSize, -1); 695 if (mChipFontSize == -1) { 696 mChipFontSize = r.getDimension(R.dimen.chip_text_size); 697 } 698 mInvalidChipBackground = a 699 .getDrawable(R.styleable.RecipientEditTextView_invalidChipBackground); 700 if (mInvalidChipBackground == null) { 701 mInvalidChipBackground = r.getDrawable(R.drawable.chip_background_invalid); 702 } 703 mLineSpacingExtra = context.getResources().getDimension(R.dimen.line_spacing_extra); 704 a.recycle(); 705 } 706 707 // Visible for testing. 708 /* package */ void setMoreItem(TextView moreItem) { 709 mMoreItem = moreItem; 710 } 711 712 713 // Visible for testing. 714 /* package */ void setChipBackground(Drawable chipBackground) { 715 mChipBackground = chipBackground; 716 } 717 718 // Visible for testing. 719 /* package */ void setChipHeight(int height) { 720 mChipHeight = height; 721 } 722 723 /** 724 * Set whether to shrink the recipients field such that at most 725 * one line of recipients chips are shown when the field loses 726 * focus. By default, the number of displayed recipients will be 727 * limited and a "more" chip will be shown when focus is lost. 728 * @param shrink 729 */ 730 public void setOnFocusListShrinkRecipients(boolean shrink) { 731 mShouldShrink = shrink; 732 } 733 734 @Override 735 public void onSizeChanged(int width, int height, int oldw, int oldh) { 736 super.onSizeChanged(width, height, oldw, oldh); 737 if (width != 0 && height != 0) { 738 if (mPendingChipsCount > 0) { 739 postHandlePendingChips(); 740 } else { 741 checkChipWidths(); 742 } 743 } 744 // Try to find the scroll view parent, if it exists. 745 if (mScrollView == null && !mTriedGettingScrollView) { 746 ViewParent parent = getParent(); 747 while (parent != null && !(parent instanceof ScrollView)) { 748 parent = parent.getParent(); 749 } 750 if (parent != null) { 751 mScrollView = (ScrollView) parent; 752 } 753 mTriedGettingScrollView = true; 754 } 755 } 756 757 private void postHandlePendingChips() { 758 mHandler.removeCallbacks(mHandlePendingChips); 759 mHandler.post(mHandlePendingChips); 760 } 761 762 private void checkChipWidths() { 763 // Check the widths of the associated chips. 764 RecipientChip[] chips = getSortedRecipients(); 765 if (chips != null) { 766 Rect bounds; 767 for (RecipientChip chip : chips) { 768 bounds = chip.getDrawable().getBounds(); 769 if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) { 770 // Need to redraw that chip. 771 replaceChip(chip, chip.getEntry()); 772 } 773 } 774 } 775 } 776 777 // Visible for testing. 778 /*package*/ void handlePendingChips() { 779 if (getViewWidth() <= 0) { 780 // The widget has not been sized yet. 781 // This will be called as a result of onSizeChanged 782 // at a later point. 783 return; 784 } 785 if (mPendingChipsCount <= 0) { 786 return; 787 } 788 789 synchronized (mPendingChips) { 790 Editable editable = getText(); 791 // Tokenize! 792 if (mPendingChipsCount <= MAX_CHIPS_PARSED) { 793 for (int i = 0; i < mPendingChips.size(); i++) { 794 String current = mPendingChips.get(i); 795 int tokenStart = editable.toString().indexOf(current); 796 int tokenEnd = tokenStart + current.length(); 797 if (tokenStart >= 0) { 798 // When we have a valid token, include it with the token 799 // to the left. 800 if (tokenEnd < editable.length() - 2 801 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) { 802 tokenEnd++; 803 } 804 createReplacementChip(tokenStart, tokenEnd, editable); 805 } 806 mPendingChipsCount--; 807 } 808 sanitizeEnd(); 809 } else { 810 mNoChips = true; 811 } 812 813 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0 814 && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) { 815 if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) { 816 new RecipientReplacementTask().execute(); 817 mTemporaryRecipients = null; 818 } else { 819 // Create the "more" chip 820 mIndividualReplacements = new IndividualReplacementTask(); 821 mIndividualReplacements.execute(new ArrayList<RecipientChip>( 822 mTemporaryRecipients.subList(0, CHIP_LIMIT))); 823 if (mTemporaryRecipients.size() > CHIP_LIMIT) { 824 mTemporaryRecipients = new ArrayList<RecipientChip>( 825 mTemporaryRecipients.subList(CHIP_LIMIT, 826 mTemporaryRecipients.size())); 827 } else { 828 mTemporaryRecipients = null; 829 } 830 createMoreChip(); 831 } 832 } else { 833 // There are too many recipients to look up, so just fall back 834 // to showing addresses for all of them. 835 mTemporaryRecipients = null; 836 createMoreChip(); 837 } 838 mPendingChipsCount = 0; 839 mPendingChips.clear(); 840 } 841 } 842 843 // Visible for testing. 844 /*package*/ int getViewWidth() { 845 return getWidth(); 846 } 847 848 /** 849 * Remove any characters after the last valid chip. 850 */ 851 // Visible for testing. 852 /*package*/ void sanitizeEnd() { 853 // Don't sanitize while we are waiting for pending chips to complete. 854 if (mPendingChipsCount > 0) { 855 return; 856 } 857 // Find the last chip; eliminate any commit characters after it. 858 RecipientChip[] chips = getSortedRecipients(); 859 if (chips != null && chips.length > 0) { 860 int end; 861 ImageSpan lastSpan; 862 mMoreChip = getMoreChip(); 863 if (mMoreChip != null) { 864 lastSpan = mMoreChip; 865 } else { 866 lastSpan = getLastChip(); 867 } 868 end = getSpannable().getSpanEnd(lastSpan); 869 Editable editable = getText(); 870 int length = editable.length(); 871 if (length > end) { 872 // See what characters occur after that and eliminate them. 873 if (Log.isLoggable(TAG, Log.DEBUG)) { 874 Log.d(TAG, "There were extra characters after the last tokenizable entry." 875 + editable); 876 } 877 editable.delete(end + 1, length); 878 } 879 } 880 } 881 882 /** 883 * Create a chip that represents just the email address of a recipient. At some later 884 * point, this chip will be attached to a real contact entry, if one exists. 885 */ 886 private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) { 887 if (alreadyHasChip(tokenStart, tokenEnd)) { 888 // There is already a chip present at this location. 889 // Don't recreate it. 890 return; 891 } 892 String token = editable.toString().substring(tokenStart, tokenEnd); 893 int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA); 894 if (commitCharIndex == token.length() - 1) { 895 token = token.substring(0, token.length() - 1); 896 } 897 RecipientEntry entry = createTokenizedEntry(token); 898 if (entry != null) { 899 String destText = createAddressText(entry); 900 SpannableString chipText = new SpannableString(destText); 901 int end = getSelectionEnd(); 902 int start = mTokenizer != null ? mTokenizer.findTokenStart(getText(), end) : 0; 903 RecipientChip chip = null; 904 try { 905 if (!mNoChips) { 906 /* leave space for the contact icon if this is not just an email address */ 907 chip = constructChipSpan( 908 entry, 909 start, 910 false, 911 TextUtils.isEmpty(entry.getDisplayName()) 912 || TextUtils.equals(entry.getDisplayName(), 913 entry.getDestination())); 914 } 915 } catch (NullPointerException e) { 916 Log.e(TAG, e.getMessage(), e); 917 } 918 editable.setSpan(chip, tokenStart, tokenEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 919 // Add this chip to the list of entries "to replace" 920 if (chip != null) { 921 if (mTemporaryRecipients == null) { 922 mTemporaryRecipients = new ArrayList<RecipientChip>(); 923 } 924 chip.setOriginalText(chipText.toString()); 925 mTemporaryRecipients.add(chip); 926 } 927 } 928 } 929 930 private static boolean isPhoneNumber(String number) { 931 // TODO: replace this function with libphonenumber's isPossibleNumber (see 932 // PhoneNumberUtil). One complication is that it requires the sender's region which 933 // comes from the CurrentCountryIso. For now, let's just do this simple match. 934 if (TextUtils.isEmpty(number)) { 935 return false; 936 } 937 938 Matcher match = Patterns.PHONE.matcher(number); 939 return match.matches(); 940 } 941 942 private RecipientEntry createTokenizedEntry(String token) { 943 if (TextUtils.isEmpty(token)) { 944 return null; 945 } 946 if (isPhoneQuery() && isPhoneNumber(token)) { 947 return RecipientEntry 948 .constructFakeEntry(token); 949 } 950 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token); 951 String display = null; 952 if (isValid(token) && tokens != null && tokens.length > 0) { 953 // If we can get a name from tokenizing, then generate an entry from 954 // this. 955 display = tokens[0].getName(); 956 if (!TextUtils.isEmpty(display)) { 957 if (!isPhoneQuery()) { 958 if (!TextUtils.isEmpty(token)) { 959 token = token.trim(); 960 } 961 char charAt = token.charAt(token.length() - 1); 962 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) { 963 token = token.substring(0, token.length() - 1); 964 } 965 } 966 return RecipientEntry.constructGeneratedEntry(display, token); 967 } else { 968 display = tokens[0].getAddress(); 969 if (!TextUtils.isEmpty(display)) { 970 return RecipientEntry.constructFakeEntry(display); 971 } 972 } 973 } 974 // Unable to validate the token or to create a valid token from it. 975 // Just create a chip the user can edit. 976 String validatedToken = null; 977 if (mValidator != null && !mValidator.isValid(token)) { 978 // Try fixing up the entry using the validator. 979 validatedToken = mValidator.fixText(token).toString(); 980 if (!TextUtils.isEmpty(validatedToken)) { 981 if (validatedToken.contains(token)) { 982 // protect against the case of a validator with a null domain, 983 // which doesn't add a domain to the token 984 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken); 985 if (tokenized.length > 0) { 986 validatedToken = tokenized[0].getAddress(); 987 } 988 } else { 989 // We ran into a case where the token was invalid and removed 990 // by the validator. In this case, just use the original token 991 // and let the user sort out the error chip. 992 validatedToken = null; 993 } 994 } 995 } 996 // Otherwise, fallback to just creating an editable email address chip. 997 return RecipientEntry 998 .constructFakeEntry(!TextUtils.isEmpty(validatedToken) ? validatedToken : token); 999 } 1000 1001 private boolean isValid(String text) { 1002 return mValidator == null ? true : mValidator.isValid(text); 1003 } 1004 1005 private String tokenizeAddress(String destination) { 1006 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination); 1007 if (tokens != null && tokens.length > 0) { 1008 return tokens[0].getAddress(); 1009 } 1010 return destination; 1011 } 1012 1013 @Override 1014 public void setTokenizer(Tokenizer tokenizer) { 1015 mTokenizer = tokenizer; 1016 super.setTokenizer(mTokenizer); 1017 } 1018 1019 @Override 1020 public void setValidator(Validator validator) { 1021 mValidator = validator; 1022 super.setValidator(validator); 1023 } 1024 1025 /** 1026 * We cannot use the default mechanism for replaceText. Instead, 1027 * we override onItemClickListener so we can get all the associated 1028 * contact information including display text, address, and id. 1029 */ 1030 @Override 1031 protected void replaceText(CharSequence text) { 1032 return; 1033 } 1034 1035 /** 1036 * Dismiss any selected chips when the back key is pressed. 1037 */ 1038 @Override 1039 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 1040 if (keyCode == KeyEvent.KEYCODE_BACK && mSelectedChip != null) { 1041 clearSelectedChip(); 1042 return true; 1043 } 1044 return super.onKeyPreIme(keyCode, event); 1045 } 1046 1047 /** 1048 * Monitor key presses in this view to see if the user types 1049 * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER. 1050 * If the user has entered text that has contact matches and types 1051 * a commit key, create a chip from the topmost matching contact. 1052 * If the user has entered text that has no contact matches and types 1053 * a commit key, then create a chip from the text they have entered. 1054 */ 1055 @Override 1056 public boolean onKeyUp(int keyCode, KeyEvent event) { 1057 switch (keyCode) { 1058 case KeyEvent.KEYCODE_ENTER: 1059 case KeyEvent.KEYCODE_DPAD_CENTER: 1060 if (event.hasNoModifiers()) { 1061 if (commitDefault()) { 1062 return true; 1063 } 1064 if (mSelectedChip != null) { 1065 clearSelectedChip(); 1066 return true; 1067 } else if (focusNext()) { 1068 return true; 1069 } 1070 } 1071 break; 1072 case KeyEvent.KEYCODE_TAB: 1073 if (event.hasNoModifiers()) { 1074 if (mSelectedChip != null) { 1075 clearSelectedChip(); 1076 } else { 1077 commitDefault(); 1078 } 1079 if (focusNext()) { 1080 return true; 1081 } 1082 } 1083 break; 1084 } 1085 return super.onKeyUp(keyCode, event); 1086 } 1087 1088 private boolean focusNext() { 1089 View next = focusSearch(View.FOCUS_DOWN); 1090 if (next != null) { 1091 next.requestFocus(); 1092 return true; 1093 } 1094 return false; 1095 } 1096 1097 /** 1098 * Create a chip from the default selection. If the popup is showing, the 1099 * default is the first item in the popup suggestions list. Otherwise, it is 1100 * whatever the user had typed in. End represents where the the tokenizer 1101 * should search for a token to turn into a chip. 1102 * @return If a chip was created from a real contact. 1103 */ 1104 private boolean commitDefault() { 1105 // If there is no tokenizer, don't try to commit. 1106 if (mTokenizer == null) { 1107 return false; 1108 } 1109 Editable editable = getText(); 1110 int end = getSelectionEnd(); 1111 int start = mTokenizer.findTokenStart(editable, end); 1112 1113 if (shouldCreateChip(start, end)) { 1114 int whatEnd = mTokenizer.findTokenEnd(getText(), start); 1115 // In the middle of chip; treat this as an edit 1116 // and commit the whole token. 1117 whatEnd = movePastTerminators(whatEnd); 1118 if (whatEnd != getSelectionEnd()) { 1119 handleEdit(start, whatEnd); 1120 return true; 1121 } 1122 return commitChip(start, end , editable); 1123 } 1124 return false; 1125 } 1126 1127 private void commitByCharacter() { 1128 // We can't possibly commit by character if we can't tokenize. 1129 if (mTokenizer == null) { 1130 return; 1131 } 1132 Editable editable = getText(); 1133 int end = getSelectionEnd(); 1134 int start = mTokenizer.findTokenStart(editable, end); 1135 if (shouldCreateChip(start, end)) { 1136 commitChip(start, end, editable); 1137 } 1138 setSelection(getText().length()); 1139 } 1140 1141 private boolean commitChip(int start, int end, Editable editable) { 1142 ListAdapter adapter = getAdapter(); 1143 if (adapter != null && adapter.getCount() > 0 && enoughToFilter() 1144 && end == getSelectionEnd() && !isPhoneQuery()) { 1145 // choose the first entry. 1146 submitItemAtPosition(0); 1147 dismissDropDown(); 1148 return true; 1149 } else { 1150 int tokenEnd = mTokenizer.findTokenEnd(editable, start); 1151 if (editable.length() > tokenEnd + 1) { 1152 char charAt = editable.charAt(tokenEnd + 1); 1153 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) { 1154 tokenEnd++; 1155 } 1156 } 1157 String text = editable.toString().substring(start, tokenEnd).trim(); 1158 clearComposingText(); 1159 if (text != null && text.length() > 0 && !text.equals(" ")) { 1160 RecipientEntry entry = createTokenizedEntry(text); 1161 if (entry != null) { 1162 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1163 CharSequence chipText = createChip(entry, false); 1164 if (chipText != null && start > -1 && end > -1) { 1165 editable.replace(start, end, chipText); 1166 } 1167 } 1168 // Only dismiss the dropdown if it is related to the text we 1169 // just committed. 1170 // For paste, it may not be as there are possibly multiple 1171 // tokens being added. 1172 if (end == getSelectionEnd()) { 1173 dismissDropDown(); 1174 } 1175 sanitizeBetween(); 1176 return true; 1177 } 1178 } 1179 return false; 1180 } 1181 1182 // Visible for testing. 1183 /* package */ void sanitizeBetween() { 1184 // Don't sanitize while we are waiting for content to chipify. 1185 if (mPendingChipsCount > 0) { 1186 return; 1187 } 1188 // Find the last chip. 1189 RecipientChip[] recips = getSortedRecipients(); 1190 if (recips != null && recips.length > 0) { 1191 RecipientChip last = recips[recips.length - 1]; 1192 RecipientChip beforeLast = null; 1193 if (recips.length > 1) { 1194 beforeLast = recips[recips.length - 2]; 1195 } 1196 int startLooking = 0; 1197 int end = getSpannable().getSpanStart(last); 1198 if (beforeLast != null) { 1199 startLooking = getSpannable().getSpanEnd(beforeLast); 1200 Editable text = getText(); 1201 if (startLooking == -1 || startLooking > text.length() - 1) { 1202 // There is nothing after this chip. 1203 return; 1204 } 1205 if (text.charAt(startLooking) == ' ') { 1206 startLooking++; 1207 } 1208 } 1209 if (startLooking >= 0 && end >= 0 && startLooking < end) { 1210 getText().delete(startLooking, end); 1211 } 1212 } 1213 } 1214 1215 private boolean shouldCreateChip(int start, int end) { 1216 return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end); 1217 } 1218 1219 private boolean alreadyHasChip(int start, int end) { 1220 if (mNoChips) { 1221 return true; 1222 } 1223 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); 1224 if ((chips == null || chips.length == 0)) { 1225 return false; 1226 } 1227 return true; 1228 } 1229 1230 private void handleEdit(int start, int end) { 1231 if (start == -1 || end == -1) { 1232 // This chip no longer exists in the field. 1233 dismissDropDown(); 1234 return; 1235 } 1236 // This is in the middle of a chip, so select out the whole chip 1237 // and commit it. 1238 Editable editable = getText(); 1239 setSelection(end); 1240 String text = getText().toString().substring(start, end); 1241 if (!TextUtils.isEmpty(text)) { 1242 RecipientEntry entry = RecipientEntry.constructFakeEntry(text); 1243 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1244 CharSequence chipText = createChip(entry, false); 1245 int selEnd = getSelectionEnd(); 1246 if (chipText != null && start > -1 && selEnd > -1) { 1247 editable.replace(start, selEnd, chipText); 1248 } 1249 } 1250 dismissDropDown(); 1251 } 1252 1253 /** 1254 * If there is a selected chip, delegate the key events 1255 * to the selected chip. 1256 */ 1257 @Override 1258 public boolean onKeyDown(int keyCode, KeyEvent event) { 1259 if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) { 1260 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 1261 mAlternatesPopup.dismiss(); 1262 } 1263 removeChip(mSelectedChip); 1264 } 1265 1266 if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) { 1267 return true; 1268 } 1269 1270 return super.onKeyDown(keyCode, event); 1271 } 1272 1273 // Visible for testing. 1274 /* package */ Spannable getSpannable() { 1275 return getText(); 1276 } 1277 1278 private int getChipStart(RecipientChip chip) { 1279 return getSpannable().getSpanStart(chip); 1280 } 1281 1282 private int getChipEnd(RecipientChip chip) { 1283 return getSpannable().getSpanEnd(chip); 1284 } 1285 1286 /** 1287 * Instead of filtering on the entire contents of the edit box, 1288 * this subclass method filters on the range from 1289 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd} 1290 * if the length of that range meets or exceeds {@link #getThreshold} 1291 * and makes sure that the range is not already a Chip. 1292 */ 1293 @Override 1294 protected void performFiltering(CharSequence text, int keyCode) { 1295 if (enoughToFilter() && !isCompletedToken(text)) { 1296 int end = getSelectionEnd(); 1297 int start = mTokenizer.findTokenStart(text, end); 1298 // If this is a RecipientChip, don't filter 1299 // on its contents. 1300 Spannable span = getSpannable(); 1301 RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class); 1302 if (chips != null && chips.length > 0) { 1303 return; 1304 } 1305 } 1306 super.performFiltering(text, keyCode); 1307 } 1308 1309 // Visible for testing. 1310 /*package*/ boolean isCompletedToken(CharSequence text) { 1311 if (TextUtils.isEmpty(text)) { 1312 return false; 1313 } 1314 // Check to see if this is a completed token before filtering. 1315 int end = text.length(); 1316 int start = mTokenizer.findTokenStart(text, end); 1317 String token = text.toString().substring(start, end).trim(); 1318 if (!TextUtils.isEmpty(token)) { 1319 char atEnd = token.charAt(token.length() - 1); 1320 return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON; 1321 } 1322 return false; 1323 } 1324 1325 private void clearSelectedChip() { 1326 if (mSelectedChip != null) { 1327 unselectChip(mSelectedChip); 1328 mSelectedChip = null; 1329 } 1330 setCursorVisible(true); 1331 } 1332 1333 /** 1334 * Monitor touch events in the RecipientEditTextView. 1335 * If the view does not have focus, any tap on the view 1336 * will just focus the view. If the view has focus, determine 1337 * if the touch target is a recipient chip. If it is and the chip 1338 * is not selected, select it and clear any other selected chips. 1339 * If it isn't, then select that chip. 1340 */ 1341 @Override 1342 public boolean onTouchEvent(MotionEvent event) { 1343 if (!isFocused()) { 1344 // Ignore any chip taps until this view is focused. 1345 return super.onTouchEvent(event); 1346 } 1347 boolean handled = super.onTouchEvent(event); 1348 int action = event.getAction(); 1349 boolean chipWasSelected = false; 1350 if (mSelectedChip == null) { 1351 mGestureDetector.onTouchEvent(event); 1352 } 1353 if (mCopyAddress == null && action == MotionEvent.ACTION_UP) { 1354 float x = event.getX(); 1355 float y = event.getY(); 1356 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 1357 RecipientChip currentChip = findChip(offset); 1358 if (currentChip != null) { 1359 if (action == MotionEvent.ACTION_UP) { 1360 if (mSelectedChip != null && mSelectedChip != currentChip) { 1361 clearSelectedChip(); 1362 mSelectedChip = selectChip(currentChip); 1363 } else if (mSelectedChip == null) { 1364 setSelection(getText().length()); 1365 commitDefault(); 1366 mSelectedChip = selectChip(currentChip); 1367 } else { 1368 onClick(mSelectedChip, offset, x, y); 1369 } 1370 } 1371 chipWasSelected = true; 1372 handled = true; 1373 } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) { 1374 chipWasSelected = true; 1375 } 1376 } 1377 if (action == MotionEvent.ACTION_UP && !chipWasSelected) { 1378 clearSelectedChip(); 1379 } 1380 return handled; 1381 } 1382 1383 private void scrollLineIntoView(int line) { 1384 if (mScrollView != null) { 1385 mScrollView.scrollBy(0, calculateOffsetFromBottom(line)); 1386 } 1387 } 1388 1389 private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup, 1390 int width, Context context) { 1391 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1392 int bottom; 1393 if (line == getLineCount() -1) { 1394 bottom = 0; 1395 } else { 1396 bottom = -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math.abs(getLineCount() - 1 1397 - line))); 1398 } 1399 // Align the alternates popup with the left side of the View, 1400 // regardless of the position of the chip tapped. 1401 alternatesPopup.setWidth(width); 1402 alternatesPopup.setAnchorView(this); 1403 alternatesPopup.setVerticalOffset(bottom); 1404 alternatesPopup.setAdapter(createAlternatesAdapter(currentChip)); 1405 alternatesPopup.setOnItemClickListener(mAlternatesListener); 1406 // Clear the checked item. 1407 mCheckedItem = -1; 1408 alternatesPopup.show(); 1409 ListView listView = alternatesPopup.getListView(); 1410 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1411 // Checked item would be -1 if the adapter has not 1412 // loaded the view that should be checked yet. The 1413 // variable will be set correctly when onCheckedItemChanged 1414 // is called in a separate thread. 1415 if (mCheckedItem != -1) { 1416 listView.setItemChecked(mCheckedItem, true); 1417 mCheckedItem = -1; 1418 } 1419 } 1420 1421 private ListAdapter createAlternatesAdapter(RecipientChip chip) { 1422 return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(), 1423 mAlternatesLayout, ((BaseRecipientAdapter)getAdapter()).getQueryType(), this); 1424 } 1425 1426 private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) { 1427 return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip 1428 .getEntry()); 1429 } 1430 1431 @Override 1432 public void onCheckedItemChanged(int position) { 1433 ListView listView = mAlternatesPopup.getListView(); 1434 if (listView != null && listView.getCheckedItemCount() == 0) { 1435 listView.setItemChecked(position, true); 1436 } 1437 mCheckedItem = position; 1438 } 1439 1440 // TODO: This algorithm will need a lot of tweaking after more people have used 1441 // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring 1442 // what comes before the finger. 1443 private int putOffsetInRange(int o) { 1444 int offset = o; 1445 Editable text = getText(); 1446 int length = text.length(); 1447 // Remove whitespace from end to find "real end" 1448 int realLength = length; 1449 for (int i = length - 1; i >= 0; i--) { 1450 if (text.charAt(i) == ' ') { 1451 realLength--; 1452 } else { 1453 break; 1454 } 1455 } 1456 1457 // If the offset is beyond or at the end of the text, 1458 // leave it alone. 1459 if (offset >= realLength) { 1460 return offset; 1461 } 1462 Editable editable = getText(); 1463 while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) { 1464 // Keep walking backward! 1465 offset--; 1466 } 1467 return offset; 1468 } 1469 1470 private int findText(Editable text, int offset) { 1471 if (text.charAt(offset) != ' ') { 1472 return offset; 1473 } 1474 return -1; 1475 } 1476 1477 private RecipientChip findChip(int offset) { 1478 RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class); 1479 // Find the chip that contains this offset. 1480 for (int i = 0; i < chips.length; i++) { 1481 RecipientChip chip = chips[i]; 1482 int start = getChipStart(chip); 1483 int end = getChipEnd(chip); 1484 if (offset >= start && offset <= end) { 1485 return chip; 1486 } 1487 } 1488 return null; 1489 } 1490 1491 // Visible for testing. 1492 // Use this method to generate text to add to the list of addresses. 1493 /* package */String createAddressText(RecipientEntry entry) { 1494 String display = entry.getDisplayName(); 1495 String address = entry.getDestination(); 1496 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1497 display = null; 1498 } 1499 String trimmedDisplayText; 1500 if (isPhoneQuery() && isPhoneNumber(address)) { 1501 trimmedDisplayText = address.trim(); 1502 } else { 1503 if (address != null) { 1504 // Tokenize out the address in case the address already 1505 // contained the username as well. 1506 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1507 if (tokenized != null && tokenized.length > 0) { 1508 address = tokenized[0].getAddress(); 1509 } 1510 } 1511 Rfc822Token token = new Rfc822Token(display, address, null); 1512 trimmedDisplayText = token.toString().trim(); 1513 } 1514 int index = trimmedDisplayText.indexOf(","); 1515 return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText) 1516 && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer 1517 .terminateToken(trimmedDisplayText) : trimmedDisplayText; 1518 } 1519 1520 // Visible for testing. 1521 // Use this method to generate text to display in a chip. 1522 /*package*/ String createChipDisplayText(RecipientEntry entry) { 1523 String display = entry.getDisplayName(); 1524 String address = entry.getDestination(); 1525 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1526 display = null; 1527 } 1528 if (address != null && !(isPhoneQuery() && isPhoneNumber(address))) { 1529 // Tokenize out the address in case the address already 1530 // contained the username as well. 1531 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1532 if (tokenized != null && tokenized.length > 0) { 1533 address = tokenized[0].getAddress(); 1534 } 1535 } 1536 if (!TextUtils.isEmpty(display)) { 1537 return display; 1538 } else if (!TextUtils.isEmpty(address)){ 1539 return address; 1540 } else { 1541 return new Rfc822Token(display, address, null).toString(); 1542 } 1543 } 1544 1545 private CharSequence createChip(RecipientEntry entry, boolean pressed) { 1546 String displayText = createAddressText(entry); 1547 if (TextUtils.isEmpty(displayText)) { 1548 return null; 1549 } 1550 SpannableString chipText = null; 1551 // Always leave a blank space at the end of a chip. 1552 int end = getSelectionEnd(); 1553 int start = mTokenizer.findTokenStart(getText(), end); 1554 int textLength = displayText.length()-1; 1555 chipText = new SpannableString(displayText); 1556 if (!mNoChips) { 1557 try { 1558 RecipientChip chip = constructChipSpan(entry, start, pressed, 1559 false /* leave space for contact icon */); 1560 chipText.setSpan(chip, 0, textLength, 1561 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1562 chip.setOriginalText(chipText.toString()); 1563 } catch (NullPointerException e) { 1564 Log.e(TAG, e.getMessage(), e); 1565 return null; 1566 } 1567 } 1568 return chipText; 1569 } 1570 1571 /** 1572 * When an item in the suggestions list has been clicked, create a chip from the 1573 * contact information of the selected item. 1574 */ 1575 @Override 1576 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1577 submitItemAtPosition(position); 1578 } 1579 1580 private void submitItemAtPosition(int position) { 1581 RecipientEntry entry = createValidatedEntry( 1582 (RecipientEntry)getAdapter().getItem(position)); 1583 if (entry == null) { 1584 return; 1585 } 1586 clearComposingText(); 1587 1588 int end = getSelectionEnd(); 1589 int start = mTokenizer.findTokenStart(getText(), end); 1590 1591 Editable editable = getText(); 1592 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1593 CharSequence chip = createChip(entry, false); 1594 if (chip != null && start >= 0 && end >= 0) { 1595 editable.replace(start, end, chip); 1596 } 1597 sanitizeBetween(); 1598 } 1599 1600 private RecipientEntry createValidatedEntry(RecipientEntry item) { 1601 if (item == null) { 1602 return null; 1603 } 1604 final RecipientEntry entry; 1605 // If the display name and the address are the same, or if this is a 1606 // valid contact, but the destination is invalid, then make this a fake 1607 // recipient that is editable. 1608 String destination = item.getDestination(); 1609 if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1610 entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(), 1611 destination); 1612 } else if (RecipientEntry.isCreatedRecipient(item.getContactId()) 1613 && (TextUtils.isEmpty(item.getDisplayName()) 1614 || TextUtils.equals(item.getDisplayName(), destination) 1615 || (mValidator != null && !mValidator.isValid(destination)))) { 1616 entry = RecipientEntry.constructFakeEntry(destination); 1617 } else { 1618 entry = item; 1619 } 1620 return entry; 1621 } 1622 1623 /** Returns a collection of contact Id for each chip inside this View. */ 1624 /* package */ Collection<Long> getContactIds() { 1625 final Set<Long> result = new HashSet<Long>(); 1626 RecipientChip[] chips = getSortedRecipients(); 1627 if (chips != null) { 1628 for (RecipientChip chip : chips) { 1629 result.add(chip.getContactId()); 1630 } 1631 } 1632 return result; 1633 } 1634 1635 1636 /** Returns a collection of data Id for each chip inside this View. May be null. */ 1637 /* package */ Collection<Long> getDataIds() { 1638 final Set<Long> result = new HashSet<Long>(); 1639 RecipientChip [] chips = getSortedRecipients(); 1640 if (chips != null) { 1641 for (RecipientChip chip : chips) { 1642 result.add(chip.getDataId()); 1643 } 1644 } 1645 return result; 1646 } 1647 1648 // Visible for testing. 1649 /* package */RecipientChip[] getSortedRecipients() { 1650 RecipientChip[] recips = getSpannable() 1651 .getSpans(0, getText().length(), RecipientChip.class); 1652 ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays 1653 .asList(recips)); 1654 final Spannable spannable = getSpannable(); 1655 Collections.sort(recipientsList, new Comparator<RecipientChip>() { 1656 1657 @Override 1658 public int compare(RecipientChip first, RecipientChip second) { 1659 int firstStart = spannable.getSpanStart(first); 1660 int secondStart = spannable.getSpanStart(second); 1661 if (firstStart < secondStart) { 1662 return -1; 1663 } else if (firstStart > secondStart) { 1664 return 1; 1665 } else { 1666 return 0; 1667 } 1668 } 1669 }); 1670 return recipientsList.toArray(new RecipientChip[recipientsList.size()]); 1671 } 1672 1673 @Override 1674 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 1675 return false; 1676 } 1677 1678 @Override 1679 public void onDestroyActionMode(ActionMode mode) { 1680 } 1681 1682 @Override 1683 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 1684 return false; 1685 } 1686 1687 /** 1688 * No chips are selectable. 1689 */ 1690 @Override 1691 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 1692 return false; 1693 } 1694 1695 // Visible for testing. 1696 /* package */ImageSpan getMoreChip() { 1697 MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(), 1698 MoreImageSpan.class); 1699 return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null; 1700 } 1701 1702 private MoreImageSpan createMoreSpan(int count) { 1703 String moreText = String.format(mMoreItem.getText().toString(), count); 1704 TextPaint morePaint = new TextPaint(getPaint()); 1705 morePaint.setTextSize(mMoreItem.getTextSize()); 1706 morePaint.setColor(mMoreItem.getCurrentTextColor()); 1707 int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft() 1708 + mMoreItem.getPaddingRight(); 1709 int height = getLineHeight(); 1710 Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 1711 Canvas canvas = new Canvas(drawable); 1712 int adjustedHeight = height; 1713 Layout layout = getLayout(); 1714 if (layout != null) { 1715 adjustedHeight -= layout.getLineDescent(0); 1716 } 1717 canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint); 1718 1719 Drawable result = new BitmapDrawable(getResources(), drawable); 1720 result.setBounds(0, 0, width, height); 1721 return new MoreImageSpan(result); 1722 } 1723 1724 // Visible for testing. 1725 /*package*/ void createMoreChipPlainText() { 1726 // Take the first <= CHIP_LIMIT addresses and get to the end of the second one. 1727 Editable text = getText(); 1728 int start = 0; 1729 int end = start; 1730 for (int i = 0; i < CHIP_LIMIT; i++) { 1731 end = movePastTerminators(mTokenizer.findTokenEnd(text, start)); 1732 start = end; // move to the next token and get its end. 1733 } 1734 // Now, count total addresses. 1735 start = 0; 1736 int tokenCount = countTokens(text); 1737 MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT); 1738 SpannableString chipText = new SpannableString(text.subSequence(end, text.length())); 1739 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1740 text.replace(end, text.length(), chipText); 1741 mMoreChip = moreSpan; 1742 } 1743 1744 // Visible for testing. 1745 /* package */int countTokens(Editable text) { 1746 int tokenCount = 0; 1747 int start = 0; 1748 while (start < text.length()) { 1749 start = movePastTerminators(mTokenizer.findTokenEnd(text, start)); 1750 tokenCount++; 1751 if (start >= text.length()) { 1752 break; 1753 } 1754 } 1755 return tokenCount; 1756 } 1757 1758 /** 1759 * Create the more chip. The more chip is text that replaces any chips that 1760 * do not fit in the pre-defined available space when the 1761 * RecipientEditTextView loses focus. 1762 */ 1763 // Visible for testing. 1764 /* package */ void createMoreChip() { 1765 if (mNoChips) { 1766 createMoreChipPlainText(); 1767 return; 1768 } 1769 1770 if (!mShouldShrink) { 1771 return; 1772 } 1773 ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class); 1774 if (tempMore.length > 0) { 1775 getSpannable().removeSpan(tempMore[0]); 1776 } 1777 RecipientChip[] recipients = getSortedRecipients(); 1778 1779 if (recipients == null || recipients.length <= CHIP_LIMIT) { 1780 mMoreChip = null; 1781 return; 1782 } 1783 Spannable spannable = getSpannable(); 1784 int numRecipients = recipients.length; 1785 int overage = numRecipients - CHIP_LIMIT; 1786 MoreImageSpan moreSpan = createMoreSpan(overage); 1787 mRemovedSpans = new ArrayList<RecipientChip>(); 1788 int totalReplaceStart = 0; 1789 int totalReplaceEnd = 0; 1790 Editable text = getText(); 1791 for (int i = numRecipients - overage; i < recipients.length; i++) { 1792 mRemovedSpans.add(recipients[i]); 1793 if (i == numRecipients - overage) { 1794 totalReplaceStart = spannable.getSpanStart(recipients[i]); 1795 } 1796 if (i == recipients.length - 1) { 1797 totalReplaceEnd = spannable.getSpanEnd(recipients[i]); 1798 } 1799 if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) { 1800 int spanStart = spannable.getSpanStart(recipients[i]); 1801 int spanEnd = spannable.getSpanEnd(recipients[i]); 1802 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd)); 1803 } 1804 spannable.removeSpan(recipients[i]); 1805 } 1806 if (totalReplaceEnd < text.length()) { 1807 totalReplaceEnd = text.length(); 1808 } 1809 int end = Math.max(totalReplaceStart, totalReplaceEnd); 1810 int start = Math.min(totalReplaceStart, totalReplaceEnd); 1811 SpannableString chipText = new SpannableString(text.subSequence(start, end)); 1812 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1813 text.replace(start, end, chipText); 1814 mMoreChip = moreSpan; 1815 // If adding the +more chip goes over the limit, resize accordingly. 1816 if (!isPhoneQuery() && getLineCount() > mMaxLines) { 1817 setMaxLines(getLineCount()); 1818 } 1819 } 1820 1821 /** 1822 * Replace the more chip, if it exists, with all of the recipient chips it had 1823 * replaced when the RecipientEditTextView gains focus. 1824 */ 1825 // Visible for testing. 1826 /*package*/ void removeMoreChip() { 1827 if (mMoreChip != null) { 1828 Spannable span = getSpannable(); 1829 span.removeSpan(mMoreChip); 1830 mMoreChip = null; 1831 // Re-add the spans that were removed. 1832 if (mRemovedSpans != null && mRemovedSpans.size() > 0) { 1833 // Recreate each removed span. 1834 RecipientChip[] recipients = getSortedRecipients(); 1835 // Start the search for tokens after the last currently visible 1836 // chip. 1837 if (recipients == null || recipients.length == 0) { 1838 return; 1839 } 1840 int end = span.getSpanEnd(recipients[recipients.length - 1]); 1841 Editable editable = getText(); 1842 for (RecipientChip chip : mRemovedSpans) { 1843 int chipStart; 1844 int chipEnd; 1845 String token; 1846 // Need to find the location of the chip, again. 1847 token = (String) chip.getOriginalText(); 1848 // As we find the matching recipient for the remove spans, 1849 // reduce the size of the string we need to search. 1850 // That way, if there are duplicates, we always find the correct 1851 // recipient. 1852 chipStart = editable.toString().indexOf(token, end); 1853 end = chipEnd = Math.min(editable.length(), chipStart + token.length()); 1854 // Only set the span if we found a matching token. 1855 if (chipStart != -1) { 1856 editable.setSpan(chip, chipStart, chipEnd, 1857 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 1858 } 1859 } 1860 mRemovedSpans.clear(); 1861 } 1862 } 1863 } 1864 1865 /** 1866 * Show specified chip as selected. If the RecipientChip is just an email address, 1867 * selecting the chip will take the contents of the chip and place it at 1868 * the end of the RecipientEditTextView for inline editing. If the 1869 * RecipientChip is a complete contact, then selecting the chip 1870 * will change the background color of the chip, show the delete icon, 1871 * and a popup window with the address in use highlighted and any other 1872 * alternate addresses for the contact. 1873 * @param currentChip Chip to select. 1874 * @return A RecipientChip in the selected state or null if the chip 1875 * just contained an email address. 1876 */ 1877 private RecipientChip selectChip(RecipientChip currentChip) { 1878 if (shouldShowEditableText(currentChip)) { 1879 CharSequence text = currentChip.getValue(); 1880 Editable editable = getText(); 1881 getSpannable().removeSpan(currentChip); 1882 setCursorVisible(true); 1883 setSelection(editable.length()); 1884 return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1); 1885 } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1886 int start = getChipStart(currentChip); 1887 int end = getChipEnd(currentChip); 1888 getSpannable().removeSpan(currentChip); 1889 RecipientChip newChip; 1890 try { 1891 if (mNoChips) { 1892 return null; 1893 } 1894 newChip = constructChipSpan(currentChip.getEntry(), start, true, false); 1895 } catch (NullPointerException e) { 1896 Log.e(TAG, e.getMessage(), e); 1897 return null; 1898 } 1899 Editable editable = getText(); 1900 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1901 if (start == -1 || end == -1) { 1902 Log.d(TAG, "The chip being selected no longer exists but should."); 1903 } else { 1904 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1905 } 1906 newChip.setSelected(true); 1907 if (shouldShowEditableText(newChip)) { 1908 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1909 } 1910 showAddress(newChip, mAddressPopup, getWidth(), getContext()); 1911 setCursorVisible(false); 1912 return newChip; 1913 } else { 1914 int start = getChipStart(currentChip); 1915 int end = getChipEnd(currentChip); 1916 getSpannable().removeSpan(currentChip); 1917 RecipientChip newChip; 1918 try { 1919 newChip = constructChipSpan(currentChip.getEntry(), start, true, false); 1920 } catch (NullPointerException e) { 1921 Log.e(TAG, e.getMessage(), e); 1922 return null; 1923 } 1924 Editable editable = getText(); 1925 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1926 if (start == -1 || end == -1) { 1927 Log.d(TAG, "The chip being selected no longer exists but should."); 1928 } else { 1929 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1930 } 1931 newChip.setSelected(true); 1932 if (shouldShowEditableText(newChip)) { 1933 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1934 } 1935 showAlternates(newChip, mAlternatesPopup, getWidth(), getContext()); 1936 setCursorVisible(false); 1937 return newChip; 1938 } 1939 } 1940 1941 private boolean shouldShowEditableText(RecipientChip currentChip) { 1942 long contactId = currentChip.getContactId(); 1943 return contactId == RecipientEntry.INVALID_CONTACT 1944 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT); 1945 } 1946 1947 private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup, 1948 int width, Context context) { 1949 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1950 int bottom = calculateOffsetFromBottom(line); 1951 // Align the alternates popup with the left side of the View, 1952 // regardless of the position of the chip tapped. 1953 popup.setWidth(width); 1954 popup.setAnchorView(this); 1955 popup.setVerticalOffset(bottom); 1956 popup.setAdapter(createSingleAddressAdapter(currentChip)); 1957 popup.setOnItemClickListener(new OnItemClickListener() { 1958 @Override 1959 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1960 unselectChip(currentChip); 1961 popup.dismiss(); 1962 } 1963 }); 1964 popup.show(); 1965 ListView listView = popup.getListView(); 1966 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1967 listView.setItemChecked(0, true); 1968 } 1969 1970 /** 1971 * Remove selection from this chip. Unselecting a RecipientChip will render 1972 * the chip without a delete icon and with an unfocused background. This is 1973 * called when the RecipientChip no longer has focus. 1974 */ 1975 private void unselectChip(RecipientChip chip) { 1976 int start = getChipStart(chip); 1977 int end = getChipEnd(chip); 1978 Editable editable = getText(); 1979 mSelectedChip = null; 1980 if (start == -1 || end == -1) { 1981 Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing"); 1982 setSelection(editable.length()); 1983 commitDefault(); 1984 } else { 1985 getSpannable().removeSpan(chip); 1986 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1987 editable.removeSpan(chip); 1988 try { 1989 if (!mNoChips) { 1990 editable.setSpan(constructChipSpan(chip.getEntry(), start, false, false), 1991 start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1992 } 1993 } catch (NullPointerException e) { 1994 Log.e(TAG, e.getMessage(), e); 1995 } 1996 } 1997 setCursorVisible(true); 1998 setSelection(editable.length()); 1999 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 2000 mAlternatesPopup.dismiss(); 2001 } 2002 } 2003 2004 /** 2005 * Return whether a touch event was inside the delete target of 2006 * a selected chip. It is in the delete target if: 2007 * 1) the x and y points of the event are within the 2008 * delete assset. 2009 * 2) the point tapped would have caused a cursor to appear 2010 * right after the selected chip. 2011 * @return boolean 2012 */ 2013 private boolean isInDelete(RecipientChip chip, int offset, float x, float y) { 2014 // Figure out the bounds of this chip and whether or not 2015 // the user clicked in the X portion. 2016 return chip.isSelected() && offset == getChipEnd(chip); 2017 } 2018 2019 /** 2020 * Remove the chip and any text associated with it from the RecipientEditTextView. 2021 */ 2022 // Visible for testing. 2023 /*pacakge*/ void removeChip(RecipientChip chip) { 2024 Spannable spannable = getSpannable(); 2025 int spanStart = spannable.getSpanStart(chip); 2026 int spanEnd = spannable.getSpanEnd(chip); 2027 Editable text = getText(); 2028 int toDelete = spanEnd; 2029 boolean wasSelected = chip == mSelectedChip; 2030 // Clear that there is a selected chip before updating any text. 2031 if (wasSelected) { 2032 mSelectedChip = null; 2033 } 2034 // Always remove trailing spaces when removing a chip. 2035 while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') { 2036 toDelete++; 2037 } 2038 spannable.removeSpan(chip); 2039 if (spanStart >= 0 && toDelete > 0) { 2040 text.delete(spanStart, toDelete); 2041 } 2042 if (wasSelected) { 2043 clearSelectedChip(); 2044 } 2045 } 2046 2047 /** 2048 * Replace this currently selected chip with a new chip 2049 * that uses the contact data provided. 2050 */ 2051 // Visible for testing. 2052 /*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) { 2053 boolean wasSelected = chip == mSelectedChip; 2054 if (wasSelected) { 2055 mSelectedChip = null; 2056 } 2057 int start = getChipStart(chip); 2058 int end = getChipEnd(chip); 2059 getSpannable().removeSpan(chip); 2060 Editable editable = getText(); 2061 CharSequence chipText = createChip(entry, false); 2062 if (chipText != null) { 2063 if (start == -1 || end == -1) { 2064 Log.e(TAG, "The chip to replace does not exist but should."); 2065 editable.insert(0, chipText); 2066 } else { 2067 if (!TextUtils.isEmpty(chipText)) { 2068 // There may be a space to replace with this chip's new 2069 // associated space. Check for it 2070 int toReplace = end; 2071 while (toReplace >= 0 && toReplace < editable.length() 2072 && editable.charAt(toReplace) == ' ') { 2073 toReplace++; 2074 } 2075 editable.replace(start, toReplace, chipText); 2076 } 2077 } 2078 } 2079 setCursorVisible(true); 2080 if (wasSelected) { 2081 clearSelectedChip(); 2082 } 2083 } 2084 2085 /** 2086 * Handle click events for a chip. When a selected chip receives a click 2087 * event, see if that event was in the delete icon. If so, delete it. 2088 * Otherwise, unselect the chip. 2089 */ 2090 public void onClick(RecipientChip chip, int offset, float x, float y) { 2091 if (chip.isSelected()) { 2092 if (isInDelete(chip, offset, x, y)) { 2093 removeChip(chip); 2094 } else { 2095 clearSelectedChip(); 2096 } 2097 } 2098 } 2099 2100 private boolean chipsPending() { 2101 return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0); 2102 } 2103 2104 @Override 2105 public void removeTextChangedListener(TextWatcher watcher) { 2106 mTextWatcher = null; 2107 super.removeTextChangedListener(watcher); 2108 } 2109 2110 private class RecipientTextWatcher implements TextWatcher { 2111 2112 @Override 2113 public void afterTextChanged(Editable s) { 2114 // If the text has been set to null or empty, make sure we remove 2115 // all the spans we applied. 2116 if (TextUtils.isEmpty(s)) { 2117 // Remove all the chips spans. 2118 Spannable spannable = getSpannable(); 2119 RecipientChip[] chips = spannable.getSpans(0, getText().length(), 2120 RecipientChip.class); 2121 for (RecipientChip chip : chips) { 2122 spannable.removeSpan(chip); 2123 } 2124 if (mMoreChip != null) { 2125 spannable.removeSpan(mMoreChip); 2126 } 2127 return; 2128 } 2129 // Get whether there are any recipients pending addition to the 2130 // view. If there are, don't do anything in the text watcher. 2131 if (chipsPending()) { 2132 return; 2133 } 2134 // If the user is editing a chip, don't clear it. 2135 if (mSelectedChip != null 2136 && shouldShowEditableText(mSelectedChip)) { 2137 setCursorVisible(true); 2138 setSelection(getText().length()); 2139 clearSelectedChip(); 2140 } 2141 int length = s.length(); 2142 // Make sure there is content there to parse and that it is 2143 // not just the commit character. 2144 if (length > 1) { 2145 char last; 2146 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1; 2147 int len = length() - 1; 2148 if (end != len) { 2149 last = s.charAt(end); 2150 } else { 2151 last = s.charAt(len); 2152 } 2153 if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) { 2154 commitByCharacter(); 2155 } else if (last == COMMIT_CHAR_SPACE) { 2156 if (!isPhoneQuery()) { 2157 // Check if this is a valid email address. If it is, 2158 // commit it. 2159 String text = getText().toString(); 2160 int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 2161 String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text, 2162 tokenStart)); 2163 if (!TextUtils.isEmpty(sub) && mValidator != null && 2164 mValidator.isValid(sub)) { 2165 commitByCharacter(); 2166 } 2167 } 2168 } 2169 } 2170 } 2171 2172 @Override 2173 public void onTextChanged(CharSequence s, int start, int before, int count) { 2174 // This is a delete; check to see if the insertion point is on a space 2175 // following a chip. 2176 if (before > count) { 2177 // If the item deleted is a space, and the thing before the 2178 // space is a chip, delete the entire span. 2179 int selStart = getSelectionStart(); 2180 RecipientChip[] repl = getSpannable().getSpans(selStart, selStart, 2181 RecipientChip.class); 2182 if (repl.length > 0) { 2183 // There is a chip there! Just remove it. 2184 Editable editable = getText(); 2185 // Add the separator token. 2186 int tokenStart = mTokenizer.findTokenStart(editable, selStart); 2187 int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart); 2188 tokenEnd = tokenEnd + 1; 2189 if (tokenEnd > editable.length()) { 2190 tokenEnd = editable.length(); 2191 } 2192 editable.delete(tokenStart, tokenEnd); 2193 getSpannable().removeSpan(repl[0]); 2194 } 2195 } else if (count > before) { 2196 scrollBottomIntoView(); 2197 } 2198 } 2199 2200 @Override 2201 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 2202 // Do nothing. 2203 } 2204 } 2205 2206 private void scrollBottomIntoView() { 2207 if (mScrollView != null) { 2208 mScrollView.scrollBy(0, (int) (getLineCount() * mChipHeight)); 2209 } 2210 } 2211 2212 /** 2213 * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}. 2214 */ 2215 private void handlePasteClip(ClipData clip) { 2216 removeTextChangedListener(mTextWatcher); 2217 2218 if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){ 2219 for (int i = 0; i < clip.getItemCount(); i++) { 2220 CharSequence paste = clip.getItemAt(i).getText(); 2221 if (paste != null) { 2222 int start = getSelectionStart(); 2223 int end = getSelectionEnd(); 2224 Editable editable = getText(); 2225 if (start >= 0 && end >= 0 && start != end) { 2226 editable.append(paste, start, end); 2227 } else { 2228 editable.insert(end, paste); 2229 } 2230 handlePasteAndReplace(); 2231 } 2232 } 2233 } 2234 2235 mHandler.post(mAddTextWatcher); 2236 } 2237 2238 @Override 2239 public boolean onTextContextMenuItem(int id) { 2240 if (id == android.R.id.paste) { 2241 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2242 Context.CLIPBOARD_SERVICE); 2243 handlePasteClip(clipboard.getPrimaryClip()); 2244 return true; 2245 } 2246 return super.onTextContextMenuItem(id); 2247 } 2248 2249 private void handlePasteAndReplace() { 2250 ArrayList<RecipientChip> created = handlePaste(); 2251 if (created != null && created.size() > 0) { 2252 // Perform reverse lookups on the pasted contacts. 2253 IndividualReplacementTask replace = new IndividualReplacementTask(); 2254 replace.execute(created); 2255 } 2256 } 2257 2258 // Visible for testing. 2259 /* package */ArrayList<RecipientChip> handlePaste() { 2260 String text = getText().toString(); 2261 int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 2262 String lastAddress = text.substring(originalTokenStart); 2263 int tokenStart = originalTokenStart; 2264 int prevTokenStart = tokenStart; 2265 RecipientChip findChip = null; 2266 ArrayList<RecipientChip> created = new ArrayList<RecipientChip>(); 2267 if (tokenStart != 0) { 2268 // There are things before this! 2269 while (tokenStart != 0 && findChip == null) { 2270 prevTokenStart = tokenStart; 2271 tokenStart = mTokenizer.findTokenStart(text, tokenStart); 2272 findChip = findChip(tokenStart); 2273 } 2274 if (tokenStart != originalTokenStart) { 2275 if (findChip != null) { 2276 tokenStart = prevTokenStart; 2277 } 2278 int tokenEnd; 2279 RecipientChip createdChip; 2280 while (tokenStart < originalTokenStart) { 2281 tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(), 2282 tokenStart)); 2283 commitChip(tokenStart, tokenEnd, getText()); 2284 createdChip = findChip(tokenStart); 2285 if (createdChip == null) { 2286 break; 2287 } 2288 // +1 for the space at the end. 2289 tokenStart = getSpannable().getSpanEnd(createdChip) + 1; 2290 created.add(createdChip); 2291 } 2292 } 2293 } 2294 // Take a look at the last token. If the token has been completed with a 2295 // commit character, create a chip. 2296 if (isCompletedToken(lastAddress)) { 2297 Editable editable = getText(); 2298 tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart); 2299 commitChip(tokenStart, editable.length(), editable); 2300 created.add(findChip(tokenStart)); 2301 } 2302 return created; 2303 } 2304 2305 // Visible for testing. 2306 /* package */int movePastTerminators(int tokenEnd) { 2307 if (tokenEnd >= length()) { 2308 return tokenEnd; 2309 } 2310 char atEnd = getText().toString().charAt(tokenEnd); 2311 if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) { 2312 tokenEnd++; 2313 } 2314 // This token had not only an end token character, but also a space 2315 // separating it from the next token. 2316 if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') { 2317 tokenEnd++; 2318 } 2319 return tokenEnd; 2320 } 2321 2322 private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> { 2323 private RecipientChip createFreeChip(RecipientEntry entry) { 2324 try { 2325 if (mNoChips) { 2326 return null; 2327 } 2328 return constructChipSpan(entry, -1, false, 2329 false /*leave space for contact icon */); 2330 } catch (NullPointerException e) { 2331 Log.e(TAG, e.getMessage(), e); 2332 return null; 2333 } 2334 } 2335 2336 @Override 2337 protected Void doInBackground(Void... params) { 2338 if (mIndividualReplacements != null) { 2339 mIndividualReplacements.cancel(true); 2340 } 2341 // For each chip in the list, look up the matching contact. 2342 // If there is a match, replace that chip with the matching 2343 // chip. 2344 final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>(); 2345 RecipientChip[] existingChips = getSortedRecipients(); 2346 for (int i = 0; i < existingChips.length; i++) { 2347 originalRecipients.add(existingChips[i]); 2348 } 2349 if (mRemovedSpans != null) { 2350 originalRecipients.addAll(mRemovedSpans); 2351 } 2352 ArrayList<String> addresses = new ArrayList<String>(); 2353 RecipientChip chip; 2354 for (int i = 0; i < originalRecipients.size(); i++) { 2355 chip = originalRecipients.get(i); 2356 if (chip != null) { 2357 addresses.add(createAddressText(chip.getEntry())); 2358 } 2359 } 2360 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 2361 .getMatchingRecipients(getContext(), addresses); 2362 final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>(); 2363 for (final RecipientChip temp : originalRecipients) { 2364 RecipientEntry entry = null; 2365 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 2366 && getSpannable().getSpanStart(temp) != -1) { 2367 // Replace this. 2368 entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry() 2369 .getDestination()))); 2370 } 2371 if (entry != null) { 2372 replacements.add(createFreeChip(entry)); 2373 } else { 2374 replacements.add(temp); 2375 } 2376 } 2377 if (replacements != null && replacements.size() > 0) { 2378 mHandler.post(new Runnable() { 2379 @Override 2380 public void run() { 2381 Editable oldText = getText(); 2382 int start, end; 2383 int i = 0; 2384 for (RecipientChip chip : originalRecipients) { 2385 // Find the location of the chip in the text currently shown. 2386 start = oldText.getSpanStart(chip); 2387 if (start != -1) { 2388 end = oldText.getSpanEnd(chip); 2389 oldText.removeSpan(chip); 2390 RecipientChip replacement = replacements.get(i); 2391 // Make sure we always have just 1 space at the 2392 // end to separate this chip from the next chip. 2393 SpannableString displayText = new SpannableString( 2394 createAddressText(replacement.getEntry()).trim() + " "); 2395 displayText.setSpan(replacement, 0, displayText.length()-1, 2396 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2397 // Replace the old text we found with with the new display text, 2398 // which now may also contain the display name of the recipient. 2399 oldText.replace(start, end, displayText); 2400 replacement.setOriginalText(displayText.toString()); 2401 } 2402 i++; 2403 } 2404 originalRecipients.clear(); 2405 } 2406 }); 2407 } 2408 return null; 2409 } 2410 } 2411 2412 private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> { 2413 @SuppressWarnings("unchecked") 2414 @Override 2415 protected Void doInBackground(Object... params) { 2416 // For each chip in the list, look up the matching contact. 2417 // If there is a match, replace that chip with the matching 2418 // chip. 2419 final ArrayList<RecipientChip> originalRecipients = 2420 (ArrayList<RecipientChip>) params[0]; 2421 ArrayList<String> addresses = new ArrayList<String>(); 2422 RecipientChip chip; 2423 for (int i = 0; i < originalRecipients.size(); i++) { 2424 chip = originalRecipients.get(i); 2425 if (chip != null) { 2426 addresses.add(createAddressText(chip.getEntry())); 2427 } 2428 } 2429 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 2430 .getMatchingRecipients(getContext(), addresses); 2431 for (final RecipientChip temp : originalRecipients) { 2432 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 2433 && getSpannable().getSpanStart(temp) != -1) { 2434 // Replace this. 2435 RecipientEntry entry = createValidatedEntry(entries.get(tokenizeAddress( 2436 temp.getEntry().getDestination()).toLowerCase())); 2437 // If we don't have a validated contact match, just use the 2438 // entry as it existed before. 2439 if (entry == null && !isPhoneQuery()) { 2440 entry = temp.getEntry(); 2441 } 2442 final RecipientEntry tempEntry = entry; 2443 if (tempEntry != null) { 2444 mHandler.post(new Runnable() { 2445 @Override 2446 public void run() { 2447 replaceChip(temp, tempEntry); 2448 } 2449 }); 2450 } 2451 } 2452 } 2453 return null; 2454 } 2455 } 2456 2457 2458 /** 2459 * MoreImageSpan is a simple class created for tracking the existence of a 2460 * more chip across activity restarts/ 2461 */ 2462 private class MoreImageSpan extends ImageSpan { 2463 public MoreImageSpan(Drawable b) { 2464 super(b); 2465 } 2466 } 2467 2468 @Override 2469 public boolean onDown(MotionEvent e) { 2470 return false; 2471 } 2472 2473 @Override 2474 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 2475 // Do nothing. 2476 return false; 2477 } 2478 2479 @Override 2480 public void onLongPress(MotionEvent event) { 2481 if (mSelectedChip != null) { 2482 return; 2483 } 2484 float x = event.getX(); 2485 float y = event.getY(); 2486 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 2487 RecipientChip currentChip = findChip(offset); 2488 if (currentChip != null) { 2489 if (mDragEnabled) { 2490 // Start drag-and-drop for the selected chip. 2491 startDrag(currentChip); 2492 } else { 2493 // Copy the selected chip email address. 2494 showCopyDialog(currentChip.getEntry().getDestination()); 2495 } 2496 } 2497 } 2498 2499 /** 2500 * Enables drag-and-drop for chips. 2501 */ 2502 public void enableDrag() { 2503 mDragEnabled = true; 2504 } 2505 2506 /** 2507 * Starts drag-and-drop for the selected chip. 2508 */ 2509 private void startDrag(RecipientChip currentChip) { 2510 String address = currentChip.getEntry().getDestination(); 2511 ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA); 2512 2513 // Start drag mode. 2514 startDrag(data, new RecipientChipShadow(currentChip), null, 0); 2515 2516 // Remove the current chip, so drag-and-drop will result in a move. 2517 // TODO (phamm): consider readd this chip if it's dropped outside a target. 2518 removeChip(currentChip); 2519 } 2520 2521 /** 2522 * Handles drag event. 2523 */ 2524 @Override 2525 public boolean onDragEvent(DragEvent event) { 2526 switch (event.getAction()) { 2527 case DragEvent.ACTION_DRAG_STARTED: 2528 // Only handle plain text drag and drop. 2529 return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN); 2530 case DragEvent.ACTION_DRAG_ENTERED: 2531 requestFocus(); 2532 return true; 2533 case DragEvent.ACTION_DROP: 2534 handlePasteClip(event.getClipData()); 2535 return true; 2536 } 2537 return false; 2538 } 2539 2540 /** 2541 * Drag shadow for a {@link RecipientChip}. 2542 */ 2543 private final class RecipientChipShadow extends DragShadowBuilder { 2544 private final RecipientChip mChip; 2545 2546 public RecipientChipShadow(RecipientChip chip) { 2547 mChip = chip; 2548 } 2549 2550 @Override 2551 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 2552 Rect rect = mChip.getDrawable().getBounds(); 2553 shadowSize.set(rect.width(), rect.height()); 2554 shadowTouchPoint.set(rect.centerX(), rect.centerY()); 2555 } 2556 2557 @Override 2558 public void onDrawShadow(Canvas canvas) { 2559 mChip.getDrawable().draw(canvas); 2560 } 2561 } 2562 2563 private void showCopyDialog(final String address) { 2564 mCopyAddress = address; 2565 mCopyDialog.setTitle(address); 2566 mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout); 2567 mCopyDialog.setCancelable(true); 2568 mCopyDialog.setCanceledOnTouchOutside(true); 2569 Button button = (Button)mCopyDialog.findViewById(android.R.id.button1); 2570 button.setOnClickListener(this); 2571 int btnTitleId; 2572 if (isPhoneQuery()) { 2573 btnTitleId = R.string.copy_number; 2574 } else { 2575 btnTitleId = R.string.copy_email; 2576 } 2577 String buttonTitle = getContext().getResources().getString(btnTitleId); 2578 button.setText(buttonTitle); 2579 mCopyDialog.setOnDismissListener(this); 2580 mCopyDialog.show(); 2581 } 2582 2583 @Override 2584 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 2585 // Do nothing. 2586 return false; 2587 } 2588 2589 @Override 2590 public void onShowPress(MotionEvent e) { 2591 // Do nothing. 2592 } 2593 2594 @Override 2595 public boolean onSingleTapUp(MotionEvent e) { 2596 // Do nothing. 2597 return false; 2598 } 2599 2600 @Override 2601 public void onDismiss(DialogInterface dialog) { 2602 mCopyAddress = null; 2603 } 2604 2605 @Override 2606 public void onClick(View v) { 2607 // Copy this to the clipboard. 2608 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2609 Context.CLIPBOARD_SERVICE); 2610 clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress)); 2611 mCopyDialog.dismiss(); 2612 } 2613 2614 protected boolean isPhoneQuery() { 2615 return getAdapter() != null 2616 && ((BaseRecipientAdapter) getAdapter()).getQueryType() 2617 == BaseRecipientAdapter.QUERY_TYPE_PHONE; 2618 } 2619} 2620