RecipientEditTextView.java revision c6e6141037bf299cabf4a1ba6b3664f5bc426bd0
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        // TODO: when b/4559727 is fixed, the bottom padding should be applied to each line.
439        return -((actualLine * (int)mChipHeight) + getPaddingBottom() + getPaddingTop());
440    }
441
442    /**
443     * Get the max amount of space a chip can take up. The formula takes into
444     * account the width of the EditTextView, any view padding, and padding
445     * that will be added to the chip.
446     */
447    private float calculateAvailableWidth(boolean pressed) {
448        return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
449    }
450
451    /**
452     * Set all chip dimensions and resources. This has to be done from the
453     * application as this is a static library.
454     * @param chipBackground
455     * @param chipBackgroundPressed
456     * @param invalidChip
457     * @param chipDelete
458     * @param defaultContact
459     * @param moreResource
460     * @param alternatesLayout
461     * @param chipHeight
462     * @param padding Padding around the text in a chip
463     */
464    public void setChipDimensions(Drawable chipBackground, Drawable chipBackgroundPressed,
465            Drawable invalidChip, Drawable chipDelete, Bitmap defaultContact, int moreResource,
466            int alternatesLayout, float chipHeight, float padding,
467            float chipFontSize) {
468        mChipBackground = chipBackground;
469        mChipBackgroundPressed = chipBackgroundPressed;
470        mChipDelete = chipDelete;
471        mChipPadding = (int) padding;
472        mAlternatesLayout = alternatesLayout;
473        mDefaultContactPhoto = defaultContact;
474        mMoreString = moreResource;
475        mChipHeight = chipHeight;
476        mChipFontSize = chipFontSize;
477        mInvalidChipBackground = invalidChip;
478    }
479
480    @Override
481    public void onSizeChanged(int width, int height, int oldw, int oldh) {
482        super.onSizeChanged(width, height, oldw, oldh);
483        // Check for any pending tokens created before layout had been completed
484        // on the view.
485        if (width != 0 && height != 0) {
486            if (mPendingChipsCount > 0) {
487                handlePendingChips();
488            }
489            mPendingChipsCount = 0;
490            mPendingChips.clear();
491            mHandler.post(mAddTextWatcher);
492        }
493        // Try to find the scroll view parent, if it exists.
494        if (mScrollView == null && !mTried) {
495            ViewParent parent = getParent();
496            while (parent != null && !(parent instanceof ScrollView)) {
497                parent = parent.getParent();
498            }
499            if (parent != null) {
500                mScrollView = (ScrollView) parent;
501            }
502            mTried = true;
503        }
504    }
505
506    private void handlePendingChips() {
507        mTemporaryRecipients = new ArrayList<RecipientChip>(mPendingChipsCount);
508        Editable editable = getText();
509        // Tokenize!
510        for (int i = 0; i < mPendingChips.size(); i++) {
511            String current = mPendingChips.get(i);
512            int tokenStart = editable.toString().indexOf(current);
513            int tokenEnd = tokenStart + current.length();
514            if (tokenStart >= 0) {
515                // When we have a valid token, include it with the token
516                // to the left.
517                if (tokenEnd < editable.length() - 2
518                        && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
519                    tokenEnd++;
520                }
521                createReplacementChip(tokenStart, tokenEnd, editable);
522            }
523            mPendingChipsCount--;
524        }
525        sanitizeSpannable();
526        if (mTemporaryRecipients != null
527                && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
528            if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
529                new RecipientReplacementTask().execute();
530                mTemporaryRecipients = null;
531            } else {
532                // Create the "more" chip
533                mIndividualReplacements = new IndividualReplacementTask();
534                mIndividualReplacements.execute(new ArrayList<RecipientChip>(mTemporaryRecipients
535                        .subList(0, CHIP_LIMIT)));
536
537                createMoreChip();
538            }
539        } else {
540            // There are too many recipients to look up, so just fall back to
541            // showing addresses 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                    } else {
882                        onClick(mSelectedChip, offset, x, y);
883                    }
884                }
885                chipWasSelected = true;
886                handled = true;
887            }
888        }
889        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
890            clearSelectedChip();
891        }
892        return handled;
893    }
894
895    private void scrollLineIntoView(int line) {
896        if (mScrollView != null) {
897            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
898        }
899    }
900
901    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
902            int width, Context context) {
903        int line = getLayout().getLineForOffset(getChipStart(currentChip));
904        int bottom = calculateOffsetFromBottom(line);
905        // Align the alternates popup with the left side of the View,
906        // regardless of the position of the chip tapped.
907        alternatesPopup.setWidth(width);
908        alternatesPopup.setAnchorView(this);
909        alternatesPopup.setVerticalOffset(bottom);
910        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
911        alternatesPopup.setOnItemClickListener(mAlternatesListener);
912        alternatesPopup.show();
913        ListView listView = alternatesPopup.getListView();
914        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
915        // Checked item would be -1 if the adapter has not
916        // loaded the view that should be checked yet. The
917        // variable will be set correctly when onCheckedItemChanged
918        // is called in a separate thread.
919        if (mCheckedItem != -1) {
920            listView.setItemChecked(mCheckedItem, true);
921            mCheckedItem = -1;
922        }
923    }
924
925    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
926        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
927                mAlternatesLayout, this);
928    }
929
930    public void onCheckedItemChanged(int position) {
931        ListView listView = mAlternatesPopup.getListView();
932        if (listView != null && listView.getCheckedItemCount() == 0) {
933            listView.setItemChecked(position, true);
934        } else {
935            mCheckedItem = position;
936        }
937    }
938
939    // TODO: This algorithm will need a lot of tweaking after more people have used
940    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
941    // what comes before the finger.
942    private int putOffsetInRange(int o) {
943        int offset = o;
944        Editable text = getText();
945        int length = text.length();
946        // Remove whitespace from end to find "real end"
947        int realLength = length;
948        for (int i = length - 1; i >= 0; i--) {
949            if (text.charAt(i) == ' ') {
950                realLength--;
951            } else {
952                break;
953            }
954        }
955
956        // If the offset is beyond or at the end of the text,
957        // leave it alone.
958        if (offset >= realLength) {
959            return offset;
960        }
961        Editable editable = getText();
962        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
963            // Keep walking backward!
964            offset--;
965        }
966        return offset;
967    }
968
969    private int findText(Editable text, int offset) {
970        if (text.charAt(offset) != ' ') {
971            return offset;
972        }
973        return -1;
974    }
975
976    private RecipientChip findChip(int offset) {
977        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
978        // Find the chip that contains this offset.
979        for (int i = 0; i < chips.length; i++) {
980            RecipientChip chip = chips[i];
981            int start = getChipStart(chip);
982            int end = getChipEnd(chip);
983            if (offset >= start && offset <= end) {
984                return chip;
985            }
986        }
987        return null;
988    }
989
990    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
991        String displayText = entry.getDestination();
992        displayText = (String) mTokenizer.terminateToken(displayText);
993        // Always leave a blank space at the end of a chip.
994        int textLength = displayText.length() - 1;
995        SpannableString chipText = new SpannableString(displayText);
996        int end = getSelectionEnd();
997        int start = mTokenizer.findTokenStart(getText(), end);
998        try {
999            chipText.setSpan(constructChipSpan(entry, start, pressed), 0, textLength,
1000                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1001        } catch (NullPointerException e) {
1002            Log.e(TAG, e.getMessage(), e);
1003            return null;
1004        }
1005
1006        return chipText;
1007    }
1008
1009    /**
1010     * When an item in the suggestions list has been clicked, create a chip from the
1011     * contact information of the selected item.
1012     */
1013    @Override
1014    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1015        submitItemAtPosition(position);
1016    }
1017
1018    private void submitItemAtPosition(int position) {
1019        RecipientEntry entry = createValidatedEntry(
1020                (RecipientEntry)getAdapter().getItem(position));
1021        clearComposingText();
1022
1023        int end = getSelectionEnd();
1024        int start = mTokenizer.findTokenStart(getText(), end);
1025
1026        Editable editable = getText();
1027        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1028        editable.replace(start, end, createChip(entry, false));
1029    }
1030
1031    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1032        if (item == null) {
1033            return null;
1034        }
1035        final RecipientEntry entry;
1036        // If the display name and the address are the same, or if this is a
1037        // valid contact, but the destination is invalid, then make this a fake
1038        // recipient that is editable.
1039        String destination = item.getDestination();
1040        if (TextUtils.equals(item.getDisplayName(), destination)
1041                || (mValidator != null && !mValidator.isValid(destination))) {
1042            entry = RecipientEntry.constructFakeEntry(destination);
1043        } else {
1044            entry = item;
1045        }
1046        return entry;
1047    }
1048
1049    /** Returns a collection of contact Id for each chip inside this View. */
1050    /* package */ Collection<Long> getContactIds() {
1051        final Set<Long> result = new HashSet<Long>();
1052        RecipientChip[] chips = getRecipients();
1053        if (chips != null) {
1054            for (RecipientChip chip : chips) {
1055                result.add(chip.getContactId());
1056            }
1057        }
1058        return result;
1059    }
1060
1061    private RecipientChip[] getRecipients() {
1062        return getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1063    }
1064
1065    /** Returns a collection of data Id for each chip inside this View. May be null. */
1066    /* package */ Collection<Long> getDataIds() {
1067        final Set<Long> result = new HashSet<Long>();
1068        RecipientChip [] chips = getRecipients();
1069        if (chips != null) {
1070            for (RecipientChip chip : chips) {
1071                result.add(chip.getDataId());
1072            }
1073        }
1074        return result;
1075    }
1076
1077
1078    @Override
1079    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1080        return false;
1081    }
1082
1083    @Override
1084    public void onDestroyActionMode(ActionMode mode) {
1085    }
1086
1087    @Override
1088    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1089        return false;
1090    }
1091
1092    /**
1093     * No chips are selectable.
1094     */
1095    @Override
1096    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1097        return false;
1098    }
1099
1100    /**
1101     * Create the more chip. The more chip is text that replaces any chips that
1102     * do not fit in the pre-defined available space when the
1103     * RecipientEditTextView loses focus.
1104     */
1105    private void createMoreChip() {
1106        RecipientChip[] recipients = getRecipients();
1107        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1108            mMoreChip = null;
1109            return;
1110        }
1111        int numRecipients = recipients.length;
1112        int overage = numRecipients - CHIP_LIMIT;
1113        Editable text = getText();
1114        // TODO: get the correct size from visual design.
1115        int width = (int) Math.floor(getWidth() * MORE_WIDTH_FACTOR);
1116        int height = getLineHeight();
1117        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1118        Canvas canvas = new Canvas(drawable);
1119        String moreText = getResources().getString(mMoreString, overage);
1120        canvas.drawText(moreText, 0, moreText.length(), 0, height - getLayout().getLineDescent(0),
1121                getPaint());
1122
1123        Drawable result = new BitmapDrawable(getResources(), drawable);
1124        result.setBounds(0, 0, width, height);
1125        ImageSpan moreSpan = new ImageSpan(result);
1126        Spannable spannable = getSpannable();
1127        // Remove the overage chips.
1128        if (recipients == null || recipients.length == 0) {
1129            Log.w(TAG,
1130                    "We have recipients. Tt should not be possible to have zero RecipientChips.");
1131            mMoreChip = null;
1132            return;
1133        }
1134        mRemovedSpans = new ArrayList<RecipientChip>();
1135        int totalReplaceStart = 0;
1136        int totalReplaceEnd = 0;
1137        for (int i = numRecipients - overage; i < recipients.length; i++) {
1138            mRemovedSpans.add(recipients[i]);
1139            if (i == numRecipients - overage) {
1140                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1141            }
1142            if (i == recipients.length - 1) {
1143                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1144            }
1145            if (mTemporaryRecipients != null && !mTemporaryRecipients.contains(recipients[i])) {
1146                recipients[i].storeChipStart(spannable.getSpanStart(recipients[i]));
1147                recipients[i].storeChipEnd(spannable.getSpanEnd(recipients[i]));
1148            }
1149            spannable.removeSpan(recipients[i]);
1150        }
1151        // TODO: why would these ever be backwards?
1152        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1153        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1154        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1155        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1156        text.replace(start, end, chipText);
1157        mMoreChip = moreSpan;
1158    }
1159
1160    /**
1161     * Replace the more chip, if it exists, with all of the recipient chips it had
1162     * replaced when the RecipientEditTextView gains focus.
1163     */
1164    private void removeMoreChip() {
1165        if (mMoreChip != null) {
1166            Spannable span = getSpannable();
1167            span.removeSpan(mMoreChip);
1168            mMoreChip = null;
1169            // Re-add the spans that were removed.
1170            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1171                // Recreate each removed span.
1172                Editable editable = getText();
1173                SpannableString associatedText;
1174                for (RecipientChip chip : mRemovedSpans) {
1175                    int chipStart = chip.getStoredChipStart();
1176                    int chipEnd;
1177                    String token;
1178                    if (chipStart == -1) {
1179                        // Need to find the location of the chip, again.
1180                        token = (String)mTokenizer.terminateToken(chip.getEntry().getDestination());
1181                        chipStart = editable.toString().indexOf(token);
1182                        chipEnd = chipStart + token.length();
1183                    } else {
1184                        chipEnd = Math.min(editable.length(), chip.getStoredChipEnd());
1185                    }
1186                    if (Log.isLoggable(TAG, Log.DEBUG) && chipEnd != chip.getStoredChipEnd()) {
1187                        Log.d(TAG,
1188                                "Unexpectedly, the chip ended after the end of the editable text. "
1189                                        + "Chip End " + chip.getStoredChipEnd()
1190                                        + "Editable length " + editable.length());
1191                    }
1192                    associatedText = new SpannableString(editable.subSequence(chipStart, chipEnd));
1193                    associatedText.setSpan(chip, 0, associatedText.length(),
1194                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1195                    editable.replace(chipStart, chipEnd, associatedText);
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            CharSequence displayText = mTokenizer.terminateToken(currentChip.getValue());
1221            // Always leave a blank space at the end of a chip.
1222            int textLength = displayText.length() - 1;
1223            SpannableString chipText = new SpannableString(displayText);
1224            try {
1225                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1226                chipText.setSpan(newChip, 0, textLength,
1227                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1228            } catch (NullPointerException e) {
1229                Log.e(TAG, e.getMessage(), e);
1230                return null;
1231            }
1232            Editable editable = getText();
1233            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1234            if (start == -1 || end == -1) {
1235                Log.d(TAG, "The chip being selected no longer exists but should.");
1236            } else {
1237                editable.replace(start, end, chipText);
1238            }
1239            newChip.setSelected(true);
1240            if (newChip.getEntry().getContactId() == INVALID_CONTACT) {
1241                scrollLineIntoView(getLayout().getLineForOffset(
1242                        getChipStart(newChip)));
1243            }
1244            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1245            return newChip;
1246        } else {
1247            CharSequence text = currentChip.getValue();
1248            Editable editable = getText();
1249            removeChip(currentChip);
1250            editable.append(text);
1251            setCursorVisible(true);
1252            setSelection(editable.length());
1253            return null;
1254        }
1255    }
1256
1257
1258    /**
1259     * Remove selection from this chip. Unselecting a RecipientChip will render
1260     * the chip without a delete icon and with an unfocused background. This
1261     * is called when the RecipientChip no longer has focus.
1262     */
1263    public void unselectChip(RecipientChip chip) {
1264        int start = getChipStart(chip);
1265        int end = getChipEnd(chip);
1266        Editable editable = getText();
1267        mSelectedChip = null;
1268        if (start == -1 || end == -1) {
1269            Log.e(TAG, "The chip being unselected no longer exists but should.");
1270        } else {
1271            getSpannable().removeSpan(chip);
1272            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1273            editable.replace(start, end, createChip(chip.getEntry(), false));
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() - 1 && 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            editable.replace(start, end, chipText);
1355        }
1356        setCursorVisible(true);
1357        if (wasSelected) {
1358            clearSelectedChip();
1359        }
1360    }
1361
1362    /**
1363     * Handle click events for a chip. When a selected chip receives a click
1364     * event, see if that event was in the delete icon. If so, delete it.
1365     * Otherwise, unselect the chip.
1366     */
1367    public void onClick(RecipientChip chip, int offset, float x, float y) {
1368        if (chip.isSelected()) {
1369            if (isInDelete(chip, offset, x, y)) {
1370                removeChip(chip);
1371            } else {
1372                clearSelectedChip();
1373            }
1374        }
1375    }
1376
1377    private boolean chipsPending() {
1378        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1379    }
1380
1381    private class RecipientTextWatcher implements TextWatcher {
1382        @Override
1383        public void afterTextChanged(Editable s) {
1384            // Get whether there are any recipients pending addition to the view.
1385            // If there are, don't do anything in the text watcher.
1386            if (chipsPending()) {
1387                return;
1388            }
1389            if (mSelectedChip != null) {
1390                setCursorVisible(true);
1391                setSelection(getText().length());
1392                clearSelectedChip();
1393            }
1394            int length = s.length();
1395            // Make sure there is content there to parse and that it is
1396            // not just the commit character.
1397            if (length > 1) {
1398                char last;
1399                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
1400                int len = length() - 1;
1401                if (end != len) {
1402                    last = s.charAt(end);
1403                } else {
1404                    last = s.charAt(len);
1405                }
1406                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
1407                    commitByCharacter();
1408                } else if (last == COMMIT_CHAR_SPACE) {
1409                    // Check if this is a valid email address. If it is,
1410                    // commit it.
1411                    String text = getText().toString();
1412                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1413                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
1414                            tokenStart));
1415                    if (mValidator != null && mValidator.isValid(sub)) {
1416                        commitByCharacter();
1417                    }
1418                }
1419            }
1420        }
1421
1422        @Override
1423        public void onTextChanged(CharSequence s, int start, int before, int count) {
1424        }
1425
1426        @Override
1427        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1428        }
1429    }
1430
1431    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
1432        private RecipientChip createFreeChip(RecipientEntry entry) {
1433            String displayText = entry.getDestination();
1434            displayText = (String) mTokenizer.terminateToken(displayText);
1435            try {
1436                return constructChipSpan(entry, -1, false);
1437            } catch (NullPointerException e) {
1438                Log.e(TAG, e.getMessage(), e);
1439                return null;
1440            }
1441        }
1442
1443        @Override
1444        protected Void doInBackground(Void... params) {
1445            if (mIndividualReplacements != null) {
1446                mIndividualReplacements.cancel(true);
1447            }
1448            // For each chip in the list, look up the matching contact.
1449            // If there is a match, replace that chip with the matching
1450            // chip.
1451            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
1452            RecipientChip[] existingChips = getSpannable().getSpans(0, getText().length(),
1453                    RecipientChip.class);
1454            for (int i = 0; i < existingChips.length; i++) {
1455                originalRecipients.add(existingChips[i]);
1456            }
1457            if (mRemovedSpans != null) {
1458                originalRecipients.addAll(mRemovedSpans);
1459            }
1460            String[] addresses = new String[originalRecipients.size()];
1461            for (int i = 0; i < originalRecipients.size(); i++) {
1462                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1463            }
1464            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1465                    .getMatchingRecipients(getContext(), addresses);
1466            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
1467            for (final RecipientChip temp : originalRecipients) {
1468                RecipientEntry entry = null;
1469                if (temp.getEntry().getContactId() == INVALID_CONTACT
1470                        && getSpannable().getSpanStart(temp) != -1) {
1471                    // Replace this.
1472                    entry = createValidatedEntry(entries.get(temp.getEntry().getDestination()));
1473                }
1474                if (entry != null) {
1475                    replacements.add(createFreeChip(entry));
1476                } else {
1477                    replacements.add(temp);
1478                }
1479            }
1480            if (replacements != null && replacements.size() > 0) {
1481                mHandler.post(new Runnable() {
1482                    @Override
1483                    public void run() {
1484                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
1485                                .toString());
1486                        Editable oldText = getText();
1487                        SpannableString chipText;
1488                        int start, end;
1489                        int i = 0;
1490                        for (RecipientChip chip : originalRecipients) {
1491                            start = oldText.getSpanStart(chip);
1492                            if (start != -1) {
1493                            end = oldText.getSpanEnd(chip);
1494                            chipText = new SpannableString(text.subSequence(start, end));
1495                            chipText.setSpan(replacements.get(i), 0, end - start,
1496                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1497                            text.removeSpan(chip);
1498                            text.replace(start, end, chipText);
1499                            }
1500                            i++;
1501                        }
1502                        Editable editable = getText();
1503                        editable.clear();
1504                        editable.insert(0, text);
1505                        originalRecipients.clear();
1506                    }
1507                });
1508            }
1509            return null;
1510        }
1511    }
1512
1513    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
1514        @SuppressWarnings("unchecked")
1515        @Override
1516        protected Void doInBackground(Object... params) {
1517            // For each chip in the list, look up the matching contact.
1518            // If there is a match, replace that chip with the matching
1519            // chip.
1520            final ArrayList<RecipientChip> originalRecipients =
1521                (ArrayList<RecipientChip>) params[0];
1522            String[] addresses = new String[originalRecipients.size()];
1523            for (int i = 0; i < originalRecipients.size(); i++) {
1524                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1525            }
1526            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1527                    .getMatchingRecipients(getContext(), addresses);
1528            for (final RecipientChip temp : originalRecipients) {
1529                if (temp.getEntry().getContactId() == INVALID_CONTACT
1530                        && getSpannable().getSpanStart(temp) != -1) {
1531                    // Replace this.
1532                    final RecipientEntry entry = createValidatedEntry(entries.get(temp.getEntry()
1533                            .getDestination()));
1534                    if (entry != null) {
1535                        mHandler.post(new Runnable() {
1536                            @Override
1537                            public void run() {
1538                                replaceChip(temp, entry);
1539                            }
1540                        });
1541                    }
1542                }
1543            }
1544            return null;
1545        }
1546    }
1547}
1548