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