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