RecipientEditTextView.java revision 20c9d620e79ae28994856541761a951074551518
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.Filterable;
68import android.widget.ListAdapter;
69import android.widget.ListPopupWindow;
70import android.widget.ListView;
71import android.widget.MultiAutoCompleteTextView;
72import android.widget.PopupWindow;
73import android.widget.ScrollView;
74import android.widget.TextView;
75
76import java.util.ArrayList;
77import java.util.Arrays;
78import java.util.Collection;
79import java.util.Collections;
80import java.util.Comparator;
81import java.util.HashMap;
82import java.util.HashSet;
83import java.util.Set;
84
85/**
86 * RecipientEditTextView is an auto complete text view for use with applications
87 * that use the new Chips UI for addressing a message to recipients.
88 */
89public class RecipientEditTextView extends MultiAutoCompleteTextView implements
90        OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener,
91        GestureDetector.OnGestureListener, OnDismissListener, OnClickListener,
92        PopupWindow.OnDismissListener {
93
94    private static final String TAG = "RecipientEditTextView";
95
96    // TODO: get correct number/ algorithm from with UX.
97    private static final int CHIP_LIMIT = 2;
98
99    private Drawable mChipBackground = null;
100
101    private Drawable mChipDelete = null;
102
103    private int mChipPadding;
104
105    private Tokenizer mTokenizer;
106
107    private Drawable mChipBackgroundPressed;
108
109    private RecipientChip mSelectedChip;
110
111    private int mAlternatesLayout;
112
113    private Bitmap mDefaultContactPhoto;
114
115    private ImageSpan mMoreChip;
116
117    private TextView mMoreItem;
118
119    private final ArrayList<String> mPendingChips = new ArrayList<String>();
120
121    private float mChipHeight;
122
123    private float mChipFontSize;
124
125    private Validator mValidator;
126
127    private Drawable mInvalidChipBackground;
128
129    private Handler mHandler;
130
131    private static int DISMISS = "dismiss".hashCode();
132
133    private static final long DISMISS_DELAY = 300;
134
135    private int mPendingChipsCount = 0;
136
137    private static int sSelectedTextColor = -1;
138
139    private static final char COMMIT_CHAR_COMMA = ',';
140
141    private static final char COMMIT_CHAR_SEMICOLON = ';';
142
143    private static final char COMMIT_CHAR_SPACE = ' ';
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    private TextWatcher mTextWatcher;
172
173    private ScrollView mScrollView;
174
175    private boolean mTried;
176
177    private final Runnable mAddTextWatcher = new Runnable() {
178        @Override
179        public void run() {
180            if (mTextWatcher == null) {
181                mTextWatcher = new RecipientTextWatcher();
182                addTextChangedListener(mTextWatcher);
183            }
184        }
185    };
186
187    private IndividualReplacementTask mIndividualReplacements;
188
189    private Runnable mHandlePendingChips = new Runnable() {
190
191        @Override
192        public void run() {
193            handlePendingChips();
194        }
195
196    };
197
198    private Runnable mDelayedShrink = new Runnable() {
199
200        @Override
201        public void run() {
202            shrink();
203        }
204
205    };
206
207    public RecipientEditTextView(Context context, AttributeSet attrs) {
208        super(context, attrs);
209        if (sSelectedTextColor == -1) {
210            sSelectedTextColor = context.getResources().getColor(android.R.color.white);
211        }
212        mAlternatesPopup = new ListPopupWindow(context);
213        mAlternatesPopup.setOnDismissListener(this);
214        mAddressPopup = new ListPopupWindow(context);
215        mAddressPopup.setOnDismissListener(this);
216        mCopyDialog = new Dialog(context);
217        mAlternatesListener = new OnItemClickListener() {
218            @Override
219            public void onItemClick(AdapterView<?> adapterView,View view, int position,
220                    long rowId) {
221                mAlternatesPopup.setOnItemClickListener(null);
222                setEnabled(true);
223                replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
224                        .getRecipientEntry(position));
225                Message delayed = Message.obtain(mHandler, DISMISS);
226                delayed.obj = mAlternatesPopup;
227                mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
228                clearComposingText();
229            }
230        };
231        setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
232        setOnItemClickListener(this);
233        setCustomSelectionActionModeCallback(this);
234        mHandler = new Handler() {
235            @Override
236            public void handleMessage(Message msg) {
237                if (msg.what == DISMISS) {
238                    ((ListPopupWindow) msg.obj).dismiss();
239                    return;
240                }
241                super.handleMessage(msg);
242            }
243        };
244        mTextWatcher = new RecipientTextWatcher();
245        addTextChangedListener(mTextWatcher);
246        mGestureDetector = new GestureDetector(context, this);
247    }
248
249    @Override
250    public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
251        super.setAdapter(adapter);
252        if (adapter == null) {
253            return;
254        }
255    }
256
257    @Override
258    public void onSelectionChanged(int start, int end) {
259        // When selection changes, see if it is inside the chips area.
260        // If so, move the cursor back after the chips again.
261        Spannable span = getSpannable();
262        int textLength = getText().length();
263        RecipientChip[] chips = span.getSpans(start, textLength, RecipientChip.class);
264        if (chips != null && chips.length > 0) {
265            if (chips != null && chips.length > 0) {
266                // Grab the last chip and set the cursor to after it.
267                setSelection(Math.min(span.getSpanEnd(chips[chips.length - 1]) + 1, textLength));
268            }
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
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(contact.getDisplayName(), 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     * Get the background drawable for a RecipientChip.
443     */
444    public Drawable getChipBackground(RecipientEntry contact) {
445        return (mValidator != null && mValidator.isValid(contact.getDestination())) ?
446                mChipBackground : mInvalidChipBackground;
447    }
448
449    private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
450        // Ellipsize the text so that it takes AT MOST the entire width of the
451        // autocomplete text entry area. Make sure to leave space for padding
452        // on the sides.
453        int height = (int) mChipHeight;
454        int iconWidth = height;
455        String displayText =
456            !TextUtils.isEmpty(contact.getDisplayName()) ? contact.getDisplayName() :
457            !TextUtils.isEmpty(contact.getDestination()) ? contact.getDestination() : "";
458        CharSequence ellipsizedText = ellipsizeText(displayText, paint,
459                calculateAvailableWidth(false) - iconWidth);
460        // Make sure there is a minimum chip width so the user can ALWAYS
461        // tap a chip without difficulty.
462        int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
463                ellipsizedText.length()))
464                + (mChipPadding * 2) + iconWidth);
465
466        // Create the background of the chip.
467        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
468        Canvas canvas = new Canvas(tmpBitmap);
469        Drawable background = getChipBackground(contact);
470        if (background != null) {
471            background.setBounds(0, 0, width, height);
472            background.draw(canvas);
473
474            // Don't draw photos for recipients that have been typed in.
475            if (contact.getContactId() != RecipientEntry.INVALID_CONTACT) {
476                byte[] photoBytes = contact.getPhotoBytes();
477                // There may not be a photo yet if anything but the first contact address
478                // was selected.
479                if (photoBytes == null && contact.getPhotoThumbnailUri() != null) {
480                    // TODO: cache this in the recipient entry?
481                    ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact
482                            .getPhotoThumbnailUri());
483                    photoBytes = contact.getPhotoBytes();
484                }
485
486                Bitmap photo;
487                if (photoBytes != null) {
488                    photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
489                } else {
490                    // TODO: can the scaled down default photo be cached?
491                    photo = mDefaultContactPhoto;
492                }
493                // Draw the photo on the left side.
494                if (photo != null) {
495                    RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight());
496                    Rect backgroundPadding = new Rect();
497                    mChipBackground.getPadding(backgroundPadding);
498                    RectF dst = new RectF(width - iconWidth + backgroundPadding.left,
499                            0 + backgroundPadding.top,
500                            width - backgroundPadding.right,
501                            height - backgroundPadding.bottom);
502                    Matrix matrix = new Matrix();
503                    matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
504                    canvas.drawBitmap(photo, matrix, paint);
505                }
506            } else {
507                // Don't leave any space for the icon. It isn't being drawn.
508                iconWidth = 0;
509            }
510            paint.setColor(getContext().getResources().getColor(android.R.color.black));
511            // Vertically center the text in the chip.
512            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
513                    getTextYOffset((String)ellipsizedText, paint, height), paint);
514        } else {
515            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
516        }
517        return tmpBitmap;
518    }
519
520    private float getTextYOffset(String text, TextPaint paint, int height) {
521        Rect bounds = new Rect();
522        paint.getTextBounds((String)text, 0, text.length(), bounds);
523        int textHeight = bounds.bottom - bounds.top  - (int)paint.descent();
524        return height - ((height - textHeight) / 2);
525    }
526
527    public RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed)
528            throws NullPointerException {
529        if (mChipBackground == null) {
530            throw new NullPointerException(
531                    "Unable to render any chips as setChipDimensions was not called.");
532        }
533        Layout layout = getLayout();
534
535        TextPaint paint = getPaint();
536        float defaultSize = paint.getTextSize();
537        int defaultColor = paint.getColor();
538
539        Bitmap tmpBitmap;
540        if (pressed) {
541            tmpBitmap = createSelectedChip(contact, paint, layout);
542
543        } else {
544            tmpBitmap = createUnselectedChip(contact, paint, layout);
545        }
546
547        // Pass the full text, un-ellipsized, to the chip.
548        Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
549        result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
550        RecipientChip recipientChip = new RecipientChip(result, contact, offset);
551        // Return text to the original size.
552        paint.setTextSize(defaultSize);
553        paint.setColor(defaultColor);
554        return recipientChip;
555    }
556
557    /**
558     * Calculate the bottom of the line the chip will be located on using:
559     * 1) which line the chip appears on
560     * 2) the height of a chip
561     * 3) padding built into the edit text view
562     */
563    private int calculateOffsetFromBottom(int line) {
564        // Line offsets start at zero.
565        int actualLine = getLineCount() - (line + 1);
566        return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop())
567                + getDropDownVerticalOffset();
568    }
569
570    /**
571     * Get the max amount of space a chip can take up. The formula takes into
572     * account the width of the EditTextView, any view padding, and padding
573     * that will be added to the chip.
574     */
575    private float calculateAvailableWidth(boolean pressed) {
576        return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
577    }
578
579    /**
580     * Set all chip dimensions and resources. This has to be done from the
581     * application as this is a static library.
582     * @param chipBackground
583     * @param chipBackgroundPressed
584     * @param invalidChip
585     * @param chipDelete
586     * @param defaultContact
587     * @param moreResource
588     * @param alternatesLayout
589     * @param chipHeight
590     * @param padding Padding around the text in a chip
591     * @param chipFontSize
592     * @param copyViewRes
593     */
594    public void setChipDimensions(Drawable chipBackground, Drawable chipBackgroundPressed,
595            Drawable invalidChip, Drawable chipDelete, Bitmap defaultContact, int moreResource,
596            int alternatesLayout, float chipHeight, float padding,
597            float chipFontSize, int copyViewRes) {
598        mChipBackground = chipBackground;
599        mChipBackgroundPressed = chipBackgroundPressed;
600        mChipDelete = chipDelete;
601        mChipPadding = (int) padding;
602        mAlternatesLayout = alternatesLayout;
603        mDefaultContactPhoto = defaultContact;
604        mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(moreResource, null);
605        mChipHeight = chipHeight;
606        mChipFontSize = chipFontSize;
607        mInvalidChipBackground = invalidChip;
608        mCopyViewRes = copyViewRes;
609    }
610
611    // Visible for testing.
612    /* package */ void setMoreItem(TextView moreItem) {
613        mMoreItem = moreItem;
614    }
615
616
617    // Visible for testing.
618    /* package */ void setChipBackground(Drawable chipBackground) {
619        mChipBackground = chipBackground;
620    }
621
622    // Visible for testing.
623    /* package */ void setChipHeight(int height) {
624        mChipHeight = height;
625    }
626
627    /**
628     * Set whether to shrink the recipients field such that at most
629     * one line of recipients chips are shown when the field loses
630     * focus. By default, the number of displayed recipients will be
631     * limited and a "more" chip will be shown when focus is lost.
632     * @param shrink
633     */
634    public void setOnFocusListShrinkRecipients(boolean shrink) {
635        mShouldShrink = shrink;
636    }
637
638    @Override
639    public void onSizeChanged(int width, int height, int oldw, int oldh) {
640        super.onSizeChanged(width, height, oldw, oldh);
641        if (width != 0 && height != 0) {
642            if (mPendingChipsCount > 0) {
643                postHandlePendingChips();
644            } else {
645                checkChipWidths();
646            }
647        }
648        // Try to find the scroll view parent, if it exists.
649        if (mScrollView == null && !mTried) {
650            ViewParent parent = getParent();
651            while (parent != null && !(parent instanceof ScrollView)) {
652                parent = parent.getParent();
653            }
654            if (parent != null) {
655                mScrollView = (ScrollView) parent;
656            }
657            mTried = true;
658        }
659    }
660
661    private void postHandlePendingChips() {
662        mHandler.removeCallbacks(mHandlePendingChips);
663        mHandler.post(mHandlePendingChips);
664    }
665
666    private void checkChipWidths() {
667        // Check the widths of the associated chips.
668        RecipientChip[] chips = getSortedRecipients();
669        if (chips != null) {
670            Rect bounds;
671            for (RecipientChip chip : chips) {
672                bounds = chip.getDrawable().getBounds();
673                if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) {
674                    // Need to redraw that chip.
675                    replaceChip(chip, chip.getEntry());
676                }
677            }
678        }
679    }
680
681    private void handlePendingChips() {
682        if (getWidth() <= 0) {
683            // The widget has not been sized yet.
684            // This will be called as a result of onSizeChanged
685            // at a later point.
686            return;
687        }
688
689        if (mPendingChipsCount <= 0) {
690            return;
691        }
692
693        synchronized (mPendingChips) {
694            Editable editable = getText();
695            // Tokenize!
696            for (int i = 0; i < mPendingChips.size(); i++) {
697                String current = mPendingChips.get(i);
698                int tokenStart = editable.toString().indexOf(current);
699                int tokenEnd = tokenStart + current.length();
700                if (tokenStart >= 0) {
701                    // When we have a valid token, include it with the token
702                    // to the left.
703                    if (tokenEnd < editable.length() - 2
704                            && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
705                        tokenEnd++;
706                    }
707                    createReplacementChip(tokenStart, tokenEnd, editable);
708                }
709                mPendingChipsCount--;
710            }
711            sanitizeSpannable();
712            if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0
713                    && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
714                if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
715                    new RecipientReplacementTask().execute();
716                    mTemporaryRecipients = null;
717                } else {
718                    // Create the "more" chip
719                    mIndividualReplacements = new IndividualReplacementTask();
720                    mIndividualReplacements.execute(new ArrayList<RecipientChip>(
721                            mTemporaryRecipients.subList(0, CHIP_LIMIT)));
722
723                    createMoreChip();
724                }
725            } else {
726                // There are too many recipients to look up, so just fall back
727                // to showing addresses for all of them.
728                mTemporaryRecipients = null;
729                createMoreChip();
730            }
731            mPendingChipsCount = 0;
732            mPendingChips.clear();
733        }
734    }
735
736    /**
737     * Remove any characters after the last valid chip.
738     */
739    private void sanitizeSpannable() {
740        // Find the last chip; eliminate any commit characters after it.
741        RecipientChip[] chips = getRecipients();
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 = chips[chips.length - 1];
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 = createDisplayText(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    /* package */ String createDisplayText(RecipientEntry entry) {
1328        String display = entry.getDisplayName();
1329        String address = entry.getDestination();
1330        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1331            display = null;
1332        }
1333        if (address != null) {
1334            // Tokenize out the address in case the address already
1335            // contained the username as well.
1336            Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1337            if (tokenized != null && tokenized.length > 0) {
1338                address = tokenized[0].getAddress();
1339            }
1340        }
1341        Rfc822Token token = new Rfc822Token(display, address, null);
1342        String displayText = token.toString();
1343        String trimmedDisplayText = displayText.trim();
1344        int index = trimmedDisplayText.indexOf(",");
1345        return index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
1346                .terminateToken(displayText) : displayText;
1347    }
1348
1349    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1350        String displayText = createDisplayText(entry);
1351        if (TextUtils.isEmpty(displayText)) {
1352            return null;
1353        }
1354        // Always leave a blank space at the end of a chip.
1355        int textLength = displayText.length()-1;
1356        SpannableString chipText = new SpannableString(displayText);
1357        int end = getSelectionEnd();
1358        int start = mTokenizer.findTokenStart(getText(), end);
1359        try {
1360            RecipientChip chip = constructChipSpan(entry, start, pressed);
1361            chipText.setSpan(chip, 0, textLength,
1362                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1363            chip.setOriginalText(chipText.toString());
1364        } catch (NullPointerException e) {
1365            Log.e(TAG, e.getMessage(), e);
1366            return null;
1367        }
1368
1369        return chipText;
1370    }
1371
1372    /**
1373     * When an item in the suggestions list has been clicked, create a chip from the
1374     * contact information of the selected item.
1375     */
1376    @Override
1377    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1378        submitItemAtPosition(position);
1379    }
1380
1381    private void submitItemAtPosition(int position) {
1382        RecipientEntry entry = createValidatedEntry(
1383                (RecipientEntry)getAdapter().getItem(position));
1384        if (entry == null) {
1385            return;
1386        }
1387        clearComposingText();
1388
1389        int end = getSelectionEnd();
1390        int start = mTokenizer.findTokenStart(getText(), end);
1391
1392        Editable editable = getText();
1393        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1394        CharSequence chip = createChip(entry, false);
1395        if (chip != null) {
1396            editable.replace(start, end, chip);
1397        }
1398        sanitizeBetween();
1399    }
1400
1401    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1402        if (item == null) {
1403            return null;
1404        }
1405        final RecipientEntry entry;
1406        // If the display name and the address are the same, or if this is a
1407        // valid contact, but the destination is invalid, then make this a fake
1408        // recipient that is editable.
1409        String destination = item.getDestination();
1410        if (TextUtils.isEmpty(item.getDisplayName())
1411                || TextUtils.equals(item.getDisplayName(), destination)
1412                || (mValidator != null && !mValidator.isValid(destination))) {
1413            entry = RecipientEntry.constructFakeEntry(destination);
1414        } else {
1415            entry = item;
1416        }
1417        return entry;
1418    }
1419
1420    /** Returns a collection of contact Id for each chip inside this View. */
1421    /* package */ Collection<Long> getContactIds() {
1422        final Set<Long> result = new HashSet<Long>();
1423        RecipientChip[] chips = getRecipients();
1424        if (chips != null) {
1425            for (RecipientChip chip : chips) {
1426                result.add(chip.getContactId());
1427            }
1428        }
1429        return result;
1430    }
1431
1432    private RecipientChip[] getRecipients() {
1433        return getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1434    }
1435
1436    // Visible for testing.
1437    /* package */ RecipientChip[] getSortedRecipients() {
1438        ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays
1439                .asList(getRecipients()));
1440        final Spannable spannable = getSpannable();
1441        Collections.sort(recipientsList, new Comparator<RecipientChip>() {
1442
1443            @Override
1444            public int compare(RecipientChip first, RecipientChip second) {
1445                int firstStart = spannable.getSpanStart(first);
1446                int secondStart = spannable.getSpanStart(second);
1447                if (firstStart < secondStart) {
1448                    return -1;
1449                } else if (firstStart > secondStart) {
1450                    return 1;
1451                } else {
1452                    return 0;
1453                }
1454            }
1455        });
1456        return recipientsList.toArray(new RecipientChip[recipientsList.size()]);
1457    }
1458
1459    /** Returns a collection of data Id for each chip inside this View. May be null. */
1460    /* package */ Collection<Long> getDataIds() {
1461        final Set<Long> result = new HashSet<Long>();
1462        RecipientChip [] chips = getRecipients();
1463        if (chips != null) {
1464            for (RecipientChip chip : chips) {
1465                result.add(chip.getDataId());
1466            }
1467        }
1468        return result;
1469    }
1470
1471
1472    @Override
1473    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1474        return false;
1475    }
1476
1477    @Override
1478    public void onDestroyActionMode(ActionMode mode) {
1479    }
1480
1481    @Override
1482    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1483        return false;
1484    }
1485
1486    /**
1487     * No chips are selectable.
1488     */
1489    @Override
1490    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1491        return false;
1492    }
1493
1494    // Visible for testing.
1495    /* package */ImageSpan getMoreChip() {
1496        MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
1497                MoreImageSpan.class);
1498        return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
1499    }
1500
1501    /**
1502     * Create the more chip. The more chip is text that replaces any chips that
1503     * do not fit in the pre-defined available space when the
1504     * RecipientEditTextView loses focus.
1505     */
1506    // Visible for testing.
1507    /* package */ void createMoreChip() {
1508        if (!mShouldShrink) {
1509            return;
1510        }
1511
1512        ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
1513        if (tempMore.length > 0) {
1514            getSpannable().removeSpan(tempMore[0]);
1515        }
1516        RecipientChip[] recipients = getSortedRecipients();
1517        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1518            mMoreChip = null;
1519            return;
1520        }
1521        Spannable spannable = getSpannable();
1522        int numRecipients = recipients.length;
1523        int overage = numRecipients - CHIP_LIMIT;
1524        String moreText = String.format(mMoreItem.getText().toString(), overage);
1525        TextPaint morePaint = new TextPaint(getPaint());
1526        morePaint.setTextSize(mMoreItem.getTextSize());
1527        morePaint.setColor(mMoreItem.getCurrentTextColor());
1528        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1529                + mMoreItem.getPaddingRight();
1530        int height = getLineHeight();
1531        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1532        Canvas canvas = new Canvas(drawable);
1533        int adjustedHeight = height;
1534        Layout layout = getLayout();
1535        if (layout != null) {
1536            adjustedHeight -= layout.getLineDescent(0);
1537        }
1538        canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
1539
1540        Drawable result = new BitmapDrawable(getResources(), drawable);
1541        result.setBounds(0, 0, width, height);
1542        MoreImageSpan moreSpan = new MoreImageSpan(result);
1543        // Remove the overage chips.
1544        if (recipients == null || recipients.length == 0) {
1545            Log.w(TAG,
1546                    "We have recipients. Tt should not be possible to have zero RecipientChips.");
1547            mMoreChip = null;
1548            return;
1549        }
1550        mRemovedSpans = new ArrayList<RecipientChip>();
1551        int totalReplaceStart = 0;
1552        int totalReplaceEnd = 0;
1553        Editable text = getText();
1554        for (int i = numRecipients - overage; i < recipients.length; i++) {
1555            mRemovedSpans.add(recipients[i]);
1556            if (i == numRecipients - overage) {
1557                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1558            }
1559            if (i == recipients.length - 1) {
1560                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1561            }
1562            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
1563                int spanStart = spannable.getSpanStart(recipients[i]);
1564                int spanEnd = spannable.getSpanEnd(recipients[i]);
1565                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
1566            }
1567            spannable.removeSpan(recipients[i]);
1568        }
1569        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1570        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1571        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1572        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1573        text.replace(start, end, chipText);
1574        mMoreChip = moreSpan;
1575    }
1576
1577    /**
1578     * Replace the more chip, if it exists, with all of the recipient chips it had
1579     * replaced when the RecipientEditTextView gains focus.
1580     */
1581    // Visible for testing.
1582    /*package*/ void removeMoreChip() {
1583        if (mMoreChip != null) {
1584            Spannable span = getSpannable();
1585            span.removeSpan(mMoreChip);
1586            mMoreChip = null;
1587            // Re-add the spans that were removed.
1588            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1589                // Recreate each removed span.
1590                RecipientChip[] recipients = getSortedRecipients();
1591                // Start the search for tokens after the last currently visible
1592                // chip.
1593                if (recipients == null || recipients.length == 0) {
1594                    return;
1595                }
1596                int end = span.getSpanEnd(recipients[recipients.length - 1]);
1597                Editable editable = getText();
1598                for (RecipientChip chip : mRemovedSpans) {
1599                    int chipStart;
1600                    int chipEnd;
1601                    String token;
1602                    // Need to find the location of the chip, again.
1603                    token = (String) chip.getOriginalText();
1604                    // As we find the matching recipient for the remove spans,
1605                    // reduce the size of the string we need to search.
1606                    // That way, if there are duplicates, we always find the correct
1607                    // recipient.
1608                    chipStart = editable.toString().indexOf(token, end);
1609                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
1610                    // Only set the span if we found a matching token.
1611                    if (chipStart != -1) {
1612                        editable.setSpan(chip, chipStart, chipEnd,
1613                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1614                    }
1615                }
1616                mRemovedSpans.clear();
1617            }
1618        }
1619    }
1620
1621    /**
1622     * Show specified chip as selected. If the RecipientChip is just an email address,
1623     * selecting the chip will take the contents of the chip and place it at
1624     * the end of the RecipientEditTextView for inline editing. If the
1625     * RecipientChip is a complete contact, then selecting the chip
1626     * will change the background color of the chip, show the delete icon,
1627     * and a popup window with the address in use highlighted and any other
1628     * alternate addresses for the contact.
1629     * @param currentChip Chip to select.
1630     * @return A RecipientChip in the selected state or null if the chip
1631     * just contained an email address.
1632     */
1633    public RecipientChip selectChip(RecipientChip currentChip) {
1634        if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1635            CharSequence text = currentChip.getValue();
1636            Editable editable = getText();
1637            removeChip(currentChip);
1638            editable.append(text);
1639            setCursorVisible(true);
1640            setSelection(editable.length());
1641            return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1);
1642        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1643            int start = getChipStart(currentChip);
1644            int end = getChipEnd(currentChip);
1645            getSpannable().removeSpan(currentChip);
1646            RecipientChip newChip;
1647            try {
1648                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1649            } catch (NullPointerException e) {
1650                Log.e(TAG, e.getMessage(), e);
1651                return null;
1652            }
1653            Editable editable = getText();
1654            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1655            if (start == -1 || end == -1) {
1656                Log.d(TAG, "The chip being selected no longer exists but should.");
1657            } else {
1658                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1659            }
1660            newChip.setSelected(true);
1661            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1662                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1663            }
1664            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1665            setCursorVisible(false);
1666            return newChip;
1667        } else {
1668            int start = getChipStart(currentChip);
1669            int end = getChipEnd(currentChip);
1670            getSpannable().removeSpan(currentChip);
1671            RecipientChip newChip;
1672            try {
1673                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1674            } catch (NullPointerException e) {
1675                Log.e(TAG, e.getMessage(), e);
1676                return null;
1677            }
1678            Editable editable = getText();
1679            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1680            if (start == -1 || end == -1) {
1681                Log.d(TAG, "The chip being selected no longer exists but should.");
1682            } else {
1683                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1684            }
1685            newChip.setSelected(true);
1686            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1687                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1688            }
1689            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1690            setCursorVisible(false);
1691            return newChip;
1692        }
1693    }
1694
1695
1696    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
1697            int width, Context context) {
1698        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1699        int bottom = calculateOffsetFromBottom(line);
1700        // Align the alternates popup with the left side of the View,
1701        // regardless of the position of the chip tapped.
1702        setEnabled(false);
1703        popup.setWidth(width);
1704        popup.setAnchorView(this);
1705        popup.setVerticalOffset(bottom);
1706        popup.setAdapter(createSingleAddressAdapter(currentChip));
1707        popup.setOnItemClickListener(new OnItemClickListener() {
1708            @Override
1709            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1710                unselectChip(currentChip);
1711                popup.dismiss();
1712            }
1713        });
1714        popup.show();
1715        ListView listView = popup.getListView();
1716        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1717        listView.setItemChecked(0, true);
1718    }
1719
1720    /**
1721     * Remove selection from this chip. Unselecting a RecipientChip will render
1722     * the chip without a delete icon and with an unfocused background. This
1723     * is called when the RecipientChip no longer has focus.
1724     */
1725    public void unselectChip(RecipientChip chip) {
1726        int start = getChipStart(chip);
1727        int end = getChipEnd(chip);
1728        Editable editable = getText();
1729        mSelectedChip = null;
1730        if (start == -1 || end == -1) {
1731            Log.w(TAG,
1732                    "The chip doesn't exist or may be a chip a user was editing");
1733            setSelection(editable.length());
1734            commitDefault();
1735        } else {
1736            getSpannable().removeSpan(chip);
1737            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1738            editable.removeSpan(chip);
1739            try {
1740                editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1741                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1742            } catch (NullPointerException e) {
1743                Log.e(TAG, e.getMessage(), e);
1744            }
1745        }
1746        setCursorVisible(true);
1747        setSelection(editable.length());
1748        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1749            mAlternatesPopup.dismiss();
1750        }
1751    }
1752
1753    /**
1754     * Return whether this chip contains the position passed in.
1755     */
1756    public boolean matchesChip(RecipientChip chip, int offset) {
1757        int start = getChipStart(chip);
1758        int end = getChipEnd(chip);
1759
1760        if (start == -1 || end == -1) {
1761            return false;
1762        }
1763        return (offset >= start && offset <= end);
1764    }
1765
1766
1767    /**
1768     * Return whether a touch event was inside the delete target of
1769     * a selected chip. It is in the delete target if:
1770     * 1) the x and y points of the event are within the
1771     * delete assset.
1772     * 2) the point tapped would have caused a cursor to appear
1773     * right after the selected chip.
1774     * @return boolean
1775     */
1776    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1777        // Figure out the bounds of this chip and whether or not
1778        // the user clicked in the X portion.
1779        return chip.isSelected() && offset == getChipEnd(chip);
1780    }
1781
1782    /**
1783     * Remove the chip and any text associated with it from the RecipientEditTextView.
1784     */
1785    // Visible for testing.
1786    /*pacakge*/ void removeChip(RecipientChip chip) {
1787        Spannable spannable = getSpannable();
1788        int spanStart = spannable.getSpanStart(chip);
1789        int spanEnd = spannable.getSpanEnd(chip);
1790        Editable text = getText();
1791        int toDelete = spanEnd;
1792        boolean wasSelected = chip == mSelectedChip;
1793        // Clear that there is a selected chip before updating any text.
1794        if (wasSelected) {
1795            mSelectedChip = null;
1796        }
1797        // Always remove trailing spaces when removing a chip.
1798        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
1799            toDelete++;
1800        }
1801        spannable.removeSpan(chip);
1802        text.delete(spanStart, toDelete);
1803        if (wasSelected) {
1804            clearSelectedChip();
1805        }
1806    }
1807
1808    /**
1809     * Replace this currently selected chip with a new chip
1810     * that uses the contact data provided.
1811     */
1812    public void replaceChip(RecipientChip chip, RecipientEntry entry) {
1813        boolean wasSelected = chip == mSelectedChip;
1814        if (wasSelected) {
1815            mSelectedChip = null;
1816        }
1817        int start = getChipStart(chip);
1818        int end = getChipEnd(chip);
1819        getSpannable().removeSpan(chip);
1820        Editable editable = getText();
1821        CharSequence chipText = createChip(entry, false);
1822        if (chipText != null) {
1823            if (start == -1 || end == -1) {
1824                Log.e(TAG, "The chip to replace does not exist but should.");
1825                editable.insert(0, chipText);
1826            } else {
1827                if (!TextUtils.isEmpty(chipText)) {
1828                    // There may be a space to replace with this chip's new
1829                    // associated
1830                    // space. Check for it
1831                    int toReplace = end;
1832                    while (toReplace >= 0 && toReplace < editable.length()
1833                            && editable.charAt(toReplace) == ' ') {
1834                        toReplace++;
1835                    }
1836                    editable.replace(start, toReplace, chipText);
1837                }
1838            }
1839        }
1840        setCursorVisible(true);
1841        if (wasSelected) {
1842            clearSelectedChip();
1843        }
1844    }
1845
1846    /**
1847     * Handle click events for a chip. When a selected chip receives a click
1848     * event, see if that event was in the delete icon. If so, delete it.
1849     * Otherwise, unselect the chip.
1850     */
1851    public void onClick(RecipientChip chip, int offset, float x, float y) {
1852        if (chip.isSelected()) {
1853            if (isInDelete(chip, offset, x, y)) {
1854                removeChip(chip);
1855            } else {
1856                clearSelectedChip();
1857            }
1858        }
1859    }
1860
1861    private boolean chipsPending() {
1862        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1863    }
1864
1865    @Override
1866    public void removeTextChangedListener(TextWatcher watcher) {
1867        mTextWatcher = null;
1868        super.removeTextChangedListener(watcher);
1869    }
1870
1871    private class RecipientTextWatcher implements TextWatcher {
1872        @Override
1873        public void afterTextChanged(Editable s) {
1874            // If the text has been set to null or empty, make sure we remove
1875            // all the spans we applied.
1876            if (TextUtils.isEmpty(s)) {
1877                // Remove all the chips spans.
1878                Spannable spannable = getSpannable();
1879                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
1880                        RecipientChip.class);
1881                for (RecipientChip chip : chips) {
1882                    spannable.removeSpan(chip);
1883                }
1884                if (mMoreChip != null) {
1885                    spannable.removeSpan(mMoreChip);
1886                }
1887                return;
1888            }
1889            // Get whether there are any recipients pending addition to the
1890            // view. If there are, don't do anything in the text watcher.
1891            if (chipsPending()) {
1892                return;
1893            }
1894            // If the user is editing a chip, don't clear it.
1895            if (mSelectedChip != null
1896                    && mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) {
1897                setCursorVisible(true);
1898                setSelection(getText().length());
1899                clearSelectedChip();
1900            }
1901            int length = s.length();
1902            // Make sure there is content there to parse and that it is
1903            // not just the commit character.
1904            if (length > 1) {
1905                char last;
1906                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
1907                int len = length() - 1;
1908                if (end != len) {
1909                    last = s.charAt(end);
1910                } else {
1911                    last = s.charAt(len);
1912                }
1913                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
1914                    commitByCharacter();
1915                } else if (last == COMMIT_CHAR_SPACE) {
1916                    // Check if this is a valid email address. If it is,
1917                    // commit it.
1918                    String text = getText().toString();
1919                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1920                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
1921                            tokenStart));
1922                    if (!TextUtils.isEmpty(sub) && mValidator != null && mValidator.isValid(sub)) {
1923                        commitByCharacter();
1924                    }
1925                }
1926            }
1927        }
1928
1929        @Override
1930        public void onTextChanged(CharSequence s, int start, int before, int count) {
1931            // Do nothing.
1932        }
1933
1934        @Override
1935        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1936            // Do nothing.
1937        }
1938    }
1939
1940    @Override
1941    public boolean onTextContextMenuItem(int id) {
1942        if (id == android.R.id.paste) {
1943            removeTextChangedListener(mTextWatcher);
1944            ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
1945                    Context.CLIPBOARD_SERVICE);
1946            ClipData clip = clipboard.getPrimaryClip();
1947            if (clip != null
1948                    && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
1949                for (int i = 0; i < clip.getItemCount(); i++) {
1950                    CharSequence paste = clip.getItemAt(i).getText();
1951                    if (paste != null) {
1952                        int start = getSelectionStart();
1953                        int end = getSelectionEnd();
1954                        Editable editable = getText();
1955                        if (start >= 0 && end >= 0 && start != end) {
1956                            editable.append(paste, start, end);
1957                        } else {
1958                            editable.insert(end, paste);
1959                        }
1960                        handlePaste();
1961                    }
1962                }
1963            }
1964            mHandler.post(mAddTextWatcher);
1965            return true;
1966        }
1967        return super.onTextContextMenuItem(id);
1968    }
1969
1970    // Visible for testing.
1971    /* package */void handlePaste() {
1972        String text = getText().toString();
1973        int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1974        String lastAddress = text.substring(originalTokenStart);
1975        int tokenStart = originalTokenStart;
1976        int prevTokenStart = tokenStart;
1977        RecipientChip findChip = null;
1978        if (tokenStart != 0) {
1979            // There are things before this!
1980            while (tokenStart != 0 && findChip == null) {
1981                prevTokenStart = tokenStart;
1982                tokenStart = mTokenizer.findTokenStart(text, tokenStart);
1983                findChip = findChip(tokenStart);
1984            }
1985            if (tokenStart != originalTokenStart) {
1986                if (findChip != null) {
1987                    tokenStart = prevTokenStart;
1988                }
1989                int tokenEnd;
1990                RecipientChip createdChip;
1991                while (tokenStart < originalTokenStart) {
1992                    tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(text, tokenStart));
1993                    commitChip(tokenStart, tokenEnd, getText());
1994                    createdChip = findChip(tokenStart);
1995                    // +1 for the space at the end.
1996                    tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
1997                }
1998            }
1999        }
2000        // Take a look at the last token. If the token has been completed with a
2001        // commit character, create a chip.
2002        if (isCompletedToken(lastAddress)) {
2003            Editable editable = getText();
2004            commitChip(editable.toString().indexOf(lastAddress, originalTokenStart), editable
2005                    .length(), editable);
2006        }
2007    }
2008
2009    // Visible for testing.
2010    /* package */int movePastTerminators(int tokenEnd) {
2011        if (tokenEnd >= length()) {
2012            return tokenEnd;
2013        }
2014        char atEnd = getText().toString().charAt(tokenEnd);
2015        if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2016            tokenEnd++;
2017        }
2018        // This token had not only an end token character, but also a space
2019        // separating it from the next token.
2020        if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2021            tokenEnd++;
2022        }
2023        return tokenEnd;
2024    }
2025
2026    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
2027        private RecipientChip createFreeChip(RecipientEntry entry) {
2028            try {
2029                return constructChipSpan(entry, -1, false);
2030            } catch (NullPointerException e) {
2031                Log.e(TAG, e.getMessage(), e);
2032                return null;
2033            }
2034        }
2035
2036        @Override
2037        protected Void doInBackground(Void... params) {
2038            if (mIndividualReplacements != null) {
2039                mIndividualReplacements.cancel(true);
2040            }
2041            // For each chip in the list, look up the matching contact.
2042            // If there is a match, replace that chip with the matching
2043            // chip.
2044            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
2045            RecipientChip[] existingChips = getSortedRecipients();
2046            for (int i = 0; i < existingChips.length; i++) {
2047                originalRecipients.add(existingChips[i]);
2048            }
2049            if (mRemovedSpans != null) {
2050                originalRecipients.addAll(mRemovedSpans);
2051            }
2052            String[] addresses = new String[originalRecipients.size()];
2053            for (int i = 0; i < originalRecipients.size(); i++) {
2054                addresses[i] = createDisplayText(originalRecipients.get(i).getEntry());
2055            }
2056            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2057                    .getMatchingRecipients(getContext(), addresses);
2058            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
2059            for (final RecipientChip temp : originalRecipients) {
2060                RecipientEntry entry = null;
2061                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2062                        && getSpannable().getSpanStart(temp) != -1) {
2063                    // Replace this.
2064                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
2065                            .getDestination())));
2066                }
2067                if (entry != null) {
2068                    replacements.add(createFreeChip(entry));
2069                } else {
2070                    replacements.add(temp);
2071                }
2072            }
2073            if (replacements != null && replacements.size() > 0) {
2074                mHandler.post(new Runnable() {
2075                    @Override
2076                    public void run() {
2077                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
2078                                .toString());
2079                        Editable oldText = getText();
2080                        int start, end;
2081                        int i = 0;
2082                        for (RecipientChip chip : originalRecipients) {
2083                            start = oldText.getSpanStart(chip);
2084                            if (start != -1) {
2085                                end = oldText.getSpanEnd(chip);
2086                                oldText.removeSpan(chip);
2087                                // Leave a spot for the space!
2088                                RecipientChip replacement = replacements.get(i);
2089                                text.setSpan(replacement, start, end,
2090                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2091                                replacement.setOriginalText(text.toString().substring(start, end));
2092                            }
2093                            i++;
2094                        }
2095                        originalRecipients.clear();
2096                        setText(text);
2097                    }
2098                });
2099            }
2100            return null;
2101        }
2102    }
2103
2104    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
2105        @SuppressWarnings("unchecked")
2106        @Override
2107        protected Void doInBackground(Object... params) {
2108            // For each chip in the list, look up the matching contact.
2109            // If there is a match, replace that chip with the matching
2110            // chip.
2111            final ArrayList<RecipientChip> originalRecipients =
2112                (ArrayList<RecipientChip>) params[0];
2113            String[] addresses = new String[originalRecipients.size()];
2114            for (int i = 0; i < originalRecipients.size(); i++) {
2115                addresses[i] = createDisplayText(originalRecipients.get(i).getEntry());
2116            }
2117            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2118                    .getMatchingRecipients(getContext(), addresses);
2119            for (final RecipientChip temp : originalRecipients) {
2120                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2121                        && getSpannable().getSpanStart(temp) != -1) {
2122                    // Replace this.
2123                    final RecipientEntry entry = createValidatedEntry(entries
2124                            .get(tokenizeAddress(temp.getEntry().getDestination())));
2125                    if (entry != null) {
2126                        mHandler.post(new Runnable() {
2127                            @Override
2128                            public void run() {
2129                                replaceChip(temp, entry);
2130                            }
2131                        });
2132                    }
2133                }
2134            }
2135            return null;
2136        }
2137    }
2138
2139
2140    /**
2141     * MoreImageSpan is a simple class created for tracking the existence of a
2142     * more chip across activity restarts/
2143     */
2144    private class MoreImageSpan extends ImageSpan {
2145        public MoreImageSpan(Drawable b) {
2146            super(b);
2147        }
2148    }
2149
2150    @Override
2151    public boolean onDown(MotionEvent e) {
2152        return false;
2153    }
2154
2155    @Override
2156    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2157        // Do nothing.
2158        return false;
2159    }
2160
2161    @Override
2162    public void onLongPress(MotionEvent event) {
2163        if (mSelectedChip != null) {
2164            return;
2165        }
2166        float x = event.getX();
2167        float y = event.getY();
2168        int offset = putOffsetInRange(getOffsetForPosition(x, y));
2169        RecipientChip currentChip = findChip(offset);
2170        if (currentChip != null) {
2171            // Copy the selected chip email address.
2172            showCopyDialog(currentChip.getEntry().getDestination());
2173        }
2174    }
2175
2176    private void showCopyDialog(final String address) {
2177        mCopyAddress = address;
2178        mCopyDialog.setTitle(address);
2179        mCopyDialog.setContentView(mCopyViewRes);
2180        mCopyDialog.setCancelable(true);
2181        mCopyDialog.setCanceledOnTouchOutside(true);
2182        mCopyDialog.findViewById(android.R.id.button1).setOnClickListener(this);
2183        mCopyDialog.setOnDismissListener(this);
2184        mCopyDialog.show();
2185    }
2186
2187    @Override
2188    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
2189        // Do nothing.
2190        return false;
2191    }
2192
2193    @Override
2194    public void onShowPress(MotionEvent e) {
2195        // Do nothing.
2196    }
2197
2198    @Override
2199    public boolean onSingleTapUp(MotionEvent e) {
2200        // Do nothing.
2201        return false;
2202    }
2203
2204    @Override
2205    public void onDismiss(DialogInterface dialog) {
2206        mCopyAddress = null;
2207    }
2208
2209    @Override
2210    public void onClick(View v) {
2211        // Copy this to the clipboard.
2212        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2213                Context.CLIPBOARD_SERVICE);
2214        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
2215        mCopyDialog.dismiss();
2216    }
2217}
2218