RecipientEditTextView.java revision daa640c82bfa8b1f81d986d7109029d2fdec263d
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.ClipboardManager; 22import android.content.Context; 23import android.content.DialogInterface; 24import android.content.DialogInterface.OnDismissListener; 25import android.graphics.Bitmap; 26import android.graphics.BitmapFactory; 27import android.graphics.Canvas; 28import android.graphics.Matrix; 29import android.graphics.Rect; 30import android.graphics.RectF; 31import android.graphics.drawable.BitmapDrawable; 32import android.graphics.drawable.Drawable; 33import android.os.AsyncTask; 34import android.os.Handler; 35import android.os.Message; 36import android.os.Parcelable; 37import android.text.Editable; 38import android.text.InputType; 39import android.text.Layout; 40import android.text.Spannable; 41import android.text.SpannableString; 42import android.text.SpannableStringBuilder; 43import android.text.Spanned; 44import android.text.TextPaint; 45import android.text.TextUtils; 46import android.text.TextWatcher; 47import android.text.method.QwertyKeyListener; 48import android.text.style.ImageSpan; 49import android.text.util.Rfc822Token; 50import android.text.util.Rfc822Tokenizer; 51import android.util.AttributeSet; 52import android.util.Log; 53import android.view.ActionMode; 54import android.view.ActionMode.Callback; 55import android.view.GestureDetector; 56import android.view.KeyEvent; 57import android.view.LayoutInflater; 58import android.view.Menu; 59import android.view.MenuItem; 60import android.view.MotionEvent; 61import android.view.View; 62import android.view.View.OnClickListener; 63import android.view.ViewParent; 64import android.widget.AdapterView; 65import android.widget.AdapterView.OnItemClickListener; 66import android.widget.Filterable; 67import android.widget.ListAdapter; 68import android.widget.ListPopupWindow; 69import android.widget.ListView; 70import android.widget.MultiAutoCompleteTextView; 71import android.widget.PopupWindow; 72import android.widget.ScrollView; 73import android.widget.TextView; 74 75import java.util.ArrayList; 76import java.util.Arrays; 77import java.util.Collection; 78import java.util.Collections; 79import java.util.Comparator; 80import java.util.HashMap; 81import java.util.HashSet; 82import java.util.Set; 83 84/** 85 * RecipientEditTextView is an auto complete text view for use with applications 86 * that use the new Chips UI for addressing a message to recipients. 87 */ 88public class RecipientEditTextView extends MultiAutoCompleteTextView implements 89 OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener, 90 GestureDetector.OnGestureListener, OnDismissListener, OnClickListener, 91 PopupWindow.OnDismissListener { 92 93 private static final String TAG = "RecipientEditTextView"; 94 95 // TODO: get correct number/ algorithm from with UX. 96 private static final int CHIP_LIMIT = 2; 97 98 private Drawable mChipBackground = null; 99 100 private Drawable mChipDelete = null; 101 102 private int mChipPadding; 103 104 private Tokenizer mTokenizer; 105 106 private Drawable mChipBackgroundPressed; 107 108 private RecipientChip mSelectedChip; 109 110 private int mAlternatesLayout; 111 112 private Bitmap mDefaultContactPhoto; 113 114 private ImageSpan mMoreChip; 115 116 private TextView mMoreItem; 117 118 private final ArrayList<String> mPendingChips = new ArrayList<String>(); 119 120 private float mChipHeight; 121 122 private float mChipFontSize; 123 124 private Validator mValidator; 125 126 private Drawable mInvalidChipBackground; 127 128 private Handler mHandler; 129 130 private static int DISMISS = "dismiss".hashCode(); 131 132 private static final long DISMISS_DELAY = 300; 133 134 private int mPendingChipsCount = 0; 135 136 private static int sSelectedTextColor = -1; 137 138 private static final char COMMIT_CHAR_COMMA = ','; 139 140 private static final char COMMIT_CHAR_SEMICOLON = ';'; 141 142 private static final char COMMIT_CHAR_SPACE = ' '; 143 144 private ListPopupWindow mAlternatesPopup; 145 146 private ListPopupWindow mAddressPopup; 147 148 private ArrayList<RecipientChip> mTemporaryRecipients; 149 150 private ArrayList<RecipientChip> mRemovedSpans; 151 152 private boolean mShouldShrink = true; 153 154 // Chip copy fields. 155 private GestureDetector mGestureDetector; 156 157 private Dialog mCopyDialog; 158 159 private int mCopyViewRes; 160 161 private String mCopyAddress; 162 163 /** 164 * Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a 165 * selected chip. 166 */ 167 private OnItemClickListener mAlternatesListener; 168 169 private int mCheckedItem; 170 private TextWatcher mTextWatcher; 171 172 private ScrollView mScrollView; 173 174 private boolean mTried; 175 176 private final Runnable mAddTextWatcher = new Runnable() { 177 @Override 178 public void run() { 179 if (mTextWatcher == null) { 180 mTextWatcher = new RecipientTextWatcher(); 181 addTextChangedListener(mTextWatcher); 182 } 183 } 184 }; 185 186 private IndividualReplacementTask mIndividualReplacements; 187 188 private Runnable mHandlePendingChips = new Runnable() { 189 190 @Override 191 public void run() { 192 handlePendingChips(); 193 } 194 195 }; 196 197 private Runnable mDelayedShrink = new Runnable() { 198 199 @Override 200 public void run() { 201 shrink(); 202 } 203 204 }; 205 206 public RecipientEditTextView(Context context, AttributeSet attrs) { 207 super(context, attrs); 208 if (sSelectedTextColor == -1) { 209 sSelectedTextColor = context.getResources().getColor(android.R.color.white); 210 } 211 mAlternatesPopup = new ListPopupWindow(context); 212 mAlternatesPopup.setOnDismissListener(this); 213 mAddressPopup = new ListPopupWindow(context); 214 mAddressPopup.setOnDismissListener(this); 215 mCopyDialog = new Dialog(context); 216 mAlternatesListener = new OnItemClickListener() { 217 @Override 218 public void onItemClick(AdapterView<?> adapterView,View view, int position, 219 long rowId) { 220 mAlternatesPopup.setOnItemClickListener(null); 221 setEnabled(true); 222 replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter()) 223 .getRecipientEntry(position)); 224 Message delayed = Message.obtain(mHandler, DISMISS); 225 delayed.obj = mAlternatesPopup; 226 mHandler.sendMessageDelayed(delayed, DISMISS_DELAY); 227 clearComposingText(); 228 } 229 }; 230 setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); 231 setOnItemClickListener(this); 232 setCustomSelectionActionModeCallback(this); 233 mHandler = new Handler() { 234 @Override 235 public void handleMessage(Message msg) { 236 if (msg.what == DISMISS) { 237 ((ListPopupWindow) msg.obj).dismiss(); 238 return; 239 } 240 super.handleMessage(msg); 241 } 242 }; 243 mTextWatcher = new RecipientTextWatcher(); 244 addTextChangedListener(mTextWatcher); 245 mGestureDetector = new GestureDetector(context, this); 246 } 247 248 @Override 249 public <T extends ListAdapter & Filterable> void setAdapter(T adapter) { 250 super.setAdapter(adapter); 251 if (adapter == null) { 252 return; 253 } 254 } 255 256 @Override 257 public void onSelectionChanged(int start, int end) { 258 // When selection changes, see if it is inside the chips area. 259 // If so, move the cursor back after the chips again. 260 Spannable span = getSpannable(); 261 int textLength = getText().length(); 262 RecipientChip[] chips = span.getSpans(start, textLength, RecipientChip.class); 263 if (chips != null && chips.length > 0) { 264 if (chips != null && chips.length > 0) { 265 // Grab the last chip and set the cursor to after it. 266 setSelection(Math.min(span.getSpanEnd(chips[chips.length - 1]) + 1, textLength)); 267 } 268 } 269 super.onSelectionChanged(start, end); 270 } 271 272 @Override 273 public void onRestoreInstanceState(Parcelable state) { 274 if (!TextUtils.isEmpty(getText())) { 275 super.onRestoreInstanceState(null); 276 } else { 277 super.onRestoreInstanceState(state); 278 } 279 } 280 281 282 public Parcelable onSaveInstanceState() { 283 // If the user changes orientation while they are editing, just roll back the selection. 284 clearSelectedChip(); 285 return super.onSaveInstanceState(); 286 } 287 288 /** 289 * Convenience method: Append the specified text slice to the TextView's 290 * display buffer, upgrading it to BufferType.EDITABLE if it was 291 * not already editable. Commas are excluded as they are added automatically 292 * by the view. 293 */ 294 @Override 295 public void append(CharSequence text, int start, int end) { 296 // We don't care about watching text changes while appending. 297 if (mTextWatcher != null) { 298 removeTextChangedListener(mTextWatcher); 299 } 300 super.append(text, start, end); 301 if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) { 302 final String displayString = (String) text; 303 int seperatorPos = displayString.indexOf(COMMIT_CHAR_COMMA); 304 if (seperatorPos != 0 && !TextUtils.isEmpty(displayString) 305 && TextUtils.getTrimmedLength(displayString) > 0) { 306 mPendingChipsCount++; 307 mPendingChips.add((String)text); 308 } 309 } 310 // Put a message on the queue to make sure we ALWAYS handle pending chips. 311 if (mPendingChipsCount > 0) { 312 postHandlePendingChips(); 313 } 314 mHandler.post(mAddTextWatcher); 315 } 316 317 @Override 318 public void onFocusChanged(boolean hasFocus, int direction, Rect previous) { 319 super.onFocusChanged(hasFocus, direction, previous); 320 if (!hasFocus) { 321 shrink(); 322 } else { 323 expand(); 324 scrollLineIntoView(getLineCount()); 325 } 326 } 327 328 @Override 329 public void performValidation() { 330 // Do nothing. Chips handles its own validation. 331 } 332 333 private void shrink() { 334 if (mSelectedChip != null 335 && mSelectedChip.getEntry().getContactId() != RecipientEntry.INVALID_CONTACT) { 336 clearSelectedChip(); 337 } else { 338 if (getWidth() <= 0) { 339 // We don't have the width yet which means the view hasn't been drawn yet 340 // and there is no reason to attempt to commit chips yet. 341 // This focus lost must be the result of an orientation change 342 // or an initial rendering. 343 // Re-post the shrink for later. 344 mHandler.removeCallbacks(mDelayedShrink); 345 mHandler.post(mDelayedShrink); 346 return; 347 } 348 // Reset any pending chips as they would have been handled 349 // when the field lost focus. 350 if (mPendingChipsCount > 0) { 351 postHandlePendingChips(); 352 } else { 353 Editable editable = getText(); 354 int end = getSelectionEnd(); 355 int start = mTokenizer.findTokenStart(editable, end); 356 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); 357 if ((chips == null || chips.length == 0)) { 358 Editable text = getText(); 359 int whatEnd = mTokenizer.findTokenEnd(text, start); 360 // This token was already tokenized, so skip past the ending token. 361 if (whatEnd < text.length() && text.charAt(whatEnd) == ',') { 362 whatEnd++; 363 } 364 // In the middle of chip; treat this as an edit 365 // and commit the whole token. 366 int selEnd = getSelectionEnd(); 367 if (whatEnd != selEnd && whatEnd != editable.toString().trim().length()) { 368 handleEdit(start, whatEnd); 369 } else { 370 commitChip(start, end, editable); 371 } 372 } 373 } 374 mHandler.post(mAddTextWatcher); 375 } 376 createMoreChip(); 377 } 378 379 private void expand() { 380 removeMoreChip(); 381 setCursorVisible(true); 382 Editable text = getText(); 383 setSelection(text != null && text.length() > 0 ? text.length() : 0); 384 // If there are any temporary chips, try replacing them now that the user 385 // has expanded the field. 386 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) { 387 new RecipientReplacementTask().execute(); 388 mTemporaryRecipients = null; 389 } 390 } 391 392 private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) { 393 paint.setTextSize(mChipFontSize); 394 if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) { 395 Log.d(TAG, "Max width is negative: " + maxWidth); 396 } 397 return TextUtils.ellipsize(text, paint, maxWidth, 398 TextUtils.TruncateAt.END); 399 } 400 401 private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) { 402 // Ellipsize the text so that it takes AT MOST the entire width of the 403 // autocomplete text entry area. Make sure to leave space for padding 404 // on the sides. 405 int height = (int) mChipHeight; 406 int deleteWidth = height; 407 CharSequence ellipsizedText = ellipsizeText(contact.getDisplayName(), paint, 408 calculateAvailableWidth(true) - deleteWidth); 409 410 // Make sure there is a minimum chip width so the user can ALWAYS 411 // tap a chip without difficulty. 412 int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, 413 ellipsizedText.length())) 414 + (mChipPadding * 2) + deleteWidth); 415 416 // Create the background of the chip. 417 Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 418 Canvas canvas = new Canvas(tmpBitmap); 419 if (mChipBackgroundPressed != null) { 420 mChipBackgroundPressed.setBounds(0, 0, width, height); 421 mChipBackgroundPressed.draw(canvas); 422 paint.setColor(sSelectedTextColor); 423 // Vertically center the text in the chip. 424 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, 425 getTextYOffset((String) ellipsizedText, paint, height), paint); 426 // Make the delete a square. 427 Rect backgroundPadding = new Rect(); 428 mChipBackgroundPressed.getPadding(backgroundPadding); 429 mChipDelete.setBounds(width - deleteWidth + backgroundPadding.left, 430 0 + backgroundPadding.top, 431 width - backgroundPadding.right, 432 height - backgroundPadding.bottom); 433 mChipDelete.draw(canvas); 434 } else { 435 Log.w(TAG, "Unable to draw a background for the chips as it was never set"); 436 } 437 return tmpBitmap; 438 } 439 440 /** 441 * Get the background drawable for a RecipientChip. 442 */ 443 public Drawable getChipBackground(RecipientEntry contact) { 444 String destination = contact.getDestination(); 445 return (mValidator != null && !TextUtils.isEmpty(destination) && mValidator 446 .isValid(destination)) ? mChipBackground : mInvalidChipBackground; 447 } 448 449 private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout) { 450 // Ellipsize the text so that it takes AT MOST the entire width of the 451 // autocomplete text entry area. Make sure to leave space for padding 452 // on the sides. 453 int height = (int) mChipHeight; 454 int iconWidth = height; 455 String displayText = 456 !TextUtils.isEmpty(contact.getDisplayName()) ? contact.getDisplayName() : 457 !TextUtils.isEmpty(contact.getDestination()) ? contact.getDestination() : ""; 458 CharSequence ellipsizedText = ellipsizeText(displayText, paint, 459 calculateAvailableWidth(false) - iconWidth); 460 // Make sure there is a minimum chip width so the user can ALWAYS 461 // tap a chip without difficulty. 462 int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, 463 ellipsizedText.length())) 464 + (mChipPadding * 2) + iconWidth); 465 466 // Create the background of the chip. 467 Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 468 Canvas canvas = new Canvas(tmpBitmap); 469 Drawable background = getChipBackground(contact); 470 if (background != null) { 471 background.setBounds(0, 0, width, height); 472 background.draw(canvas); 473 474 // Don't draw photos for recipients that have been typed in. 475 if (contact.getContactId() != RecipientEntry.INVALID_CONTACT) { 476 byte[] photoBytes = contact.getPhotoBytes(); 477 // There may not be a photo yet if anything but the first contact address 478 // was selected. 479 if (photoBytes == null && contact.getPhotoThumbnailUri() != null) { 480 // TODO: cache this in the recipient entry? 481 ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact 482 .getPhotoThumbnailUri()); 483 photoBytes = contact.getPhotoBytes(); 484 } 485 486 Bitmap photo; 487 if (photoBytes != null) { 488 photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length); 489 } else { 490 // TODO: can the scaled down default photo be cached? 491 photo = mDefaultContactPhoto; 492 } 493 // Draw the photo on the left side. 494 if (photo != null) { 495 RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight()); 496 Rect backgroundPadding = new Rect(); 497 mChipBackground.getPadding(backgroundPadding); 498 RectF dst = new RectF(width - iconWidth + backgroundPadding.left, 499 0 + backgroundPadding.top, 500 width - backgroundPadding.right, 501 height - backgroundPadding.bottom); 502 Matrix matrix = new Matrix(); 503 matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL); 504 canvas.drawBitmap(photo, matrix, paint); 505 } 506 } else { 507 // Don't leave any space for the icon. It isn't being drawn. 508 iconWidth = 0; 509 } 510 paint.setColor(getContext().getResources().getColor(android.R.color.black)); 511 // Vertically center the text in the chip. 512 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, 513 getTextYOffset((String)ellipsizedText, paint, height), paint); 514 } else { 515 Log.w(TAG, "Unable to draw a background for the chips as it was never set"); 516 } 517 return tmpBitmap; 518 } 519 520 private float getTextYOffset(String text, TextPaint paint, int height) { 521 Rect bounds = new Rect(); 522 paint.getTextBounds((String)text, 0, text.length(), bounds); 523 int textHeight = bounds.bottom - bounds.top - (int)paint.descent(); 524 return height - ((height - textHeight) / 2); 525 } 526 527 public RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed) 528 throws NullPointerException { 529 if (mChipBackground == null) { 530 throw new NullPointerException( 531 "Unable to render any chips as setChipDimensions was not called."); 532 } 533 Layout layout = getLayout(); 534 535 TextPaint paint = getPaint(); 536 float defaultSize = paint.getTextSize(); 537 int defaultColor = paint.getColor(); 538 539 Bitmap tmpBitmap; 540 if (pressed) { 541 tmpBitmap = createSelectedChip(contact, paint, layout); 542 543 } else { 544 tmpBitmap = createUnselectedChip(contact, paint, layout); 545 } 546 547 // Pass the full text, un-ellipsized, to the chip. 548 Drawable result = new BitmapDrawable(getResources(), tmpBitmap); 549 result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight()); 550 RecipientChip recipientChip = new RecipientChip(result, contact, offset); 551 // Return text to the original size. 552 paint.setTextSize(defaultSize); 553 paint.setColor(defaultColor); 554 return recipientChip; 555 } 556 557 /** 558 * Calculate the bottom of the line the chip will be located on using: 559 * 1) which line the chip appears on 560 * 2) the height of a chip 561 * 3) padding built into the edit text view 562 */ 563 private int calculateOffsetFromBottom(int line) { 564 // Line offsets start at zero. 565 int actualLine = getLineCount() - (line + 1); 566 return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop()) 567 + getDropDownVerticalOffset(); 568 } 569 570 /** 571 * Get the max amount of space a chip can take up. The formula takes into 572 * account the width of the EditTextView, any view padding, and padding 573 * that will be added to the chip. 574 */ 575 private float calculateAvailableWidth(boolean pressed) { 576 return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2); 577 } 578 579 /** 580 * Set all chip dimensions and resources. This has to be done from the 581 * application as this is a static library. 582 * @param chipBackground 583 * @param chipBackgroundPressed 584 * @param invalidChip 585 * @param chipDelete 586 * @param defaultContact 587 * @param moreResource 588 * @param alternatesLayout 589 * @param chipHeight 590 * @param padding Padding around the text in a chip 591 * @param chipFontSize 592 * @param copyViewRes 593 */ 594 public void setChipDimensions(Drawable chipBackground, Drawable chipBackgroundPressed, 595 Drawable invalidChip, Drawable chipDelete, Bitmap defaultContact, int moreResource, 596 int alternatesLayout, float chipHeight, float padding, 597 float chipFontSize, int copyViewRes) { 598 mChipBackground = chipBackground; 599 mChipBackgroundPressed = chipBackgroundPressed; 600 mChipDelete = chipDelete; 601 mChipPadding = (int) padding; 602 mAlternatesLayout = alternatesLayout; 603 mDefaultContactPhoto = defaultContact; 604 mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(moreResource, null); 605 mChipHeight = chipHeight; 606 mChipFontSize = chipFontSize; 607 mInvalidChipBackground = invalidChip; 608 mCopyViewRes = copyViewRes; 609 } 610 611 // Visible for testing. 612 /* package */ void setMoreItem(TextView moreItem) { 613 mMoreItem = moreItem; 614 } 615 616 617 // Visible for testing. 618 /* package */ void setChipBackground(Drawable chipBackground) { 619 mChipBackground = chipBackground; 620 } 621 622 // Visible for testing. 623 /* package */ void setChipHeight(int height) { 624 mChipHeight = height; 625 } 626 627 /** 628 * Set whether to shrink the recipients field such that at most 629 * one line of recipients chips are shown when the field loses 630 * focus. By default, the number of displayed recipients will be 631 * limited and a "more" chip will be shown when focus is lost. 632 * @param shrink 633 */ 634 public void setOnFocusListShrinkRecipients(boolean shrink) { 635 mShouldShrink = shrink; 636 } 637 638 @Override 639 public void onSizeChanged(int width, int height, int oldw, int oldh) { 640 super.onSizeChanged(width, height, oldw, oldh); 641 if (width != 0 && height != 0) { 642 if (mPendingChipsCount > 0) { 643 postHandlePendingChips(); 644 } else { 645 checkChipWidths(); 646 } 647 } 648 // Try to find the scroll view parent, if it exists. 649 if (mScrollView == null && !mTried) { 650 ViewParent parent = getParent(); 651 while (parent != null && !(parent instanceof ScrollView)) { 652 parent = parent.getParent(); 653 } 654 if (parent != null) { 655 mScrollView = (ScrollView) parent; 656 } 657 mTried = true; 658 } 659 } 660 661 private void postHandlePendingChips() { 662 mHandler.removeCallbacks(mHandlePendingChips); 663 mHandler.post(mHandlePendingChips); 664 } 665 666 private void checkChipWidths() { 667 // Check the widths of the associated chips. 668 RecipientChip[] chips = getSortedRecipients(); 669 if (chips != null) { 670 Rect bounds; 671 for (RecipientChip chip : chips) { 672 bounds = chip.getDrawable().getBounds(); 673 if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) { 674 // Need to redraw that chip. 675 replaceChip(chip, chip.getEntry()); 676 } 677 } 678 } 679 } 680 681 private void handlePendingChips() { 682 if (getWidth() <= 0) { 683 // The widget has not been sized yet. 684 // This will be called as a result of onSizeChanged 685 // at a later point. 686 return; 687 } 688 689 if (mPendingChipsCount <= 0) { 690 return; 691 } 692 693 synchronized (mPendingChips) { 694 Editable editable = getText(); 695 // Tokenize! 696 for (int i = 0; i < mPendingChips.size(); i++) { 697 String current = mPendingChips.get(i); 698 int tokenStart = editable.toString().indexOf(current); 699 int tokenEnd = tokenStart + current.length(); 700 if (tokenStart >= 0) { 701 // When we have a valid token, include it with the token 702 // to the left. 703 if (tokenEnd < editable.length() - 2 704 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) { 705 tokenEnd++; 706 } 707 createReplacementChip(tokenStart, tokenEnd, editable); 708 } 709 mPendingChipsCount--; 710 } 711 sanitizeSpannable(); 712 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0 713 && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) { 714 if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) { 715 new RecipientReplacementTask().execute(); 716 mTemporaryRecipients = null; 717 } else { 718 // Create the "more" chip 719 mIndividualReplacements = new IndividualReplacementTask(); 720 mIndividualReplacements.execute(new ArrayList<RecipientChip>( 721 mTemporaryRecipients.subList(0, CHIP_LIMIT))); 722 723 createMoreChip(); 724 } 725 } else { 726 // There are too many recipients to look up, so just fall back 727 // to showing addresses for all of them. 728 mTemporaryRecipients = null; 729 createMoreChip(); 730 } 731 mPendingChipsCount = 0; 732 mPendingChips.clear(); 733 } 734 } 735 736 /** 737 * Remove any characters after the last valid chip. 738 */ 739 private void sanitizeSpannable() { 740 // Find the last chip; eliminate any commit characters after it. 741 RecipientChip[] chips = getRecipients(); 742 if (chips != null && chips.length > 0) { 743 int end; 744 ImageSpan lastSpan; 745 mMoreChip = getMoreChip(); 746 if (mMoreChip != null) { 747 lastSpan = mMoreChip; 748 } else { 749 lastSpan = chips[chips.length - 1]; 750 } 751 end = getSpannable().getSpanEnd(lastSpan); 752 Editable editable = getText(); 753 int length = editable.length(); 754 if (length > end) { 755 // See what characters occur after that and eliminate them. 756 if (Log.isLoggable(TAG, Log.DEBUG)) { 757 Log.d(TAG, "There were extra characters after the last tokenizable entry." 758 + editable); 759 } 760 editable.delete(end + 1, length); 761 } 762 } 763 } 764 765 /** 766 * Create a chip that represents just the email address of a recipient. At some later 767 * point, this chip will be attached to a real contact entry, if one exists. 768 */ 769 private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) { 770 if (alreadyHasChip(tokenStart, tokenEnd)) { 771 // There is already a chip present at this location. 772 // Don't recreate it. 773 return; 774 } 775 String token = editable.toString().substring(tokenStart, tokenEnd); 776 int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA); 777 if (commitCharIndex == token.length() - 1) { 778 token = token.substring(0, token.length() - 1); 779 } 780 RecipientEntry entry = createTokenizedEntry(token); 781 if (entry != null) { 782 String destText = createDisplayText(entry); 783 // Always leave a blank space at the end of a chip. 784 int textLength = destText.length(); 785 SpannableString chipText = new SpannableString(destText); 786 int end = getSelectionEnd(); 787 int start = mTokenizer.findTokenStart(getText(), end); 788 RecipientChip chip = null; 789 try { 790 chip = constructChipSpan(entry, start, false); 791 chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 792 } catch (NullPointerException e) { 793 Log.e(TAG, e.getMessage(), e); 794 } 795 editable.replace(tokenStart, tokenEnd, chipText); 796 // Add this chip to the list of entries "to replace" 797 if (chip != null) { 798 if (mTemporaryRecipients == null) { 799 mTemporaryRecipients = new ArrayList<RecipientChip>(); 800 } 801 chip.setOriginalText(chipText.toString()); 802 mTemporaryRecipients.add(chip); 803 } 804 } 805 } 806 807 private RecipientEntry createTokenizedEntry(String token) { 808 if (TextUtils.isEmpty(token)) { 809 return null; 810 } 811 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token); 812 String display = null; 813 if (isValid(token) && tokens != null && tokens.length > 0) { 814 // If we can get a name from tokenizing, then generate an entry from 815 // this. 816 display = tokens[0].getName(); 817 if (!TextUtils.isEmpty(display)) { 818 return RecipientEntry.constructGeneratedEntry(display, token); 819 } else { 820 display = tokens[0].getAddress(); 821 if (!TextUtils.isEmpty(display)) { 822 return RecipientEntry.constructFakeEntry(display); 823 } 824 } 825 } 826 // Unable to validate the token or to create a valid token from it. 827 // Just create a chip the user can edit. 828 String validatedToken = null; 829 if (mValidator != null && !mValidator.isValid(token)) { 830 // Try fixing up the entry using the validator. 831 validatedToken = mValidator.fixText(token).toString(); 832 if (!TextUtils.isEmpty(validatedToken)) { 833 if (validatedToken.contains(token)) { 834 // protect against the case of a validator with a null domain, 835 // which doesn't add a domain to the token 836 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken); 837 if (tokenized.length > 0) { 838 validatedToken = tokenized[0].getAddress(); 839 } 840 } else { 841 // We ran into a case where the token was invalid and removed 842 // by the validator. In this case, just use the original token 843 // and let the user sort out the error chip. 844 validatedToken = null; 845 } 846 } 847 } 848 // Otherwise, fallback to just creating an editable email address chip. 849 return RecipientEntry 850 .constructFakeEntry(!TextUtils.isEmpty(validatedToken) ? validatedToken : token); 851 } 852 853 private boolean isValid(String text) { 854 return mValidator == null ? true : mValidator.isValid(text); 855 } 856 857 private String tokenizeAddress(String destination) { 858 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination); 859 if (tokens != null && tokens.length > 0) { 860 return tokens[0].getAddress(); 861 } 862 return destination; 863 } 864 865 @Override 866 public void setTokenizer(Tokenizer tokenizer) { 867 mTokenizer = tokenizer; 868 super.setTokenizer(mTokenizer); 869 } 870 871 @Override 872 public void setValidator(Validator validator) { 873 mValidator = validator; 874 super.setValidator(validator); 875 } 876 877 /** 878 * We cannot use the default mechanism for replaceText. Instead, 879 * we override onItemClickListener so we can get all the associated 880 * contact information including display text, address, and id. 881 */ 882 @Override 883 protected void replaceText(CharSequence text) { 884 return; 885 } 886 887 /** 888 * Dismiss any selected chips when the back key is pressed. 889 */ 890 @Override 891 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 892 if (keyCode == KeyEvent.KEYCODE_BACK) { 893 clearSelectedChip(); 894 } 895 return super.onKeyPreIme(keyCode, event); 896 } 897 898 /** 899 * Monitor key presses in this view to see if the user types 900 * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER. 901 * If the user has entered text that has contact matches and types 902 * a commit key, create a chip from the topmost matching contact. 903 * If the user has entered text that has no contact matches and types 904 * a commit key, then create a chip from the text they have entered. 905 */ 906 @Override 907 public boolean onKeyUp(int keyCode, KeyEvent event) { 908 switch (keyCode) { 909 case KeyEvent.KEYCODE_ENTER: 910 case KeyEvent.KEYCODE_DPAD_CENTER: 911 if (event.hasNoModifiers()) { 912 if (commitDefault()) { 913 return true; 914 } 915 if (mSelectedChip != null) { 916 clearSelectedChip(); 917 return true; 918 } else if (focusNext()) { 919 return true; 920 } 921 } 922 break; 923 case KeyEvent.KEYCODE_TAB: 924 if (event.hasNoModifiers()) { 925 if (mSelectedChip != null) { 926 clearSelectedChip(); 927 } else { 928 commitDefault(); 929 } 930 if (focusNext()) { 931 return true; 932 } 933 } 934 } 935 return super.onKeyUp(keyCode, event); 936 } 937 938 private boolean focusNext() { 939 View next = focusSearch(View.FOCUS_DOWN); 940 if (next != null) { 941 next.requestFocus(); 942 return true; 943 } 944 return false; 945 } 946 947 /** 948 * Create a chip from the default selection. If the popup is showing, the 949 * default is the first item in the popup suggestions list. Otherwise, it is 950 * whatever the user had typed in. End represents where the the tokenizer 951 * should search for a token to turn into a chip. 952 * @return If a chip was created from a real contact. 953 */ 954 private boolean commitDefault() { 955 Editable editable = getText(); 956 int end = getSelectionEnd(); 957 int start = mTokenizer.findTokenStart(editable, end); 958 959 if (shouldCreateChip(start, end)) { 960 int whatEnd = mTokenizer.findTokenEnd(getText(), start); 961 // In the middle of chip; treat this as an edit 962 // and commit the whole token. 963 if (whatEnd != getSelectionEnd()) { 964 handleEdit(start, whatEnd); 965 return true; 966 } 967 return commitChip(start, end , editable); 968 } 969 return false; 970 } 971 972 private void commitByCharacter() { 973 Editable editable = getText(); 974 int end = getSelectionEnd(); 975 int start = mTokenizer.findTokenStart(editable, end); 976 if (shouldCreateChip(start, end)) { 977 commitChip(start, end, editable); 978 } 979 setSelection(getText().length()); 980 } 981 982 private boolean commitChip(int start, int end, Editable editable) { 983 if (getAdapter().getCount() > 0 && enoughToFilter()) { 984 // choose the first entry. 985 submitItemAtPosition(0); 986 dismissDropDown(); 987 return true; 988 } else { 989 int tokenEnd = mTokenizer.findTokenEnd(editable, start); 990 if (editable.length() > tokenEnd && editable.charAt(tokenEnd) == ',') { 991 tokenEnd++; 992 } 993 String text = editable.toString().substring(start, tokenEnd); 994 clearComposingText(); 995 if (text != null && text.length() > 0 && !text.equals(" ")) { 996 RecipientEntry entry = createTokenizedEntry(text); 997 if (entry != null) { 998 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 999 CharSequence chipText = createChip(entry, false); 1000 if (chipText != null) { 1001 editable.replace(start, end, chipText); 1002 } 1003 } 1004 dismissDropDown(); 1005 sanitizeBetween(); 1006 return true; 1007 } 1008 } 1009 return false; 1010 } 1011 1012 // Visible for testing. 1013 /* package */ void sanitizeBetween() { 1014 // Find the last chip. 1015 RecipientChip[] recips = getSortedRecipients(); 1016 if (recips != null && recips.length > 0) { 1017 RecipientChip last = recips[recips.length - 1]; 1018 RecipientChip beforeLast = null; 1019 if (recips.length > 1) { 1020 beforeLast = recips[recips.length - 2]; 1021 } 1022 int startLooking = 0; 1023 int end = getSpannable().getSpanStart(last); 1024 if (beforeLast != null) { 1025 startLooking = getSpannable().getSpanEnd(beforeLast); 1026 Editable text = getText(); 1027 if (startLooking == -1 || startLooking > text.length() - 1) { 1028 // There is nothing after this chip. 1029 return; 1030 } 1031 if (text.charAt(startLooking) == ' ') { 1032 startLooking++; 1033 } 1034 } 1035 if (startLooking >= 0 && end >= 0 && startLooking != end) { 1036 getText().delete(startLooking, end); 1037 } 1038 } 1039 } 1040 1041 private boolean shouldCreateChip(int start, int end) { 1042 return hasFocus() && enoughToFilter() && !alreadyHasChip(start, end); 1043 } 1044 1045 private boolean alreadyHasChip(int start, int end) { 1046 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); 1047 if ((chips == null || chips.length == 0)) { 1048 return false; 1049 } 1050 return true; 1051 } 1052 1053 private void handleEdit(int start, int end) { 1054 if (start == -1 || end == -1) { 1055 // This chip no longer exists in the field. 1056 dismissDropDown(); 1057 return; 1058 } 1059 // This is in the middle of a chip, so select out the whole chip 1060 // and commit it. 1061 Editable editable = getText(); 1062 setSelection(end); 1063 String text = getText().toString().substring(start, end); 1064 if (!TextUtils.isEmpty(text)) { 1065 RecipientEntry entry = RecipientEntry.constructFakeEntry(text); 1066 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1067 CharSequence chipText = createChip(entry, false); 1068 editable.replace(start, getSelectionEnd(), chipText); 1069 } 1070 dismissDropDown(); 1071 } 1072 1073 /** 1074 * If there is a selected chip, delegate the key events 1075 * to the selected chip. 1076 */ 1077 @Override 1078 public boolean onKeyDown(int keyCode, KeyEvent event) { 1079 if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) { 1080 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 1081 mAlternatesPopup.dismiss(); 1082 } 1083 removeChip(mSelectedChip); 1084 } 1085 1086 if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) { 1087 return true; 1088 } 1089 1090 return super.onKeyDown(keyCode, event); 1091 } 1092 1093 // Visible for testing. 1094 /* package */ Spannable getSpannable() { 1095 return getText(); 1096 } 1097 1098 private int getChipStart(RecipientChip chip) { 1099 return getSpannable().getSpanStart(chip); 1100 } 1101 1102 private int getChipEnd(RecipientChip chip) { 1103 return getSpannable().getSpanEnd(chip); 1104 } 1105 1106 /** 1107 * Instead of filtering on the entire contents of the edit box, 1108 * this subclass method filters on the range from 1109 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd} 1110 * if the length of that range meets or exceeds {@link #getThreshold} 1111 * and makes sure that the range is not already a Chip. 1112 */ 1113 @Override 1114 protected void performFiltering(CharSequence text, int keyCode) { 1115 if (enoughToFilter()) { 1116 int end = getSelectionEnd(); 1117 int start = mTokenizer.findTokenStart(text, end); 1118 // If this is a RecipientChip, don't filter 1119 // on its contents. 1120 Spannable span = getSpannable(); 1121 RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class); 1122 if (chips != null && chips.length > 0) { 1123 return; 1124 } 1125 } 1126 super.performFiltering(text, keyCode); 1127 } 1128 1129 private void clearSelectedChip() { 1130 if (mSelectedChip != null) { 1131 unselectChip(mSelectedChip); 1132 mSelectedChip = null; 1133 } 1134 setCursorVisible(true); 1135 } 1136 1137 /** 1138 * Monitor touch events in the RecipientEditTextView. 1139 * If the view does not have focus, any tap on the view 1140 * will just focus the view. If the view has focus, determine 1141 * if the touch target is a recipient chip. If it is and the chip 1142 * is not selected, select it and clear any other selected chips. 1143 * If it isn't, then select that chip. 1144 */ 1145 @Override 1146 public boolean onTouchEvent(MotionEvent event) { 1147 if (!isFocused()) { 1148 // Ignore any chip taps until this view is focused. 1149 return super.onTouchEvent(event); 1150 } 1151 boolean handled = super.onTouchEvent(event); 1152 int action = event.getAction(); 1153 boolean chipWasSelected = false; 1154 if (mSelectedChip == null) { 1155 mGestureDetector.onTouchEvent(event); 1156 } 1157 if (mCopyAddress == null && action == MotionEvent.ACTION_UP) { 1158 float x = event.getX(); 1159 float y = event.getY(); 1160 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 1161 RecipientChip currentChip = findChip(offset); 1162 if (currentChip != null) { 1163 if (action == MotionEvent.ACTION_UP) { 1164 if (mSelectedChip != null && mSelectedChip != currentChip) { 1165 clearSelectedChip(); 1166 mSelectedChip = selectChip(currentChip); 1167 } else if (mSelectedChip == null) { 1168 setSelection(getText().length()); 1169 commitDefault(); 1170 mSelectedChip = selectChip(currentChip); 1171 } else { 1172 onClick(mSelectedChip, offset, x, y); 1173 } 1174 } 1175 chipWasSelected = true; 1176 handled = true; 1177 } else if (mSelectedChip != null 1178 && mSelectedChip.getContactId() == RecipientEntry.INVALID_CONTACT) { 1179 chipWasSelected = true; 1180 } 1181 } 1182 if (action == MotionEvent.ACTION_UP && !chipWasSelected) { 1183 clearSelectedChip(); 1184 } 1185 return handled; 1186 } 1187 1188 private void scrollLineIntoView(int line) { 1189 if (mScrollView != null) { 1190 mScrollView.scrollBy(0, calculateOffsetFromBottom(line)); 1191 } 1192 } 1193 1194 private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup, 1195 int width, Context context) { 1196 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1197 int bottom = calculateOffsetFromBottom(line); 1198 // Align the alternates popup with the left side of the View, 1199 // regardless of the position of the chip tapped. 1200 alternatesPopup.setWidth(width); 1201 setEnabled(false); 1202 alternatesPopup.setAnchorView(this); 1203 alternatesPopup.setVerticalOffset(bottom); 1204 alternatesPopup.setAdapter(createAlternatesAdapter(currentChip)); 1205 alternatesPopup.setOnItemClickListener(mAlternatesListener); 1206 // Clear the checked item. 1207 mCheckedItem = -1; 1208 alternatesPopup.show(); 1209 ListView listView = alternatesPopup.getListView(); 1210 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1211 // Checked item would be -1 if the adapter has not 1212 // loaded the view that should be checked yet. The 1213 // variable will be set correctly when onCheckedItemChanged 1214 // is called in a separate thread. 1215 if (mCheckedItem != -1) { 1216 listView.setItemChecked(mCheckedItem, true); 1217 mCheckedItem = -1; 1218 } 1219 } 1220 1221 // Dismiss listener for alterns and single address popup. 1222 @Override 1223 public void onDismiss() { 1224 setEnabled(true); 1225 } 1226 1227 private ListAdapter createAlternatesAdapter(RecipientChip chip) { 1228 return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(), 1229 mAlternatesLayout, this); 1230 } 1231 1232 private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) { 1233 return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip 1234 .getEntry()); 1235 } 1236 1237 @Override 1238 public void onCheckedItemChanged(int position) { 1239 ListView listView = mAlternatesPopup.getListView(); 1240 if (listView != null && listView.getCheckedItemCount() == 0) { 1241 listView.setItemChecked(position, true); 1242 } 1243 mCheckedItem = position; 1244 } 1245 1246 // TODO: This algorithm will need a lot of tweaking after more people have used 1247 // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring 1248 // what comes before the finger. 1249 private int putOffsetInRange(int o) { 1250 int offset = o; 1251 Editable text = getText(); 1252 int length = text.length(); 1253 // Remove whitespace from end to find "real end" 1254 int realLength = length; 1255 for (int i = length - 1; i >= 0; i--) { 1256 if (text.charAt(i) == ' ') { 1257 realLength--; 1258 } else { 1259 break; 1260 } 1261 } 1262 1263 // If the offset is beyond or at the end of the text, 1264 // leave it alone. 1265 if (offset >= realLength) { 1266 return offset; 1267 } 1268 Editable editable = getText(); 1269 while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) { 1270 // Keep walking backward! 1271 offset--; 1272 } 1273 return offset; 1274 } 1275 1276 private int findText(Editable text, int offset) { 1277 if (text.charAt(offset) != ' ') { 1278 return offset; 1279 } 1280 return -1; 1281 } 1282 1283 private RecipientChip findChip(int offset) { 1284 RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class); 1285 // Find the chip that contains this offset. 1286 for (int i = 0; i < chips.length; i++) { 1287 RecipientChip chip = chips[i]; 1288 int start = getChipStart(chip); 1289 int end = getChipEnd(chip); 1290 if (offset >= start && offset <= end) { 1291 return chip; 1292 } 1293 } 1294 return null; 1295 } 1296 1297 // Visible for testing. 1298 /* package */ String createDisplayText(RecipientEntry entry) { 1299 String display = entry.getDisplayName(); 1300 String address = entry.getDestination(); 1301 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1302 display = null; 1303 } 1304 if (address != null) { 1305 // Tokenize out the address in case the address already 1306 // contained the username as well. 1307 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1308 if (tokenized != null && tokenized.length > 0) { 1309 address = tokenized[0].getAddress(); 1310 } 1311 } 1312 Rfc822Token token = new Rfc822Token(display, address, null); 1313 String displayText = token.toString(); 1314 String trimmedDisplayText = displayText.trim(); 1315 int index = trimmedDisplayText.indexOf(","); 1316 return index < trimmedDisplayText.length() - 1 ? (String) mTokenizer 1317 .terminateToken(displayText) : displayText; 1318 } 1319 1320 private CharSequence createChip(RecipientEntry entry, boolean pressed) { 1321 String displayText = createDisplayText(entry); 1322 // Always leave a blank space at the end of a chip. 1323 int textLength = displayText.length(); 1324 SpannableString chipText = new SpannableString(displayText); 1325 int end = getSelectionEnd(); 1326 int start = mTokenizer.findTokenStart(getText(), end); 1327 try { 1328 RecipientChip chip = constructChipSpan(entry, start, pressed); 1329 chipText.setSpan(chip, 0, textLength, 1330 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1331 chip.setOriginalText(chipText.toString()); 1332 } catch (NullPointerException e) { 1333 Log.e(TAG, e.getMessage(), e); 1334 return null; 1335 } 1336 1337 return chipText; 1338 } 1339 1340 /** 1341 * When an item in the suggestions list has been clicked, create a chip from the 1342 * contact information of the selected item. 1343 */ 1344 @Override 1345 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1346 submitItemAtPosition(position); 1347 } 1348 1349 private void submitItemAtPosition(int position) { 1350 RecipientEntry entry = createValidatedEntry( 1351 (RecipientEntry)getAdapter().getItem(position)); 1352 if (entry == null) { 1353 return; 1354 } 1355 clearComposingText(); 1356 1357 int end = getSelectionEnd(); 1358 int start = mTokenizer.findTokenStart(getText(), end); 1359 1360 Editable editable = getText(); 1361 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1362 CharSequence chip = createChip(entry, false); 1363 if (chip != null) { 1364 editable.replace(start, end, chip); 1365 } 1366 sanitizeBetween(); 1367 } 1368 1369 private RecipientEntry createValidatedEntry(RecipientEntry item) { 1370 if (item == null) { 1371 return null; 1372 } 1373 final RecipientEntry entry; 1374 // If the display name and the address are the same, or if this is a 1375 // valid contact, but the destination is invalid, then make this a fake 1376 // recipient that is editable. 1377 String destination = item.getDestination(); 1378 if (TextUtils.isEmpty(item.getDisplayName()) 1379 || TextUtils.equals(item.getDisplayName(), destination) 1380 || (mValidator != null && !mValidator.isValid(destination))) { 1381 entry = RecipientEntry.constructFakeEntry(destination); 1382 } else { 1383 entry = item; 1384 } 1385 return entry; 1386 } 1387 1388 /** Returns a collection of contact Id for each chip inside this View. */ 1389 /* package */ Collection<Long> getContactIds() { 1390 final Set<Long> result = new HashSet<Long>(); 1391 RecipientChip[] chips = getRecipients(); 1392 if (chips != null) { 1393 for (RecipientChip chip : chips) { 1394 result.add(chip.getContactId()); 1395 } 1396 } 1397 return result; 1398 } 1399 1400 private RecipientChip[] getRecipients() { 1401 return getSpannable().getSpans(0, getText().length(), RecipientChip.class); 1402 } 1403 1404 // Visible for testing. 1405 /* package */ RecipientChip[] getSortedRecipients() { 1406 ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays 1407 .asList(getRecipients())); 1408 final Spannable spannable = getSpannable(); 1409 Collections.sort(recipientsList, new Comparator<RecipientChip>() { 1410 1411 @Override 1412 public int compare(RecipientChip first, RecipientChip second) { 1413 int firstStart = spannable.getSpanStart(first); 1414 int secondStart = spannable.getSpanStart(second); 1415 if (firstStart < secondStart) { 1416 return -1; 1417 } else if (firstStart > secondStart) { 1418 return 1; 1419 } else { 1420 return 0; 1421 } 1422 } 1423 }); 1424 return recipientsList.toArray(new RecipientChip[recipientsList.size()]); 1425 } 1426 1427 /** Returns a collection of data Id for each chip inside this View. May be null. */ 1428 /* package */ Collection<Long> getDataIds() { 1429 final Set<Long> result = new HashSet<Long>(); 1430 RecipientChip [] chips = getRecipients(); 1431 if (chips != null) { 1432 for (RecipientChip chip : chips) { 1433 result.add(chip.getDataId()); 1434 } 1435 } 1436 return result; 1437 } 1438 1439 1440 @Override 1441 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 1442 return false; 1443 } 1444 1445 @Override 1446 public void onDestroyActionMode(ActionMode mode) { 1447 } 1448 1449 @Override 1450 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 1451 return false; 1452 } 1453 1454 /** 1455 * No chips are selectable. 1456 */ 1457 @Override 1458 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 1459 return false; 1460 } 1461 1462 // Visible for testing. 1463 /* package */ImageSpan getMoreChip() { 1464 MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(), 1465 MoreImageSpan.class); 1466 return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null; 1467 } 1468 1469 /** 1470 * Create the more chip. The more chip is text that replaces any chips that 1471 * do not fit in the pre-defined available space when the 1472 * RecipientEditTextView loses focus. 1473 */ 1474 // Visible for testing. 1475 /* package */ void createMoreChip() { 1476 if (!mShouldShrink) { 1477 return; 1478 } 1479 1480 ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class); 1481 if (tempMore.length > 0) { 1482 getSpannable().removeSpan(tempMore[0]); 1483 } 1484 RecipientChip[] recipients = getSortedRecipients(); 1485 if (recipients == null || recipients.length <= CHIP_LIMIT) { 1486 mMoreChip = null; 1487 return; 1488 } 1489 Spannable spannable = getSpannable(); 1490 int numRecipients = recipients.length; 1491 int overage = numRecipients - CHIP_LIMIT; 1492 String moreText = String.format(mMoreItem.getText().toString(), overage); 1493 TextPaint morePaint = new TextPaint(getPaint()); 1494 morePaint.setTextSize(mMoreItem.getTextSize()); 1495 morePaint.setColor(mMoreItem.getCurrentTextColor()); 1496 int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft() 1497 + mMoreItem.getPaddingRight(); 1498 int height = getLineHeight(); 1499 Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 1500 Canvas canvas = new Canvas(drawable); 1501 int adjustedHeight = height; 1502 Layout layout = getLayout(); 1503 if (layout != null) { 1504 adjustedHeight -= layout.getLineDescent(0); 1505 } 1506 canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint); 1507 1508 Drawable result = new BitmapDrawable(getResources(), drawable); 1509 result.setBounds(0, 0, width, height); 1510 MoreImageSpan moreSpan = new MoreImageSpan(result); 1511 // Remove the overage chips. 1512 if (recipients == null || recipients.length == 0) { 1513 Log.w(TAG, 1514 "We have recipients. Tt should not be possible to have zero RecipientChips."); 1515 mMoreChip = null; 1516 return; 1517 } 1518 mRemovedSpans = new ArrayList<RecipientChip>(); 1519 int totalReplaceStart = 0; 1520 int totalReplaceEnd = 0; 1521 Editable text = getText(); 1522 for (int i = numRecipients - overage; i < recipients.length; i++) { 1523 mRemovedSpans.add(recipients[i]); 1524 if (i == numRecipients - overage) { 1525 totalReplaceStart = spannable.getSpanStart(recipients[i]); 1526 } 1527 if (i == recipients.length - 1) { 1528 totalReplaceEnd = spannable.getSpanEnd(recipients[i]); 1529 } 1530 if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) { 1531 int spanStart = spannable.getSpanStart(recipients[i]); 1532 int spanEnd = spannable.getSpanEnd(recipients[i]); 1533 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd)); 1534 } 1535 spannable.removeSpan(recipients[i]); 1536 } 1537 int end = Math.max(totalReplaceStart, totalReplaceEnd); 1538 int start = Math.min(totalReplaceStart, totalReplaceEnd); 1539 SpannableString chipText = new SpannableString(text.subSequence(start, end)); 1540 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1541 text.replace(start, end, chipText); 1542 mMoreChip = moreSpan; 1543 } 1544 1545 /** 1546 * Replace the more chip, if it exists, with all of the recipient chips it had 1547 * replaced when the RecipientEditTextView gains focus. 1548 */ 1549 // Visible for testing. 1550 /*package*/ void removeMoreChip() { 1551 if (mMoreChip != null) { 1552 Spannable span = getSpannable(); 1553 span.removeSpan(mMoreChip); 1554 mMoreChip = null; 1555 // Re-add the spans that were removed. 1556 if (mRemovedSpans != null && mRemovedSpans.size() > 0) { 1557 // Recreate each removed span. 1558 RecipientChip[] recipients = getSortedRecipients(); 1559 // Start the search for tokens after the last currently visible 1560 // chip. 1561 if (recipients == null || recipients.length == 0) { 1562 return; 1563 } 1564 int end = span.getSpanEnd(recipients[recipients.length - 1]); 1565 Editable editable = getText(); 1566 for (RecipientChip chip : mRemovedSpans) { 1567 int chipStart; 1568 int chipEnd; 1569 String token; 1570 // Need to find the location of the chip, again. 1571 token = (String) chip.getOriginalText(); 1572 // As we find the matching recipient for the remove spans, 1573 // reduce the size of the string we need to search. 1574 // That way, if there are duplicates, we always find the correct 1575 // recipient. 1576 chipStart = editable.toString().indexOf(token, end); 1577 end = chipEnd = Math.min(editable.length(), chipStart + token.length()); 1578 // Only set the span if we found a matching token. 1579 if (chipStart != -1) { 1580 editable.setSpan(chip, chipStart, chipEnd, 1581 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 1582 } 1583 } 1584 mRemovedSpans.clear(); 1585 } 1586 } 1587 } 1588 1589 /** 1590 * Show specified chip as selected. If the RecipientChip is just an email address, 1591 * selecting the chip will take the contents of the chip and place it at 1592 * the end of the RecipientEditTextView for inline editing. If the 1593 * RecipientChip is a complete contact, then selecting the chip 1594 * will change the background color of the chip, show the delete icon, 1595 * and a popup window with the address in use highlighted and any other 1596 * alternate addresses for the contact. 1597 * @param currentChip Chip to select. 1598 * @return A RecipientChip in the selected state or null if the chip 1599 * just contained an email address. 1600 */ 1601 public RecipientChip selectChip(RecipientChip currentChip) { 1602 if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) { 1603 CharSequence text = currentChip.getValue(); 1604 Editable editable = getText(); 1605 removeChip(currentChip); 1606 editable.append(text); 1607 setCursorVisible(true); 1608 setSelection(editable.length()); 1609 return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1); 1610 } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1611 int start = getChipStart(currentChip); 1612 int end = getChipEnd(currentChip); 1613 getSpannable().removeSpan(currentChip); 1614 RecipientChip newChip; 1615 try { 1616 newChip = constructChipSpan(currentChip.getEntry(), start, true); 1617 } catch (NullPointerException e) { 1618 Log.e(TAG, e.getMessage(), e); 1619 return null; 1620 } 1621 Editable editable = getText(); 1622 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1623 if (start == -1 || end == -1) { 1624 Log.d(TAG, "The chip being selected no longer exists but should."); 1625 } else { 1626 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1627 } 1628 newChip.setSelected(true); 1629 if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) { 1630 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1631 } 1632 showAddress(newChip, mAddressPopup, getWidth(), getContext()); 1633 setCursorVisible(false); 1634 return newChip; 1635 } else { 1636 int start = getChipStart(currentChip); 1637 int end = getChipEnd(currentChip); 1638 getSpannable().removeSpan(currentChip); 1639 RecipientChip newChip; 1640 try { 1641 newChip = constructChipSpan(currentChip.getEntry(), start, true); 1642 } catch (NullPointerException e) { 1643 Log.e(TAG, e.getMessage(), e); 1644 return null; 1645 } 1646 Editable editable = getText(); 1647 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1648 if (start == -1 || end == -1) { 1649 Log.d(TAG, "The chip being selected no longer exists but should."); 1650 } else { 1651 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1652 } 1653 newChip.setSelected(true); 1654 if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) { 1655 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1656 } 1657 showAlternates(newChip, mAlternatesPopup, getWidth(), getContext()); 1658 setCursorVisible(false); 1659 return newChip; 1660 } 1661 } 1662 1663 1664 private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup, 1665 int width, Context context) { 1666 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1667 int bottom = calculateOffsetFromBottom(line); 1668 // Align the alternates popup with the left side of the View, 1669 // regardless of the position of the chip tapped. 1670 setEnabled(false); 1671 popup.setWidth(width); 1672 popup.setAnchorView(this); 1673 popup.setVerticalOffset(bottom); 1674 popup.setAdapter(createSingleAddressAdapter(currentChip)); 1675 popup.setOnItemClickListener(new OnItemClickListener() { 1676 @Override 1677 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1678 unselectChip(currentChip); 1679 popup.dismiss(); 1680 } 1681 }); 1682 popup.show(); 1683 ListView listView = popup.getListView(); 1684 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1685 listView.setItemChecked(0, true); 1686 } 1687 1688 /** 1689 * Remove selection from this chip. Unselecting a RecipientChip will render 1690 * the chip without a delete icon and with an unfocused background. This 1691 * is called when the RecipientChip no longer has focus. 1692 */ 1693 public void unselectChip(RecipientChip chip) { 1694 int start = getChipStart(chip); 1695 int end = getChipEnd(chip); 1696 Editable editable = getText(); 1697 mSelectedChip = null; 1698 if (start == -1 || end == -1) { 1699 Log.w(TAG, 1700 "The chip doesn't exist or may be a chip a user was editing"); 1701 setSelection(editable.length()); 1702 commitDefault(); 1703 } else { 1704 getSpannable().removeSpan(chip); 1705 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1706 editable.removeSpan(chip); 1707 try { 1708 editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end, 1709 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1710 } catch (NullPointerException e) { 1711 Log.e(TAG, e.getMessage(), e); 1712 } 1713 } 1714 setCursorVisible(true); 1715 setSelection(editable.length()); 1716 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 1717 mAlternatesPopup.dismiss(); 1718 } 1719 } 1720 1721 /** 1722 * Return whether this chip contains the position passed in. 1723 */ 1724 public boolean matchesChip(RecipientChip chip, int offset) { 1725 int start = getChipStart(chip); 1726 int end = getChipEnd(chip); 1727 1728 if (start == -1 || end == -1) { 1729 return false; 1730 } 1731 return (offset >= start && offset <= end); 1732 } 1733 1734 1735 /** 1736 * Return whether a touch event was inside the delete target of 1737 * a selected chip. It is in the delete target if: 1738 * 1) the x and y points of the event are within the 1739 * delete assset. 1740 * 2) the point tapped would have caused a cursor to appear 1741 * right after the selected chip. 1742 * @return boolean 1743 */ 1744 private boolean isInDelete(RecipientChip chip, int offset, float x, float y) { 1745 // Figure out the bounds of this chip and whether or not 1746 // the user clicked in the X portion. 1747 return chip.isSelected() && offset == getChipEnd(chip); 1748 } 1749 1750 /** 1751 * Remove the chip and any text associated with it from the RecipientEditTextView. 1752 */ 1753 // Visible for testing. 1754 /*pacakge*/ void removeChip(RecipientChip chip) { 1755 Spannable spannable = getSpannable(); 1756 int spanStart = spannable.getSpanStart(chip); 1757 int spanEnd = spannable.getSpanEnd(chip); 1758 Editable text = getText(); 1759 boolean wasSelected = chip == mSelectedChip; 1760 // Clear that there is a selected chip before updating any text. 1761 if (wasSelected) { 1762 mSelectedChip = null; 1763 } 1764 spannable.removeSpan(chip); 1765 text.delete(spanStart, spanEnd); 1766 if (wasSelected) { 1767 clearSelectedChip(); 1768 } 1769 } 1770 1771 /** 1772 * Replace this currently selected chip with a new chip 1773 * that uses the contact data provided. 1774 */ 1775 public void replaceChip(RecipientChip chip, RecipientEntry entry) { 1776 boolean wasSelected = chip == mSelectedChip; 1777 if (wasSelected) { 1778 mSelectedChip = null; 1779 } 1780 int start = getChipStart(chip); 1781 int end = getChipEnd(chip); 1782 getSpannable().removeSpan(chip); 1783 Editable editable = getText(); 1784 CharSequence chipText = createChip(entry, false); 1785 if (start == -1 || end == -1) { 1786 Log.e(TAG, "The chip to replace does not exist but should."); 1787 editable.insert(0, chipText); 1788 } else { 1789 if (!TextUtils.isEmpty(chipText)) { 1790 editable.replace(start, end, chipText); 1791 } 1792 } 1793 setCursorVisible(true); 1794 if (wasSelected) { 1795 clearSelectedChip(); 1796 } 1797 } 1798 1799 /** 1800 * Handle click events for a chip. When a selected chip receives a click 1801 * event, see if that event was in the delete icon. If so, delete it. 1802 * Otherwise, unselect the chip. 1803 */ 1804 public void onClick(RecipientChip chip, int offset, float x, float y) { 1805 if (chip.isSelected()) { 1806 if (isInDelete(chip, offset, x, y)) { 1807 removeChip(chip); 1808 } else { 1809 clearSelectedChip(); 1810 } 1811 } 1812 } 1813 1814 private boolean chipsPending() { 1815 return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0); 1816 } 1817 1818 @Override 1819 public void removeTextChangedListener(TextWatcher watcher) { 1820 mTextWatcher = null; 1821 super.removeTextChangedListener(watcher); 1822 } 1823 1824 private class RecipientTextWatcher implements TextWatcher { 1825 @Override 1826 public void afterTextChanged(Editable s) { 1827 // If the text has been set to null or empty, make sure we remove 1828 // all the spans we applied. 1829 if (TextUtils.isEmpty(s)) { 1830 // Remove all the chips spans. 1831 Spannable spannable = getSpannable(); 1832 RecipientChip[] chips = spannable.getSpans(0, getText().length(), 1833 RecipientChip.class); 1834 for (RecipientChip chip : chips) { 1835 spannable.removeSpan(chip); 1836 } 1837 if (mMoreChip != null) { 1838 spannable.removeSpan(mMoreChip); 1839 } 1840 return; 1841 } 1842 // Get whether there are any recipients pending addition to the 1843 // view. If there are, don't do anything in the text watcher. 1844 if (chipsPending()) { 1845 return; 1846 } 1847 // If the user is editing a chip, don't clear it. 1848 if (mSelectedChip != null 1849 && mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) { 1850 setCursorVisible(true); 1851 setSelection(getText().length()); 1852 clearSelectedChip(); 1853 } 1854 int length = s.length(); 1855 // Make sure there is content there to parse and that it is 1856 // not just the commit character. 1857 if (length > 1) { 1858 char last; 1859 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1; 1860 int len = length() - 1; 1861 if (end != len) { 1862 last = s.charAt(end); 1863 } else { 1864 last = s.charAt(len); 1865 } 1866 if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) { 1867 commitByCharacter(); 1868 } else if (last == COMMIT_CHAR_SPACE) { 1869 // Check if this is a valid email address. If it is, 1870 // commit it. 1871 String text = getText().toString(); 1872 int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 1873 String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text, 1874 tokenStart)); 1875 if (!TextUtils.isEmpty(sub) && mValidator != null && mValidator.isValid(sub)) { 1876 commitByCharacter(); 1877 } 1878 } 1879 } 1880 } 1881 1882 @Override 1883 public void onTextChanged(CharSequence s, int start, int before, int count) { 1884 // Do nothing. 1885 } 1886 1887 @Override 1888 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 1889 // Do nothing. 1890 } 1891 } 1892 1893 private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> { 1894 private RecipientChip createFreeChip(RecipientEntry entry) { 1895 try { 1896 return constructChipSpan(entry, -1, false); 1897 } catch (NullPointerException e) { 1898 Log.e(TAG, e.getMessage(), e); 1899 return null; 1900 } 1901 } 1902 1903 @Override 1904 protected Void doInBackground(Void... params) { 1905 if (mIndividualReplacements != null) { 1906 mIndividualReplacements.cancel(true); 1907 } 1908 // For each chip in the list, look up the matching contact. 1909 // If there is a match, replace that chip with the matching 1910 // chip. 1911 final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>(); 1912 RecipientChip[] existingChips = getSortedRecipients(); 1913 for (int i = 0; i < existingChips.length; i++) { 1914 originalRecipients.add(existingChips[i]); 1915 } 1916 if (mRemovedSpans != null) { 1917 originalRecipients.addAll(mRemovedSpans); 1918 } 1919 String[] addresses = new String[originalRecipients.size()]; 1920 for (int i = 0; i < originalRecipients.size(); i++) { 1921 addresses[i] = createDisplayText(originalRecipients.get(i).getEntry()); 1922 } 1923 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 1924 .getMatchingRecipients(getContext(), addresses); 1925 final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>(); 1926 for (final RecipientChip temp : originalRecipients) { 1927 RecipientEntry entry = null; 1928 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 1929 && getSpannable().getSpanStart(temp) != -1) { 1930 // Replace this. 1931 entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry() 1932 .getDestination()))); 1933 } 1934 if (entry != null) { 1935 replacements.add(createFreeChip(entry)); 1936 } else { 1937 replacements.add(temp); 1938 } 1939 } 1940 if (replacements != null && replacements.size() > 0) { 1941 mHandler.post(new Runnable() { 1942 @Override 1943 public void run() { 1944 SpannableStringBuilder text = new SpannableStringBuilder(getText() 1945 .toString()); 1946 Editable oldText = getText(); 1947 int start, end; 1948 int i = 0; 1949 for (RecipientChip chip : originalRecipients) { 1950 start = oldText.getSpanStart(chip); 1951 if (start != -1) { 1952 end = oldText.getSpanEnd(chip); 1953 text.removeSpan(chip); 1954 // Leave a spot for the space! 1955 RecipientChip replacement = replacements.get(i); 1956 text.setSpan(replacement, start, end, 1957 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1958 replacement.setOriginalText(text.toString().substring(start, end)); 1959 } 1960 i++; 1961 } 1962 Editable editable = getText(); 1963 editable.clear(); 1964 editable.insert(0, text); 1965 originalRecipients.clear(); 1966 } 1967 }); 1968 } 1969 return null; 1970 } 1971 } 1972 1973 private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> { 1974 @SuppressWarnings("unchecked") 1975 @Override 1976 protected Void doInBackground(Object... params) { 1977 // For each chip in the list, look up the matching contact. 1978 // If there is a match, replace that chip with the matching 1979 // chip. 1980 final ArrayList<RecipientChip> originalRecipients = 1981 (ArrayList<RecipientChip>) params[0]; 1982 String[] addresses = new String[originalRecipients.size()]; 1983 for (int i = 0; i < originalRecipients.size(); i++) { 1984 addresses[i] = createDisplayText(originalRecipients.get(i).getEntry()); 1985 } 1986 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 1987 .getMatchingRecipients(getContext(), addresses); 1988 for (final RecipientChip temp : originalRecipients) { 1989 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 1990 && getSpannable().getSpanStart(temp) != -1) { 1991 // Replace this. 1992 final RecipientEntry entry = createValidatedEntry(entries 1993 .get(tokenizeAddress(temp.getEntry().getDestination()))); 1994 if (entry != null) { 1995 mHandler.post(new Runnable() { 1996 @Override 1997 public void run() { 1998 replaceChip(temp, entry); 1999 } 2000 }); 2001 } 2002 } 2003 } 2004 return null; 2005 } 2006 } 2007 2008 2009 /** 2010 * MoreImageSpan is a simple class created for tracking the existence of a 2011 * more chip across activity restarts/ 2012 */ 2013 private class MoreImageSpan extends ImageSpan { 2014 public MoreImageSpan(Drawable b) { 2015 super(b); 2016 } 2017 } 2018 2019 @Override 2020 public boolean onDown(MotionEvent e) { 2021 return false; 2022 } 2023 2024 @Override 2025 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 2026 // Do nothing. 2027 return false; 2028 } 2029 2030 @Override 2031 public void onLongPress(MotionEvent event) { 2032 if (mSelectedChip != null) { 2033 return; 2034 } 2035 float x = event.getX(); 2036 float y = event.getY(); 2037 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 2038 RecipientChip currentChip = findChip(offset); 2039 if (currentChip != null) { 2040 // Copy the selected chip email address. 2041 showCopyDialog(currentChip.getEntry().getDestination()); 2042 } 2043 } 2044 2045 private void showCopyDialog(final String address) { 2046 mCopyAddress = address; 2047 mCopyDialog.setTitle(address); 2048 mCopyDialog.setContentView(mCopyViewRes); 2049 mCopyDialog.setCancelable(true); 2050 mCopyDialog.setCanceledOnTouchOutside(true); 2051 mCopyDialog.findViewById(android.R.id.button1).setOnClickListener(this); 2052 mCopyDialog.setOnDismissListener(this); 2053 mCopyDialog.show(); 2054 } 2055 2056 @Override 2057 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 2058 // Do nothing. 2059 return false; 2060 } 2061 2062 @Override 2063 public void onShowPress(MotionEvent e) { 2064 // Do nothing. 2065 } 2066 2067 @Override 2068 public boolean onSingleTapUp(MotionEvent e) { 2069 // Do nothing. 2070 return false; 2071 } 2072 2073 @Override 2074 public void onDismiss(DialogInterface dialog) { 2075 mCopyAddress = null; 2076 } 2077 2078 @Override 2079 public void onClick(View v) { 2080 // Copy this to the clipboard. 2081 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2082 Context.CLIPBOARD_SERVICE); 2083 clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress)); 2084 mCopyDialog.dismiss(); 2085 } 2086} 2087