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