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