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