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