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