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