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