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