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