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