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