RecipientEditTextView.java revision bbf141b605f92729864984229e6e1062d9a462be
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.content.Context;
20import android.graphics.Bitmap;
21import android.graphics.BitmapFactory;
22import android.graphics.Canvas;
23import android.graphics.Matrix;
24import android.graphics.Rect;
25import android.graphics.RectF;
26import android.graphics.drawable.BitmapDrawable;
27import android.graphics.drawable.Drawable;
28import android.os.AsyncTask;
29import android.os.Handler;
30import android.os.Message;
31import android.text.Editable;
32import android.text.Layout;
33import android.text.Spannable;
34import android.text.SpannableString;
35import android.text.SpannableStringBuilder;
36import android.text.Spanned;
37import android.text.TextPaint;
38import android.text.TextUtils;
39import android.text.TextWatcher;
40import android.text.method.QwertyKeyListener;
41import android.text.style.ImageSpan;
42import android.text.util.Rfc822Token;
43import android.text.util.Rfc822Tokenizer;
44import android.util.AttributeSet;
45import android.util.Log;
46import android.view.ActionMode;
47import android.view.KeyEvent;
48import android.view.Menu;
49import android.view.MenuItem;
50import android.view.MotionEvent;
51import android.view.View;
52import android.view.ViewParent;
53import android.view.ActionMode.Callback;
54import android.widget.AdapterView;
55import android.widget.AdapterView.OnItemClickListener;
56import android.widget.Filter;
57import android.widget.Filterable;
58import android.widget.ListAdapter;
59import android.widget.ListPopupWindow;
60import android.widget.ListView;
61import android.widget.MultiAutoCompleteTextView;
62import android.widget.ScrollView;
63
64import java.util.Collection;
65import java.util.HashMap;
66import java.util.HashSet;
67import java.util.Set;
68
69import java.util.ArrayList;
70
71/**
72 * RecipientEditTextView is an auto complete text view for use with applications
73 * that use the new Chips UI for addressing a message to recipients.
74 */
75public class RecipientEditTextView extends MultiAutoCompleteTextView implements
76        OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener {
77
78    private static final String TAG = "RecipientEditTextView";
79
80    // TODO: get correct number/ algorithm from with UX.
81    private static final int CHIP_LIMIT = 2;
82
83    private static final int INVALID_CONTACT = -1;
84
85    // TODO: get correct size from UX.
86    private static final float MORE_WIDTH_FACTOR = 0.25f;
87
88    private Drawable mChipBackground = null;
89
90    private Drawable mChipDelete = null;
91
92    private int mChipPadding;
93
94    private Tokenizer mTokenizer;
95
96    private Drawable mChipBackgroundPressed;
97
98    private RecipientChip mSelectedChip;
99
100    private int mAlternatesLayout;
101
102    private Bitmap mDefaultContactPhoto;
103
104    private ImageSpan mMoreChip;
105
106    private int mMoreString;
107
108
109    private final ArrayList<String> mPendingChips = new ArrayList<String>();
110
111    private float mChipHeight;
112
113    private float mChipFontSize;
114
115    private Validator mValidator;
116
117    private Drawable mInvalidChipBackground;
118
119    private Handler mHandler;
120
121    private static int DISMISS = "dismiss".hashCode();
122
123    private static final long DISMISS_DELAY = 300;
124
125    private int mPendingChipsCount = 0;
126
127    private static int sSelectedTextColor = -1;
128
129    private static final char COMMIT_CHAR_COMMA = ',';
130
131    private static final char COMMIT_CHAR_SEMICOLON = ';';
132
133    private static final char COMMIT_CHAR_SPACE = ' ';
134
135    private ListPopupWindow mAlternatesPopup;
136
137    private ArrayList<RecipientChip> mTemporaryRecipients;
138
139    private ArrayList<RecipientChip> mRemovedSpans;
140
141    /**
142     * Used with {@link mAlternatesPopup}. Handles clicks to alternate addresses for a selected chip.
143     */
144    private OnItemClickListener mAlternatesListener;
145
146    private int mCheckedItem;
147    private TextWatcher mTextWatcher;
148
149    private ScrollView mScrollView;
150
151    private boolean mTried;
152
153    private final Runnable mAddTextWatcher = new Runnable() {
154        @Override
155        public void run() {
156            if (mTextWatcher == null) {
157                mTextWatcher = new RecipientTextWatcher();
158                addTextChangedListener(mTextWatcher);
159            }
160        }
161    };
162
163    private IndividualReplacementTask mIndividualReplacements;
164
165    public RecipientEditTextView(Context context, AttributeSet attrs) {
166        super(context, attrs);
167        if (sSelectedTextColor == -1) {
168            sSelectedTextColor = context.getResources().getColor(android.R.color.white);
169        }
170        mAlternatesPopup = new ListPopupWindow(context);
171        mAlternatesListener = new OnItemClickListener() {
172            @Override
173            public void onItemClick(AdapterView<?> adapterView,View view, int position,
174                    long rowId) {
175                mAlternatesPopup.setOnItemClickListener(null);
176                replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
177                        .getRecipientEntry(position));
178                Message delayed = Message.obtain(mHandler, DISMISS);
179                delayed.obj = mAlternatesPopup;
180                mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
181                clearComposingText();
182            }
183        };
184        setSuggestionsEnabled(false);
185        setOnItemClickListener(this);
186        setCustomSelectionActionModeCallback(this);
187        mHandler = new Handler() {
188            @Override
189            public void handleMessage(Message msg) {
190                if (msg.what == DISMISS) {
191                    ((ListPopupWindow) msg.obj).dismiss();
192                    return;
193                }
194                super.handleMessage(msg);
195            }
196        };
197    }
198
199    @Override
200    public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
201        super.setAdapter(adapter);
202        if (adapter == null) {
203            return;
204        }
205        // Start the filtering process as soon as possible. This will
206        // cause any needed services to be started and make the first filter
207        // query come back more quickly.
208        Filter f = ((Filterable) adapter).getFilter();
209        f.filter("sara");
210    }
211
212    @Override
213    public void onSelectionChanged(int start, int end) {
214        // When selection changes, see if it is inside the chips area.
215        // If so, move the cursor back after the chips again.
216        Spannable span = getSpannable();
217        int textLength = getText().length();
218        RecipientChip[] chips = span.getSpans(start, textLength, RecipientChip.class);
219        if (chips != null && chips.length > 0) {
220            if (chips != null && chips.length > 0) {
221                // Grab the last chip and set the cursor to after it.
222                setSelection(Math.min(span.getSpanEnd(chips[chips.length - 1]) + 1, textLength));
223            }
224        }
225        super.onSelectionChanged(start, end);
226    }
227
228    /**
229     * Convenience method: Append the specified text slice to the TextView's
230     * display buffer, upgrading it to BufferType.EDITABLE if it was
231     * not already editable. Commas are excluded as they are added automatically
232     * by the view.
233     */
234    @Override
235    public void append(CharSequence text, int start, int end) {
236        super.append(text, start, end);
237        if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
238            final String displayString = (String) text;
239            int seperatorPos = displayString.indexOf(COMMIT_CHAR_COMMA);
240            if (seperatorPos != 0 && !TextUtils.isEmpty(displayString)
241                    && TextUtils.getTrimmedLength(displayString) > 0) {
242                mPendingChipsCount++;
243                mPendingChips.add((String)text);
244            }
245        }
246    }
247
248    @Override
249    public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
250        if (!hasFocus) {
251            shrink();
252            // Reset any pending chips as they would have been handled
253            // when the field lost focus.
254            mPendingChipsCount = 0;
255            mPendingChips.clear();
256            mHandler.post(mAddTextWatcher);
257        } else {
258            expand();
259            scrollLineIntoView(getLineCount());
260        }
261        super.onFocusChanged(hasFocus, direction, previous);
262    }
263
264    private void shrink() {
265        if (mSelectedChip != null) {
266            clearSelectedChip();
267        } else {
268            commitDefault();
269        }
270        createMoreChip();
271    }
272
273    private void expand() {
274        removeMoreChip();
275        setCursorVisible(true);
276        Editable text = getText();
277        setSelection(text != null && text.length() > 0 ? text.length() : 0);
278        // If there are any temporary chips, try replacing them now that the user
279        // has expanded the field.
280        if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) {
281            new RecipientReplacementTask().execute();
282            mTemporaryRecipients = null;
283        }
284    }
285
286    private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
287        paint.setTextSize(mChipFontSize);
288        if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
289            Log.d(TAG, "Max width is negative: " + maxWidth);
290        }
291        return TextUtils.ellipsize(text, paint, maxWidth,
292                TextUtils.TruncateAt.END);
293    }
294
295    private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
296        // Ellipsize the text so that it takes AT MOST the entire width of the
297        // autocomplete text entry area. Make sure to leave space for padding
298        // on the sides.
299        int height = (int) mChipHeight;
300        int deleteWidth = height;
301        CharSequence ellipsizedText = ellipsizeText(contact.getDisplayName(), paint,
302                calculateAvailableWidth(true) - deleteWidth);
303
304        // Make sure there is a minimum chip width so the user can ALWAYS
305        // tap a chip without difficulty.
306        int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
307                ellipsizedText.length()))
308                + (mChipPadding * 2) + deleteWidth);
309
310        // Create the background of the chip.
311        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
312        Canvas canvas = new Canvas(tmpBitmap);
313        if (mChipBackgroundPressed != null) {
314            mChipBackgroundPressed.setBounds(0, 0, width, height);
315            mChipBackgroundPressed.draw(canvas);
316            paint.setColor(sSelectedTextColor);
317            // Align the display text with where the user enters text.
318            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, height
319                    - Math.abs(height - mChipFontSize)/2, paint);
320            // Make the delete a square.
321            mChipDelete.setBounds(width - deleteWidth, 0, width, height);
322            mChipDelete.draw(canvas);
323        } else {
324            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
325        }
326        return tmpBitmap;
327    }
328
329
330    /**
331     * Get the background drawable for a RecipientChip.
332     */
333    public Drawable getChipBackground(RecipientEntry contact) {
334        return (mValidator != null && mValidator.isValid(contact.getDestination())) ?
335                mChipBackground : mInvalidChipBackground;
336    }
337
338    private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
339        // Ellipsize the text so that it takes AT MOST the entire width of the
340        // autocomplete text entry area. Make sure to leave space for padding
341        // on the sides.
342        int height = (int) mChipHeight;
343        int iconWidth = height;
344        CharSequence ellipsizedText = ellipsizeText(contact.getDisplayName(), paint,
345                calculateAvailableWidth(false) - iconWidth);
346        // Make sure there is a minimum chip width so the user can ALWAYS
347        // tap a chip without difficulty.
348        int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
349                ellipsizedText.length()))
350                + (mChipPadding * 2) + iconWidth);
351
352        // Create the background of the chip.
353        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
354        Canvas canvas = new Canvas(tmpBitmap);
355        Drawable background = getChipBackground(contact);
356        if (background != null) {
357            background.setBounds(0, 0, width, height);
358            background.draw(canvas);
359
360            // Don't draw photos for recipients that have been typed in.
361            if (contact.getContactId() != INVALID_CONTACT) {
362                byte[] photoBytes = contact.getPhotoBytes();
363                // There may not be a photo yet if anything but the first contact address
364                // was selected.
365                if (photoBytes == null && contact.getPhotoThumbnailUri() != null) {
366                    // TODO: cache this in the recipient entry?
367                    ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact
368                            .getPhotoThumbnailUri());
369                    photoBytes = contact.getPhotoBytes();
370                }
371
372                Bitmap photo;
373                if (photoBytes != null) {
374                    photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
375                } else {
376                    // TODO: can the scaled down default photo be cached?
377                    photo = mDefaultContactPhoto;
378                }
379                // Draw the photo on the left side.
380                Matrix matrix = new Matrix();
381                RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight());
382                RectF dst = new RectF(width - iconWidth, 0, width, height);
383                matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
384                canvas.drawBitmap(photo, matrix, paint);
385            } else {
386                // Don't leave any space for the icon. It isn't being drawn.
387                iconWidth = 0;
388            }
389
390            // Align the display text with where the user enters text.
391            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
392                    height - Math.abs(height - mChipFontSize) / 2, paint);
393        } else {
394            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
395        }
396        return tmpBitmap;
397    }
398
399    public RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed)
400            throws NullPointerException {
401        if (mChipBackground == null) {
402            throw new NullPointerException(
403                    "Unable to render any chips as setChipDimensions was not called.");
404        }
405        Layout layout = getLayout();
406
407        TextPaint paint = getPaint();
408        float defaultSize = paint.getTextSize();
409        int defaultColor = paint.getColor();
410
411        Bitmap tmpBitmap;
412        if (pressed) {
413            tmpBitmap = createSelectedChip(contact, paint, layout);
414
415        } else {
416            tmpBitmap = createUnselectedChip(contact, paint, layout);
417        }
418
419        // Pass the full text, un-ellipsized, to the chip.
420        Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
421        result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
422        RecipientChip recipientChip = new RecipientChip(result, contact, offset);
423        // Return text to the original size.
424        paint.setTextSize(defaultSize);
425        paint.setColor(defaultColor);
426        return recipientChip;
427    }
428
429    /**
430     * Calculate the bottom of the line the chip will be located on using:
431     * 1) which line the chip appears on
432     * 2) the height of a chip
433     * 3) padding built into the edit text view
434     */
435    private int calculateOffsetFromBottom(int line) {
436        // Line offsets start at zero.
437        int actualLine = getLineCount() - (line + 1);
438        return -((actualLine * ((int)mChipHeight) + getPaddingBottom()) + getPaddingTop());
439    }
440
441    /**
442     * Get the max amount of space a chip can take up. The formula takes into
443     * account the width of the EditTextView, any view padding, and padding
444     * that will be added to the chip.
445     */
446    private float calculateAvailableWidth(boolean pressed) {
447        return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
448    }
449
450    /**
451     * Set all chip dimensions and resources. This has to be done from the
452     * application as this is a static library.
453     * @param chipBackground
454     * @param chipBackgroundPressed
455     * @param invalidChip
456     * @param chipDelete
457     * @param defaultContact
458     * @param moreResource
459     * @param alternatesLayout
460     * @param chipHeight
461     * @param padding Padding around the text in a chip
462     */
463    public void setChipDimensions(Drawable chipBackground, Drawable chipBackgroundPressed,
464            Drawable invalidChip, Drawable chipDelete, Bitmap defaultContact, int moreResource,
465            int alternatesLayout, float chipHeight, float padding,
466            float chipFontSize) {
467        mChipBackground = chipBackground;
468        mChipBackgroundPressed = chipBackgroundPressed;
469        mChipDelete = chipDelete;
470        mChipPadding = (int) padding;
471        mAlternatesLayout = alternatesLayout;
472        mDefaultContactPhoto = defaultContact;
473        mMoreString = moreResource;
474        mChipHeight = chipHeight;
475        mChipFontSize = chipFontSize;
476        mInvalidChipBackground = invalidChip;
477    }
478
479    @Override
480    public void onSizeChanged(int width, int height, int oldw, int oldh) {
481        super.onSizeChanged(width, height, oldw, oldh);
482        // Check for any pending tokens created before layout had been completed
483        // on the view.
484        if (width != 0 && height != 0) {
485            if (mPendingChipsCount > 0) {
486                handlePendingChips();
487            }
488            mPendingChipsCount = 0;
489            mPendingChips.clear();
490            mHandler.post(mAddTextWatcher);
491        }
492        // Try to find the scroll view parent, if it exists.
493        if (mScrollView == null && !mTried) {
494            ViewParent parent = getParent();
495            while (parent != null && !(parent instanceof ScrollView)) {
496                parent = parent.getParent();
497            }
498            if (parent != null) {
499                mScrollView = (ScrollView) parent;
500            }
501            mTried = true;
502        }
503    }
504
505    private void handlePendingChips() {
506        mTemporaryRecipients = new ArrayList<RecipientChip>(mPendingChipsCount);
507        Editable editable = getText();
508        // Tokenize!
509        for (int i = 0; i < mPendingChips.size(); i++) {
510            String current = mPendingChips.get(i);
511            int tokenStart = editable.toString().indexOf(current);
512            int tokenEnd = tokenStart + current.length();
513            if (tokenStart >= 0) {
514                // When we have a valid token, include it with the token
515                // to the left.
516                if (tokenEnd < editable.length() - 2
517                        && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
518                    tokenEnd++;
519                }
520                createReplacementChip(tokenStart, tokenEnd, editable);
521            }
522            mPendingChipsCount--;
523        }
524        sanitizeSpannable();
525        if (mTemporaryRecipients != null
526                && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
527            if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
528                new RecipientReplacementTask().execute();
529                mTemporaryRecipients = null;
530            } else {
531                // Create the "more" chip
532                mIndividualReplacements = new IndividualReplacementTask();
533                mIndividualReplacements.execute(new ArrayList<RecipientChip>(mTemporaryRecipients
534                        .subList(0, CHIP_LIMIT)));
535
536                createMoreChip();
537            }
538        } else {
539            // There are too many recipients to look up, so just fall back to
540            // showing addresses for all of them.
541            mTemporaryRecipients = null;
542            createMoreChip();
543        }
544    }
545
546    /**
547     * Remove any characters after the last valid chip.
548     */
549    private void sanitizeSpannable() {
550        // Find the last chip; eliminate any commit characters after it.
551        RecipientChip[] chips = getRecipients();
552        if (chips != null && chips.length > 0) {
553            int end;
554            ImageSpan lastSpan;
555            if (mMoreChip != null) {
556                lastSpan = mMoreChip;
557            } else {
558                lastSpan = chips[chips.length - 1];
559            }
560            end = getSpannable().getSpanEnd(lastSpan);
561            Editable editable = getText();
562            int length = editable.length();
563            if (length > end) {
564                // See what characters occur after that and eliminate them.
565                if (Log.isLoggable(TAG, Log.DEBUG)) {
566                    Log.d(TAG, "There were extra characters after the last tokenizable entry."
567                            + editable);
568                }
569                editable.delete(end + 1, length);
570            }
571        }
572    }
573
574    /**
575     * Create a chip that represents just the email address of a recipient. At some later
576     * point, this chip will be attached to a real contact entry, if one exists.
577     */
578    private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) {
579        String token = editable.toString().substring(tokenStart, tokenEnd);
580        int commitCharIndex = token.indexOf(COMMIT_CHAR_COMMA);
581        if (commitCharIndex == token.length() - 1) {
582            token = token.substring(0, token.length() - 1);
583        }
584        RecipientEntry entry = createTokenizedEntry(token);
585        String displayText = entry.getDestination();
586        displayText = (String) mTokenizer.terminateToken(displayText);
587        // Always leave a blank space at the end of a chip.
588        int textLength = displayText.length() - 1;
589        SpannableString chipText = new SpannableString(displayText);
590        int end = getSelectionEnd();
591        int start = mTokenizer.findTokenStart(getText(), end);
592        RecipientChip chip = null;
593        try {
594            chip = constructChipSpan(entry, start, false);
595            chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
596        } catch (NullPointerException e) {
597            Log.e(TAG, e.getMessage(), e);
598        }
599
600        editable.replace(tokenStart, tokenEnd, chipText);
601        // Add this chip to the list of entries "to replace"
602        if (chip != null) {
603            mTemporaryRecipients.add(chip);
604        }
605    }
606
607    private RecipientEntry createTokenizedEntry(String token) {
608        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
609        String address;
610        if (tokens != null && tokens.length > 0) {
611            address = tokens[0].getAddress();
612        } else {
613            address = token;
614        }
615        return RecipientEntry.constructFakeEntry(address);
616    }
617
618    @Override
619    public void setTokenizer(Tokenizer tokenizer) {
620        mTokenizer = tokenizer;
621        super.setTokenizer(mTokenizer);
622    }
623
624    @Override
625    public void setValidator(Validator validator) {
626        mValidator = validator;
627        super.setValidator(validator);
628    }
629
630    /**
631     * We cannot use the default mechanism for replaceText. Instead,
632     * we override onItemClickListener so we can get all the associated
633     * contact information including display text, address, and id.
634     */
635    @Override
636    protected void replaceText(CharSequence text) {
637        return;
638    }
639
640    /**
641     * Dismiss any selected chips when the back key is pressed.
642     */
643    @Override
644    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
645        if (keyCode == KeyEvent.KEYCODE_BACK) {
646            clearSelectedChip();
647        }
648        return super.onKeyPreIme(keyCode, event);
649    }
650
651    /**
652     * Monitor key presses in this view to see if the user types
653     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
654     * If the user has entered text that has contact matches and types
655     * a commit key, create a chip from the topmost matching contact.
656     * If the user has entered text that has no contact matches and types
657     * a commit key, then create a chip from the text they have entered.
658     */
659    @Override
660    public boolean onKeyUp(int keyCode, KeyEvent event) {
661        switch (keyCode) {
662            case KeyEvent.KEYCODE_ENTER:
663            case KeyEvent.KEYCODE_DPAD_CENTER:
664                if (event.hasNoModifiers()) {
665                    if (commitDefault()) {
666                        return true;
667                    }
668                    if (mSelectedChip != null) {
669                        clearSelectedChip();
670                        return true;
671                    } else if (focusNext()) {
672                        return true;
673                    }
674                }
675                break;
676            case KeyEvent.KEYCODE_TAB:
677                if (event.hasNoModifiers()) {
678                    if (mSelectedChip != null) {
679                        clearSelectedChip();
680                    } else {
681                        commitDefault();
682                    }
683                    if (focusNext()) {
684                        return true;
685                    }
686                }
687        }
688        return super.onKeyUp(keyCode, event);
689    }
690
691    private boolean focusNext() {
692        View next = focusSearch(View.FOCUS_DOWN);
693        if (next != null) {
694            next.requestFocus();
695            return true;
696        }
697        return false;
698    }
699
700    /**
701     * Create a chip from the default selection. If the popup is showing, the
702     * default is the first item in the popup suggestions list. Otherwise, it is
703     * whatever the user had typed in. End represents where the the tokenizer
704     * should search for a token to turn into a chip.
705     * @return If a chip was created from a real contact.
706     */
707    private boolean commitDefault() {
708        Editable editable = getText();
709        int end = getSelectionEnd();
710        int start = mTokenizer.findTokenStart(editable, end);
711
712        if (shouldCreateChip(start, end)) {
713            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
714            // In the middle of chip; treat this as an edit
715            // and commit the whole token.
716            if (whatEnd != getSelectionEnd()) {
717                handleEdit(start, whatEnd);
718                return true;
719            }
720            return commitChip(start, end , editable);
721        }
722        return false;
723    }
724
725    private void commitByCharacter() {
726        Editable editable = getText();
727        int end = getSelectionEnd();
728        int start = mTokenizer.findTokenStart(editable, end);
729        if (shouldCreateChip(start, end)) {
730            commitChip(start, end, editable);
731        }
732        setSelection(getText().length());
733    }
734
735    private boolean commitChip(int start, int end, Editable editable) {
736        if (getAdapter().getCount() > 0) {
737            // choose the first entry.
738            submitItemAtPosition(0);
739            dismissDropDown();
740            return true;
741        } else {
742            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
743            String text = editable.toString().substring(start, tokenEnd).trim();
744            clearComposingText();
745            if (text != null && text.length() > 0 && !text.equals(" ")) {
746                RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
747                QwertyKeyListener.markAsReplaced(editable, start, end, "");
748                CharSequence chipText = createChip(entry, false);
749                editable.replace(start, end, chipText);
750                dismissDropDown();
751                return true;
752            }
753        }
754        return false;
755    }
756
757    private boolean shouldCreateChip(int start, int end) {
758        if (hasFocus() && enoughToFilter()) {
759            RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
760            if ((chips == null || chips.length == 0)) {
761                return true;
762            }
763        }
764        return false;
765    }
766
767    private void handleEdit(int start, int end) {
768        // This is in the middle of a chip, so select out the whole chip
769        // and commit it.
770        Editable editable = getText();
771        setSelection(end);
772        String text = getText().toString().substring(start, end);
773        RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
774        QwertyKeyListener.markAsReplaced(editable, start, end, "");
775        CharSequence chipText = createChip(entry, false);
776        editable.replace(start, getSelectionEnd(), chipText);
777        dismissDropDown();
778    }
779
780    /**
781     * If there is a selected chip, delegate the key events
782     * to the selected chip.
783     */
784    @Override
785    public boolean onKeyDown(int keyCode, KeyEvent event) {
786        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
787            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
788                mAlternatesPopup.dismiss();
789            }
790            removeChip(mSelectedChip);
791        }
792
793        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
794            return true;
795        }
796
797        return super.onKeyDown(keyCode, event);
798    }
799
800    private Spannable getSpannable() {
801        return getText();
802    }
803
804    private int getChipStart(RecipientChip chip) {
805        return getSpannable().getSpanStart(chip);
806    }
807
808    private int getChipEnd(RecipientChip chip) {
809        return getSpannable().getSpanEnd(chip);
810    }
811
812    /**
813     * Instead of filtering on the entire contents of the edit box,
814     * this subclass method filters on the range from
815     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
816     * if the length of that range meets or exceeds {@link #getThreshold}
817     * and makes sure that the range is not already a Chip.
818     */
819    @Override
820    protected void performFiltering(CharSequence text, int keyCode) {
821        if (enoughToFilter()) {
822            int end = getSelectionEnd();
823            int start = mTokenizer.findTokenStart(text, end);
824            // If this is a RecipientChip, don't filter
825            // on its contents.
826            Spannable span = getSpannable();
827            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
828            if (chips != null && chips.length > 0) {
829                return;
830            }
831        }
832        super.performFiltering(text, keyCode);
833    }
834
835    private void clearSelectedChip() {
836        if (mSelectedChip != null) {
837            unselectChip(mSelectedChip);
838            mSelectedChip = null;
839        }
840        setCursorVisible(true);
841    }
842
843    /**
844     * Monitor touch events in the RecipientEditTextView.
845     * If the view does not have focus, any tap on the view
846     * will just focus the view. If the view has focus, determine
847     * if the touch target is a recipient chip. If it is and the chip
848     * is not selected, select it and clear any other selected chips.
849     * If it isn't, then select that chip.
850     */
851    @Override
852    public boolean onTouchEvent(MotionEvent event) {
853        if (!isFocused()) {
854            // Ignore any chip taps until this view is focused.
855            return super.onTouchEvent(event);
856        }
857
858        boolean handled = super.onTouchEvent(event);
859        int action = event.getAction();
860        boolean chipWasSelected = false;
861
862        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
863            float x = event.getX();
864            float y = event.getY();
865            setCursorVisible(false);
866            int offset = putOffsetInRange(getOffsetForPosition(x, y));
867            RecipientChip currentChip = findChip(offset);
868            if (currentChip != null) {
869                if (action == MotionEvent.ACTION_UP) {
870                    if (mSelectedChip != null && mSelectedChip != currentChip) {
871                        clearSelectedChip();
872                        mSelectedChip = selectChip(currentChip);
873                    } else if (mSelectedChip == null) {
874                        // Selection may have moved due to the tap event,
875                        // but make sure we correctly reset selection to the
876                        // end so that any unfinished chips are committed.
877                        setSelection(getText().length());
878                        commitDefault();
879                        mSelectedChip = selectChip(currentChip);
880                    } else {
881                        onClick(mSelectedChip, offset, x, y);
882                    }
883                }
884                chipWasSelected = true;
885                handled = true;
886            }
887        }
888        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
889            clearSelectedChip();
890        }
891        return handled;
892    }
893
894    private void scrollLineIntoView(int line) {
895        if (mScrollView != null) {
896            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
897        }
898    }
899
900    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
901            int width, Context context) {
902        int line = getLayout().getLineForOffset(getChipStart(currentChip));
903        int bottom = calculateOffsetFromBottom(line);
904        // Align the alternates popup with the left side of the View,
905        // regardless of the position of the chip tapped.
906        alternatesPopup.setWidth(width);
907        alternatesPopup.setAnchorView(this);
908        alternatesPopup.setVerticalOffset(bottom);
909        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
910        alternatesPopup.setOnItemClickListener(mAlternatesListener);
911        alternatesPopup.show();
912        ListView listView = alternatesPopup.getListView();
913        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
914        // Checked item would be -1 if the adapter has not
915        // loaded the view that should be checked yet. The
916        // variable will be set correctly when onCheckedItemChanged
917        // is called in a separate thread.
918        if (mCheckedItem != -1) {
919            listView.setItemChecked(mCheckedItem, true);
920            mCheckedItem = -1;
921        }
922    }
923
924    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
925        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
926                mAlternatesLayout, this);
927    }
928
929    public void onCheckedItemChanged(int position) {
930        ListView listView = mAlternatesPopup.getListView();
931        if (listView != null && listView.getCheckedItemCount() == 0) {
932            listView.setItemChecked(position, true);
933        } else {
934            mCheckedItem = position;
935        }
936    }
937
938    // TODO: This algorithm will need a lot of tweaking after more people have used
939    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
940    // what comes before the finger.
941    private int putOffsetInRange(int o) {
942        int offset = o;
943        Editable text = getText();
944        int length = text.length();
945        // Remove whitespace from end to find "real end"
946        int realLength = length;
947        for (int i = length - 1; i >= 0; i--) {
948            if (text.charAt(i) == ' ') {
949                realLength--;
950            } else {
951                break;
952            }
953        }
954
955        // If the offset is beyond or at the end of the text,
956        // leave it alone.
957        if (offset >= realLength) {
958            return offset;
959        }
960        Editable editable = getText();
961        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
962            // Keep walking backward!
963            offset--;
964        }
965        return offset;
966    }
967
968    private int findText(Editable text, int offset) {
969        if (text.charAt(offset) != ' ') {
970            return offset;
971        }
972        return -1;
973    }
974
975    private RecipientChip findChip(int offset) {
976        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
977        // Find the chip that contains this offset.
978        for (int i = 0; i < chips.length; i++) {
979            RecipientChip chip = chips[i];
980            int start = getChipStart(chip);
981            int end = getChipEnd(chip);
982            if (offset >= start && offset <= end) {
983                return chip;
984            }
985        }
986        return null;
987    }
988
989    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
990        String displayText = entry.getDestination();
991        displayText = (String) mTokenizer.terminateToken(displayText);
992        // Always leave a blank space at the end of a chip.
993        int textLength = displayText.length()-1;
994        SpannableString chipText = new SpannableString(displayText);
995        int end = getSelectionEnd();
996        int start = mTokenizer.findTokenStart(getText(), end);
997        try {
998            chipText.setSpan(constructChipSpan(entry, start, pressed), 0, textLength,
999                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1000        } catch (NullPointerException e) {
1001            Log.e(TAG, e.getMessage(), e);
1002            return null;
1003        }
1004
1005        return chipText;
1006    }
1007
1008    /**
1009     * When an item in the suggestions list has been clicked, create a chip from the
1010     * contact information of the selected item.
1011     */
1012    @Override
1013    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1014        submitItemAtPosition(position);
1015    }
1016
1017    private void submitItemAtPosition(int position) {
1018        RecipientEntry entry = createValidatedEntry(
1019                (RecipientEntry)getAdapter().getItem(position));
1020        clearComposingText();
1021
1022        int end = getSelectionEnd();
1023        int start = mTokenizer.findTokenStart(getText(), end);
1024
1025        Editable editable = getText();
1026        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1027        editable.replace(start, end, createChip(entry, false));
1028    }
1029
1030    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1031        if (item == null) {
1032            return null;
1033        }
1034        final RecipientEntry entry;
1035        // If the display name and the address are the same, or if this is a
1036        // valid contact, but the destination is invalid, then make this a fake
1037        // recipient that is editable.
1038        String destination = item.getDestination();
1039        if (TextUtils.equals(item.getDisplayName(), destination)
1040                || (mValidator != null && !mValidator.isValid(destination))) {
1041            entry = RecipientEntry.constructFakeEntry(destination);
1042        } else {
1043            entry = item;
1044        }
1045        return entry;
1046    }
1047
1048    /** Returns a collection of contact Id for each chip inside this View. */
1049    /* package */ Collection<Long> getContactIds() {
1050        final Set<Long> result = new HashSet<Long>();
1051        RecipientChip[] chips = getRecipients();
1052        if (chips != null) {
1053            for (RecipientChip chip : chips) {
1054                result.add(chip.getContactId());
1055            }
1056        }
1057        return result;
1058    }
1059
1060    private RecipientChip[] getRecipients() {
1061        return getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1062    }
1063
1064    /** Returns a collection of data Id for each chip inside this View. May be null. */
1065    /* package */ Collection<Long> getDataIds() {
1066        final Set<Long> result = new HashSet<Long>();
1067        RecipientChip [] chips = getRecipients();
1068        if (chips != null) {
1069            for (RecipientChip chip : chips) {
1070                result.add(chip.getDataId());
1071            }
1072        }
1073        return result;
1074    }
1075
1076
1077    @Override
1078    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1079        return false;
1080    }
1081
1082    @Override
1083    public void onDestroyActionMode(ActionMode mode) {
1084    }
1085
1086    @Override
1087    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1088        return false;
1089    }
1090
1091    /**
1092     * No chips are selectable.
1093     */
1094    @Override
1095    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1096        return false;
1097    }
1098
1099    /**
1100     * Create the more chip. The more chip is text that replaces any chips that
1101     * do not fit in the pre-defined available space when the
1102     * RecipientEditTextView loses focus.
1103     */
1104    private void createMoreChip() {
1105        RecipientChip[] recipients = getRecipients();
1106        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1107            mMoreChip = null;
1108            return;
1109        }
1110        int numRecipients = recipients.length;
1111        int overage = numRecipients - CHIP_LIMIT;
1112        Editable text = getText();
1113        // TODO: get the correct size from visual design.
1114        int width = (int) Math.floor(getWidth() * MORE_WIDTH_FACTOR);
1115        int height = getLineHeight();
1116        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1117        Canvas canvas = new Canvas(drawable);
1118        String moreText = getResources().getString(mMoreString, overage);
1119        canvas.drawText(moreText, 0, moreText.length(), 0, height - getLayout().getLineDescent(0),
1120                getPaint());
1121
1122        Drawable result = new BitmapDrawable(getResources(), drawable);
1123        result.setBounds(0, 0, width, height);
1124        ImageSpan moreSpan = new ImageSpan(result);
1125        Spannable spannable = getSpannable();
1126        // Remove the overage chips.
1127        if (recipients == null || recipients.length == 0) {
1128            Log.w(TAG,
1129                    "We have recipients. Tt should not be possible to have zero RecipientChips.");
1130            mMoreChip = null;
1131            return;
1132        }
1133        mRemovedSpans = new ArrayList<RecipientChip>();
1134        int totalReplaceStart = 0;
1135        int totalReplaceEnd = 0;
1136        for (int i = numRecipients - overage; i < recipients.length; i++) {
1137            mRemovedSpans.add(recipients[i]);
1138            if (i == numRecipients - overage) {
1139                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1140            }
1141            if (i == recipients.length - 1) {
1142                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1143            }
1144            if (mTemporaryRecipients != null && !mTemporaryRecipients.contains(recipients[i])) {
1145                recipients[i].storeChipStart(spannable.getSpanStart(recipients[i]));
1146                recipients[i].storeChipEnd(spannable.getSpanEnd(recipients[i]));
1147            }
1148            spannable.removeSpan(recipients[i]);
1149        }
1150        // TODO: why would these ever be backwards?
1151        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1152        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1153        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1154        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1155        text.replace(start, end, chipText);
1156        mMoreChip = moreSpan;
1157    }
1158
1159    /**
1160     * Replace the more chip, if it exists, with all of the recipient chips it had
1161     * replaced when the RecipientEditTextView gains focus.
1162     */
1163    private void removeMoreChip() {
1164        if (mMoreChip != null) {
1165            Spannable span = getSpannable();
1166            span.removeSpan(mMoreChip);
1167            mMoreChip = null;
1168            // Re-add the spans that were removed.
1169            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1170                // Recreate each removed span.
1171                Editable editable = getText();
1172                for (RecipientChip chip : mRemovedSpans) {
1173                    int chipStart = chip.getStoredChipStart();
1174                    int chipEnd;
1175                    String token;
1176                    if (chipStart == -1) {
1177                        // Need to find the location of the chip, again.
1178                        token = (String)mTokenizer.terminateToken(chip.getEntry().getDestination());
1179                        chipStart = editable.toString().indexOf(token);
1180                        // -1 for the space!
1181                        chipEnd = chipStart + token.length() - 1;
1182                    } else {
1183                        chipEnd = Math.min(editable.length(), chip.getStoredChipEnd());
1184                    }
1185                    if (Log.isLoggable(TAG, Log.DEBUG) && chipEnd != chip.getStoredChipEnd()) {
1186                        Log.d(TAG,
1187                                "Unexpectedly, the chip ended after the end of the editable text. "
1188                                        + "Chip End " + chip.getStoredChipEnd()
1189                                        + "Editable length " + editable.length());
1190                    }
1191                    // Only set the span if we found a matching token.
1192                    if (chipStart != -1) {
1193                        editable.setSpan(chip, chipStart, chipEnd,
1194                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1195                    }
1196                }
1197                mRemovedSpans.clear();
1198            }
1199        }
1200    }
1201
1202    /**
1203     * Show specified chip as selected. If the RecipientChip is just an email address,
1204     * selecting the chip will take the contents of the chip and place it at
1205     * the end of the RecipientEditTextView for inline editing. If the
1206     * RecipientChip is a complete contact, then selecting the chip
1207     * will change the background color of the chip, show the delete icon,
1208     * and a popup window with the address in use highlighted and any other
1209     * alternate addresses for the contact.
1210     * @param currentChip Chip to select.
1211     * @return A RecipientChip in the selected state or null if the chip
1212     * just contained an email address.
1213     */
1214    public RecipientChip selectChip(RecipientChip currentChip) {
1215        if (currentChip.getContactId() != INVALID_CONTACT) {
1216            int start = getChipStart(currentChip);
1217            int end = getChipEnd(currentChip);
1218            getSpannable().removeSpan(currentChip);
1219            RecipientChip newChip;
1220            try {
1221                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1222            } catch (NullPointerException e) {
1223                Log.e(TAG, e.getMessage(), e);
1224                return null;
1225            }
1226            Editable editable = getText();
1227            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1228            if (start == -1 || end == -1) {
1229                Log.d(TAG, "The chip being selected no longer exists but should.");
1230            } else {
1231                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1232            }
1233            newChip.setSelected(true);
1234            if (newChip.getEntry().getContactId() == INVALID_CONTACT) {
1235                scrollLineIntoView(getLayout().getLineForOffset(
1236                        getChipStart(newChip)));
1237            }
1238            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1239            return newChip;
1240        } else {
1241            CharSequence text = currentChip.getValue();
1242            Editable editable = getText();
1243            removeChip(currentChip);
1244            editable.append(text);
1245            setCursorVisible(true);
1246            setSelection(editable.length());
1247            return null;
1248        }
1249    }
1250
1251
1252    /**
1253     * Remove selection from this chip. Unselecting a RecipientChip will render
1254     * the chip without a delete icon and with an unfocused background. This
1255     * is called when the RecipientChip no longer has focus.
1256     */
1257    public void unselectChip(RecipientChip chip) {
1258        int start = getChipStart(chip);
1259        int end = getChipEnd(chip);
1260        Editable editable = getText();
1261        mSelectedChip = null;
1262        if (start == -1 || end == -1) {
1263            Log.e(TAG, "The chip being unselected no longer exists but should.");
1264        } else {
1265            getSpannable().removeSpan(chip);
1266            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1267            editable.removeSpan(chip);
1268            try {
1269                editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1270                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1271            } catch (NullPointerException e) {
1272                Log.e(TAG, e.getMessage(), e);
1273            }
1274        }
1275        setCursorVisible(true);
1276        setSelection(editable.length());
1277        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1278            mAlternatesPopup.dismiss();
1279        }
1280    }
1281
1282
1283    /**
1284     * Return whether this chip contains the position passed in.
1285     */
1286    public boolean matchesChip(RecipientChip chip, int offset) {
1287        int start = getChipStart(chip);
1288        int end = getChipEnd(chip);
1289        if (start == -1 || end == -1) {
1290            return false;
1291        }
1292        return (offset >= start && offset <= end);
1293    }
1294
1295
1296    /**
1297     * Return whether a touch event was inside the delete target of
1298     * a selected chip. It is in the delete target if:
1299     * 1) the x and y points of the event are within the
1300     * delete assset.
1301     * 2) the point tapped would have caused a cursor to appear
1302     * right after the selected chip.
1303     * @return boolean
1304     */
1305    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1306        // Figure out the bounds of this chip and whether or not
1307        // the user clicked in the X portion.
1308        return chip.isSelected() && offset == getChipEnd(chip);
1309    }
1310
1311    /**
1312     * Remove the chip and any text associated with it from the RecipientEditTextView.
1313     */
1314    private void removeChip(RecipientChip chip) {
1315        Spannable spannable = getSpannable();
1316        int spanStart = spannable.getSpanStart(chip);
1317        int spanEnd = spannable.getSpanEnd(chip);
1318        Editable text = getText();
1319        int toDelete = spanEnd;
1320        boolean wasSelected = chip == mSelectedChip;
1321        // Clear that there is a selected chip before updating any text.
1322        if (wasSelected) {
1323            mSelectedChip = null;
1324        }
1325        // Always remove trailing spaces when removing a chip.
1326        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
1327            toDelete++;
1328        }
1329        spannable.removeSpan(chip);
1330        text.delete(spanStart, toDelete);
1331        if (wasSelected) {
1332            clearSelectedChip();
1333        }
1334    }
1335
1336    /**
1337     * Replace this currently selected chip with a new chip
1338     * that uses the contact data provided.
1339     */
1340    public void replaceChip(RecipientChip chip, RecipientEntry entry) {
1341        boolean wasSelected = chip == mSelectedChip;
1342        if (wasSelected) {
1343            mSelectedChip = null;
1344        }
1345        int start = getChipStart(chip);
1346        int end = getChipEnd(chip);
1347        getSpannable().removeSpan(chip);
1348        Editable editable = getText();
1349        CharSequence chipText = createChip(entry, false);
1350        if (start == -1 || end == -1) {
1351            Log.e(TAG, "The chip to replace does not exist but should.");
1352            editable.insert(0, chipText);
1353        } else {
1354            // There may be a space to replace with this chip's new associated
1355            // space. Check for it.
1356            int toReplace = end;
1357            while (toReplace >= 0 && toReplace < editable.length()
1358                    && editable.charAt(toReplace) == ' ') {
1359                toReplace++;
1360            }
1361            editable.replace(start, toReplace, chipText);
1362        }
1363        setCursorVisible(true);
1364        if (wasSelected) {
1365            clearSelectedChip();
1366        }
1367    }
1368
1369    /**
1370     * Handle click events for a chip. When a selected chip receives a click
1371     * event, see if that event was in the delete icon. If so, delete it.
1372     * Otherwise, unselect the chip.
1373     */
1374    public void onClick(RecipientChip chip, int offset, float x, float y) {
1375        if (chip.isSelected()) {
1376            if (isInDelete(chip, offset, x, y)) {
1377                removeChip(chip);
1378            } else {
1379                clearSelectedChip();
1380            }
1381        }
1382    }
1383
1384    private boolean chipsPending() {
1385        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1386    }
1387
1388    private class RecipientTextWatcher implements TextWatcher {
1389        @Override
1390        public void afterTextChanged(Editable s) {
1391            // Get whether there are any recipients pending addition to the view.
1392            // If there are, don't do anything in the text watcher.
1393            if (chipsPending()) {
1394                return;
1395            }
1396            if (mSelectedChip != null) {
1397                setCursorVisible(true);
1398                setSelection(getText().length());
1399                clearSelectedChip();
1400            }
1401            int length = s.length();
1402            // Make sure there is content there to parse and that it is
1403            // not just the commit character.
1404            if (length > 1) {
1405                char last;
1406                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
1407                int len = length() - 1;
1408                if (end != len) {
1409                    last = s.charAt(end);
1410                } else {
1411                    last = s.charAt(len);
1412                }
1413                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
1414                    commitByCharacter();
1415                } else if (last == COMMIT_CHAR_SPACE) {
1416                    // Check if this is a valid email address. If it is,
1417                    // commit it.
1418                    String text = getText().toString();
1419                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1420                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
1421                            tokenStart));
1422                    if (mValidator != null && mValidator.isValid(sub)) {
1423                        commitByCharacter();
1424                    }
1425                }
1426            }
1427        }
1428
1429        @Override
1430        public void onTextChanged(CharSequence s, int start, int before, int count) {
1431        }
1432
1433        @Override
1434        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1435        }
1436    }
1437
1438    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
1439        private RecipientChip createFreeChip(RecipientEntry entry) {
1440            String displayText = entry.getDestination();
1441            displayText = (String) mTokenizer.terminateToken(displayText);
1442            try {
1443                return constructChipSpan(entry, -1, false);
1444            } catch (NullPointerException e) {
1445                Log.e(TAG, e.getMessage(), e);
1446                return null;
1447            }
1448        }
1449
1450        @Override
1451        protected Void doInBackground(Void... params) {
1452            if (mIndividualReplacements != null) {
1453                mIndividualReplacements.cancel(true);
1454            }
1455            // For each chip in the list, look up the matching contact.
1456            // If there is a match, replace that chip with the matching
1457            // chip.
1458            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
1459            RecipientChip[] existingChips = getSpannable().getSpans(0, getText().length(),
1460                    RecipientChip.class);
1461            for (int i = 0; i < existingChips.length; i++) {
1462                originalRecipients.add(existingChips[i]);
1463            }
1464            if (mRemovedSpans != null) {
1465                originalRecipients.addAll(mRemovedSpans);
1466            }
1467            String[] addresses = new String[originalRecipients.size()];
1468            for (int i = 0; i < originalRecipients.size(); i++) {
1469                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1470            }
1471            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1472                    .getMatchingRecipients(getContext(), addresses);
1473            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
1474            for (final RecipientChip temp : originalRecipients) {
1475                RecipientEntry entry = null;
1476                if (temp.getEntry().getContactId() == INVALID_CONTACT
1477                        && getSpannable().getSpanStart(temp) != -1) {
1478                    // Replace this.
1479                    entry = createValidatedEntry(entries.get(temp.getEntry().getDestination()));
1480                }
1481                if (entry != null) {
1482                    replacements.add(createFreeChip(entry));
1483                } else {
1484                    replacements.add(temp);
1485                }
1486            }
1487            if (replacements != null && replacements.size() > 0) {
1488                mHandler.post(new Runnable() {
1489                    @Override
1490                    public void run() {
1491                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
1492                                .toString());
1493                        Editable oldText = getText();
1494                        int start, end;
1495                        int i = 0;
1496                        for (RecipientChip chip : originalRecipients) {
1497                            start = oldText.getSpanStart(chip);
1498                            if (start != -1) {
1499                                end = oldText.getSpanEnd(chip);
1500                                text.removeSpan(chip);
1501                                // Leave a spot for the space!
1502                                text.setSpan(replacements.get(i), start, end,
1503                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1504                            }
1505                            i++;
1506                        }
1507                        Editable editable = getText();
1508                        editable.clear();
1509                        editable.insert(0, text);
1510                        originalRecipients.clear();
1511                    }
1512                });
1513            }
1514            return null;
1515        }
1516    }
1517
1518    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
1519        @SuppressWarnings("unchecked")
1520        @Override
1521        protected Void doInBackground(Object... params) {
1522            // For each chip in the list, look up the matching contact.
1523            // If there is a match, replace that chip with the matching
1524            // chip.
1525            final ArrayList<RecipientChip> originalRecipients =
1526                (ArrayList<RecipientChip>) params[0];
1527            String[] addresses = new String[originalRecipients.size()];
1528            for (int i = 0; i < originalRecipients.size(); i++) {
1529                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1530            }
1531            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1532                    .getMatchingRecipients(getContext(), addresses);
1533            for (final RecipientChip temp : originalRecipients) {
1534                if (temp.getEntry().getContactId() == INVALID_CONTACT
1535                        && getSpannable().getSpanStart(temp) != -1) {
1536                    // Replace this.
1537                    final RecipientEntry entry = createValidatedEntry(entries.get(temp.getEntry()
1538                            .getDestination()));
1539                    if (entry != null) {
1540                        mHandler.post(new Runnable() {
1541                            @Override
1542                            public void run() {
1543                                replaceChip(temp, entry);
1544                            }
1545                        });
1546                    }
1547                }
1548            }
1549            return null;
1550        }
1551    }
1552}
1553