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