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