RecipientEditTextView.java revision ba5642a5729d9d1483702d42ae4a21d8cbfaa804
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.ex.chips;
18
19import android.content.Context;
20import android.graphics.Bitmap;
21import android.graphics.BitmapFactory;
22import android.graphics.Canvas;
23import android.graphics.Matrix;
24import android.graphics.Rect;
25import android.graphics.RectF;
26import android.graphics.drawable.BitmapDrawable;
27import android.graphics.drawable.Drawable;
28import android.os.AsyncTask;
29import android.os.Handler;
30import android.os.Message;
31import android.text.Editable;
32import android.text.Layout;
33import android.text.Spannable;
34import android.text.SpannableString;
35import android.text.SpannableStringBuilder;
36import android.text.Spanned;
37import android.text.TextPaint;
38import android.text.TextUtils;
39import android.text.TextWatcher;
40import android.text.method.QwertyKeyListener;
41import android.text.style.ImageSpan;
42import android.text.util.Rfc822Token;
43import android.text.util.Rfc822Tokenizer;
44import android.util.AttributeSet;
45import android.util.Log;
46import android.view.ActionMode;
47import android.view.KeyEvent;
48import android.view.LayoutInflater;
49import android.view.Menu;
50import android.view.MenuItem;
51import android.view.MotionEvent;
52import android.view.View;
53import android.view.ViewParent;
54import android.view.ActionMode.Callback;
55import android.widget.AdapterView;
56import android.widget.AdapterView.OnItemClickListener;
57import android.widget.Filterable;
58import android.widget.ListAdapter;
59import android.widget.ListPopupWindow;
60import android.widget.ListView;
61import android.widget.MultiAutoCompleteTextView;
62import android.widget.ScrollView;
63import android.widget.TextView;
64
65import java.util.Collection;
66import java.util.HashMap;
67import java.util.HashSet;
68import java.util.Set;
69
70import java.util.ArrayList;
71
72/**
73 * RecipientEditTextView is an auto complete text view for use with applications
74 * that use the new Chips UI for addressing a message to recipients.
75 */
76public class RecipientEditTextView extends MultiAutoCompleteTextView implements
77        OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener {
78
79    private static final String TAG = "RecipientEditTextView";
80
81    // TODO: get correct number/ algorithm from with UX.
82    private static final int CHIP_LIMIT = 2;
83
84    private Drawable mChipBackground = null;
85
86    private Drawable mChipDelete = null;
87
88    private int mChipPadding;
89
90    private Tokenizer mTokenizer;
91
92    private Drawable mChipBackgroundPressed;
93
94    private RecipientChip mSelectedChip;
95
96    private int mAlternatesLayout;
97
98    private Bitmap mDefaultContactPhoto;
99
100    private ImageSpan mMoreChip;
101
102    private TextView mMoreItem;
103
104
105    private final ArrayList<String> mPendingChips = new ArrayList<String>();
106
107    private float mChipHeight;
108
109    private float mChipFontSize;
110
111    private Validator mValidator;
112
113    private Drawable mInvalidChipBackground;
114
115    private Handler mHandler;
116
117    private static int DISMISS = "dismiss".hashCode();
118
119    private static final long DISMISS_DELAY = 300;
120
121    private int mPendingChipsCount = 0;
122
123    private static int sSelectedTextColor = -1;
124
125    private static final char COMMIT_CHAR_COMMA = ',';
126
127    private static final char COMMIT_CHAR_SEMICOLON = ';';
128
129    private static final char COMMIT_CHAR_SPACE = ' ';
130
131    private ListPopupWindow mAlternatesPopup;
132
133    private ListPopupWindow mAddressPopup;
134
135    private ArrayList<RecipientChip> mTemporaryRecipients;
136
137    private ArrayList<RecipientChip> mRemovedSpans;
138
139    /**
140     * Used with {@link mAlternatesPopup}. Handles clicks to alternate addresses for a selected chip.
141     */
142    private OnItemClickListener mAlternatesListener;
143
144    private int mCheckedItem;
145    private TextWatcher mTextWatcher;
146
147    private ScrollView mScrollView;
148
149    private boolean mTried;
150
151    private final Runnable mAddTextWatcher = new Runnable() {
152        @Override
153        public void run() {
154            if (mTextWatcher == null) {
155                mTextWatcher = new RecipientTextWatcher();
156                addTextChangedListener(mTextWatcher);
157            }
158        }
159    };
160
161    private IndividualReplacementTask mIndividualReplacements;
162
163    private Runnable mHandlePendingChips = new Runnable() {
164
165        @Override
166        public void run() {
167            handlePendingChips();
168        }
169
170    };
171
172    public RecipientEditTextView(Context context, AttributeSet attrs) {
173        super(context, attrs);
174        if (sSelectedTextColor == -1) {
175            sSelectedTextColor = context.getResources().getColor(android.R.color.white);
176        }
177        mAlternatesPopup = new ListPopupWindow(context);
178        mAddressPopup = new ListPopupWindow(context);
179        mAlternatesListener = new OnItemClickListener() {
180            @Override
181            public void onItemClick(AdapterView<?> adapterView,View view, int position,
182                    long rowId) {
183                mAlternatesPopup.setOnItemClickListener(null);
184                replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
185                        .getRecipientEntry(position));
186                Message delayed = Message.obtain(mHandler, DISMISS);
187                delayed.obj = mAlternatesPopup;
188                mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
189                clearComposingText();
190            }
191        };
192        setSuggestionsEnabled(false);
193        setOnItemClickListener(this);
194        setCustomSelectionActionModeCallback(this);
195        mHandler = new Handler() {
196            @Override
197            public void handleMessage(Message msg) {
198                if (msg.what == DISMISS) {
199                    ((ListPopupWindow) msg.obj).dismiss();
200                    return;
201                }
202                super.handleMessage(msg);
203            }
204        };
205        mTextWatcher = new RecipientTextWatcher();
206        addTextChangedListener(mTextWatcher);
207    }
208
209    @Override
210    public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
211        super.setAdapter(adapter);
212        if (adapter == null) {
213            return;
214        }
215    }
216
217    @Override
218    public void onSelectionChanged(int start, int end) {
219        // When selection changes, see if it is inside the chips area.
220        // If so, move the cursor back after the chips again.
221        Spannable span = getSpannable();
222        int textLength = getText().length();
223        RecipientChip[] chips = span.getSpans(start, textLength, RecipientChip.class);
224        if (chips != null && chips.length > 0) {
225            if (chips != null && chips.length > 0) {
226                // Grab the last chip and set the cursor to after it.
227                setSelection(Math.min(span.getSpanEnd(chips[chips.length - 1]) + 1, textLength));
228            }
229        }
230        super.onSelectionChanged(start, end);
231    }
232
233    /**
234     * Convenience method: Append the specified text slice to the TextView's
235     * display buffer, upgrading it to BufferType.EDITABLE if it was
236     * not already editable. Commas are excluded as they are added automatically
237     * by the view.
238     */
239    @Override
240    public void append(CharSequence text, int start, int end) {
241        // We don't care about watching text changes while appending.
242        if (mTextWatcher != null) {
243            removeTextChangedListener(mTextWatcher);
244        }
245        super.append(text, start, end);
246        if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
247            final String displayString = (String) text;
248            int seperatorPos = displayString.indexOf(COMMIT_CHAR_COMMA);
249            if (seperatorPos != 0 && !TextUtils.isEmpty(displayString)
250                    && TextUtils.getTrimmedLength(displayString) > 0) {
251                mPendingChipsCount++;
252                mPendingChips.add((String)text);
253            }
254        }
255        // Put a message on the queue to make sure we ALWAYS handle pending chips.
256        if (mPendingChipsCount > 0) {
257            postHandlePendingChips();
258        }
259        mHandler.post(mAddTextWatcher);
260    }
261
262    @Override
263    public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
264        if (!hasFocus) {
265            shrink();
266        } else {
267            expand();
268            scrollLineIntoView(getLineCount());
269        }
270        super.onFocusChanged(hasFocus, direction, previous);
271    }
272
273    private void shrink() {
274        if (mSelectedChip != null) {
275            clearSelectedChip();
276        } else {
277            // Reset any pending chips as they would have been handled
278            // when the field lost focus.
279            if (mPendingChipsCount > 0) {
280                postHandlePendingChips();
281            } else {
282                Editable editable = getText();
283                int end = getSelectionEnd();
284                int start = mTokenizer.findTokenStart(editable, end);
285                RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
286                if ((chips == null || chips.length == 0)) {
287                    int whatEnd = mTokenizer.findTokenEnd(getText(), start);
288                    // In the middle of chip; treat this as an edit
289                    // and commit the whole token.
290                    if (whatEnd != getSelectionEnd()) {
291                        handleEdit(start, whatEnd);
292                    } else {
293                        commitChip(start, end, editable);
294                    }
295                }
296            }
297            mHandler.post(mAddTextWatcher);
298        }
299        createMoreChip();
300    }
301
302    private void expand() {
303        removeMoreChip();
304        setCursorVisible(true);
305        Editable text = getText();
306        setSelection(text != null && text.length() > 0 ? text.length() : 0);
307        // If there are any temporary chips, try replacing them now that the user
308        // has expanded the field.
309        if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) {
310            new RecipientReplacementTask().execute();
311            mTemporaryRecipients = null;
312        }
313    }
314
315    private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
316        paint.setTextSize(mChipFontSize);
317        if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
318            Log.d(TAG, "Max width is negative: " + maxWidth);
319        }
320        return TextUtils.ellipsize(text, paint, maxWidth,
321                TextUtils.TruncateAt.END);
322    }
323
324    private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
325        // Ellipsize the text so that it takes AT MOST the entire width of the
326        // autocomplete text entry area. Make sure to leave space for padding
327        // on the sides.
328        int height = (int) mChipHeight;
329        int deleteWidth = height;
330        CharSequence ellipsizedText = ellipsizeText(contact.getDisplayName(), paint,
331                calculateAvailableWidth(true) - deleteWidth);
332
333        // Make sure there is a minimum chip width so the user can ALWAYS
334        // tap a chip without difficulty.
335        int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
336                ellipsizedText.length()))
337                + (mChipPadding * 2) + deleteWidth);
338
339        // Create the background of the chip.
340        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
341        Canvas canvas = new Canvas(tmpBitmap);
342        if (mChipBackgroundPressed != null) {
343            mChipBackgroundPressed.setBounds(0, 0, width, height);
344            mChipBackgroundPressed.draw(canvas);
345            paint.setColor(sSelectedTextColor);
346            // Align the display text with where the user enters text.
347            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, height
348                    - Math.abs(height - mChipFontSize)/2, paint);
349            // Make the delete a square.
350            mChipDelete.setBounds(width - deleteWidth, 0, width, height);
351            mChipDelete.draw(canvas);
352        } else {
353            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
354        }
355        return tmpBitmap;
356    }
357
358
359    /**
360     * Get the background drawable for a RecipientChip.
361     */
362    public Drawable getChipBackground(RecipientEntry contact) {
363        return (mValidator != null && mValidator.isValid(contact.getDestination())) ?
364                mChipBackground : mInvalidChipBackground;
365    }
366
367    private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
368        // Ellipsize the text so that it takes AT MOST the entire width of the
369        // autocomplete text entry area. Make sure to leave space for padding
370        // on the sides.
371        int height = (int) mChipHeight;
372        int iconWidth = height;
373        String displayText =
374            !TextUtils.isEmpty(contact.getDisplayName()) ? contact.getDisplayName() :
375            !TextUtils.isEmpty(contact.getDestination()) ? contact.getDestination() : "";
376        CharSequence ellipsizedText = ellipsizeText(displayText, paint,
377                calculateAvailableWidth(false) - iconWidth);
378        // Make sure there is a minimum chip width so the user can ALWAYS
379        // tap a chip without difficulty.
380        int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
381                ellipsizedText.length()))
382                + (mChipPadding * 2) + iconWidth);
383
384        // Create the background of the chip.
385        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
386        Canvas canvas = new Canvas(tmpBitmap);
387        Drawable background = getChipBackground(contact);
388        if (background != null) {
389            background.setBounds(0, 0, width, height);
390            background.draw(canvas);
391
392            // Don't draw photos for recipients that have been typed in.
393            if (contact.getContactId() != RecipientEntry.INVALID_CONTACT) {
394                byte[] photoBytes = contact.getPhotoBytes();
395                // There may not be a photo yet if anything but the first contact address
396                // was selected.
397                if (photoBytes == null && contact.getPhotoThumbnailUri() != null) {
398                    // TODO: cache this in the recipient entry?
399                    ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact
400                            .getPhotoThumbnailUri());
401                    photoBytes = contact.getPhotoBytes();
402                }
403
404                Bitmap photo;
405                if (photoBytes != null) {
406                    photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
407                } else {
408                    // TODO: can the scaled down default photo be cached?
409                    photo = mDefaultContactPhoto;
410                }
411                // Draw the photo on the left side.
412                Matrix matrix = new Matrix();
413                RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight());
414                RectF dst = new RectF(width - iconWidth, 0, width, height);
415                matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
416                canvas.drawBitmap(photo, matrix, paint);
417            } else {
418                // Don't leave any space for the icon. It isn't being drawn.
419                iconWidth = 0;
420            }
421
422            // Align the display text with where the user enters text.
423            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
424                    height - Math.abs(height - mChipFontSize) / 2, paint);
425        } else {
426            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
427        }
428        return tmpBitmap;
429    }
430
431    public RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed)
432            throws NullPointerException {
433        if (mChipBackground == null) {
434            throw new NullPointerException(
435                    "Unable to render any chips as setChipDimensions was not called.");
436        }
437        Layout layout = getLayout();
438
439        TextPaint paint = getPaint();
440        float defaultSize = paint.getTextSize();
441        int defaultColor = paint.getColor();
442
443        Bitmap tmpBitmap;
444        if (pressed) {
445            tmpBitmap = createSelectedChip(contact, paint, layout);
446
447        } else {
448            tmpBitmap = createUnselectedChip(contact, paint, layout);
449        }
450
451        // Pass the full text, un-ellipsized, to the chip.
452        Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
453        result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
454        RecipientChip recipientChip = new RecipientChip(result, contact, offset);
455        // Return text to the original size.
456        paint.setTextSize(defaultSize);
457        paint.setColor(defaultColor);
458        return recipientChip;
459    }
460
461    /**
462     * Calculate the bottom of the line the chip will be located on using:
463     * 1) which line the chip appears on
464     * 2) the height of a chip
465     * 3) padding built into the edit text view
466     */
467    private int calculateOffsetFromBottom(int line) {
468        // Line offsets start at zero.
469        int actualLine = getLineCount() - (line + 1);
470        return -((actualLine * ((int)mChipHeight) + getPaddingBottom()) + getPaddingTop());
471    }
472
473    /**
474     * Get the max amount of space a chip can take up. The formula takes into
475     * account the width of the EditTextView, any view padding, and padding
476     * that will be added to the chip.
477     */
478    private float calculateAvailableWidth(boolean pressed) {
479        return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
480    }
481
482    /**
483     * Set all chip dimensions and resources. This has to be done from the
484     * application as this is a static library.
485     * @param chipBackground
486     * @param chipBackgroundPressed
487     * @param invalidChip
488     * @param chipDelete
489     * @param defaultContact
490     * @param moreResource
491     * @param alternatesLayout
492     * @param chipHeight
493     * @param padding Padding around the text in a chip
494     */
495    public void setChipDimensions(Drawable chipBackground, Drawable chipBackgroundPressed,
496            Drawable invalidChip, Drawable chipDelete, Bitmap defaultContact, int moreResource,
497            int alternatesLayout, float chipHeight, float padding,
498            float chipFontSize) {
499        mChipBackground = chipBackground;
500        mChipBackgroundPressed = chipBackgroundPressed;
501        mChipDelete = chipDelete;
502        mChipPadding = (int) padding;
503        mAlternatesLayout = alternatesLayout;
504        mDefaultContactPhoto = defaultContact;
505        mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(moreResource, null);
506        mChipHeight = chipHeight;
507        mChipFontSize = chipFontSize;
508        mInvalidChipBackground = invalidChip;
509    }
510
511    @Override
512    public void onSizeChanged(int width, int height, int oldw, int oldh) {
513        super.onSizeChanged(width, height, oldw, oldh);
514        if (width != 0 && height != 0 && mPendingChipsCount > 0) {
515            postHandlePendingChips();
516        }
517        // Try to find the scroll view parent, if it exists.
518        if (mScrollView == null && !mTried) {
519            ViewParent parent = getParent();
520            while (parent != null && !(parent instanceof ScrollView)) {
521                parent = parent.getParent();
522            }
523            if (parent != null) {
524                mScrollView = (ScrollView) parent;
525            }
526            mTried = true;
527        }
528    }
529
530    private void postHandlePendingChips() {
531        mHandler.removeCallbacks(mHandlePendingChips);
532        mHandler.post(mHandlePendingChips);
533    }
534
535    private void handlePendingChips() {
536        if (mPendingChipsCount <= 0) {
537            return;
538        }
539        if (getWidth() <= 0) {
540            // The widget has not been sized yet.
541            // This will be called as a result of onSizeChanged
542            // at a later point.
543            return;
544        }
545        synchronized (mPendingChips) {
546            mTemporaryRecipients = new ArrayList<RecipientChip>(mPendingChipsCount);
547            Editable editable = getText();
548            // Tokenize!
549            for (int i = 0; i < mPendingChips.size(); i++) {
550                String current = mPendingChips.get(i);
551                int tokenStart = editable.toString().indexOf(current);
552                int tokenEnd = tokenStart + current.length();
553                if (tokenStart >= 0) {
554                    // When we have a valid token, include it with the token
555                    // to the left.
556                    if (tokenEnd < editable.length() - 2
557                            && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
558                        tokenEnd++;
559                    }
560                    createReplacementChip(tokenStart, tokenEnd, editable);
561                }
562                mPendingChipsCount--;
563            }
564            sanitizeSpannable();
565            if (mTemporaryRecipients != null
566                    && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
567                if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
568                    new RecipientReplacementTask().execute();
569                    mTemporaryRecipients = null;
570                } else {
571                    // Create the "more" chip
572                    mIndividualReplacements = new IndividualReplacementTask();
573                    mIndividualReplacements.execute(new ArrayList<RecipientChip>(
574                            mTemporaryRecipients.subList(0, CHIP_LIMIT)));
575
576                    createMoreChip();
577                }
578            } else {
579                // There are too many recipients to look up, so just fall back
580                // to
581                // showing addresses for all of them.
582                mTemporaryRecipients = null;
583                createMoreChip();
584            }
585            mPendingChipsCount = 0;
586            mPendingChips.clear();
587        }
588    }
589
590    /**
591     * Remove any characters after the last valid chip.
592     */
593    private void sanitizeSpannable() {
594        // Find the last chip; eliminate any commit characters after it.
595        RecipientChip[] chips = getRecipients();
596        if (chips != null && chips.length > 0) {
597            int end;
598            ImageSpan lastSpan;
599            if (mMoreChip != null) {
600                lastSpan = mMoreChip;
601            } else {
602                lastSpan = chips[chips.length - 1];
603            }
604            end = getSpannable().getSpanEnd(lastSpan);
605            Editable editable = getText();
606            int length = editable.length();
607            if (length > end) {
608                // See what characters occur after that and eliminate them.
609                if (Log.isLoggable(TAG, Log.DEBUG)) {
610                    Log.d(TAG, "There were extra characters after the last tokenizable entry."
611                            + editable);
612                }
613                editable.delete(end + 1, length);
614            }
615        }
616    }
617
618    /**
619     * Create a chip that represents just the email address of a recipient. At some later
620     * point, this chip will be attached to a real contact entry, if one exists.
621     */
622    private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) {
623        if (alreadyHasChip(tokenStart, tokenEnd)) {
624            // There is already a chip present at this location.
625            // Don't recreate it.
626            return;
627        }
628        String token = editable.toString().substring(tokenStart, tokenEnd);
629        int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA);
630        if (commitCharIndex == token.length() - 1) {
631            token = token.substring(0, token.length() - 1);
632        }
633        RecipientEntry entry = createTokenizedEntry(token);
634        if (entry != null) {
635            String destText = entry.getDestination();
636            destText = (String) mTokenizer.terminateToken(destText);
637            // Always leave a blank space at the end of a chip.
638            int textLength = destText.length() - 1;
639            SpannableString chipText = new SpannableString(destText);
640            int end = getSelectionEnd();
641            int start = mTokenizer.findTokenStart(getText(), end);
642            RecipientChip chip = null;
643            try {
644                chip = constructChipSpan(entry, start, false);
645                chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
646            } catch (NullPointerException e) {
647                Log.e(TAG, e.getMessage(), e);
648            }
649
650            editable.replace(tokenStart, tokenEnd, chipText);
651            // Add this chip to the list of entries "to replace"
652            if (chip != null) {
653                mTemporaryRecipients.add(chip);
654            }
655        }
656    }
657
658    private RecipientEntry createTokenizedEntry(String token) {
659        if (TextUtils.isEmpty(token)) {
660            return null;
661        }
662        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
663        String display = null;
664        if (isValid(token) && tokens != null && tokens.length > 0) {
665            display = tokens[0].getName();
666            if (!TextUtils.isEmpty(display)) {
667                return RecipientEntry.constructGeneratedEntry(display, token);
668            }
669            display = tokens[0].getAddress();
670            if (!TextUtils.isEmpty(display)) {
671                return RecipientEntry.constructGeneratedEntry(display, token);
672            }
673        }
674        // Unable to validate the token or to create a valid token from it.
675        // Just create a chip the user can edit.
676        if (mValidator != null && !mValidator.isValid(token)) {
677            // Try fixing up the entry using the validator.
678            token = mValidator.fixText(token).toString();
679            if (tokens != null && tokens.length > 0) {
680                token = Rfc822Tokenizer.tokenize(token)[0].getAddress();
681            }
682        }
683        return RecipientEntry.constructFakeEntry(token);
684    }
685
686    private boolean isValid(String text) {
687        return mValidator == null ? true : mValidator.isValid(text);
688    }
689
690    private String tokenizeAddress(String destination) {
691        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
692        if (tokens != null && tokens.length > 0) {
693            return tokens[0].getAddress();
694        }
695        return destination;
696    }
697
698    @Override
699    public void setTokenizer(Tokenizer tokenizer) {
700        mTokenizer = tokenizer;
701        super.setTokenizer(mTokenizer);
702    }
703
704    @Override
705    public void setValidator(Validator validator) {
706        mValidator = validator;
707        super.setValidator(validator);
708    }
709
710    /**
711     * We cannot use the default mechanism for replaceText. Instead,
712     * we override onItemClickListener so we can get all the associated
713     * contact information including display text, address, and id.
714     */
715    @Override
716    protected void replaceText(CharSequence text) {
717        return;
718    }
719
720    /**
721     * Dismiss any selected chips when the back key is pressed.
722     */
723    @Override
724    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
725        if (keyCode == KeyEvent.KEYCODE_BACK) {
726            clearSelectedChip();
727        }
728        return super.onKeyPreIme(keyCode, event);
729    }
730
731    /**
732     * Monitor key presses in this view to see if the user types
733     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
734     * If the user has entered text that has contact matches and types
735     * a commit key, create a chip from the topmost matching contact.
736     * If the user has entered text that has no contact matches and types
737     * a commit key, then create a chip from the text they have entered.
738     */
739    @Override
740    public boolean onKeyUp(int keyCode, KeyEvent event) {
741        switch (keyCode) {
742            case KeyEvent.KEYCODE_ENTER:
743            case KeyEvent.KEYCODE_DPAD_CENTER:
744                if (event.hasNoModifiers()) {
745                    if (commitDefault()) {
746                        return true;
747                    }
748                    if (mSelectedChip != null) {
749                        clearSelectedChip();
750                        return true;
751                    } else if (focusNext()) {
752                        return true;
753                    }
754                }
755                break;
756            case KeyEvent.KEYCODE_TAB:
757                if (event.hasNoModifiers()) {
758                    if (mSelectedChip != null) {
759                        clearSelectedChip();
760                    } else {
761                        commitDefault();
762                    }
763                    if (focusNext()) {
764                        return true;
765                    }
766                }
767        }
768        return super.onKeyUp(keyCode, event);
769    }
770
771    private boolean focusNext() {
772        View next = focusSearch(View.FOCUS_DOWN);
773        if (next != null) {
774            next.requestFocus();
775            return true;
776        }
777        return false;
778    }
779
780    /**
781     * Create a chip from the default selection. If the popup is showing, the
782     * default is the first item in the popup suggestions list. Otherwise, it is
783     * whatever the user had typed in. End represents where the the tokenizer
784     * should search for a token to turn into a chip.
785     * @return If a chip was created from a real contact.
786     */
787    private boolean commitDefault() {
788        Editable editable = getText();
789        int end = getSelectionEnd();
790        int start = mTokenizer.findTokenStart(editable, end);
791
792        if (shouldCreateChip(start, end)) {
793            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
794            // In the middle of chip; treat this as an edit
795            // and commit the whole token.
796            if (whatEnd != getSelectionEnd()) {
797                handleEdit(start, whatEnd);
798                return true;
799            }
800            return commitChip(start, end , editable);
801        }
802        return false;
803    }
804
805    private void commitByCharacter() {
806        Editable editable = getText();
807        int end = getSelectionEnd();
808        int start = mTokenizer.findTokenStart(editable, end);
809        if (shouldCreateChip(start, end)) {
810            commitChip(start, end, editable);
811        }
812        setSelection(getText().length());
813    }
814
815    private boolean commitChip(int start, int end, Editable editable) {
816        if (getAdapter().getCount() > 0 && enoughToFilter()) {
817            // choose the first entry.
818            submitItemAtPosition(0);
819            dismissDropDown();
820            return true;
821        } else {
822            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
823            String text = editable.toString().substring(start, tokenEnd).trim();
824            clearComposingText();
825            if (text != null && text.length() > 0 && !text.equals(" ")) {
826                RecipientEntry entry = createTokenizedEntry(text);
827                if (entry != null) {
828                    QwertyKeyListener.markAsReplaced(editable, start, end, "");
829                    CharSequence chipText = createChip(entry, false);
830                    editable.replace(start, end, chipText);
831                }
832                dismissDropDown();
833                return true;
834            }
835        }
836        return false;
837    }
838
839    private boolean shouldCreateChip(int start, int end) {
840        return hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
841    }
842
843    private boolean alreadyHasChip(int start, int end) {
844        RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
845        if ((chips == null || chips.length == 0)) {
846            return false;
847        }
848        return true;
849    }
850
851    private void handleEdit(int start, int end) {
852        // This is in the middle of a chip, so select out the whole chip
853        // and commit it.
854        Editable editable = getText();
855        setSelection(end);
856        String text = getText().toString().substring(start, end);
857        RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
858        QwertyKeyListener.markAsReplaced(editable, start, end, "");
859        CharSequence chipText = createChip(entry, false);
860        editable.replace(start, getSelectionEnd(), chipText);
861        dismissDropDown();
862    }
863
864    /**
865     * If there is a selected chip, delegate the key events
866     * to the selected chip.
867     */
868    @Override
869    public boolean onKeyDown(int keyCode, KeyEvent event) {
870        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
871            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
872                mAlternatesPopup.dismiss();
873            }
874            removeChip(mSelectedChip);
875        }
876
877        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
878            return true;
879        }
880
881        return super.onKeyDown(keyCode, event);
882    }
883
884    private Spannable getSpannable() {
885        return getText();
886    }
887
888    private int getChipStart(RecipientChip chip) {
889        return getSpannable().getSpanStart(chip);
890    }
891
892    private int getChipEnd(RecipientChip chip) {
893        return getSpannable().getSpanEnd(chip);
894    }
895
896    /**
897     * Instead of filtering on the entire contents of the edit box,
898     * this subclass method filters on the range from
899     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
900     * if the length of that range meets or exceeds {@link #getThreshold}
901     * and makes sure that the range is not already a Chip.
902     */
903    @Override
904    protected void performFiltering(CharSequence text, int keyCode) {
905        if (enoughToFilter()) {
906            int end = getSelectionEnd();
907            int start = mTokenizer.findTokenStart(text, end);
908            // If this is a RecipientChip, don't filter
909            // on its contents.
910            Spannable span = getSpannable();
911            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
912            if (chips != null && chips.length > 0) {
913                return;
914            }
915        }
916        super.performFiltering(text, keyCode);
917    }
918
919    private void clearSelectedChip() {
920        if (mSelectedChip != null) {
921            unselectChip(mSelectedChip);
922            mSelectedChip = null;
923        }
924        setCursorVisible(true);
925    }
926
927    /**
928     * Monitor touch events in the RecipientEditTextView.
929     * If the view does not have focus, any tap on the view
930     * will just focus the view. If the view has focus, determine
931     * if the touch target is a recipient chip. If it is and the chip
932     * is not selected, select it and clear any other selected chips.
933     * If it isn't, then select that chip.
934     */
935    @Override
936    public boolean onTouchEvent(MotionEvent event) {
937        if (!isFocused()) {
938            // Ignore any chip taps until this view is focused.
939            return super.onTouchEvent(event);
940        }
941
942        boolean handled = super.onTouchEvent(event);
943        int action = event.getAction();
944        boolean chipWasSelected = false;
945
946        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
947            float x = event.getX();
948            float y = event.getY();
949            int offset = putOffsetInRange(getOffsetForPosition(x, y));
950            RecipientChip currentChip = findChip(offset);
951            if (currentChip != null) {
952                if (action == MotionEvent.ACTION_UP) {
953                    if (mSelectedChip != null && mSelectedChip != currentChip) {
954                        clearSelectedChip();
955                        mSelectedChip = selectChip(currentChip);
956                    } else if (mSelectedChip == null) {
957                        // Selection may have moved due to the tap event,
958                        // but make sure we correctly reset selection to the
959                        // end so that any unfinished chips are committed.
960                        setSelection(getText().length());
961                        commitDefault();
962                        mSelectedChip = selectChip(currentChip);
963                    } else {
964                        onClick(mSelectedChip, offset, x, y);
965                    }
966                }
967                chipWasSelected = true;
968                handled = true;
969            }
970        }
971        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
972            clearSelectedChip();
973        }
974        return handled;
975    }
976
977    private void scrollLineIntoView(int line) {
978        if (mScrollView != null) {
979            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
980        }
981    }
982
983    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
984            int width, Context context) {
985        int line = getLayout().getLineForOffset(getChipStart(currentChip));
986        int bottom = calculateOffsetFromBottom(line);
987        // Align the alternates popup with the left side of the View,
988        // regardless of the position of the chip tapped.
989        alternatesPopup.setWidth(width);
990        alternatesPopup.setAnchorView(this);
991        alternatesPopup.setVerticalOffset(bottom);
992        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
993        alternatesPopup.setOnItemClickListener(mAlternatesListener);
994        alternatesPopup.show();
995        ListView listView = alternatesPopup.getListView();
996        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
997        // Checked item would be -1 if the adapter has not
998        // loaded the view that should be checked yet. The
999        // variable will be set correctly when onCheckedItemChanged
1000        // is called in a separate thread.
1001        if (mCheckedItem != -1) {
1002            listView.setItemChecked(mCheckedItem, true);
1003            mCheckedItem = -1;
1004        }
1005    }
1006
1007    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
1008        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
1009                mAlternatesLayout, this);
1010    }
1011
1012    private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
1013        return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
1014                .getEntry());
1015    }
1016
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