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