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