RecipientEditTextView.java revision 454eaf31f312fd2f2e6bc3d30bb050d65079a9a0
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            // If we can get a name from tokenizing, then generate an entry from
678            // this.
679            display = tokens[0].getName();
680            if (!TextUtils.isEmpty(display)) {
681                return RecipientEntry.constructGeneratedEntry(display, token);
682            }
683        }
684        // Unable to validate the token or to create a valid token from it.
685        // Just create a chip the user can edit.
686        if (mValidator != null && !mValidator.isValid(token)) {
687            // Try fixing up the entry using the validator.
688            token = mValidator.fixText(token).toString();
689            if (!TextUtils.isEmpty(token)) {
690                // protect against the case of a validator with a null domain,
691                // which doesn't add a domain to the token
692                Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(token);
693                if (tokenized.length > 0) {
694                    token = tokenized[0].getAddress();
695                }
696            }
697        }
698        // Otherwise, fallback to just creating an editable email address chip.
699        return RecipientEntry.constructFakeEntry(token);
700    }
701
702    private boolean isValid(String text) {
703        return mValidator == null ? true : mValidator.isValid(text);
704    }
705
706    private String tokenizeAddress(String destination) {
707        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
708        if (tokens != null && tokens.length > 0) {
709            return tokens[0].getAddress();
710        }
711        return destination;
712    }
713
714    @Override
715    public void setTokenizer(Tokenizer tokenizer) {
716        mTokenizer = tokenizer;
717        super.setTokenizer(mTokenizer);
718    }
719
720    @Override
721    public void setValidator(Validator validator) {
722        mValidator = validator;
723        super.setValidator(validator);
724    }
725
726    /**
727     * We cannot use the default mechanism for replaceText. Instead,
728     * we override onItemClickListener so we can get all the associated
729     * contact information including display text, address, and id.
730     */
731    @Override
732    protected void replaceText(CharSequence text) {
733        return;
734    }
735
736    /**
737     * Dismiss any selected chips when the back key is pressed.
738     */
739    @Override
740    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
741        if (keyCode == KeyEvent.KEYCODE_BACK) {
742            clearSelectedChip();
743        }
744        return super.onKeyPreIme(keyCode, event);
745    }
746
747    /**
748     * Monitor key presses in this view to see if the user types
749     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
750     * If the user has entered text that has contact matches and types
751     * a commit key, create a chip from the topmost matching contact.
752     * If the user has entered text that has no contact matches and types
753     * a commit key, then create a chip from the text they have entered.
754     */
755    @Override
756    public boolean onKeyUp(int keyCode, KeyEvent event) {
757        switch (keyCode) {
758            case KeyEvent.KEYCODE_ENTER:
759            case KeyEvent.KEYCODE_DPAD_CENTER:
760                if (event.hasNoModifiers()) {
761                    if (commitDefault()) {
762                        return true;
763                    }
764                    if (mSelectedChip != null) {
765                        clearSelectedChip();
766                        return true;
767                    } else if (focusNext()) {
768                        return true;
769                    }
770                }
771                break;
772            case KeyEvent.KEYCODE_TAB:
773                if (event.hasNoModifiers()) {
774                    if (mSelectedChip != null) {
775                        clearSelectedChip();
776                    } else {
777                        commitDefault();
778                    }
779                    if (focusNext()) {
780                        return true;
781                    }
782                }
783        }
784        return super.onKeyUp(keyCode, event);
785    }
786
787    private boolean focusNext() {
788        View next = focusSearch(View.FOCUS_DOWN);
789        if (next != null) {
790            next.requestFocus();
791            return true;
792        }
793        return false;
794    }
795
796    /**
797     * Create a chip from the default selection. If the popup is showing, the
798     * default is the first item in the popup suggestions list. Otherwise, it is
799     * whatever the user had typed in. End represents where the the tokenizer
800     * should search for a token to turn into a chip.
801     * @return If a chip was created from a real contact.
802     */
803    private boolean commitDefault() {
804        Editable editable = getText();
805        int end = getSelectionEnd();
806        int start = mTokenizer.findTokenStart(editable, end);
807
808        if (shouldCreateChip(start, end)) {
809            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
810            // In the middle of chip; treat this as an edit
811            // and commit the whole token.
812            if (whatEnd != getSelectionEnd()) {
813                handleEdit(start, whatEnd);
814                return true;
815            }
816            return commitChip(start, end , editable);
817        }
818        return false;
819    }
820
821    private void commitByCharacter() {
822        Editable editable = getText();
823        int end = getSelectionEnd();
824        int start = mTokenizer.findTokenStart(editable, end);
825        if (shouldCreateChip(start, end)) {
826            commitChip(start, end, editable);
827        }
828        setSelection(getText().length());
829    }
830
831    private boolean commitChip(int start, int end, Editable editable) {
832        if (getAdapter().getCount() > 0 && enoughToFilter()) {
833            // choose the first entry.
834            submitItemAtPosition(0);
835            dismissDropDown();
836            return true;
837        } else {
838            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
839            String text = editable.toString().substring(start, tokenEnd).trim();
840            clearComposingText();
841            if (text != null && text.length() > 0 && !text.equals(" ")) {
842                RecipientEntry entry = createTokenizedEntry(text);
843                if (entry != null) {
844                    QwertyKeyListener.markAsReplaced(editable, start, end, "");
845                    CharSequence chipText = createChip(entry, false);
846                    editable.replace(start, end, chipText);
847                }
848                dismissDropDown();
849                return true;
850            }
851        }
852        return false;
853    }
854
855    private boolean shouldCreateChip(int start, int end) {
856        return hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
857    }
858
859    private boolean alreadyHasChip(int start, int end) {
860        RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
861        if ((chips == null || chips.length == 0)) {
862            return false;
863        }
864        return true;
865    }
866
867    private void handleEdit(int start, int end) {
868        // This is in the middle of a chip, so select out the whole chip
869        // and commit it.
870        Editable editable = getText();
871        setSelection(end);
872        String text = getText().toString().substring(start, end);
873        RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
874        QwertyKeyListener.markAsReplaced(editable, start, end, "");
875        CharSequence chipText = createChip(entry, false);
876        editable.replace(start, getSelectionEnd(), chipText);
877        dismissDropDown();
878    }
879
880    /**
881     * If there is a selected chip, delegate the key events
882     * to the selected chip.
883     */
884    @Override
885    public boolean onKeyDown(int keyCode, KeyEvent event) {
886        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
887            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
888                mAlternatesPopup.dismiss();
889            }
890            removeChip(mSelectedChip);
891        }
892
893        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
894            return true;
895        }
896
897        return super.onKeyDown(keyCode, event);
898    }
899
900    private Spannable getSpannable() {
901        return getText();
902    }
903
904    private int getChipStart(RecipientChip chip) {
905        return getSpannable().getSpanStart(chip);
906    }
907
908    private int getChipEnd(RecipientChip chip) {
909        return getSpannable().getSpanEnd(chip);
910    }
911
912    /**
913     * Instead of filtering on the entire contents of the edit box,
914     * this subclass method filters on the range from
915     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
916     * if the length of that range meets or exceeds {@link #getThreshold}
917     * and makes sure that the range is not already a Chip.
918     */
919    @Override
920    protected void performFiltering(CharSequence text, int keyCode) {
921        if (enoughToFilter()) {
922            int end = getSelectionEnd();
923            int start = mTokenizer.findTokenStart(text, end);
924            // If this is a RecipientChip, don't filter
925            // on its contents.
926            Spannable span = getSpannable();
927            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
928            if (chips != null && chips.length > 0) {
929                return;
930            }
931        }
932        super.performFiltering(text, keyCode);
933    }
934
935    private void clearSelectedChip() {
936        if (mSelectedChip != null) {
937            unselectChip(mSelectedChip);
938            mSelectedChip = null;
939        }
940        setCursorVisible(true);
941    }
942
943    /**
944     * Monitor touch events in the RecipientEditTextView.
945     * If the view does not have focus, any tap on the view
946     * will just focus the view. If the view has focus, determine
947     * if the touch target is a recipient chip. If it is and the chip
948     * is not selected, select it and clear any other selected chips.
949     * If it isn't, then select that chip.
950     */
951    @Override
952    public boolean onTouchEvent(MotionEvent event) {
953        if (!isFocused()) {
954            // Ignore any chip taps until this view is focused.
955            return super.onTouchEvent(event);
956        }
957
958        boolean handled = super.onTouchEvent(event);
959        int action = event.getAction();
960        boolean chipWasSelected = false;
961
962        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
963            float x = event.getX();
964            float y = event.getY();
965            int offset = putOffsetInRange(getOffsetForPosition(x, y));
966            RecipientChip currentChip = findChip(offset);
967            if (currentChip != null) {
968                if (action == MotionEvent.ACTION_UP) {
969                    if (mSelectedChip != null && mSelectedChip != currentChip) {
970                        clearSelectedChip();
971                        mSelectedChip = selectChip(currentChip);
972                    } else if (mSelectedChip == null) {
973                        // Selection may have moved due to the tap event,
974                        // but make sure we correctly reset selection to the
975                        // end so that any unfinished chips are committed.
976                        setSelection(getText().length());
977                        commitDefault();
978                        mSelectedChip = selectChip(currentChip);
979                    } else {
980                        onClick(mSelectedChip, offset, x, y);
981                    }
982                }
983                chipWasSelected = true;
984                handled = true;
985            }
986        }
987        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
988            clearSelectedChip();
989        }
990        return handled;
991    }
992
993    private void scrollLineIntoView(int line) {
994        if (mScrollView != null) {
995            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
996        }
997    }
998
999    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
1000            int width, Context context) {
1001        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1002        int bottom = calculateOffsetFromBottom(line);
1003        // Align the alternates popup with the left side of the View,
1004        // regardless of the position of the chip tapped.
1005        alternatesPopup.setWidth(width);
1006        alternatesPopup.setAnchorView(this);
1007        alternatesPopup.setVerticalOffset(bottom);
1008        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
1009        alternatesPopup.setOnItemClickListener(mAlternatesListener);
1010        alternatesPopup.show();
1011        ListView listView = alternatesPopup.getListView();
1012        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1013        // Checked item would be -1 if the adapter has not
1014        // loaded the view that should be checked yet. The
1015        // variable will be set correctly when onCheckedItemChanged
1016        // is called in a separate thread.
1017        if (mCheckedItem != -1) {
1018            listView.setItemChecked(mCheckedItem, true);
1019            mCheckedItem = -1;
1020        }
1021    }
1022
1023    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
1024        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
1025                mAlternatesLayout, this);
1026    }
1027
1028    private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
1029        return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
1030                .getEntry());
1031    }
1032
1033    @Override
1034    public void onCheckedItemChanged(int position) {
1035        ListView listView = mAlternatesPopup.getListView();
1036        if (listView != null && listView.getCheckedItemCount() == 0) {
1037            listView.setItemChecked(position, true);
1038        } else {
1039            mCheckedItem = position;
1040        }
1041    }
1042
1043    // TODO: This algorithm will need a lot of tweaking after more people have used
1044    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1045    // what comes before the finger.
1046    private int putOffsetInRange(int o) {
1047        int offset = o;
1048        Editable text = getText();
1049        int length = text.length();
1050        // Remove whitespace from end to find "real end"
1051        int realLength = length;
1052        for (int i = length - 1; i >= 0; i--) {
1053            if (text.charAt(i) == ' ') {
1054                realLength--;
1055            } else {
1056                break;
1057            }
1058        }
1059
1060        // If the offset is beyond or at the end of the text,
1061        // leave it alone.
1062        if (offset >= realLength) {
1063            return offset;
1064        }
1065        Editable editable = getText();
1066        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1067            // Keep walking backward!
1068            offset--;
1069        }
1070        return offset;
1071    }
1072
1073    private int findText(Editable text, int offset) {
1074        if (text.charAt(offset) != ' ') {
1075            return offset;
1076        }
1077        return -1;
1078    }
1079
1080    private RecipientChip findChip(int offset) {
1081        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1082        // Find the chip that contains this offset.
1083        for (int i = 0; i < chips.length; i++) {
1084            RecipientChip chip = chips[i];
1085            int start = getChipStart(chip);
1086            int end = getChipEnd(chip);
1087            if (offset >= start && offset <= end) {
1088                return chip;
1089            }
1090        }
1091        return null;
1092    }
1093
1094    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1095        String displayText = entry.getDestination();
1096        displayText = (String) mTokenizer.terminateToken(displayText);
1097        // Always leave a blank space at the end of a chip.
1098        int textLength = displayText.length()-1;
1099        SpannableString chipText = new SpannableString(displayText);
1100        int end = getSelectionEnd();
1101        int start = mTokenizer.findTokenStart(getText(), end);
1102        try {
1103            chipText.setSpan(constructChipSpan(entry, start, pressed), 0, textLength,
1104                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1105        } catch (NullPointerException e) {
1106            Log.e(TAG, e.getMessage(), e);
1107            return null;
1108        }
1109
1110        return chipText;
1111    }
1112
1113    /**
1114     * When an item in the suggestions list has been clicked, create a chip from the
1115     * contact information of the selected item.
1116     */
1117    @Override
1118    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1119        submitItemAtPosition(position);
1120    }
1121
1122    private void submitItemAtPosition(int position) {
1123        RecipientEntry entry = createValidatedEntry(
1124                (RecipientEntry)getAdapter().getItem(position));
1125        if (entry == null) {
1126            return;
1127        }
1128        clearComposingText();
1129
1130        int end = getSelectionEnd();
1131        int start = mTokenizer.findTokenStart(getText(), end);
1132
1133        Editable editable = getText();
1134        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1135        CharSequence chip = createChip(entry, false);
1136        if (chip != null) {
1137            editable.replace(start, end, chip);
1138        }
1139    }
1140
1141    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1142        if (item == null) {
1143            return null;
1144        }
1145        final RecipientEntry entry;
1146        // If the display name and the address are the same, or if this is a
1147        // valid contact, but the destination is invalid, then make this a fake
1148        // recipient that is editable.
1149        String destination = item.getDestination();
1150        if (TextUtils.isEmpty(item.getDisplayName())
1151                || TextUtils.equals(item.getDisplayName(), destination)
1152                || (mValidator != null && !mValidator.isValid(destination))) {
1153            entry = RecipientEntry.constructFakeEntry(destination);
1154        } else {
1155            entry = item;
1156        }
1157        return entry;
1158    }
1159
1160    /** Returns a collection of contact Id for each chip inside this View. */
1161    /* package */ Collection<Long> getContactIds() {
1162        final Set<Long> result = new HashSet<Long>();
1163        RecipientChip[] chips = getRecipients();
1164        if (chips != null) {
1165            for (RecipientChip chip : chips) {
1166                result.add(chip.getContactId());
1167            }
1168        }
1169        return result;
1170    }
1171
1172    private RecipientChip[] getRecipients() {
1173        return getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1174    }
1175
1176    /** Returns a collection of data Id for each chip inside this View. May be null. */
1177    /* package */ Collection<Long> getDataIds() {
1178        final Set<Long> result = new HashSet<Long>();
1179        RecipientChip [] chips = getRecipients();
1180        if (chips != null) {
1181            for (RecipientChip chip : chips) {
1182                result.add(chip.getDataId());
1183            }
1184        }
1185        return result;
1186    }
1187
1188
1189    @Override
1190    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1191        return false;
1192    }
1193
1194    @Override
1195    public void onDestroyActionMode(ActionMode mode) {
1196    }
1197
1198    @Override
1199    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1200        return false;
1201    }
1202
1203    /**
1204     * No chips are selectable.
1205     */
1206    @Override
1207    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1208        return false;
1209    }
1210
1211    /**
1212     * Create the more chip. The more chip is text that replaces any chips that
1213     * do not fit in the pre-defined available space when the
1214     * RecipientEditTextView loses focus.
1215     */
1216    private void createMoreChip() {
1217        if (!mShouldShrink) {
1218            return;
1219        }
1220
1221        RecipientChip[] recipients = getRecipients();
1222        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1223            mMoreChip = null;
1224            return;
1225        }
1226        int numRecipients = recipients.length;
1227        int overage = numRecipients - CHIP_LIMIT;
1228        Editable text = getText();
1229        String moreText = String.format(mMoreItem.getText().toString(), overage);
1230        TextPaint morePaint = new TextPaint(getPaint());
1231        morePaint.setTextSize(mMoreItem.getTextSize());
1232        morePaint.setColor(mMoreItem.getCurrentTextColor());
1233        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1234                + mMoreItem.getPaddingRight();
1235        int height = getLineHeight();
1236        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1237        Canvas canvas = new Canvas(drawable);
1238        canvas.drawText(moreText, 0, moreText.length(), 0, height - getLayout().getLineDescent(0),
1239                morePaint);
1240
1241        Drawable result = new BitmapDrawable(getResources(), drawable);
1242        result.setBounds(0, 0, width, height);
1243        ImageSpan moreSpan = new ImageSpan(result);
1244        Spannable spannable = getSpannable();
1245        // Remove the overage chips.
1246        if (recipients == null || recipients.length == 0) {
1247            Log.w(TAG,
1248                    "We have recipients. Tt should not be possible to have zero RecipientChips.");
1249            mMoreChip = null;
1250            return;
1251        }
1252        mRemovedSpans = new ArrayList<RecipientChip>();
1253        int totalReplaceStart = 0;
1254        int totalReplaceEnd = 0;
1255        for (int i = numRecipients - overage; i < recipients.length; i++) {
1256            mRemovedSpans.add(recipients[i]);
1257            if (i == numRecipients - overage) {
1258                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1259            }
1260            if (i == recipients.length - 1) {
1261                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1262            }
1263            if (mTemporaryRecipients != null && !mTemporaryRecipients.contains(recipients[i])) {
1264                recipients[i].storeChipStart(spannable.getSpanStart(recipients[i]));
1265                recipients[i].storeChipEnd(spannable.getSpanEnd(recipients[i]));
1266            }
1267            spannable.removeSpan(recipients[i]);
1268        }
1269        // TODO: why would these ever be backwards?
1270        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1271        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1272        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1273        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1274        text.replace(start, end, chipText);
1275        mMoreChip = moreSpan;
1276    }
1277
1278    /**
1279     * Replace the more chip, if it exists, with all of the recipient chips it had
1280     * replaced when the RecipientEditTextView gains focus.
1281     */
1282    private void removeMoreChip() {
1283        if (mMoreChip != null) {
1284            Spannable span = getSpannable();
1285            span.removeSpan(mMoreChip);
1286            mMoreChip = null;
1287            // Re-add the spans that were removed.
1288            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1289                // Recreate each removed span.
1290                Editable editable = getText();
1291                for (RecipientChip chip : mRemovedSpans) {
1292                    int chipStart = chip.getStoredChipStart();
1293                    int chipEnd;
1294                    String token;
1295                    if (chipStart == -1) {
1296                        // Need to find the location of the chip, again.
1297                        token = (String)mTokenizer.terminateToken(chip.getEntry().getDestination());
1298                        chipStart = editable.toString().indexOf(token);
1299                        // -1 for the space!
1300                        chipEnd = chipStart + token.length() - 1;
1301                    } else {
1302                        chipEnd = Math.min(editable.length(), chip.getStoredChipEnd());
1303                    }
1304                    if (Log.isLoggable(TAG, Log.DEBUG) && chipEnd != chip.getStoredChipEnd()) {
1305                        Log.d(TAG,
1306                                "Unexpectedly, the chip ended after the end of the editable text. "
1307                                        + "Chip End " + chip.getStoredChipEnd()
1308                                        + "Editable length " + editable.length());
1309                    }
1310                    // Only set the span if we found a matching token.
1311                    if (chipStart != -1) {
1312                        editable.setSpan(chip, chipStart, chipEnd,
1313                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1314                    }
1315                }
1316                mRemovedSpans.clear();
1317            }
1318        }
1319    }
1320
1321    /**
1322     * Show specified chip as selected. If the RecipientChip is just an email address,
1323     * selecting the chip will take the contents of the chip and place it at
1324     * the end of the RecipientEditTextView for inline editing. If the
1325     * RecipientChip is a complete contact, then selecting the chip
1326     * will change the background color of the chip, show the delete icon,
1327     * and a popup window with the address in use highlighted and any other
1328     * alternate addresses for the contact.
1329     * @param currentChip Chip to select.
1330     * @return A RecipientChip in the selected state or null if the chip
1331     * just contained an email address.
1332     */
1333    public RecipientChip selectChip(RecipientChip currentChip) {
1334        if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1335            CharSequence text = currentChip.getValue();
1336            Editable editable = getText();
1337            removeChip(currentChip);
1338            editable.append(text);
1339            setCursorVisible(true);
1340            setSelection(editable.length());
1341            return null;
1342        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1343            int start = getChipStart(currentChip);
1344            int end = getChipEnd(currentChip);
1345            getSpannable().removeSpan(currentChip);
1346            RecipientChip newChip;
1347            try {
1348                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1349            } catch (NullPointerException e) {
1350                Log.e(TAG, e.getMessage(), e);
1351                return null;
1352            }
1353            Editable editable = getText();
1354            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1355            if (start == -1 || end == -1) {
1356                Log.d(TAG, "The chip being selected no longer exists but should.");
1357            } else {
1358                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1359            }
1360            newChip.setSelected(true);
1361            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1362                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1363            }
1364            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1365            setCursorVisible(false);
1366            return newChip;
1367        } else {
1368            int start = getChipStart(currentChip);
1369            int end = getChipEnd(currentChip);
1370            getSpannable().removeSpan(currentChip);
1371            RecipientChip newChip;
1372            try {
1373                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1374            } catch (NullPointerException e) {
1375                Log.e(TAG, e.getMessage(), e);
1376                return null;
1377            }
1378            Editable editable = getText();
1379            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1380            if (start == -1 || end == -1) {
1381                Log.d(TAG, "The chip being selected no longer exists but should.");
1382            } else {
1383                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1384            }
1385            newChip.setSelected(true);
1386            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1387                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1388            }
1389            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1390            setCursorVisible(false);
1391            return newChip;
1392        }
1393    }
1394
1395
1396    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
1397            int width, Context context) {
1398        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1399        int bottom = calculateOffsetFromBottom(line);
1400        // Align the alternates popup with the left side of the View,
1401        // regardless of the position of the chip tapped.
1402        popup.setWidth(width);
1403        popup.setAnchorView(this);
1404        popup.setVerticalOffset(bottom);
1405        popup.setAdapter(createSingleAddressAdapter(currentChip));
1406        popup.setOnItemClickListener(new OnItemClickListener() {
1407            @Override
1408            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1409                unselectChip(currentChip);
1410                popup.dismiss();
1411            }
1412        });
1413        popup.show();
1414        ListView listView = popup.getListView();
1415        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1416        listView.setItemChecked(0, true);
1417    }
1418
1419    /**
1420     * Remove selection from this chip. Unselecting a RecipientChip will render
1421     * the chip without a delete icon and with an unfocused background. This
1422     * is called when the RecipientChip no longer has focus.
1423     */
1424    public void unselectChip(RecipientChip chip) {
1425        int start = getChipStart(chip);
1426        int end = getChipEnd(chip);
1427        Editable editable = getText();
1428        mSelectedChip = null;
1429        if (start == -1 || end == -1) {
1430            Log.e(TAG, "The chip being unselected no longer exists but should.");
1431        } else {
1432            getSpannable().removeSpan(chip);
1433            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1434            editable.removeSpan(chip);
1435            try {
1436                editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1437                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1438            } catch (NullPointerException e) {
1439                Log.e(TAG, e.getMessage(), e);
1440            }
1441        }
1442        setCursorVisible(true);
1443        setSelection(editable.length());
1444        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1445            mAlternatesPopup.dismiss();
1446        }
1447    }
1448
1449
1450    /**
1451     * Return whether this chip contains the position passed in.
1452     */
1453    public boolean matchesChip(RecipientChip chip, int offset) {
1454        int start = getChipStart(chip);
1455        int end = getChipEnd(chip);
1456        if (start == -1 || end == -1) {
1457            return false;
1458        }
1459        return (offset >= start && offset <= end);
1460    }
1461
1462
1463    /**
1464     * Return whether a touch event was inside the delete target of
1465     * a selected chip. It is in the delete target if:
1466     * 1) the x and y points of the event are within the
1467     * delete assset.
1468     * 2) the point tapped would have caused a cursor to appear
1469     * right after the selected chip.
1470     * @return boolean
1471     */
1472    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1473        // Figure out the bounds of this chip and whether or not
1474        // the user clicked in the X portion.
1475        return chip.isSelected() && offset == getChipEnd(chip);
1476    }
1477
1478    /**
1479     * Remove the chip and any text associated with it from the RecipientEditTextView.
1480     */
1481    private void removeChip(RecipientChip chip) {
1482        Spannable spannable = getSpannable();
1483        int spanStart = spannable.getSpanStart(chip);
1484        int spanEnd = spannable.getSpanEnd(chip);
1485        Editable text = getText();
1486        int toDelete = spanEnd;
1487        boolean wasSelected = chip == mSelectedChip;
1488        // Clear that there is a selected chip before updating any text.
1489        if (wasSelected) {
1490            mSelectedChip = null;
1491        }
1492        // Always remove trailing spaces when removing a chip.
1493        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
1494            toDelete++;
1495        }
1496        spannable.removeSpan(chip);
1497        text.delete(spanStart, toDelete);
1498        if (wasSelected) {
1499            clearSelectedChip();
1500        }
1501    }
1502
1503    /**
1504     * Replace this currently selected chip with a new chip
1505     * that uses the contact data provided.
1506     */
1507    public void replaceChip(RecipientChip chip, RecipientEntry entry) {
1508        boolean wasSelected = chip == mSelectedChip;
1509        if (wasSelected) {
1510            mSelectedChip = null;
1511        }
1512        int start = getChipStart(chip);
1513        int end = getChipEnd(chip);
1514        getSpannable().removeSpan(chip);
1515        Editable editable = getText();
1516        CharSequence chipText = createChip(entry, false);
1517        if (start == -1 || end == -1) {
1518            Log.e(TAG, "The chip to replace does not exist but should.");
1519            editable.insert(0, chipText);
1520        } else {
1521            // There may be a space to replace with this chip's new associated
1522            // space. Check for it.
1523            int toReplace = end;
1524            while (toReplace >= 0 && toReplace < editable.length()
1525                    && editable.charAt(toReplace) == ' ') {
1526                toReplace++;
1527            }
1528            editable.replace(start, toReplace, chipText);
1529        }
1530        setCursorVisible(true);
1531        if (wasSelected) {
1532            clearSelectedChip();
1533        }
1534    }
1535
1536    /**
1537     * Handle click events for a chip. When a selected chip receives a click
1538     * event, see if that event was in the delete icon. If so, delete it.
1539     * Otherwise, unselect the chip.
1540     */
1541    public void onClick(RecipientChip chip, int offset, float x, float y) {
1542        if (chip.isSelected()) {
1543            if (isInDelete(chip, offset, x, y)) {
1544                removeChip(chip);
1545            } else {
1546                clearSelectedChip();
1547            }
1548        }
1549    }
1550
1551    private boolean chipsPending() {
1552        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1553    }
1554
1555    @Override
1556    public void removeTextChangedListener(TextWatcher watcher) {
1557        mTextWatcher = null;
1558        super.removeTextChangedListener(watcher);
1559    }
1560
1561    private class RecipientTextWatcher implements TextWatcher {
1562        @Override
1563        public void afterTextChanged(Editable s) {
1564            // If the text has been set to null or empty, make sure we remove
1565            // all the spans we applied.
1566            if (TextUtils.isEmpty(s)) {
1567                // Remove all the chips spans.
1568                Spannable spannable = getSpannable();
1569                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
1570                        RecipientChip.class);
1571                for (RecipientChip chip : chips) {
1572                    spannable.removeSpan(chip);
1573                }
1574                if (mMoreChip != null) {
1575                    spannable.removeSpan(mMoreChip);
1576                }
1577                return;
1578            }
1579            // Get whether there are any recipients pending addition to the
1580            // view. If there are, don't do anything in the text watcher.
1581            if (chipsPending()) {
1582                return;
1583            }
1584            if (mSelectedChip != null) {
1585                setCursorVisible(true);
1586                setSelection(getText().length());
1587                clearSelectedChip();
1588            }
1589            int length = s.length();
1590            // Make sure there is content there to parse and that it is
1591            // not just the commit character.
1592            if (length > 1) {
1593                char last;
1594                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
1595                int len = length() - 1;
1596                if (end != len) {
1597                    last = s.charAt(end);
1598                } else {
1599                    last = s.charAt(len);
1600                }
1601                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
1602                    commitByCharacter();
1603                } else if (last == COMMIT_CHAR_SPACE) {
1604                    // Check if this is a valid email address. If it is,
1605                    // commit it.
1606                    String text = getText().toString();
1607                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1608                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
1609                            tokenStart));
1610                    if (mValidator != null && mValidator.isValid(sub)) {
1611                        commitByCharacter();
1612                    }
1613                }
1614            }
1615        }
1616
1617        @Override
1618        public void onTextChanged(CharSequence s, int start, int before, int count) {
1619            // Do nothing.
1620        }
1621
1622        @Override
1623        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1624        }
1625    }
1626
1627    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
1628        private RecipientChip createFreeChip(RecipientEntry entry) {
1629            String displayText = entry.getDestination();
1630            displayText = (String) mTokenizer.terminateToken(displayText);
1631            try {
1632                return constructChipSpan(entry, -1, false);
1633            } catch (NullPointerException e) {
1634                Log.e(TAG, e.getMessage(), e);
1635                return null;
1636            }
1637        }
1638
1639        @Override
1640        protected Void doInBackground(Void... params) {
1641            if (mIndividualReplacements != null) {
1642                mIndividualReplacements.cancel(true);
1643            }
1644            // For each chip in the list, look up the matching contact.
1645            // If there is a match, replace that chip with the matching
1646            // chip.
1647            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
1648            RecipientChip[] existingChips = getSpannable().getSpans(0, getText().length(),
1649                    RecipientChip.class);
1650            for (int i = 0; i < existingChips.length; i++) {
1651                originalRecipients.add(existingChips[i]);
1652            }
1653            if (mRemovedSpans != null) {
1654                originalRecipients.addAll(mRemovedSpans);
1655            }
1656            String[] addresses = new String[originalRecipients.size()];
1657            for (int i = 0; i < originalRecipients.size(); i++) {
1658                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1659            }
1660            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1661                    .getMatchingRecipients(getContext(), addresses);
1662            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
1663            for (final RecipientChip temp : originalRecipients) {
1664                RecipientEntry entry = null;
1665                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
1666                        && getSpannable().getSpanStart(temp) != -1) {
1667                    // Replace this.
1668                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
1669                            .getDestination())));
1670                }
1671                if (entry != null) {
1672                    replacements.add(createFreeChip(entry));
1673                } else {
1674                    replacements.add(temp);
1675                }
1676            }
1677            if (replacements != null && replacements.size() > 0) {
1678                mHandler.post(new Runnable() {
1679                    @Override
1680                    public void run() {
1681                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
1682                                .toString());
1683                        Editable oldText = getText();
1684                        int start, end;
1685                        int i = 0;
1686                        for (RecipientChip chip : originalRecipients) {
1687                            start = oldText.getSpanStart(chip);
1688                            if (start != -1) {
1689                                end = oldText.getSpanEnd(chip);
1690                                text.removeSpan(chip);
1691                                // Leave a spot for the space!
1692                                text.setSpan(replacements.get(i), start, end,
1693                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1694                            }
1695                            i++;
1696                        }
1697                        Editable editable = getText();
1698                        editable.clear();
1699                        editable.insert(0, text);
1700                        originalRecipients.clear();
1701                    }
1702                });
1703            }
1704            return null;
1705        }
1706    }
1707
1708    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
1709        @SuppressWarnings("unchecked")
1710        @Override
1711        protected Void doInBackground(Object... params) {
1712            // For each chip in the list, look up the matching contact.
1713            // If there is a match, replace that chip with the matching
1714            // chip.
1715            final ArrayList<RecipientChip> originalRecipients =
1716                (ArrayList<RecipientChip>) params[0];
1717            String[] addresses = new String[originalRecipients.size()];
1718            for (int i = 0; i < originalRecipients.size(); i++) {
1719                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1720            }
1721            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1722                    .getMatchingRecipients(getContext(), addresses);
1723            for (final RecipientChip temp : originalRecipients) {
1724                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
1725                        && getSpannable().getSpanStart(temp) != -1) {
1726                    // Replace this.
1727                    final RecipientEntry entry = createValidatedEntry(entries
1728                            .get(tokenizeAddress(temp.getEntry().getDestination())));
1729                    if (entry != null) {
1730                        mHandler.post(new Runnable() {
1731                            @Override
1732                            public void run() {
1733                                replaceChip(temp, entry);
1734                            }
1735                        });
1736                    }
1737                }
1738            }
1739            return null;
1740        }
1741    }
1742}
1743