RecipientEditTextView.java revision 32aff5f5bdc7c860169e50eacb7120983b3901a8
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        // Don't sanitize while we are waiting for pending chips to complete.
785        if (mPendingChipsCount > 0) {
786            return;
787        }
788        // Find the last chip; eliminate any commit characters after it.
789        RecipientChip[] chips = getSortedRecipients();
790        if (chips != null && chips.length > 0) {
791            int end;
792            ImageSpan lastSpan;
793            mMoreChip = getMoreChip();
794            if (mMoreChip != null) {
795                lastSpan = mMoreChip;
796            } else {
797                lastSpan = getLastChip();
798            }
799            end = getSpannable().getSpanEnd(lastSpan);
800            Editable editable = getText();
801            int length = editable.length();
802            if (length > end) {
803                // See what characters occur after that and eliminate them.
804                if (Log.isLoggable(TAG, Log.DEBUG)) {
805                    Log.d(TAG, "There were extra characters after the last tokenizable entry."
806                            + editable);
807                }
808                editable.delete(end + 1, length);
809            }
810        }
811    }
812
813    /**
814     * Create a chip that represents just the email address of a recipient. At some later
815     * point, this chip will be attached to a real contact entry, if one exists.
816     */
817    private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) {
818        if (alreadyHasChip(tokenStart, tokenEnd)) {
819            // There is already a chip present at this location.
820            // Don't recreate it.
821            return;
822        }
823        String token = editable.toString().substring(tokenStart, tokenEnd);
824        int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA);
825        if (commitCharIndex == token.length() - 1) {
826            token = token.substring(0, token.length() - 1);
827        }
828        RecipientEntry entry = createTokenizedEntry(token);
829        if (entry != null) {
830            String destText = createAddressText(entry);
831            // Always leave a blank space at the end of a chip.
832            int textLength = destText.length() - 1;
833            SpannableString chipText = new SpannableString(destText);
834            int end = getSelectionEnd();
835            int start = mTokenizer != null ? mTokenizer.findTokenStart(getText(), end) : 0;
836            RecipientChip chip = null;
837            try {
838                if (!mNoChips) {
839                    chip = constructChipSpan(entry, start, false);
840                    chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
841                }
842            } catch (NullPointerException e) {
843                Log.e(TAG, e.getMessage(), e);
844            }
845            editable.replace(tokenStart, tokenEnd, chipText);
846            // Add this chip to the list of entries "to replace"
847            if (chip != null) {
848                if (mTemporaryRecipients == null) {
849                    mTemporaryRecipients = new ArrayList<RecipientChip>();
850                }
851                chip.setOriginalText(chipText.toString());
852                mTemporaryRecipients.add(chip);
853            }
854        }
855    }
856
857    private RecipientEntry createTokenizedEntry(String token) {
858        if (TextUtils.isEmpty(token)) {
859            return null;
860        }
861        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
862        String display = null;
863        if (isValid(token) && tokens != null && tokens.length > 0) {
864            // If we can get a name from tokenizing, then generate an entry from
865            // this.
866            display = tokens[0].getName();
867            if (!TextUtils.isEmpty(display)) {
868                return RecipientEntry.constructGeneratedEntry(display, token);
869            } else {
870                display = tokens[0].getAddress();
871                if (!TextUtils.isEmpty(display)) {
872                    return RecipientEntry.constructFakeEntry(display);
873                }
874            }
875        }
876        // Unable to validate the token or to create a valid token from it.
877        // Just create a chip the user can edit.
878        String validatedToken = null;
879        if (mValidator != null && !mValidator.isValid(token)) {
880            // Try fixing up the entry using the validator.
881            validatedToken = mValidator.fixText(token).toString();
882            if (!TextUtils.isEmpty(validatedToken)) {
883                if (validatedToken.contains(token)) {
884                    // protect against the case of a validator with a null domain,
885                    // which doesn't add a domain to the token
886                    Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
887                    if (tokenized.length > 0) {
888                        validatedToken = tokenized[0].getAddress();
889                    }
890                } else {
891                    // We ran into a case where the token was invalid and removed
892                    // by the validator. In this case, just use the original token
893                    // and let the user sort out the error chip.
894                    validatedToken = null;
895                }
896            }
897        }
898        // Otherwise, fallback to just creating an editable email address chip.
899        return RecipientEntry
900                .constructFakeEntry(!TextUtils.isEmpty(validatedToken) ? validatedToken : token);
901    }
902
903    private boolean isValid(String text) {
904        return mValidator == null ? true : mValidator.isValid(text);
905    }
906
907    private String tokenizeAddress(String destination) {
908        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
909        if (tokens != null && tokens.length > 0) {
910            return tokens[0].getAddress();
911        }
912        return destination;
913    }
914
915    @Override
916    public void setTokenizer(Tokenizer tokenizer) {
917        mTokenizer = tokenizer;
918        super.setTokenizer(mTokenizer);
919    }
920
921    @Override
922    public void setValidator(Validator validator) {
923        mValidator = validator;
924        super.setValidator(validator);
925    }
926
927    /**
928     * We cannot use the default mechanism for replaceText. Instead,
929     * we override onItemClickListener so we can get all the associated
930     * contact information including display text, address, and id.
931     */
932    @Override
933    protected void replaceText(CharSequence text) {
934        return;
935    }
936
937    /**
938     * Dismiss any selected chips when the back key is pressed.
939     */
940    @Override
941    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
942        if (keyCode == KeyEvent.KEYCODE_BACK) {
943            clearSelectedChip();
944        }
945        return super.onKeyPreIme(keyCode, event);
946    }
947
948    /**
949     * Monitor key presses in this view to see if the user types
950     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
951     * If the user has entered text that has contact matches and types
952     * a commit key, create a chip from the topmost matching contact.
953     * If the user has entered text that has no contact matches and types
954     * a commit key, then create a chip from the text they have entered.
955     */
956    @Override
957    public boolean onKeyUp(int keyCode, KeyEvent event) {
958        switch (keyCode) {
959            case KeyEvent.KEYCODE_ENTER:
960            case KeyEvent.KEYCODE_DPAD_CENTER:
961                if (event.hasNoModifiers()) {
962                    if (commitDefault()) {
963                        return true;
964                    }
965                    if (mSelectedChip != null) {
966                        clearSelectedChip();
967                        return true;
968                    } else if (focusNext()) {
969                        return true;
970                    }
971                }
972                break;
973            case KeyEvent.KEYCODE_TAB:
974                if (event.hasNoModifiers()) {
975                    if (mSelectedChip != null) {
976                        clearSelectedChip();
977                    } else {
978                        commitDefault();
979                    }
980                    if (focusNext()) {
981                        return true;
982                    }
983                }
984        }
985        return super.onKeyUp(keyCode, event);
986    }
987
988    private boolean focusNext() {
989        View next = focusSearch(View.FOCUS_DOWN);
990        if (next != null) {
991            next.requestFocus();
992            return true;
993        }
994        return false;
995    }
996
997    /**
998     * Create a chip from the default selection. If the popup is showing, the
999     * default is the first item in the popup suggestions list. Otherwise, it is
1000     * whatever the user had typed in. End represents where the the tokenizer
1001     * should search for a token to turn into a chip.
1002     * @return If a chip was created from a real contact.
1003     */
1004    private boolean commitDefault() {
1005        Editable editable = getText();
1006        int end = getSelectionEnd();
1007        int start = mTokenizer.findTokenStart(editable, end);
1008
1009        if (shouldCreateChip(start, end)) {
1010            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
1011            // In the middle of chip; treat this as an edit
1012            // and commit the whole token.
1013            if (whatEnd != getSelectionEnd()) {
1014                handleEdit(start, whatEnd);
1015                return true;
1016            }
1017            return commitChip(start, end , editable);
1018        }
1019        return false;
1020    }
1021
1022    private void commitByCharacter() {
1023        Editable editable = getText();
1024        int end = getSelectionEnd();
1025        int start = mTokenizer.findTokenStart(editable, end);
1026        if (shouldCreateChip(start, end)) {
1027            commitChip(start, end, editable);
1028        }
1029        setSelection(getText().length());
1030    }
1031
1032    private boolean commitChip(int start, int end, Editable editable) {
1033        ListAdapter adapter = getAdapter();
1034        if (adapter != null && adapter.getCount() > 0 && enoughToFilter()
1035                && end == getSelectionEnd()) {
1036            // choose the first entry.
1037            submitItemAtPosition(0);
1038            dismissDropDown();
1039            return true;
1040        } else {
1041            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
1042            if (editable.length() > tokenEnd + 1) {
1043                char charAt = editable.charAt(tokenEnd + 1);
1044                if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
1045                    tokenEnd++;
1046                }
1047            }
1048            String text = editable.toString().substring(start, tokenEnd).trim();
1049            clearComposingText();
1050            if (text != null && text.length() > 0 && !text.equals(" ")) {
1051                RecipientEntry entry = createTokenizedEntry(text);
1052                if (entry != null) {
1053                    QwertyKeyListener.markAsReplaced(editable, start, end, "");
1054                    CharSequence chipText = createChip(entry, false);
1055                    if (chipText != null && start > -1 && end > -1) {
1056                        editable.replace(start, end, chipText);
1057                    }
1058                }
1059                // Only dismiss the dropdown if it is related to the text we
1060                // just committed.
1061                // For paste, it may not be as there are possibly multiple
1062                // tokens being added.
1063                if (end == getSelectionEnd()) {
1064                    dismissDropDown();
1065                }
1066                sanitizeBetween();
1067                return true;
1068            }
1069        }
1070        return false;
1071    }
1072
1073    // Visible for testing.
1074    /* package */ void sanitizeBetween() {
1075        // Don't sanitize while we are waiting for content to chipify.
1076        if (mPendingChipsCount > 0) {
1077            return;
1078        }
1079        // Find the last chip.
1080        RecipientChip[] recips = getSortedRecipients();
1081        if (recips != null && recips.length > 0) {
1082            RecipientChip last = recips[recips.length - 1];
1083            RecipientChip beforeLast = null;
1084            if (recips.length > 1) {
1085                beforeLast = recips[recips.length - 2];
1086            }
1087            int startLooking = 0;
1088            int end = getSpannable().getSpanStart(last);
1089            if (beforeLast != null) {
1090                startLooking = getSpannable().getSpanEnd(beforeLast);
1091                Editable text = getText();
1092                if (startLooking == -1 || startLooking > text.length() - 1) {
1093                    // There is nothing after this chip.
1094                    return;
1095                }
1096                if (text.charAt(startLooking) == ' ') {
1097                    startLooking++;
1098                }
1099            }
1100            if (startLooking >= 0 && end >= 0 && startLooking < end) {
1101                getText().delete(startLooking, end);
1102            }
1103        }
1104    }
1105
1106    private boolean shouldCreateChip(int start, int end) {
1107        return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
1108    }
1109
1110    private boolean alreadyHasChip(int start, int end) {
1111        if (mNoChips) {
1112            return true;
1113        }
1114        RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
1115        if ((chips == null || chips.length == 0)) {
1116            return false;
1117        }
1118        return true;
1119    }
1120
1121    private void handleEdit(int start, int end) {
1122        if (start == -1 || end == -1) {
1123            // This chip no longer exists in the field.
1124            dismissDropDown();
1125            return;
1126        }
1127        // This is in the middle of a chip, so select out the whole chip
1128        // and commit it.
1129        Editable editable = getText();
1130        setSelection(end);
1131        String text = getText().toString().substring(start, end);
1132        if (!TextUtils.isEmpty(text)) {
1133            RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
1134            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1135            CharSequence chipText = createChip(entry, false);
1136            int selEnd = getSelectionEnd();
1137            if (chipText != null && start > -1 && selEnd > -1) {
1138                editable.replace(start, selEnd, chipText);
1139            }
1140        }
1141        dismissDropDown();
1142    }
1143
1144    /**
1145     * If there is a selected chip, delegate the key events
1146     * to the selected chip.
1147     */
1148    @Override
1149    public boolean onKeyDown(int keyCode, KeyEvent event) {
1150        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
1151            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1152                mAlternatesPopup.dismiss();
1153            }
1154            removeChip(mSelectedChip);
1155        }
1156
1157        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
1158            return true;
1159        }
1160
1161        return super.onKeyDown(keyCode, event);
1162    }
1163
1164    // Visible for testing.
1165    /* package */ Spannable getSpannable() {
1166        return getText();
1167    }
1168
1169    private int getChipStart(RecipientChip chip) {
1170        return getSpannable().getSpanStart(chip);
1171    }
1172
1173    private int getChipEnd(RecipientChip chip) {
1174        return getSpannable().getSpanEnd(chip);
1175    }
1176
1177    /**
1178     * Instead of filtering on the entire contents of the edit box,
1179     * this subclass method filters on the range from
1180     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
1181     * if the length of that range meets or exceeds {@link #getThreshold}
1182     * and makes sure that the range is not already a Chip.
1183     */
1184    @Override
1185    protected void performFiltering(CharSequence text, int keyCode) {
1186        if (enoughToFilter() && !isCompletedToken(text)) {
1187            int end = getSelectionEnd();
1188            int start = mTokenizer.findTokenStart(text, end);
1189            // If this is a RecipientChip, don't filter
1190            // on its contents.
1191            Spannable span = getSpannable();
1192            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
1193            if (chips != null && chips.length > 0) {
1194                return;
1195            }
1196        }
1197        super.performFiltering(text, keyCode);
1198    }
1199
1200    // Visible for testing.
1201    /*package*/ boolean isCompletedToken(CharSequence text) {
1202        if (TextUtils.isEmpty(text)) {
1203            return false;
1204        }
1205        // Check to see if this is a completed token before filtering.
1206        int end = text.length();
1207        int start = mTokenizer.findTokenStart(text, end);
1208        String token = text.toString().substring(start, end).trim();
1209        if (!TextUtils.isEmpty(token)) {
1210            char atEnd = token.charAt(token.length() - 1);
1211            return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
1212        }
1213        return false;
1214    }
1215
1216    private void clearSelectedChip() {
1217        if (mSelectedChip != null) {
1218            unselectChip(mSelectedChip);
1219            mSelectedChip = null;
1220        }
1221        setCursorVisible(true);
1222    }
1223
1224    /**
1225     * Monitor touch events in the RecipientEditTextView.
1226     * If the view does not have focus, any tap on the view
1227     * will just focus the view. If the view has focus, determine
1228     * if the touch target is a recipient chip. If it is and the chip
1229     * is not selected, select it and clear any other selected chips.
1230     * If it isn't, then select that chip.
1231     */
1232    @Override
1233    public boolean onTouchEvent(MotionEvent event) {
1234        if (!isFocused()) {
1235            // Ignore any chip taps until this view is focused.
1236            return super.onTouchEvent(event);
1237        }
1238        boolean handled = super.onTouchEvent(event);
1239        int action = event.getAction();
1240        boolean chipWasSelected = false;
1241        if (mSelectedChip == null) {
1242            mGestureDetector.onTouchEvent(event);
1243        }
1244        if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
1245            float x = event.getX();
1246            float y = event.getY();
1247            int offset = putOffsetInRange(getOffsetForPosition(x, y));
1248            RecipientChip currentChip = findChip(offset);
1249            if (currentChip != null) {
1250                if (action == MotionEvent.ACTION_UP) {
1251                    if (mSelectedChip != null && mSelectedChip != currentChip) {
1252                        clearSelectedChip();
1253                        mSelectedChip = selectChip(currentChip);
1254                    } else if (mSelectedChip == null) {
1255                        setSelection(getText().length());
1256                        commitDefault();
1257                        mSelectedChip = selectChip(currentChip);
1258                    } else {
1259                        onClick(mSelectedChip, offset, x, y);
1260                    }
1261                }
1262                chipWasSelected = true;
1263                handled = true;
1264            } else if (mSelectedChip != null
1265                    && mSelectedChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1266                chipWasSelected = true;
1267            }
1268        }
1269        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1270            clearSelectedChip();
1271        }
1272        return handled;
1273    }
1274
1275    private void scrollLineIntoView(int line) {
1276        if (mScrollView != null) {
1277            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
1278        }
1279    }
1280
1281    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
1282            int width, Context context) {
1283        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1284        int bottom = calculateOffsetFromBottom(line);
1285        // Align the alternates popup with the left side of the View,
1286        // regardless of the position of the chip tapped.
1287        alternatesPopup.setWidth(width);
1288        setEnabled(false);
1289        alternatesPopup.setAnchorView(this);
1290        alternatesPopup.setVerticalOffset(bottom);
1291        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
1292        alternatesPopup.setOnItemClickListener(mAlternatesListener);
1293        // Clear the checked item.
1294        mCheckedItem = -1;
1295        alternatesPopup.show();
1296        ListView listView = alternatesPopup.getListView();
1297        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1298        // Checked item would be -1 if the adapter has not
1299        // loaded the view that should be checked yet. The
1300        // variable will be set correctly when onCheckedItemChanged
1301        // is called in a separate thread.
1302        if (mCheckedItem != -1) {
1303            listView.setItemChecked(mCheckedItem, true);
1304            mCheckedItem = -1;
1305        }
1306    }
1307
1308    // Dismiss listener for alterns and single address popup.
1309    @Override
1310    public void onDismiss() {
1311        setEnabled(true);
1312    }
1313
1314    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
1315        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
1316                mAlternatesLayout, this);
1317    }
1318
1319    private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
1320        return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
1321                .getEntry());
1322    }
1323
1324    @Override
1325    public void onCheckedItemChanged(int position) {
1326        ListView listView = mAlternatesPopup.getListView();
1327        if (listView != null && listView.getCheckedItemCount() == 0) {
1328            listView.setItemChecked(position, true);
1329        }
1330        mCheckedItem = position;
1331    }
1332
1333    // TODO: This algorithm will need a lot of tweaking after more people have used
1334    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1335    // what comes before the finger.
1336    private int putOffsetInRange(int o) {
1337        int offset = o;
1338        Editable text = getText();
1339        int length = text.length();
1340        // Remove whitespace from end to find "real end"
1341        int realLength = length;
1342        for (int i = length - 1; i >= 0; i--) {
1343            if (text.charAt(i) == ' ') {
1344                realLength--;
1345            } else {
1346                break;
1347            }
1348        }
1349
1350        // If the offset is beyond or at the end of the text,
1351        // leave it alone.
1352        if (offset >= realLength) {
1353            return offset;
1354        }
1355        Editable editable = getText();
1356        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1357            // Keep walking backward!
1358            offset--;
1359        }
1360        return offset;
1361    }
1362
1363    private int findText(Editable text, int offset) {
1364        if (text.charAt(offset) != ' ') {
1365            return offset;
1366        }
1367        return -1;
1368    }
1369
1370    private RecipientChip findChip(int offset) {
1371        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1372        // Find the chip that contains this offset.
1373        for (int i = 0; i < chips.length; i++) {
1374            RecipientChip chip = chips[i];
1375            int start = getChipStart(chip);
1376            int end = getChipEnd(chip);
1377            if (offset >= start && offset <= end) {
1378                return chip;
1379            }
1380        }
1381        return null;
1382    }
1383
1384    // Visible for testing.
1385    // Use this method to generate text to add to the list of addresses.
1386    /* package */String createAddressText(RecipientEntry entry) {
1387        String display = entry.getDisplayName();
1388        String address = entry.getDestination();
1389        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1390            display = null;
1391        }
1392        if (address != null) {
1393            // Tokenize out the address in case the address already
1394            // contained the username as well.
1395            Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1396            if (tokenized != null && tokenized.length > 0) {
1397                address = tokenized[0].getAddress();
1398            }
1399        }
1400        Rfc822Token token = new Rfc822Token(display, address, null);
1401        String trimmedDisplayText = token.toString().trim();
1402        int index = trimmedDisplayText.indexOf(",");
1403        return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
1404                && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
1405                .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1406    }
1407
1408    // Visible for testing.
1409    // Use this method to generate text to display in a chip.
1410    /*package*/ String createChipDisplayText(RecipientEntry entry) {
1411        String display = entry.getDisplayName();
1412        String address = entry.getDestination();
1413        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1414            display = null;
1415        }
1416        if (address != null) {
1417            // Tokenize out the address in case the address already
1418            // contained the username as well.
1419            Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1420            if (tokenized != null && tokenized.length > 0) {
1421                address = tokenized[0].getAddress();
1422            }
1423        }
1424        if (!TextUtils.isEmpty(display)) {
1425            return display;
1426        } else if (!TextUtils.isEmpty(address)){
1427            return address;
1428        } else {
1429            return new Rfc822Token(display, address, null).toString();
1430        }
1431    }
1432
1433    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1434        String displayText = createAddressText(entry);
1435        if (TextUtils.isEmpty(displayText)) {
1436            return null;
1437        }
1438        SpannableString chipText = null;
1439        // Always leave a blank space at the end of a chip.
1440        int end = getSelectionEnd();
1441        int start = mTokenizer.findTokenStart(getText(), end);
1442        int textLength = displayText.length()-1;
1443        chipText = new SpannableString(displayText);
1444        if (!mNoChips) {
1445            try {
1446                RecipientChip chip = constructChipSpan(entry, start, pressed);
1447                chipText.setSpan(chip, 0, textLength,
1448                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1449                chip.setOriginalText(chipText.toString());
1450            } catch (NullPointerException e) {
1451                Log.e(TAG, e.getMessage(), e);
1452                return null;
1453            }
1454        }
1455        return chipText;
1456    }
1457
1458    /**
1459     * When an item in the suggestions list has been clicked, create a chip from the
1460     * contact information of the selected item.
1461     */
1462    @Override
1463    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1464        submitItemAtPosition(position);
1465    }
1466
1467    private void submitItemAtPosition(int position) {
1468        RecipientEntry entry = createValidatedEntry(
1469                (RecipientEntry)getAdapter().getItem(position));
1470        if (entry == null) {
1471            return;
1472        }
1473        clearComposingText();
1474
1475        int end = getSelectionEnd();
1476        int start = mTokenizer.findTokenStart(getText(), end);
1477
1478        Editable editable = getText();
1479        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1480        CharSequence chip = createChip(entry, false);
1481        if (chip != null && start >= 0 && end >= 0) {
1482            editable.replace(start, end, chip);
1483        }
1484        sanitizeBetween();
1485    }
1486
1487    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1488        if (item == null) {
1489            return null;
1490        }
1491        final RecipientEntry entry;
1492        // If the display name and the address are the same, or if this is a
1493        // valid contact, but the destination is invalid, then make this a fake
1494        // recipient that is editable.
1495        String destination = item.getDestination();
1496        if (RecipientEntry.isCreatedRecipient(item.getContactId())
1497                && (TextUtils.isEmpty(item.getDisplayName())
1498                        || TextUtils.equals(item.getDisplayName(), destination)
1499                        || (mValidator != null && !mValidator.isValid(destination)))) {
1500            entry = RecipientEntry.constructFakeEntry(destination);
1501        } else {
1502            entry = item;
1503        }
1504        return entry;
1505    }
1506
1507    /** Returns a collection of contact Id for each chip inside this View. */
1508    /* package */ Collection<Long> getContactIds() {
1509        final Set<Long> result = new HashSet<Long>();
1510        RecipientChip[] chips = getSortedRecipients();
1511        if (chips != null) {
1512            for (RecipientChip chip : chips) {
1513                result.add(chip.getContactId());
1514            }
1515        }
1516        return result;
1517    }
1518
1519
1520    /** Returns a collection of data Id for each chip inside this View. May be null. */
1521    /* package */ Collection<Long> getDataIds() {
1522        final Set<Long> result = new HashSet<Long>();
1523        RecipientChip [] chips = getSortedRecipients();
1524        if (chips != null) {
1525            for (RecipientChip chip : chips) {
1526                result.add(chip.getDataId());
1527            }
1528        }
1529        return result;
1530    }
1531
1532    // Visible for testing.
1533    /* package */RecipientChip[] getSortedRecipients() {
1534        RecipientChip[] recips = getSpannable()
1535                .getSpans(0, getText().length(), RecipientChip.class);
1536        ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays
1537                .asList(recips));
1538        final Spannable spannable = getSpannable();
1539        Collections.sort(recipientsList, new Comparator<RecipientChip>() {
1540
1541            @Override
1542            public int compare(RecipientChip first, RecipientChip second) {
1543                int firstStart = spannable.getSpanStart(first);
1544                int secondStart = spannable.getSpanStart(second);
1545                if (firstStart < secondStart) {
1546                    return -1;
1547                } else if (firstStart > secondStart) {
1548                    return 1;
1549                } else {
1550                    return 0;
1551                }
1552            }
1553        });
1554        return recipientsList.toArray(new RecipientChip[recipientsList.size()]);
1555    }
1556
1557    @Override
1558    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1559        return false;
1560    }
1561
1562    @Override
1563    public void onDestroyActionMode(ActionMode mode) {
1564    }
1565
1566    @Override
1567    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1568        return false;
1569    }
1570
1571    /**
1572     * No chips are selectable.
1573     */
1574    @Override
1575    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1576        return false;
1577    }
1578
1579    // Visible for testing.
1580    /* package */ImageSpan getMoreChip() {
1581        MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
1582                MoreImageSpan.class);
1583        return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
1584    }
1585
1586    private MoreImageSpan createMoreSpan(int count) {
1587        String moreText = String.format(mMoreItem.getText().toString(), count);
1588        TextPaint morePaint = new TextPaint(getPaint());
1589        morePaint.setTextSize(mMoreItem.getTextSize());
1590        morePaint.setColor(mMoreItem.getCurrentTextColor());
1591        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1592                + mMoreItem.getPaddingRight();
1593        int height = getLineHeight();
1594        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1595        Canvas canvas = new Canvas(drawable);
1596        int adjustedHeight = height;
1597        Layout layout = getLayout();
1598        if (layout != null) {
1599            adjustedHeight -= layout.getLineDescent(0);
1600        }
1601        canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
1602
1603        Drawable result = new BitmapDrawable(getResources(), drawable);
1604        result.setBounds(0, 0, width, height);
1605        return new MoreImageSpan(result);
1606    }
1607
1608    // Visible for testing.
1609    /*package*/ void createMoreChipPlainText() {
1610        // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
1611        Editable text = getText();
1612        int start = 0;
1613        int end = start;
1614        for (int i = 0; i < CHIP_LIMIT; i++) {
1615            end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1616            start = end; // move to the next token and get its end.
1617        }
1618        // Now, count total addresses.
1619        start = 0;
1620        int tokenCount = countTokens(text);
1621        MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
1622        SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
1623        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1624        text.replace(end, text.length(), chipText);
1625        mMoreChip = moreSpan;
1626    }
1627
1628    // Visible for testing.
1629    /* package */int countTokens(Editable text) {
1630        int tokenCount = 0;
1631        int start = 0;
1632        while (start < text.length()) {
1633            start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1634            tokenCount++;
1635            if (start >= text.length()) {
1636                break;
1637            }
1638        }
1639        return tokenCount;
1640    }
1641
1642    /**
1643     * Create the more chip. The more chip is text that replaces any chips that
1644     * do not fit in the pre-defined available space when the
1645     * RecipientEditTextView loses focus.
1646     */
1647    // Visible for testing.
1648    /* package */ void createMoreChip() {
1649        if (mNoChips) {
1650            createMoreChipPlainText();
1651            return;
1652        }
1653
1654        if (!mShouldShrink) {
1655            return;
1656        }
1657
1658        ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
1659        if (tempMore.length > 0) {
1660            getSpannable().removeSpan(tempMore[0]);
1661        }
1662        RecipientChip[] recipients = getSortedRecipients();
1663
1664        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1665            mMoreChip = null;
1666            return;
1667        }
1668        Spannable spannable = getSpannable();
1669        int numRecipients = recipients.length;
1670        int overage = numRecipients - CHIP_LIMIT;
1671        MoreImageSpan moreSpan = createMoreSpan(overage);
1672        mRemovedSpans = new ArrayList<RecipientChip>();
1673        int totalReplaceStart = 0;
1674        int totalReplaceEnd = 0;
1675        Editable text = getText();
1676        for (int i = numRecipients - overage; i < recipients.length; i++) {
1677            mRemovedSpans.add(recipients[i]);
1678            if (i == numRecipients - overage) {
1679                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1680            }
1681            if (i == recipients.length - 1) {
1682                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1683            }
1684            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
1685                int spanStart = spannable.getSpanStart(recipients[i]);
1686                int spanEnd = spannable.getSpanEnd(recipients[i]);
1687                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
1688            }
1689            spannable.removeSpan(recipients[i]);
1690        }
1691        if (totalReplaceEnd < text.length()) {
1692            totalReplaceEnd = text.length();
1693        }
1694        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1695        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1696        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1697        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1698        text.replace(start, end, chipText);
1699        mMoreChip = moreSpan;
1700    }
1701
1702    /**
1703     * Replace the more chip, if it exists, with all of the recipient chips it had
1704     * replaced when the RecipientEditTextView gains focus.
1705     */
1706    // Visible for testing.
1707    /*package*/ void removeMoreChip() {
1708        if (mMoreChip != null) {
1709            Spannable span = getSpannable();
1710            span.removeSpan(mMoreChip);
1711            mMoreChip = null;
1712            // Re-add the spans that were removed.
1713            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1714                // Recreate each removed span.
1715                RecipientChip[] recipients = getSortedRecipients();
1716                // Start the search for tokens after the last currently visible
1717                // chip.
1718                if (recipients == null || recipients.length == 0) {
1719                    return;
1720                }
1721                int end = span.getSpanEnd(recipients[recipients.length - 1]);
1722                Editable editable = getText();
1723                for (RecipientChip chip : mRemovedSpans) {
1724                    int chipStart;
1725                    int chipEnd;
1726                    String token;
1727                    // Need to find the location of the chip, again.
1728                    token = (String) chip.getOriginalText();
1729                    // As we find the matching recipient for the remove spans,
1730                    // reduce the size of the string we need to search.
1731                    // That way, if there are duplicates, we always find the correct
1732                    // recipient.
1733                    chipStart = editable.toString().indexOf(token, end);
1734                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
1735                    // Only set the span if we found a matching token.
1736                    if (chipStart != -1) {
1737                        editable.setSpan(chip, chipStart, chipEnd,
1738                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1739                    }
1740                }
1741                mRemovedSpans.clear();
1742            }
1743        }
1744    }
1745
1746    /**
1747     * Show specified chip as selected. If the RecipientChip is just an email address,
1748     * selecting the chip will take the contents of the chip and place it at
1749     * the end of the RecipientEditTextView for inline editing. If the
1750     * RecipientChip is a complete contact, then selecting the chip
1751     * will change the background color of the chip, show the delete icon,
1752     * and a popup window with the address in use highlighted and any other
1753     * alternate addresses for the contact.
1754     * @param currentChip Chip to select.
1755     * @return A RecipientChip in the selected state or null if the chip
1756     * just contained an email address.
1757     */
1758    private RecipientChip selectChip(RecipientChip currentChip) {
1759        if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1760            CharSequence text = currentChip.getValue();
1761            Editable editable = getText();
1762            removeChip(currentChip);
1763            editable.append(text);
1764            setCursorVisible(true);
1765            setSelection(editable.length());
1766            return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1);
1767        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1768            int start = getChipStart(currentChip);
1769            int end = getChipEnd(currentChip);
1770            getSpannable().removeSpan(currentChip);
1771            RecipientChip newChip;
1772            try {
1773                if (mNoChips) {
1774                    return null;
1775                }
1776                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1777            } catch (NullPointerException e) {
1778                Log.e(TAG, e.getMessage(), e);
1779                return null;
1780            }
1781            Editable editable = getText();
1782            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1783            if (start == -1 || end == -1) {
1784                Log.d(TAG, "The chip being selected no longer exists but should.");
1785            } else {
1786                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1787            }
1788            newChip.setSelected(true);
1789            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1790                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1791            }
1792            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1793            setCursorVisible(false);
1794            return newChip;
1795        } else {
1796            int start = getChipStart(currentChip);
1797            int end = getChipEnd(currentChip);
1798            getSpannable().removeSpan(currentChip);
1799            RecipientChip newChip;
1800            try {
1801                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1802            } catch (NullPointerException e) {
1803                Log.e(TAG, e.getMessage(), e);
1804                return null;
1805            }
1806            Editable editable = getText();
1807            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1808            if (start == -1 || end == -1) {
1809                Log.d(TAG, "The chip being selected no longer exists but should.");
1810            } else {
1811                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1812            }
1813            newChip.setSelected(true);
1814            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1815                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1816            }
1817            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1818            setCursorVisible(false);
1819            return newChip;
1820        }
1821    }
1822
1823
1824    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
1825            int width, Context context) {
1826        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1827        int bottom = calculateOffsetFromBottom(line);
1828        // Align the alternates popup with the left side of the View,
1829        // regardless of the position of the chip tapped.
1830        setEnabled(false);
1831        popup.setWidth(width);
1832        popup.setAnchorView(this);
1833        popup.setVerticalOffset(bottom);
1834        popup.setAdapter(createSingleAddressAdapter(currentChip));
1835        popup.setOnItemClickListener(new OnItemClickListener() {
1836            @Override
1837            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1838                unselectChip(currentChip);
1839                popup.dismiss();
1840            }
1841        });
1842        popup.show();
1843        ListView listView = popup.getListView();
1844        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1845        listView.setItemChecked(0, true);
1846    }
1847
1848    /**
1849     * Remove selection from this chip. Unselecting a RecipientChip will render
1850     * the chip without a delete icon and with an unfocused background. This is
1851     * called when the RecipientChip no longer has focus.
1852     */
1853    private void unselectChip(RecipientChip chip) {
1854        int start = getChipStart(chip);
1855        int end = getChipEnd(chip);
1856        Editable editable = getText();
1857        mSelectedChip = null;
1858        if (start == -1 || end == -1) {
1859            Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
1860            setSelection(editable.length());
1861            commitDefault();
1862        } else {
1863            getSpannable().removeSpan(chip);
1864            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1865            editable.removeSpan(chip);
1866            try {
1867                if (!mNoChips) {
1868                    editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1869                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1870                }
1871            } catch (NullPointerException e) {
1872                Log.e(TAG, e.getMessage(), e);
1873            }
1874        }
1875        setCursorVisible(true);
1876        setSelection(editable.length());
1877        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1878            mAlternatesPopup.dismiss();
1879        }
1880    }
1881
1882    /**
1883     * Return whether a touch event was inside the delete target of
1884     * a selected chip. It is in the delete target if:
1885     * 1) the x and y points of the event are within the
1886     * delete assset.
1887     * 2) the point tapped would have caused a cursor to appear
1888     * right after the selected chip.
1889     * @return boolean
1890     */
1891    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1892        // Figure out the bounds of this chip and whether or not
1893        // the user clicked in the X portion.
1894        return chip.isSelected() && offset == getChipEnd(chip);
1895    }
1896
1897    /**
1898     * Remove the chip and any text associated with it from the RecipientEditTextView.
1899     */
1900    // Visible for testing.
1901    /*pacakge*/ void removeChip(RecipientChip chip) {
1902        Spannable spannable = getSpannable();
1903        int spanStart = spannable.getSpanStart(chip);
1904        int spanEnd = spannable.getSpanEnd(chip);
1905        Editable text = getText();
1906        int toDelete = spanEnd;
1907        boolean wasSelected = chip == mSelectedChip;
1908        // Clear that there is a selected chip before updating any text.
1909        if (wasSelected) {
1910            mSelectedChip = null;
1911        }
1912        // Always remove trailing spaces when removing a chip.
1913        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
1914            toDelete++;
1915        }
1916        spannable.removeSpan(chip);
1917        text.delete(spanStart, toDelete);
1918        if (wasSelected) {
1919            clearSelectedChip();
1920        }
1921    }
1922
1923    /**
1924     * Replace this currently selected chip with a new chip
1925     * that uses the contact data provided.
1926     */
1927    // Visible for testing.
1928    /*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) {
1929        boolean wasSelected = chip == mSelectedChip;
1930        if (wasSelected) {
1931            mSelectedChip = null;
1932        }
1933        int start = getChipStart(chip);
1934        int end = getChipEnd(chip);
1935        getSpannable().removeSpan(chip);
1936        Editable editable = getText();
1937        CharSequence chipText = createChip(entry, false);
1938        if (chipText != null) {
1939            if (start == -1 || end == -1) {
1940                Log.e(TAG, "The chip to replace does not exist but should.");
1941                editable.insert(0, chipText);
1942            } else {
1943                if (!TextUtils.isEmpty(chipText)) {
1944                    // There may be a space to replace with this chip's new
1945                    // associated
1946                    // space. Check for it
1947                    int toReplace = end;
1948                    while (toReplace >= 0 && toReplace < editable.length()
1949                            && editable.charAt(toReplace) == ' ') {
1950                        toReplace++;
1951                    }
1952                    editable.replace(start, toReplace, chipText);
1953                }
1954            }
1955        }
1956        setCursorVisible(true);
1957        if (wasSelected) {
1958            clearSelectedChip();
1959        }
1960    }
1961
1962    /**
1963     * Handle click events for a chip. When a selected chip receives a click
1964     * event, see if that event was in the delete icon. If so, delete it.
1965     * Otherwise, unselect the chip.
1966     */
1967    public void onClick(RecipientChip chip, int offset, float x, float y) {
1968        if (chip.isSelected()) {
1969            if (isInDelete(chip, offset, x, y)) {
1970                removeChip(chip);
1971            } else {
1972                clearSelectedChip();
1973            }
1974        }
1975    }
1976
1977    private boolean chipsPending() {
1978        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1979    }
1980
1981    @Override
1982    public void removeTextChangedListener(TextWatcher watcher) {
1983        mTextWatcher = null;
1984        super.removeTextChangedListener(watcher);
1985    }
1986
1987    private class RecipientTextWatcher implements TextWatcher {
1988        @Override
1989        public void afterTextChanged(Editable s) {
1990            // If the text has been set to null or empty, make sure we remove
1991            // all the spans we applied.
1992            if (TextUtils.isEmpty(s)) {
1993                // Remove all the chips spans.
1994                Spannable spannable = getSpannable();
1995                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
1996                        RecipientChip.class);
1997                for (RecipientChip chip : chips) {
1998                    spannable.removeSpan(chip);
1999                }
2000                if (mMoreChip != null) {
2001                    spannable.removeSpan(mMoreChip);
2002                }
2003                return;
2004            }
2005            // Get whether there are any recipients pending addition to the
2006            // view. If there are, don't do anything in the text watcher.
2007            if (chipsPending()) {
2008                return;
2009            }
2010            // If the user is editing a chip, don't clear it.
2011            if (mSelectedChip != null
2012                    && mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) {
2013                setCursorVisible(true);
2014                setSelection(getText().length());
2015                clearSelectedChip();
2016            }
2017            int length = s.length();
2018            // Make sure there is content there to parse and that it is
2019            // not just the commit character.
2020            if (length > 1) {
2021                char last;
2022                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2023                int len = length() - 1;
2024                if (end != len) {
2025                    last = s.charAt(end);
2026                } else {
2027                    last = s.charAt(len);
2028                }
2029                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
2030                    commitByCharacter();
2031                } else if (last == COMMIT_CHAR_SPACE) {
2032                    // Check if this is a valid email address. If it is,
2033                    // commit it.
2034                    String text = getText().toString();
2035                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2036                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
2037                            tokenStart));
2038                    if (!TextUtils.isEmpty(sub) && mValidator != null && mValidator.isValid(sub)) {
2039                        commitByCharacter();
2040                    }
2041                }
2042            }
2043        }
2044
2045        @Override
2046        public void onTextChanged(CharSequence s, int start, int before, int count) {
2047            // Do nothing.
2048        }
2049
2050        @Override
2051        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2052            // Do nothing.
2053        }
2054    }
2055
2056    /**
2057     * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2058     */
2059    private void handlePasteClip(ClipData clip) {
2060        removeTextChangedListener(mTextWatcher);
2061
2062        if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
2063            for (int i = 0; i < clip.getItemCount(); i++) {
2064                CharSequence paste = clip.getItemAt(i).getText();
2065                if (paste != null) {
2066                    int start = getSelectionStart();
2067                    int end = getSelectionEnd();
2068                    Editable editable = getText();
2069                    if (start >= 0 && end >= 0 && start != end) {
2070                        editable.append(paste, start, end);
2071                    } else {
2072                        editable.insert(end, paste);
2073                    }
2074                    handlePasteAndReplace();
2075                }
2076            }
2077        }
2078
2079        mHandler.post(mAddTextWatcher);
2080    }
2081
2082    @Override
2083    public boolean onTextContextMenuItem(int id) {
2084        if (id == android.R.id.paste) {
2085            ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2086                    Context.CLIPBOARD_SERVICE);
2087            handlePasteClip(clipboard.getPrimaryClip());
2088            return true;
2089        }
2090        return super.onTextContextMenuItem(id);
2091    }
2092
2093    private void handlePasteAndReplace() {
2094        ArrayList<RecipientChip> created = handlePaste();
2095        if (created != null && created.size() > 0) {
2096            // Perform reverse lookups on the pasted contacts.
2097            IndividualReplacementTask replace = new IndividualReplacementTask();
2098            replace.execute(created);
2099        }
2100    }
2101
2102    // Visible for testing.
2103    /* package */ArrayList<RecipientChip> handlePaste() {
2104        String text = getText().toString();
2105        int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2106        String lastAddress = text.substring(originalTokenStart);
2107        int tokenStart = originalTokenStart;
2108        int prevTokenStart = tokenStart;
2109        RecipientChip findChip = null;
2110        ArrayList<RecipientChip> created = new ArrayList<RecipientChip>();
2111        if (tokenStart != 0) {
2112            // There are things before this!
2113            while (tokenStart != 0 && findChip == null) {
2114                prevTokenStart = tokenStart;
2115                tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2116                findChip = findChip(tokenStart);
2117            }
2118            if (tokenStart != originalTokenStart) {
2119                if (findChip != null) {
2120                    tokenStart = prevTokenStart;
2121                }
2122                int tokenEnd;
2123                RecipientChip createdChip;
2124                while (tokenStart < originalTokenStart) {
2125                    tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(text, tokenStart));
2126                    commitChip(tokenStart, tokenEnd, getText());
2127                    createdChip = findChip(tokenStart);
2128                    // +1 for the space at the end.
2129                    tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
2130                    created.add(createdChip);
2131                }
2132            }
2133        }
2134        // Take a look at the last token. If the token has been completed with a
2135        // commit character, create a chip.
2136        if (isCompletedToken(lastAddress)) {
2137            Editable editable = getText();
2138            tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2139            commitChip(tokenStart, editable.length(), editable);
2140            created.add(findChip(tokenStart));
2141        }
2142        return created;
2143    }
2144
2145    // Visible for testing.
2146    /* package */int movePastTerminators(int tokenEnd) {
2147        if (tokenEnd >= length()) {
2148            return tokenEnd;
2149        }
2150        char atEnd = getText().toString().charAt(tokenEnd);
2151        if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2152            tokenEnd++;
2153        }
2154        // This token had not only an end token character, but also a space
2155        // separating it from the next token.
2156        if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2157            tokenEnd++;
2158        }
2159        return tokenEnd;
2160    }
2161
2162    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
2163        private RecipientChip createFreeChip(RecipientEntry entry) {
2164            try {
2165                if (mNoChips) {
2166                    return null;
2167                }
2168                return constructChipSpan(entry, -1, false);
2169            } catch (NullPointerException e) {
2170                Log.e(TAG, e.getMessage(), e);
2171                return null;
2172            }
2173        }
2174
2175        @Override
2176        protected Void doInBackground(Void... params) {
2177            if (mIndividualReplacements != null) {
2178                mIndividualReplacements.cancel(true);
2179            }
2180            // For each chip in the list, look up the matching contact.
2181            // If there is a match, replace that chip with the matching
2182            // chip.
2183            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
2184            RecipientChip[] existingChips = getSortedRecipients();
2185            for (int i = 0; i < existingChips.length; i++) {
2186                originalRecipients.add(existingChips[i]);
2187            }
2188            if (mRemovedSpans != null) {
2189                originalRecipients.addAll(mRemovedSpans);
2190            }
2191            String[] addresses = new String[originalRecipients.size()];
2192            RecipientChip chip;
2193            for (int i = 0; i < originalRecipients.size(); i++) {
2194                chip = originalRecipients.get(i);
2195                if (chip != null) {
2196                    addresses[i] = createAddressText(chip.getEntry());
2197                }
2198            }
2199            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2200                    .getMatchingRecipients(getContext(), addresses);
2201            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
2202            for (final RecipientChip temp : originalRecipients) {
2203                RecipientEntry entry = null;
2204                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2205                        && getSpannable().getSpanStart(temp) != -1) {
2206                    // Replace this.
2207                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
2208                            .getDestination())));
2209                }
2210                if (entry != null) {
2211                    replacements.add(createFreeChip(entry));
2212                } else {
2213                    replacements.add(temp);
2214                }
2215            }
2216            if (replacements != null && replacements.size() > 0) {
2217                mHandler.post(new Runnable() {
2218                    @Override
2219                    public void run() {
2220                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
2221                                .toString());
2222                        Editable oldText = getText();
2223                        int start, end;
2224                        int i = 0;
2225                        for (RecipientChip chip : originalRecipients) {
2226                            start = oldText.getSpanStart(chip);
2227                            if (start != -1) {
2228                                end = oldText.getSpanEnd(chip);
2229                                oldText.removeSpan(chip);
2230                                // Leave a spot for the space!
2231                                RecipientChip replacement = replacements.get(i);
2232                                text.setSpan(replacement, start, end,
2233                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2234                                replacement.setOriginalText(text.toString().substring(start, end));
2235                            }
2236                            i++;
2237                        }
2238                        originalRecipients.clear();
2239                        setText(text);
2240                    }
2241                });
2242            }
2243            return null;
2244        }
2245    }
2246
2247    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
2248        @SuppressWarnings("unchecked")
2249        @Override
2250        protected Void doInBackground(Object... params) {
2251            // For each chip in the list, look up the matching contact.
2252            // If there is a match, replace that chip with the matching
2253            // chip.
2254            final ArrayList<RecipientChip> originalRecipients =
2255                (ArrayList<RecipientChip>) params[0];
2256            String[] addresses = new String[originalRecipients.size()];
2257            RecipientChip chip;
2258            for (int i = 0; i < originalRecipients.size(); i++) {
2259                chip = originalRecipients.get(i);
2260                if (chip != null) {
2261                    addresses[i] = createAddressText(chip.getEntry());
2262                }
2263            }
2264            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2265                    .getMatchingRecipients(getContext(), addresses);
2266            for (final RecipientChip temp : originalRecipients) {
2267                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2268                        && getSpannable().getSpanStart(temp) != -1) {
2269                    // Replace this.
2270                    final RecipientEntry entry = createValidatedEntry(entries
2271                            .get(tokenizeAddress(temp.getEntry().getDestination()).toLowerCase()));
2272                    if (entry != null) {
2273                        mHandler.post(new Runnable() {
2274                            @Override
2275                            public void run() {
2276                                replaceChip(temp, entry);
2277                            }
2278                        });
2279                    }
2280                }
2281            }
2282            return null;
2283        }
2284    }
2285
2286
2287    /**
2288     * MoreImageSpan is a simple class created for tracking the existence of a
2289     * more chip across activity restarts/
2290     */
2291    private class MoreImageSpan extends ImageSpan {
2292        public MoreImageSpan(Drawable b) {
2293            super(b);
2294        }
2295    }
2296
2297    @Override
2298    public boolean onDown(MotionEvent e) {
2299        return false;
2300    }
2301
2302    @Override
2303    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2304        // Do nothing.
2305        return false;
2306    }
2307
2308    @Override
2309    public void onLongPress(MotionEvent event) {
2310        if (mSelectedChip != null) {
2311            return;
2312        }
2313        float x = event.getX();
2314        float y = event.getY();
2315        int offset = putOffsetInRange(getOffsetForPosition(x, y));
2316        RecipientChip currentChip = findChip(offset);
2317        if (currentChip != null) {
2318            if (mDragEnabled) {
2319                // Start drag-and-drop for the selected chip.
2320                startDrag(currentChip);
2321            } else {
2322                // Copy the selected chip email address.
2323                showCopyDialog(currentChip.getEntry().getDestination());
2324            }
2325        }
2326    }
2327
2328    /**
2329     * Enables drag-and-drop for chips.
2330     */
2331    public void enableDrag() {
2332        mDragEnabled = true;
2333    }
2334
2335    /**
2336     * Starts drag-and-drop for the selected chip.
2337     */
2338    private void startDrag(RecipientChip currentChip) {
2339        String address = currentChip.getEntry().getDestination();
2340        ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
2341
2342        // Start drag mode.
2343        startDrag(data, new RecipientChipShadow(currentChip), null, 0);
2344
2345        // Remove the current chip, so drag-and-drop will result in a move.
2346        // TODO (phamm): consider readd this chip if it's dropped outside a target.
2347        removeChip(currentChip);
2348    }
2349
2350    /**
2351     * Handles drag event.
2352     */
2353    @Override
2354    public boolean onDragEvent(DragEvent event) {
2355        switch (event.getAction()) {
2356            case DragEvent.ACTION_DRAG_STARTED:
2357                // Only handle plain text drag and drop.
2358                return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
2359            case DragEvent.ACTION_DRAG_ENTERED:
2360                requestFocus();
2361                return true;
2362            case DragEvent.ACTION_DROP:
2363                handlePasteClip(event.getClipData());
2364                return true;
2365        }
2366        return false;
2367    }
2368
2369    /**
2370     * Drag shadow for a {@link RecipientChip}.
2371     */
2372    private final class RecipientChipShadow extends DragShadowBuilder {
2373        private final RecipientChip mChip;
2374
2375        public RecipientChipShadow(RecipientChip chip) {
2376            mChip = chip;
2377        }
2378
2379        @Override
2380        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
2381            Rect rect = mChip.getDrawable().getBounds();
2382            shadowSize.set(rect.width(), rect.height());
2383            shadowTouchPoint.set(rect.centerX(), rect.centerY());
2384        }
2385
2386        @Override
2387        public void onDrawShadow(Canvas canvas) {
2388            mChip.getDrawable().draw(canvas);
2389        }
2390    }
2391
2392    private void showCopyDialog(final String address) {
2393        mCopyAddress = address;
2394        mCopyDialog.setTitle(address);
2395        mCopyDialog.setContentView(mCopyViewRes);
2396        mCopyDialog.setCancelable(true);
2397        mCopyDialog.setCanceledOnTouchOutside(true);
2398        mCopyDialog.findViewById(android.R.id.button1).setOnClickListener(this);
2399        mCopyDialog.setOnDismissListener(this);
2400        mCopyDialog.show();
2401    }
2402
2403    @Override
2404    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
2405        // Do nothing.
2406        return false;
2407    }
2408
2409    @Override
2410    public void onShowPress(MotionEvent e) {
2411        // Do nothing.
2412    }
2413
2414    @Override
2415    public boolean onSingleTapUp(MotionEvent e) {
2416        // Do nothing.
2417        return false;
2418    }
2419
2420    @Override
2421    public void onDismiss(DialogInterface dialog) {
2422        mCopyAddress = null;
2423    }
2424
2425    @Override
2426    public void onClick(View v) {
2427        // Copy this to the clipboard.
2428        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2429                Context.CLIPBOARD_SERVICE);
2430        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
2431        mCopyDialog.dismiss();
2432    }
2433}
2434