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