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