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