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