RecipientEditTextView.java revision dbb8560594f297da570a4dc2c800eefe0faa6c16
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        String validatedToken = null;
747        if (mValidator != null && !mValidator.isValid(token)) {
748            // Try fixing up the entry using the validator.
749            validatedToken = mValidator.fixText(token).toString();
750            if (!TextUtils.isEmpty(validatedToken)) {
751                if (validatedToken.contains(token)) {
752                    // protect against the case of a validator with a null domain,
753                    // which doesn't add a domain to the token
754                    Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
755                    if (tokenized.length > 0) {
756                        validatedToken = tokenized[0].getAddress();
757                    }
758                } else {
759                    // We ran into a case where the token was invalid and removed
760                    // by the validator. In this case, just use the original token
761                    // and let the user sort out the error chip.
762                    validatedToken = null;
763                }
764            }
765        }
766        // Otherwise, fallback to just creating an editable email address chip.
767        return RecipientEntry
768                .constructFakeEntry(!TextUtils.isEmpty(validatedToken) ? validatedToken : token);
769    }
770
771    private boolean isValid(String text) {
772        return mValidator == null ? true : mValidator.isValid(text);
773    }
774
775    private String tokenizeAddress(String destination) {
776        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
777        if (tokens != null && tokens.length > 0) {
778            return tokens[0].getAddress();
779        }
780        return destination;
781    }
782
783    @Override
784    public void setTokenizer(Tokenizer tokenizer) {
785        mTokenizer = tokenizer;
786        super.setTokenizer(mTokenizer);
787    }
788
789    @Override
790    public void setValidator(Validator validator) {
791        mValidator = validator;
792        super.setValidator(validator);
793    }
794
795    /**
796     * We cannot use the default mechanism for replaceText. Instead,
797     * we override onItemClickListener so we can get all the associated
798     * contact information including display text, address, and id.
799     */
800    @Override
801    protected void replaceText(CharSequence text) {
802        return;
803    }
804
805    /**
806     * Dismiss any selected chips when the back key is pressed.
807     */
808    @Override
809    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
810        if (keyCode == KeyEvent.KEYCODE_BACK) {
811            clearSelectedChip();
812        }
813        return super.onKeyPreIme(keyCode, event);
814    }
815
816    /**
817     * Monitor key presses in this view to see if the user types
818     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
819     * If the user has entered text that has contact matches and types
820     * a commit key, create a chip from the topmost matching contact.
821     * If the user has entered text that has no contact matches and types
822     * a commit key, then create a chip from the text they have entered.
823     */
824    @Override
825    public boolean onKeyUp(int keyCode, KeyEvent event) {
826        switch (keyCode) {
827            case KeyEvent.KEYCODE_ENTER:
828            case KeyEvent.KEYCODE_DPAD_CENTER:
829                if (event.hasNoModifiers()) {
830                    if (commitDefault()) {
831                        return true;
832                    }
833                    if (mSelectedChip != null) {
834                        clearSelectedChip();
835                        return true;
836                    } else if (focusNext()) {
837                        return true;
838                    }
839                }
840                break;
841            case KeyEvent.KEYCODE_TAB:
842                if (event.hasNoModifiers()) {
843                    if (mSelectedChip != null) {
844                        clearSelectedChip();
845                    } else {
846                        commitDefault();
847                    }
848                    if (focusNext()) {
849                        return true;
850                    }
851                }
852        }
853        return super.onKeyUp(keyCode, event);
854    }
855
856    private boolean focusNext() {
857        View next = focusSearch(View.FOCUS_DOWN);
858        if (next != null) {
859            next.requestFocus();
860            return true;
861        }
862        return false;
863    }
864
865    /**
866     * Create a chip from the default selection. If the popup is showing, the
867     * default is the first item in the popup suggestions list. Otherwise, it is
868     * whatever the user had typed in. End represents where the the tokenizer
869     * should search for a token to turn into a chip.
870     * @return If a chip was created from a real contact.
871     */
872    private boolean commitDefault() {
873        Editable editable = getText();
874        int end = getSelectionEnd();
875        int start = mTokenizer.findTokenStart(editable, end);
876
877        if (shouldCreateChip(start, end)) {
878            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
879            // In the middle of chip; treat this as an edit
880            // and commit the whole token.
881            if (whatEnd != getSelectionEnd()) {
882                handleEdit(start, whatEnd);
883                return true;
884            }
885            return commitChip(start, end , editable);
886        }
887        return false;
888    }
889
890    private void commitByCharacter() {
891        Editable editable = getText();
892        int end = getSelectionEnd();
893        int start = mTokenizer.findTokenStart(editable, end);
894        if (shouldCreateChip(start, end)) {
895            commitChip(start, end, editable);
896        }
897        setSelection(getText().length());
898    }
899
900    private boolean commitChip(int start, int end, Editable editable) {
901        if (getAdapter().getCount() > 0 && enoughToFilter()) {
902            // choose the first entry.
903            submitItemAtPosition(0);
904            dismissDropDown();
905            return true;
906        } else {
907            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
908            String text = editable.toString().substring(start, tokenEnd).trim();
909            clearComposingText();
910            if (text != null && text.length() > 0 && !text.equals(" ")) {
911                RecipientEntry entry = createTokenizedEntry(text);
912                if (entry != null) {
913                    QwertyKeyListener.markAsReplaced(editable, start, end, "");
914                    CharSequence chipText = createChip(entry, false);
915                    if (chipText != null) {
916                        editable.replace(start, end, chipText);
917                    }
918                }
919                dismissDropDown();
920                return true;
921            }
922        }
923        return false;
924    }
925
926    private boolean shouldCreateChip(int start, int end) {
927        return hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
928    }
929
930    private boolean alreadyHasChip(int start, int end) {
931        RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
932        if ((chips == null || chips.length == 0)) {
933            return false;
934        }
935        return true;
936    }
937
938    private void handleEdit(int start, int end) {
939        if (start == -1 || end == -1) {
940            // This chip no longer exists in the field.
941            dismissDropDown();
942            return;
943        }
944        // This is in the middle of a chip, so select out the whole chip
945        // and commit it.
946        Editable editable = getText();
947        setSelection(end);
948        String text = getText().toString().substring(start, end);
949        if (!TextUtils.isEmpty(text)) {
950            RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
951            QwertyKeyListener.markAsReplaced(editable, start, end, "");
952            CharSequence chipText = createChip(entry, false);
953            editable.replace(start, getSelectionEnd(), chipText);
954        }
955        dismissDropDown();
956    }
957
958    /**
959     * If there is a selected chip, delegate the key events
960     * to the selected chip.
961     */
962    @Override
963    public boolean onKeyDown(int keyCode, KeyEvent event) {
964        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
965            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
966                mAlternatesPopup.dismiss();
967            }
968            removeChip(mSelectedChip);
969        }
970
971        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
972            return true;
973        }
974
975        return super.onKeyDown(keyCode, event);
976    }
977
978    private Spannable getSpannable() {
979        return getText();
980    }
981
982    private int getChipStart(RecipientChip chip) {
983        return getSpannable().getSpanStart(chip);
984    }
985
986    private int getChipEnd(RecipientChip chip) {
987        return getSpannable().getSpanEnd(chip);
988    }
989
990    /**
991     * Instead of filtering on the entire contents of the edit box,
992     * this subclass method filters on the range from
993     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
994     * if the length of that range meets or exceeds {@link #getThreshold}
995     * and makes sure that the range is not already a Chip.
996     */
997    @Override
998    protected void performFiltering(CharSequence text, int keyCode) {
999        if (enoughToFilter()) {
1000            int end = getSelectionEnd();
1001            int start = mTokenizer.findTokenStart(text, end);
1002            // If this is a RecipientChip, don't filter
1003            // on its contents.
1004            Spannable span = getSpannable();
1005            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
1006            if (chips != null && chips.length > 0) {
1007                return;
1008            }
1009        }
1010        super.performFiltering(text, keyCode);
1011    }
1012
1013    private void clearSelectedChip() {
1014        if (mSelectedChip != null) {
1015            unselectChip(mSelectedChip);
1016            mSelectedChip = null;
1017        }
1018        setCursorVisible(true);
1019    }
1020
1021    /**
1022     * Monitor touch events in the RecipientEditTextView.
1023     * If the view does not have focus, any tap on the view
1024     * will just focus the view. If the view has focus, determine
1025     * if the touch target is a recipient chip. If it is and the chip
1026     * is not selected, select it and clear any other selected chips.
1027     * If it isn't, then select that chip.
1028     */
1029    @Override
1030    public boolean onTouchEvent(MotionEvent event) {
1031        if (!isFocused()) {
1032            // Ignore any chip taps until this view is focused.
1033            return super.onTouchEvent(event);
1034        }
1035        boolean handled = super.onTouchEvent(event);
1036        int action = event.getAction();
1037        boolean chipWasSelected = false;
1038        if (mSelectedChip == null) {
1039            mGestureDetector.onTouchEvent(event);
1040        }
1041        if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
1042            float x = event.getX();
1043            float y = event.getY();
1044            int offset = putOffsetInRange(getOffsetForPosition(x, y));
1045            RecipientChip currentChip = findChip(offset);
1046            if (currentChip != null) {
1047                if (action == MotionEvent.ACTION_UP) {
1048                    if (mSelectedChip != null && mSelectedChip != currentChip) {
1049                        clearSelectedChip();
1050                        mSelectedChip = selectChip(currentChip);
1051                    } else if (mSelectedChip == null) {
1052                        setSelection(getText().length());
1053                        commitDefault();
1054                        mSelectedChip = selectChip(currentChip);
1055                    } else {
1056                        onClick(mSelectedChip, offset, x, y);
1057                    }
1058                }
1059                chipWasSelected = true;
1060                handled = true;
1061            } else if (mSelectedChip != null
1062                    && mSelectedChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1063                chipWasSelected = true;
1064            }
1065        }
1066        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1067            clearSelectedChip();
1068        }
1069        return handled;
1070    }
1071
1072    private void scrollLineIntoView(int line) {
1073        if (mScrollView != null) {
1074            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
1075        }
1076    }
1077
1078    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
1079            int width, Context context) {
1080        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1081        int bottom = calculateOffsetFromBottom(line);
1082        // Align the alternates popup with the left side of the View,
1083        // regardless of the position of the chip tapped.
1084        alternatesPopup.setWidth(width);
1085        setEnabled(false);
1086        alternatesPopup.setAnchorView(this);
1087        alternatesPopup.setVerticalOffset(bottom);
1088        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
1089        alternatesPopup.setOnItemClickListener(mAlternatesListener);
1090        // Clear the checked item.
1091        mCheckedItem = -1;
1092        alternatesPopup.show();
1093        ListView listView = alternatesPopup.getListView();
1094        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1095        // Checked item would be -1 if the adapter has not
1096        // loaded the view that should be checked yet. The
1097        // variable will be set correctly when onCheckedItemChanged
1098        // is called in a separate thread.
1099        if (mCheckedItem != -1) {
1100            listView.setItemChecked(mCheckedItem, true);
1101            mCheckedItem = -1;
1102        }
1103    }
1104
1105    // Dismiss listener for alterns and single address popup.
1106    @Override
1107    public void onDismiss() {
1108        setEnabled(true);
1109    }
1110
1111    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
1112        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
1113                mAlternatesLayout, this);
1114    }
1115
1116    private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
1117        return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
1118                .getEntry());
1119    }
1120
1121    @Override
1122    public void onCheckedItemChanged(int position) {
1123        ListView listView = mAlternatesPopup.getListView();
1124        if (listView != null && listView.getCheckedItemCount() == 0) {
1125            listView.setItemChecked(position, true);
1126        }
1127        mCheckedItem = position;
1128    }
1129
1130    // TODO: This algorithm will need a lot of tweaking after more people have used
1131    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1132    // what comes before the finger.
1133    private int putOffsetInRange(int o) {
1134        int offset = o;
1135        Editable text = getText();
1136        int length = text.length();
1137        // Remove whitespace from end to find "real end"
1138        int realLength = length;
1139        for (int i = length - 1; i >= 0; i--) {
1140            if (text.charAt(i) == ' ') {
1141                realLength--;
1142            } else {
1143                break;
1144            }
1145        }
1146
1147        // If the offset is beyond or at the end of the text,
1148        // leave it alone.
1149        if (offset >= realLength) {
1150            return offset;
1151        }
1152        Editable editable = getText();
1153        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1154            // Keep walking backward!
1155            offset--;
1156        }
1157        return offset;
1158    }
1159
1160    private int findText(Editable text, int offset) {
1161        if (text.charAt(offset) != ' ') {
1162            return offset;
1163        }
1164        return -1;
1165    }
1166
1167    private RecipientChip findChip(int offset) {
1168        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1169        // Find the chip that contains this offset.
1170        for (int i = 0; i < chips.length; i++) {
1171            RecipientChip chip = chips[i];
1172            int start = getChipStart(chip);
1173            int end = getChipEnd(chip);
1174            if (offset >= start && offset <= end) {
1175                return chip;
1176            }
1177        }
1178        return null;
1179    }
1180
1181    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1182        String displayText = entry.getDestination();
1183        displayText = (String) mTokenizer.terminateToken(displayText);
1184        // Always leave a blank space at the end of a chip.
1185        int textLength = displayText.length()-1;
1186        SpannableString chipText = new SpannableString(displayText);
1187        int end = getSelectionEnd();
1188        int start = mTokenizer.findTokenStart(getText(), end);
1189        try {
1190            RecipientChip chip = constructChipSpan(entry, start, pressed);
1191            chipText.setSpan(chip, 0, textLength,
1192                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1193            chip.setOriginalText(chipText.toString());
1194        } catch (NullPointerException e) {
1195            Log.e(TAG, e.getMessage(), e);
1196            return null;
1197        }
1198
1199        return chipText;
1200    }
1201
1202    /**
1203     * When an item in the suggestions list has been clicked, create a chip from the
1204     * contact information of the selected item.
1205     */
1206    @Override
1207    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1208        submitItemAtPosition(position);
1209    }
1210
1211    private void submitItemAtPosition(int position) {
1212        RecipientEntry entry = createValidatedEntry(
1213                (RecipientEntry)getAdapter().getItem(position));
1214        if (entry == null) {
1215            return;
1216        }
1217        clearComposingText();
1218
1219        int end = getSelectionEnd();
1220        int start = mTokenizer.findTokenStart(getText(), end);
1221
1222        Editable editable = getText();
1223        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1224        CharSequence chip = createChip(entry, false);
1225        if (chip != null) {
1226            editable.replace(start, end, chip);
1227        }
1228    }
1229
1230    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1231        if (item == null) {
1232            return null;
1233        }
1234        final RecipientEntry entry;
1235        // If the display name and the address are the same, or if this is a
1236        // valid contact, but the destination is invalid, then make this a fake
1237        // recipient that is editable.
1238        String destination = item.getDestination();
1239        if (TextUtils.isEmpty(item.getDisplayName())
1240                || TextUtils.equals(item.getDisplayName(), destination)
1241                || (mValidator != null && !mValidator.isValid(destination))) {
1242            entry = RecipientEntry.constructFakeEntry(destination);
1243        } else {
1244            entry = item;
1245        }
1246        return entry;
1247    }
1248
1249    /** Returns a collection of contact Id for each chip inside this View. */
1250    /* package */ Collection<Long> getContactIds() {
1251        final Set<Long> result = new HashSet<Long>();
1252        RecipientChip[] chips = getRecipients();
1253        if (chips != null) {
1254            for (RecipientChip chip : chips) {
1255                result.add(chip.getContactId());
1256            }
1257        }
1258        return result;
1259    }
1260
1261    private RecipientChip[] getRecipients() {
1262        return getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1263    }
1264
1265    private RecipientChip[] getSortedRecipients() {
1266        ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays
1267                .asList(getRecipients()));
1268        final Spannable spannable = getSpannable();
1269        Collections.sort(recipientsList, new Comparator<RecipientChip>() {
1270
1271            @Override
1272            public int compare(RecipientChip first, RecipientChip second) {
1273                int firstStart = spannable.getSpanStart(first);
1274                int secondStart = spannable.getSpanStart(second);
1275                if (firstStart < secondStart) {
1276                    return -1;
1277                } else if (firstStart > secondStart) {
1278                    return 1;
1279                } else {
1280                    return 0;
1281                }
1282            }
1283        });
1284        return recipientsList.toArray(new RecipientChip[recipientsList.size()]);
1285    }
1286
1287    /** Returns a collection of data Id for each chip inside this View. May be null. */
1288    /* package */ Collection<Long> getDataIds() {
1289        final Set<Long> result = new HashSet<Long>();
1290        RecipientChip [] chips = getRecipients();
1291        if (chips != null) {
1292            for (RecipientChip chip : chips) {
1293                result.add(chip.getDataId());
1294            }
1295        }
1296        return result;
1297    }
1298
1299
1300    @Override
1301    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1302        return false;
1303    }
1304
1305    @Override
1306    public void onDestroyActionMode(ActionMode mode) {
1307    }
1308
1309    @Override
1310    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1311        return false;
1312    }
1313
1314    /**
1315     * No chips are selectable.
1316     */
1317    @Override
1318    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1319        return false;
1320    }
1321
1322    /**
1323     * Create the more chip. The more chip is text that replaces any chips that
1324     * do not fit in the pre-defined available space when the
1325     * RecipientEditTextView loses focus.
1326     */
1327    private void createMoreChip() {
1328        if (!mShouldShrink) {
1329            return;
1330        }
1331
1332        ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
1333        if (tempMore.length > 0) {
1334            getSpannable().removeSpan(tempMore[0]);
1335        }
1336        RecipientChip[] recipients = getSortedRecipients();
1337        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1338            mMoreChip = null;
1339            return;
1340        }
1341        Spannable spannable = getSpannable();
1342        int numRecipients = recipients.length;
1343        int overage = numRecipients - CHIP_LIMIT;
1344        String moreText = String.format(mMoreItem.getText().toString(), overage);
1345        TextPaint morePaint = new TextPaint(getPaint());
1346        morePaint.setTextSize(mMoreItem.getTextSize());
1347        morePaint.setColor(mMoreItem.getCurrentTextColor());
1348        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1349                + mMoreItem.getPaddingRight();
1350        int height = getLineHeight();
1351        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1352        Canvas canvas = new Canvas(drawable);
1353        canvas.drawText(moreText, 0, moreText.length(), 0, height - getLayout().getLineDescent(0),
1354                morePaint);
1355
1356        Drawable result = new BitmapDrawable(getResources(), drawable);
1357        result.setBounds(0, 0, width, height);
1358        MoreImageSpan moreSpan = new MoreImageSpan(result);
1359        // Remove the overage chips.
1360        if (recipients == null || recipients.length == 0) {
1361            Log.w(TAG,
1362                    "We have recipients. Tt should not be possible to have zero RecipientChips.");
1363            mMoreChip = null;
1364            return;
1365        }
1366        mRemovedSpans = new ArrayList<RecipientChip>();
1367        int totalReplaceStart = 0;
1368        int totalReplaceEnd = 0;
1369        Editable text = getText();
1370        for (int i = numRecipients - overage; i < recipients.length; i++) {
1371            mRemovedSpans.add(recipients[i]);
1372            if (i == numRecipients - overage) {
1373                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1374            }
1375            if (i == recipients.length - 1) {
1376                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1377            }
1378            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
1379                int spanStart = spannable.getSpanStart(recipients[i]);
1380                int spanEnd = spannable.getSpanEnd(recipients[i]);
1381                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
1382            }
1383            spannable.removeSpan(recipients[i]);
1384        }
1385        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1386        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1387        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1388        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1389        text.replace(start, end, chipText);
1390        mMoreChip = moreSpan;
1391    }
1392
1393    /**
1394     * Replace the more chip, if it exists, with all of the recipient chips it had
1395     * replaced when the RecipientEditTextView gains focus.
1396     */
1397    private void removeMoreChip() {
1398        if (mMoreChip != null) {
1399            Spannable span = getSpannable();
1400            span.removeSpan(mMoreChip);
1401            mMoreChip = null;
1402            // Re-add the spans that were removed.
1403            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1404                // Recreate each removed span.
1405                RecipientChip[] recipients = getRecipients();
1406                // Start the search for tokens after the last currently visible
1407                // chip.
1408                int end = span.getSpanEnd(recipients[recipients.length - 1]);
1409                Editable editable = getText();
1410                for (RecipientChip chip : mRemovedSpans) {
1411                    int chipStart;
1412                    int chipEnd;
1413                    String token;
1414                    // Need to find the location of the chip, again.
1415                    token = (String) chip.getOriginalText();
1416                    // As we find the matching recipient for the remove spans,
1417                    // reduce the size of the string we need to search.
1418                    // That way, if there are duplicates, we always find the correct
1419                    // recipient.
1420                    chipStart = editable.toString().indexOf(token, end);
1421                    // -1 for the space!
1422                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
1423                    // Only set the span if we found a matching token.
1424                    if (chipStart != -1) {
1425                        editable.setSpan(chip, chipStart, chipEnd,
1426                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1427                    }
1428                }
1429                mRemovedSpans.clear();
1430            }
1431        }
1432    }
1433
1434    /**
1435     * Show specified chip as selected. If the RecipientChip is just an email address,
1436     * selecting the chip will take the contents of the chip and place it at
1437     * the end of the RecipientEditTextView for inline editing. If the
1438     * RecipientChip is a complete contact, then selecting the chip
1439     * will change the background color of the chip, show the delete icon,
1440     * and a popup window with the address in use highlighted and any other
1441     * alternate addresses for the contact.
1442     * @param currentChip Chip to select.
1443     * @return A RecipientChip in the selected state or null if the chip
1444     * just contained an email address.
1445     */
1446    public RecipientChip selectChip(RecipientChip currentChip) {
1447        if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1448            CharSequence text = currentChip.getValue();
1449            Editable editable = getText();
1450            removeChip(currentChip);
1451            editable.append(text);
1452            setCursorVisible(true);
1453            setSelection(editable.length());
1454            return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1);
1455        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1456            int start = getChipStart(currentChip);
1457            int end = getChipEnd(currentChip);
1458            getSpannable().removeSpan(currentChip);
1459            RecipientChip newChip;
1460            try {
1461                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1462            } catch (NullPointerException e) {
1463                Log.e(TAG, e.getMessage(), e);
1464                return null;
1465            }
1466            Editable editable = getText();
1467            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1468            if (start == -1 || end == -1) {
1469                Log.d(TAG, "The chip being selected no longer exists but should.");
1470            } else {
1471                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1472            }
1473            newChip.setSelected(true);
1474            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1475                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1476            }
1477            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1478            setCursorVisible(false);
1479            return newChip;
1480        } else {
1481            int start = getChipStart(currentChip);
1482            int end = getChipEnd(currentChip);
1483            getSpannable().removeSpan(currentChip);
1484            RecipientChip newChip;
1485            try {
1486                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1487            } catch (NullPointerException e) {
1488                Log.e(TAG, e.getMessage(), e);
1489                return null;
1490            }
1491            Editable editable = getText();
1492            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1493            if (start == -1 || end == -1) {
1494                Log.d(TAG, "The chip being selected no longer exists but should.");
1495            } else {
1496                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1497            }
1498            newChip.setSelected(true);
1499            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1500                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1501            }
1502            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1503            setCursorVisible(false);
1504            return newChip;
1505        }
1506    }
1507
1508
1509    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
1510            int width, Context context) {
1511        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1512        int bottom = calculateOffsetFromBottom(line);
1513        // Align the alternates popup with the left side of the View,
1514        // regardless of the position of the chip tapped.
1515        setEnabled(false);
1516        popup.setWidth(width);
1517        popup.setAnchorView(this);
1518        popup.setVerticalOffset(bottom);
1519        popup.setAdapter(createSingleAddressAdapter(currentChip));
1520        popup.setOnItemClickListener(new OnItemClickListener() {
1521            @Override
1522            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1523                unselectChip(currentChip);
1524                popup.dismiss();
1525            }
1526        });
1527        popup.show();
1528        ListView listView = popup.getListView();
1529        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1530        listView.setItemChecked(0, true);
1531    }
1532
1533    /**
1534     * Remove selection from this chip. Unselecting a RecipientChip will render
1535     * the chip without a delete icon and with an unfocused background. This
1536     * is called when the RecipientChip no longer has focus.
1537     */
1538    public void unselectChip(RecipientChip chip) {
1539        int start = getChipStart(chip);
1540        int end = getChipEnd(chip);
1541        Editable editable = getText();
1542        mSelectedChip = null;
1543        if (start == -1 || end == -1) {
1544            Log.w(TAG,
1545                    "The chip doesn't exist or may be a chip a user was editing");
1546            setSelection(editable.length());
1547            commitDefault();
1548        } else {
1549            getSpannable().removeSpan(chip);
1550            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1551            editable.removeSpan(chip);
1552            try {
1553                editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1554                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1555            } catch (NullPointerException e) {
1556                Log.e(TAG, e.getMessage(), e);
1557            }
1558        }
1559        setCursorVisible(true);
1560        setSelection(editable.length());
1561        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1562            mAlternatesPopup.dismiss();
1563        }
1564    }
1565
1566    /**
1567     * Return whether this chip contains the position passed in.
1568     */
1569    public boolean matchesChip(RecipientChip chip, int offset) {
1570        int start = getChipStart(chip);
1571        int end = getChipEnd(chip);
1572        if (start == -1 || end == -1) {
1573            return false;
1574        }
1575        return (offset >= start && offset <= end);
1576    }
1577
1578
1579    /**
1580     * Return whether a touch event was inside the delete target of
1581     * a selected chip. It is in the delete target if:
1582     * 1) the x and y points of the event are within the
1583     * delete assset.
1584     * 2) the point tapped would have caused a cursor to appear
1585     * right after the selected chip.
1586     * @return boolean
1587     */
1588    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1589        // Figure out the bounds of this chip and whether or not
1590        // the user clicked in the X portion.
1591        return chip.isSelected() && offset == getChipEnd(chip);
1592    }
1593
1594    /**
1595     * Remove the chip and any text associated with it from the RecipientEditTextView.
1596     */
1597    private void removeChip(RecipientChip chip) {
1598        Spannable spannable = getSpannable();
1599        int spanStart = spannable.getSpanStart(chip);
1600        int spanEnd = spannable.getSpanEnd(chip);
1601        Editable text = getText();
1602        int toDelete = spanEnd;
1603        boolean wasSelected = chip == mSelectedChip;
1604        // Clear that there is a selected chip before updating any text.
1605        if (wasSelected) {
1606            mSelectedChip = null;
1607        }
1608        // Always remove trailing spaces when removing a chip.
1609        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
1610            toDelete++;
1611        }
1612        spannable.removeSpan(chip);
1613        text.delete(spanStart, toDelete);
1614        if (wasSelected) {
1615            clearSelectedChip();
1616        }
1617    }
1618
1619    /**
1620     * Replace this currently selected chip with a new chip
1621     * that uses the contact data provided.
1622     */
1623    public void replaceChip(RecipientChip chip, RecipientEntry entry) {
1624        boolean wasSelected = chip == mSelectedChip;
1625        if (wasSelected) {
1626            mSelectedChip = null;
1627        }
1628        int start = getChipStart(chip);
1629        int end = getChipEnd(chip);
1630        getSpannable().removeSpan(chip);
1631        Editable editable = getText();
1632        CharSequence chipText = createChip(entry, false);
1633        if (start == -1 || end == -1) {
1634            Log.e(TAG, "The chip to replace does not exist but should.");
1635            editable.insert(0, chipText);
1636        } else {
1637            // There may be a space to replace with this chip's new associated
1638            // space. Check for it.
1639            int toReplace = end;
1640            while (toReplace >= 0 && toReplace < editable.length()
1641                    && editable.charAt(toReplace) == ' ') {
1642                toReplace++;
1643            }
1644            editable.replace(start, toReplace, chipText);
1645        }
1646        setCursorVisible(true);
1647        if (wasSelected) {
1648            clearSelectedChip();
1649        }
1650    }
1651
1652    /**
1653     * Handle click events for a chip. When a selected chip receives a click
1654     * event, see if that event was in the delete icon. If so, delete it.
1655     * Otherwise, unselect the chip.
1656     */
1657    public void onClick(RecipientChip chip, int offset, float x, float y) {
1658        if (chip.isSelected()) {
1659            if (isInDelete(chip, offset, x, y)) {
1660                removeChip(chip);
1661            } else {
1662                clearSelectedChip();
1663            }
1664        }
1665    }
1666
1667    private boolean chipsPending() {
1668        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1669    }
1670
1671    @Override
1672    public void removeTextChangedListener(TextWatcher watcher) {
1673        mTextWatcher = null;
1674        super.removeTextChangedListener(watcher);
1675    }
1676
1677    private class RecipientTextWatcher implements TextWatcher {
1678        @Override
1679        public void afterTextChanged(Editable s) {
1680            // If the text has been set to null or empty, make sure we remove
1681            // all the spans we applied.
1682            if (TextUtils.isEmpty(s)) {
1683                // Remove all the chips spans.
1684                Spannable spannable = getSpannable();
1685                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
1686                        RecipientChip.class);
1687                for (RecipientChip chip : chips) {
1688                    spannable.removeSpan(chip);
1689                }
1690                if (mMoreChip != null) {
1691                    spannable.removeSpan(mMoreChip);
1692                }
1693                return;
1694            }
1695            // Get whether there are any recipients pending addition to the
1696            // view. If there are, don't do anything in the text watcher.
1697            if (chipsPending()) {
1698                return;
1699            }
1700            // If the user is editing a chip, don't clear it.
1701            if (mSelectedChip != null
1702                    && mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) {
1703                setCursorVisible(true);
1704                setSelection(getText().length());
1705                clearSelectedChip();
1706            }
1707            int length = s.length();
1708            // Make sure there is content there to parse and that it is
1709            // not just the commit character.
1710            if (length > 1) {
1711                char last;
1712                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
1713                int len = length() - 1;
1714                if (end != len) {
1715                    last = s.charAt(end);
1716                } else {
1717                    last = s.charAt(len);
1718                }
1719                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
1720                    commitByCharacter();
1721                } else if (last == COMMIT_CHAR_SPACE) {
1722                    // Check if this is a valid email address. If it is,
1723                    // commit it.
1724                    String text = getText().toString();
1725                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1726                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
1727                            tokenStart));
1728                    if (!TextUtils.isEmpty(sub) && mValidator != null && mValidator.isValid(sub)) {
1729                        commitByCharacter();
1730                    }
1731                }
1732            }
1733        }
1734
1735        @Override
1736        public void onTextChanged(CharSequence s, int start, int before, int count) {
1737            // Do nothing.
1738        }
1739
1740        @Override
1741        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1742        }
1743    }
1744
1745    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
1746        private RecipientChip createFreeChip(RecipientEntry entry) {
1747            String displayText = entry.getDestination();
1748            if (displayText.indexOf(",") == -1) {
1749                displayText = (String) mTokenizer.terminateToken(displayText);
1750            }
1751            try {
1752                return constructChipSpan(entry, -1, false);
1753            } catch (NullPointerException e) {
1754                Log.e(TAG, e.getMessage(), e);
1755                return null;
1756            }
1757        }
1758
1759        @Override
1760        protected Void doInBackground(Void... params) {
1761            if (mIndividualReplacements != null) {
1762                mIndividualReplacements.cancel(true);
1763            }
1764            // For each chip in the list, look up the matching contact.
1765            // If there is a match, replace that chip with the matching
1766            // chip.
1767            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
1768            RecipientChip[] existingChips = getSortedRecipients();
1769            for (int i = 0; i < existingChips.length; i++) {
1770                originalRecipients.add(existingChips[i]);
1771            }
1772            if (mRemovedSpans != null) {
1773                originalRecipients.addAll(mRemovedSpans);
1774            }
1775            String[] addresses = new String[originalRecipients.size()];
1776            for (int i = 0; i < originalRecipients.size(); i++) {
1777                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1778            }
1779            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1780                    .getMatchingRecipients(getContext(), addresses);
1781            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
1782            for (final RecipientChip temp : originalRecipients) {
1783                RecipientEntry entry = null;
1784                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
1785                        && getSpannable().getSpanStart(temp) != -1) {
1786                    // Replace this.
1787                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
1788                            .getDestination())));
1789                }
1790                if (entry != null) {
1791                    replacements.add(createFreeChip(entry));
1792                } else {
1793                    replacements.add(temp);
1794                }
1795            }
1796            if (replacements != null && replacements.size() > 0) {
1797                mHandler.post(new Runnable() {
1798                    @Override
1799                    public void run() {
1800                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
1801                                .toString());
1802                        Editable oldText = getText();
1803                        int start, end;
1804                        int i = 0;
1805                        for (RecipientChip chip : originalRecipients) {
1806                            start = oldText.getSpanStart(chip);
1807                            if (start != -1) {
1808                                end = oldText.getSpanEnd(chip);
1809                                text.removeSpan(chip);
1810                                // Leave a spot for the space!
1811                                RecipientChip replacement = replacements.get(i);
1812                                text.setSpan(replacement, start, end,
1813                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1814                                replacement.setOriginalText(text.toString().substring(start, end));
1815                            }
1816                            i++;
1817                        }
1818                        Editable editable = getText();
1819                        editable.clear();
1820                        editable.insert(0, text);
1821                        originalRecipients.clear();
1822                    }
1823                });
1824            }
1825            return null;
1826        }
1827    }
1828
1829    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
1830        @SuppressWarnings("unchecked")
1831        @Override
1832        protected Void doInBackground(Object... params) {
1833            // For each chip in the list, look up the matching contact.
1834            // If there is a match, replace that chip with the matching
1835            // chip.
1836            final ArrayList<RecipientChip> originalRecipients =
1837                (ArrayList<RecipientChip>) params[0];
1838            String[] addresses = new String[originalRecipients.size()];
1839            for (int i = 0; i < originalRecipients.size(); i++) {
1840                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1841            }
1842            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1843                    .getMatchingRecipients(getContext(), addresses);
1844            for (final RecipientChip temp : originalRecipients) {
1845                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
1846                        && getSpannable().getSpanStart(temp) != -1) {
1847                    // Replace this.
1848                    final RecipientEntry entry = createValidatedEntry(entries
1849                            .get(tokenizeAddress(temp.getEntry().getDestination())));
1850                    if (entry != null) {
1851                        mHandler.post(new Runnable() {
1852                            @Override
1853                            public void run() {
1854                                replaceChip(temp, entry);
1855                            }
1856                        });
1857                    }
1858                }
1859            }
1860            return null;
1861        }
1862    }
1863
1864
1865    /**
1866     * MoreImageSpan is a simple class created for tracking the existence of a
1867     * more chip across activity restarts/
1868     */
1869    private class MoreImageSpan extends ImageSpan {
1870        public MoreImageSpan(Drawable b) {
1871            super(b);
1872        }
1873    }
1874
1875    @Override
1876    public boolean onDown(MotionEvent e) {
1877        return false;
1878    }
1879
1880    @Override
1881    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
1882        // Do nothing.
1883        return false;
1884    }
1885
1886    @Override
1887    public void onLongPress(MotionEvent event) {
1888        if (mSelectedChip != null) {
1889            return;
1890        }
1891        float x = event.getX();
1892        float y = event.getY();
1893        int offset = putOffsetInRange(getOffsetForPosition(x, y));
1894        RecipientChip currentChip = findChip(offset);
1895        if (currentChip != null) {
1896            // Copy the selected chip email address.
1897            showCopyDialog(currentChip.getEntry().getDestination());
1898        }
1899    }
1900
1901    private void showCopyDialog(final String address) {
1902        mCopyAddress = address;
1903        mCopyDialog.setTitle(address);
1904        mCopyDialog.setContentView(mCopyViewRes);
1905        mCopyDialog.setCancelable(true);
1906        mCopyDialog.setCanceledOnTouchOutside(true);
1907        mCopyDialog.findViewById(android.R.id.button1).setOnClickListener(this);
1908        mCopyDialog.setOnDismissListener(this);
1909        mCopyDialog.show();
1910    }
1911
1912    @Override
1913    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
1914        // Do nothing.
1915        return false;
1916    }
1917
1918    @Override
1919    public void onShowPress(MotionEvent e) {
1920        // Do nothing.
1921    }
1922
1923    @Override
1924    public boolean onSingleTapUp(MotionEvent e) {
1925        // Do nothing.
1926        return false;
1927    }
1928
1929    @Override
1930    public void onDismiss(DialogInterface dialog) {
1931        mCopyAddress = null;
1932    }
1933
1934    @Override
1935    public void onClick(View v) {
1936        // Copy this to the clipboard.
1937        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
1938                Context.CLIPBOARD_SERVICE);
1939        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
1940        mCopyDialog.dismiss();
1941    }
1942}
1943