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