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