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