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