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