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