RecipientEditTextView.java revision 7e10c86c8bead949f2f4694e97d7844c6aef9e08
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.util.Patterns; 57import android.view.ActionMode; 58import android.view.ActionMode.Callback; 59import android.view.DragEvent; 60import android.view.GestureDetector; 61import android.view.KeyEvent; 62import android.view.LayoutInflater; 63import android.view.Menu; 64import android.view.MenuItem; 65import android.view.MotionEvent; 66import android.view.View; 67import android.view.View.OnClickListener; 68import android.view.ViewParent; 69import android.view.inputmethod.EditorInfo; 70import android.view.inputmethod.InputConnection; 71import android.widget.AdapterView; 72import android.widget.AdapterView.OnItemClickListener; 73import android.widget.Button; 74import android.widget.ListAdapter; 75import android.widget.ListPopupWindow; 76import android.widget.ListView; 77import android.widget.MultiAutoCompleteTextView; 78import android.widget.ScrollView; 79import android.widget.TextView; 80 81import java.util.ArrayList; 82import java.util.Arrays; 83import java.util.Collection; 84import java.util.Collections; 85import java.util.Comparator; 86import java.util.HashMap; 87import java.util.HashSet; 88import java.util.Set; 89import java.util.regex.Matcher; 90import java.util.regex.Pattern; 91 92/** 93 * RecipientEditTextView is an auto complete text view for use with applications 94 * that use the new Chips UI for addressing a message to recipients. 95 */ 96public class RecipientEditTextView extends MultiAutoCompleteTextView implements 97 OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener, 98 GestureDetector.OnGestureListener, OnDismissListener, OnClickListener, 99 TextView.OnEditorActionListener { 100 101 private static final char COMMIT_CHAR_COMMA = ','; 102 103 private static final char NAME_WRAPPER_CHAR = '"'; 104 105 private static final char COMMIT_CHAR_SEMICOLON = ';'; 106 107 private static final char COMMIT_CHAR_SPACE = ' '; 108 109 private static final String TAG = "RecipientEditTextView"; 110 111 private static int DISMISS = "dismiss".hashCode(); 112 113 private static final long DISMISS_DELAY = 300; 114 115 // TODO: get correct number/ algorithm from with UX. 116 // Visible for testing. 117 /*package*/ static final int CHIP_LIMIT = 2; 118 119 private static final int MAX_CHIPS_PARSED = 50; 120 121 private static int sSelectedTextColor = -1; 122 123 // Resources for displaying chips. 124 private Drawable mChipBackground = null; 125 126 private Drawable mChipDelete = null; 127 128 private Drawable mInvalidChipBackground; 129 130 private Drawable mChipBackgroundPressed; 131 132 private float mChipHeight; 133 134 private float mChipFontSize; 135 136 private float mLineSpacingExtra; 137 138 private int mChipPadding; 139 140 private Tokenizer mTokenizer; 141 142 private Validator mValidator; 143 144 private RecipientChip mSelectedChip; 145 146 private int mAlternatesLayout; 147 148 private Bitmap mDefaultContactPhoto; 149 150 private ImageSpan mMoreChip; 151 152 private TextView mMoreItem; 153 154 private final ArrayList<String> mPendingChips = new ArrayList<String>(); 155 156 private Handler mHandler; 157 158 private int mPendingChipsCount = 0; 159 160 private boolean mNoChips = false; 161 162 private ListPopupWindow mAlternatesPopup; 163 164 private ListPopupWindow mAddressPopup; 165 166 private ArrayList<RecipientChip> mTemporaryRecipients; 167 168 private ArrayList<RecipientChip> mRemovedSpans; 169 170 private boolean mShouldShrink = true; 171 172 // Chip copy fields. 173 private GestureDetector mGestureDetector; 174 175 private Dialog mCopyDialog; 176 177 private String mCopyAddress; 178 179 /** 180 * Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a 181 * selected chip. 182 */ 183 private OnItemClickListener mAlternatesListener; 184 185 private int mCheckedItem; 186 187 private TextWatcher mTextWatcher; 188 189 // Obtain the enclosing scroll view, if it exists, so that the view can be 190 // scrolled to show the last line of chips content. 191 private ScrollView mScrollView; 192 193 private boolean mTriedGettingScrollView; 194 195 private boolean mDragEnabled = false; 196 197 // This pattern comes from android.util.Patterns. It has been tweaked to handle a "1" before 198 // parens, so numbers such as "1 (425) 222-2342" match. 199 private static final Pattern PHONE_PATTERN 200 = Pattern.compile( // sdd = space, dot, or dash 201 "(\\+[0-9]+[\\- \\.]*)?" // +<digits><sdd>* 202 + "(1?[ ]*\\([0-9]+\\)[\\- \\.]*)?" // 1(<digits>)<sdd>* 203 + "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit> 204 205 private final Runnable mAddTextWatcher = new Runnable() { 206 @Override 207 public void run() { 208 if (mTextWatcher == null) { 209 mTextWatcher = new RecipientTextWatcher(); 210 addTextChangedListener(mTextWatcher); 211 } 212 } 213 }; 214 215 private IndividualReplacementTask mIndividualReplacements; 216 217 private Runnable mHandlePendingChips = new Runnable() { 218 219 @Override 220 public void run() { 221 handlePendingChips(); 222 } 223 224 }; 225 226 private Runnable mDelayedShrink = new Runnable() { 227 228 @Override 229 public void run() { 230 shrink(); 231 } 232 233 }; 234 235 private int mMaxLines; 236 237 public RecipientEditTextView(Context context, AttributeSet attrs) { 238 super(context, attrs); 239 setChipDimensions(context, attrs); 240 if (sSelectedTextColor == -1) { 241 sSelectedTextColor = context.getResources().getColor(android.R.color.white); 242 } 243 mAlternatesPopup = new ListPopupWindow(context); 244 mAddressPopup = new ListPopupWindow(context); 245 mCopyDialog = new Dialog(context); 246 mAlternatesListener = new OnItemClickListener() { 247 @Override 248 public void onItemClick(AdapterView<?> adapterView,View view, int position, 249 long rowId) { 250 mAlternatesPopup.setOnItemClickListener(null); 251 replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter()) 252 .getRecipientEntry(position)); 253 Message delayed = Message.obtain(mHandler, DISMISS); 254 delayed.obj = mAlternatesPopup; 255 mHandler.sendMessageDelayed(delayed, DISMISS_DELAY); 256 clearComposingText(); 257 } 258 }; 259 setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); 260 setOnItemClickListener(this); 261 setCustomSelectionActionModeCallback(this); 262 mHandler = new Handler() { 263 @Override 264 public void handleMessage(Message msg) { 265 if (msg.what == DISMISS) { 266 ((ListPopupWindow) msg.obj).dismiss(); 267 return; 268 } 269 super.handleMessage(msg); 270 } 271 }; 272 mTextWatcher = new RecipientTextWatcher(); 273 addTextChangedListener(mTextWatcher); 274 mGestureDetector = new GestureDetector(context, this); 275 setOnEditorActionListener(this); 276 mMaxLines = getLineCount(); 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 RecipientChip(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 = context.getResources().getDimension(R.dimen.line_spacing_extra); 711 a.recycle(); 712 } 713 714 // Visible for testing. 715 /* package */ void setMoreItem(TextView moreItem) { 716 mMoreItem = moreItem; 717 } 718 719 720 // Visible for testing. 721 /* package */ void setChipBackground(Drawable chipBackground) { 722 mChipBackground = chipBackground; 723 } 724 725 // Visible for testing. 726 /* package */ void setChipHeight(int height) { 727 mChipHeight = height; 728 } 729 730 /** 731 * Set whether to shrink the recipients field such that at most 732 * one line of recipients chips are shown when the field loses 733 * focus. By default, the number of displayed recipients will be 734 * limited and a "more" chip will be shown when focus is lost. 735 * @param shrink 736 */ 737 public void setOnFocusListShrinkRecipients(boolean shrink) { 738 mShouldShrink = shrink; 739 } 740 741 @Override 742 public void onSizeChanged(int width, int height, int oldw, int oldh) { 743 super.onSizeChanged(width, height, oldw, oldh); 744 if (width != 0 && height != 0) { 745 if (mPendingChipsCount > 0) { 746 postHandlePendingChips(); 747 } else { 748 checkChipWidths(); 749 } 750 } 751 // Try to find the scroll view parent, if it exists. 752 if (mScrollView == null && !mTriedGettingScrollView) { 753 ViewParent parent = getParent(); 754 while (parent != null && !(parent instanceof ScrollView)) { 755 parent = parent.getParent(); 756 } 757 if (parent != null) { 758 mScrollView = (ScrollView) parent; 759 } 760 mTriedGettingScrollView = true; 761 } 762 } 763 764 private void postHandlePendingChips() { 765 mHandler.removeCallbacks(mHandlePendingChips); 766 mHandler.post(mHandlePendingChips); 767 } 768 769 private void checkChipWidths() { 770 // Check the widths of the associated chips. 771 RecipientChip[] chips = getSortedRecipients(); 772 if (chips != null) { 773 Rect bounds; 774 for (RecipientChip chip : chips) { 775 bounds = chip.getDrawable().getBounds(); 776 if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) { 777 // Need to redraw that chip. 778 replaceChip(chip, chip.getEntry()); 779 } 780 } 781 } 782 } 783 784 // Visible for testing. 785 /*package*/ void handlePendingChips() { 786 if (getViewWidth() <= 0) { 787 // The widget has not been sized yet. 788 // This will be called as a result of onSizeChanged 789 // at a later point. 790 return; 791 } 792 if (mPendingChipsCount <= 0) { 793 return; 794 } 795 796 synchronized (mPendingChips) { 797 Editable editable = getText(); 798 // Tokenize! 799 if (mPendingChipsCount <= MAX_CHIPS_PARSED) { 800 for (int i = 0; i < mPendingChips.size(); i++) { 801 String current = mPendingChips.get(i); 802 int tokenStart = editable.toString().indexOf(current); 803 int tokenEnd = tokenStart + current.length(); 804 if (tokenStart >= 0) { 805 // When we have a valid token, include it with the token 806 // to the left. 807 if (tokenEnd < editable.length() - 2 808 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) { 809 tokenEnd++; 810 } 811 createReplacementChip(tokenStart, tokenEnd, editable); 812 } 813 mPendingChipsCount--; 814 } 815 sanitizeEnd(); 816 } else { 817 mNoChips = true; 818 } 819 820 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0 821 && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) { 822 if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) { 823 new RecipientReplacementTask().execute(); 824 mTemporaryRecipients = null; 825 } else { 826 // Create the "more" chip 827 mIndividualReplacements = new IndividualReplacementTask(); 828 mIndividualReplacements.execute(new ArrayList<RecipientChip>( 829 mTemporaryRecipients.subList(0, CHIP_LIMIT))); 830 if (mTemporaryRecipients.size() > CHIP_LIMIT) { 831 mTemporaryRecipients = new ArrayList<RecipientChip>( 832 mTemporaryRecipients.subList(CHIP_LIMIT, 833 mTemporaryRecipients.size())); 834 } else { 835 mTemporaryRecipients = null; 836 } 837 createMoreChip(); 838 } 839 } else { 840 // There are too many recipients to look up, so just fall back 841 // to showing addresses for all of them. 842 mTemporaryRecipients = null; 843 createMoreChip(); 844 } 845 mPendingChipsCount = 0; 846 mPendingChips.clear(); 847 } 848 } 849 850 // Visible for testing. 851 /*package*/ int getViewWidth() { 852 return getWidth(); 853 } 854 855 /** 856 * Remove any characters after the last valid chip. 857 */ 858 // Visible for testing. 859 /*package*/ void sanitizeEnd() { 860 // Don't sanitize while we are waiting for pending chips to complete. 861 if (mPendingChipsCount > 0) { 862 return; 863 } 864 // Find the last chip; eliminate any commit characters after it. 865 RecipientChip[] chips = getSortedRecipients(); 866 if (chips != null && chips.length > 0) { 867 int end; 868 ImageSpan lastSpan; 869 mMoreChip = getMoreChip(); 870 if (mMoreChip != null) { 871 lastSpan = mMoreChip; 872 } else { 873 lastSpan = getLastChip(); 874 } 875 end = getSpannable().getSpanEnd(lastSpan); 876 Editable editable = getText(); 877 int length = editable.length(); 878 if (length > end) { 879 // See what characters occur after that and eliminate them. 880 if (Log.isLoggable(TAG, Log.DEBUG)) { 881 Log.d(TAG, "There were extra characters after the last tokenizable entry." 882 + editable); 883 } 884 editable.delete(end + 1, length); 885 } 886 } 887 } 888 889 /** 890 * Create a chip that represents just the email address of a recipient. At some later 891 * point, this chip will be attached to a real contact entry, if one exists. 892 */ 893 private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) { 894 if (alreadyHasChip(tokenStart, tokenEnd)) { 895 // There is already a chip present at this location. 896 // Don't recreate it. 897 return; 898 } 899 String token = editable.toString().substring(tokenStart, tokenEnd); 900 int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA); 901 if (commitCharIndex == token.length() - 1) { 902 token = token.substring(0, token.length() - 1); 903 } 904 RecipientEntry entry = createTokenizedEntry(token); 905 if (entry != null) { 906 String destText = createAddressText(entry); 907 SpannableString chipText = new SpannableString(destText); 908 RecipientChip chip = null; 909 try { 910 if (!mNoChips) { 911 /* leave space for the contact icon if this is not just an email address */ 912 chip = constructChipSpan( 913 entry, 914 tokenStart, 915 false, 916 TextUtils.isEmpty(entry.getDisplayName()) 917 || TextUtils.equals(entry.getDisplayName(), 918 entry.getDestination())); 919 } 920 } catch (NullPointerException e) { 921 Log.e(TAG, e.getMessage(), e); 922 } 923 editable.setSpan(chip, tokenStart, tokenEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 924 // Add this chip to the list of entries "to replace" 925 if (chip != null) { 926 if (mTemporaryRecipients == null) { 927 mTemporaryRecipients = new ArrayList<RecipientChip>(); 928 } 929 chip.setOriginalText(chipText.toString()); 930 mTemporaryRecipients.add(chip); 931 } 932 } 933 } 934 935 private static boolean isPhoneNumber(String number) { 936 // TODO: replace this function with libphonenumber's isPossibleNumber (see 937 // PhoneNumberUtil). One complication is that it requires the sender's region which 938 // comes from the CurrentCountryIso. For now, let's just do this simple match. 939 if (TextUtils.isEmpty(number)) { 940 return false; 941 } 942 943 Matcher match = PHONE_PATTERN.matcher(number); 944 return match.matches(); 945 } 946 947 private RecipientEntry createTokenizedEntry(String token) { 948 if (TextUtils.isEmpty(token)) { 949 return null; 950 } 951 if (isPhoneQuery() && isPhoneNumber(token)) { 952 return RecipientEntry.constructFakeEntry(token, true); 953 } 954 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token); 955 String display = null; 956 boolean isValid = isValid(token); 957 if (isValid && tokens != null && tokens.length > 0) { 958 // If we can get a name from tokenizing, then generate an entry from 959 // this. 960 display = tokens[0].getName(); 961 if (!TextUtils.isEmpty(display)) { 962 if (!isPhoneQuery()) { 963 if (!TextUtils.isEmpty(token)) { 964 token = token.trim(); 965 } 966 char charAt = token.charAt(token.length() - 1); 967 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) { 968 token = token.substring(0, token.length() - 1); 969 } 970 } 971 return RecipientEntry.constructGeneratedEntry(display, token, isValid); 972 } else { 973 display = tokens[0].getAddress(); 974 if (!TextUtils.isEmpty(display)) { 975 return RecipientEntry.constructFakeEntry(display, isValid); 976 } 977 } 978 } 979 // Unable to validate the token or to create a valid token from it. 980 // Just create a chip the user can edit. 981 String validatedToken = null; 982 if (mValidator != null && !isValid) { 983 // Try fixing up the entry using the validator. 984 validatedToken = mValidator.fixText(token).toString(); 985 if (!TextUtils.isEmpty(validatedToken)) { 986 if (validatedToken.contains(token)) { 987 // protect against the case of a validator with a null 988 // domain, 989 // which doesn't add a domain to the token 990 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken); 991 if (tokenized.length > 0) { 992 validatedToken = tokenized[0].getAddress(); 993 isValid = true; 994 } 995 } else { 996 // We ran into a case where the token was invalid and 997 // removed 998 // by the validator. In this case, just use the original 999 // token 1000 // and let the user sort out the error chip. 1001 validatedToken = null; 1002 isValid = false; 1003 } 1004 } 1005 } 1006 // Otherwise, fallback to just creating an editable email address chip. 1007 return RecipientEntry.constructFakeEntry( 1008 !TextUtils.isEmpty(validatedToken) ? validatedToken : token, isValid); 1009 } 1010 1011 private boolean isValid(String text) { 1012 return mValidator == null ? true : mValidator.isValid(text); 1013 } 1014 1015 private String tokenizeAddress(String destination) { 1016 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination); 1017 if (tokens != null && tokens.length > 0) { 1018 return tokens[0].getAddress(); 1019 } 1020 return destination; 1021 } 1022 1023 @Override 1024 public void setTokenizer(Tokenizer tokenizer) { 1025 mTokenizer = tokenizer; 1026 super.setTokenizer(mTokenizer); 1027 } 1028 1029 @Override 1030 public void setValidator(Validator validator) { 1031 mValidator = validator; 1032 super.setValidator(validator); 1033 } 1034 1035 /** 1036 * We cannot use the default mechanism for replaceText. Instead, 1037 * we override onItemClickListener so we can get all the associated 1038 * contact information including display text, address, and id. 1039 */ 1040 @Override 1041 protected void replaceText(CharSequence text) { 1042 return; 1043 } 1044 1045 /** 1046 * Dismiss any selected chips when the back key is pressed. 1047 */ 1048 @Override 1049 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 1050 if (keyCode == KeyEvent.KEYCODE_BACK && mSelectedChip != null) { 1051 clearSelectedChip(); 1052 return true; 1053 } 1054 return super.onKeyPreIme(keyCode, event); 1055 } 1056 1057 /** 1058 * Monitor key presses in this view to see if the user types 1059 * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER. 1060 * If the user has entered text that has contact matches and types 1061 * a commit key, create a chip from the topmost matching contact. 1062 * If the user has entered text that has no contact matches and types 1063 * a commit key, then create a chip from the text they have entered. 1064 */ 1065 @Override 1066 public boolean onKeyUp(int keyCode, KeyEvent event) { 1067 switch (keyCode) { 1068 case KeyEvent.KEYCODE_ENTER: 1069 case KeyEvent.KEYCODE_DPAD_CENTER: 1070 if (event.hasNoModifiers()) { 1071 if (commitDefault()) { 1072 return true; 1073 } 1074 if (mSelectedChip != null) { 1075 clearSelectedChip(); 1076 return true; 1077 } else if (focusNext()) { 1078 return true; 1079 } 1080 } 1081 break; 1082 case KeyEvent.KEYCODE_TAB: 1083 if (event.hasNoModifiers()) { 1084 if (mSelectedChip != null) { 1085 clearSelectedChip(); 1086 } else { 1087 commitDefault(); 1088 } 1089 if (focusNext()) { 1090 return true; 1091 } 1092 } 1093 break; 1094 } 1095 return super.onKeyUp(keyCode, event); 1096 } 1097 1098 private boolean focusNext() { 1099 View next = focusSearch(View.FOCUS_DOWN); 1100 if (next != null) { 1101 next.requestFocus(); 1102 return true; 1103 } 1104 return false; 1105 } 1106 1107 /** 1108 * Create a chip from the default selection. If the popup is showing, the 1109 * default is the first item in the popup suggestions list. Otherwise, it is 1110 * whatever the user had typed in. End represents where the the tokenizer 1111 * should search for a token to turn into a chip. 1112 * @return If a chip was created from a real contact. 1113 */ 1114 private boolean commitDefault() { 1115 // If there is no tokenizer, don't try to commit. 1116 if (mTokenizer == null) { 1117 return false; 1118 } 1119 Editable editable = getText(); 1120 int end = getSelectionEnd(); 1121 int start = mTokenizer.findTokenStart(editable, end); 1122 1123 if (shouldCreateChip(start, end)) { 1124 int whatEnd = mTokenizer.findTokenEnd(getText(), start); 1125 // In the middle of chip; treat this as an edit 1126 // and commit the whole token. 1127 whatEnd = movePastTerminators(whatEnd); 1128 if (whatEnd != getSelectionEnd()) { 1129 handleEdit(start, whatEnd); 1130 return true; 1131 } 1132 return commitChip(start, end , editable); 1133 } 1134 return false; 1135 } 1136 1137 private void commitByCharacter() { 1138 // We can't possibly commit by character if we can't tokenize. 1139 if (mTokenizer == null) { 1140 return; 1141 } 1142 Editable editable = getText(); 1143 int end = getSelectionEnd(); 1144 int start = mTokenizer.findTokenStart(editable, end); 1145 if (shouldCreateChip(start, end)) { 1146 commitChip(start, end, editable); 1147 } 1148 setSelection(getText().length()); 1149 } 1150 1151 private boolean commitChip(int start, int end, Editable editable) { 1152 ListAdapter adapter = getAdapter(); 1153 if (adapter != null && adapter.getCount() > 0 && enoughToFilter() 1154 && end == getSelectionEnd() && !isPhoneQuery()) { 1155 // choose the first entry. 1156 submitItemAtPosition(0); 1157 dismissDropDown(); 1158 return true; 1159 } else { 1160 int tokenEnd = mTokenizer.findTokenEnd(editable, start); 1161 if (editable.length() > tokenEnd + 1) { 1162 char charAt = editable.charAt(tokenEnd + 1); 1163 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) { 1164 tokenEnd++; 1165 } 1166 } 1167 String text = editable.toString().substring(start, tokenEnd).trim(); 1168 clearComposingText(); 1169 if (text != null && text.length() > 0 && !text.equals(" ")) { 1170 RecipientEntry entry = createTokenizedEntry(text); 1171 if (entry != null) { 1172 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1173 CharSequence chipText = createChip(entry, false); 1174 if (chipText != null && start > -1 && end > -1) { 1175 editable.replace(start, end, chipText); 1176 } 1177 } 1178 // Only dismiss the dropdown if it is related to the text we 1179 // just committed. 1180 // For paste, it may not be as there are possibly multiple 1181 // tokens being added. 1182 if (end == getSelectionEnd()) { 1183 dismissDropDown(); 1184 } 1185 sanitizeBetween(); 1186 return true; 1187 } 1188 } 1189 return false; 1190 } 1191 1192 // Visible for testing. 1193 /* package */ void sanitizeBetween() { 1194 // Don't sanitize while we are waiting for content to chipify. 1195 if (mPendingChipsCount > 0) { 1196 return; 1197 } 1198 // Find the last chip. 1199 RecipientChip[] recips = getSortedRecipients(); 1200 if (recips != null && recips.length > 0) { 1201 RecipientChip last = recips[recips.length - 1]; 1202 RecipientChip beforeLast = null; 1203 if (recips.length > 1) { 1204 beforeLast = recips[recips.length - 2]; 1205 } 1206 int startLooking = 0; 1207 int end = getSpannable().getSpanStart(last); 1208 if (beforeLast != null) { 1209 startLooking = getSpannable().getSpanEnd(beforeLast); 1210 Editable text = getText(); 1211 if (startLooking == -1 || startLooking > text.length() - 1) { 1212 // There is nothing after this chip. 1213 return; 1214 } 1215 if (text.charAt(startLooking) == ' ') { 1216 startLooking++; 1217 } 1218 } 1219 if (startLooking >= 0 && end >= 0 && startLooking < end) { 1220 getText().delete(startLooking, end); 1221 } 1222 } 1223 } 1224 1225 private boolean shouldCreateChip(int start, int end) { 1226 return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end); 1227 } 1228 1229 private boolean alreadyHasChip(int start, int end) { 1230 if (mNoChips) { 1231 return true; 1232 } 1233 RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.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 if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) { 1277 return true; 1278 } 1279 1280 return super.onKeyDown(keyCode, event); 1281 } 1282 1283 // Visible for testing. 1284 /* package */ Spannable getSpannable() { 1285 return getText(); 1286 } 1287 1288 private int getChipStart(RecipientChip chip) { 1289 return getSpannable().getSpanStart(chip); 1290 } 1291 1292 private int getChipEnd(RecipientChip chip) { 1293 return getSpannable().getSpanEnd(chip); 1294 } 1295 1296 /** 1297 * Instead of filtering on the entire contents of the edit box, 1298 * this subclass method filters on the range from 1299 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd} 1300 * if the length of that range meets or exceeds {@link #getThreshold} 1301 * and makes sure that the range is not already a Chip. 1302 */ 1303 @Override 1304 protected void performFiltering(CharSequence text, int keyCode) { 1305 if (enoughToFilter() && !isCompletedToken(text)) { 1306 int end = getSelectionEnd(); 1307 int start = mTokenizer.findTokenStart(text, end); 1308 // If this is a RecipientChip, don't filter 1309 // on its contents. 1310 Spannable span = getSpannable(); 1311 RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class); 1312 if (chips != null && chips.length > 0) { 1313 return; 1314 } 1315 } 1316 super.performFiltering(text, keyCode); 1317 } 1318 1319 // Visible for testing. 1320 /*package*/ boolean isCompletedToken(CharSequence text) { 1321 if (TextUtils.isEmpty(text)) { 1322 return false; 1323 } 1324 // Check to see if this is a completed token before filtering. 1325 int end = text.length(); 1326 int start = mTokenizer.findTokenStart(text, end); 1327 String token = text.toString().substring(start, end).trim(); 1328 if (!TextUtils.isEmpty(token)) { 1329 char atEnd = token.charAt(token.length() - 1); 1330 return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON; 1331 } 1332 return false; 1333 } 1334 1335 private void clearSelectedChip() { 1336 if (mSelectedChip != null) { 1337 unselectChip(mSelectedChip); 1338 mSelectedChip = null; 1339 } 1340 setCursorVisible(true); 1341 } 1342 1343 /** 1344 * Monitor touch events in the RecipientEditTextView. 1345 * If the view does not have focus, any tap on the view 1346 * will just focus the view. If the view has focus, determine 1347 * if the touch target is a recipient chip. If it is and the chip 1348 * is not selected, select it and clear any other selected chips. 1349 * If it isn't, then select that chip. 1350 */ 1351 @Override 1352 public boolean onTouchEvent(MotionEvent event) { 1353 if (!isFocused()) { 1354 // Ignore any chip taps until this view is focused. 1355 return super.onTouchEvent(event); 1356 } 1357 boolean handled = super.onTouchEvent(event); 1358 int action = event.getAction(); 1359 boolean chipWasSelected = false; 1360 if (mSelectedChip == null) { 1361 mGestureDetector.onTouchEvent(event); 1362 } 1363 if (mCopyAddress == null && action == MotionEvent.ACTION_UP) { 1364 float x = event.getX(); 1365 float y = event.getY(); 1366 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 1367 RecipientChip currentChip = findChip(offset); 1368 if (currentChip != null) { 1369 if (action == MotionEvent.ACTION_UP) { 1370 if (mSelectedChip != null && mSelectedChip != currentChip) { 1371 clearSelectedChip(); 1372 mSelectedChip = selectChip(currentChip); 1373 } else if (mSelectedChip == null) { 1374 setSelection(getText().length()); 1375 commitDefault(); 1376 mSelectedChip = selectChip(currentChip); 1377 } else { 1378 onClick(mSelectedChip, offset, x, y); 1379 } 1380 } 1381 chipWasSelected = true; 1382 handled = true; 1383 } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) { 1384 chipWasSelected = true; 1385 } 1386 } 1387 if (action == MotionEvent.ACTION_UP && !chipWasSelected) { 1388 clearSelectedChip(); 1389 } 1390 return handled; 1391 } 1392 1393 private void scrollLineIntoView(int line) { 1394 if (mScrollView != null) { 1395 mScrollView.scrollBy(0, calculateOffsetFromBottom(line)); 1396 } 1397 } 1398 1399 private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup, 1400 int width, Context context) { 1401 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1402 int bottom; 1403 if (line == getLineCount() -1) { 1404 bottom = 0; 1405 } else { 1406 bottom = -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math.abs(getLineCount() - 1 1407 - line))); 1408 } 1409 // Align the alternates popup with the left side of the View, 1410 // regardless of the position of the chip tapped. 1411 alternatesPopup.setWidth(width); 1412 alternatesPopup.setAnchorView(this); 1413 alternatesPopup.setVerticalOffset(bottom); 1414 alternatesPopup.setAdapter(createAlternatesAdapter(currentChip)); 1415 alternatesPopup.setOnItemClickListener(mAlternatesListener); 1416 // Clear the checked item. 1417 mCheckedItem = -1; 1418 alternatesPopup.show(); 1419 ListView listView = alternatesPopup.getListView(); 1420 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1421 // Checked item would be -1 if the adapter has not 1422 // loaded the view that should be checked yet. The 1423 // variable will be set correctly when onCheckedItemChanged 1424 // is called in a separate thread. 1425 if (mCheckedItem != -1) { 1426 listView.setItemChecked(mCheckedItem, true); 1427 mCheckedItem = -1; 1428 } 1429 } 1430 1431 private ListAdapter createAlternatesAdapter(RecipientChip chip) { 1432 return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(), 1433 mAlternatesLayout, ((BaseRecipientAdapter)getAdapter()).getQueryType(), this); 1434 } 1435 1436 private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) { 1437 return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip 1438 .getEntry()); 1439 } 1440 1441 @Override 1442 public void onCheckedItemChanged(int position) { 1443 ListView listView = mAlternatesPopup.getListView(); 1444 if (listView != null && listView.getCheckedItemCount() == 0) { 1445 listView.setItemChecked(position, true); 1446 } 1447 mCheckedItem = position; 1448 } 1449 1450 // TODO: This algorithm will need a lot of tweaking after more people have used 1451 // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring 1452 // what comes before the finger. 1453 private int putOffsetInRange(int o) { 1454 int offset = o; 1455 Editable text = getText(); 1456 int length = text.length(); 1457 // Remove whitespace from end to find "real end" 1458 int realLength = length; 1459 for (int i = length - 1; i >= 0; i--) { 1460 if (text.charAt(i) == ' ') { 1461 realLength--; 1462 } else { 1463 break; 1464 } 1465 } 1466 1467 // If the offset is beyond or at the end of the text, 1468 // leave it alone. 1469 if (offset >= realLength) { 1470 return offset; 1471 } 1472 Editable editable = getText(); 1473 while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) { 1474 // Keep walking backward! 1475 offset--; 1476 } 1477 return offset; 1478 } 1479 1480 private int findText(Editable text, int offset) { 1481 if (text.charAt(offset) != ' ') { 1482 return offset; 1483 } 1484 return -1; 1485 } 1486 1487 private RecipientChip findChip(int offset) { 1488 RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class); 1489 // Find the chip that contains this offset. 1490 for (int i = 0; i < chips.length; i++) { 1491 RecipientChip chip = chips[i]; 1492 int start = getChipStart(chip); 1493 int end = getChipEnd(chip); 1494 if (offset >= start && offset <= end) { 1495 return chip; 1496 } 1497 } 1498 return null; 1499 } 1500 1501 // Visible for testing. 1502 // Use this method to generate text to add to the list of addresses. 1503 /* package */String createAddressText(RecipientEntry entry) { 1504 String display = entry.getDisplayName(); 1505 String address = entry.getDestination(); 1506 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1507 display = null; 1508 } 1509 String trimmedDisplayText; 1510 if (isPhoneQuery() && isPhoneNumber(address)) { 1511 trimmedDisplayText = address.trim(); 1512 } else { 1513 if (address != null) { 1514 // Tokenize out the address in case the address already 1515 // contained the username as well. 1516 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1517 if (tokenized != null && tokenized.length > 0) { 1518 address = tokenized[0].getAddress(); 1519 } 1520 } 1521 Rfc822Token token = new Rfc822Token(display, address, null); 1522 trimmedDisplayText = token.toString().trim(); 1523 } 1524 int index = trimmedDisplayText.indexOf(","); 1525 return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText) 1526 && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer 1527 .terminateToken(trimmedDisplayText) : trimmedDisplayText; 1528 } 1529 1530 // Visible for testing. 1531 // Use this method to generate text to display in a chip. 1532 /*package*/ String createChipDisplayText(RecipientEntry entry) { 1533 String display = entry.getDisplayName(); 1534 String address = entry.getDestination(); 1535 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) { 1536 display = null; 1537 } 1538 if (address != null && !(isPhoneQuery() && isPhoneNumber(address))) { 1539 // Tokenize out the address in case the address already 1540 // contained the username as well. 1541 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address); 1542 if (tokenized != null && tokenized.length > 0) { 1543 address = tokenized[0].getAddress(); 1544 } 1545 } 1546 if (!TextUtils.isEmpty(display)) { 1547 return display; 1548 } else if (!TextUtils.isEmpty(address)){ 1549 return address; 1550 } else { 1551 return new Rfc822Token(display, address, null).toString(); 1552 } 1553 } 1554 1555 private CharSequence createChip(RecipientEntry entry, boolean pressed) { 1556 String displayText = createAddressText(entry); 1557 if (TextUtils.isEmpty(displayText)) { 1558 return null; 1559 } 1560 SpannableString chipText = null; 1561 // Always leave a blank space at the end of a chip. 1562 int end = getSelectionEnd(); 1563 int start = mTokenizer.findTokenStart(getText(), end); 1564 int textLength = displayText.length()-1; 1565 chipText = new SpannableString(displayText); 1566 if (!mNoChips) { 1567 try { 1568 RecipientChip chip = constructChipSpan(entry, start, pressed, 1569 false /* leave space for contact icon */); 1570 chipText.setSpan(chip, 0, textLength, 1571 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1572 chip.setOriginalText(chipText.toString()); 1573 } catch (NullPointerException e) { 1574 Log.e(TAG, e.getMessage(), e); 1575 return null; 1576 } 1577 } 1578 return chipText; 1579 } 1580 1581 /** 1582 * When an item in the suggestions list has been clicked, create a chip from the 1583 * contact information of the selected item. 1584 */ 1585 @Override 1586 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1587 submitItemAtPosition(position); 1588 } 1589 1590 private void submitItemAtPosition(int position) { 1591 RecipientEntry entry = createValidatedEntry( 1592 (RecipientEntry)getAdapter().getItem(position)); 1593 if (entry == null) { 1594 return; 1595 } 1596 clearComposingText(); 1597 1598 int end = getSelectionEnd(); 1599 int start = mTokenizer.findTokenStart(getText(), end); 1600 1601 Editable editable = getText(); 1602 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1603 CharSequence chip = createChip(entry, false); 1604 if (chip != null && start >= 0 && end >= 0) { 1605 editable.replace(start, end, chip); 1606 } 1607 sanitizeBetween(); 1608 } 1609 1610 private RecipientEntry createValidatedEntry(RecipientEntry item) { 1611 if (item == null) { 1612 return null; 1613 } 1614 final RecipientEntry entry; 1615 // If the display name and the address are the same, or if this is a 1616 // valid contact, but the destination is invalid, then make this a fake 1617 // recipient that is editable. 1618 String destination = item.getDestination(); 1619 if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1620 entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(), 1621 destination, item.isValid()); 1622 } else if (RecipientEntry.isCreatedRecipient(item.getContactId()) 1623 && (TextUtils.isEmpty(item.getDisplayName()) 1624 || TextUtils.equals(item.getDisplayName(), destination) 1625 || (mValidator != null && !mValidator.isValid(destination)))) { 1626 entry = RecipientEntry.constructFakeEntry(destination, item.isValid()); 1627 } else { 1628 entry = item; 1629 } 1630 return entry; 1631 } 1632 1633 /** Returns a collection of contact Id for each chip inside this View. */ 1634 /* package */ Collection<Long> getContactIds() { 1635 final Set<Long> result = new HashSet<Long>(); 1636 RecipientChip[] chips = getSortedRecipients(); 1637 if (chips != null) { 1638 for (RecipientChip chip : chips) { 1639 result.add(chip.getContactId()); 1640 } 1641 } 1642 return result; 1643 } 1644 1645 1646 /** Returns a collection of data Id for each chip inside this View. May be null. */ 1647 /* package */ Collection<Long> getDataIds() { 1648 final Set<Long> result = new HashSet<Long>(); 1649 RecipientChip [] chips = getSortedRecipients(); 1650 if (chips != null) { 1651 for (RecipientChip chip : chips) { 1652 result.add(chip.getDataId()); 1653 } 1654 } 1655 return result; 1656 } 1657 1658 // Visible for testing. 1659 /* package */RecipientChip[] getSortedRecipients() { 1660 RecipientChip[] recips = getSpannable() 1661 .getSpans(0, getText().length(), RecipientChip.class); 1662 ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays 1663 .asList(recips)); 1664 final Spannable spannable = getSpannable(); 1665 Collections.sort(recipientsList, new Comparator<RecipientChip>() { 1666 1667 @Override 1668 public int compare(RecipientChip first, RecipientChip second) { 1669 int firstStart = spannable.getSpanStart(first); 1670 int secondStart = spannable.getSpanStart(second); 1671 if (firstStart < secondStart) { 1672 return -1; 1673 } else if (firstStart > secondStart) { 1674 return 1; 1675 } else { 1676 return 0; 1677 } 1678 } 1679 }); 1680 return recipientsList.toArray(new RecipientChip[recipientsList.size()]); 1681 } 1682 1683 @Override 1684 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 1685 return false; 1686 } 1687 1688 @Override 1689 public void onDestroyActionMode(ActionMode mode) { 1690 } 1691 1692 @Override 1693 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 1694 return false; 1695 } 1696 1697 /** 1698 * No chips are selectable. 1699 */ 1700 @Override 1701 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 1702 return false; 1703 } 1704 1705 // Visible for testing. 1706 /* package */ImageSpan getMoreChip() { 1707 MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(), 1708 MoreImageSpan.class); 1709 return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null; 1710 } 1711 1712 private MoreImageSpan createMoreSpan(int count) { 1713 String moreText = String.format(mMoreItem.getText().toString(), count); 1714 TextPaint morePaint = new TextPaint(getPaint()); 1715 morePaint.setTextSize(mMoreItem.getTextSize()); 1716 morePaint.setColor(mMoreItem.getCurrentTextColor()); 1717 int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft() 1718 + mMoreItem.getPaddingRight(); 1719 int height = getLineHeight(); 1720 Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 1721 Canvas canvas = new Canvas(drawable); 1722 int adjustedHeight = height; 1723 Layout layout = getLayout(); 1724 if (layout != null) { 1725 adjustedHeight -= layout.getLineDescent(0); 1726 } 1727 canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint); 1728 1729 Drawable result = new BitmapDrawable(getResources(), drawable); 1730 result.setBounds(0, 0, width, height); 1731 return new MoreImageSpan(result); 1732 } 1733 1734 // Visible for testing. 1735 /*package*/ void createMoreChipPlainText() { 1736 // Take the first <= CHIP_LIMIT addresses and get to the end of the second one. 1737 Editable text = getText(); 1738 int start = 0; 1739 int end = start; 1740 for (int i = 0; i < CHIP_LIMIT; i++) { 1741 end = movePastTerminators(mTokenizer.findTokenEnd(text, start)); 1742 start = end; // move to the next token and get its end. 1743 } 1744 // Now, count total addresses. 1745 start = 0; 1746 int tokenCount = countTokens(text); 1747 MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT); 1748 SpannableString chipText = new SpannableString(text.subSequence(end, text.length())); 1749 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1750 text.replace(end, text.length(), chipText); 1751 mMoreChip = moreSpan; 1752 } 1753 1754 // Visible for testing. 1755 /* package */int countTokens(Editable text) { 1756 int tokenCount = 0; 1757 int start = 0; 1758 while (start < text.length()) { 1759 start = movePastTerminators(mTokenizer.findTokenEnd(text, start)); 1760 tokenCount++; 1761 if (start >= text.length()) { 1762 break; 1763 } 1764 } 1765 return tokenCount; 1766 } 1767 1768 /** 1769 * Create the more chip. The more chip is text that replaces any chips that 1770 * do not fit in the pre-defined available space when the 1771 * RecipientEditTextView loses focus. 1772 */ 1773 // Visible for testing. 1774 /* package */ void createMoreChip() { 1775 if (mNoChips) { 1776 createMoreChipPlainText(); 1777 return; 1778 } 1779 1780 if (!mShouldShrink) { 1781 return; 1782 } 1783 ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class); 1784 if (tempMore.length > 0) { 1785 getSpannable().removeSpan(tempMore[0]); 1786 } 1787 RecipientChip[] recipients = getSortedRecipients(); 1788 1789 if (recipients == null || recipients.length <= CHIP_LIMIT) { 1790 mMoreChip = null; 1791 return; 1792 } 1793 Spannable spannable = getSpannable(); 1794 int numRecipients = recipients.length; 1795 int overage = numRecipients - CHIP_LIMIT; 1796 MoreImageSpan moreSpan = createMoreSpan(overage); 1797 mRemovedSpans = new ArrayList<RecipientChip>(); 1798 int totalReplaceStart = 0; 1799 int totalReplaceEnd = 0; 1800 Editable text = getText(); 1801 for (int i = numRecipients - overage; i < recipients.length; i++) { 1802 mRemovedSpans.add(recipients[i]); 1803 if (i == numRecipients - overage) { 1804 totalReplaceStart = spannable.getSpanStart(recipients[i]); 1805 } 1806 if (i == recipients.length - 1) { 1807 totalReplaceEnd = spannable.getSpanEnd(recipients[i]); 1808 } 1809 if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) { 1810 int spanStart = spannable.getSpanStart(recipients[i]); 1811 int spanEnd = spannable.getSpanEnd(recipients[i]); 1812 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd)); 1813 } 1814 spannable.removeSpan(recipients[i]); 1815 } 1816 if (totalReplaceEnd < text.length()) { 1817 totalReplaceEnd = text.length(); 1818 } 1819 int end = Math.max(totalReplaceStart, totalReplaceEnd); 1820 int start = Math.min(totalReplaceStart, totalReplaceEnd); 1821 SpannableString chipText = new SpannableString(text.subSequence(start, end)); 1822 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1823 text.replace(start, end, chipText); 1824 mMoreChip = moreSpan; 1825 // If adding the +more chip goes over the limit, resize accordingly. 1826 if (!isPhoneQuery() && getLineCount() > mMaxLines) { 1827 setMaxLines(getLineCount()); 1828 } 1829 } 1830 1831 /** 1832 * Replace the more chip, if it exists, with all of the recipient chips it had 1833 * replaced when the RecipientEditTextView gains focus. 1834 */ 1835 // Visible for testing. 1836 /*package*/ void removeMoreChip() { 1837 if (mMoreChip != null) { 1838 Spannable span = getSpannable(); 1839 span.removeSpan(mMoreChip); 1840 mMoreChip = null; 1841 // Re-add the spans that were removed. 1842 if (mRemovedSpans != null && mRemovedSpans.size() > 0) { 1843 // Recreate each removed span. 1844 RecipientChip[] recipients = getSortedRecipients(); 1845 // Start the search for tokens after the last currently visible 1846 // chip. 1847 if (recipients == null || recipients.length == 0) { 1848 return; 1849 } 1850 int end = span.getSpanEnd(recipients[recipients.length - 1]); 1851 Editable editable = getText(); 1852 for (RecipientChip chip : mRemovedSpans) { 1853 int chipStart; 1854 int chipEnd; 1855 String token; 1856 // Need to find the location of the chip, again. 1857 token = (String) chip.getOriginalText(); 1858 // As we find the matching recipient for the remove spans, 1859 // reduce the size of the string we need to search. 1860 // That way, if there are duplicates, we always find the correct 1861 // recipient. 1862 chipStart = editable.toString().indexOf(token, end); 1863 end = chipEnd = Math.min(editable.length(), chipStart + token.length()); 1864 // Only set the span if we found a matching token. 1865 if (chipStart != -1) { 1866 editable.setSpan(chip, chipStart, chipEnd, 1867 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 1868 } 1869 } 1870 mRemovedSpans.clear(); 1871 } 1872 } 1873 } 1874 1875 /** 1876 * Show specified chip as selected. If the RecipientChip is just an email address, 1877 * selecting the chip will take the contents of the chip and place it at 1878 * the end of the RecipientEditTextView for inline editing. If the 1879 * RecipientChip is a complete contact, then selecting the chip 1880 * will change the background color of the chip, show the delete icon, 1881 * and a popup window with the address in use highlighted and any other 1882 * alternate addresses for the contact. 1883 * @param currentChip Chip to select. 1884 * @return A RecipientChip in the selected state or null if the chip 1885 * just contained an email address. 1886 */ 1887 private RecipientChip selectChip(RecipientChip currentChip) { 1888 if (shouldShowEditableText(currentChip)) { 1889 CharSequence text = currentChip.getValue(); 1890 Editable editable = getText(); 1891 Spannable spannable = getSpannable(); 1892 int spanStart = spannable.getSpanStart(currentChip); 1893 int spanEnd = spannable.getSpanEnd(currentChip); 1894 spannable.removeSpan(currentChip); 1895 editable.delete(spanStart, spanEnd); 1896 setCursorVisible(true); 1897 setSelection(editable.length()); 1898 editable.append(text); 1899 return constructChipSpan( 1900 RecipientEntry.constructFakeEntry((String) text, isValid(text.toString())), 1901 getSelectionStart(), true, false); 1902 } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) { 1903 int start = getChipStart(currentChip); 1904 int end = getChipEnd(currentChip); 1905 getSpannable().removeSpan(currentChip); 1906 RecipientChip newChip; 1907 try { 1908 if (mNoChips) { 1909 return null; 1910 } 1911 newChip = constructChipSpan(currentChip.getEntry(), start, true, false); 1912 } catch (NullPointerException e) { 1913 Log.e(TAG, e.getMessage(), e); 1914 return null; 1915 } 1916 Editable editable = getText(); 1917 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1918 if (start == -1 || end == -1) { 1919 Log.d(TAG, "The chip being selected no longer exists but should."); 1920 } else { 1921 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1922 } 1923 newChip.setSelected(true); 1924 if (shouldShowEditableText(newChip)) { 1925 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1926 } 1927 showAddress(newChip, mAddressPopup, getWidth(), getContext()); 1928 setCursorVisible(false); 1929 return newChip; 1930 } else { 1931 int start = getChipStart(currentChip); 1932 int end = getChipEnd(currentChip); 1933 getSpannable().removeSpan(currentChip); 1934 RecipientChip newChip; 1935 try { 1936 newChip = constructChipSpan(currentChip.getEntry(), start, true, false); 1937 } catch (NullPointerException e) { 1938 Log.e(TAG, e.getMessage(), e); 1939 return null; 1940 } 1941 Editable editable = getText(); 1942 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 1943 if (start == -1 || end == -1) { 1944 Log.d(TAG, "The chip being selected no longer exists but should."); 1945 } else { 1946 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 1947 } 1948 newChip.setSelected(true); 1949 if (shouldShowEditableText(newChip)) { 1950 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); 1951 } 1952 showAlternates(newChip, mAlternatesPopup, getWidth(), getContext()); 1953 setCursorVisible(false); 1954 return newChip; 1955 } 1956 } 1957 1958 private boolean shouldShowEditableText(RecipientChip currentChip) { 1959 long contactId = currentChip.getContactId(); 1960 return contactId == RecipientEntry.INVALID_CONTACT 1961 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT); 1962 } 1963 1964 private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup, 1965 int width, Context context) { 1966 int line = getLayout().getLineForOffset(getChipStart(currentChip)); 1967 int bottom = calculateOffsetFromBottom(line); 1968 // Align the alternates popup with the left side of the View, 1969 // regardless of the position of the chip tapped. 1970 popup.setWidth(width); 1971 popup.setAnchorView(this); 1972 popup.setVerticalOffset(bottom); 1973 popup.setAdapter(createSingleAddressAdapter(currentChip)); 1974 popup.setOnItemClickListener(new OnItemClickListener() { 1975 @Override 1976 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 1977 unselectChip(currentChip); 1978 popup.dismiss(); 1979 } 1980 }); 1981 popup.show(); 1982 ListView listView = popup.getListView(); 1983 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 1984 listView.setItemChecked(0, true); 1985 } 1986 1987 /** 1988 * Remove selection from this chip. Unselecting a RecipientChip will render 1989 * the chip without a delete icon and with an unfocused background. This is 1990 * called when the RecipientChip no longer has focus. 1991 */ 1992 private void unselectChip(RecipientChip chip) { 1993 int start = getChipStart(chip); 1994 int end = getChipEnd(chip); 1995 Editable editable = getText(); 1996 mSelectedChip = null; 1997 if (start == -1 || end == -1) { 1998 Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing"); 1999 setSelection(editable.length()); 2000 commitDefault(); 2001 } else { 2002 getSpannable().removeSpan(chip); 2003 QwertyKeyListener.markAsReplaced(editable, start, end, ""); 2004 editable.removeSpan(chip); 2005 try { 2006 if (!mNoChips) { 2007 editable.setSpan(constructChipSpan(chip.getEntry(), start, false, false), 2008 start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2009 } 2010 } catch (NullPointerException e) { 2011 Log.e(TAG, e.getMessage(), e); 2012 } 2013 } 2014 setCursorVisible(true); 2015 setSelection(editable.length()); 2016 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { 2017 mAlternatesPopup.dismiss(); 2018 } 2019 } 2020 2021 /** 2022 * Return whether a touch event was inside the delete target of 2023 * a selected chip. It is in the delete target if: 2024 * 1) the x and y points of the event are within the 2025 * delete assset. 2026 * 2) the point tapped would have caused a cursor to appear 2027 * right after the selected chip. 2028 * @return boolean 2029 */ 2030 private boolean isInDelete(RecipientChip chip, int offset, float x, float y) { 2031 // Figure out the bounds of this chip and whether or not 2032 // the user clicked in the X portion. 2033 return chip.isSelected() && offset == getChipEnd(chip); 2034 } 2035 2036 /** 2037 * Remove the chip and any text associated with it from the RecipientEditTextView. 2038 */ 2039 // Visible for testing. 2040 /*pacakge*/ void removeChip(RecipientChip chip) { 2041 Spannable spannable = getSpannable(); 2042 int spanStart = spannable.getSpanStart(chip); 2043 int spanEnd = spannable.getSpanEnd(chip); 2044 Editable text = getText(); 2045 int toDelete = spanEnd; 2046 boolean wasSelected = chip == mSelectedChip; 2047 // Clear that there is a selected chip before updating any text. 2048 if (wasSelected) { 2049 mSelectedChip = null; 2050 } 2051 // Always remove trailing spaces when removing a chip. 2052 while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') { 2053 toDelete++; 2054 } 2055 spannable.removeSpan(chip); 2056 if (spanStart >= 0 && toDelete > 0) { 2057 text.delete(spanStart, toDelete); 2058 } 2059 if (wasSelected) { 2060 clearSelectedChip(); 2061 } 2062 } 2063 2064 /** 2065 * Replace this currently selected chip with a new chip 2066 * that uses the contact data provided. 2067 */ 2068 // Visible for testing. 2069 /*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) { 2070 boolean wasSelected = chip == mSelectedChip; 2071 if (wasSelected) { 2072 mSelectedChip = null; 2073 } 2074 int start = getChipStart(chip); 2075 int end = getChipEnd(chip); 2076 getSpannable().removeSpan(chip); 2077 Editable editable = getText(); 2078 CharSequence chipText = createChip(entry, false); 2079 if (chipText != null) { 2080 if (start == -1 || end == -1) { 2081 Log.e(TAG, "The chip to replace does not exist but should."); 2082 editable.insert(0, chipText); 2083 } else { 2084 if (!TextUtils.isEmpty(chipText)) { 2085 // There may be a space to replace with this chip's new 2086 // associated space. Check for it 2087 int toReplace = end; 2088 while (toReplace >= 0 && toReplace < editable.length() 2089 && editable.charAt(toReplace) == ' ') { 2090 toReplace++; 2091 } 2092 editable.replace(start, toReplace, chipText); 2093 } 2094 } 2095 } 2096 setCursorVisible(true); 2097 if (wasSelected) { 2098 clearSelectedChip(); 2099 } 2100 } 2101 2102 /** 2103 * Handle click events for a chip. When a selected chip receives a click 2104 * event, see if that event was in the delete icon. If so, delete it. 2105 * Otherwise, unselect the chip. 2106 */ 2107 public void onClick(RecipientChip chip, int offset, float x, float y) { 2108 if (chip.isSelected()) { 2109 if (isInDelete(chip, offset, x, y)) { 2110 removeChip(chip); 2111 } else { 2112 clearSelectedChip(); 2113 } 2114 } 2115 } 2116 2117 private boolean chipsPending() { 2118 return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0); 2119 } 2120 2121 @Override 2122 public void removeTextChangedListener(TextWatcher watcher) { 2123 mTextWatcher = null; 2124 super.removeTextChangedListener(watcher); 2125 } 2126 2127 private class RecipientTextWatcher implements TextWatcher { 2128 2129 @Override 2130 public void afterTextChanged(Editable s) { 2131 // If the text has been set to null or empty, make sure we remove 2132 // all the spans we applied. 2133 if (TextUtils.isEmpty(s)) { 2134 // Remove all the chips spans. 2135 Spannable spannable = getSpannable(); 2136 RecipientChip[] chips = spannable.getSpans(0, getText().length(), 2137 RecipientChip.class); 2138 for (RecipientChip chip : chips) { 2139 spannable.removeSpan(chip); 2140 } 2141 if (mMoreChip != null) { 2142 spannable.removeSpan(mMoreChip); 2143 } 2144 return; 2145 } 2146 // Get whether there are any recipients pending addition to the 2147 // view. If there are, don't do anything in the text watcher. 2148 if (chipsPending()) { 2149 return; 2150 } 2151 // If the user is editing a chip, don't clear it. 2152 if (mSelectedChip != null) { 2153 if (!isGeneratedContact(mSelectedChip)) { 2154 setCursorVisible(true); 2155 setSelection(getText().length()); 2156 clearSelectedChip(); 2157 } else { 2158 return; 2159 } 2160 } 2161 int length = s.length(); 2162 // Make sure there is content there to parse and that it is 2163 // not just the commit character. 2164 if (length > 1) { 2165 if (lastCharacterIsCommitCharacter(s)) { 2166 commitByCharacter(); 2167 return; 2168 } 2169 char last; 2170 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1; 2171 int len = length() - 1; 2172 if (end != len) { 2173 last = s.charAt(end); 2174 } else { 2175 last = s.charAt(len); 2176 } 2177 if (last == COMMIT_CHAR_SPACE) { 2178 if (!isPhoneQuery()) { 2179 // Check if this is a valid email address. If it is, 2180 // commit it. 2181 String text = getText().toString(); 2182 int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 2183 String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text, 2184 tokenStart)); 2185 if (!TextUtils.isEmpty(sub) && mValidator != null && 2186 mValidator.isValid(sub)) { 2187 commitByCharacter(); 2188 } 2189 } 2190 } 2191 } 2192 } 2193 2194 @Override 2195 public void onTextChanged(CharSequence s, int start, int before, int count) { 2196 // This is a delete; check to see if the insertion point is on a space 2197 // following a chip. 2198 if (before > count) { 2199 // If the item deleted is a space, and the thing before the 2200 // space is a chip, delete the entire span. 2201 int selStart = getSelectionStart(); 2202 RecipientChip[] repl = getSpannable().getSpans(selStart, selStart, 2203 RecipientChip.class); 2204 if (repl.length > 0) { 2205 // There is a chip there! Just remove it. 2206 Editable editable = getText(); 2207 // Add the separator token. 2208 int tokenStart = mTokenizer.findTokenStart(editable, selStart); 2209 int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart); 2210 tokenEnd = tokenEnd + 1; 2211 if (tokenEnd > editable.length()) { 2212 tokenEnd = editable.length(); 2213 } 2214 editable.delete(tokenStart, tokenEnd); 2215 getSpannable().removeSpan(repl[0]); 2216 } 2217 } else if (count > before) { 2218 if (mSelectedChip != null 2219 && isGeneratedContact(mSelectedChip)) { 2220 if (lastCharacterIsCommitCharacter(s)) { 2221 commitByCharacter(); 2222 return; 2223 } 2224 } 2225 scrollBottomIntoView(); 2226 } 2227 } 2228 2229 @Override 2230 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 2231 // Do nothing. 2232 } 2233 } 2234 2235 private void scrollBottomIntoView() { 2236 if (mScrollView != null) { 2237 mScrollView.scrollBy(0, (int) (getLineCount() * mChipHeight)); 2238 } 2239 } 2240 2241 public boolean lastCharacterIsCommitCharacter(CharSequence s) { 2242 char last; 2243 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1; 2244 int len = length() - 1; 2245 if (end != len) { 2246 last = s.charAt(end); 2247 } else { 2248 last = s.charAt(len); 2249 } 2250 return last == COMMIT_CHAR_COMMA || last == COMMIT_CHAR_SEMICOLON; 2251 } 2252 2253 public boolean isGeneratedContact(RecipientChip chip) { 2254 long contactId = chip.getContactId(); 2255 return contactId == RecipientEntry.INVALID_CONTACT 2256 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT); 2257 } 2258 2259 /** 2260 * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}. 2261 */ 2262 private void handlePasteClip(ClipData clip) { 2263 removeTextChangedListener(mTextWatcher); 2264 2265 if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){ 2266 for (int i = 0; i < clip.getItemCount(); i++) { 2267 CharSequence paste = clip.getItemAt(i).getText(); 2268 if (paste != null) { 2269 int start = getSelectionStart(); 2270 int end = getSelectionEnd(); 2271 Editable editable = getText(); 2272 if (start >= 0 && end >= 0 && start != end) { 2273 editable.append(paste, start, end); 2274 } else { 2275 editable.insert(end, paste); 2276 } 2277 handlePasteAndReplace(); 2278 } 2279 } 2280 } 2281 2282 mHandler.post(mAddTextWatcher); 2283 } 2284 2285 @Override 2286 public boolean onTextContextMenuItem(int id) { 2287 if (id == android.R.id.paste) { 2288 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2289 Context.CLIPBOARD_SERVICE); 2290 handlePasteClip(clipboard.getPrimaryClip()); 2291 return true; 2292 } 2293 return super.onTextContextMenuItem(id); 2294 } 2295 2296 private void handlePasteAndReplace() { 2297 ArrayList<RecipientChip> created = handlePaste(); 2298 if (created != null && created.size() > 0) { 2299 // Perform reverse lookups on the pasted contacts. 2300 IndividualReplacementTask replace = new IndividualReplacementTask(); 2301 replace.execute(created); 2302 } 2303 } 2304 2305 // Visible for testing. 2306 /* package */ArrayList<RecipientChip> handlePaste() { 2307 String text = getText().toString(); 2308 int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); 2309 String lastAddress = text.substring(originalTokenStart); 2310 int tokenStart = originalTokenStart; 2311 int prevTokenStart = tokenStart; 2312 RecipientChip findChip = null; 2313 ArrayList<RecipientChip> created = new ArrayList<RecipientChip>(); 2314 if (tokenStart != 0) { 2315 // There are things before this! 2316 while (tokenStart != 0 && findChip == null) { 2317 prevTokenStart = tokenStart; 2318 tokenStart = mTokenizer.findTokenStart(text, tokenStart); 2319 findChip = findChip(tokenStart); 2320 } 2321 if (tokenStart != originalTokenStart) { 2322 if (findChip != null) { 2323 tokenStart = prevTokenStart; 2324 } 2325 int tokenEnd; 2326 RecipientChip createdChip; 2327 while (tokenStart < originalTokenStart) { 2328 tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(), 2329 tokenStart)); 2330 commitChip(tokenStart, tokenEnd, getText()); 2331 createdChip = findChip(tokenStart); 2332 if (createdChip == null) { 2333 break; 2334 } 2335 // +1 for the space at the end. 2336 tokenStart = getSpannable().getSpanEnd(createdChip) + 1; 2337 created.add(createdChip); 2338 } 2339 } 2340 } 2341 // Take a look at the last token. If the token has been completed with a 2342 // commit character, create a chip. 2343 if (isCompletedToken(lastAddress)) { 2344 Editable editable = getText(); 2345 tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart); 2346 commitChip(tokenStart, editable.length(), editable); 2347 created.add(findChip(tokenStart)); 2348 } 2349 return created; 2350 } 2351 2352 // Visible for testing. 2353 /* package */int movePastTerminators(int tokenEnd) { 2354 if (tokenEnd >= length()) { 2355 return tokenEnd; 2356 } 2357 char atEnd = getText().toString().charAt(tokenEnd); 2358 if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) { 2359 tokenEnd++; 2360 } 2361 // This token had not only an end token character, but also a space 2362 // separating it from the next token. 2363 if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') { 2364 tokenEnd++; 2365 } 2366 return tokenEnd; 2367 } 2368 2369 private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> { 2370 private RecipientChip createFreeChip(RecipientEntry entry) { 2371 try { 2372 if (mNoChips) { 2373 return null; 2374 } 2375 return constructChipSpan(entry, -1, false, 2376 false /*leave space for contact icon */); 2377 } catch (NullPointerException e) { 2378 Log.e(TAG, e.getMessage(), e); 2379 return null; 2380 } 2381 } 2382 2383 @Override 2384 protected Void doInBackground(Void... params) { 2385 if (mIndividualReplacements != null) { 2386 mIndividualReplacements.cancel(true); 2387 } 2388 // For each chip in the list, look up the matching contact. 2389 // If there is a match, replace that chip with the matching 2390 // chip. 2391 final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>(); 2392 RecipientChip[] existingChips = getSortedRecipients(); 2393 for (int i = 0; i < existingChips.length; i++) { 2394 originalRecipients.add(existingChips[i]); 2395 } 2396 if (mRemovedSpans != null) { 2397 originalRecipients.addAll(mRemovedSpans); 2398 } 2399 ArrayList<String> addresses = new ArrayList<String>(); 2400 RecipientChip chip; 2401 for (int i = 0; i < originalRecipients.size(); i++) { 2402 chip = originalRecipients.get(i); 2403 if (chip != null) { 2404 addresses.add(createAddressText(chip.getEntry())); 2405 } 2406 } 2407 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 2408 .getMatchingRecipients(getContext(), addresses); 2409 final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>(); 2410 for (final RecipientChip temp : originalRecipients) { 2411 RecipientEntry entry = null; 2412 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 2413 && getSpannable().getSpanStart(temp) != -1) { 2414 // Replace this. 2415 entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry() 2416 .getDestination()))); 2417 } 2418 if (entry != null) { 2419 replacements.add(createFreeChip(entry)); 2420 } else { 2421 replacements.add(temp); 2422 } 2423 } 2424 if (replacements != null && replacements.size() > 0) { 2425 mHandler.post(new Runnable() { 2426 @Override 2427 public void run() { 2428 Editable oldText = getText(); 2429 int start, end; 2430 int i = 0; 2431 for (RecipientChip chip : originalRecipients) { 2432 // Find the location of the chip in the text currently shown. 2433 start = oldText.getSpanStart(chip); 2434 if (start != -1) { 2435 end = oldText.getSpanEnd(chip); 2436 oldText.removeSpan(chip); 2437 RecipientChip replacement = replacements.get(i); 2438 // Make sure we always have just 1 space at the 2439 // end to separate this chip from the next chip. 2440 SpannableString displayText = new SpannableString( 2441 createAddressText(replacement.getEntry()).trim() + " "); 2442 displayText.setSpan(replacement, 0, displayText.length()-1, 2443 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 2444 // Replace the old text we found with with the new display text, 2445 // which now may also contain the display name of the recipient. 2446 oldText.replace(start, end, displayText); 2447 replacement.setOriginalText(displayText.toString()); 2448 } 2449 i++; 2450 } 2451 originalRecipients.clear(); 2452 } 2453 }); 2454 } 2455 return null; 2456 } 2457 } 2458 2459 private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> { 2460 @SuppressWarnings("unchecked") 2461 @Override 2462 protected Void doInBackground(Object... params) { 2463 // For each chip in the list, look up the matching contact. 2464 // If there is a match, replace that chip with the matching 2465 // chip. 2466 final ArrayList<RecipientChip> originalRecipients = 2467 (ArrayList<RecipientChip>) params[0]; 2468 ArrayList<String> addresses = new ArrayList<String>(); 2469 RecipientChip chip; 2470 for (int i = 0; i < originalRecipients.size(); i++) { 2471 chip = originalRecipients.get(i); 2472 if (chip != null) { 2473 addresses.add(createAddressText(chip.getEntry())); 2474 } 2475 } 2476 HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter 2477 .getMatchingRecipients(getContext(), addresses); 2478 for (final RecipientChip temp : originalRecipients) { 2479 if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) 2480 && getSpannable().getSpanStart(temp) != -1) { 2481 // Replace this. 2482 RecipientEntry entry = createValidatedEntry(entries.get(tokenizeAddress( 2483 temp.getEntry().getDestination()).toLowerCase())); 2484 // If we don't have a validated contact match, just use the 2485 // entry as it existed before. 2486 if (entry == null && !isPhoneQuery()) { 2487 entry = temp.getEntry(); 2488 } 2489 final RecipientEntry tempEntry = entry; 2490 if (tempEntry != null) { 2491 mHandler.post(new Runnable() { 2492 @Override 2493 public void run() { 2494 replaceChip(temp, tempEntry); 2495 } 2496 }); 2497 } 2498 } 2499 } 2500 return null; 2501 } 2502 } 2503 2504 2505 /** 2506 * MoreImageSpan is a simple class created for tracking the existence of a 2507 * more chip across activity restarts/ 2508 */ 2509 private class MoreImageSpan extends ImageSpan { 2510 public MoreImageSpan(Drawable b) { 2511 super(b); 2512 } 2513 } 2514 2515 @Override 2516 public boolean onDown(MotionEvent e) { 2517 return false; 2518 } 2519 2520 @Override 2521 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 2522 // Do nothing. 2523 return false; 2524 } 2525 2526 @Override 2527 public void onLongPress(MotionEvent event) { 2528 if (mSelectedChip != null) { 2529 return; 2530 } 2531 float x = event.getX(); 2532 float y = event.getY(); 2533 int offset = putOffsetInRange(getOffsetForPosition(x, y)); 2534 RecipientChip currentChip = findChip(offset); 2535 if (currentChip != null) { 2536 if (mDragEnabled) { 2537 // Start drag-and-drop for the selected chip. 2538 startDrag(currentChip); 2539 } else { 2540 // Copy the selected chip email address. 2541 showCopyDialog(currentChip.getEntry().getDestination()); 2542 } 2543 } 2544 } 2545 2546 /** 2547 * Enables drag-and-drop for chips. 2548 */ 2549 public void enableDrag() { 2550 mDragEnabled = true; 2551 } 2552 2553 /** 2554 * Starts drag-and-drop for the selected chip. 2555 */ 2556 private void startDrag(RecipientChip currentChip) { 2557 String address = currentChip.getEntry().getDestination(); 2558 ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA); 2559 2560 // Start drag mode. 2561 startDrag(data, new RecipientChipShadow(currentChip), null, 0); 2562 2563 // Remove the current chip, so drag-and-drop will result in a move. 2564 // TODO (phamm): consider readd this chip if it's dropped outside a target. 2565 removeChip(currentChip); 2566 } 2567 2568 /** 2569 * Handles drag event. 2570 */ 2571 @Override 2572 public boolean onDragEvent(DragEvent event) { 2573 switch (event.getAction()) { 2574 case DragEvent.ACTION_DRAG_STARTED: 2575 // Only handle plain text drag and drop. 2576 return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN); 2577 case DragEvent.ACTION_DRAG_ENTERED: 2578 requestFocus(); 2579 return true; 2580 case DragEvent.ACTION_DROP: 2581 handlePasteClip(event.getClipData()); 2582 return true; 2583 } 2584 return false; 2585 } 2586 2587 /** 2588 * Drag shadow for a {@link RecipientChip}. 2589 */ 2590 private final class RecipientChipShadow extends DragShadowBuilder { 2591 private final RecipientChip mChip; 2592 2593 public RecipientChipShadow(RecipientChip chip) { 2594 mChip = chip; 2595 } 2596 2597 @Override 2598 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 2599 Rect rect = mChip.getDrawable().getBounds(); 2600 shadowSize.set(rect.width(), rect.height()); 2601 shadowTouchPoint.set(rect.centerX(), rect.centerY()); 2602 } 2603 2604 @Override 2605 public void onDrawShadow(Canvas canvas) { 2606 mChip.getDrawable().draw(canvas); 2607 } 2608 } 2609 2610 private void showCopyDialog(final String address) { 2611 mCopyAddress = address; 2612 mCopyDialog.setTitle(address); 2613 mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout); 2614 mCopyDialog.setCancelable(true); 2615 mCopyDialog.setCanceledOnTouchOutside(true); 2616 Button button = (Button)mCopyDialog.findViewById(android.R.id.button1); 2617 button.setOnClickListener(this); 2618 int btnTitleId; 2619 if (isPhoneQuery()) { 2620 btnTitleId = R.string.copy_number; 2621 } else { 2622 btnTitleId = R.string.copy_email; 2623 } 2624 String buttonTitle = getContext().getResources().getString(btnTitleId); 2625 button.setText(buttonTitle); 2626 mCopyDialog.setOnDismissListener(this); 2627 mCopyDialog.show(); 2628 } 2629 2630 @Override 2631 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 2632 // Do nothing. 2633 return false; 2634 } 2635 2636 @Override 2637 public void onShowPress(MotionEvent e) { 2638 // Do nothing. 2639 } 2640 2641 @Override 2642 public boolean onSingleTapUp(MotionEvent e) { 2643 // Do nothing. 2644 return false; 2645 } 2646 2647 @Override 2648 public void onDismiss(DialogInterface dialog) { 2649 mCopyAddress = null; 2650 } 2651 2652 @Override 2653 public void onClick(View v) { 2654 // Copy this to the clipboard. 2655 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( 2656 Context.CLIPBOARD_SERVICE); 2657 clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress)); 2658 mCopyDialog.dismiss(); 2659 } 2660 2661 protected boolean isPhoneQuery() { 2662 return getAdapter() != null 2663 && ((BaseRecipientAdapter) getAdapter()).getQueryType() 2664 == BaseRecipientAdapter.QUERY_TYPE_PHONE; 2665 } 2666} 2667