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