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