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