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