RecipientEditTextView.java revision 444f2054519c0f5d96d9352ac30e03787a881d80
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        // Don't sanitize while we are waiting for pending chips to complete.
764        if (mPendingChipsCount > 0) {
765            return;
766        }
767        // Find the last chip; eliminate any commit characters after it.
768        RecipientChip[] chips = getSortedRecipients();
769        if (chips != null && chips.length > 0) {
770            int end;
771            ImageSpan lastSpan;
772            mMoreChip = getMoreChip();
773            if (mMoreChip != null) {
774                lastSpan = mMoreChip;
775            } else {
776                lastSpan = getLastChip();
777            }
778            end = getSpannable().getSpanEnd(lastSpan);
779            Editable editable = getText();
780            int length = editable.length();
781            if (length > end) {
782                // See what characters occur after that and eliminate them.
783                if (Log.isLoggable(TAG, Log.DEBUG)) {
784                    Log.d(TAG, "There were extra characters after the last tokenizable entry."
785                            + editable);
786                }
787                editable.delete(end + 1, length);
788            }
789        }
790    }
791
792    /**
793     * Create a chip that represents just the email address of a recipient. At some later
794     * point, this chip will be attached to a real contact entry, if one exists.
795     */
796    private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) {
797        if (alreadyHasChip(tokenStart, tokenEnd)) {
798            // There is already a chip present at this location.
799            // Don't recreate it.
800            return;
801        }
802        String token = editable.toString().substring(tokenStart, tokenEnd);
803        int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA);
804        if (commitCharIndex == token.length() - 1) {
805            token = token.substring(0, token.length() - 1);
806        }
807        RecipientEntry entry = createTokenizedEntry(token);
808        if (entry != null) {
809            String destText = createAddressText(entry);
810            // Always leave a blank space at the end of a chip.
811            int textLength = destText.length() - 1;
812            SpannableString chipText = new SpannableString(destText);
813            int end = getSelectionEnd();
814            int start = mTokenizer.findTokenStart(getText(), end);
815            RecipientChip chip = null;
816            try {
817                if (!mNoChips) {
818                    chip = constructChipSpan(entry, start, false);
819                    chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
820                }
821            } catch (NullPointerException e) {
822                Log.e(TAG, e.getMessage(), e);
823            }
824            editable.replace(tokenStart, tokenEnd, chipText);
825            // Add this chip to the list of entries "to replace"
826            if (chip != null) {
827                if (mTemporaryRecipients == null) {
828                    mTemporaryRecipients = new ArrayList<RecipientChip>();
829                }
830                chip.setOriginalText(chipText.toString());
831                mTemporaryRecipients.add(chip);
832            }
833        }
834    }
835
836    private RecipientEntry createTokenizedEntry(String token) {
837        if (TextUtils.isEmpty(token)) {
838            return null;
839        }
840        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
841        String display = null;
842        if (isValid(token) && tokens != null && tokens.length > 0) {
843            // If we can get a name from tokenizing, then generate an entry from
844            // this.
845            display = tokens[0].getName();
846            if (!TextUtils.isEmpty(display)) {
847                return RecipientEntry.constructGeneratedEntry(display, token);
848            } else {
849                display = tokens[0].getAddress();
850                if (!TextUtils.isEmpty(display)) {
851                    return RecipientEntry.constructFakeEntry(display);
852                }
853            }
854        }
855        // Unable to validate the token or to create a valid token from it.
856        // Just create a chip the user can edit.
857        String validatedToken = null;
858        if (mValidator != null && !mValidator.isValid(token)) {
859            // Try fixing up the entry using the validator.
860            validatedToken = mValidator.fixText(token).toString();
861            if (!TextUtils.isEmpty(validatedToken)) {
862                if (validatedToken.contains(token)) {
863                    // protect against the case of a validator with a null domain,
864                    // which doesn't add a domain to the token
865                    Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
866                    if (tokenized.length > 0) {
867                        validatedToken = tokenized[0].getAddress();
868                    }
869                } else {
870                    // We ran into a case where the token was invalid and removed
871                    // by the validator. In this case, just use the original token
872                    // and let the user sort out the error chip.
873                    validatedToken = null;
874                }
875            }
876        }
877        // Otherwise, fallback to just creating an editable email address chip.
878        return RecipientEntry
879                .constructFakeEntry(!TextUtils.isEmpty(validatedToken) ? validatedToken : token);
880    }
881
882    private boolean isValid(String text) {
883        return mValidator == null ? true : mValidator.isValid(text);
884    }
885
886    private String tokenizeAddress(String destination) {
887        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
888        if (tokens != null && tokens.length > 0) {
889            return tokens[0].getAddress();
890        }
891        return destination;
892    }
893
894    @Override
895    public void setTokenizer(Tokenizer tokenizer) {
896        mTokenizer = tokenizer;
897        super.setTokenizer(mTokenizer);
898    }
899
900    @Override
901    public void setValidator(Validator validator) {
902        mValidator = validator;
903        super.setValidator(validator);
904    }
905
906    /**
907     * We cannot use the default mechanism for replaceText. Instead,
908     * we override onItemClickListener so we can get all the associated
909     * contact information including display text, address, and id.
910     */
911    @Override
912    protected void replaceText(CharSequence text) {
913        return;
914    }
915
916    /**
917     * Dismiss any selected chips when the back key is pressed.
918     */
919    @Override
920    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
921        if (keyCode == KeyEvent.KEYCODE_BACK) {
922            clearSelectedChip();
923        }
924        return super.onKeyPreIme(keyCode, event);
925    }
926
927    /**
928     * Monitor key presses in this view to see if the user types
929     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
930     * If the user has entered text that has contact matches and types
931     * a commit key, create a chip from the topmost matching contact.
932     * If the user has entered text that has no contact matches and types
933     * a commit key, then create a chip from the text they have entered.
934     */
935    @Override
936    public boolean onKeyUp(int keyCode, KeyEvent event) {
937        switch (keyCode) {
938            case KeyEvent.KEYCODE_ENTER:
939            case KeyEvent.KEYCODE_DPAD_CENTER:
940                if (event.hasNoModifiers()) {
941                    if (commitDefault()) {
942                        return true;
943                    }
944                    if (mSelectedChip != null) {
945                        clearSelectedChip();
946                        return true;
947                    } else if (focusNext()) {
948                        return true;
949                    }
950                }
951                break;
952            case KeyEvent.KEYCODE_TAB:
953                if (event.hasNoModifiers()) {
954                    if (mSelectedChip != null) {
955                        clearSelectedChip();
956                    } else {
957                        commitDefault();
958                    }
959                    if (focusNext()) {
960                        return true;
961                    }
962                }
963        }
964        return super.onKeyUp(keyCode, event);
965    }
966
967    private boolean focusNext() {
968        View next = focusSearch(View.FOCUS_DOWN);
969        if (next != null) {
970            next.requestFocus();
971            return true;
972        }
973        return false;
974    }
975
976    /**
977     * Create a chip from the default selection. If the popup is showing, the
978     * default is the first item in the popup suggestions list. Otherwise, it is
979     * whatever the user had typed in. End represents where the the tokenizer
980     * should search for a token to turn into a chip.
981     * @return If a chip was created from a real contact.
982     */
983    private boolean commitDefault() {
984        Editable editable = getText();
985        int end = getSelectionEnd();
986        int start = mTokenizer.findTokenStart(editable, end);
987
988        if (shouldCreateChip(start, end)) {
989            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
990            // In the middle of chip; treat this as an edit
991            // and commit the whole token.
992            if (whatEnd != getSelectionEnd()) {
993                handleEdit(start, whatEnd);
994                return true;
995            }
996            return commitChip(start, end , editable);
997        }
998        return false;
999    }
1000
1001    private void commitByCharacter() {
1002        Editable editable = getText();
1003        int end = getSelectionEnd();
1004        int start = mTokenizer.findTokenStart(editable, end);
1005        if (shouldCreateChip(start, end)) {
1006            commitChip(start, end, editable);
1007        }
1008        setSelection(getText().length());
1009    }
1010
1011    private boolean commitChip(int start, int end, Editable editable) {
1012        ListAdapter adapter = getAdapter();
1013        if (adapter != null && adapter.getCount() > 0 && enoughToFilter()
1014                && end == getSelectionEnd()) {
1015            // choose the first entry.
1016            submitItemAtPosition(0);
1017            dismissDropDown();
1018            return true;
1019        } else {
1020            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
1021            if (editable.length() > tokenEnd + 1) {
1022                char charAt = editable.charAt(tokenEnd + 1);
1023                if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
1024                    tokenEnd++;
1025                }
1026            }
1027            String text = editable.toString().substring(start, tokenEnd).trim();
1028            clearComposingText();
1029            if (text != null && text.length() > 0 && !text.equals(" ")) {
1030                RecipientEntry entry = createTokenizedEntry(text);
1031                if (entry != null) {
1032                    QwertyKeyListener.markAsReplaced(editable, start, end, "");
1033                    CharSequence chipText = createChip(entry, false);
1034                    if (chipText != null && start > -1 && end > -1) {
1035                        editable.replace(start, end, chipText);
1036                    }
1037                }
1038                // Only dismiss the dropdown if it is related to the text we
1039                // just committed.
1040                // For paste, it may not be as there are possibly multiple
1041                // tokens being added.
1042                if (end == getSelectionEnd()) {
1043                    dismissDropDown();
1044                }
1045                sanitizeBetween();
1046                return true;
1047            }
1048        }
1049        return false;
1050    }
1051
1052    // Visible for testing.
1053    /* package */ void sanitizeBetween() {
1054        // Don't sanitize while we are waiting for content to chipify.
1055        if (mPendingChipsCount > 0) {
1056            return;
1057        }
1058        // Find the last chip.
1059        RecipientChip[] recips = getSortedRecipients();
1060        if (recips != null && recips.length > 0) {
1061            RecipientChip last = recips[recips.length - 1];
1062            RecipientChip beforeLast = null;
1063            if (recips.length > 1) {
1064                beforeLast = recips[recips.length - 2];
1065            }
1066            int startLooking = 0;
1067            int end = getSpannable().getSpanStart(last);
1068            if (beforeLast != null) {
1069                startLooking = getSpannable().getSpanEnd(beforeLast);
1070                Editable text = getText();
1071                if (startLooking == -1 || startLooking > text.length() - 1) {
1072                    // There is nothing after this chip.
1073                    return;
1074                }
1075                if (text.charAt(startLooking) == ' ') {
1076                    startLooking++;
1077                }
1078            }
1079            if (startLooking >= 0 && end >= 0 && startLooking != end) {
1080                getText().delete(startLooking, end);
1081            }
1082        }
1083    }
1084
1085    private boolean shouldCreateChip(int start, int end) {
1086        return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
1087    }
1088
1089    private boolean alreadyHasChip(int start, int end) {
1090        if (mNoChips) {
1091            return true;
1092        }
1093        RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
1094        if ((chips == null || chips.length == 0)) {
1095            return false;
1096        }
1097        return true;
1098    }
1099
1100    private void handleEdit(int start, int end) {
1101        if (start == -1 || end == -1) {
1102            // This chip no longer exists in the field.
1103            dismissDropDown();
1104            return;
1105        }
1106        // This is in the middle of a chip, so select out the whole chip
1107        // and commit it.
1108        Editable editable = getText();
1109        setSelection(end);
1110        String text = getText().toString().substring(start, end);
1111        if (!TextUtils.isEmpty(text)) {
1112            RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
1113            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1114            CharSequence chipText = createChip(entry, false);
1115            int selEnd = getSelectionEnd();
1116            if (chipText != null && start > -1 && selEnd > -1) {
1117                editable.replace(start, selEnd, chipText);
1118            }
1119        }
1120        dismissDropDown();
1121    }
1122
1123    /**
1124     * If there is a selected chip, delegate the key events
1125     * to the selected chip.
1126     */
1127    @Override
1128    public boolean onKeyDown(int keyCode, KeyEvent event) {
1129        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
1130            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1131                mAlternatesPopup.dismiss();
1132            }
1133            removeChip(mSelectedChip);
1134        }
1135
1136        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
1137            return true;
1138        }
1139
1140        return super.onKeyDown(keyCode, event);
1141    }
1142
1143    // Visible for testing.
1144    /* package */ Spannable getSpannable() {
1145        return getText();
1146    }
1147
1148    private int getChipStart(RecipientChip chip) {
1149        return getSpannable().getSpanStart(chip);
1150    }
1151
1152    private int getChipEnd(RecipientChip chip) {
1153        return getSpannable().getSpanEnd(chip);
1154    }
1155
1156    /**
1157     * Instead of filtering on the entire contents of the edit box,
1158     * this subclass method filters on the range from
1159     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
1160     * if the length of that range meets or exceeds {@link #getThreshold}
1161     * and makes sure that the range is not already a Chip.
1162     */
1163    @Override
1164    protected void performFiltering(CharSequence text, int keyCode) {
1165        if (enoughToFilter() && !isCompletedToken(text)) {
1166            int end = getSelectionEnd();
1167            int start = mTokenizer.findTokenStart(text, end);
1168            // If this is a RecipientChip, don't filter
1169            // on its contents.
1170            Spannable span = getSpannable();
1171            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
1172            if (chips != null && chips.length > 0) {
1173                return;
1174            }
1175        }
1176        super.performFiltering(text, keyCode);
1177    }
1178
1179    // Visible for testing.
1180    /*package*/ boolean isCompletedToken(CharSequence text) {
1181        if (TextUtils.isEmpty(text)) {
1182            return false;
1183        }
1184        // Check to see if this is a completed token before filtering.
1185        int end = text.length();
1186        int start = mTokenizer.findTokenStart(text, end);
1187        String token = text.toString().substring(start, end).trim();
1188        if (!TextUtils.isEmpty(token)) {
1189            char atEnd = token.charAt(token.length() - 1);
1190            return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
1191        }
1192        return false;
1193    }
1194
1195    private void clearSelectedChip() {
1196        if (mSelectedChip != null) {
1197            unselectChip(mSelectedChip);
1198            mSelectedChip = null;
1199        }
1200        setCursorVisible(true);
1201    }
1202
1203    /**
1204     * Monitor touch events in the RecipientEditTextView.
1205     * If the view does not have focus, any tap on the view
1206     * will just focus the view. If the view has focus, determine
1207     * if the touch target is a recipient chip. If it is and the chip
1208     * is not selected, select it and clear any other selected chips.
1209     * If it isn't, then select that chip.
1210     */
1211    @Override
1212    public boolean onTouchEvent(MotionEvent event) {
1213        if (!isFocused()) {
1214            // Ignore any chip taps until this view is focused.
1215            return super.onTouchEvent(event);
1216        }
1217        boolean handled = super.onTouchEvent(event);
1218        int action = event.getAction();
1219        boolean chipWasSelected = false;
1220        if (mSelectedChip == null) {
1221            mGestureDetector.onTouchEvent(event);
1222        }
1223        if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
1224            float x = event.getX();
1225            float y = event.getY();
1226            int offset = putOffsetInRange(getOffsetForPosition(x, y));
1227            RecipientChip currentChip = findChip(offset);
1228            if (currentChip != null) {
1229                if (action == MotionEvent.ACTION_UP) {
1230                    if (mSelectedChip != null && mSelectedChip != currentChip) {
1231                        clearSelectedChip();
1232                        mSelectedChip = selectChip(currentChip);
1233                    } else if (mSelectedChip == null) {
1234                        setSelection(getText().length());
1235                        commitDefault();
1236                        mSelectedChip = selectChip(currentChip);
1237                    } else {
1238                        onClick(mSelectedChip, offset, x, y);
1239                    }
1240                }
1241                chipWasSelected = true;
1242                handled = true;
1243            } else if (mSelectedChip != null
1244                    && mSelectedChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1245                chipWasSelected = true;
1246            }
1247        }
1248        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1249            clearSelectedChip();
1250        }
1251        return handled;
1252    }
1253
1254    private void scrollLineIntoView(int line) {
1255        if (mScrollView != null) {
1256            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
1257        }
1258    }
1259
1260    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
1261            int width, Context context) {
1262        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1263        int bottom = calculateOffsetFromBottom(line);
1264        // Align the alternates popup with the left side of the View,
1265        // regardless of the position of the chip tapped.
1266        alternatesPopup.setWidth(width);
1267        setEnabled(false);
1268        alternatesPopup.setAnchorView(this);
1269        alternatesPopup.setVerticalOffset(bottom);
1270        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
1271        alternatesPopup.setOnItemClickListener(mAlternatesListener);
1272        // Clear the checked item.
1273        mCheckedItem = -1;
1274        alternatesPopup.show();
1275        ListView listView = alternatesPopup.getListView();
1276        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1277        // Checked item would be -1 if the adapter has not
1278        // loaded the view that should be checked yet. The
1279        // variable will be set correctly when onCheckedItemChanged
1280        // is called in a separate thread.
1281        if (mCheckedItem != -1) {
1282            listView.setItemChecked(mCheckedItem, true);
1283            mCheckedItem = -1;
1284        }
1285    }
1286
1287    // Dismiss listener for alterns and single address popup.
1288    @Override
1289    public void onDismiss() {
1290        setEnabled(true);
1291    }
1292
1293    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
1294        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
1295                mAlternatesLayout, this);
1296    }
1297
1298    private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
1299        return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
1300                .getEntry());
1301    }
1302
1303    @Override
1304    public void onCheckedItemChanged(int position) {
1305        ListView listView = mAlternatesPopup.getListView();
1306        if (listView != null && listView.getCheckedItemCount() == 0) {
1307            listView.setItemChecked(position, true);
1308        }
1309        mCheckedItem = position;
1310    }
1311
1312    // TODO: This algorithm will need a lot of tweaking after more people have used
1313    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1314    // what comes before the finger.
1315    private int putOffsetInRange(int o) {
1316        int offset = o;
1317        Editable text = getText();
1318        int length = text.length();
1319        // Remove whitespace from end to find "real end"
1320        int realLength = length;
1321        for (int i = length - 1; i >= 0; i--) {
1322            if (text.charAt(i) == ' ') {
1323                realLength--;
1324            } else {
1325                break;
1326            }
1327        }
1328
1329        // If the offset is beyond or at the end of the text,
1330        // leave it alone.
1331        if (offset >= realLength) {
1332            return offset;
1333        }
1334        Editable editable = getText();
1335        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1336            // Keep walking backward!
1337            offset--;
1338        }
1339        return offset;
1340    }
1341
1342    private int findText(Editable text, int offset) {
1343        if (text.charAt(offset) != ' ') {
1344            return offset;
1345        }
1346        return -1;
1347    }
1348
1349    private RecipientChip findChip(int offset) {
1350        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1351        // Find the chip that contains this offset.
1352        for (int i = 0; i < chips.length; i++) {
1353            RecipientChip chip = chips[i];
1354            int start = getChipStart(chip);
1355            int end = getChipEnd(chip);
1356            if (offset >= start && offset <= end) {
1357                return chip;
1358            }
1359        }
1360        return null;
1361    }
1362
1363    // Visible for testing.
1364    // Use this method to generate text to add to the list of addresses.
1365    /*package*/ String createAddressText(RecipientEntry entry) {
1366        String display = entry.getDisplayName();
1367        String address = entry.getDestination();
1368        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1369            display = null;
1370        }
1371        if (address != null) {
1372            // Tokenize out the address in case the address already
1373            // contained the username as well.
1374            Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1375            if (tokenized != null && tokenized.length > 0) {
1376                address = tokenized[0].getAddress();
1377            }
1378        }
1379        Rfc822Token token = new Rfc822Token(display, address, null);
1380        String trimmedDisplayText = token.toString().trim();
1381        int index = trimmedDisplayText.indexOf(",");
1382        return index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
1383                .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1384    }
1385
1386    // Visible for testing.
1387    // Use this method to generate text to display in a chip.
1388    /*package*/ String createChipDisplayText(RecipientEntry entry) {
1389        String display = entry.getDisplayName();
1390        String address = entry.getDestination();
1391        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1392            display = null;
1393        }
1394        if (address != null) {
1395            // Tokenize out the address in case the address already
1396            // contained the username as well.
1397            Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1398            if (tokenized != null && tokenized.length > 0) {
1399                address = tokenized[0].getAddress();
1400            }
1401        }
1402        if (!TextUtils.isEmpty(display)) {
1403            return display;
1404        } else if (!TextUtils.isEmpty(address)){
1405            return address;
1406        } else {
1407            return new Rfc822Token(display, address, null).toString();
1408        }
1409    }
1410
1411    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1412        String displayText = createAddressText(entry);
1413        if (TextUtils.isEmpty(displayText)) {
1414            return null;
1415        }
1416        SpannableString chipText = null;
1417        // Always leave a blank space at the end of a chip.
1418        int end = getSelectionEnd();
1419        int start = mTokenizer.findTokenStart(getText(), end);
1420        int textLength = displayText.length()-1;
1421        chipText = new SpannableString(displayText);
1422        if (!mNoChips) {
1423            try {
1424                RecipientChip chip = constructChipSpan(entry, start, pressed);
1425                chipText.setSpan(chip, 0, textLength,
1426                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1427                chip.setOriginalText(chipText.toString());
1428            } catch (NullPointerException e) {
1429                Log.e(TAG, e.getMessage(), e);
1430                return null;
1431            }
1432        }
1433        return chipText;
1434    }
1435
1436    /**
1437     * When an item in the suggestions list has been clicked, create a chip from the
1438     * contact information of the selected item.
1439     */
1440    @Override
1441    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1442        submitItemAtPosition(position);
1443    }
1444
1445    private void submitItemAtPosition(int position) {
1446        RecipientEntry entry = createValidatedEntry(
1447                (RecipientEntry)getAdapter().getItem(position));
1448        if (entry == null) {
1449            return;
1450        }
1451        clearComposingText();
1452
1453        int end = getSelectionEnd();
1454        int start = mTokenizer.findTokenStart(getText(), end);
1455
1456        Editable editable = getText();
1457        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1458        CharSequence chip = createChip(entry, false);
1459        if (chip != null && start >= 0 && end >= 0) {
1460            editable.replace(start, end, chip);
1461        }
1462        sanitizeBetween();
1463    }
1464
1465    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1466        if (item == null) {
1467            return null;
1468        }
1469        final RecipientEntry entry;
1470        // If the display name and the address are the same, or if this is a
1471        // valid contact, but the destination is invalid, then make this a fake
1472        // recipient that is editable.
1473        String destination = item.getDestination();
1474        if (RecipientEntry.isCreatedRecipient(item.getContactId())
1475                && (TextUtils.isEmpty(item.getDisplayName())
1476                        || TextUtils.equals(item.getDisplayName(), destination)
1477                        || (mValidator != null && !mValidator.isValid(destination)))) {
1478            entry = RecipientEntry.constructFakeEntry(destination);
1479        } else {
1480            entry = item;
1481        }
1482        return entry;
1483    }
1484
1485    /** Returns a collection of contact Id for each chip inside this View. */
1486    /* package */ Collection<Long> getContactIds() {
1487        final Set<Long> result = new HashSet<Long>();
1488        RecipientChip[] chips = getSortedRecipients();
1489        if (chips != null) {
1490            for (RecipientChip chip : chips) {
1491                result.add(chip.getContactId());
1492            }
1493        }
1494        return result;
1495    }
1496
1497
1498    /** Returns a collection of data Id for each chip inside this View. May be null. */
1499    /* package */ Collection<Long> getDataIds() {
1500        final Set<Long> result = new HashSet<Long>();
1501        RecipientChip [] chips = getSortedRecipients();
1502        if (chips != null) {
1503            for (RecipientChip chip : chips) {
1504                result.add(chip.getDataId());
1505            }
1506        }
1507        return result;
1508    }
1509
1510    // Visible for testing.
1511    /* package */RecipientChip[] getSortedRecipients() {
1512        RecipientChip[] recips = getSpannable()
1513                .getSpans(0, getText().length(), RecipientChip.class);
1514        ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays
1515                .asList(recips));
1516        final Spannable spannable = getSpannable();
1517        Collections.sort(recipientsList, new Comparator<RecipientChip>() {
1518
1519            @Override
1520            public int compare(RecipientChip first, RecipientChip second) {
1521                int firstStart = spannable.getSpanStart(first);
1522                int secondStart = spannable.getSpanStart(second);
1523                if (firstStart < secondStart) {
1524                    return -1;
1525                } else if (firstStart > secondStart) {
1526                    return 1;
1527                } else {
1528                    return 0;
1529                }
1530            }
1531        });
1532        return recipientsList.toArray(new RecipientChip[recipientsList.size()]);
1533    }
1534
1535    @Override
1536    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1537        return false;
1538    }
1539
1540    @Override
1541    public void onDestroyActionMode(ActionMode mode) {
1542    }
1543
1544    @Override
1545    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1546        return false;
1547    }
1548
1549    /**
1550     * No chips are selectable.
1551     */
1552    @Override
1553    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1554        return false;
1555    }
1556
1557    // Visible for testing.
1558    /* package */ImageSpan getMoreChip() {
1559        MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
1560                MoreImageSpan.class);
1561        return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
1562    }
1563
1564    private MoreImageSpan createMoreSpan(int count) {
1565        String moreText = String.format(mMoreItem.getText().toString(), count);
1566        TextPaint morePaint = new TextPaint(getPaint());
1567        morePaint.setTextSize(mMoreItem.getTextSize());
1568        morePaint.setColor(mMoreItem.getCurrentTextColor());
1569        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1570                + mMoreItem.getPaddingRight();
1571        int height = getLineHeight();
1572        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1573        Canvas canvas = new Canvas(drawable);
1574        int adjustedHeight = height;
1575        Layout layout = getLayout();
1576        if (layout != null) {
1577            adjustedHeight -= layout.getLineDescent(0);
1578        }
1579        canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
1580
1581        Drawable result = new BitmapDrawable(getResources(), drawable);
1582        result.setBounds(0, 0, width, height);
1583        return new MoreImageSpan(result);
1584    }
1585
1586    // Visible for testing.
1587    /*package*/ void createMoreChipPlainText() {
1588        // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
1589        Editable text = getText();
1590        int start = 0;
1591        int end = start;
1592        for (int i = 0; i < CHIP_LIMIT; i++) {
1593            end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1594            start = end; // move to the next token and get its end.
1595        }
1596        // Now, count total addresses.
1597        start = 0;
1598        int tokenCount = countTokens(text);
1599        MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
1600        SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
1601        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1602        text.replace(end, text.length(), chipText);
1603        mMoreChip = moreSpan;
1604    }
1605
1606    // Visible for testing.
1607    /* package */int countTokens(Editable text) {
1608        int tokenCount = 0;
1609        int start = 0;
1610        while (start < text.length()) {
1611            start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1612            tokenCount++;
1613            if (start >= text.length()) {
1614                break;
1615            }
1616        }
1617        return tokenCount;
1618    }
1619
1620    /**
1621     * Create the more chip. The more chip is text that replaces any chips that
1622     * do not fit in the pre-defined available space when the
1623     * RecipientEditTextView loses focus.
1624     */
1625    // Visible for testing.
1626    /* package */ void createMoreChip() {
1627        if (mNoChips) {
1628            createMoreChipPlainText();
1629            return;
1630        }
1631
1632        if (!mShouldShrink) {
1633            return;
1634        }
1635
1636        ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
1637        if (tempMore.length > 0) {
1638            getSpannable().removeSpan(tempMore[0]);
1639        }
1640        RecipientChip[] recipients = getSortedRecipients();
1641
1642        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1643            mMoreChip = null;
1644            return;
1645        }
1646        Spannable spannable = getSpannable();
1647        int numRecipients = recipients.length;
1648        int overage = numRecipients - CHIP_LIMIT;
1649        MoreImageSpan moreSpan = createMoreSpan(overage);
1650        mRemovedSpans = new ArrayList<RecipientChip>();
1651        int totalReplaceStart = 0;
1652        int totalReplaceEnd = 0;
1653        Editable text = getText();
1654        for (int i = numRecipients - overage; i < recipients.length; i++) {
1655            mRemovedSpans.add(recipients[i]);
1656            if (i == numRecipients - overage) {
1657                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1658            }
1659            if (i == recipients.length - 1) {
1660                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1661            }
1662            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
1663                int spanStart = spannable.getSpanStart(recipients[i]);
1664                int spanEnd = spannable.getSpanEnd(recipients[i]);
1665                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
1666            }
1667            spannable.removeSpan(recipients[i]);
1668        }
1669        if (totalReplaceEnd < text.length()) {
1670            totalReplaceEnd = text.length();
1671        }
1672        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1673        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1674        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1675        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1676        text.replace(start, end, chipText);
1677        mMoreChip = moreSpan;
1678    }
1679
1680    /**
1681     * Replace the more chip, if it exists, with all of the recipient chips it had
1682     * replaced when the RecipientEditTextView gains focus.
1683     */
1684    // Visible for testing.
1685    /*package*/ void removeMoreChip() {
1686        if (mMoreChip != null) {
1687            Spannable span = getSpannable();
1688            span.removeSpan(mMoreChip);
1689            mMoreChip = null;
1690            // Re-add the spans that were removed.
1691            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1692                // Recreate each removed span.
1693                RecipientChip[] recipients = getSortedRecipients();
1694                // Start the search for tokens after the last currently visible
1695                // chip.
1696                if (recipients == null || recipients.length == 0) {
1697                    return;
1698                }
1699                int end = span.getSpanEnd(recipients[recipients.length - 1]);
1700                Editable editable = getText();
1701                for (RecipientChip chip : mRemovedSpans) {
1702                    int chipStart;
1703                    int chipEnd;
1704                    String token;
1705                    // Need to find the location of the chip, again.
1706                    token = (String) chip.getOriginalText();
1707                    // As we find the matching recipient for the remove spans,
1708                    // reduce the size of the string we need to search.
1709                    // That way, if there are duplicates, we always find the correct
1710                    // recipient.
1711                    chipStart = editable.toString().indexOf(token, end);
1712                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
1713                    // Only set the span if we found a matching token.
1714                    if (chipStart != -1) {
1715                        editable.setSpan(chip, chipStart, chipEnd,
1716                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1717                    }
1718                }
1719                mRemovedSpans.clear();
1720            }
1721        }
1722    }
1723
1724    /**
1725     * Show specified chip as selected. If the RecipientChip is just an email address,
1726     * selecting the chip will take the contents of the chip and place it at
1727     * the end of the RecipientEditTextView for inline editing. If the
1728     * RecipientChip is a complete contact, then selecting the chip
1729     * will change the background color of the chip, show the delete icon,
1730     * and a popup window with the address in use highlighted and any other
1731     * alternate addresses for the contact.
1732     * @param currentChip Chip to select.
1733     * @return A RecipientChip in the selected state or null if the chip
1734     * just contained an email address.
1735     */
1736    private RecipientChip selectChip(RecipientChip currentChip) {
1737        if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1738            CharSequence text = currentChip.getValue();
1739            Editable editable = getText();
1740            removeChip(currentChip);
1741            editable.append(text);
1742            setCursorVisible(true);
1743            setSelection(editable.length());
1744            return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1);
1745        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1746            int start = getChipStart(currentChip);
1747            int end = getChipEnd(currentChip);
1748            getSpannable().removeSpan(currentChip);
1749            RecipientChip newChip;
1750            try {
1751                if (mNoChips) {
1752                    return null;
1753                }
1754                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1755            } catch (NullPointerException e) {
1756                Log.e(TAG, e.getMessage(), e);
1757                return null;
1758            }
1759            Editable editable = getText();
1760            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1761            if (start == -1 || end == -1) {
1762                Log.d(TAG, "The chip being selected no longer exists but should.");
1763            } else {
1764                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1765            }
1766            newChip.setSelected(true);
1767            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1768                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1769            }
1770            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1771            setCursorVisible(false);
1772            return newChip;
1773        } else {
1774            int start = getChipStart(currentChip);
1775            int end = getChipEnd(currentChip);
1776            getSpannable().removeSpan(currentChip);
1777            RecipientChip newChip;
1778            try {
1779                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1780            } catch (NullPointerException e) {
1781                Log.e(TAG, e.getMessage(), e);
1782                return null;
1783            }
1784            Editable editable = getText();
1785            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1786            if (start == -1 || end == -1) {
1787                Log.d(TAG, "The chip being selected no longer exists but should.");
1788            } else {
1789                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1790            }
1791            newChip.setSelected(true);
1792            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1793                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1794            }
1795            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1796            setCursorVisible(false);
1797            return newChip;
1798        }
1799    }
1800
1801
1802    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
1803            int width, Context context) {
1804        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1805        int bottom = calculateOffsetFromBottom(line);
1806        // Align the alternates popup with the left side of the View,
1807        // regardless of the position of the chip tapped.
1808        setEnabled(false);
1809        popup.setWidth(width);
1810        popup.setAnchorView(this);
1811        popup.setVerticalOffset(bottom);
1812        popup.setAdapter(createSingleAddressAdapter(currentChip));
1813        popup.setOnItemClickListener(new OnItemClickListener() {
1814            @Override
1815            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1816                unselectChip(currentChip);
1817                popup.dismiss();
1818            }
1819        });
1820        popup.show();
1821        ListView listView = popup.getListView();
1822        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1823        listView.setItemChecked(0, true);
1824    }
1825
1826    /**
1827     * Remove selection from this chip. Unselecting a RecipientChip will render
1828     * the chip without a delete icon and with an unfocused background. This is
1829     * called when the RecipientChip no longer has focus.
1830     */
1831    private void unselectChip(RecipientChip chip) {
1832        int start = getChipStart(chip);
1833        int end = getChipEnd(chip);
1834        Editable editable = getText();
1835        mSelectedChip = null;
1836        if (start == -1 || end == -1) {
1837            Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
1838            setSelection(editable.length());
1839            commitDefault();
1840        } else {
1841            getSpannable().removeSpan(chip);
1842            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1843            editable.removeSpan(chip);
1844            try {
1845                if (!mNoChips) {
1846                    editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1847                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1848                }
1849            } catch (NullPointerException e) {
1850                Log.e(TAG, e.getMessage(), e);
1851            }
1852        }
1853        setCursorVisible(true);
1854        setSelection(editable.length());
1855        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1856            mAlternatesPopup.dismiss();
1857        }
1858    }
1859
1860    /**
1861     * Return whether a touch event was inside the delete target of
1862     * a selected chip. It is in the delete target if:
1863     * 1) the x and y points of the event are within the
1864     * delete assset.
1865     * 2) the point tapped would have caused a cursor to appear
1866     * right after the selected chip.
1867     * @return boolean
1868     */
1869    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1870        // Figure out the bounds of this chip and whether or not
1871        // the user clicked in the X portion.
1872        return chip.isSelected() && offset == getChipEnd(chip);
1873    }
1874
1875    /**
1876     * Remove the chip and any text associated with it from the RecipientEditTextView.
1877     */
1878    // Visible for testing.
1879    /*pacakge*/ void removeChip(RecipientChip chip) {
1880        Spannable spannable = getSpannable();
1881        int spanStart = spannable.getSpanStart(chip);
1882        int spanEnd = spannable.getSpanEnd(chip);
1883        Editable text = getText();
1884        int toDelete = spanEnd;
1885        boolean wasSelected = chip == mSelectedChip;
1886        // Clear that there is a selected chip before updating any text.
1887        if (wasSelected) {
1888            mSelectedChip = null;
1889        }
1890        // Always remove trailing spaces when removing a chip.
1891        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
1892            toDelete++;
1893        }
1894        spannable.removeSpan(chip);
1895        text.delete(spanStart, toDelete);
1896        if (wasSelected) {
1897            clearSelectedChip();
1898        }
1899    }
1900
1901    /**
1902     * Replace this currently selected chip with a new chip
1903     * that uses the contact data provided.
1904     */
1905    // Visible for testing.
1906    /*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) {
1907        boolean wasSelected = chip == mSelectedChip;
1908        if (wasSelected) {
1909            mSelectedChip = null;
1910        }
1911        int start = getChipStart(chip);
1912        int end = getChipEnd(chip);
1913        getSpannable().removeSpan(chip);
1914        Editable editable = getText();
1915        CharSequence chipText = createChip(entry, false);
1916        if (chipText != null) {
1917            if (start == -1 || end == -1) {
1918                Log.e(TAG, "The chip to replace does not exist but should.");
1919                editable.insert(0, chipText);
1920            } else {
1921                if (!TextUtils.isEmpty(chipText)) {
1922                    // There may be a space to replace with this chip's new
1923                    // associated
1924                    // space. Check for it
1925                    int toReplace = end;
1926                    while (toReplace >= 0 && toReplace < editable.length()
1927                            && editable.charAt(toReplace) == ' ') {
1928                        toReplace++;
1929                    }
1930                    editable.replace(start, toReplace, chipText);
1931                }
1932            }
1933        }
1934        setCursorVisible(true);
1935        if (wasSelected) {
1936            clearSelectedChip();
1937        }
1938    }
1939
1940    /**
1941     * Handle click events for a chip. When a selected chip receives a click
1942     * event, see if that event was in the delete icon. If so, delete it.
1943     * Otherwise, unselect the chip.
1944     */
1945    public void onClick(RecipientChip chip, int offset, float x, float y) {
1946        if (chip.isSelected()) {
1947            if (isInDelete(chip, offset, x, y)) {
1948                removeChip(chip);
1949            } else {
1950                clearSelectedChip();
1951            }
1952        }
1953    }
1954
1955    private boolean chipsPending() {
1956        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1957    }
1958
1959    @Override
1960    public void removeTextChangedListener(TextWatcher watcher) {
1961        mTextWatcher = null;
1962        super.removeTextChangedListener(watcher);
1963    }
1964
1965    private class RecipientTextWatcher implements TextWatcher {
1966        @Override
1967        public void afterTextChanged(Editable s) {
1968            // If the text has been set to null or empty, make sure we remove
1969            // all the spans we applied.
1970            if (TextUtils.isEmpty(s)) {
1971                // Remove all the chips spans.
1972                Spannable spannable = getSpannable();
1973                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
1974                        RecipientChip.class);
1975                for (RecipientChip chip : chips) {
1976                    spannable.removeSpan(chip);
1977                }
1978                if (mMoreChip != null) {
1979                    spannable.removeSpan(mMoreChip);
1980                }
1981                return;
1982            }
1983            // Get whether there are any recipients pending addition to the
1984            // view. If there are, don't do anything in the text watcher.
1985            if (chipsPending()) {
1986                return;
1987            }
1988            // If the user is editing a chip, don't clear it.
1989            if (mSelectedChip != null
1990                    && mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) {
1991                setCursorVisible(true);
1992                setSelection(getText().length());
1993                clearSelectedChip();
1994            }
1995            int length = s.length();
1996            // Make sure there is content there to parse and that it is
1997            // not just the commit character.
1998            if (length > 1) {
1999                char last;
2000                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2001                int len = length() - 1;
2002                if (end != len) {
2003                    last = s.charAt(end);
2004                } else {
2005                    last = s.charAt(len);
2006                }
2007                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
2008                    commitByCharacter();
2009                } else if (last == COMMIT_CHAR_SPACE) {
2010                    // Check if this is a valid email address. If it is,
2011                    // commit it.
2012                    String text = getText().toString();
2013                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2014                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
2015                            tokenStart));
2016                    if (!TextUtils.isEmpty(sub) && mValidator != null && mValidator.isValid(sub)) {
2017                        commitByCharacter();
2018                    }
2019                }
2020            }
2021        }
2022
2023        @Override
2024        public void onTextChanged(CharSequence s, int start, int before, int count) {
2025            // Do nothing.
2026        }
2027
2028        @Override
2029        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2030            // Do nothing.
2031        }
2032    }
2033
2034    /**
2035     * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2036     */
2037    private void handlePasteClip(ClipData clip) {
2038        removeTextChangedListener(mTextWatcher);
2039
2040        if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
2041            for (int i = 0; i < clip.getItemCount(); i++) {
2042                CharSequence paste = clip.getItemAt(i).getText();
2043                if (paste != null) {
2044                    int start = getSelectionStart();
2045                    int end = getSelectionEnd();
2046                    Editable editable = getText();
2047                    if (start >= 0 && end >= 0 && start != end) {
2048                        editable.append(paste, start, end);
2049                    } else {
2050                        editable.insert(end, paste);
2051                    }
2052                    handlePasteAndReplace();
2053                }
2054            }
2055        }
2056
2057        mHandler.post(mAddTextWatcher);
2058    }
2059
2060    @Override
2061    public boolean onTextContextMenuItem(int id) {
2062        if (id == android.R.id.paste) {
2063            ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2064                    Context.CLIPBOARD_SERVICE);
2065            handlePasteClip(clipboard.getPrimaryClip());
2066            return true;
2067        }
2068        return super.onTextContextMenuItem(id);
2069    }
2070
2071    private void handlePasteAndReplace() {
2072        ArrayList<RecipientChip> created = handlePaste();
2073        if (created != null && created.size() > 0) {
2074            // Perform reverse lookups on the pasted contacts.
2075            IndividualReplacementTask replace = new IndividualReplacementTask();
2076            replace.execute(created);
2077        }
2078    }
2079
2080    // Visible for testing.
2081    /* package */ArrayList<RecipientChip> handlePaste() {
2082        String text = getText().toString();
2083        int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2084        String lastAddress = text.substring(originalTokenStart);
2085        int tokenStart = originalTokenStart;
2086        int prevTokenStart = tokenStart;
2087        RecipientChip findChip = null;
2088        ArrayList<RecipientChip> created = new ArrayList<RecipientChip>();
2089        if (tokenStart != 0) {
2090            // There are things before this!
2091            while (tokenStart != 0 && findChip == null) {
2092                prevTokenStart = tokenStart;
2093                tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2094                findChip = findChip(tokenStart);
2095            }
2096            if (tokenStart != originalTokenStart) {
2097                if (findChip != null) {
2098                    tokenStart = prevTokenStart;
2099                }
2100                int tokenEnd;
2101                RecipientChip createdChip;
2102                while (tokenStart < originalTokenStart) {
2103                    tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(text, tokenStart));
2104                    commitChip(tokenStart, tokenEnd, getText());
2105                    createdChip = findChip(tokenStart);
2106                    // +1 for the space at the end.
2107                    tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
2108                    created.add(createdChip);
2109                }
2110            }
2111        }
2112        // Take a look at the last token. If the token has been completed with a
2113        // commit character, create a chip.
2114        if (isCompletedToken(lastAddress)) {
2115            Editable editable = getText();
2116            tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2117            commitChip(tokenStart, editable.length(), editable);
2118            created.add(findChip(tokenStart));
2119        }
2120        return created;
2121    }
2122
2123    // Visible for testing.
2124    /* package */int movePastTerminators(int tokenEnd) {
2125        if (tokenEnd >= length()) {
2126            return tokenEnd;
2127        }
2128        char atEnd = getText().toString().charAt(tokenEnd);
2129        if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2130            tokenEnd++;
2131        }
2132        // This token had not only an end token character, but also a space
2133        // separating it from the next token.
2134        if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2135            tokenEnd++;
2136        }
2137        return tokenEnd;
2138    }
2139
2140    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
2141        private RecipientChip createFreeChip(RecipientEntry entry) {
2142            try {
2143                if (mNoChips) {
2144                    return null;
2145                }
2146                return constructChipSpan(entry, -1, false);
2147            } catch (NullPointerException e) {
2148                Log.e(TAG, e.getMessage(), e);
2149                return null;
2150            }
2151        }
2152
2153        @Override
2154        protected Void doInBackground(Void... params) {
2155            if (mIndividualReplacements != null) {
2156                mIndividualReplacements.cancel(true);
2157            }
2158            // For each chip in the list, look up the matching contact.
2159            // If there is a match, replace that chip with the matching
2160            // chip.
2161            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
2162            RecipientChip[] existingChips = getSortedRecipients();
2163            for (int i = 0; i < existingChips.length; i++) {
2164                originalRecipients.add(existingChips[i]);
2165            }
2166            if (mRemovedSpans != null) {
2167                originalRecipients.addAll(mRemovedSpans);
2168            }
2169            String[] addresses = new String[originalRecipients.size()];
2170            for (int i = 0; i < originalRecipients.size(); i++) {
2171                addresses[i] = createAddressText(originalRecipients.get(i).getEntry());
2172            }
2173            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2174                    .getMatchingRecipients(getContext(), addresses);
2175            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
2176            for (final RecipientChip temp : originalRecipients) {
2177                RecipientEntry entry = null;
2178                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2179                        && getSpannable().getSpanStart(temp) != -1) {
2180                    // Replace this.
2181                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
2182                            .getDestination())));
2183                }
2184                if (entry != null) {
2185                    replacements.add(createFreeChip(entry));
2186                } else {
2187                    replacements.add(temp);
2188                }
2189            }
2190            if (replacements != null && replacements.size() > 0) {
2191                mHandler.post(new Runnable() {
2192                    @Override
2193                    public void run() {
2194                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
2195                                .toString());
2196                        Editable oldText = getText();
2197                        int start, end;
2198                        int i = 0;
2199                        for (RecipientChip chip : originalRecipients) {
2200                            start = oldText.getSpanStart(chip);
2201                            if (start != -1) {
2202                                end = oldText.getSpanEnd(chip);
2203                                oldText.removeSpan(chip);
2204                                // Leave a spot for the space!
2205                                RecipientChip replacement = replacements.get(i);
2206                                text.setSpan(replacement, start, end,
2207                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2208                                replacement.setOriginalText(text.toString().substring(start, end));
2209                            }
2210                            i++;
2211                        }
2212                        originalRecipients.clear();
2213                        setText(text);
2214                    }
2215                });
2216            }
2217            return null;
2218        }
2219    }
2220
2221    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
2222        @SuppressWarnings("unchecked")
2223        @Override
2224        protected Void doInBackground(Object... params) {
2225            // For each chip in the list, look up the matching contact.
2226            // If there is a match, replace that chip with the matching
2227            // chip.
2228            final ArrayList<RecipientChip> originalRecipients =
2229                (ArrayList<RecipientChip>) params[0];
2230            String[] addresses = new String[originalRecipients.size()];
2231            for (int i = 0; i < originalRecipients.size(); i++) {
2232                addresses[i] = createAddressText(originalRecipients.get(i).getEntry());
2233            }
2234            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2235                    .getMatchingRecipients(getContext(), addresses);
2236            for (final RecipientChip temp : originalRecipients) {
2237                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2238                        && getSpannable().getSpanStart(temp) != -1) {
2239                    // Replace this.
2240                    final RecipientEntry entry = createValidatedEntry(entries
2241                            .get(tokenizeAddress(temp.getEntry().getDestination()).toLowerCase()));
2242                    if (entry != null) {
2243                        mHandler.post(new Runnable() {
2244                            @Override
2245                            public void run() {
2246                                replaceChip(temp, entry);
2247                            }
2248                        });
2249                    }
2250                }
2251            }
2252            return null;
2253        }
2254    }
2255
2256
2257    /**
2258     * MoreImageSpan is a simple class created for tracking the existence of a
2259     * more chip across activity restarts/
2260     */
2261    private class MoreImageSpan extends ImageSpan {
2262        public MoreImageSpan(Drawable b) {
2263            super(b);
2264        }
2265    }
2266
2267    @Override
2268    public boolean onDown(MotionEvent e) {
2269        return false;
2270    }
2271
2272    @Override
2273    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2274        // Do nothing.
2275        return false;
2276    }
2277
2278    @Override
2279    public void onLongPress(MotionEvent event) {
2280        if (mSelectedChip != null) {
2281            return;
2282        }
2283        float x = event.getX();
2284        float y = event.getY();
2285        int offset = putOffsetInRange(getOffsetForPosition(x, y));
2286        RecipientChip currentChip = findChip(offset);
2287        if (currentChip != null) {
2288            if (mDragEnabled) {
2289                // Start drag-and-drop for the selected chip.
2290                startDrag(currentChip);
2291            } else {
2292                // Copy the selected chip email address.
2293                showCopyDialog(currentChip.getEntry().getDestination());
2294            }
2295        }
2296    }
2297
2298    /**
2299     * Enables drag-and-drop for chips.
2300     */
2301    public void enableDrag() {
2302        mDragEnabled = true;
2303    }
2304
2305    /**
2306     * Starts drag-and-drop for the selected chip.
2307     */
2308    private void startDrag(RecipientChip currentChip) {
2309        String address = currentChip.getEntry().getDestination();
2310        ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
2311
2312        // Start drag mode.
2313        startDrag(data, new RecipientChipShadow(currentChip), null, 0);
2314
2315        // Remove the current chip, so drag-and-drop will result in a move.
2316        // TODO (phamm): consider readd this chip if it's dropped outside a target.
2317        removeChip(currentChip);
2318    }
2319
2320    /**
2321     * Handles drag event.
2322     */
2323    @Override
2324    public boolean onDragEvent(DragEvent event) {
2325        switch (event.getAction()) {
2326            case DragEvent.ACTION_DRAG_STARTED:
2327                // Only handle plain text drag and drop.
2328                return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
2329            case DragEvent.ACTION_DRAG_ENTERED:
2330                requestFocus();
2331                return true;
2332            case DragEvent.ACTION_DROP:
2333                handlePasteClip(event.getClipData());
2334                return true;
2335        }
2336        return false;
2337    }
2338
2339    /**
2340     * Drag shadow for a {@link RecipientChip}.
2341     */
2342    private final class RecipientChipShadow extends DragShadowBuilder {
2343        private final RecipientChip mChip;
2344
2345        public RecipientChipShadow(RecipientChip chip) {
2346            mChip = chip;
2347        }
2348
2349        @Override
2350        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
2351            Rect rect = mChip.getDrawable().getBounds();
2352            shadowSize.set(rect.width(), rect.height());
2353            shadowTouchPoint.set(rect.centerX(), rect.centerY());
2354        }
2355
2356        @Override
2357        public void onDrawShadow(Canvas canvas) {
2358            mChip.getDrawable().draw(canvas);
2359        }
2360    }
2361
2362    private void showCopyDialog(final String address) {
2363        mCopyAddress = address;
2364        mCopyDialog.setTitle(address);
2365        mCopyDialog.setContentView(mCopyViewRes);
2366        mCopyDialog.setCancelable(true);
2367        mCopyDialog.setCanceledOnTouchOutside(true);
2368        mCopyDialog.findViewById(android.R.id.button1).setOnClickListener(this);
2369        mCopyDialog.setOnDismissListener(this);
2370        mCopyDialog.show();
2371    }
2372
2373    @Override
2374    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
2375        // Do nothing.
2376        return false;
2377    }
2378
2379    @Override
2380    public void onShowPress(MotionEvent e) {
2381        // Do nothing.
2382    }
2383
2384    @Override
2385    public boolean onSingleTapUp(MotionEvent e) {
2386        // Do nothing.
2387        return false;
2388    }
2389
2390    @Override
2391    public void onDismiss(DialogInterface dialog) {
2392        mCopyAddress = null;
2393    }
2394
2395    @Override
2396    public void onClick(View v) {
2397        // Copy this to the clipboard.
2398        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2399                Context.CLIPBOARD_SERVICE);
2400        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
2401        mCopyDialog.dismiss();
2402    }
2403}
2404