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