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