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