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