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