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