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