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