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