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