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