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