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