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