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