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