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