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