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