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