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.SpannableStringBuilder;
47import android.text.Spanned;
48import android.text.TextPaint;
49import android.text.TextUtils;
50import android.text.TextWatcher;
51import android.text.method.QwertyKeyListener;
52import android.text.style.ImageSpan;
53import android.text.util.Rfc822Token;
54import android.text.util.Rfc822Tokenizer;
55import android.util.AttributeSet;
56import android.util.Log;
57import android.util.TypedValue;
58import android.util.Patterns;
59import android.view.ActionMode;
60import android.view.ActionMode.Callback;
61import android.view.DragEvent;
62import android.view.GestureDetector;
63import android.view.KeyEvent;
64import android.view.LayoutInflater;
65import android.view.Menu;
66import android.view.MenuItem;
67import android.view.MotionEvent;
68import android.view.View;
69import android.view.View.OnClickListener;
70import android.view.ViewParent;
71import android.view.inputmethod.EditorInfo;
72import android.view.inputmethod.InputConnection;
73import android.widget.AdapterView;
74import android.widget.AdapterView.OnItemClickListener;
75import android.widget.Button;
76import android.widget.Filterable;
77import android.widget.ListAdapter;
78import android.widget.ListPopupWindow;
79import android.widget.ListView;
80import android.widget.MultiAutoCompleteTextView;
81import android.widget.ScrollView;
82import android.widget.TextView;
83
84import java.util.ArrayList;
85import java.util.Arrays;
86import java.util.Collection;
87import java.util.Collections;
88import java.util.Comparator;
89import java.util.HashMap;
90import java.util.HashSet;
91import java.util.List;
92import java.util.Set;
93import java.util.regex.Matcher;
94import java.util.regex.Pattern;
95
96/**
97 * RecipientEditTextView is an auto complete text view for use with applications
98 * that use the new Chips UI for addressing a message to recipients.
99 */
100public class RecipientEditTextView extends MultiAutoCompleteTextView implements
101        OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener,
102        GestureDetector.OnGestureListener, OnDismissListener, OnClickListener,
103        TextView.OnEditorActionListener {
104
105    private static final char COMMIT_CHAR_COMMA = ',';
106
107    private static final char NAME_WRAPPER_CHAR = '"';
108
109    private static final char COMMIT_CHAR_SEMICOLON = ';';
110
111    private static final char COMMIT_CHAR_SPACE = ' ';
112
113    private static final String TAG = "RecipientEditTextView";
114
115    private static int DISMISS = "dismiss".hashCode();
116
117    private static final long DISMISS_DELAY = 300;
118
119    // TODO: get correct number/ algorithm from with UX.
120    // Visible for testing.
121    /*package*/ static final int CHIP_LIMIT = 2;
122
123    private static final int MAX_CHIPS_PARSED = 50;
124
125    private static int sSelectedTextColor = -1;
126
127    // Resources for displaying chips.
128    private Drawable mChipBackground = null;
129
130    private Drawable mChipDelete = null;
131
132    private Drawable mInvalidChipBackground;
133
134    private Drawable mChipBackgroundPressed;
135
136    private float mChipHeight;
137
138    private float mChipFontSize;
139
140    private float mLineSpacingExtra;
141
142    private int mChipPadding;
143
144    private Tokenizer mTokenizer;
145
146    private Validator mValidator;
147
148    private RecipientChip mSelectedChip;
149
150    private int mAlternatesLayout;
151
152    private Bitmap mDefaultContactPhoto;
153
154    private ImageSpan mMoreChip;
155
156    private TextView mMoreItem;
157
158    private final ArrayList<String> mPendingChips = new ArrayList<String>();
159
160    private Handler mHandler;
161
162    private int mPendingChipsCount = 0;
163
164    private boolean mNoChips = false;
165
166    private ListPopupWindow mAlternatesPopup;
167
168    private ListPopupWindow mAddressPopup;
169
170    private ArrayList<RecipientChip> mTemporaryRecipients;
171
172    private ArrayList<RecipientChip> mRemovedSpans;
173
174    private boolean mShouldShrink = true;
175
176    // Chip copy fields.
177    private GestureDetector mGestureDetector;
178
179    private Dialog mCopyDialog;
180
181    private String mCopyAddress;
182
183    /**
184     * Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a
185     * selected chip.
186     */
187    private OnItemClickListener mAlternatesListener;
188
189    private int mCheckedItem;
190
191    private TextWatcher mTextWatcher;
192
193    // Obtain the enclosing scroll view, if it exists, so that the view can be
194    // scrolled to show the last line of chips content.
195    private ScrollView mScrollView;
196
197    private boolean mTriedGettingScrollView;
198
199    private boolean mDragEnabled = false;
200
201    // This pattern comes from android.util.Patterns. It has been tweaked to handle a "1" before
202    // parens, so numbers such as "1 (425) 222-2342" match.
203    private static final Pattern PHONE_PATTERN
204        = Pattern.compile(                                  // sdd = space, dot, or dash
205                "(\\+[0-9]+[\\- \\.]*)?"                    // +<digits><sdd>*
206                + "(1?[ ]*\\([0-9]+\\)[\\- \\.]*)?"         // 1(<digits>)<sdd>*
207                + "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>
208
209
210    private final Runnable mAddTextWatcher = new Runnable() {
211        @Override
212        public void run() {
213            if (mTextWatcher == null) {
214                mTextWatcher = new RecipientTextWatcher();
215                addTextChangedListener(mTextWatcher);
216            }
217        }
218    };
219
220    private IndividualReplacementTask mIndividualReplacements;
221
222    private Runnable mHandlePendingChips = new Runnable() {
223
224        @Override
225        public void run() {
226            handlePendingChips();
227        }
228
229    };
230
231    private Runnable mDelayedShrink = new Runnable() {
232
233        @Override
234        public void run() {
235            shrink();
236        }
237
238    };
239
240    private int mMaxLines;
241
242    private static int sExcessTopPadding = -1;
243
244    private int mActionBarHeight;
245
246    public RecipientEditTextView(Context context, AttributeSet attrs) {
247        super(context, attrs);
248        setChipDimensions(context, attrs);
249        if (sSelectedTextColor == -1) {
250            sSelectedTextColor = context.getResources().getColor(android.R.color.white);
251        }
252        mAlternatesPopup = new ListPopupWindow(context);
253        mAddressPopup = new ListPopupWindow(context);
254        mCopyDialog = new Dialog(context);
255        mAlternatesListener = new OnItemClickListener() {
256            @Override
257            public void onItemClick(AdapterView<?> adapterView,View view, int position,
258                    long rowId) {
259                mAlternatesPopup.setOnItemClickListener(null);
260                replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
261                        .getRecipientEntry(position));
262                Message delayed = Message.obtain(mHandler, DISMISS);
263                delayed.obj = mAlternatesPopup;
264                mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
265                clearComposingText();
266            }
267        };
268        setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
269        setOnItemClickListener(this);
270        setCustomSelectionActionModeCallback(this);
271        mHandler = new Handler() {
272            @Override
273            public void handleMessage(Message msg) {
274                if (msg.what == DISMISS) {
275                    ((ListPopupWindow) msg.obj).dismiss();
276                    return;
277                }
278                super.handleMessage(msg);
279            }
280        };
281        mTextWatcher = new RecipientTextWatcher();
282        addTextChangedListener(mTextWatcher);
283        mGestureDetector = new GestureDetector(context, this);
284        setOnEditorActionListener(this);
285        mMaxLines = getLineCount();
286    }
287
288    @Override
289    public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
290        if (action == EditorInfo.IME_ACTION_DONE) {
291            if (commitDefault()) {
292                return true;
293            }
294            if (mSelectedChip != null) {
295                clearSelectedChip();
296                return true;
297            } else if (focusNext()) {
298                return true;
299            }
300        }
301        return false;
302    }
303
304    @Override
305    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
306        InputConnection connection = super.onCreateInputConnection(outAttrs);
307        int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION;
308        if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) {
309            // clear the existing action
310            outAttrs.imeOptions ^= imeActions;
311            // set the DONE action
312            outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
313        }
314        if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
315            outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
316        }
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 (mValidator != null && mValidator.isValid(contact.getDestination())) ?
651                mChipBackground : mInvalidChipBackground;
652    }
653
654    private float getTextYOffset(String text, TextPaint paint, int height) {
655        Rect bounds = new Rect();
656        paint.getTextBounds(text, 0, text.length(), bounds);
657        int textHeight = bounds.bottom - bounds.top ;
658        return height - ((height - textHeight) / 2) - (int)paint.descent();
659    }
660
661    private RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed,
662            boolean leaveIconSpace) throws NullPointerException {
663        if (mChipBackground == null) {
664            throw new NullPointerException(
665                    "Unable to render any chips as setChipDimensions was not called.");
666        }
667        Layout layout = getLayout();
668
669        TextPaint paint = getPaint();
670        float defaultSize = paint.getTextSize();
671        int defaultColor = paint.getColor();
672
673        Bitmap tmpBitmap;
674        if (pressed) {
675            tmpBitmap = createSelectedChip(contact, paint, layout);
676
677        } else {
678            tmpBitmap = createUnselectedChip(contact, paint, layout, leaveIconSpace);
679        }
680
681        // Pass the full text, un-ellipsized, to the chip.
682        Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
683        result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
684        RecipientChip recipientChip = new RecipientChip(result, contact, offset);
685        // Return text to the original size.
686        paint.setTextSize(defaultSize);
687        paint.setColor(defaultColor);
688        return recipientChip;
689    }
690
691    /**
692     * Calculate the bottom of the line the chip will be located on using:
693     * 1) which line the chip appears on
694     * 2) the height of a chip
695     * 3) padding built into the edit text view
696     */
697    private int calculateOffsetFromBottom(int line) {
698        // Line offsets start at zero.
699        int actualLine = getLineCount() - (line + 1);
700        return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop())
701                + getDropDownVerticalOffset();
702    }
703
704    /**
705     * Get the max amount of space a chip can take up. The formula takes into
706     * account the width of the EditTextView, any view padding, and padding
707     * that will be added to the chip.
708     */
709    private float calculateAvailableWidth(boolean pressed) {
710        return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
711    }
712
713
714    private void setChipDimensions(Context context, AttributeSet attrs) {
715        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0,
716                0);
717        Resources r = getContext().getResources();
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 =  context.getResources().getDimension(R.dimen.line_spacing_extra);
759        TypedValue tv = new TypedValue();
760        if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
761            mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources()
762                    .getDisplayMetrics());
763        }
764        a.recycle();
765    }
766
767    // Visible for testing.
768    /* package */ void setMoreItem(TextView moreItem) {
769        mMoreItem = moreItem;
770    }
771
772
773    // Visible for testing.
774    /* package */ void setChipBackground(Drawable chipBackground) {
775        mChipBackground = chipBackground;
776    }
777
778    // Visible for testing.
779    /* package */ void setChipHeight(int height) {
780        mChipHeight = height;
781    }
782
783    /**
784     * Set whether to shrink the recipients field such that at most
785     * one line of recipients chips are shown when the field loses
786     * focus. By default, the number of displayed recipients will be
787     * limited and a "more" chip will be shown when focus is lost.
788     * @param shrink
789     */
790    public void setOnFocusListShrinkRecipients(boolean shrink) {
791        mShouldShrink = shrink;
792    }
793
794    @Override
795    public void onSizeChanged(int width, int height, int oldw, int oldh) {
796        super.onSizeChanged(width, height, oldw, oldh);
797        if (width != 0 && height != 0) {
798            if (mPendingChipsCount > 0) {
799                postHandlePendingChips();
800            } else {
801                checkChipWidths();
802            }
803        }
804        // Try to find the scroll view parent, if it exists.
805        if (mScrollView == null && !mTriedGettingScrollView) {
806            ViewParent parent = getParent();
807            while (parent != null && !(parent instanceof ScrollView)) {
808                parent = parent.getParent();
809            }
810            if (parent != null) {
811                mScrollView = (ScrollView) parent;
812            }
813            mTriedGettingScrollView = true;
814        }
815    }
816
817    private void postHandlePendingChips() {
818        mHandler.removeCallbacks(mHandlePendingChips);
819        mHandler.post(mHandlePendingChips);
820    }
821
822    private void checkChipWidths() {
823        // Check the widths of the associated chips.
824        RecipientChip[] chips = getSortedRecipients();
825        if (chips != null) {
826            Rect bounds;
827            for (RecipientChip chip : chips) {
828                bounds = chip.getDrawable().getBounds();
829                if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) {
830                    // Need to redraw that chip.
831                    replaceChip(chip, chip.getEntry());
832                }
833            }
834        }
835    }
836
837    // Visible for testing.
838    /*package*/ void handlePendingChips() {
839        if (getViewWidth() <= 0) {
840            // The widget has not been sized yet.
841            // This will be called as a result of onSizeChanged
842            // at a later point.
843            return;
844        }
845        if (mPendingChipsCount <= 0) {
846            return;
847        }
848
849        synchronized (mPendingChips) {
850            Editable editable = getText();
851            // Tokenize!
852            if (mPendingChipsCount <= MAX_CHIPS_PARSED) {
853                for (int i = 0; i < mPendingChips.size(); i++) {
854                    String current = mPendingChips.get(i);
855                    int tokenStart = editable.toString().indexOf(current);
856                    int tokenEnd = tokenStart + current.length();
857                    if (tokenStart >= 0) {
858                        // When we have a valid token, include it with the token
859                        // to the left.
860                        if (tokenEnd < editable.length() - 2
861                                && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
862                            tokenEnd++;
863                        }
864                        createReplacementChip(tokenStart, tokenEnd, editable);
865                    }
866                    mPendingChipsCount--;
867                }
868                sanitizeEnd();
869            } else {
870                mNoChips = true;
871            }
872
873            if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0
874                    && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
875                if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
876                    new RecipientReplacementTask().execute();
877                    mTemporaryRecipients = null;
878                } else {
879                    // Create the "more" chip
880                    mIndividualReplacements = new IndividualReplacementTask();
881                    mIndividualReplacements.execute(new ArrayList<RecipientChip>(
882                            mTemporaryRecipients.subList(0, CHIP_LIMIT)));
883                    if (mTemporaryRecipients.size() > CHIP_LIMIT) {
884                        mTemporaryRecipients = new ArrayList<RecipientChip>(
885                                mTemporaryRecipients.subList(CHIP_LIMIT,
886                                        mTemporaryRecipients.size()));
887                    } else {
888                        mTemporaryRecipients = null;
889                    }
890                    createMoreChip();
891                }
892            } else {
893                // There are too many recipients to look up, so just fall back
894                // to showing addresses for all of them.
895                mTemporaryRecipients = null;
896                createMoreChip();
897            }
898            mPendingChipsCount = 0;
899            mPendingChips.clear();
900        }
901    }
902
903    // Visible for testing.
904    /*package*/ int getViewWidth() {
905        return getWidth();
906    }
907
908    /**
909     * Remove any characters after the last valid chip.
910     */
911    // Visible for testing.
912    /*package*/ void sanitizeEnd() {
913        // Don't sanitize while we are waiting for pending chips to complete.
914        if (mPendingChipsCount > 0) {
915            return;
916        }
917        // Find the last chip; eliminate any commit characters after it.
918        RecipientChip[] chips = getSortedRecipients();
919        if (chips != null && chips.length > 0) {
920            int end;
921            ImageSpan lastSpan;
922            mMoreChip = getMoreChip();
923            if (mMoreChip != null) {
924                lastSpan = mMoreChip;
925            } else {
926                lastSpan = getLastChip();
927            }
928            end = getSpannable().getSpanEnd(lastSpan);
929            Editable editable = getText();
930            int length = editable.length();
931            if (length > end) {
932                // See what characters occur after that and eliminate them.
933                if (Log.isLoggable(TAG, Log.DEBUG)) {
934                    Log.d(TAG, "There were extra characters after the last tokenizable entry."
935                            + editable);
936                }
937                editable.delete(end + 1, length);
938            }
939        }
940    }
941
942    /**
943     * Create a chip that represents just the email address of a recipient. At some later
944     * point, this chip will be attached to a real contact entry, if one exists.
945     */
946    private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) {
947        if (alreadyHasChip(tokenStart, tokenEnd)) {
948            // There is already a chip present at this location.
949            // Don't recreate it.
950            return;
951        }
952        String token = editable.toString().substring(tokenStart, tokenEnd);
953        int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA);
954        if (commitCharIndex == token.length() - 1) {
955            token = token.substring(0, token.length() - 1);
956        }
957        RecipientEntry entry = createTokenizedEntry(token);
958        if (entry != null) {
959            String destText = createAddressText(entry);
960            SpannableString chipText = new SpannableString(destText);
961            int end = getSelectionEnd();
962            int start = mTokenizer != null ? mTokenizer.findTokenStart(getText(), end) : 0;
963            RecipientChip chip = null;
964            try {
965                if (!mNoChips) {
966                    /* leave space for the contact icon if this is not just an email address */
967                    chip = constructChipSpan(
968                            entry,
969                            start,
970                            false,
971                            TextUtils.isEmpty(entry.getDisplayName())
972                                    || TextUtils.equals(entry.getDisplayName(),
973                                            entry.getDestination()));
974                }
975            } catch (NullPointerException e) {
976                Log.e(TAG, e.getMessage(), e);
977            }
978            editable.setSpan(chip, tokenStart, tokenEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
979            // Add this chip to the list of entries "to replace"
980            if (chip != null) {
981                if (mTemporaryRecipients == null) {
982                    mTemporaryRecipients = new ArrayList<RecipientChip>();
983                }
984                chip.setOriginalText(chipText.toString());
985                mTemporaryRecipients.add(chip);
986            }
987        }
988    }
989
990    private static boolean isPhoneNumber(String number) {
991        // TODO: replace this function with libphonenumber's isPossibleNumber (see
992        // PhoneNumberUtil). One complication is that it requires the sender's region which
993        // comes from the CurrentCountryIso. For now, let's just do this simple match.
994        if (TextUtils.isEmpty(number)) {
995            return false;
996        }
997
998        Matcher match = PHONE_PATTERN.matcher(number);
999        return match.matches();
1000    }
1001
1002    private RecipientEntry createTokenizedEntry(String token) {
1003        if (TextUtils.isEmpty(token)) {
1004            return null;
1005        }
1006        if (isPhoneQuery() && isPhoneNumber(token)) {
1007            return RecipientEntry
1008                    .constructFakeEntry(token);
1009        }
1010        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
1011        String display = null;
1012        if (isValid(token) && tokens != null && tokens.length > 0) {
1013            // If we can get a name from tokenizing, then generate an entry from
1014            // this.
1015            display = tokens[0].getName();
1016            if (!TextUtils.isEmpty(display)) {
1017                if (!isPhoneQuery()) {
1018                    if (!TextUtils.isEmpty(token)) {
1019                        token = token.trim();
1020                    }
1021                    char charAt = token.charAt(token.length() - 1);
1022                    if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
1023                        token = token.substring(0, token.length() - 1);
1024                    }
1025                }
1026                return RecipientEntry.constructGeneratedEntry(display, token);
1027            } else {
1028                display = tokens[0].getAddress();
1029                if (!TextUtils.isEmpty(display)) {
1030                    return RecipientEntry.constructFakeEntry(display);
1031                }
1032            }
1033        }
1034        // Unable to validate the token or to create a valid token from it.
1035        // Just create a chip the user can edit.
1036        String validatedToken = null;
1037        if (mValidator != null && !mValidator.isValid(token)) {
1038            // Try fixing up the entry using the validator.
1039            validatedToken = mValidator.fixText(token).toString();
1040            if (!TextUtils.isEmpty(validatedToken)) {
1041                if (validatedToken.contains(token)) {
1042                    // protect against the case of a validator with a null domain,
1043                    // which doesn't add a domain to the token
1044                    Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
1045                    if (tokenized.length > 0) {
1046                        validatedToken = tokenized[0].getAddress();
1047                    }
1048                } else {
1049                    // We ran into a case where the token was invalid and removed
1050                    // by the validator. In this case, just use the original token
1051                    // and let the user sort out the error chip.
1052                    validatedToken = null;
1053                }
1054            }
1055        }
1056        // Otherwise, fallback to just creating an editable email address chip.
1057        return RecipientEntry
1058                .constructFakeEntry(!TextUtils.isEmpty(validatedToken) ? validatedToken : token);
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);
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        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
1327            return true;
1328        }
1329
1330        return super.onKeyDown(keyCode, event);
1331    }
1332
1333    // Visible for testing.
1334    /* package */ Spannable getSpannable() {
1335        return getText();
1336    }
1337
1338    private int getChipStart(RecipientChip chip) {
1339        return getSpannable().getSpanStart(chip);
1340    }
1341
1342    private int getChipEnd(RecipientChip chip) {
1343        return getSpannable().getSpanEnd(chip);
1344    }
1345
1346    /**
1347     * Instead of filtering on the entire contents of the edit box,
1348     * this subclass method filters on the range from
1349     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
1350     * if the length of that range meets or exceeds {@link #getThreshold}
1351     * and makes sure that the range is not already a Chip.
1352     */
1353    @Override
1354    protected void performFiltering(CharSequence text, int keyCode) {
1355        boolean isCompletedToken = isCompletedToken(text);
1356        if (enoughToFilter() && !isCompletedToken) {
1357            int end = getSelectionEnd();
1358            int start = mTokenizer.findTokenStart(text, end);
1359            // If this is a RecipientChip, don't filter
1360            // on its contents.
1361            Spannable span = getSpannable();
1362            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
1363            if (chips != null && chips.length > 0) {
1364                return;
1365            }
1366        } else if (isCompletedToken) {
1367            return;
1368        }
1369        super.performFiltering(text, keyCode);
1370    }
1371
1372    // Visible for testing.
1373    /*package*/ boolean isCompletedToken(CharSequence text) {
1374        if (TextUtils.isEmpty(text)) {
1375            return false;
1376        }
1377        // Check to see if this is a completed token before filtering.
1378        int end = text.length();
1379        int start = mTokenizer.findTokenStart(text, end);
1380        String token = text.toString().substring(start, end).trim();
1381        if (!TextUtils.isEmpty(token)) {
1382            char atEnd = token.charAt(token.length() - 1);
1383            return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
1384        }
1385        return false;
1386    }
1387
1388    private void clearSelectedChip() {
1389        if (mSelectedChip != null) {
1390            unselectChip(mSelectedChip);
1391            mSelectedChip = null;
1392        }
1393        setCursorVisible(true);
1394    }
1395
1396    /**
1397     * Monitor touch events in the RecipientEditTextView.
1398     * If the view does not have focus, any tap on the view
1399     * will just focus the view. If the view has focus, determine
1400     * if the touch target is a recipient chip. If it is and the chip
1401     * is not selected, select it and clear any other selected chips.
1402     * If it isn't, then select that chip.
1403     */
1404    @Override
1405    public boolean onTouchEvent(MotionEvent event) {
1406        if (!isFocused()) {
1407            // Ignore any chip taps until this view is focused.
1408            return super.onTouchEvent(event);
1409        }
1410        boolean handled = super.onTouchEvent(event);
1411        int action = event.getAction();
1412        boolean chipWasSelected = false;
1413        if (mSelectedChip == null) {
1414            mGestureDetector.onTouchEvent(event);
1415        }
1416        if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
1417            float x = event.getX();
1418            float y = event.getY();
1419            int offset = putOffsetInRange(getOffsetForPosition(x, y));
1420            RecipientChip currentChip = findChip(offset);
1421            if (currentChip != null) {
1422                if (action == MotionEvent.ACTION_UP) {
1423                    if (mSelectedChip != null && mSelectedChip != currentChip) {
1424                        clearSelectedChip();
1425                        mSelectedChip = selectChip(currentChip);
1426                    } else if (mSelectedChip == null) {
1427                        setSelection(getText().length());
1428                        commitDefault();
1429                        mSelectedChip = selectChip(currentChip);
1430                    } else {
1431                        onClick(mSelectedChip, offset, x, y);
1432                    }
1433                }
1434                chipWasSelected = true;
1435                handled = true;
1436            } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) {
1437                chipWasSelected = true;
1438            }
1439        }
1440        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1441            clearSelectedChip();
1442        }
1443        return handled;
1444    }
1445
1446    private void scrollLineIntoView(int line) {
1447        if (mScrollView != null) {
1448            mScrollView.smoothScrollBy(0, calculateOffsetFromBottom(line));
1449        }
1450    }
1451
1452    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
1453            int width, Context context) {
1454        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1455        int bottom;
1456        if (line == getLineCount() -1) {
1457            bottom = 0;
1458        } else {
1459            bottom = -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math.abs(getLineCount() - 1
1460                    - line)));
1461        }
1462        // Align the alternates popup with the left side of the View,
1463        // regardless of the position of the chip tapped.
1464        alternatesPopup.setWidth(width);
1465        alternatesPopup.setAnchorView(this);
1466        alternatesPopup.setVerticalOffset(bottom);
1467        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
1468        alternatesPopup.setOnItemClickListener(mAlternatesListener);
1469        // Clear the checked item.
1470        mCheckedItem = -1;
1471        alternatesPopup.show();
1472        ListView listView = alternatesPopup.getListView();
1473        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1474        // Checked item would be -1 if the adapter has not
1475        // loaded the view that should be checked yet. The
1476        // variable will be set correctly when onCheckedItemChanged
1477        // is called in a separate thread.
1478        if (mCheckedItem != -1) {
1479            listView.setItemChecked(mCheckedItem, true);
1480            mCheckedItem = -1;
1481        }
1482    }
1483
1484    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
1485        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
1486                mAlternatesLayout, ((BaseRecipientAdapter)getAdapter()).getQueryType(), this);
1487    }
1488
1489    private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
1490        return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
1491                .getEntry());
1492    }
1493
1494    @Override
1495    public void onCheckedItemChanged(int position) {
1496        ListView listView = mAlternatesPopup.getListView();
1497        if (listView != null && listView.getCheckedItemCount() == 0) {
1498            listView.setItemChecked(position, true);
1499        }
1500        mCheckedItem = position;
1501    }
1502
1503    // TODO: This algorithm will need a lot of tweaking after more people have used
1504    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1505    // what comes before the finger.
1506    private int putOffsetInRange(int o) {
1507        int offset = o;
1508        Editable text = getText();
1509        int length = text.length();
1510        // Remove whitespace from end to find "real end"
1511        int realLength = length;
1512        for (int i = length - 1; i >= 0; i--) {
1513            if (text.charAt(i) == ' ') {
1514                realLength--;
1515            } else {
1516                break;
1517            }
1518        }
1519
1520        // If the offset is beyond or at the end of the text,
1521        // leave it alone.
1522        if (offset >= realLength) {
1523            return offset;
1524        }
1525        Editable editable = getText();
1526        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1527            // Keep walking backward!
1528            offset--;
1529        }
1530        return offset;
1531    }
1532
1533    private int findText(Editable text, int offset) {
1534        if (text.charAt(offset) != ' ') {
1535            return offset;
1536        }
1537        return -1;
1538    }
1539
1540    private RecipientChip findChip(int offset) {
1541        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1542        // Find the chip that contains this offset.
1543        for (int i = 0; i < chips.length; i++) {
1544            RecipientChip chip = chips[i];
1545            int start = getChipStart(chip);
1546            int end = getChipEnd(chip);
1547            if (offset >= start && offset <= end) {
1548                return chip;
1549            }
1550        }
1551        return null;
1552    }
1553
1554    // Visible for testing.
1555    // Use this method to generate text to add to the list of addresses.
1556    /* package */String createAddressText(RecipientEntry entry) {
1557        String display = entry.getDisplayName();
1558        String address = entry.getDestination();
1559        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1560            display = null;
1561        }
1562        String trimmedDisplayText;
1563        if (isPhoneQuery() && isPhoneNumber(address)) {
1564            trimmedDisplayText = address.trim();
1565        } else {
1566            if (address != null) {
1567                // Tokenize out the address in case the address already
1568                // contained the username as well.
1569                Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1570                if (tokenized != null && tokenized.length > 0) {
1571                    address = tokenized[0].getAddress();
1572                }
1573            }
1574            Rfc822Token token = new Rfc822Token(display, address, null);
1575            trimmedDisplayText = token.toString().trim();
1576        }
1577        int index = trimmedDisplayText.indexOf(",");
1578        return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
1579                && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
1580                .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1581    }
1582
1583    // Visible for testing.
1584    // Use this method to generate text to display in a chip.
1585    /*package*/ String createChipDisplayText(RecipientEntry entry) {
1586        String display = entry.getDisplayName();
1587        String address = entry.getDestination();
1588        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1589            display = null;
1590        }
1591        if (address != null && !(isPhoneQuery() && isPhoneNumber(address))) {
1592            // Tokenize out the address in case the address already
1593            // contained the username as well.
1594            Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1595            if (tokenized != null && tokenized.length > 0) {
1596                address = tokenized[0].getAddress();
1597            }
1598        }
1599        if (!TextUtils.isEmpty(display)) {
1600            return display;
1601        } else if (!TextUtils.isEmpty(address)){
1602            return address;
1603        } else {
1604            return new Rfc822Token(display, address, null).toString();
1605        }
1606    }
1607
1608    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1609        String displayText = createAddressText(entry);
1610        if (TextUtils.isEmpty(displayText)) {
1611            return null;
1612        }
1613        SpannableString chipText = null;
1614        // Always leave a blank space at the end of a chip.
1615        int end = getSelectionEnd();
1616        int start = mTokenizer.findTokenStart(getText(), end);
1617        int textLength = displayText.length()-1;
1618        chipText = new SpannableString(displayText);
1619        if (!mNoChips) {
1620            try {
1621                RecipientChip chip = constructChipSpan(entry, start, pressed,
1622                        false /* leave space for contact icon */);
1623                chipText.setSpan(chip, 0, textLength,
1624                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1625                chip.setOriginalText(chipText.toString());
1626            } catch (NullPointerException e) {
1627                Log.e(TAG, e.getMessage(), e);
1628                return null;
1629            }
1630        }
1631        return chipText;
1632    }
1633
1634    /**
1635     * When an item in the suggestions list has been clicked, create a chip from the
1636     * contact information of the selected item.
1637     */
1638    @Override
1639    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1640        submitItemAtPosition(position);
1641    }
1642
1643    private void submitItemAtPosition(int position) {
1644        RecipientEntry entry = createValidatedEntry(
1645                (RecipientEntry)getAdapter().getItem(position));
1646        if (entry == null) {
1647            return;
1648        }
1649        clearComposingText();
1650
1651        int end = getSelectionEnd();
1652        int start = mTokenizer.findTokenStart(getText(), end);
1653
1654        Editable editable = getText();
1655        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1656        CharSequence chip = createChip(entry, false);
1657        if (chip != null && start >= 0 && end >= 0) {
1658            editable.replace(start, end, chip);
1659        }
1660        sanitizeBetween();
1661    }
1662
1663    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1664        if (item == null) {
1665            return null;
1666        }
1667        final RecipientEntry entry;
1668        // If the display name and the address are the same, or if this is a
1669        // valid contact, but the destination is invalid, then make this a fake
1670        // recipient that is editable.
1671        String destination = item.getDestination();
1672        if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1673            entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(),
1674                    destination);
1675        } else if (RecipientEntry.isCreatedRecipient(item.getContactId())
1676                && (TextUtils.isEmpty(item.getDisplayName())
1677                        || TextUtils.equals(item.getDisplayName(), destination)
1678                        || (mValidator != null && !mValidator.isValid(destination)))) {
1679            entry = RecipientEntry.constructFakeEntry(destination);
1680        } else {
1681            entry = item;
1682        }
1683        return entry;
1684    }
1685
1686    /** Returns a collection of contact Id for each chip inside this View. */
1687    /* package */ Collection<Long> getContactIds() {
1688        final Set<Long> result = new HashSet<Long>();
1689        RecipientChip[] chips = getSortedRecipients();
1690        if (chips != null) {
1691            for (RecipientChip chip : chips) {
1692                result.add(chip.getContactId());
1693            }
1694        }
1695        return result;
1696    }
1697
1698
1699    /** Returns a collection of data Id for each chip inside this View. May be null. */
1700    /* package */ Collection<Long> getDataIds() {
1701        final Set<Long> result = new HashSet<Long>();
1702        RecipientChip [] chips = getSortedRecipients();
1703        if (chips != null) {
1704            for (RecipientChip chip : chips) {
1705                result.add(chip.getDataId());
1706            }
1707        }
1708        return result;
1709    }
1710
1711    // Visible for testing.
1712    /* package */RecipientChip[] getSortedRecipients() {
1713        RecipientChip[] recips = getSpannable()
1714                .getSpans(0, getText().length(), RecipientChip.class);
1715        ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays
1716                .asList(recips));
1717        final Spannable spannable = getSpannable();
1718        Collections.sort(recipientsList, new Comparator<RecipientChip>() {
1719
1720            @Override
1721            public int compare(RecipientChip first, RecipientChip second) {
1722                int firstStart = spannable.getSpanStart(first);
1723                int secondStart = spannable.getSpanStart(second);
1724                if (firstStart < secondStart) {
1725                    return -1;
1726                } else if (firstStart > secondStart) {
1727                    return 1;
1728                } else {
1729                    return 0;
1730                }
1731            }
1732        });
1733        return recipientsList.toArray(new RecipientChip[recipientsList.size()]);
1734    }
1735
1736    @Override
1737    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1738        return false;
1739    }
1740
1741    @Override
1742    public void onDestroyActionMode(ActionMode mode) {
1743    }
1744
1745    @Override
1746    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1747        return false;
1748    }
1749
1750    /**
1751     * No chips are selectable.
1752     */
1753    @Override
1754    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1755        return false;
1756    }
1757
1758    // Visible for testing.
1759    /* package */ImageSpan getMoreChip() {
1760        MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
1761                MoreImageSpan.class);
1762        return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
1763    }
1764
1765    private MoreImageSpan createMoreSpan(int count) {
1766        String moreText = String.format(mMoreItem.getText().toString(), count);
1767        TextPaint morePaint = new TextPaint(getPaint());
1768        morePaint.setTextSize(mMoreItem.getTextSize());
1769        morePaint.setColor(mMoreItem.getCurrentTextColor());
1770        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1771                + mMoreItem.getPaddingRight();
1772        int height = getLineHeight();
1773        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1774        Canvas canvas = new Canvas(drawable);
1775        int adjustedHeight = height;
1776        Layout layout = getLayout();
1777        if (layout != null) {
1778            adjustedHeight -= layout.getLineDescent(0);
1779        }
1780        canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
1781
1782        Drawable result = new BitmapDrawable(getResources(), drawable);
1783        result.setBounds(0, 0, width, height);
1784        return new MoreImageSpan(result);
1785    }
1786
1787    // Visible for testing.
1788    /*package*/ void createMoreChipPlainText() {
1789        // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
1790        Editable text = getText();
1791        int start = 0;
1792        int end = start;
1793        for (int i = 0; i < CHIP_LIMIT; i++) {
1794            end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1795            start = end; // move to the next token and get its end.
1796        }
1797        // Now, count total addresses.
1798        start = 0;
1799        int tokenCount = countTokens(text);
1800        MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
1801        SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
1802        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1803        text.replace(end, text.length(), chipText);
1804        mMoreChip = moreSpan;
1805    }
1806
1807    // Visible for testing.
1808    /* package */int countTokens(Editable text) {
1809        int tokenCount = 0;
1810        int start = 0;
1811        while (start < text.length()) {
1812            start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1813            tokenCount++;
1814            if (start >= text.length()) {
1815                break;
1816            }
1817        }
1818        return tokenCount;
1819    }
1820
1821    /**
1822     * Create the more chip. The more chip is text that replaces any chips that
1823     * do not fit in the pre-defined available space when the
1824     * RecipientEditTextView loses focus.
1825     */
1826    // Visible for testing.
1827    /* package */ void createMoreChip() {
1828        if (mNoChips) {
1829            createMoreChipPlainText();
1830            return;
1831        }
1832
1833        if (!mShouldShrink) {
1834            return;
1835        }
1836        ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
1837        if (tempMore.length > 0) {
1838            getSpannable().removeSpan(tempMore[0]);
1839        }
1840        RecipientChip[] recipients = getSortedRecipients();
1841
1842        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1843            mMoreChip = null;
1844            return;
1845        }
1846        Spannable spannable = getSpannable();
1847        int numRecipients = recipients.length;
1848        int overage = numRecipients - CHIP_LIMIT;
1849        MoreImageSpan moreSpan = createMoreSpan(overage);
1850        mRemovedSpans = new ArrayList<RecipientChip>();
1851        int totalReplaceStart = 0;
1852        int totalReplaceEnd = 0;
1853        Editable text = getText();
1854        for (int i = numRecipients - overage; i < recipients.length; i++) {
1855            mRemovedSpans.add(recipients[i]);
1856            if (i == numRecipients - overage) {
1857                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1858            }
1859            if (i == recipients.length - 1) {
1860                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1861            }
1862            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
1863                int spanStart = spannable.getSpanStart(recipients[i]);
1864                int spanEnd = spannable.getSpanEnd(recipients[i]);
1865                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
1866            }
1867            spannable.removeSpan(recipients[i]);
1868        }
1869        if (totalReplaceEnd < text.length()) {
1870            totalReplaceEnd = text.length();
1871        }
1872        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1873        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1874        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1875        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1876        text.replace(start, end, chipText);
1877        mMoreChip = moreSpan;
1878        // If adding the +more chip goes over the limit, resize accordingly.
1879        if (!isPhoneQuery() && getLineCount() > mMaxLines) {
1880            setMaxLines(getLineCount());
1881        }
1882    }
1883
1884    /**
1885     * Replace the more chip, if it exists, with all of the recipient chips it had
1886     * replaced when the RecipientEditTextView gains focus.
1887     */
1888    // Visible for testing.
1889    /*package*/ void removeMoreChip() {
1890        if (mMoreChip != null) {
1891            Spannable span = getSpannable();
1892            span.removeSpan(mMoreChip);
1893            mMoreChip = null;
1894            // Re-add the spans that were removed.
1895            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1896                // Recreate each removed span.
1897                RecipientChip[] recipients = getSortedRecipients();
1898                // Start the search for tokens after the last currently visible
1899                // chip.
1900                if (recipients == null || recipients.length == 0) {
1901                    return;
1902                }
1903                int end = span.getSpanEnd(recipients[recipients.length - 1]);
1904                Editable editable = getText();
1905                for (RecipientChip chip : mRemovedSpans) {
1906                    int chipStart;
1907                    int chipEnd;
1908                    String token;
1909                    // Need to find the location of the chip, again.
1910                    token = (String) chip.getOriginalText();
1911                    // As we find the matching recipient for the remove spans,
1912                    // reduce the size of the string we need to search.
1913                    // That way, if there are duplicates, we always find the correct
1914                    // recipient.
1915                    chipStart = editable.toString().indexOf(token, end);
1916                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
1917                    // Only set the span if we found a matching token.
1918                    if (chipStart != -1) {
1919                        editable.setSpan(chip, chipStart, chipEnd,
1920                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1921                    }
1922                }
1923                mRemovedSpans.clear();
1924            }
1925        }
1926    }
1927
1928    /**
1929     * Show specified chip as selected. If the RecipientChip is just an email address,
1930     * selecting the chip will take the contents of the chip and place it at
1931     * the end of the RecipientEditTextView for inline editing. If the
1932     * RecipientChip is a complete contact, then selecting the chip
1933     * will change the background color of the chip, show the delete icon,
1934     * and a popup window with the address in use highlighted and any other
1935     * alternate addresses for the contact.
1936     * @param currentChip Chip to select.
1937     * @return A RecipientChip in the selected state or null if the chip
1938     * just contained an email address.
1939     */
1940    private RecipientChip selectChip(RecipientChip currentChip) {
1941        if (shouldShowEditableText(currentChip)) {
1942            CharSequence text = currentChip.getValue();
1943            Editable editable = getText();
1944            Spannable spannable = getSpannable();
1945            int spanStart = spannable.getSpanStart(currentChip);
1946            int spanEnd = spannable.getSpanEnd(currentChip);
1947            spannable.removeSpan(currentChip);
1948            editable.delete(spanStart, spanEnd);
1949            setCursorVisible(true);
1950            setSelection(editable.length());
1951            editable.append(text);
1952            return constructChipSpan(
1953                    RecipientEntry.constructFakeEntry((String) text),
1954                    getSelectionStart(), true, false);
1955        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1956            int start = getChipStart(currentChip);
1957            int end = getChipEnd(currentChip);
1958            getSpannable().removeSpan(currentChip);
1959            RecipientChip newChip;
1960            try {
1961                if (mNoChips) {
1962                    return null;
1963                }
1964                newChip = constructChipSpan(currentChip.getEntry(), start, true, false);
1965            } catch (NullPointerException e) {
1966                Log.e(TAG, e.getMessage(), e);
1967                return null;
1968            }
1969            Editable editable = getText();
1970            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1971            if (start == -1 || end == -1) {
1972                Log.d(TAG, "The chip being selected no longer exists but should.");
1973            } else {
1974                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1975            }
1976            newChip.setSelected(true);
1977            if (shouldShowEditableText(newChip)) {
1978                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1979            }
1980            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1981            setCursorVisible(false);
1982            return newChip;
1983        } else {
1984            int start = getChipStart(currentChip);
1985            int end = getChipEnd(currentChip);
1986            getSpannable().removeSpan(currentChip);
1987            RecipientChip newChip;
1988            try {
1989                newChip = constructChipSpan(currentChip.getEntry(), start, true, false);
1990            } catch (NullPointerException e) {
1991                Log.e(TAG, e.getMessage(), e);
1992                return null;
1993            }
1994            Editable editable = getText();
1995            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1996            if (start == -1 || end == -1) {
1997                Log.d(TAG, "The chip being selected no longer exists but should.");
1998            } else {
1999                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2000            }
2001            newChip.setSelected(true);
2002            if (shouldShowEditableText(newChip)) {
2003                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
2004            }
2005            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
2006            setCursorVisible(false);
2007            return newChip;
2008        }
2009    }
2010
2011    private boolean shouldShowEditableText(RecipientChip currentChip) {
2012        long contactId = currentChip.getContactId();
2013        return contactId == RecipientEntry.INVALID_CONTACT
2014                || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2015    }
2016
2017    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
2018            int width, Context context) {
2019        int line = getLayout().getLineForOffset(getChipStart(currentChip));
2020        int bottom = calculateOffsetFromBottom(line);
2021        // Align the alternates popup with the left side of the View,
2022        // regardless of the position of the chip tapped.
2023        popup.setWidth(width);
2024        popup.setAnchorView(this);
2025        popup.setVerticalOffset(bottom);
2026        popup.setAdapter(createSingleAddressAdapter(currentChip));
2027        popup.setOnItemClickListener(new OnItemClickListener() {
2028            @Override
2029            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2030                unselectChip(currentChip);
2031                popup.dismiss();
2032            }
2033        });
2034        popup.show();
2035        ListView listView = popup.getListView();
2036        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
2037        listView.setItemChecked(0, true);
2038    }
2039
2040    /**
2041     * Remove selection from this chip. Unselecting a RecipientChip will render
2042     * the chip without a delete icon and with an unfocused background. This is
2043     * called when the RecipientChip no longer has focus.
2044     */
2045    private void unselectChip(RecipientChip chip) {
2046        int start = getChipStart(chip);
2047        int end = getChipEnd(chip);
2048        Editable editable = getText();
2049        mSelectedChip = null;
2050        if (start == -1 || end == -1) {
2051            Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
2052            setSelection(editable.length());
2053            commitDefault();
2054        } else {
2055            getSpannable().removeSpan(chip);
2056            QwertyKeyListener.markAsReplaced(editable, start, end, "");
2057            editable.removeSpan(chip);
2058            try {
2059                if (!mNoChips) {
2060                    editable.setSpan(constructChipSpan(chip.getEntry(), start, false, false),
2061                            start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2062                }
2063            } catch (NullPointerException e) {
2064                Log.e(TAG, e.getMessage(), e);
2065            }
2066        }
2067        setCursorVisible(true);
2068        setSelection(editable.length());
2069        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
2070            mAlternatesPopup.dismiss();
2071        }
2072    }
2073
2074    /**
2075     * Return whether a touch event was inside the delete target of
2076     * a selected chip. It is in the delete target if:
2077     * 1) the x and y points of the event are within the
2078     * delete assset.
2079     * 2) the point tapped would have caused a cursor to appear
2080     * right after the selected chip.
2081     * @return boolean
2082     */
2083    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
2084        // Figure out the bounds of this chip and whether or not
2085        // the user clicked in the X portion.
2086        return chip.isSelected() && offset == getChipEnd(chip);
2087    }
2088
2089    /**
2090     * Remove the chip and any text associated with it from the RecipientEditTextView.
2091     */
2092    // Visible for testing.
2093    /*pacakge*/ void removeChip(RecipientChip chip) {
2094        Spannable spannable = getSpannable();
2095        int spanStart = spannable.getSpanStart(chip);
2096        int spanEnd = spannable.getSpanEnd(chip);
2097        Editable text = getText();
2098        int toDelete = spanEnd;
2099        boolean wasSelected = chip == mSelectedChip;
2100        // Clear that there is a selected chip before updating any text.
2101        if (wasSelected) {
2102            mSelectedChip = null;
2103        }
2104        // Always remove trailing spaces when removing a chip.
2105        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
2106            toDelete++;
2107        }
2108        spannable.removeSpan(chip);
2109        if (spanStart >= 0 && toDelete > 0) {
2110            text.delete(spanStart, toDelete);
2111        }
2112        if (wasSelected) {
2113            clearSelectedChip();
2114        }
2115    }
2116
2117    /**
2118     * Replace this currently selected chip with a new chip
2119     * that uses the contact data provided.
2120     */
2121    // Visible for testing.
2122    /*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) {
2123        boolean wasSelected = chip == mSelectedChip;
2124        if (wasSelected) {
2125            mSelectedChip = null;
2126        }
2127        int start = getChipStart(chip);
2128        int end = getChipEnd(chip);
2129        getSpannable().removeSpan(chip);
2130        Editable editable = getText();
2131        CharSequence chipText = createChip(entry, false);
2132        if (chipText != null) {
2133            if (start == -1 || end == -1) {
2134                Log.e(TAG, "The chip to replace does not exist but should.");
2135                editable.insert(0, chipText);
2136            } else {
2137                if (!TextUtils.isEmpty(chipText)) {
2138                    // There may be a space to replace with this chip's new
2139                    // associated space. Check for it
2140                    int toReplace = end;
2141                    while (toReplace >= 0 && toReplace < editable.length()
2142                            && editable.charAt(toReplace) == ' ') {
2143                        toReplace++;
2144                    }
2145                    editable.replace(start, toReplace, chipText);
2146                }
2147            }
2148        }
2149        setCursorVisible(true);
2150        if (wasSelected) {
2151            clearSelectedChip();
2152        }
2153    }
2154
2155    /**
2156     * Handle click events for a chip. When a selected chip receives a click
2157     * event, see if that event was in the delete icon. If so, delete it.
2158     * Otherwise, unselect the chip.
2159     */
2160    public void onClick(RecipientChip chip, int offset, float x, float y) {
2161        if (chip.isSelected()) {
2162            if (isInDelete(chip, offset, x, y)) {
2163                removeChip(chip);
2164            } else {
2165                clearSelectedChip();
2166            }
2167        }
2168    }
2169
2170    private boolean chipsPending() {
2171        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
2172    }
2173
2174    @Override
2175    public void removeTextChangedListener(TextWatcher watcher) {
2176        mTextWatcher = null;
2177        super.removeTextChangedListener(watcher);
2178    }
2179
2180    private class RecipientTextWatcher implements TextWatcher {
2181
2182        @Override
2183        public void afterTextChanged(Editable s) {
2184            // If the text has been set to null or empty, make sure we remove
2185            // all the spans we applied.
2186            if (TextUtils.isEmpty(s)) {
2187                // Remove all the chips spans.
2188                Spannable spannable = getSpannable();
2189                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
2190                        RecipientChip.class);
2191                for (RecipientChip chip : chips) {
2192                    spannable.removeSpan(chip);
2193                }
2194                if (mMoreChip != null) {
2195                    spannable.removeSpan(mMoreChip);
2196                }
2197                return;
2198            }
2199            // Get whether there are any recipients pending addition to the
2200            // view. If there are, don't do anything in the text watcher.
2201            if (chipsPending()) {
2202                return;
2203            }
2204            // If the user is editing a chip, don't clear it.
2205            if (mSelectedChip != null
2206                    && shouldShowEditableText(mSelectedChip)) {
2207                setCursorVisible(true);
2208                setSelection(getText().length());
2209                clearSelectedChip();
2210            }
2211            int length = s.length();
2212            // Make sure there is content there to parse and that it is
2213            // not just the commit character.
2214            if (length > 1) {
2215                char last;
2216                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2217                int len = length() - 1;
2218                if (end != len) {
2219                    last = s.charAt(end);
2220                } else {
2221                    last = s.charAt(len);
2222                }
2223                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
2224                    commitByCharacter();
2225                } else 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            // This is a delete; check to see if the insertion point is on a space
2245            // following a chip.
2246            if (before - count == 1) {
2247                // If the item deleted is a space, and the thing before the
2248                // space is a chip, delete the entire span.
2249                int selStart = getSelectionStart();
2250                RecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
2251                        RecipientChip.class);
2252                if (repl.length > 0) {
2253                    // There is a chip there! Just remove it.
2254                    Editable editable = getText();
2255                    // Add the separator token.
2256                    int tokenStart = mTokenizer.findTokenStart(editable, selStart);
2257                    int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart);
2258                    tokenEnd = tokenEnd + 1;
2259                    if (tokenEnd > editable.length()) {
2260                        tokenEnd = editable.length();
2261                    }
2262                    editable.delete(tokenStart, tokenEnd);
2263                    getSpannable().removeSpan(repl[0]);
2264                }
2265            }
2266        }
2267
2268        @Override
2269        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2270            // Do nothing.
2271        }
2272    }
2273
2274    /**
2275     * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2276     */
2277    private void handlePasteClip(ClipData clip) {
2278        removeTextChangedListener(mTextWatcher);
2279
2280        if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
2281            for (int i = 0; i < clip.getItemCount(); i++) {
2282                CharSequence paste = clip.getItemAt(i).getText();
2283                if (paste != null) {
2284                    int start = getSelectionStart();
2285                    int end = getSelectionEnd();
2286                    Editable editable = getText();
2287                    if (start >= 0 && end >= 0 && start != end) {
2288                        editable.append(paste, start, end);
2289                    } else {
2290                        editable.insert(end, paste);
2291                    }
2292                    handlePasteAndReplace();
2293                }
2294            }
2295        }
2296
2297        mHandler.post(mAddTextWatcher);
2298    }
2299
2300    @Override
2301    public boolean onTextContextMenuItem(int id) {
2302        if (id == android.R.id.paste) {
2303            ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2304                    Context.CLIPBOARD_SERVICE);
2305            handlePasteClip(clipboard.getPrimaryClip());
2306            return true;
2307        }
2308        return super.onTextContextMenuItem(id);
2309    }
2310
2311    private void handlePasteAndReplace() {
2312        ArrayList<RecipientChip> created = handlePaste();
2313        if (created != null && created.size() > 0) {
2314            // Perform reverse lookups on the pasted contacts.
2315            IndividualReplacementTask replace = new IndividualReplacementTask();
2316            replace.execute(created);
2317        }
2318    }
2319
2320    // Visible for testing.
2321    /* package */ArrayList<RecipientChip> handlePaste() {
2322        String text = getText().toString();
2323        int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2324        String lastAddress = text.substring(originalTokenStart);
2325        int tokenStart = originalTokenStart;
2326        int prevTokenStart = tokenStart;
2327        RecipientChip findChip = null;
2328        ArrayList<RecipientChip> created = new ArrayList<RecipientChip>();
2329        if (tokenStart != 0) {
2330            // There are things before this!
2331            while (tokenStart != 0 && findChip == null) {
2332                prevTokenStart = tokenStart;
2333                tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2334                findChip = findChip(tokenStart);
2335            }
2336            if (tokenStart != originalTokenStart) {
2337                if (findChip != null) {
2338                    tokenStart = prevTokenStart;
2339                }
2340                int tokenEnd;
2341                RecipientChip createdChip;
2342                while (tokenStart < originalTokenStart) {
2343                    tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(),
2344                            tokenStart));
2345                    commitChip(tokenStart, tokenEnd, getText());
2346                    createdChip = findChip(tokenStart);
2347                    if (createdChip == null) {
2348                        break;
2349                    }
2350                    // +1 for the space at the end.
2351                    tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
2352                    created.add(createdChip);
2353                }
2354            }
2355        }
2356        // Take a look at the last token. If the token has been completed with a
2357        // commit character, create a chip.
2358        if (isCompletedToken(lastAddress)) {
2359            Editable editable = getText();
2360            tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2361            commitChip(tokenStart, editable.length(), editable);
2362            created.add(findChip(tokenStart));
2363        }
2364        return created;
2365    }
2366
2367    // Visible for testing.
2368    /* package */int movePastTerminators(int tokenEnd) {
2369        if (tokenEnd >= length()) {
2370            return tokenEnd;
2371        }
2372        char atEnd = getText().toString().charAt(tokenEnd);
2373        if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2374            tokenEnd++;
2375        }
2376        // This token had not only an end token character, but also a space
2377        // separating it from the next token.
2378        if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2379            tokenEnd++;
2380        }
2381        return tokenEnd;
2382    }
2383
2384    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
2385        private RecipientChip createFreeChip(RecipientEntry entry) {
2386            try {
2387                if (mNoChips) {
2388                    return null;
2389                }
2390                return constructChipSpan(entry, -1, false,
2391                        false /*leave space for contact icon */);
2392            } catch (NullPointerException e) {
2393                Log.e(TAG, e.getMessage(), e);
2394                return null;
2395            }
2396        }
2397
2398        @Override
2399        protected Void doInBackground(Void... params) {
2400            if (mIndividualReplacements != null) {
2401                mIndividualReplacements.cancel(true);
2402            }
2403            // For each chip in the list, look up the matching contact.
2404            // If there is a match, replace that chip with the matching
2405            // chip.
2406            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
2407            RecipientChip[] existingChips = getSortedRecipients();
2408            for (int i = 0; i < existingChips.length; i++) {
2409                originalRecipients.add(existingChips[i]);
2410            }
2411            if (mRemovedSpans != null) {
2412                originalRecipients.addAll(mRemovedSpans);
2413            }
2414            ArrayList<String> addresses = new ArrayList<String>();
2415            RecipientChip chip;
2416            for (int i = 0; i < originalRecipients.size(); i++) {
2417                chip = originalRecipients.get(i);
2418                if (chip != null) {
2419                    addresses.add(createAddressText(chip.getEntry()));
2420                }
2421            }
2422            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2423                    .getMatchingRecipients(getContext(), addresses);
2424            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
2425            for (final RecipientChip temp : originalRecipients) {
2426                RecipientEntry entry = null;
2427                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2428                        && getSpannable().getSpanStart(temp) != -1) {
2429                    // Replace this.
2430                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
2431                            .getDestination())));
2432                }
2433                if (entry != null) {
2434                    replacements.add(createFreeChip(entry));
2435                } else {
2436                    replacements.add(temp);
2437                }
2438            }
2439            if (replacements != null && replacements.size() > 0) {
2440                mHandler.post(new Runnable() {
2441                    @Override
2442                    public void run() {
2443                        Editable oldText = getText();
2444                        int start, end;
2445                        int i = 0;
2446                        for (RecipientChip chip : originalRecipients) {
2447                            // Find the location of the chip in the text currently shown.
2448                            start = oldText.getSpanStart(chip);
2449                            if (start != -1) {
2450                                end = oldText.getSpanEnd(chip);
2451                                oldText.removeSpan(chip);
2452                                RecipientChip replacement = replacements.get(i);
2453                                // Make sure we always have just 1 space at the
2454                                // end to separate this chip from the next chip.
2455                                SpannableString displayText = new SpannableString(
2456                                        createAddressText(replacement.getEntry()).trim() + " ");
2457                                displayText.setSpan(replacement, 0, displayText.length()-1,
2458                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2459                                // Replace the old text we found with with the new display text,
2460                                // which now may also contain the display name of the recipient.
2461                                oldText.replace(start, end, displayText);
2462                                replacement.setOriginalText(displayText.toString());
2463                            }
2464                            i++;
2465                        }
2466                        originalRecipients.clear();
2467                    }
2468                });
2469            }
2470            return null;
2471        }
2472    }
2473
2474    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
2475        @SuppressWarnings("unchecked")
2476        @Override
2477        protected Void doInBackground(Object... params) {
2478            // For each chip in the list, look up the matching contact.
2479            // If there is a match, replace that chip with the matching
2480            // chip.
2481            final ArrayList<RecipientChip> originalRecipients =
2482                    (ArrayList<RecipientChip>) params[0];
2483            ArrayList<String> addresses = new ArrayList<String>();
2484            RecipientChip chip;
2485            for (int i = 0; i < originalRecipients.size(); i++) {
2486                chip = originalRecipients.get(i);
2487                if (chip != null) {
2488                    addresses.add(createAddressText(chip.getEntry()));
2489                }
2490            }
2491            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2492                    .getMatchingRecipients(getContext(), addresses);
2493            for (final RecipientChip temp : originalRecipients) {
2494                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2495                        && getSpannable().getSpanStart(temp) != -1) {
2496                    // Replace this.
2497                    RecipientEntry entry = createValidatedEntry(entries.get(tokenizeAddress(
2498                            temp.getEntry().getDestination()).toLowerCase()));
2499                    // If we don't have a validated contact match, just use the
2500                    // entry as it existed before.
2501                    if (entry == null && !isPhoneQuery()) {
2502                        entry = temp.getEntry();
2503                    }
2504                    final RecipientEntry tempEntry = entry;
2505                    if (tempEntry != null) {
2506                        mHandler.post(new Runnable() {
2507                            @Override
2508                            public void run() {
2509                                replaceChip(temp, tempEntry);
2510                            }
2511                        });
2512                    }
2513                }
2514            }
2515            return null;
2516        }
2517    }
2518
2519
2520    /**
2521     * MoreImageSpan is a simple class created for tracking the existence of a
2522     * more chip across activity restarts/
2523     */
2524    private class MoreImageSpan extends ImageSpan {
2525        public MoreImageSpan(Drawable b) {
2526            super(b);
2527        }
2528    }
2529
2530    @Override
2531    public boolean onDown(MotionEvent e) {
2532        return false;
2533    }
2534
2535    @Override
2536    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2537        // Do nothing.
2538        return false;
2539    }
2540
2541    @Override
2542    public void onLongPress(MotionEvent event) {
2543        if (mSelectedChip != null) {
2544            return;
2545        }
2546        float x = event.getX();
2547        float y = event.getY();
2548        int offset = putOffsetInRange(getOffsetForPosition(x, y));
2549        RecipientChip currentChip = findChip(offset);
2550        if (currentChip != null) {
2551            if (mDragEnabled) {
2552                // Start drag-and-drop for the selected chip.
2553                startDrag(currentChip);
2554            } else {
2555                // Copy the selected chip email address.
2556                showCopyDialog(currentChip.getEntry().getDestination());
2557            }
2558        }
2559    }
2560
2561    /**
2562     * Enables drag-and-drop for chips.
2563     */
2564    public void enableDrag() {
2565        mDragEnabled = true;
2566    }
2567
2568    /**
2569     * Starts drag-and-drop for the selected chip.
2570     */
2571    private void startDrag(RecipientChip currentChip) {
2572        String address = currentChip.getEntry().getDestination();
2573        ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
2574
2575        // Start drag mode.
2576        startDrag(data, new RecipientChipShadow(currentChip), null, 0);
2577
2578        // Remove the current chip, so drag-and-drop will result in a move.
2579        // TODO (phamm): consider readd this chip if it's dropped outside a target.
2580        removeChip(currentChip);
2581    }
2582
2583    /**
2584     * Handles drag event.
2585     */
2586    @Override
2587    public boolean onDragEvent(DragEvent event) {
2588        switch (event.getAction()) {
2589            case DragEvent.ACTION_DRAG_STARTED:
2590                // Only handle plain text drag and drop.
2591                return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
2592            case DragEvent.ACTION_DRAG_ENTERED:
2593                requestFocus();
2594                return true;
2595            case DragEvent.ACTION_DROP:
2596                handlePasteClip(event.getClipData());
2597                return true;
2598        }
2599        return false;
2600    }
2601
2602    /**
2603     * Drag shadow for a {@link RecipientChip}.
2604     */
2605    private final class RecipientChipShadow extends DragShadowBuilder {
2606        private final RecipientChip mChip;
2607
2608        public RecipientChipShadow(RecipientChip chip) {
2609            mChip = chip;
2610        }
2611
2612        @Override
2613        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
2614            Rect rect = mChip.getDrawable().getBounds();
2615            shadowSize.set(rect.width(), rect.height());
2616            shadowTouchPoint.set(rect.centerX(), rect.centerY());
2617        }
2618
2619        @Override
2620        public void onDrawShadow(Canvas canvas) {
2621            mChip.getDrawable().draw(canvas);
2622        }
2623    }
2624
2625    private void showCopyDialog(final String address) {
2626        mCopyAddress = address;
2627        mCopyDialog.setTitle(address);
2628        mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
2629        mCopyDialog.setCancelable(true);
2630        mCopyDialog.setCanceledOnTouchOutside(true);
2631        Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
2632        button.setOnClickListener(this);
2633        int btnTitleId;
2634        if (isPhoneQuery()) {
2635            btnTitleId = R.string.copy_number;
2636        } else {
2637            btnTitleId = R.string.copy_email;
2638        }
2639        String buttonTitle = getContext().getResources().getString(btnTitleId);
2640        button.setText(buttonTitle);
2641        mCopyDialog.setOnDismissListener(this);
2642        mCopyDialog.show();
2643    }
2644
2645    @Override
2646    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
2647        // Do nothing.
2648        return false;
2649    }
2650
2651    @Override
2652    public void onShowPress(MotionEvent e) {
2653        // Do nothing.
2654    }
2655
2656    @Override
2657    public boolean onSingleTapUp(MotionEvent e) {
2658        // Do nothing.
2659        return false;
2660    }
2661
2662    @Override
2663    public void onDismiss(DialogInterface dialog) {
2664        mCopyAddress = null;
2665    }
2666
2667    @Override
2668    public void onClick(View v) {
2669        // Copy this to the clipboard.
2670        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2671                Context.CLIPBOARD_SERVICE);
2672        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
2673        mCopyDialog.dismiss();
2674    }
2675
2676    protected boolean isPhoneQuery() {
2677        return getAdapter() != null
2678                && ((BaseRecipientAdapter) getAdapter()).getQueryType()
2679                    == BaseRecipientAdapter.QUERY_TYPE_PHONE;
2680    }
2681}
2682