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