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