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