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