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