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