RecipientEditTextView.java revision 77056d7532cd26e869964a52456ef18c96f6cbd7
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, int chipHeight) {
436        // Line offsets start at zero.
437        int actualLine = getLineCount() - (line + 1);
438        return -((actualLine * (chipHeight + 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
541            // for all of them.
542            mTemporaryRecipients = null;
543            createMoreChip();
544        }
545    }
546
547    /**
548     * Remove any characters after the last valid chip.
549     */
550    private void sanitizeSpannable() {
551        // Find the last chip; eliminate any commit characters after it.
552        RecipientChip[] chips = getRecipients();
553        if (chips != null && chips.length > 0) {
554            int end;
555            ImageSpan lastSpan;
556            if (mMoreChip != null) {
557                lastSpan = mMoreChip;
558            } else {
559                lastSpan = chips[chips.length - 1];
560            }
561            end = getSpannable().getSpanEnd(lastSpan);
562            Editable editable = getText();
563            int length = editable.length();
564            if (length > end) {
565                // See what characters occur after that and eliminate them.
566                if (Log.isLoggable(TAG, Log.DEBUG)) {
567                    Log.d(TAG, "There were extra characters after the last tokenizable entry."
568                            + editable);
569                }
570                editable.delete(end + 1, length);
571            }
572        }
573    }
574
575    /**
576     * Create a chip that represents just the email address of a recipient. At some later
577     * point, this chip will be attached to a real contact entry, if one exists.
578     */
579    private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) {
580        String token = editable.toString().substring(tokenStart, tokenEnd).trim();
581        int commitCharIndex = token.indexOf(COMMIT_CHAR_COMMA);
582        if (commitCharIndex == token.length() - 1) {
583            token = token.substring(0, token.length() - 1);
584        }
585        RecipientEntry entry = createTokenizedEntry(token);
586        String displayText = entry.getDestination();
587        displayText = (String) mTokenizer.terminateToken(displayText);
588        // Always leave a blank space at the end of a chip.
589        int textLength = displayText.length() - 1;
590        SpannableString chipText = new SpannableString(displayText);
591        int end = getSelectionEnd();
592        int start = mTokenizer.findTokenStart(getText(), end);
593        RecipientChip chip = null;
594        try {
595            chip = constructChipSpan(entry, start, false);
596            chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
597        } catch (NullPointerException e) {
598            Log.e(TAG, e.getMessage(), e);
599        }
600
601        editable.replace(tokenStart, tokenEnd, chipText);
602        // Add this chip to the list of entries "to replace"
603        if (chip != null) {
604            mTemporaryRecipients.add(chip);
605        }
606    }
607
608    private RecipientEntry createTokenizedEntry(String token) {
609        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
610        String address;
611        if (tokens != null && tokens.length > 0) {
612            address = tokens[0].getAddress();
613        } else {
614            address = token;
615        }
616        return RecipientEntry.constructFakeEntry(address);
617    }
618
619    @Override
620    public void setTokenizer(Tokenizer tokenizer) {
621        mTokenizer = tokenizer;
622        super.setTokenizer(mTokenizer);
623    }
624
625    @Override
626    public void setValidator(Validator validator) {
627        mValidator = validator;
628        super.setValidator(validator);
629    }
630
631    /**
632     * We cannot use the default mechanism for replaceText. Instead,
633     * we override onItemClickListener so we can get all the associated
634     * contact information including display text, address, and id.
635     */
636    @Override
637    protected void replaceText(CharSequence text) {
638        return;
639    }
640
641    /**
642     * Dismiss any selected chips when the back key is pressed.
643     */
644    @Override
645    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
646        if (keyCode == KeyEvent.KEYCODE_BACK) {
647            clearSelectedChip();
648        }
649        return super.onKeyPreIme(keyCode, event);
650    }
651
652    /**
653     * Monitor key presses in this view to see if the user types
654     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
655     * If the user has entered text that has contact matches and types
656     * a commit key, create a chip from the topmost matching contact.
657     * If the user has entered text that has no contact matches and types
658     * a commit key, then create a chip from the text they have entered.
659     */
660    @Override
661    public boolean onKeyUp(int keyCode, KeyEvent event) {
662        switch (keyCode) {
663            case KeyEvent.KEYCODE_ENTER:
664            case KeyEvent.KEYCODE_DPAD_CENTER:
665                if (event.hasNoModifiers()) {
666                    if (commitDefault()) {
667                        return true;
668                    }
669                    if (mSelectedChip != null) {
670                        clearSelectedChip();
671                        return true;
672                    } else if (focusNext()) {
673                        return true;
674                    }
675                }
676                break;
677            case KeyEvent.KEYCODE_TAB:
678                if (event.hasNoModifiers()) {
679                    if (mSelectedChip != null) {
680                        clearSelectedChip();
681                    } else {
682                        commitDefault();
683                    }
684                    if (focusNext()) {
685                        return true;
686                    }
687                }
688        }
689        return super.onKeyUp(keyCode, event);
690    }
691
692    private boolean focusNext() {
693        View next = focusSearch(View.FOCUS_DOWN);
694        if (next != null) {
695            next.requestFocus();
696            return true;
697        }
698        return false;
699    }
700
701    /**
702     * Create a chip from the default selection. If the popup is showing, the
703     * default is the first item in the popup suggestions list. Otherwise, it is
704     * whatever the user had typed in. End represents where the the tokenizer
705     * should search for a token to turn into a chip.
706     * @return If a chip was created from a real contact.
707     */
708    private boolean commitDefault() {
709        Editable editable = getText();
710        int end = getSelectionEnd();
711        int start = mTokenizer.findTokenStart(editable, end);
712
713        if (shouldCreateChip(start, end)) {
714            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
715            // In the middle of chip; treat this as an edit
716            // and commit the whole token.
717            if (whatEnd != getSelectionEnd()) {
718                handleEdit(start, whatEnd);
719                return true;
720            }
721            return commitChip(start, end , editable);
722        }
723        return false;
724    }
725
726    private void commitByCharacter() {
727        Editable editable = getText();
728        int end = getSelectionEnd();
729        int start = mTokenizer.findTokenStart(editable, end);
730        if (shouldCreateChip(start, end)) {
731            commitChip(start, end, editable);
732        }
733        setSelection(getText().length());
734    }
735
736    private boolean commitChip(int start, int end, Editable editable) {
737        if (getAdapter().getCount() > 0) {
738            // choose the first entry.
739            submitItemAtPosition(0);
740            dismissDropDown();
741            return true;
742        } else {
743            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
744            String text = editable.toString().substring(start, tokenEnd).trim();
745            clearComposingText();
746            if (text != null && text.length() > 0 && !text.equals(" ")) {
747                RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
748                QwertyKeyListener.markAsReplaced(editable, start, end, "");
749                CharSequence chipText = createChip(entry, false);
750                editable.replace(start, end, chipText);
751                dismissDropDown();
752                return true;
753            }
754        }
755        return false;
756    }
757
758    private boolean shouldCreateChip(int start, int end) {
759        if (hasFocus() && enoughToFilter()) {
760            RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
761            if ((chips == null || chips.length == 0)) {
762                return true;
763            }
764        }
765        return false;
766    }
767
768    private void handleEdit(int start, int end) {
769        // This is in the middle of a chip, so select out the whole chip
770        // and commit it.
771        Editable editable = getText();
772        setSelection(end);
773        String text = getText().toString().substring(start, end);
774        RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
775        QwertyKeyListener.markAsReplaced(editable, start, end, "");
776        CharSequence chipText = createChip(entry, false);
777        editable.replace(start, getSelectionEnd(), chipText);
778        dismissDropDown();
779    }
780
781    /**
782     * If there is a selected chip, delegate the key events
783     * to the selected chip.
784     */
785    @Override
786    public boolean onKeyDown(int keyCode, KeyEvent event) {
787        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
788            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
789                mAlternatesPopup.dismiss();
790            }
791            removeChip(mSelectedChip);
792        }
793
794        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
795            return true;
796        }
797
798        return super.onKeyDown(keyCode, event);
799    }
800
801    private Spannable getSpannable() {
802        return getText();
803    }
804
805    private int getChipStart(RecipientChip chip) {
806        return getSpannable().getSpanStart(chip);
807    }
808
809    private int getChipEnd(RecipientChip chip) {
810        return getSpannable().getSpanEnd(chip);
811    }
812
813    /**
814     * Instead of filtering on the entire contents of the edit box,
815     * this subclass method filters on the range from
816     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
817     * if the length of that range meets or exceeds {@link #getThreshold}
818     * and makes sure that the range is not already a Chip.
819     */
820    @Override
821    protected void performFiltering(CharSequence text, int keyCode) {
822        if (enoughToFilter()) {
823            int end = getSelectionEnd();
824            int start = mTokenizer.findTokenStart(text, end);
825            // If this is a RecipientChip, don't filter
826            // on its contents.
827            Spannable span = getSpannable();
828            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
829            if (chips != null && chips.length > 0) {
830                return;
831            }
832        }
833        super.performFiltering(text, keyCode);
834    }
835
836    private void clearSelectedChip() {
837        if (mSelectedChip != null) {
838            unselectChip(mSelectedChip);
839            mSelectedChip = null;
840        }
841        setCursorVisible(true);
842    }
843
844    /**
845     * Monitor touch events in the RecipientEditTextView.
846     * If the view does not have focus, any tap on the view
847     * will just focus the view. If the view has focus, determine
848     * if the touch target is a recipient chip. If it is and the chip
849     * is not selected, select it and clear any other selected chips.
850     * If it isn't, then select that chip.
851     */
852    @Override
853    public boolean onTouchEvent(MotionEvent event) {
854        if (!isFocused()) {
855            // Ignore any chip taps until this view is focused.
856            return super.onTouchEvent(event);
857        }
858
859        boolean handled = super.onTouchEvent(event);
860        int action = event.getAction();
861        boolean chipWasSelected = false;
862
863        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
864            float x = event.getX();
865            float y = event.getY();
866            setCursorVisible(false);
867            int offset = putOffsetInRange(getOffsetForPosition(x, y));
868            RecipientChip currentChip = findChip(offset);
869            if (currentChip != null) {
870                if (action == MotionEvent.ACTION_UP) {
871                    if (mSelectedChip != null && mSelectedChip != currentChip) {
872                        clearSelectedChip();
873                        mSelectedChip = selectChip(currentChip);
874                    } else if (mSelectedChip == null) {
875                        // Selection may have moved due to the tap event,
876                        // but make sure we correctly reset selection to the
877                        // end so that any unfinished chips are committed.
878                        setSelection(getText().length());
879                        commitDefault();
880                        mSelectedChip = selectChip(currentChip);
881                        if (mSelectedChip != null
882                                && mSelectedChip.getEntry().getContactId() == INVALID_CONTACT) {
883                            scrollLineIntoView(getLayout().getLineForOffset(
884                                    getChipStart(mSelectedChip)));
885                        }
886                    } else {
887                        onClick(mSelectedChip, offset, x, y);
888                    }
889                }
890                chipWasSelected = true;
891                handled = true;
892            }
893        }
894        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
895            clearSelectedChip();
896        }
897        return handled;
898    }
899
900    private void scrollLineIntoView(int line) {
901        if (mScrollView != null) {
902            mScrollView.scrollBy(0, calculateOffsetFromBottom(line, (int) mChipHeight));
903        }
904    }
905
906    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
907            int width, Context context) {
908        int line = getLayout().getLineForOffset(getChipStart(currentChip));
909        int bottom = calculateOffsetFromBottom(line, (int) mChipHeight);
910        // Align the alternates popup with the left side of the View,
911        // regardless of the position of the chip tapped.
912        alternatesPopup.setWidth(width);
913        alternatesPopup.setAnchorView(this);
914        alternatesPopup.setVerticalOffset(bottom);
915        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
916        alternatesPopup.setOnItemClickListener(mAlternatesListener);
917        alternatesPopup.show();
918        ListView listView = alternatesPopup.getListView();
919        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
920        // Checked item would be -1 if the adapter has not
921        // loaded the view that should be checked yet. The
922        // variable will be set correctly when onCheckedItemChanged
923        // is called in a separate thread.
924        if (mCheckedItem != -1) {
925            listView.setItemChecked(mCheckedItem, true);
926            mCheckedItem = -1;
927        }
928    }
929
930    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
931        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
932                mAlternatesLayout, this);
933    }
934
935    public void onCheckedItemChanged(int position) {
936        ListView listView = mAlternatesPopup.getListView();
937        if (listView != null && listView.getCheckedItemCount() == 0) {
938            listView.setItemChecked(position, true);
939        } else {
940            mCheckedItem = position;
941        }
942    }
943
944    // TODO: This algorithm will need a lot of tweaking after more people have used
945    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
946    // what comes before the finger.
947    private int putOffsetInRange(int o) {
948        int offset = o;
949        Editable text = getText();
950        int length = text.length();
951        // Remove whitespace from end to find "real end"
952        int realLength = length;
953        for (int i = length - 1; i >= 0; i--) {
954            if (text.charAt(i) == ' ') {
955                realLength--;
956            } else {
957                break;
958            }
959        }
960
961        // If the offset is beyond or at the end of the text,
962        // leave it alone.
963        if (offset >= realLength) {
964            return offset;
965        }
966        Editable editable = getText();
967        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
968            // Keep walking backward!
969            offset--;
970        }
971        return offset;
972    }
973
974    private int findText(Editable text, int offset) {
975        if (text.charAt(offset) != ' ') {
976            return offset;
977        }
978        return -1;
979    }
980
981    private RecipientChip findChip(int offset) {
982        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
983        // Find the chip that contains this offset.
984        for (int i = 0; i < chips.length; i++) {
985            RecipientChip chip = chips[i];
986            int start = getChipStart(chip);
987            int end = getChipEnd(chip);
988            if (offset >= start && offset <= end) {
989                return chip;
990            }
991        }
992        return null;
993    }
994
995    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
996        String displayText = entry.getDestination();
997        displayText = (String) mTokenizer.terminateToken(displayText);
998        // Always leave a blank space at the end of a chip.
999        int textLength = displayText.length() - 1;
1000        SpannableString chipText = new SpannableString(displayText);
1001        int end = getSelectionEnd();
1002        int start = mTokenizer.findTokenStart(getText(), end);
1003        try {
1004            chipText.setSpan(constructChipSpan(entry, start, pressed), 0, textLength,
1005                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1006        } catch (NullPointerException e) {
1007            Log.e(TAG, e.getMessage(), e);
1008            return null;
1009        }
1010
1011        return chipText;
1012    }
1013
1014    /**
1015     * When an item in the suggestions list has been clicked, create a chip from the
1016     * contact information of the selected item.
1017     */
1018    @Override
1019    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1020        submitItemAtPosition(position);
1021    }
1022
1023    private void submitItemAtPosition(int position) {
1024        RecipientEntry entry = createValidatedEntry(
1025                (RecipientEntry)getAdapter().getItem(position));
1026        clearComposingText();
1027
1028        int end = getSelectionEnd();
1029        int start = mTokenizer.findTokenStart(getText(), end);
1030
1031        Editable editable = getText();
1032        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1033        editable.replace(start, end, createChip(entry, false));
1034    }
1035
1036    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1037        if (item == null) {
1038            return null;
1039        }
1040        final RecipientEntry entry;
1041        // If the display name and the address are the same, or if this is a
1042        // valid contact, but the destination is invalid, then make this a fake
1043        // recipient that is editable.
1044        String destination = item.getDestination();
1045        if (TextUtils.equals(item.getDisplayName(), destination)
1046                || (mValidator != null && !mValidator.isValid(destination))) {
1047            entry = RecipientEntry.constructFakeEntry(destination);
1048        } else {
1049            entry = item;
1050        }
1051        return entry;
1052    }
1053
1054    /** Returns a collection of contact Id for each chip inside this View. */
1055    /* package */ Collection<Long> getContactIds() {
1056        final Set<Long> result = new HashSet<Long>();
1057        RecipientChip[] chips = getRecipients();
1058        if (chips != null) {
1059            for (RecipientChip chip : chips) {
1060                result.add(chip.getContactId());
1061            }
1062        }
1063        return result;
1064    }
1065
1066    private RecipientChip[] getRecipients() {
1067        return getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1068    }
1069
1070    /** Returns a collection of data Id for each chip inside this View. May be null. */
1071    /* package */ Collection<Long> getDataIds() {
1072        final Set<Long> result = new HashSet<Long>();
1073        RecipientChip [] chips = getRecipients();
1074        if (chips != null) {
1075            for (RecipientChip chip : chips) {
1076                result.add(chip.getDataId());
1077            }
1078        }
1079        return result;
1080    }
1081
1082
1083    @Override
1084    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1085        return false;
1086    }
1087
1088    @Override
1089    public void onDestroyActionMode(ActionMode mode) {
1090    }
1091
1092    @Override
1093    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1094        return false;
1095    }
1096
1097    /**
1098     * No chips are selectable.
1099     */
1100    @Override
1101    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1102        return false;
1103    }
1104
1105    /**
1106     * Create the more chip. The more chip is text that replaces any chips that
1107     * do not fit in the pre-defined available space when the
1108     * RecipientEditTextView loses focus.
1109     */
1110    private void createMoreChip() {
1111        RecipientChip[] recipients = getRecipients();
1112        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1113            mMoreChip = null;
1114            return;
1115        }
1116        int numRecipients = recipients.length;
1117        int overage = numRecipients - CHIP_LIMIT;
1118        Editable text = getText();
1119        // TODO: get the correct size from visual design.
1120        int width = (int) Math.floor(getWidth() * MORE_WIDTH_FACTOR);
1121        int height = getLineHeight();
1122        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1123        Canvas canvas = new Canvas(drawable);
1124        String moreText = getResources().getString(mMoreString, overage);
1125        canvas.drawText(moreText, 0, moreText.length(), 0, height - getLayout().getLineDescent(0),
1126                getPaint());
1127
1128        Drawable result = new BitmapDrawable(getResources(), drawable);
1129        result.setBounds(0, 0, width, height);
1130        ImageSpan moreSpan = new ImageSpan(result);
1131        Spannable spannable = getSpannable();
1132        // Remove the overage chips.
1133        if (recipients == null || recipients.length == 0) {
1134            Log.w(TAG,
1135                    "We have recipients. Tt should not be possible to have zero RecipientChips.");
1136            mMoreChip = null;
1137            return;
1138        }
1139        mRemovedSpans = new ArrayList<RecipientChip>();
1140        int totalReplaceStart = 0;
1141        int totalReplaceEnd = 0;
1142        for (int i = numRecipients - overage; i < recipients.length; i++) {
1143            mRemovedSpans.add(recipients[i]);
1144            if (i == numRecipients - overage) {
1145                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1146            }
1147            if (i == recipients.length - 1) {
1148                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1149            }
1150            if (mTemporaryRecipients != null && !mTemporaryRecipients.contains(recipients[i])) {
1151                recipients[i].storeChipStart(spannable.getSpanStart(recipients[i]));
1152                recipients[i].storeChipEnd(spannable.getSpanEnd(recipients[i]));
1153            }
1154            spannable.removeSpan(recipients[i]);
1155        }
1156        // TODO: why would these ever be backwards?
1157        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1158        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1159        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1160        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1161        text.replace(start, end, chipText);
1162        mMoreChip = moreSpan;
1163    }
1164
1165    /**
1166     * Replace the more chip, if it exists, with all of the recipient chips it had
1167     * replaced when the RecipientEditTextView gains focus.
1168     */
1169    private void removeMoreChip() {
1170        if (mMoreChip != null) {
1171            Spannable span = getSpannable();
1172            span.removeSpan(mMoreChip);
1173            mMoreChip = null;
1174            // Re-add the spans that were removed.
1175            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1176                // Recreate each removed span.
1177                Editable editable = getText();
1178                SpannableString associatedText;
1179                for (RecipientChip chip : mRemovedSpans) {
1180                    int chipStart = chip.getStoredChipStart();
1181                    int chipEnd;
1182                    String token;
1183                    if (chipStart == -1) {
1184                        // Need to find the location of the chip, again.
1185                        token = (String)mTokenizer.terminateToken(chip.getEntry().getDestination());
1186                        chipStart = editable.toString().indexOf(token);
1187                        chipEnd = chipStart + token.length();
1188                    } else {
1189                        chipEnd = Math.min(editable.length(), chip.getStoredChipEnd());
1190                    }
1191                    if (Log.isLoggable(TAG, Log.DEBUG) && chipEnd != chip.getStoredChipEnd()) {
1192                        Log.d(TAG,
1193                                "Unexpectedly, the chip ended after the end of the editable text. "
1194                                        + "Chip End " + chip.getStoredChipEnd()
1195                                        + "Editable length " + editable.length());
1196                    }
1197                    associatedText = new SpannableString(editable.subSequence(chipStart, chipEnd));
1198                    associatedText.setSpan(chip, 0, associatedText.length(),
1199                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1200                    editable.replace(chipStart, chipEnd, associatedText);
1201                }
1202                mRemovedSpans.clear();
1203            }
1204        }
1205    }
1206
1207    /**
1208     * Show specified chip as selected. If the RecipientChip is just an email address,
1209     * selecting the chip will take the contents of the chip and place it at
1210     * the end of the RecipientEditTextView for inline editing. If the
1211     * RecipientChip is a complete contact, then selecting the chip
1212     * will change the background color of the chip, show the delete icon,
1213     * and a popup window with the address in use highlighted and any other
1214     * alternate addresses for the contact.
1215     * @param currentChip Chip to select.
1216     * @return A RecipientChip in the selected state or null if the chip
1217     * just contained an email address.
1218     */
1219    public RecipientChip selectChip(RecipientChip currentChip) {
1220        if (currentChip.getContactId() != INVALID_CONTACT) {
1221            int start = getChipStart(currentChip);
1222            int end = getChipEnd(currentChip);
1223            getSpannable().removeSpan(currentChip);
1224            RecipientChip newChip;
1225            CharSequence displayText = mTokenizer.terminateToken(currentChip.getValue());
1226            // Always leave a blank space at the end of a chip.
1227            int textLength = displayText.length() - 1;
1228            SpannableString chipText = new SpannableString(displayText);
1229            try {
1230                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1231                chipText.setSpan(newChip, 0, textLength,
1232                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1233            } catch (NullPointerException e) {
1234                Log.e(TAG, e.getMessage(), e);
1235                return null;
1236            }
1237            Editable editable = getText();
1238            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1239            if (start == -1 || end == -1) {
1240                Log.d(TAG, "The chip being selected no longer exists but should.");
1241            } else {
1242                editable.replace(start, end, chipText);
1243            }
1244            newChip.setSelected(true);
1245            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1246            return newChip;
1247        } else {
1248            CharSequence text = currentChip.getValue();
1249            Editable editable = getText();
1250            removeChip(currentChip);
1251            editable.append(text);
1252            setCursorVisible(true);
1253            setSelection(editable.length());
1254            return null;
1255        }
1256    }
1257
1258
1259    /**
1260     * Remove selection from this chip. Unselecting a RecipientChip will render
1261     * the chip without a delete icon and with an unfocused background. This
1262     * is called when the RecipientChip no longer has focus.
1263     */
1264    public void unselectChip(RecipientChip chip) {
1265        int start = getChipStart(chip);
1266        int end = getChipEnd(chip);
1267        Editable editable = getText();
1268        mSelectedChip = null;
1269        if (start == -1 || end == -1) {
1270            Log.e(TAG, "The chip being unselected no longer exists but should.");
1271        } else {
1272            getSpannable().removeSpan(chip);
1273            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1274            editable.replace(start, end, createChip(chip.getEntry(), false));
1275        }
1276        setCursorVisible(true);
1277        setSelection(editable.length());
1278        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1279            mAlternatesPopup.dismiss();
1280        }
1281    }
1282
1283
1284    /**
1285     * Return whether this chip contains the position passed in.
1286     */
1287    public boolean matchesChip(RecipientChip chip, int offset) {
1288        int start = getChipStart(chip);
1289        int end = getChipEnd(chip);
1290        if (start == -1 || end == -1) {
1291            return false;
1292        }
1293        return (offset >= start && offset <= end);
1294    }
1295
1296
1297    /**
1298     * Return whether a touch event was inside the delete target of
1299     * a selected chip. It is in the delete target if:
1300     * 1) the x and y points of the event are within the
1301     * delete assset.
1302     * 2) the point tapped would have caused a cursor to appear
1303     * right after the selected chip.
1304     * @return boolean
1305     */
1306    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1307        // Figure out the bounds of this chip and whether or not
1308        // the user clicked in the X portion.
1309        return chip.isSelected() && offset == getChipEnd(chip);
1310    }
1311
1312    /**
1313     * Remove the chip and any text associated with it from the RecipientEditTextView.
1314     */
1315    private void removeChip(RecipientChip chip) {
1316        Spannable spannable = getSpannable();
1317        int spanStart = spannable.getSpanStart(chip);
1318        int spanEnd = spannable.getSpanEnd(chip);
1319        Editable text = getText();
1320        int toDelete = spanEnd;
1321        boolean wasSelected = chip == mSelectedChip;
1322        // Clear that there is a selected chip before updating any text.
1323        if (wasSelected) {
1324            mSelectedChip = null;
1325        }
1326        // Always remove trailing spaces when removing a chip.
1327        while (toDelete >= 0 && toDelete < text.length() - 1 && text.charAt(toDelete) == ' ') {
1328            toDelete++;
1329        }
1330        spannable.removeSpan(chip);
1331        text.delete(spanStart, toDelete);
1332        if (wasSelected) {
1333            clearSelectedChip();
1334        }
1335    }
1336
1337    /**
1338     * Replace this currently selected chip with a new chip
1339     * that uses the contact data provided.
1340     */
1341    public void replaceChip(RecipientChip chip, RecipientEntry entry) {
1342        boolean wasSelected = chip == mSelectedChip;
1343        if (wasSelected) {
1344            mSelectedChip = null;
1345        }
1346        int start = getChipStart(chip);
1347        int end = getChipEnd(chip);
1348        getSpannable().removeSpan(chip);
1349        Editable editable = getText();
1350        CharSequence chipText = createChip(entry, false);
1351        if (start == -1 || end == -1) {
1352            Log.e(TAG, "The chip to replace does not exist but should.");
1353            editable.insert(0, chipText);
1354        } else {
1355            editable.replace(start, end, chipText);
1356        }
1357        setCursorVisible(true);
1358        if (wasSelected) {
1359            clearSelectedChip();
1360        }
1361    }
1362
1363    /**
1364     * Handle click events for a chip. When a selected chip receives a click
1365     * event, see if that event was in the delete icon. If so, delete it.
1366     * Otherwise, unselect the chip.
1367     */
1368    public void onClick(RecipientChip chip, int offset, float x, float y) {
1369        if (chip.isSelected()) {
1370            if (isInDelete(chip, offset, x, y)) {
1371                removeChip(chip);
1372            } else {
1373                clearSelectedChip();
1374            }
1375        }
1376    }
1377
1378    private boolean chipsPending() {
1379        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1380    }
1381
1382    private class RecipientTextWatcher implements TextWatcher {
1383        @Override
1384        public void afterTextChanged(Editable s) {
1385            // Get whether there are any recipients pending addition to the view.
1386            // If there are, don't do anything in the text watcher.
1387            if (chipsPending()) {
1388                return;
1389            }
1390            if (mSelectedChip != null) {
1391                setCursorVisible(true);
1392                setSelection(getText().length());
1393                clearSelectedChip();
1394            }
1395            int length = s.length();
1396            // Make sure there is content there to parse and that it is
1397            // not just the commit character.
1398            if (length > 1) {
1399                char last;
1400                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
1401                int len = length() - 1;
1402                if (end != len) {
1403                    last = s.charAt(end);
1404                } else {
1405                    last = s.charAt(len);
1406                }
1407                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
1408                    commitByCharacter();
1409                } else if (last == COMMIT_CHAR_SPACE) {
1410                    // Check if this is a valid email address. If it is,
1411                    // commit it.
1412                    String text = getText().toString();
1413                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1414                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
1415                            tokenStart));
1416                    if (mValidator != null && mValidator.isValid(sub)) {
1417                        commitByCharacter();
1418                    }
1419                }
1420            }
1421        }
1422
1423        @Override
1424        public void onTextChanged(CharSequence s, int start, int before, int count) {
1425        }
1426
1427        @Override
1428        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1429        }
1430    }
1431
1432    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
1433        private RecipientChip createFreeChip(RecipientEntry entry) {
1434            String displayText = entry.getDestination();
1435            displayText = (String) mTokenizer.terminateToken(displayText);
1436            try {
1437                return constructChipSpan(entry, -1, false);
1438            } catch (NullPointerException e) {
1439                Log.e(TAG, e.getMessage(), e);
1440                return null;
1441            }
1442        }
1443
1444        @Override
1445        protected Void doInBackground(Void... params) {
1446            if (mIndividualReplacements != null) {
1447                mIndividualReplacements.cancel(true);
1448            }
1449            // For each chip in the list, look up the matching contact.
1450            // If there is a match, replace that chip with the matching
1451            // chip.
1452            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
1453            RecipientChip[] existingChips = getSpannable().getSpans(0, getText().length(),
1454                    RecipientChip.class);
1455            for (int i = 0; i < existingChips.length; i++) {
1456                originalRecipients.add(existingChips[i]);
1457            }
1458            if (mRemovedSpans != null) {
1459                originalRecipients.addAll(mRemovedSpans);
1460            }
1461            String[] addresses = new String[originalRecipients.size()];
1462            for (int i = 0; i < originalRecipients.size(); i++) {
1463                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1464            }
1465            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1466                    .getMatchingRecipients(getContext(), addresses);
1467            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
1468            for (final RecipientChip temp : originalRecipients) {
1469                RecipientEntry entry = null;
1470                if (temp.getEntry().getContactId() == INVALID_CONTACT
1471                        && getSpannable().getSpanStart(temp) != -1) {
1472                    // Replace this.
1473                    entry = createValidatedEntry(entries.get(temp.getEntry().getDestination()));
1474                }
1475                if (entry != null) {
1476                    replacements.add(createFreeChip(entry));
1477                } else {
1478                    replacements.add(temp);
1479                }
1480            }
1481            if (replacements != null && replacements.size() > 0) {
1482                mHandler.post(new Runnable() {
1483                    @Override
1484                    public void run() {
1485                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
1486                                .toString());
1487                        Editable oldText = getText();
1488                        SpannableString chipText;
1489                        int start, end;
1490                        int i = 0;
1491                        for (RecipientChip chip : originalRecipients) {
1492                            start = oldText.getSpanStart(chip);
1493                            if (start != -1) {
1494                            end = oldText.getSpanEnd(chip);
1495                            chipText = new SpannableString(text.subSequence(start, end));
1496                            chipText.setSpan(replacements.get(i), 0, end - start,
1497                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1498                            text.removeSpan(chip);
1499                            text.replace(start, end, chipText);
1500                            }
1501                            i++;
1502                        }
1503                        Editable editable = getText();
1504                        editable.clear();
1505                        editable.insert(0, text);
1506                        originalRecipients.clear();
1507                    }
1508                });
1509            }
1510            return null;
1511        }
1512    }
1513
1514    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
1515        @SuppressWarnings("unchecked")
1516        @Override
1517        protected Void doInBackground(Object... params) {
1518            // For each chip in the list, look up the matching contact.
1519            // If there is a match, replace that chip with the matching
1520            // chip.
1521            final ArrayList<RecipientChip> originalRecipients =
1522                (ArrayList<RecipientChip>) params[0];
1523            String[] addresses = new String[originalRecipients.size()];
1524            for (int i = 0; i < originalRecipients.size(); i++) {
1525                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1526            }
1527            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1528                    .getMatchingRecipients(getContext(), addresses);
1529            for (final RecipientChip temp : originalRecipients) {
1530                if (temp.getEntry().getContactId() == INVALID_CONTACT
1531                        && getSpannable().getSpanStart(temp) != -1) {
1532                    // Replace this.
1533                    final RecipientEntry entry = createValidatedEntry(entries.get(temp.getEntry()
1534                            .getDestination()));
1535                    if (entry != null) {
1536                        mHandler.post(new Runnable() {
1537                            @Override
1538                            public void run() {
1539                                replaceChip(temp, entry);
1540                            }
1541                        });
1542                    }
1543                }
1544            }
1545            return null;
1546        }
1547    }
1548}
1549