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