RecipientEditTextView.java revision bae3fba541f49eac5a397a9cef309391d9a37fe5
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    private void clearSelectedChip() {
1629        if (mSelectedChip != null) {
1630            unselectChip(mSelectedChip);
1631            mSelectedChip = null;
1632        }
1633        setCursorVisible(true);
1634    }
1635
1636    /**
1637     * Monitor touch events in the RecipientEditTextView.
1638     * If the view does not have focus, any tap on the view
1639     * will just focus the view. If the view has focus, determine
1640     * if the touch target is a recipient chip. If it is and the chip
1641     * is not selected, select it and clear any other selected chips.
1642     * If it isn't, then select that chip.
1643     */
1644    @Override
1645    public boolean onTouchEvent(MotionEvent event) {
1646        if (!isFocused()) {
1647            // Ignore any chip taps until this view is focused.
1648            return super.onTouchEvent(event);
1649        }
1650        boolean handled = super.onTouchEvent(event);
1651        int action = event.getAction();
1652        boolean chipWasSelected = false;
1653        if (mSelectedChip == null) {
1654            mGestureDetector.onTouchEvent(event);
1655        }
1656        if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
1657            float x = event.getX();
1658            float y = event.getY();
1659            int offset = putOffsetInRange(x, y);
1660            DrawableRecipientChip currentChip = findChip(offset);
1661            if (currentChip != null) {
1662                if (action == MotionEvent.ACTION_UP) {
1663                    if (mSelectedChip != null && mSelectedChip != currentChip) {
1664                        clearSelectedChip();
1665                        mSelectedChip = selectChip(currentChip);
1666                    } else if (mSelectedChip == null) {
1667                        setSelection(getText().length());
1668                        commitDefault();
1669                        mSelectedChip = selectChip(currentChip);
1670                    } else {
1671                        onClick(mSelectedChip);
1672                    }
1673                }
1674                chipWasSelected = true;
1675                handled = true;
1676            } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) {
1677                chipWasSelected = true;
1678            }
1679        }
1680        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1681            clearSelectedChip();
1682        }
1683        return handled;
1684    }
1685
1686    private void scrollLineIntoView(int line) {
1687        if (mScrollView != null) {
1688            mScrollView.smoothScrollBy(0, calculateOffsetFromBottom(line));
1689        }
1690    }
1691
1692    private void showAlternates(final DrawableRecipientChip currentChip,
1693            final ListPopupWindow alternatesPopup) {
1694        new AsyncTask<Void, Void, ListAdapter>() {
1695            @Override
1696            protected ListAdapter doInBackground(final Void... params) {
1697                return createAlternatesAdapter(currentChip);
1698            }
1699
1700            @Override
1701            protected void onPostExecute(final ListAdapter result) {
1702                if (!mAttachedToWindow) {
1703                    return;
1704                }
1705                int line = getLayout().getLineForOffset(getChipStart(currentChip));
1706                int bottomOffset = calculateOffsetFromBottomToTop(line);
1707
1708                // Align the alternates popup with the left side of the View,
1709                // regardless of the position of the chip tapped.
1710                alternatesPopup.setAnchorView((mAlternatePopupAnchor != null) ?
1711                        mAlternatePopupAnchor : RecipientEditTextView.this);
1712                alternatesPopup.setVerticalOffset(bottomOffset);
1713                alternatesPopup.setAdapter(result);
1714                alternatesPopup.setOnItemClickListener(mAlternatesListener);
1715                // Clear the checked item.
1716                mCheckedItem = -1;
1717                alternatesPopup.show();
1718                ListView listView = alternatesPopup.getListView();
1719                listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1720                // Checked item would be -1 if the adapter has not
1721                // loaded the view that should be checked yet. The
1722                // variable will be set correctly when onCheckedItemChanged
1723                // is called in a separate thread.
1724                if (mCheckedItem != -1) {
1725                    listView.setItemChecked(mCheckedItem, true);
1726                    mCheckedItem = -1;
1727                }
1728            }
1729        }.execute((Void[]) null);
1730    }
1731
1732    private ListAdapter createAlternatesAdapter(DrawableRecipientChip chip) {
1733        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(),
1734                chip.getDirectoryId(), chip.getLookupKey(), chip.getDataId(),
1735                getAdapter().getQueryType(), this, mDropdownChipLayouter,
1736                constructStateListDeleteDrawable());
1737    }
1738
1739    private ListAdapter createSingleAddressAdapter(DrawableRecipientChip currentChip) {
1740        return new SingleRecipientArrayAdapter(getContext(), currentChip.getEntry(),
1741                mDropdownChipLayouter, constructStateListDeleteDrawable());
1742    }
1743
1744    private StateListDrawable constructStateListDeleteDrawable() {
1745        // Construct the StateListDrawable from deleteDrawable
1746        StateListDrawable deleteDrawable = new StateListDrawable();
1747        if (!mDisableDelete) {
1748            deleteDrawable.addState(new int[]{android.R.attr.state_activated}, mChipDelete);
1749        }
1750        deleteDrawable.addState(new int[0], null);
1751        return deleteDrawable;
1752    }
1753
1754    @Override
1755    public void onCheckedItemChanged(int position) {
1756        ListView listView = mAlternatesPopup.getListView();
1757        if (listView != null && listView.getCheckedItemCount() == 0) {
1758            listView.setItemChecked(position, true);
1759        }
1760        mCheckedItem = position;
1761    }
1762
1763    private int putOffsetInRange(final float x, final float y) {
1764        final int offset;
1765
1766        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1767            offset = getOffsetForPosition(x, y);
1768        } else {
1769            offset = supportGetOffsetForPosition(x, y);
1770        }
1771
1772        return putOffsetInRange(offset);
1773    }
1774
1775    // TODO: This algorithm will need a lot of tweaking after more people have used
1776    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1777    // what comes before the finger.
1778    private int putOffsetInRange(int o) {
1779        int offset = o;
1780        Editable text = getText();
1781        int length = text.length();
1782        // Remove whitespace from end to find "real end"
1783        int realLength = length;
1784        for (int i = length - 1; i >= 0; i--) {
1785            if (text.charAt(i) == ' ') {
1786                realLength--;
1787            } else {
1788                break;
1789            }
1790        }
1791
1792        // If the offset is beyond or at the end of the text,
1793        // leave it alone.
1794        if (offset >= realLength) {
1795            return offset;
1796        }
1797        Editable editable = getText();
1798        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1799            // Keep walking backward!
1800            offset--;
1801        }
1802        return offset;
1803    }
1804
1805    private static int findText(Editable text, int offset) {
1806        if (text.charAt(offset) != ' ') {
1807            return offset;
1808        }
1809        return -1;
1810    }
1811
1812    private DrawableRecipientChip findChip(int offset) {
1813        DrawableRecipientChip[] chips =
1814                getSpannable().getSpans(0, getText().length(), DrawableRecipientChip.class);
1815        // Find the chip that contains this offset.
1816        for (int i = 0; i < chips.length; i++) {
1817            DrawableRecipientChip chip = chips[i];
1818            int start = getChipStart(chip);
1819            int end = getChipEnd(chip);
1820            if (offset >= start && offset <= end) {
1821                return chip;
1822            }
1823        }
1824        return null;
1825    }
1826
1827    // Visible for testing.
1828    // Use this method to generate text to add to the list of addresses.
1829    /* package */String createAddressText(RecipientEntry entry) {
1830        String display = entry.getDisplayName();
1831        String address = entry.getDestination();
1832        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1833            display = null;
1834        }
1835        String trimmedDisplayText;
1836        if (isPhoneQuery() && isPhoneNumber(address)) {
1837            trimmedDisplayText = address.trim();
1838        } else {
1839            if (address != null) {
1840                // Tokenize out the address in case the address already
1841                // contained the username as well.
1842                Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1843                if (tokenized != null && tokenized.length > 0) {
1844                    address = tokenized[0].getAddress();
1845                }
1846            }
1847            Rfc822Token token = new Rfc822Token(display, address, null);
1848            trimmedDisplayText = token.toString().trim();
1849        }
1850        int index = trimmedDisplayText.indexOf(",");
1851        return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
1852                && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
1853                .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1854    }
1855
1856    // Visible for testing.
1857    // Use this method to generate text to display in a chip.
1858    /*package*/ String createChipDisplayText(RecipientEntry entry) {
1859        String display = entry.getDisplayName();
1860        String address = entry.getDestination();
1861        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1862            display = null;
1863        }
1864        if (!TextUtils.isEmpty(display)) {
1865            return display;
1866        } else if (!TextUtils.isEmpty(address)){
1867            return address;
1868        } else {
1869            return new Rfc822Token(display, address, null).toString();
1870        }
1871    }
1872
1873    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1874        final String displayText = createAddressText(entry);
1875        if (TextUtils.isEmpty(displayText)) {
1876            return null;
1877        }
1878        // Always leave a blank space at the end of a chip.
1879        final int textLength = displayText.length() - 1;
1880        final SpannableString  chipText = new SpannableString(displayText);
1881        if (!mNoChips) {
1882            try {
1883                DrawableRecipientChip chip = constructChipSpan(entry, pressed);
1884                chipText.setSpan(chip, 0, textLength,
1885                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1886                chip.setOriginalText(chipText.toString());
1887            } catch (NullPointerException e) {
1888                Log.e(TAG, e.getMessage(), e);
1889                return null;
1890            }
1891        }
1892        onChipCreated(entry);
1893        return chipText;
1894    }
1895
1896    /**
1897     * A callback for subclasses to use to know when a chip was created with the
1898     * given RecipientEntry.
1899     */
1900    protected void onChipCreated(RecipientEntry entry) {}
1901
1902    /**
1903     * When an item in the suggestions list has been clicked, create a chip from the
1904     * contact information of the selected item.
1905     */
1906    @Override
1907    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1908        if (position < 0) {
1909            return;
1910        }
1911
1912        final int charactersTyped = submitItemAtPosition(position);
1913        if (charactersTyped > -1 && mRecipientEntryItemClickedListener != null) {
1914            mRecipientEntryItemClickedListener
1915                    .onRecipientEntryItemClicked(charactersTyped, position);
1916        }
1917    }
1918
1919    private int submitItemAtPosition(int position) {
1920        RecipientEntry entry = createValidatedEntry(getAdapter().getItem(position));
1921        if (entry == null) {
1922            return -1;
1923        }
1924        clearComposingText();
1925
1926        int end = getSelectionEnd();
1927        int start = mTokenizer.findTokenStart(getText(), end);
1928
1929        Editable editable = getText();
1930        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1931        CharSequence chip = createChip(entry, false);
1932        if (chip != null && start >= 0 && end >= 0) {
1933            editable.replace(start, end, chip);
1934        }
1935        sanitizeBetween();
1936
1937        return end - start;
1938    }
1939
1940    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1941        if (item == null) {
1942            return null;
1943        }
1944        final RecipientEntry entry;
1945        // If the display name and the address are the same, or if this is a
1946        // valid contact, but the destination is invalid, then make this a fake
1947        // recipient that is editable.
1948        String destination = item.getDestination();
1949        if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1950            entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(),
1951                    destination, item.isValid());
1952        } else if (RecipientEntry.isCreatedRecipient(item.getContactId())
1953                && (TextUtils.isEmpty(item.getDisplayName())
1954                        || TextUtils.equals(item.getDisplayName(), destination)
1955                        || (mValidator != null && !mValidator.isValid(destination)))) {
1956            entry = RecipientEntry.constructFakeEntry(destination, item.isValid());
1957        } else {
1958            entry = item;
1959        }
1960        return entry;
1961    }
1962
1963    // Visible for testing.
1964    /* package */DrawableRecipientChip[] getSortedRecipients() {
1965        DrawableRecipientChip[] recips = getSpannable()
1966                .getSpans(0, getText().length(), DrawableRecipientChip.class);
1967        ArrayList<DrawableRecipientChip> recipientsList = new ArrayList<DrawableRecipientChip>(
1968                Arrays.asList(recips));
1969        final Spannable spannable = getSpannable();
1970        Collections.sort(recipientsList, new Comparator<DrawableRecipientChip>() {
1971
1972            @Override
1973            public int compare(DrawableRecipientChip first, DrawableRecipientChip second) {
1974                int firstStart = spannable.getSpanStart(first);
1975                int secondStart = spannable.getSpanStart(second);
1976                if (firstStart < secondStart) {
1977                    return -1;
1978                } else if (firstStart > secondStart) {
1979                    return 1;
1980                } else {
1981                    return 0;
1982                }
1983            }
1984        });
1985        return recipientsList.toArray(new DrawableRecipientChip[recipientsList.size()]);
1986    }
1987
1988    @Override
1989    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1990        return false;
1991    }
1992
1993    @Override
1994    public void onDestroyActionMode(ActionMode mode) {
1995    }
1996
1997    @Override
1998    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1999        return false;
2000    }
2001
2002    /**
2003     * No chips are selectable.
2004     */
2005    @Override
2006    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2007        return false;
2008    }
2009
2010    // Visible for testing.
2011    /* package */ReplacementDrawableSpan getMoreChip() {
2012        MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
2013                MoreImageSpan.class);
2014        return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
2015    }
2016
2017    private MoreImageSpan createMoreSpan(int count) {
2018        String moreText = String.format(mMoreItem.getText().toString(), count);
2019        mWorkPaint.set(getPaint());
2020        mWorkPaint.setTextSize(mMoreItem.getTextSize());
2021        mWorkPaint.setColor(mMoreItem.getCurrentTextColor());
2022        final int width = (int) mWorkPaint.measureText(moreText) + mMoreItem.getPaddingLeft()
2023                + mMoreItem.getPaddingRight();
2024        final int height = (int) mChipHeight;
2025        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
2026        Canvas canvas = new Canvas(drawable);
2027        int adjustedHeight = height;
2028        Layout layout = getLayout();
2029        if (layout != null) {
2030            adjustedHeight -= layout.getLineDescent(0);
2031        }
2032        canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, mWorkPaint);
2033
2034        Drawable result = new BitmapDrawable(getResources(), drawable);
2035        result.setBounds(0, 0, width, height);
2036        return new MoreImageSpan(result);
2037    }
2038
2039    // Visible for testing.
2040    /*package*/ void createMoreChipPlainText() {
2041        // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
2042        Editable text = getText();
2043        int start = 0;
2044        int end = start;
2045        for (int i = 0; i < CHIP_LIMIT; i++) {
2046            end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
2047            start = end; // move to the next token and get its end.
2048        }
2049        // Now, count total addresses.
2050        start = 0;
2051        int tokenCount = countTokens(text);
2052        MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
2053        SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
2054        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2055        text.replace(end, text.length(), chipText);
2056        mMoreChip = moreSpan;
2057    }
2058
2059    // Visible for testing.
2060    /* package */int countTokens(Editable text) {
2061        int tokenCount = 0;
2062        int start = 0;
2063        while (start < text.length()) {
2064            start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
2065            tokenCount++;
2066            if (start >= text.length()) {
2067                break;
2068            }
2069        }
2070        return tokenCount;
2071    }
2072
2073    /**
2074     * Create the more chip. The more chip is text that replaces any chips that
2075     * do not fit in the pre-defined available space when the
2076     * RecipientEditTextView loses focus.
2077     */
2078    // Visible for testing.
2079    /* package */ void createMoreChip() {
2080        if (mNoChips) {
2081            createMoreChipPlainText();
2082            return;
2083        }
2084
2085        if (!mShouldShrink) {
2086            return;
2087        }
2088        ReplacementDrawableSpan[] tempMore = getSpannable().getSpans(0, getText().length(),
2089                MoreImageSpan.class);
2090        if (tempMore.length > 0) {
2091            getSpannable().removeSpan(tempMore[0]);
2092        }
2093        DrawableRecipientChip[] recipients = getSortedRecipients();
2094
2095        if (recipients == null || recipients.length <= CHIP_LIMIT) {
2096            mMoreChip = null;
2097            return;
2098        }
2099        Spannable spannable = getSpannable();
2100        int numRecipients = recipients.length;
2101        int overage = numRecipients - CHIP_LIMIT;
2102        MoreImageSpan moreSpan = createMoreSpan(overage);
2103        mRemovedSpans = new ArrayList<DrawableRecipientChip>();
2104        int totalReplaceStart = 0;
2105        int totalReplaceEnd = 0;
2106        Editable text = getText();
2107        for (int i = numRecipients - overage; i < recipients.length; i++) {
2108            mRemovedSpans.add(recipients[i]);
2109            if (i == numRecipients - overage) {
2110                totalReplaceStart = spannable.getSpanStart(recipients[i]);
2111            }
2112            if (i == recipients.length - 1) {
2113                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
2114            }
2115            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
2116                int spanStart = spannable.getSpanStart(recipients[i]);
2117                int spanEnd = spannable.getSpanEnd(recipients[i]);
2118                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
2119            }
2120            spannable.removeSpan(recipients[i]);
2121        }
2122        if (totalReplaceEnd < text.length()) {
2123            totalReplaceEnd = text.length();
2124        }
2125        int end = Math.max(totalReplaceStart, totalReplaceEnd);
2126        int start = Math.min(totalReplaceStart, totalReplaceEnd);
2127        SpannableString chipText = new SpannableString(text.subSequence(start, end));
2128        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2129        text.replace(start, end, chipText);
2130        mMoreChip = moreSpan;
2131        // If adding the +more chip goes over the limit, resize accordingly.
2132        if (!isPhoneQuery() && getLineCount() > mMaxLines) {
2133            setMaxLines(getLineCount());
2134        }
2135    }
2136
2137    /**
2138     * Replace the more chip, if it exists, with all of the recipient chips it had
2139     * replaced when the RecipientEditTextView gains focus.
2140     */
2141    // Visible for testing.
2142    /*package*/ void removeMoreChip() {
2143        if (mMoreChip != null) {
2144            Spannable span = getSpannable();
2145            span.removeSpan(mMoreChip);
2146            mMoreChip = null;
2147            // Re-add the spans that were removed.
2148            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
2149                // Recreate each removed span.
2150                DrawableRecipientChip[] recipients = getSortedRecipients();
2151                // Start the search for tokens after the last currently visible
2152                // chip.
2153                if (recipients == null || recipients.length == 0) {
2154                    return;
2155                }
2156                int end = span.getSpanEnd(recipients[recipients.length - 1]);
2157                Editable editable = getText();
2158                for (DrawableRecipientChip chip : mRemovedSpans) {
2159                    int chipStart;
2160                    int chipEnd;
2161                    String token;
2162                    // Need to find the location of the chip, again.
2163                    token = (String) chip.getOriginalText();
2164                    // As we find the matching recipient for the remove spans,
2165                    // reduce the size of the string we need to search.
2166                    // That way, if there are duplicates, we always find the correct
2167                    // recipient.
2168                    chipStart = editable.toString().indexOf(token, end);
2169                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
2170                    // Only set the span if we found a matching token.
2171                    if (chipStart != -1) {
2172                        editable.setSpan(chip, chipStart, chipEnd,
2173                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
2174                    }
2175                }
2176                mRemovedSpans.clear();
2177            }
2178        }
2179    }
2180
2181    /**
2182     * Show specified chip as selected. If the RecipientChip is just an email address,
2183     * selecting the chip will take the contents of the chip and place it at
2184     * the end of the RecipientEditTextView for inline editing. If the
2185     * RecipientChip is a complete contact, then selecting the chip
2186     * will change the background color of the chip, show the delete icon,
2187     * and a popup window with the address in use highlighted and any other
2188     * alternate addresses for the contact.
2189     * @param currentChip Chip to select.
2190     * @return A RecipientChip in the selected state or null if the chip
2191     * just contained an email address.
2192     */
2193    private DrawableRecipientChip selectChip(DrawableRecipientChip currentChip) {
2194        if (shouldShowEditableText(currentChip)) {
2195            CharSequence text = currentChip.getValue();
2196            Editable editable = getText();
2197            Spannable spannable = getSpannable();
2198            int spanStart = spannable.getSpanStart(currentChip);
2199            int spanEnd = spannable.getSpanEnd(currentChip);
2200            spannable.removeSpan(currentChip);
2201            // Don't need leading space if it's the only chip
2202            if (spanEnd - spanStart == editable.length() - 1) {
2203                spanEnd++;
2204            }
2205            editable.delete(spanStart, spanEnd);
2206            setCursorVisible(true);
2207            setSelection(editable.length());
2208            editable.append(text);
2209            return constructChipSpan(
2210                    RecipientEntry.constructFakeEntry((String) text, isValid(text.toString())),
2211                    true);
2212        } else {
2213            int start = getChipStart(currentChip);
2214            int end = getChipEnd(currentChip);
2215            getSpannable().removeSpan(currentChip);
2216            DrawableRecipientChip newChip;
2217            final boolean showAddress =
2218                    currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT ||
2219                    getAdapter().forceShowAddress();
2220            try {
2221                if (showAddress && mNoChips) {
2222                    return null;
2223                }
2224                newChip = constructChipSpan(currentChip.getEntry(), true);
2225            } catch (NullPointerException e) {
2226                Log.e(TAG, e.getMessage(), e);
2227                return null;
2228            }
2229            Editable editable = getText();
2230            QwertyKeyListener.markAsReplaced(editable, start, end, "");
2231            if (start == -1 || end == -1) {
2232                Log.d(TAG, "The chip being selected no longer exists but should.");
2233            } else {
2234                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2235            }
2236            newChip.setSelected(true);
2237            if (shouldShowEditableText(newChip)) {
2238                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
2239            }
2240            if (showAddress) {
2241                showAddress(newChip, mAddressPopup);
2242            } else {
2243                showAlternates(newChip, mAlternatesPopup);
2244            }
2245            setCursorVisible(false);
2246            return newChip;
2247        }
2248    }
2249
2250    private boolean shouldShowEditableText(DrawableRecipientChip currentChip) {
2251        long contactId = currentChip.getContactId();
2252        return contactId == RecipientEntry.INVALID_CONTACT
2253                || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2254    }
2255
2256    private void showAddress(final DrawableRecipientChip currentChip, final ListPopupWindow popup) {
2257        if (!mAttachedToWindow) {
2258            return;
2259        }
2260        int line = getLayout().getLineForOffset(getChipStart(currentChip));
2261        int bottomOffset = calculateOffsetFromBottomToTop(line);
2262        // Align the alternates popup with the left side of the View,
2263        // regardless of the position of the chip tapped.
2264        popup.setAnchorView((mAlternatePopupAnchor != null) ? mAlternatePopupAnchor : this);
2265        popup.setVerticalOffset(bottomOffset);
2266        popup.setAdapter(createSingleAddressAdapter(currentChip));
2267        popup.setOnItemClickListener(new OnItemClickListener() {
2268            @Override
2269            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2270                unselectChip(currentChip);
2271            }
2272        });
2273        popup.show();
2274        ListView listView = popup.getListView();
2275        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
2276        listView.setItemChecked(0, true);
2277    }
2278
2279    /**
2280     * Remove selection from this chip. Unselecting a RecipientChip will render
2281     * the chip without a delete icon and with an unfocused background. This is
2282     * called when the RecipientChip no longer has focus.
2283     */
2284    private void unselectChip(DrawableRecipientChip chip) {
2285        int start = getChipStart(chip);
2286        int end = getChipEnd(chip);
2287        Editable editable = getText();
2288        mSelectedChip = null;
2289        if (start == -1 || end == -1) {
2290            Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
2291            setSelection(editable.length());
2292            commitDefault();
2293        } else {
2294            getSpannable().removeSpan(chip);
2295            QwertyKeyListener.markAsReplaced(editable, start, end, "");
2296            editable.removeSpan(chip);
2297            try {
2298                if (!mNoChips) {
2299                    editable.setSpan(constructChipSpan(chip.getEntry(), false),
2300                            start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2301                }
2302            } catch (NullPointerException e) {
2303                Log.e(TAG, e.getMessage(), e);
2304            }
2305        }
2306        setCursorVisible(true);
2307        setSelection(editable.length());
2308        dismissPopups();
2309    }
2310
2311    @Override
2312    public void onChipDelete() {
2313        if (mSelectedChip != null) {
2314            removeChip(mSelectedChip);
2315        }
2316        dismissPopups();
2317    }
2318
2319    private void dismissPopups() {
2320        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
2321            mAlternatesPopup.dismiss();
2322        }
2323        if (mAddressPopup != null && mAddressPopup.isShowing()) {
2324            mAddressPopup.dismiss();
2325        }
2326    }
2327
2328    /**
2329     * Remove the chip and any text associated with it from the RecipientEditTextView.
2330     */
2331    // Visible for testing.
2332    /* package */void removeChip(DrawableRecipientChip chip) {
2333        Spannable spannable = getSpannable();
2334        int spanStart = spannable.getSpanStart(chip);
2335        int spanEnd = spannable.getSpanEnd(chip);
2336        Editable text = getText();
2337        int toDelete = spanEnd;
2338        boolean wasSelected = chip == mSelectedChip;
2339        // Clear that there is a selected chip before updating any text.
2340        if (wasSelected) {
2341            mSelectedChip = null;
2342        }
2343        // Always remove trailing spaces when removing a chip.
2344        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
2345            toDelete++;
2346        }
2347        spannable.removeSpan(chip);
2348        if (spanStart >= 0 && toDelete > 0) {
2349            text.delete(spanStart, toDelete);
2350        }
2351        if (wasSelected) {
2352            clearSelectedChip();
2353        }
2354    }
2355
2356    /**
2357     * Replace this currently selected chip with a new chip
2358     * that uses the contact data provided.
2359     */
2360    // Visible for testing.
2361    /*package*/ void replaceChip(DrawableRecipientChip chip, RecipientEntry entry) {
2362        boolean wasSelected = chip == mSelectedChip;
2363        if (wasSelected) {
2364            mSelectedChip = null;
2365        }
2366        int start = getChipStart(chip);
2367        int end = getChipEnd(chip);
2368        getSpannable().removeSpan(chip);
2369        Editable editable = getText();
2370        CharSequence chipText = createChip(entry, false);
2371        if (chipText != null) {
2372            if (start == -1 || end == -1) {
2373                Log.e(TAG, "The chip to replace does not exist but should.");
2374                editable.insert(0, chipText);
2375            } else {
2376                if (!TextUtils.isEmpty(chipText)) {
2377                    // There may be a space to replace with this chip's new
2378                    // associated space. Check for it
2379                    int toReplace = end;
2380                    while (toReplace >= 0 && toReplace < editable.length()
2381                            && editable.charAt(toReplace) == ' ') {
2382                        toReplace++;
2383                    }
2384                    editable.replace(start, toReplace, chipText);
2385                }
2386            }
2387        }
2388        setCursorVisible(true);
2389        if (wasSelected) {
2390            clearSelectedChip();
2391        }
2392    }
2393
2394    /**
2395     * Handle click events for a chip. When a selected chip receives a click
2396     * event, see if that event was in the delete icon. If so, delete it.
2397     * Otherwise, unselect the chip.
2398     */
2399    public void onClick(DrawableRecipientChip chip) {
2400        if (chip.isSelected()) {
2401            clearSelectedChip();
2402        }
2403    }
2404
2405    private boolean chipsPending() {
2406        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
2407    }
2408
2409    @Override
2410    public void removeTextChangedListener(TextWatcher watcher) {
2411        mTextWatcher = null;
2412        super.removeTextChangedListener(watcher);
2413    }
2414
2415    private boolean isValidEmailAddress(String input) {
2416        return !TextUtils.isEmpty(input) && mValidator != null &&
2417                mValidator.isValid(input);
2418    }
2419
2420    private class RecipientTextWatcher implements TextWatcher {
2421
2422        @Override
2423        public void afterTextChanged(Editable s) {
2424            // If the text has been set to null or empty, make sure we remove
2425            // all the spans we applied.
2426            if (TextUtils.isEmpty(s)) {
2427                // Remove all the chips spans.
2428                Spannable spannable = getSpannable();
2429                DrawableRecipientChip[] chips = spannable.getSpans(0, getText().length(),
2430                        DrawableRecipientChip.class);
2431                for (DrawableRecipientChip chip : chips) {
2432                    spannable.removeSpan(chip);
2433                }
2434                if (mMoreChip != null) {
2435                    spannable.removeSpan(mMoreChip);
2436                }
2437                clearSelectedChip();
2438                return;
2439            }
2440            // Get whether there are any recipients pending addition to the
2441            // view. If there are, don't do anything in the text watcher.
2442            if (chipsPending()) {
2443                return;
2444            }
2445            // If the user is editing a chip, don't clear it.
2446            if (mSelectedChip != null) {
2447                if (!isGeneratedContact(mSelectedChip)) {
2448                    setCursorVisible(true);
2449                    setSelection(getText().length());
2450                    clearSelectedChip();
2451                } else {
2452                    return;
2453                }
2454            }
2455            int length = s.length();
2456            // Make sure there is content there to parse and that it is
2457            // not just the commit character.
2458            if (length > 1) {
2459                if (lastCharacterIsCommitCharacter(s)) {
2460                    commitByCharacter();
2461                    return;
2462                }
2463                char last;
2464                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2465                int len = length() - 1;
2466                if (end != len) {
2467                    last = s.charAt(end);
2468                } else {
2469                    last = s.charAt(len);
2470                }
2471                if (last == COMMIT_CHAR_SPACE) {
2472                    if (!isPhoneQuery()) {
2473                        // Check if this is a valid email address. If it is,
2474                        // commit it.
2475                        String text = getText().toString();
2476                        int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2477                        String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
2478                                tokenStart));
2479                        if (isValidEmailAddress(sub)) {
2480                            commitByCharacter();
2481                        }
2482                    }
2483                }
2484            }
2485        }
2486
2487        @Override
2488        public void onTextChanged(CharSequence s, int start, int before, int count) {
2489            // The user deleted some text OR some text was replaced; check to
2490            // see if the insertion point is on a space
2491            // following a chip.
2492            if (before - count == 1) {
2493                // If the item deleted is a space, and the thing before the
2494                // space is a chip, delete the entire span.
2495                int selStart = getSelectionStart();
2496                DrawableRecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
2497                        DrawableRecipientChip.class);
2498                if (repl.length > 0) {
2499                    // There is a chip there! Just remove it.
2500                    Editable editable = getText();
2501                    // Add the separator token.
2502                    int tokenStart = mTokenizer.findTokenStart(editable, selStart);
2503                    int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart);
2504                    tokenEnd = tokenEnd + 1;
2505                    if (tokenEnd > editable.length()) {
2506                        tokenEnd = editable.length();
2507                    }
2508                    editable.delete(tokenStart, tokenEnd);
2509                    getSpannable().removeSpan(repl[0]);
2510                }
2511            } else if (count > before) {
2512                if (mSelectedChip != null
2513                    && isGeneratedContact(mSelectedChip)) {
2514                    if (lastCharacterIsCommitCharacter(s)) {
2515                        commitByCharacter();
2516                        return;
2517                    }
2518                }
2519            }
2520        }
2521
2522        @Override
2523        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2524            // Do nothing.
2525        }
2526    }
2527
2528   public boolean lastCharacterIsCommitCharacter(CharSequence s) {
2529        char last;
2530        int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2531        int len = length() - 1;
2532        if (end != len) {
2533            last = s.charAt(end);
2534        } else {
2535            last = s.charAt(len);
2536        }
2537        return last == COMMIT_CHAR_COMMA || last == COMMIT_CHAR_SEMICOLON;
2538    }
2539
2540    public boolean isGeneratedContact(DrawableRecipientChip chip) {
2541        long contactId = chip.getContactId();
2542        return contactId == RecipientEntry.INVALID_CONTACT
2543                || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2544    }
2545
2546    /**
2547     * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2548     */
2549    // Visible for testing.
2550    void handlePasteClip(ClipData clip) {
2551        if (clip == null) {
2552            // Do nothing.
2553            return;
2554        }
2555
2556        final ClipDescription clipDesc = clip.getDescription();
2557        boolean containsSupportedType = clipDesc.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) ||
2558                clipDesc.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML);
2559        if (!containsSupportedType) {
2560            return;
2561        }
2562
2563        removeTextChangedListener(mTextWatcher);
2564
2565        final ClipDescription clipDescription = clip.getDescription();
2566        for (int i = 0; i < clip.getItemCount(); i++) {
2567            final String mimeType = clipDescription.getMimeType(i);
2568            final boolean supportedType = ClipDescription.MIMETYPE_TEXT_PLAIN.equals(mimeType) ||
2569                    ClipDescription.MIMETYPE_TEXT_HTML.equals(mimeType);
2570            if (!supportedType) {
2571                // Only plain text and html can be pasted.
2572                continue;
2573            }
2574
2575            final CharSequence pastedItem = clip.getItemAt(i).getText();
2576            if (!TextUtils.isEmpty(pastedItem)) {
2577                final Editable editable = getText();
2578                final int start = getSelectionStart();
2579                final int end = getSelectionEnd();
2580                if (start < 0 || end < 1) {
2581                    // No selection.
2582                    editable.append(pastedItem);
2583                } else if (start == end) {
2584                    // Insert at position.
2585                    editable.insert(start, pastedItem);
2586                } else {
2587                    editable.append(pastedItem, start, end);
2588                }
2589                handlePasteAndReplace();
2590            }
2591        }
2592
2593        mHandler.post(mAddTextWatcher);
2594    }
2595
2596    @Override
2597    public boolean onTextContextMenuItem(int id) {
2598        if (id == android.R.id.paste) {
2599            ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2600                    Context.CLIPBOARD_SERVICE);
2601            handlePasteClip(clipboard.getPrimaryClip());
2602            return true;
2603        }
2604        return super.onTextContextMenuItem(id);
2605    }
2606
2607    private void handlePasteAndReplace() {
2608        ArrayList<DrawableRecipientChip> created = handlePaste();
2609        if (created != null && created.size() > 0) {
2610            // Perform reverse lookups on the pasted contacts.
2611            IndividualReplacementTask replace = new IndividualReplacementTask();
2612            replace.execute(created);
2613        }
2614    }
2615
2616    // Visible for testing.
2617    /* package */ArrayList<DrawableRecipientChip> handlePaste() {
2618        String text = getText().toString();
2619        int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2620        String lastAddress = text.substring(originalTokenStart);
2621        int tokenStart = originalTokenStart;
2622        int prevTokenStart = 0;
2623        DrawableRecipientChip findChip = null;
2624        ArrayList<DrawableRecipientChip> created = new ArrayList<DrawableRecipientChip>();
2625        if (tokenStart != 0) {
2626            // There are things before this!
2627            while (tokenStart != 0 && findChip == null && tokenStart != prevTokenStart) {
2628                prevTokenStart = tokenStart;
2629                tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2630                findChip = findChip(tokenStart);
2631                if (tokenStart == originalTokenStart && findChip == null) {
2632                    break;
2633                }
2634            }
2635            if (tokenStart != originalTokenStart) {
2636                if (findChip != null) {
2637                    tokenStart = prevTokenStart;
2638                }
2639                int tokenEnd;
2640                DrawableRecipientChip createdChip;
2641                while (tokenStart < originalTokenStart) {
2642                    tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(),
2643                            tokenStart));
2644                    commitChip(tokenStart, tokenEnd, getText());
2645                    createdChip = findChip(tokenStart);
2646                    if (createdChip == null) {
2647                        break;
2648                    }
2649                    // +1 for the space at the end.
2650                    tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
2651                    created.add(createdChip);
2652                }
2653            }
2654        }
2655        // Take a look at the last token. If the token has been completed with a
2656        // commit character, create a chip.
2657        if (isCompletedToken(lastAddress)) {
2658            Editable editable = getText();
2659            tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2660            commitChip(tokenStart, editable.length(), editable);
2661            created.add(findChip(tokenStart));
2662        }
2663        return created;
2664    }
2665
2666    // Visible for testing.
2667    /* package */int movePastTerminators(int tokenEnd) {
2668        if (tokenEnd >= length()) {
2669            return tokenEnd;
2670        }
2671        char atEnd = getText().toString().charAt(tokenEnd);
2672        if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2673            tokenEnd++;
2674        }
2675        // This token had not only an end token character, but also a space
2676        // separating it from the next token.
2677        if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2678            tokenEnd++;
2679        }
2680        return tokenEnd;
2681    }
2682
2683    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
2684        private DrawableRecipientChip createFreeChip(RecipientEntry entry) {
2685            try {
2686                if (mNoChips) {
2687                    return null;
2688                }
2689                return constructChipSpan(entry, false);
2690            } catch (NullPointerException e) {
2691                Log.e(TAG, e.getMessage(), e);
2692                return null;
2693            }
2694        }
2695
2696        @Override
2697        protected void onPreExecute() {
2698            // Ensure everything is in chip-form already, so we don't have text that slowly gets
2699            // replaced
2700            final List<DrawableRecipientChip> originalRecipients =
2701                    new ArrayList<DrawableRecipientChip>();
2702            final DrawableRecipientChip[] existingChips = getSortedRecipients();
2703            for (int i = 0; i < existingChips.length; i++) {
2704                originalRecipients.add(existingChips[i]);
2705            }
2706            if (mRemovedSpans != null) {
2707                originalRecipients.addAll(mRemovedSpans);
2708            }
2709
2710            final List<DrawableRecipientChip> replacements =
2711                    new ArrayList<DrawableRecipientChip>(originalRecipients.size());
2712
2713            for (final DrawableRecipientChip chip : originalRecipients) {
2714                if (RecipientEntry.isCreatedRecipient(chip.getEntry().getContactId())
2715                        && getSpannable().getSpanStart(chip) != -1) {
2716                    replacements.add(createFreeChip(chip.getEntry()));
2717                } else {
2718                    replacements.add(null);
2719                }
2720            }
2721
2722            processReplacements(originalRecipients, replacements);
2723        }
2724
2725        @Override
2726        protected Void doInBackground(Void... params) {
2727            if (mIndividualReplacements != null) {
2728                mIndividualReplacements.cancel(true);
2729            }
2730            // For each chip in the list, look up the matching contact.
2731            // If there is a match, replace that chip with the matching
2732            // chip.
2733            final ArrayList<DrawableRecipientChip> recipients =
2734                    new ArrayList<DrawableRecipientChip>();
2735            DrawableRecipientChip[] existingChips = getSortedRecipients();
2736            for (int i = 0; i < existingChips.length; i++) {
2737                recipients.add(existingChips[i]);
2738            }
2739            if (mRemovedSpans != null) {
2740                recipients.addAll(mRemovedSpans);
2741            }
2742            ArrayList<String> addresses = new ArrayList<String>();
2743            DrawableRecipientChip chip;
2744            for (int i = 0; i < recipients.size(); i++) {
2745                chip = recipients.get(i);
2746                if (chip != null) {
2747                    addresses.add(createAddressText(chip.getEntry()));
2748                }
2749            }
2750            final BaseRecipientAdapter adapter = getAdapter();
2751            adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
2752                        @Override
2753                        public void matchesFound(Map<String, RecipientEntry> entries) {
2754                            final ArrayList<DrawableRecipientChip> replacements =
2755                                    new ArrayList<DrawableRecipientChip>();
2756                            for (final DrawableRecipientChip temp : recipients) {
2757                                RecipientEntry entry = null;
2758                                if (temp != null && RecipientEntry.isCreatedRecipient(
2759                                        temp.getEntry().getContactId())
2760                                        && getSpannable().getSpanStart(temp) != -1) {
2761                                    // Replace this.
2762                                    entry = createValidatedEntry(
2763                                            entries.get(tokenizeAddress(temp.getEntry()
2764                                                    .getDestination())));
2765                                }
2766                                if (entry != null) {
2767                                    replacements.add(createFreeChip(entry));
2768                                } else {
2769                                    replacements.add(null);
2770                                }
2771                            }
2772                            processReplacements(recipients, replacements);
2773                        }
2774
2775                        @Override
2776                        public void matchesNotFound(final Set<String> unfoundAddresses) {
2777                            final List<DrawableRecipientChip> replacements =
2778                                    new ArrayList<DrawableRecipientChip>(unfoundAddresses.size());
2779
2780                            for (final DrawableRecipientChip temp : recipients) {
2781                                if (temp != null && RecipientEntry.isCreatedRecipient(
2782                                        temp.getEntry().getContactId())
2783                                        && getSpannable().getSpanStart(temp) != -1) {
2784                                    if (unfoundAddresses.contains(
2785                                            temp.getEntry().getDestination())) {
2786                                        replacements.add(createFreeChip(temp.getEntry()));
2787                                    } else {
2788                                        replacements.add(null);
2789                                    }
2790                                } else {
2791                                    replacements.add(null);
2792                                }
2793                            }
2794
2795                            processReplacements(recipients, replacements);
2796                        }
2797                    });
2798            return null;
2799        }
2800
2801        private void processReplacements(final List<DrawableRecipientChip> recipients,
2802                final List<DrawableRecipientChip> replacements) {
2803            if (replacements != null && replacements.size() > 0) {
2804                final Runnable runnable = new Runnable() {
2805                    @Override
2806                    public void run() {
2807                        final Editable text = new SpannableStringBuilder(getText());
2808                        int i = 0;
2809                        for (final DrawableRecipientChip chip : recipients) {
2810                            final DrawableRecipientChip replacement = replacements.get(i);
2811                            if (replacement != null) {
2812                                final RecipientEntry oldEntry = chip.getEntry();
2813                                final RecipientEntry newEntry = replacement.getEntry();
2814                                final boolean isBetter =
2815                                        RecipientAlternatesAdapter.getBetterRecipient(
2816                                                oldEntry, newEntry) == newEntry;
2817
2818                                if (isBetter) {
2819                                    // Find the location of the chip in the text currently shown.
2820                                    final int start = text.getSpanStart(chip);
2821                                    if (start != -1) {
2822                                        // Replacing the entirety of what the chip represented,
2823                                        // including the extra space dividing it from other chips.
2824                                        final int end =
2825                                                Math.min(text.getSpanEnd(chip) + 1, text.length());
2826                                        text.removeSpan(chip);
2827                                        // Make sure we always have just 1 space at the end to
2828                                        // separate this chip from the next chip.
2829                                        final SpannableString displayText =
2830                                                new SpannableString(createAddressText(
2831                                                        replacement.getEntry()).trim() + " ");
2832                                        displayText.setSpan(replacement, 0,
2833                                                displayText.length() - 1,
2834                                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2835                                        // Replace the old text we found with with the new display
2836                                        // text, which now may also contain the display name of the
2837                                        // recipient.
2838                                        text.replace(start, end, displayText);
2839                                        replacement.setOriginalText(displayText.toString());
2840                                        replacements.set(i, null);
2841
2842                                        recipients.set(i, replacement);
2843                                    }
2844                                }
2845                            }
2846                            i++;
2847                        }
2848                        setText(text);
2849                    }
2850                };
2851
2852                if (Looper.myLooper() == Looper.getMainLooper()) {
2853                    runnable.run();
2854                } else {
2855                    mHandler.post(runnable);
2856                }
2857            }
2858        }
2859    }
2860
2861    private class IndividualReplacementTask
2862            extends AsyncTask<ArrayList<DrawableRecipientChip>, Void, Void> {
2863        @Override
2864        protected Void doInBackground(ArrayList<DrawableRecipientChip>... params) {
2865            // For each chip in the list, look up the matching contact.
2866            // If there is a match, replace that chip with the matching
2867            // chip.
2868            final ArrayList<DrawableRecipientChip> originalRecipients = params[0];
2869            ArrayList<String> addresses = new ArrayList<String>();
2870            DrawableRecipientChip chip;
2871            for (int i = 0; i < originalRecipients.size(); i++) {
2872                chip = originalRecipients.get(i);
2873                if (chip != null) {
2874                    addresses.add(createAddressText(chip.getEntry()));
2875                }
2876            }
2877            final BaseRecipientAdapter adapter = getAdapter();
2878            adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
2879
2880                        @Override
2881                        public void matchesFound(Map<String, RecipientEntry> entries) {
2882                            for (final DrawableRecipientChip temp : originalRecipients) {
2883                                if (RecipientEntry.isCreatedRecipient(temp.getEntry()
2884                                        .getContactId())
2885                                        && getSpannable().getSpanStart(temp) != -1) {
2886                                    // Replace this.
2887                                    final RecipientEntry entry = createValidatedEntry(entries
2888                                            .get(tokenizeAddress(temp.getEntry().getDestination())
2889                                                    .toLowerCase()));
2890                                    if (entry != null) {
2891                                        mHandler.post(new Runnable() {
2892                                            @Override
2893                                            public void run() {
2894                                                replaceChip(temp, entry);
2895                                            }
2896                                        });
2897                                    }
2898                                }
2899                            }
2900                        }
2901
2902                        @Override
2903                        public void matchesNotFound(final Set<String> unfoundAddresses) {
2904                            // No action required
2905                        }
2906                    });
2907            return null;
2908        }
2909    }
2910
2911
2912    /**
2913     * MoreImageSpan is a simple class created for tracking the existence of a
2914     * more chip across activity restarts/
2915     */
2916    private class MoreImageSpan extends ReplacementDrawableSpan {
2917        public MoreImageSpan(Drawable b) {
2918            super(b);
2919            setExtraMargin(mLineSpacingExtra);
2920        }
2921    }
2922
2923    @Override
2924    public boolean onDown(MotionEvent e) {
2925        return false;
2926    }
2927
2928    @Override
2929    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2930        // Do nothing.
2931        return false;
2932    }
2933
2934    @Override
2935    public void onLongPress(MotionEvent event) {
2936        if (mSelectedChip != null) {
2937            return;
2938        }
2939        float x = event.getX();
2940        float y = event.getY();
2941        final int offset = putOffsetInRange(x, y);
2942        DrawableRecipientChip currentChip = findChip(offset);
2943        if (currentChip != null) {
2944            if (mDragEnabled) {
2945                // Start drag-and-drop for the selected chip.
2946                startDrag(currentChip);
2947            } else {
2948                // Copy the selected chip email address.
2949                showCopyDialog(currentChip.getEntry().getDestination());
2950            }
2951        }
2952    }
2953
2954    // The following methods are used to provide some functionality on older versions of Android
2955    // These methods were copied out of JB MR2's TextView
2956    /////////////////////////////////////////////////
2957    private int supportGetOffsetForPosition(float x, float y) {
2958        if (getLayout() == null) return -1;
2959        final int line = supportGetLineAtCoordinate(y);
2960        final int offset = supportGetOffsetAtCoordinate(line, x);
2961        return offset;
2962    }
2963
2964    private float supportConvertToLocalHorizontalCoordinate(float x) {
2965        x -= getTotalPaddingLeft();
2966        // Clamp the position to inside of the view.
2967        x = Math.max(0.0f, x);
2968        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
2969        x += getScrollX();
2970        return x;
2971    }
2972
2973    private int supportGetLineAtCoordinate(float y) {
2974        y -= getTotalPaddingLeft();
2975        // Clamp the position to inside of the view.
2976        y = Math.max(0.0f, y);
2977        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
2978        y += getScrollY();
2979        return getLayout().getLineForVertical((int) y);
2980    }
2981
2982    private int supportGetOffsetAtCoordinate(int line, float x) {
2983        x = supportConvertToLocalHorizontalCoordinate(x);
2984        return getLayout().getOffsetForHorizontal(line, x);
2985    }
2986    /////////////////////////////////////////////////
2987
2988    /**
2989     * Enables drag-and-drop for chips.
2990     */
2991    public void enableDrag() {
2992        mDragEnabled = true;
2993    }
2994
2995    /**
2996     * Starts drag-and-drop for the selected chip.
2997     */
2998    private void startDrag(DrawableRecipientChip currentChip) {
2999        String address = currentChip.getEntry().getDestination();
3000        ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
3001
3002        // Start drag mode.
3003        startDrag(data, new RecipientChipShadow(currentChip), null, 0);
3004
3005        // Remove the current chip, so drag-and-drop will result in a move.
3006        // TODO (phamm): consider readd this chip if it's dropped outside a target.
3007        removeChip(currentChip);
3008    }
3009
3010    /**
3011     * Handles drag event.
3012     */
3013    @Override
3014    public boolean onDragEvent(DragEvent event) {
3015        switch (event.getAction()) {
3016            case DragEvent.ACTION_DRAG_STARTED:
3017                // Only handle plain text drag and drop.
3018                return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
3019            case DragEvent.ACTION_DRAG_ENTERED:
3020                requestFocus();
3021                return true;
3022            case DragEvent.ACTION_DROP:
3023                handlePasteClip(event.getClipData());
3024                return true;
3025        }
3026        return false;
3027    }
3028
3029    /**
3030     * Drag shadow for a {@link DrawableRecipientChip}.
3031     */
3032    private final class RecipientChipShadow extends DragShadowBuilder {
3033        private final DrawableRecipientChip mChip;
3034
3035        public RecipientChipShadow(DrawableRecipientChip chip) {
3036            mChip = chip;
3037        }
3038
3039        @Override
3040        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
3041            Rect rect = mChip.getBounds();
3042            shadowSize.set(rect.width(), rect.height());
3043            shadowTouchPoint.set(rect.centerX(), rect.centerY());
3044        }
3045
3046        @Override
3047        public void onDrawShadow(Canvas canvas) {
3048            mChip.draw(canvas);
3049        }
3050    }
3051
3052    private void showCopyDialog(final String address) {
3053        if (!mAttachedToWindow) {
3054            return;
3055        }
3056        mCopyAddress = address;
3057        mCopyDialog.setTitle(address);
3058        mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
3059        mCopyDialog.setCancelable(true);
3060        mCopyDialog.setCanceledOnTouchOutside(true);
3061        Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
3062        button.setOnClickListener(this);
3063        int btnTitleId;
3064        if (isPhoneQuery()) {
3065            btnTitleId = R.string.copy_number;
3066        } else {
3067            btnTitleId = R.string.copy_email;
3068        }
3069        String buttonTitle = getContext().getResources().getString(btnTitleId);
3070        button.setText(buttonTitle);
3071        mCopyDialog.setOnDismissListener(this);
3072        mCopyDialog.show();
3073    }
3074
3075    @Override
3076    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
3077        // Do nothing.
3078        return false;
3079    }
3080
3081    @Override
3082    public void onShowPress(MotionEvent e) {
3083        // Do nothing.
3084    }
3085
3086    @Override
3087    public boolean onSingleTapUp(MotionEvent e) {
3088        // Do nothing.
3089        return false;
3090    }
3091
3092    @Override
3093    public void onDismiss(DialogInterface dialog) {
3094        mCopyAddress = null;
3095    }
3096
3097    @Override
3098    public void onClick(View v) {
3099        // Copy this to the clipboard.
3100        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
3101                Context.CLIPBOARD_SERVICE);
3102        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
3103        mCopyDialog.dismiss();
3104    }
3105
3106    protected boolean isPhoneQuery() {
3107        return getAdapter() != null
3108                && getAdapter().getQueryType() == BaseRecipientAdapter.QUERY_TYPE_PHONE;
3109    }
3110
3111    @Override
3112    public BaseRecipientAdapter getAdapter() {
3113        return (BaseRecipientAdapter) super.getAdapter();
3114    }
3115
3116    /**
3117     * Append a new {@link RecipientEntry} to the end of the recipient chips, leaving any
3118     * unfinished text at the end.
3119     */
3120    public void appendRecipientEntry(final RecipientEntry entry) {
3121        clearComposingText();
3122
3123        final Editable editable = getText();
3124        int chipInsertionPoint = 0;
3125
3126        // Find the end of last chip and see if there's any unchipified text.
3127        final DrawableRecipientChip[] recips = getSortedRecipients();
3128        if (recips != null && recips.length > 0) {
3129            final DrawableRecipientChip last = recips[recips.length - 1];
3130            // The chip will be inserted at the end of last chip + 1. All the unfinished text after
3131            // the insertion point will be kept untouched.
3132            chipInsertionPoint = editable.getSpanEnd(last) + 1;
3133        }
3134
3135        final CharSequence chip = createChip(entry, false);
3136        if (chip != null) {
3137            editable.insert(chipInsertionPoint, chip);
3138        }
3139    }
3140
3141    /**
3142     * Remove all chips matching the given RecipientEntry.
3143     */
3144    public void removeRecipientEntry(final RecipientEntry entry) {
3145        final DrawableRecipientChip[] recips = getText()
3146                .getSpans(0, getText().length(), DrawableRecipientChip.class);
3147
3148        for (final DrawableRecipientChip recipient : recips) {
3149            final RecipientEntry existingEntry = recipient.getEntry();
3150            if (existingEntry != null && existingEntry.isValid() &&
3151                    existingEntry.isSamePerson(entry)) {
3152                removeChip(recipient);
3153            }
3154        }
3155    }
3156
3157    public void setAlternatePopupAnchor(View v) {
3158        mAlternatePopupAnchor = v;
3159    }
3160
3161    private static class ChipBitmapContainer {
3162        Bitmap bitmap;
3163        // information used for positioning the loaded icon
3164        boolean loadIcon = true;
3165        float left;
3166        float top;
3167        float right;
3168        float bottom;
3169    }
3170}
3171