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