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