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